blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
721
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
5
91
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
321 values
visit_date
timestamp[ns]date
2016-08-12 09:31:09
2023-09-06 10:45:07
revision_date
timestamp[ns]date
2010-09-28 14:01:40
2023-09-06 06:22:19
committer_date
timestamp[ns]date
2010-09-28 14:01:40
2023-09-06 06:22:19
github_id
int64
426
681M
star_events_count
int64
101
243k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[ns]date
2012-06-28 18:51:49
2023-09-14 21:59:16
gha_created_at
timestamp[ns]date
2008-02-11 22:55:26
2023-08-10 11:14:58
gha_language
stringclasses
147 values
src_encoding
stringclasses
26 values
language
stringclasses
2 values
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
6
10.2M
extension
stringclasses
115 values
filename
stringlengths
3
113
content
stringlengths
6
10.2M
c490dfa484de12ca66db6e217ab6c458b6e37435
d78d8e2eba9180c174caec9594c8d9e9b78b7b9f
/include/wally_bip38.h
f37b63f8008f55707d4f06c1349d3b8ac654c5bd
[ "MIT" ]
permissive
ElementsProject/libwally-core
21adf16982aecc5de7c19044cec078794bde883b
0131dd7d746ed4c1ecfc0ebd9ea5b168cf15c7f9
refs/heads/master
2023-08-10T21:07:00.174677
2023-08-02T01:47:54
2023-08-02T01:47:54
95,169,962
269
146
NOASSERTION
2023-09-14T09:49:22
2017-06-23T01:09:27
C
UTF-8
C
false
false
4,113
h
wally_bip38.h
#ifndef LIBWALLY_CORE_BIP38_H #define LIBWALLY_CORE_BIP38_H #include "wally_core.h" #ifdef __cplusplus extern "C" { #endif /*** bip38-flags BIP38 conversion flags */ #define BIP38_KEY_NETWORK_MASK 0xff /** Mask for the bottom 8 bitflags which hold the network */ #define BIP38_KEY_MAINNET 0 /** Address is for main network */ #define BIP38_KEY_TESTNET 111 /** Address is for test network */ #define BIP38_KEY_COMPRESSED 256 /** Public key is compressed */ #define BIP38_KEY_EC_MULT 512 /** EC-Multiplied key (FIXME: Not implemented) */ #define BIP38_KEY_QUICK_CHECK 1024 /** Check structure only (no password required) */ #define BIP38_KEY_RAW_MODE 2048 /** Treat bytes in as raw data */ #define BIP38_KEY_SWAP_ORDER 4096 /** Hash comes after encrypted key */ #define BIP38_SERIALIZED_LEN 39 /** Length of a raw BIP38 key in bytes */ /** * Encode a private key in raw BIP 38 address format. * * :param bytes: Private key to use. * :param bytes_len: Size of ``bytes`` in bytes. Must be `EC_PRIVATE_KEY_LEN`. * :param pass: Password for the encoded private key. * :param pass_len: Length of ``pass`` in bytes. * :param flags: :ref:`bip38-flags` indicating desired behavior. * :param bytes_out: Destination for the resulting raw BIP38 address. * FIXED_SIZED_OUTPUT(len, bytes_out, BIP38_SERIALIZED_LEN) */ WALLY_CORE_API int bip38_raw_from_private_key( const unsigned char *bytes, size_t bytes_len, const unsigned char *pass, size_t pass_len, uint32_t flags, unsigned char *bytes_out, size_t len); /** * Encode a private key in BIP 38 address format. * * :param bytes: Private key to use. * :param bytes_len: Size of ``bytes`` in bytes. Must be `EC_PRIVATE_KEY_LEN`. * :param pass: Password for the encoded private key. * :param pass_len: Length of ``pass`` in bytes. * :param flags: :ref:`bip38-flags` indicating desired behavior. * :param output: Destination for the resulting BIP38 address. */ WALLY_CORE_API int bip38_from_private_key( const unsigned char *bytes, size_t bytes_len, const unsigned char *pass, size_t pass_len, uint32_t flags, char **output); /** * Decode a raw BIP 38 address to a private key. * * :param bytes: Raw BIP 38 address to decode. * :param bytes_len: Size of ``bytes`` in bytes. Must be `BIP38_SERIALIZED_LEN`. * :param pass: Password for the encoded private key. * :param pass_len: Length of ``pass`` in bytes. * :param flags: :ref:`bip38-flags` indicating desired behavior. * :param bytes_out: Destination for the resulting private key. * FIXED_SIZED_OUTPUT(len, bytes_out, EC_PRIVATE_KEY_LEN) */ WALLY_CORE_API int bip38_raw_to_private_key( const unsigned char *bytes, size_t bytes_len, const unsigned char *pass, size_t pass_len, uint32_t flags, unsigned char *bytes_out, size_t len); /** * Decode a BIP 38 address to a private key. * * :param bip38: BIP 38 address to decode. * :param pass: Password for the encoded private key. * :param pass_len: Length of ``pass`` in bytes. * :param flags: :ref:`bip38-flags` indicating desired behavior. * :param bytes_out: Destination for the resulting private key. * FIXED_SIZED_OUTPUT(len, bytes_out, EC_PRIVATE_KEY_LEN) */ WALLY_CORE_API int bip38_to_private_key( const char *bip38, const unsigned char *pass, size_t pass_len, uint32_t flags, unsigned char *bytes_out, size_t len); /** * Get compression and/or EC mult flags. * * :param bytes: Raw BIP 38 address to get the flags from. * :param bytes_len: Size of ``bytes`` in bytes. Must be `BIP38_SERIALIZED_LEN`. * :param written: :ref:`bip38-flags` indicating behavior. */ WALLY_CORE_API int bip38_raw_get_flags( const unsigned char *bytes, size_t bytes_len, size_t *written); /** * Get compression and/or EC mult flags. * * :param bip38: BIP 38 address to get the flags from. * :param written: :ref:`bip38-flags` indicating behavior. */ WALLY_CORE_API int bip38_get_flags( const char *bip38, size_t *written); #ifdef __cplusplus } #endif #endif /* LIBWALLY_CORE_BIP38_H */
76ed5b354d2bb29fad06b6e24d01e7e5a7dc5134
52db6253baa4bf3d32cc7ce0e9e5694b48391e65
/tests/platform-independent-tests/tests/texture-bunnymark/game.c
ec5e6f0c522cfdea9372b938ce20b5ad41467faf
[ "Unlicense" ]
permissive
SasLuca/rayfork
02a8e185002b872a115318410e94abfc0a015bb0
0db32b2c80384e89555aa8f64d5be390bbb28573
refs/heads/rayfork-0.9
2021-09-11T06:30:40.597951
2020-12-03T10:59:55
2020-12-03T10:59:55
228,938,024
347
27
Unlicense
2022-08-22T06:09:44
2019-12-18T23:25:18
C
UTF-8
C
false
false
3,832
c
game.c
//Implementation of the geometric shapes example from raylib using rayfork #include "game.h" #include "include/rayfork.h" #include "glad.h" #include "stdlib.h" #include "stdio.h" #define MAX_BUNNIES (50000) // 50K bunnies limit // This is the maximum amount of elements (quads) per batch // NOTE: This value is defined in [rlgl] module and can be changed there typedef struct bunny_t bunny_t; struct bunny_t { rf_vec2 position; rf_vec2 speed; rf_color color; }; rf_context rf_ctx; rf_default_render_batch rf_mem; rf_default_font default_font_mem; rf_texture2d bunny_texture; bunny_t* bunnies; int bunnies_count; int random_value_in_range(int min, int max) { if (min > max) { int tmp = max; max = min; min = tmp; } return (rand() % (abs(max - min) + 1) + min); } void on_init(void) { //Load opengl with glad gladLoadGL(); //Initialise rayfork and load the default font rf_init(&rf_ctx, &rf_mem, SCREEN_WIDTH, SCREEN_HEIGHT, RF_DEFAULT_OPENGL_PROCS); rf_load_default_font(&default_font_mem); bunny_texture = rf_load_texture_from_file(ASSETS_PATH"wabbit_alpha.png", RF_DEFAULT_ALLOCATOR, RF_DEFAULT_IO); bunnies = (bunny_t*) malloc(MAX_BUNNIES * sizeof(bunny_t)); // Bunnies array } void on_frame(const input_data input) { // Update if (input.left_mouse_button_pressed) { // Create more bunnies for (int i = 0; i < 100; i++) { if (bunnies_count < MAX_BUNNIES) { bunnies[bunnies_count].position = (rf_vec2) { (float) input.mouse_x, (float) input.mouse_y }; bunnies[bunnies_count].speed.x = (float) random_value_in_range(-250, 250) / 60.0f; bunnies[bunnies_count].speed.y = (float) random_value_in_range(-250, 250) / 60.0f; bunnies[bunnies_count].color = (rf_color) { random_value_in_range(50, 240), random_value_in_range(80, 240), random_value_in_range(100, 240), 255 }; bunnies_count++; } } } // Update bunnies for (int i = 0; i < bunnies_count; i++) { bunnies[i].position.x += bunnies[i].speed.x; bunnies[i].position.y += bunnies[i].speed.y; if (((bunnies[i].position.x + bunny_texture.width / 2) > SCREEN_WIDTH) || ((bunnies[i].position.x + bunny_texture.width / 2) < 0)) bunnies[i].speed.x *= -1; if (((bunnies[i].position.y + bunny_texture.height / 2) > SCREEN_HEIGHT) || ((bunnies[i].position.y + bunny_texture.height / 2 - 40) < 0)) bunnies[i].speed.y *= -1; } // Draw rf_begin(); rf_clear(RF_RAYWHITE); for (int i = 0; i < bunnies_count; i++) { // NOTE: When internal batch buffer limit is reached (MAX_BATCH_ELEMENTS), // a draw call is launched and buffer starts being filled again; // before issuing a draw call, updated vertex data from internal CPU buffer is send to GPU... // Process of sending data is costly and it could happen that GPU data has not been completely // processed for drawing while new data is tried to be sent (updating current in-use buffers) // it could generates a stall and consequently a frame drop, limiting the number of drawn bunnies rf_draw_texture(bunny_texture, bunnies[i].position.x, bunnies[i].position.y, bunnies[i].color); } rf_draw_rectangle(0, 0, SCREEN_WIDTH, 40, RF_BLACK); char text[1024]; snprintf(text, sizeof(text), "bunnies: %i", bunnies_count); rf_draw_text(text, 120, 10, 20, RF_GREEN); snprintf(text, sizeof(text), "batched draw calls: %i", 1 + bunnies_count / RF_DEFAULT_BATCH_ELEMENTS_COUNT); rf_draw_text(text, 320, 10, 20, RF_MAROON); rf_end(); }
8d2c2e4824cc5f8839702aed6f984425f62cbe56
b9f0b0458a57eaf8f8c8b44ff3942bb0ebca0044
/bin/pg_repack.c
d47631b108e6c6d1bdd7f2e4aa95c3250f6aecf1
[]
permissive
reorg/pg_repack
7d5517e99d11f9acb54f18896c21fff5e9dd6a62
a526a38b78b4917ce8e57461930bcb62bf4d87f5
refs/heads/master
2023-09-02T21:59:55.630599
2023-06-14T20:53:28
2023-06-14T20:53:28
6,633,165
1,512
160
BSD-3-Clause
2023-06-21T10:50:31
2012-11-10T22:39:27
C
UTF-8
C
false
false
70,425
c
pg_repack.c
/* * pg_repack.c: bin/pg_repack.c * * Portions Copyright (c) 2008-2011, NIPPON TELEGRAPH AND TELEPHONE CORPORATION * Portions Copyright (c) 2011, Itagaki Takahiro * Portions Copyright (c) 2012-2020, The Reorg Development Team */ /** * @brief Client Modules */ const char *PROGRAM_URL = "https://reorg.github.io/pg_repack/"; const char *PROGRAM_ISSUES = "https://github.com/reorg/pg_repack/issues"; #ifdef REPACK_VERSION /* macro trick to stringify a macro expansion */ #define xstr(s) str(s) #define str(s) #s const char *PROGRAM_VERSION = xstr(REPACK_VERSION); #else const char *PROGRAM_VERSION = "unknown"; #endif #include "pgut/pgut-fe.h" #include <errno.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <time.h> #ifdef HAVE_POLL_H #include <poll.h> #endif #ifdef HAVE_SYS_POLL_H #include <sys/poll.h> #endif #ifdef HAVE_SYS_SELECT_H #include <sys/select.h> #endif /* * APPLY_COUNT: Number of applied logs per transaction. Larger values * could be faster, but will be long transactions in the REDO phase. */ #define APPLY_COUNT 1000 /* Once we get down to seeing fewer than this many tuples in the * log table, we'll say that we're ready to perform the switch. */ #define SWITCH_THRESHOLD_DEFAULT 100 /* poll() or select() timeout, in seconds */ #define POLL_TIMEOUT 3 /* Compile an array of existing transactions which are active during * pg_repack's setup. Some transactions we can safely ignore: * a. The '1/1, -1/0' lock skipped is from the bgwriter on newly promoted * servers. See https://github.com/reorg/pg_reorg/issues/1 * b. Our own database connections * c. Other pg_repack clients, as distinguished by application_name, which * may be operating on other tables at the same time. See * https://github.com/reorg/pg_repack/issues/1 * d. open transactions/locks existing on other databases than the actual * processing relation (except for locks on shared objects) * e. VACUUMs which are always executed outside transaction blocks. * * Note, there is some redundancy in how the filtering is done (e.g. excluding * based on pg_backend_pid() and application_name), but that shouldn't hurt * anything. Also, the test of application_name is not bulletproof -- for * instance, the application name when running installcheck will be * pg_regress. */ #define SQL_XID_SNAPSHOT_90200 \ "SELECT coalesce(array_agg(l.virtualtransaction), '{}') " \ " FROM pg_locks AS l " \ " LEFT JOIN pg_stat_activity AS a " \ " ON l.pid = a.pid " \ " LEFT JOIN pg_database AS d " \ " ON a.datid = d.oid " \ " WHERE l.locktype = 'virtualxid' " \ " AND l.pid NOT IN (pg_backend_pid(), $1) " \ " AND (l.virtualxid, l.virtualtransaction) <> ('1/1', '-1/0') " \ " AND (a.application_name IS NULL OR a.application_name <> $2)" \ " AND a.query !~* E'^\\\\s*vacuum\\\\s+' " \ " AND a.query !~ E'^autovacuum: ' " \ " AND ((d.datname IS NULL OR d.datname = current_database()) OR l.database = 0)" #define SQL_XID_SNAPSHOT_90000 \ "SELECT coalesce(array_agg(l.virtualtransaction), '{}') " \ " FROM pg_locks AS l " \ " LEFT JOIN pg_stat_activity AS a " \ " ON l.pid = a.procpid " \ " LEFT JOIN pg_database AS d " \ " ON a.datid = d.oid " \ " WHERE l.locktype = 'virtualxid' " \ " AND l.pid NOT IN (pg_backend_pid(), $1) " \ " AND (l.virtualxid, l.virtualtransaction) <> ('1/1', '-1/0') " \ " AND (a.application_name IS NULL OR a.application_name <> $2)" \ " AND a.current_query !~* E'^\\\\s*vacuum\\\\s+' " \ " AND a.current_query !~ E'^autovacuum: ' " \ " AND ((d.datname IS NULL OR d.datname = current_database()) OR l.database = 0)" /* application_name is not available before 9.0. The last clause of * the WHERE clause is just to eat the $2 parameter (application name). */ #define SQL_XID_SNAPSHOT_80300 \ "SELECT coalesce(array_agg(l.virtualtransaction), '{}') " \ " FROM pg_locks AS l" \ " LEFT JOIN pg_stat_activity AS a " \ " ON l.pid = a.procpid " \ " LEFT JOIN pg_database AS d " \ " ON a.datid = d.oid " \ " WHERE l.locktype = 'virtualxid' AND l.pid NOT IN (pg_backend_pid(), $1)" \ " AND (l.virtualxid, l.virtualtransaction) <> ('1/1', '-1/0') " \ " AND a.current_query !~* E'^\\\\s*vacuum\\\\s+' " \ " AND a.current_query !~ E'^autovacuum: ' " \ " AND ((d.datname IS NULL OR d.datname = current_database()) OR l.database = 0)" \ " AND ($2::text IS NOT NULL)" #define SQL_XID_SNAPSHOT \ (PQserverVersion(connection) >= 90200 ? SQL_XID_SNAPSHOT_90200 : \ (PQserverVersion(connection) >= 90000 ? SQL_XID_SNAPSHOT_90000 : \ SQL_XID_SNAPSHOT_80300)) /* Later, check whether any of the transactions we saw before are still * alive, and wait for them to go away. */ #define SQL_XID_ALIVE \ "SELECT pid FROM pg_locks WHERE locktype = 'virtualxid'"\ " AND pid <> pg_backend_pid() AND virtualtransaction = ANY($1)" /* To be run while our main connection holds an AccessExclusive lock on the * target table, and our secondary conn is attempting to grab an AccessShare * lock. We know that "granted" must be false for these queries because * we already hold the AccessExclusive lock. Also, we only care about other * transactions trying to grab an ACCESS EXCLUSIVE lock, because we are only * trying to kill off disallowed DDL commands, e.g. ALTER TABLE or TRUNCATE. */ #define CANCEL_COMPETING_LOCKS \ "SELECT pg_cancel_backend(pid) FROM pg_locks WHERE locktype = 'relation'"\ " AND granted = false AND relation = %u"\ " AND mode = 'AccessExclusiveLock' AND pid <> pg_backend_pid()" #define KILL_COMPETING_LOCKS \ "SELECT pg_terminate_backend(pid) "\ "FROM pg_locks WHERE locktype = 'relation'"\ " AND granted = false AND relation = %u"\ " AND mode = 'AccessExclusiveLock' AND pid <> pg_backend_pid()" #define COUNT_COMPETING_LOCKS \ "SELECT pid FROM pg_locks WHERE locktype = 'relation'" \ " AND granted = false AND relation = %u" \ " AND mode = 'AccessExclusiveLock' AND pid <> pg_backend_pid()" /* Will be used as a unique prefix for advisory locks. */ #define REPACK_LOCK_PREFIX_STR "16185446" typedef enum { UNPROCESSED, INPROGRESS, FINISHED } index_status_t; /* * per-index information */ typedef struct repack_index { Oid target_oid; /* target: OID */ const char *create_index; /* CREATE INDEX */ index_status_t status; /* Track parallel build statuses. */ int worker_idx; /* which worker conn is handling */ } repack_index; /* * per-table information */ typedef struct repack_table { const char *target_name; /* target: relname */ Oid target_oid; /* target: OID */ Oid target_toast; /* target: toast OID */ Oid target_tidx; /* target: toast index OID */ Oid pkid; /* target: PK OID */ Oid ckid; /* target: CK OID */ const char *create_pktype; /* CREATE TYPE pk */ const char *create_log; /* CREATE TABLE log */ const char *create_trigger; /* CREATE TRIGGER repack_trigger */ const char *enable_trigger; /* ALTER TABLE ENABLE ALWAYS TRIGGER repack_trigger */ const char *create_table; /* CREATE TABLE table AS SELECT WITH NO DATA*/ const char *copy_data; /* INSERT INTO */ const char *alter_col_storage; /* ALTER TABLE ALTER COLUMN SET STORAGE */ const char *drop_columns; /* ALTER TABLE DROP COLUMNs */ const char *delete_log; /* DELETE FROM log */ const char *lock_table; /* LOCK TABLE table */ const char *sql_peek; /* SQL used in flush */ const char *sql_insert; /* SQL used in flush */ const char *sql_delete; /* SQL used in flush */ const char *sql_update; /* SQL used in flush */ const char *sql_pop; /* SQL used in flush */ int n_indexes; /* number of indexes */ repack_index *indexes; /* info on each index */ } repack_table; static bool is_superuser(void); static void check_tablespace(void); static bool preliminary_checks(char *errbuf, size_t errsize); static bool is_requested_relation_exists(char *errbuf, size_t errsize); static void repack_all_databases(const char *order_by); static bool repack_one_database(const char *order_by, char *errbuf, size_t errsize); static void repack_one_table(repack_table *table, const char *order_by); static bool repack_table_indexes(PGresult *index_details); static bool repack_all_indexes(char *errbuf, size_t errsize); static void repack_cleanup(bool fatal, const repack_table *table); static void repack_cleanup_callback(bool fatal, void *userdata); static bool rebuild_indexes(const repack_table *table); static char *getstr(PGresult *res, int row, int col); static Oid getoid(PGresult *res, int row, int col); static bool advisory_lock(PGconn *conn, const char *relid); static bool lock_exclusive(PGconn *conn, const char *relid, const char *lock_query, bool start_xact); static bool kill_ddl(PGconn *conn, Oid relid, bool terminate); static bool lock_access_share(PGconn *conn, Oid relid, const char *target_name); #define SQLSTATE_INVALID_SCHEMA_NAME "3F000" #define SQLSTATE_UNDEFINED_FUNCTION "42883" #define SQLSTATE_LOCK_NOT_AVAILABLE "55P03" static bool sqlstate_equals(PGresult *res, const char *state) { return strcmp(PQresultErrorField(res, PG_DIAG_SQLSTATE), state) == 0; } static bool analyze = true; static bool alldb = false; static bool noorder = false; static SimpleStringList parent_table_list = {NULL, NULL}; static SimpleStringList table_list = {NULL, NULL}; static SimpleStringList schema_list = {NULL, NULL}; static char *orderby = NULL; static char *tablespace = NULL; static bool moveidx = false; static SimpleStringList r_index = {NULL, NULL}; static bool only_indexes = false; static int wait_timeout = 60; /* in seconds */ static int jobs = 0; /* number of concurrent worker conns. */ static bool dryrun = false; static unsigned int temp_obj_num = 0; /* temporary objects counter */ static bool no_kill_backend = false; /* abandon when timed-out */ static bool no_superuser_check = false; static SimpleStringList exclude_extension_list = {NULL, NULL}; /* don't repack tables of these extensions */ static bool error_on_invalid_index = false; /* don't repack when invalid index is found */ static int switch_threshold = SWITCH_THRESHOLD_DEFAULT; /* buffer should have at least 11 bytes */ static char * utoa(unsigned int value, char *buffer) { sprintf(buffer, "%u", value); return buffer; } static pgut_option options[] = { { 'b', 'a', "all", &alldb }, { 'l', 't', "table", &table_list }, { 'l', 'I', "parent-table", &parent_table_list }, { 'l', 'c', "schema", &schema_list }, { 'b', 'n', "no-order", &noorder }, { 'b', 'N', "dry-run", &dryrun }, { 's', 'o', "order-by", &orderby }, { 's', 's', "tablespace", &tablespace }, { 'b', 'S', "moveidx", &moveidx }, { 'l', 'i', "index", &r_index }, { 'b', 'x', "only-indexes", &only_indexes }, { 'i', 'T', "wait-timeout", &wait_timeout }, { 'B', 'Z', "no-analyze", &analyze }, { 'i', 'j', "jobs", &jobs }, { 'b', 'D', "no-kill-backend", &no_kill_backend }, { 'b', 'k', "no-superuser-check", &no_superuser_check }, { 'l', 'C', "exclude-extension", &exclude_extension_list }, { 'b', 2, "error-on-invalid-index", &error_on_invalid_index }, { 'i', 1, "switch-threshold", &switch_threshold }, { 0 }, }; int main(int argc, char *argv[]) { int i; char errbuf[256]; i = pgut_getopt(argc, argv, options); if (i == argc - 1) dbname = argv[i]; else if (i < argc) ereport(ERROR, (errcode(EINVAL), errmsg("too many arguments"))); check_tablespace(); if (dryrun) elog(INFO, "Dry run enabled, not executing repack"); if (r_index.head || only_indexes) { if (r_index.head && table_list.head) ereport(ERROR, (errcode(EINVAL), errmsg("cannot specify --index (-i) and --table (-t)"))); if (r_index.head && parent_table_list.head) ereport(ERROR, (errcode(EINVAL), errmsg("cannot specify --index (-i) and --parent-table (-I)"))); else if (r_index.head && only_indexes) ereport(ERROR, (errcode(EINVAL), errmsg("cannot specify --index (-i) and --only-indexes (-x)"))); else if (r_index.head && exclude_extension_list.head) ereport(ERROR, (errcode(EINVAL), errmsg("cannot specify --index (-i) and --exclude-extension (-C)"))); else if (only_indexes && !(table_list.head || parent_table_list.head)) ereport(ERROR, (errcode(EINVAL), errmsg("cannot repack all indexes of database, specify the table(s)" "via --table (-t) or --parent-table (-I)"))); else if (only_indexes && exclude_extension_list.head) ereport(ERROR, (errcode(EINVAL), errmsg("cannot specify --only-indexes (-x) and --exclude-extension (-C)"))); else if (alldb) ereport(ERROR, (errcode(EINVAL), errmsg("cannot repack specific index(es) in all databases"))); else { if (orderby) ereport(WARNING, (errcode(EINVAL), errmsg("option -o (--order-by) has no effect while repacking indexes"))); else if (noorder) ereport(WARNING, (errcode(EINVAL), errmsg("option -n (--no-order) has no effect while repacking indexes"))); else if (!analyze) ereport(WARNING, (errcode(EINVAL), errmsg("ANALYZE is not performed after repacking indexes, -z (--no-analyze) has no effect"))); else if (jobs) ereport(WARNING, (errcode(EINVAL), errmsg("option -j (--jobs) has no effect, repacking indexes does not use parallel jobs"))); if (!repack_all_indexes(errbuf, sizeof(errbuf))) ereport(ERROR, (errcode(ERROR), errmsg("%s", errbuf))); } } else { if (schema_list.head && (table_list.head || parent_table_list.head)) ereport(ERROR, (errcode(EINVAL), errmsg("cannot repack specific table(s) in schema, use schema.table notation instead"))); if (exclude_extension_list.head && table_list.head) ereport(ERROR, (errcode(EINVAL), errmsg("cannot specify --table (-t) and --exclude-extension (-C)"))); if (exclude_extension_list.head && parent_table_list.head) ereport(ERROR, (errcode(EINVAL), errmsg("cannot specify --parent-table (-I) and --exclude-extension (-C)"))); if (noorder) orderby = ""; if (alldb) { if (table_list.head || parent_table_list.head) ereport(ERROR, (errcode(EINVAL), errmsg("cannot repack specific table(s) in all databases"))); if (schema_list.head) ereport(ERROR, (errcode(EINVAL), errmsg("cannot repack specific schema(s) in all databases"))); repack_all_databases(orderby); } else { if (!repack_one_database(orderby, errbuf, sizeof(errbuf))) ereport(ERROR, (errcode(ERROR), errmsg("%s failed with error: %s", PROGRAM_NAME, errbuf))); } } return 0; } /* * Test if the current user is a database superuser. * Borrowed from psql/common.c * * Note: this will correctly detect superuserness only with a protocol-3.0 * or newer backend; otherwise it will always say "false". */ bool is_superuser(void) { const char *val; if (no_superuser_check) return true; if (!connection) return false; val = PQparameterStatus(connection, "is_superuser"); if (val && strcmp(val, "on") == 0) return true; return false; } /* * Check if the tablespace requested exists. * * Raise an exception on error. */ void check_tablespace() { PGresult *res = NULL; const char *params[1]; if (tablespace == NULL) { /* nothing to check, but let's see the options */ if (moveidx) { ereport(ERROR, (errcode(EINVAL), errmsg("cannot specify --moveidx (-S) without --tablespace (-s)"))); } return; } /* check if the tablespace exists */ reconnect(ERROR); params[0] = tablespace; res = execute_elevel( "select spcname from pg_tablespace where spcname = $1", 1, params, DEBUG2); if (PQresultStatus(res) == PGRES_TUPLES_OK) { if (PQntuples(res) == 0) { ereport(ERROR, (errcode(EINVAL), errmsg("the tablespace \"%s\" doesn't exist", tablespace))); } } else { ereport(ERROR, (errcode(EINVAL), errmsg("error checking the namespace: %s", PQerrorMessage(connection)))); } CLEARPGRES(res); } /* * Perform sanity checks before beginning work. Make sure pg_repack is * installed in the database, the user is a superuser, etc. */ static bool preliminary_checks(char *errbuf, size_t errsize){ bool ret = false; PGresult *res = NULL; if (!is_superuser()) { if (errbuf) snprintf(errbuf, errsize, "You must be a superuser to use %s", PROGRAM_NAME); goto cleanup; } /* Query the extension version. Exit if no match */ res = execute_elevel("select repack.version(), repack.version_sql()", 0, NULL, DEBUG2); if (PQresultStatus(res) == PGRES_TUPLES_OK) { const char *libver; char buf[64]; /* the string is something like "pg_repack 1.1.7" */ snprintf(buf, sizeof(buf), "%s %s", PROGRAM_NAME, PROGRAM_VERSION); /* check the version of the C library */ libver = getstr(res, 0, 0); if (0 != strcmp(buf, libver)) { if (errbuf) snprintf(errbuf, errsize, "program '%s' does not match database library '%s'", buf, libver); goto cleanup; } /* check the version of the SQL extension */ libver = getstr(res, 0, 1); if (0 != strcmp(buf, libver)) { if (errbuf) snprintf(errbuf, errsize, "extension '%s' required, found '%s';" " please drop and re-create the extension", buf, libver); goto cleanup; } } else { if (sqlstate_equals(res, SQLSTATE_INVALID_SCHEMA_NAME) || sqlstate_equals(res, SQLSTATE_UNDEFINED_FUNCTION)) { /* Schema repack does not exist, or version too old (version * functions not found). Skip the database. */ if (errbuf) snprintf(errbuf, errsize, "%s %s is not installed in the database", PROGRAM_NAME, PROGRAM_VERSION); } else { /* Return the error message otherwise */ if (errbuf) snprintf(errbuf, errsize, "%s", PQerrorMessage(connection)); } goto cleanup; } CLEARPGRES(res); /* Disable statement timeout. */ command("SET statement_timeout = 0", 0, NULL); /* Restrict search_path to system catalog. */ command("SET search_path = pg_catalog, pg_temp, public", 0, NULL); /* To avoid annoying "create implicit ..." messages. */ command("SET client_min_messages = warning", 0, NULL); ret = true; cleanup: CLEARPGRES(res); return ret; } /* * Check the presence of tables specified by --parent-table and --table * otherwise format user-friendly message */ static bool is_requested_relation_exists(char *errbuf, size_t errsize){ bool ret = false; PGresult *res = NULL; const char **params = NULL; int iparam = 0; StringInfoData sql; int num_relations; SimpleStringListCell *cell; num_relations = simple_string_list_size(parent_table_list) + simple_string_list_size(table_list); /* nothing was implicitly requested, so nothing to do here */ if (num_relations == 0) return true; /* has no suitable to_regclass(text) */ if (PQserverVersion(connection)<90600) return true; params = pgut_malloc(num_relations * sizeof(char *)); initStringInfo(&sql); appendStringInfoString(&sql, "SELECT r FROM (VALUES "); for (cell = table_list.head; cell; cell = cell->next) { appendStringInfo(&sql, "($%d, 'r')", iparam + 1); params[iparam++] = cell->val; if (iparam < num_relations) appendStringInfoChar(&sql, ','); } for (cell = parent_table_list.head; cell; cell = cell->next) { appendStringInfo(&sql, "($%d, 'p')", iparam + 1); params[iparam++] = cell->val; if (iparam < num_relations) appendStringInfoChar(&sql, ','); } appendStringInfoString(&sql, ") AS given_t(r,kind) WHERE" /* regular --table relation or inherited --parent-table */ " NOT EXISTS(" " SELECT FROM repack.tables WHERE relid=to_regclass(given_t.r))" /* declarative partitioned --parent-table */ " AND NOT EXISTS(" " SELECT FROM pg_catalog.pg_class c WHERE c.oid=to_regclass(given_t.r) AND c.relkind = given_t.kind AND given_t.kind = 'p')" ); /* double check the parameters array is sane */ if (iparam != num_relations) { if (errbuf) snprintf(errbuf, errsize, "internal error: bad parameters count: %i instead of %i", iparam, num_relations); goto cleanup; } res = execute_elevel(sql.data, iparam, params, DEBUG2); if (PQresultStatus(res) == PGRES_TUPLES_OK) { int num; num = PQntuples(res); if (num != 0) { int i; StringInfoData rel_names; initStringInfo(&rel_names); for (i = 0; i < num; i++) { appendStringInfo(&rel_names, "\"%s\"", getstr(res, i, 0)); if ((i + 1) != num) appendStringInfoString(&rel_names, ", "); } if (errbuf) { if (num > 1) snprintf(errbuf, errsize, "relations do not exist: %s", rel_names.data); else snprintf(errbuf, errsize, "ERROR: relation %s does not exist", rel_names.data); } termStringInfo(&rel_names); } else ret = true; } else { if (errbuf) snprintf(errbuf, errsize, "%s", PQerrorMessage(connection)); } CLEARPGRES(res); cleanup: CLEARPGRES(res); termStringInfo(&sql); free(params); return ret; } /* * Call repack_one_database for each database. */ static void repack_all_databases(const char *orderby) { PGresult *result; int i; dbname = "postgres"; reconnect(ERROR); if (!is_superuser()) elog(ERROR, "You must be a superuser to use %s", PROGRAM_NAME); result = execute("SELECT datname FROM pg_database WHERE datallowconn ORDER BY 1;", 0, NULL); disconnect(); for (i = 0; i < PQntuples(result); i++) { bool ret; char errbuf[256]; dbname = PQgetvalue(result, i, 0); elog(INFO, "repacking database \"%s\"", dbname); if (!dryrun) { ret = repack_one_database(orderby, errbuf, sizeof(errbuf)); if (!ret) elog(INFO, "database \"%s\" skipped: %s", dbname, errbuf); } } CLEARPGRES(result); } /* result is not copied */ static char * getstr(PGresult *res, int row, int col) { if (PQgetisnull(res, row, col)) return NULL; else return PQgetvalue(res, row, col); } static Oid getoid(PGresult *res, int row, int col) { if (PQgetisnull(res, row, col)) return InvalidOid; else return (Oid)strtoul(PQgetvalue(res, row, col), NULL, 10); } /* * Call repack_one_table for the target tables or each table in a database. */ static bool repack_one_database(const char *orderby, char *errbuf, size_t errsize) { bool ret = false; PGresult *res = NULL; int i; int num; StringInfoData sql; SimpleStringListCell *cell; const char **params = NULL; int iparam = 0; size_t num_parent_tables, num_tables, num_schemas, num_params, num_excluded_extensions; num_parent_tables = simple_string_list_size(parent_table_list); num_tables = simple_string_list_size(table_list); num_schemas = simple_string_list_size(schema_list); num_excluded_extensions = simple_string_list_size(exclude_extension_list); /* 1st param is the user-specified tablespace */ num_params = num_excluded_extensions + num_parent_tables + num_tables + num_schemas + 1; params = pgut_malloc(num_params * sizeof(char *)); initStringInfo(&sql); reconnect(ERROR); /* No sense in setting up concurrent workers if --jobs=1 */ if (jobs > 1) setup_workers(jobs); if (!preliminary_checks(errbuf, errsize)) goto cleanup; if (!is_requested_relation_exists(errbuf, errsize)) goto cleanup; /* acquire target tables */ appendStringInfoString(&sql, "SELECT t.*," " coalesce(v.tablespace, t.tablespace_orig) as tablespace_dest" " FROM repack.tables t, " " (VALUES (quote_ident($1::text))) as v (tablespace)" " WHERE "); params[iparam++] = tablespace; if (num_tables || num_parent_tables) { /* standalone tables */ if (num_tables) { appendStringInfoString(&sql, "("); for (cell = table_list.head; cell; cell = cell->next) { /* Construct table name placeholders to be used by PQexecParams */ appendStringInfo(&sql, "relid = $%d::regclass", iparam + 1); params[iparam++] = cell->val; if (cell->next) appendStringInfoString(&sql, " OR "); } appendStringInfoString(&sql, ")"); } if (num_tables && num_parent_tables) appendStringInfoString(&sql, " OR "); /* parent tables + inherited children */ if (num_parent_tables) { appendStringInfoString(&sql, "("); for (cell = parent_table_list.head; cell; cell = cell->next) { /* Construct table name placeholders to be used by PQexecParams */ appendStringInfo(&sql, "relid = ANY(repack.get_table_and_inheritors($%d::regclass))", iparam + 1); params[iparam++] = cell->val; if (cell->next) appendStringInfoString(&sql, " OR "); } appendStringInfoString(&sql, ")"); } } else if (num_schemas) { appendStringInfoString(&sql, "schemaname IN ("); for (cell = schema_list.head; cell; cell = cell->next) { /* Construct schema name placeholders to be used by PQexecParams */ appendStringInfo(&sql, "$%d", iparam + 1); params[iparam++] = cell->val; if (cell->next) appendStringInfoString(&sql, ", "); } appendStringInfoString(&sql, ")"); } else { appendStringInfoString(&sql, "pkid IS NOT NULL"); } /* Exclude tables which belong to extensions */ if (exclude_extension_list.head) { appendStringInfoString(&sql, " AND t.relid NOT IN" " (SELECT d.objid::regclass" " FROM pg_depend d JOIN pg_extension e" " ON d.refobjid = e.oid" " WHERE d.classid = 'pg_class'::regclass AND ("); /* List all excluded extensions */ for (cell = exclude_extension_list.head; cell; cell = cell->next) { appendStringInfo(&sql, "e.extname = $%d", iparam + 1); params[iparam++] = cell->val; appendStringInfoString(&sql, cell->next ? " OR " : ")"); } /* Close subquery */ appendStringInfoString(&sql, ")"); } /* Ensure the regression tests get a consistent ordering of tables */ appendStringInfoString(&sql, " ORDER BY t.relname, t.schemaname"); /* double check the parameters array is sane */ if (iparam != num_params) { if (errbuf) snprintf(errbuf, errsize, "internal error: bad parameters count: %i instead of %zi", iparam, num_params); goto cleanup; } res = execute_elevel(sql.data, (int) num_params, params, DEBUG2); /* on error skip the database */ if (PQresultStatus(res) != PGRES_TUPLES_OK) { /* Return the error message otherwise */ if (errbuf) snprintf(errbuf, errsize, "%s", PQerrorMessage(connection)); goto cleanup; } num = PQntuples(res); for (i = 0; i < num; i++) { repack_table table; StringInfoData copy_sql; const char *create_table_1; const char *create_table_2; const char *tablespace; const char *ckey; int c = 0; table.target_name = getstr(res, i, c++); table.target_oid = getoid(res, i, c++); table.target_toast = getoid(res, i, c++); table.target_tidx = getoid(res, i, c++); c++; // Skip schemaname table.pkid = getoid(res, i, c++); table.ckid = getoid(res, i, c++); if (table.pkid == 0) { ereport(WARNING, (errcode(E_PG_COMMAND), errmsg("relation \"%s\" must have a primary key or not-null unique keys", table.target_name))); continue; } table.create_pktype = getstr(res, i, c++); table.create_log = getstr(res, i, c++); table.create_trigger = getstr(res, i, c++); table.enable_trigger = getstr(res, i, c++); create_table_1 = getstr(res, i, c++); tablespace = getstr(res, i, c++); /* to be clobbered */ create_table_2 = getstr(res, i, c++); table.copy_data = getstr(res, i , c++); table.alter_col_storage = getstr(res, i, c++); table.drop_columns = getstr(res, i, c++); table.delete_log = getstr(res, i, c++); table.lock_table = getstr(res, i, c++); ckey = getstr(res, i, c++); table.sql_peek = getstr(res, i, c++); table.sql_insert = getstr(res, i, c++); table.sql_delete = getstr(res, i, c++); table.sql_update = getstr(res, i, c++); table.sql_pop = getstr(res, i, c++); tablespace = getstr(res, i, c++); /* Craft CREATE TABLE SQL */ resetStringInfo(&sql); appendStringInfoString(&sql, create_table_1); appendStringInfoString(&sql, tablespace); appendStringInfoString(&sql, create_table_2); /* Always append WITH NO DATA to CREATE TABLE SQL*/ appendStringInfoString(&sql, " WITH NO DATA"); table.create_table = sql.data; /* Craft Copy SQL */ initStringInfo(&copy_sql); appendStringInfoString(&copy_sql, table.copy_data); if (!orderby) { if (ckey != NULL) { /* CLUSTER mode */ appendStringInfoString(&copy_sql, " ORDER BY "); appendStringInfoString(&copy_sql, ckey); } /* else, VACUUM FULL mode (non-clustered tables) */ } else if (!orderby[0]) { /* VACUUM FULL mode (for clustered tables too), do nothing */ } else { /* User specified ORDER BY */ appendStringInfoString(&copy_sql, " ORDER BY "); appendStringInfoString(&copy_sql, orderby); } table.copy_data = copy_sql.data; repack_one_table(&table, orderby); } ret = true; cleanup: CLEARPGRES(res); disconnect(); termStringInfo(&sql); free(params); return ret; } static int apply_log(PGconn *conn, const repack_table *table, int count) { int result; PGresult *res; const char *params[6]; char buffer[12]; params[0] = table->sql_peek; params[1] = table->sql_insert; params[2] = table->sql_delete; params[3] = table->sql_update; params[4] = table->sql_pop; params[5] = utoa(count, buffer); res = pgut_execute(conn, "SELECT repack.repack_apply($1, $2, $3, $4, $5, $6)", 6, params); result = atoi(PQgetvalue(res, 0, 0)); CLEARPGRES(res); return result; } /* * Create indexes on temp table, possibly using multiple worker connections * concurrently if the user asked for --jobs=... */ static bool rebuild_indexes(const repack_table *table) { PGresult *res = NULL; int num_indexes; int i; int num_active_workers; int num_workers; repack_index *index_jobs; bool have_error = false; elog(DEBUG2, "---- create indexes ----"); num_indexes = table->n_indexes; /* We might have more actual worker connections than we need, * if the number of workers exceeds the number of indexes to be * built. In that case, ignore the extra workers. */ num_workers = num_indexes > workers.num_workers ? workers.num_workers : num_indexes; num_active_workers = num_workers; elog(DEBUG2, "Have %d indexes and num_workers=%d", num_indexes, num_workers); index_jobs = table->indexes; for (i = 0; i < num_indexes; i++) { elog(DEBUG2, "set up index_jobs [%d]", i); elog(DEBUG2, "target_oid : %u", index_jobs[i].target_oid); elog(DEBUG2, "create_index : %s", index_jobs[i].create_index); if (num_workers <= 1) { /* Use primary connection if we are not setting up parallel * index building, or if we only have one worker. */ command(index_jobs[i].create_index, 0, NULL); /* This bookkeeping isn't actually important in this no-workers * case, but just for clarity. */ index_jobs[i].status = FINISHED; } else if (i < num_workers) { /* Assign available worker to build an index. */ index_jobs[i].status = INPROGRESS; index_jobs[i].worker_idx = i; elog(LOG, "Initial worker %d to build index: %s", i, index_jobs[i].create_index); if (!(PQsendQuery(workers.conns[i], index_jobs[i].create_index))) { elog(WARNING, "Error sending async query: %s\n%s", index_jobs[i].create_index, PQerrorMessage(workers.conns[i])); have_error = true; goto cleanup; } } /* Else we have more indexes to be built than workers * available. That's OK, we'll get to them later. */ } if (num_workers > 1) { int freed_worker = -1; int ret; /* Prefer poll() over select(), following PostgreSQL custom. */ #ifdef HAVE_POLL struct pollfd *input_fds; input_fds = pgut_malloc(sizeof(struct pollfd) * num_workers); for (i = 0; i < num_workers; i++) { input_fds[i].fd = PQsocket(workers.conns[i]); input_fds[i].events = POLLIN | POLLERR; input_fds[i].revents = 0; } #else fd_set input_mask; struct timeval timeout; /* select() needs the highest-numbered socket descriptor */ int max_fd; #endif /* Now go through our index builds, and look for any which is * reported complete. Reassign that worker to the next index to * be built, if any. */ while (num_active_workers > 0) { elog(DEBUG2, "polling %d active workers", num_active_workers); #ifdef HAVE_POLL ret = poll(input_fds, num_workers, POLL_TIMEOUT * 1000); #else /* re-initialize timeout and input_mask before each * invocation of select(). I think this isn't * necessary on many Unixen, but just in case. */ timeout.tv_sec = POLL_TIMEOUT; timeout.tv_usec = 0; FD_ZERO(&input_mask); for (i = 0, max_fd = 0; i < num_workers; i++) { FD_SET(PQsocket(workers.conns[i]), &input_mask); if (PQsocket(workers.conns[i]) > max_fd) max_fd = PQsocket(workers.conns[i]); } ret = select(max_fd + 1, &input_mask, NULL, NULL, &timeout); #endif /* XXX: the errno != EINTR check means we won't bail * out on SIGINT. We should probably just remove this * check, though it seems we also need to fix up * the on_interrupt handling for workers' index * builds (those PGconns don't seem to have c->cancel * set, so we don't cancel the in-progress builds). */ if (ret < 0 && errno != EINTR) elog(ERROR, "poll() failed: %d, %d", ret, errno); elog(DEBUG2, "Poll returned: %d", ret); for (i = 0; i < num_indexes; i++) { if (index_jobs[i].status == INPROGRESS) { Assert(index_jobs[i].worker_idx >= 0); /* Must call PQconsumeInput before we can check PQisBusy */ if (PQconsumeInput(workers.conns[index_jobs[i].worker_idx]) != 1) { elog(WARNING, "Error fetching async query status: %s", PQerrorMessage(workers.conns[index_jobs[i].worker_idx])); have_error = true; goto cleanup; } if (!PQisBusy(workers.conns[index_jobs[i].worker_idx])) { elog(LOG, "Command finished in worker %d: %s", index_jobs[i].worker_idx, index_jobs[i].create_index); while ((res = PQgetResult(workers.conns[index_jobs[i].worker_idx]))) { if (PQresultStatus(res) != PGRES_COMMAND_OK) { elog(WARNING, "Error with create index: %s", PQerrorMessage(workers.conns[index_jobs[i].worker_idx])); have_error = true; goto cleanup; } CLEARPGRES(res); } /* We are only going to re-queue one worker, even * though more than one index build might be finished. * Any other jobs which may be finished will * just have to wait for the next pass through the * poll()/select() loop. */ freed_worker = index_jobs[i].worker_idx; index_jobs[i].status = FINISHED; num_active_workers--; break; } } } if (freed_worker > -1) { for (i = 0; i < num_indexes; i++) { if (index_jobs[i].status == UNPROCESSED) { index_jobs[i].status = INPROGRESS; index_jobs[i].worker_idx = freed_worker; elog(LOG, "Assigning worker %d to build index #%d: " "%s", freed_worker, i, index_jobs[i].create_index); if (!(PQsendQuery(workers.conns[freed_worker], index_jobs[i].create_index))) { elog(WARNING, "Error sending async query: %s\n%s", index_jobs[i].create_index, PQerrorMessage(workers.conns[freed_worker])); have_error = true; goto cleanup; } num_active_workers++; break; } } freed_worker = -1; } } } cleanup: CLEARPGRES(res); return (!have_error); } /* * Re-organize one table. */ static void repack_one_table(repack_table *table, const char *orderby) { PGresult *res = NULL; const char *params[3]; int num; char *vxid = NULL; char buffer[12]; StringInfoData sql; bool ret = false; PGresult *indexres = NULL; const char *indexparams[2]; char indexbuffer[12]; int j; /* appname will be "pg_repack" in normal use on 9.0+, or * "pg_regress" when run under `make installcheck` */ const char *appname = getenv("PGAPPNAME"); /* Keep track of whether we have gotten through setup to install * the repack_trigger, log table, etc. ourselves. We don't want to * go through repack_cleanup() if we didn't actually set up the * trigger ourselves, lest we be cleaning up another pg_repack's mess, * or worse, interfering with a still-running pg_repack. */ bool table_init = false; initStringInfo(&sql); elog(INFO, "repacking table \"%s\"", table->target_name); elog(DEBUG2, "---- repack_one_table ----"); elog(DEBUG2, "target_name : %s", table->target_name); elog(DEBUG2, "target_oid : %u", table->target_oid); elog(DEBUG2, "target_toast : %u", table->target_toast); elog(DEBUG2, "target_tidx : %u", table->target_tidx); elog(DEBUG2, "pkid : %u", table->pkid); elog(DEBUG2, "ckid : %u", table->ckid); elog(DEBUG2, "create_pktype : %s", table->create_pktype); elog(DEBUG2, "create_log : %s", table->create_log); elog(DEBUG2, "create_trigger : %s", table->create_trigger); elog(DEBUG2, "enable_trigger : %s", table->enable_trigger); elog(DEBUG2, "create_table : %s", table->create_table); elog(DEBUG2, "copy_data : %s", table->copy_data); elog(DEBUG2, "alter_col_storage : %s", table->alter_col_storage ? table->alter_col_storage : "(skipped)"); elog(DEBUG2, "drop_columns : %s", table->drop_columns ? table->drop_columns : "(skipped)"); elog(DEBUG2, "delete_log : %s", table->delete_log); elog(DEBUG2, "lock_table : %s", table->lock_table); elog(DEBUG2, "sql_peek : %s", table->sql_peek); elog(DEBUG2, "sql_insert : %s", table->sql_insert); elog(DEBUG2, "sql_delete : %s", table->sql_delete); elog(DEBUG2, "sql_update : %s", table->sql_update); elog(DEBUG2, "sql_pop : %s", table->sql_pop); if (dryrun) return; /* push repack_cleanup_callback() on stack to clean temporary objects */ pgut_atexit_push(repack_cleanup_callback, table); /* * 1. Setup advisory lock and trigger on main table. */ elog(DEBUG2, "---- setup ----"); params[0] = utoa(table->target_oid, buffer); if (!advisory_lock(connection, buffer)) goto cleanup; if (!(lock_exclusive(connection, buffer, table->lock_table, true))) { if (no_kill_backend) elog(INFO, "Skipping repack %s due to timeout", table->target_name); else elog(WARNING, "lock_exclusive() failed for %s", table->target_name); goto cleanup; } /* * pg_get_indexdef requires an access share lock, so do those calls while * we have an access exclusive lock anyway, so we know they won't block. */ indexparams[0] = utoa(table->target_oid, indexbuffer); indexparams[1] = moveidx ? tablespace : NULL; /* First, just display a warning message for any invalid indexes * which may be on the table (mostly to match the behavior of 1.1.8), * if --error-on-invalid-index is not set */ indexres = execute( "SELECT pg_get_indexdef(indexrelid)" " FROM pg_index WHERE indrelid = $1 AND NOT indisvalid", 1, indexparams); for (j = 0; j < PQntuples(indexres); j++) { const char *indexdef; indexdef = getstr(indexres, j, 0); if (error_on_invalid_index) { elog(WARNING, "Invalid index: %s", indexdef); goto cleanup; } else { elog(WARNING, "skipping invalid index: %s", indexdef); } } indexres = execute( "SELECT indexrelid," " repack.repack_indexdef(indexrelid, indrelid, $2, FALSE) " " FROM pg_index WHERE indrelid = $1 AND indisvalid", 2, indexparams); table->n_indexes = PQntuples(indexres); table->indexes = pgut_malloc(table->n_indexes * sizeof(repack_index)); for (j = 0; j < table->n_indexes; j++) { table->indexes[j].target_oid = getoid(indexres, j, 0); table->indexes[j].create_index = getstr(indexres, j, 1); table->indexes[j].status = UNPROCESSED; table->indexes[j].worker_idx = -1; /* Unassigned */ } for (j = 0; j < table->n_indexes; j++) { elog(DEBUG2, "index[%d].target_oid : %u", j, table->indexes[j].target_oid); elog(DEBUG2, "index[%d].create_index : %s", j, table->indexes[j].create_index); } /* * Check if repack_trigger is not conflict with existing trigger. We can * find it out later but we check it in advance and go to cleanup if needed. * In AFTER trigger context, since triggered tuple is not changed by other * trigger we don't care about the fire order. */ res = execute("SELECT repack.conflicted_triggers($1)", 1, params); if (PQntuples(res) > 0) { ereport(WARNING, (errcode(E_PG_COMMAND), errmsg("the table \"%s\" already has a trigger called \"%s\"", table->target_name, "repack_trigger"), errdetail( "The trigger was probably installed during a previous" " attempt to run pg_repack on the table which was" " interrupted and for some reason failed to clean up" " the temporary objects. Please drop the trigger or drop" " and recreate the pg_repack extension altogether" " to remove all the temporary objects left over."))); goto cleanup; } CLEARPGRES(res); command(table->create_pktype, 0, NULL); temp_obj_num++; command(table->create_log, 0, NULL); temp_obj_num++; command(table->create_trigger, 0, NULL); temp_obj_num++; command(table->enable_trigger, 0, NULL); printfStringInfo(&sql, "SELECT repack.disable_autovacuum('repack.log_%u')", table->target_oid); command(sql.data, 0, NULL); /* While we are still holding an AccessExclusive lock on the table, submit * the request for an AccessShare lock asynchronously from conn2. * We want to submit this query in conn2 while connection's * transaction still holds its lock, so that no DDL may sneak in * between the time that connection commits and conn2 gets its lock. */ pgut_command(conn2, "BEGIN ISOLATION LEVEL READ COMMITTED", 0, NULL); /* grab the backend PID of conn2; we'll need this when querying * pg_locks momentarily. */ res = pgut_execute(conn2, "SELECT pg_backend_pid()", 0, NULL); buffer[0] = '\0'; strncat(buffer, PQgetvalue(res, 0, 0), sizeof(buffer) - 1); CLEARPGRES(res); /* * Not using lock_access_share() here since we know that * it's not possible to obtain the ACCESS SHARE lock right now * in conn2, since the primary connection holds ACCESS EXCLUSIVE. */ printfStringInfo(&sql, "LOCK TABLE %s IN ACCESS SHARE MODE", table->target_name); elog(DEBUG2, "LOCK TABLE %s IN ACCESS SHARE MODE", table->target_name); if (PQsetnonblocking(conn2, 1)) { elog(WARNING, "Unable to set conn2 nonblocking."); goto cleanup; } if (!(PQsendQuery(conn2, sql.data))) { elog(WARNING, "Error sending async query: %s\n%s", sql.data, PQerrorMessage(conn2)); goto cleanup; } /* Now that we've submitted the LOCK TABLE request through conn2, * look for and cancel any (potentially dangerous) DDL commands which * might also be waiting on our table lock at this point -- * it's not safe to let them wait, because they may grab their * AccessExclusive lock before conn2 gets its AccessShare lock, * and perform unsafe DDL on the table. * * Normally, lock_access_share() would take care of this for us, * but we're not able to use it here. */ if (!(kill_ddl(connection, table->target_oid, true))) { if (no_kill_backend) elog(INFO, "Skipping repack %s due to timeout.", table->target_name); else elog(WARNING, "kill_ddl() failed."); goto cleanup; } /* We're finished killing off any unsafe DDL. COMMIT in our main * connection, so that conn2 may get its AccessShare lock. */ command("COMMIT", 0, NULL); /* The main connection has now committed its repack_trigger, * log table, and temp. table. If any error occurs from this point * on and we bail out, we should try to clean those up. */ table_init = true; /* Keep looping PQgetResult() calls until it returns NULL, indicating the * command is done and we have obtained our lock. */ while ((res = PQgetResult(conn2))) { elog(DEBUG2, "Waiting on ACCESS SHARE lock..."); if (PQresultStatus(res) != PGRES_COMMAND_OK) { elog(WARNING, "Error with LOCK TABLE: %s", PQerrorMessage(conn2)); goto cleanup; } CLEARPGRES(res); } /* Turn conn2 back into blocking mode for further non-async use. */ if (PQsetnonblocking(conn2, 0)) { elog(WARNING, "Unable to set conn2 blocking."); goto cleanup; } /* * 2. Copy tuples into temp table. */ elog(DEBUG2, "---- copy tuples ----"); /* Must use SERIALIZABLE (or at least not READ COMMITTED) to avoid race * condition between the create_table statement and rows subsequently * being added to the log. */ command("BEGIN ISOLATION LEVEL SERIALIZABLE", 0, NULL); /* SET work_mem = maintenance_work_mem */ command("SELECT set_config('work_mem', current_setting('maintenance_work_mem'), true)", 0, NULL); if (orderby && !orderby[0]) command("SET LOCAL synchronize_seqscans = off", 0, NULL); /* Fetch an array of Virtual IDs of all transactions active right now. */ params[0] = buffer; /* backend PID of conn2 */ params[1] = PROGRAM_NAME; res = execute(SQL_XID_SNAPSHOT, 2, params); vxid = pgut_strdup(PQgetvalue(res, 0, 0)); CLEARPGRES(res); /* Delete any existing entries in the log table now, since we have not * yet run the CREATE TABLE ... AS SELECT, which will take in all existing * rows from the target table; if we also included prior rows from the * log we could wind up with duplicates. */ command(table->delete_log, 0, NULL); /* We need to be able to obtain an AccessShare lock on the target table * for the create_table command to go through, so go ahead and obtain * the lock explicitly. * * Since conn2 has been diligently holding its AccessShare lock, it * is possible that another transaction has been waiting to acquire * an AccessExclusive lock on the table (e.g. a concurrent ALTER TABLE * or TRUNCATE which we must not allow). If there are any such * transactions, lock_access_share() will kill them so that our * CREATE TABLE ... AS SELECT does not deadlock waiting for an * AccessShare lock. */ if (!(lock_access_share(connection, table->target_oid, table->target_name))) goto cleanup; /* * Before copying data to the target table, we need to set the column storage * type if its storage type has been changed from the type default. */ command(table->create_table, 0, NULL); if (table->alter_col_storage) command(table->alter_col_storage, 0, NULL); command(table->copy_data, 0, NULL); temp_obj_num++; printfStringInfo(&sql, "SELECT repack.disable_autovacuum('repack.table_%u')", table->target_oid); if (table->drop_columns) command(table->drop_columns, 0, NULL); command(sql.data, 0, NULL); command("COMMIT", 0, NULL); /* * 3. Create indexes on temp table. */ if (!rebuild_indexes(table)) goto cleanup; /* don't clear indexres until after rebuild_indexes or bad things happen */ CLEARPGRES(indexres); CLEARPGRES(res); /* * 4. Apply log to temp table until no tuples are left in the log * and all of the old transactions are finished. */ for (;;) { num = apply_log(connection, table, APPLY_COUNT); /* We'll keep applying tuples from the log table in batches * of APPLY_COUNT, until applying a batch of tuples * (via LIMIT) results in our having applied * switch_threshold or fewer tuples. We don't want to * get stuck repetitively applying some small number of tuples * from the log table as inserts/updates/deletes may be * constantly coming into the original table. */ if (num > switch_threshold) continue; /* there might be still some tuples, repeat. */ /* old transactions still alive ? */ params[0] = vxid; res = execute(SQL_XID_ALIVE, 1, params); num = PQntuples(res); if (num > 0) { /* Wait for old transactions. * Only display this message if we are NOT * running under pg_regress, so as not to cause * noise which would trip up pg_regress. */ if (!appname || strcmp(appname, "pg_regress") != 0) { elog(NOTICE, "Waiting for %d transactions to finish. First PID: %s", num, PQgetvalue(res, 0, 0)); } CLEARPGRES(res); sleep(1); continue; } else { /* All old transactions are finished; * go to next step. */ CLEARPGRES(res); break; } } /* * 5. Swap: will be done with conn2, since it already holds an * AccessShare lock. */ elog(DEBUG2, "---- swap ----"); /* Bump our existing AccessShare lock to AccessExclusive */ if (!(lock_exclusive(conn2, utoa(table->target_oid, buffer), table->lock_table, false))) { elog(WARNING, "lock_exclusive() failed in conn2 for %s", table->target_name); goto cleanup; } apply_log(conn2, table, 0); params[0] = utoa(table->target_oid, buffer); pgut_command(conn2, "SELECT repack.repack_swap($1)", 1, params); pgut_command(conn2, "COMMIT", 0, NULL); /* * 6. Drop. */ elog(DEBUG2, "---- drop ----"); command("BEGIN ISOLATION LEVEL READ COMMITTED", 0, NULL); if (!(lock_exclusive(connection, utoa(table->target_oid, buffer), table->lock_table, false))) { elog(WARNING, "lock_exclusive() failed in connection for %s", table->target_name); goto cleanup; } params[1] = utoa(temp_obj_num, indexbuffer); command("SELECT repack.repack_drop($1, $2)", 2, params); command("COMMIT", 0, NULL); temp_obj_num = 0; /* reset temporary object counter after cleanup */ /* * 7. Analyze. * Note that cleanup hook has been already uninstalled here because analyze * is not an important operation; No clean up even if failed. */ if (analyze) { elog(DEBUG2, "---- analyze ----"); command("BEGIN ISOLATION LEVEL READ COMMITTED", 0, NULL); printfStringInfo(&sql, "ANALYZE %s", table->target_name); command(sql.data, 0, NULL); command("COMMIT", 0, NULL); } /* Release advisory lock on table. */ params[0] = REPACK_LOCK_PREFIX_STR; params[1] = utoa(table->target_oid, buffer); res = pgut_execute(connection, "SELECT pg_advisory_unlock($1, CAST(-2147483648 + $2::bigint AS integer))", 2, params); ret = true; cleanup: CLEARPGRES(res); termStringInfo(&sql); if (vxid) free(vxid); /* Rollback current transactions */ pgut_rollback(connection); pgut_rollback(conn2); /* XXX: distinguish between fatal and non-fatal errors via the first * arg to repack_cleanup(). */ if ((!ret) && table_init) repack_cleanup(false, table); } /* Kill off any concurrent DDL (or any transaction attempting to take * an AccessExclusive lock) trying to run against our table if we want to * do. Note, we're killing these queries off *before* they are granted * an AccessExclusive lock on our table. * * Returns true if no problems encountered, false otherwise. */ static bool kill_ddl(PGconn *conn, Oid relid, bool terminate) { bool ret = true; PGresult *res; StringInfoData sql; int n_tuples; initStringInfo(&sql); /* Check the number of backends competing AccessExclusiveLock */ printfStringInfo(&sql, COUNT_COMPETING_LOCKS, relid); res = pgut_execute(conn, sql.data, 0, NULL); n_tuples = PQntuples(res); if (n_tuples != 0) { /* Competing backend is exsits, but if we do not want to calcel/terminate * any backend, do nothing. */ if (no_kill_backend) { elog(WARNING, "%d unsafe queries remain but do not cancel them and skip to repack it", n_tuples); ret = false; } else { resetStringInfo(&sql); printfStringInfo(&sql, CANCEL_COMPETING_LOCKS, relid); res = pgut_execute(conn, sql.data, 0, NULL); if (PQresultStatus(res) != PGRES_TUPLES_OK) { elog(WARNING, "Error canceling unsafe queries: %s", PQerrorMessage(conn)); ret = false; } else if (PQntuples(res) > 0 && terminate && PQserverVersion(conn) >= 80400) { elog(WARNING, "Canceled %d unsafe queries. Terminating any remaining PIDs.", PQntuples(res)); CLEARPGRES(res); printfStringInfo(&sql, KILL_COMPETING_LOCKS, relid); res = pgut_execute(conn, sql.data, 0, NULL); if (PQresultStatus(res) != PGRES_TUPLES_OK) { elog(WARNING, "Error killing unsafe queries: %s", PQerrorMessage(conn)); ret = false; } } else if (PQntuples(res) > 0) elog(NOTICE, "Canceled %d unsafe queries", PQntuples(res)); } } else elog(DEBUG2, "No competing DDL to cancel."); CLEARPGRES(res); termStringInfo(&sql); return ret; } /* * Try to acquire an ACCESS SHARE table lock, avoiding deadlocks and long * waits by killing off other sessions which may be stuck trying to obtain * an ACCESS EXCLUSIVE lock. * * Arguments: * * conn: connection to use * relid: OID of relation * target_name: name of table */ static bool lock_access_share(PGconn *conn, Oid relid, const char *target_name) { StringInfoData sql; time_t start = time(NULL); int i; bool ret = true; initStringInfo(&sql); for (i = 1; ; i++) { time_t duration; PGresult *res; int wait_msec; duration = time(NULL) - start; /* Cancel queries unconditionally, i.e. don't bother waiting * wait_timeout as lock_exclusive() does -- the only queries we * should be killing are disallowed DDL commands hanging around * for an AccessExclusive lock, which must be deadlocked at * this point anyway since conn2 holds its AccessShare lock * already. */ if (duration > (wait_timeout * 2)) ret = kill_ddl(conn, relid, true); else ret = kill_ddl(conn, relid, false); if (!ret) break; /* wait for a while to lock the table. */ wait_msec = Min(1000, i * 100); printfStringInfo(&sql, "SET LOCAL lock_timeout = %d", wait_msec); pgut_command(conn, sql.data, 0, NULL); printfStringInfo(&sql, "LOCK TABLE %s IN ACCESS SHARE MODE", target_name); res = pgut_execute_elevel(conn, sql.data, 0, NULL, DEBUG2); if (PQresultStatus(res) == PGRES_COMMAND_OK) { CLEARPGRES(res); break; } else if (sqlstate_equals(res, SQLSTATE_LOCK_NOT_AVAILABLE)) { /* retry if lock conflicted */ CLEARPGRES(res); pgut_rollback(conn); continue; } else { /* exit otherwise */ elog(WARNING, "%s", PQerrorMessage(connection)); CLEARPGRES(res); ret = false; break; } } termStringInfo(&sql); pgut_command(conn, "RESET lock_timeout", 0, NULL); return ret; } /* Obtain an advisory lock on the table's OID, to make sure no other * pg_repack is working on the table. This is not so much a concern with * full-table repacks, but mainly so that index-only repacks don't interfere * with each other or a full-table repack. */ static bool advisory_lock(PGconn *conn, const char *relid) { PGresult *res = NULL; bool ret = false; const char *params[2]; params[0] = REPACK_LOCK_PREFIX_STR; params[1] = relid; /* For the 2-argument form of pg_try_advisory_lock, we need to * pass in two signed 4-byte integers. But a table OID is an * *unsigned* 4-byte integer. Add -2147483648 to that OID to make * it fit reliably into signed int space. */ res = pgut_execute(conn, "SELECT pg_try_advisory_lock($1, CAST(-2147483648 + $2::bigint AS integer))", 2, params); if (PQresultStatus(res) != PGRES_TUPLES_OK) { elog(ERROR, "%s", PQerrorMessage(connection)); } else if (strcmp(getstr(res, 0, 0), "t") != 0) { elog(ERROR, "Another pg_repack command may be running on the table. Please try again later."); } else { ret = true; } CLEARPGRES(res); return ret; } /* * Try acquire an ACCESS EXCLUSIVE table lock, avoiding deadlocks and long * waits by killing off other sessions. * Arguments: * * conn: connection to use * relid: OID of relation * lock_query: LOCK TABLE ... IN ACCESS EXCLUSIVE query to be executed * start_xact: whether we will issue a BEGIN ourselves. If not, we will * use a SAVEPOINT and ROLLBACK TO SAVEPOINT if our query * times out, to avoid leaving the transaction in error state. */ static bool lock_exclusive(PGconn *conn, const char *relid, const char *lock_query, bool start_xact) { time_t start = time(NULL); int i; bool ret = true; for (i = 1; ; i++) { time_t duration; char sql[1024]; PGresult *res; int wait_msec; if (start_xact) pgut_command(conn, "BEGIN ISOLATION LEVEL READ COMMITTED", 0, NULL); else pgut_command(conn, "SAVEPOINT repack_sp1", 0, NULL); duration = time(NULL) - start; if (duration > wait_timeout) { if (no_kill_backend) { elog(WARNING, "timed out, do not cancel conflicting backends"); ret = false; /* Before exit the loop reset the transaction */ if (start_xact) pgut_rollback(conn); else pgut_command(conn, "ROLLBACK TO SAVEPOINT repack_sp1", 0, NULL); break; } else { const char *cancel_query; if (PQserverVersion(conn) >= 80400 && duration > wait_timeout * 2) { elog(WARNING, "terminating conflicted backends"); cancel_query = "SELECT pg_terminate_backend(pid) FROM pg_locks" " WHERE locktype = 'relation'" " AND relation = $1 AND pid <> pg_backend_pid()"; } else { elog(WARNING, "canceling conflicted backends"); cancel_query = "SELECT pg_cancel_backend(pid) FROM pg_locks" " WHERE locktype = 'relation'" " AND relation = $1 AND pid <> pg_backend_pid()"; } pgut_command(conn, cancel_query, 1, &relid); } } /* wait for a while to lock the table. */ wait_msec = Min(1000, i * 100); snprintf(sql, lengthof(sql), "SET LOCAL lock_timeout = %d", wait_msec); pgut_command(conn, sql, 0, NULL); res = pgut_execute_elevel(conn, lock_query, 0, NULL, DEBUG2); if (PQresultStatus(res) == PGRES_COMMAND_OK) { CLEARPGRES(res); break; } else if (sqlstate_equals(res, SQLSTATE_LOCK_NOT_AVAILABLE)) { /* retry if lock conflicted */ CLEARPGRES(res); if (start_xact) pgut_rollback(conn); else pgut_command(conn, "ROLLBACK TO SAVEPOINT repack_sp1", 0, NULL); continue; } else { /* exit otherwise */ printf("%s", PQerrorMessage(connection)); CLEARPGRES(res); ret = false; break; } } pgut_command(conn, "RESET lock_timeout", 0, NULL); return ret; } /* This function calls to repack_drop() to clean temporary objects on error * in creation of temporary objects. */ void repack_cleanup_callback(bool fatal, void *userdata) { repack_table *table = (repack_table *) userdata; Oid target_table = table->target_oid; const char *params[2]; char buffer[12]; char num_buff[12]; if(fatal) { params[0] = utoa(target_table, buffer); params[1] = utoa(temp_obj_num, num_buff); /* testing PQstatus() of connection and conn2, as we do * in repack_cleanup(), doesn't seem to work here, * so just use an unconditional reconnect(). */ reconnect(ERROR); command("BEGIN ISOLATION LEVEL READ COMMITTED", 0, NULL); if (!(lock_exclusive(connection, params[0], table->lock_table, false))) { pgut_rollback(connection); elog(ERROR, "lock_exclusive() failed in connection for %s during cleanup callback", table->target_name); } command("SELECT repack.repack_drop($1, $2)", 2, params); command("COMMIT", 0, NULL); temp_obj_num = 0; /* reset temporary object counter after cleanup */ } } /* * The userdata pointing a table being re-organized. We need to cleanup temp * objects before the program exits. */ static void repack_cleanup(bool fatal, const repack_table *table) { if (fatal) { fprintf(stderr, "!!!FATAL ERROR!!! Please refer to the manual.\n\n"); } else { char buffer[12]; char num_buff[12]; const char *params[2]; /* Try reconnection if not available. */ if (PQstatus(connection) != CONNECTION_OK || PQstatus(conn2) != CONNECTION_OK) reconnect(ERROR); /* do cleanup */ params[0] = utoa(table->target_oid, buffer); params[1] = utoa(temp_obj_num, num_buff); command("BEGIN ISOLATION LEVEL READ COMMITTED", 0, NULL); if (!(lock_exclusive(connection, params[0], table->lock_table, false))) { pgut_rollback(connection); elog(ERROR, "lock_exclusive() failed in connection for %s during cleanup", table->target_name); } command("SELECT repack.repack_drop($1, $2)", 2, params); command("COMMIT", 0, NULL); temp_obj_num = 0; /* reset temporary object counter after cleanup */ } } /* * Indexes of a table are repacked. */ static bool repack_table_indexes(PGresult *index_details) { bool ret = false; PGresult *res = NULL, *res2 = NULL; StringInfoData sql, sql_drop; char buffer[2][12]; const char *create_idx, *schema_name, *table_name, *params[3]; Oid table, index; int i, num, num_repacked = 0; bool *repacked_indexes; initStringInfo(&sql); num = PQntuples(index_details); table = getoid(index_details, 0, 3); params[1] = utoa(table, buffer[1]); params[2] = tablespace; schema_name = getstr(index_details, 0, 5); /* table_name is schema-qualified */ table_name = getstr(index_details, 0, 4); /* Keep track of which of the table's indexes we have successfully * repacked, so that we may DROP only those indexes. */ if (!(repacked_indexes = calloc(num, sizeof(bool)))) ereport(ERROR, (errcode(ENOMEM), errmsg("Unable to calloc repacked_indexes"))); /* Check if any concurrent pg_repack command is being run on the same * table. */ if (!advisory_lock(connection, params[1])) ereport(ERROR, (errcode(EINVAL), errmsg("Unable to obtain advisory lock on \"%s\"", table_name))); for (i = 0; i < num; i++) { char *isvalid = getstr(index_details, i, 2); char *idx_name = getstr(index_details, i, 0); if (isvalid[0] == 't') { index = getoid(index_details, i, 1); resetStringInfo(&sql); appendStringInfo(&sql, "SELECT pgc.relname, nsp.nspname " "FROM pg_class pgc INNER JOIN pg_namespace nsp " "ON nsp.oid = pgc.relnamespace " "WHERE pgc.relname = 'index_%u' " "AND nsp.nspname = $1", index); params[0] = schema_name; elog(INFO, "repacking index \"%s\"", idx_name); res = execute(sql.data, 1, params); if (PQresultStatus(res) != PGRES_TUPLES_OK) { elog(WARNING, "%s", PQerrorMessage(connection)); continue; } if (PQntuples(res) > 0) { ereport(WARNING, (errcode(E_PG_COMMAND), errmsg("Cannot create index \"%s\".\"index_%u\", " "already exists", schema_name, index), errdetail("An invalid index may have been left behind" " by a previous pg_repack on the table" " which was interrupted. Please use DROP " "INDEX \"%s\".\"index_%u\"" " to remove this index and try again.", schema_name, index))); continue; } if (dryrun) continue; params[0] = utoa(index, buffer[0]); res = execute("SELECT repack.repack_indexdef($1, $2, $3, true)", 3, params); if (PQntuples(res) < 1) { elog(WARNING, "unable to generate SQL to CREATE work index for %s", getstr(index_details, i, 0)); continue; } create_idx = getstr(res, 0, 0); /* Use a separate PGresult to avoid stomping on create_idx */ res2 = execute_elevel(create_idx, 0, NULL, DEBUG2); if (PQresultStatus(res2) != PGRES_COMMAND_OK) { ereport(WARNING, (errcode(E_PG_COMMAND), errmsg("Error creating index \"%s\".\"index_%u\": %s", schema_name, index, PQerrorMessage(connection) ) )); } else { repacked_indexes[i] = true; num_repacked++; } CLEARPGRES(res); CLEARPGRES(res2); } else elog(WARNING, "skipping invalid index: %s.%s", schema_name, getstr(index_details, i, 0)); } if (dryrun) { ret = true; goto done; } /* If we did not successfully repack any indexes, e.g. because of some * error affecting every CREATE INDEX attempt, don't waste time with * the ACCESS EXCLUSIVE lock on the table, and return false. * N.B. none of the DROP INDEXes should be performed since * repacked_indexes[] flags should all be false. */ if (!num_repacked) { elog(WARNING, "Skipping index swapping for \"%s\", since no new indexes built", table_name); goto drop_idx; } /* take an exclusive lock on table before calling repack_index_swap() */ resetStringInfo(&sql); appendStringInfo(&sql, "LOCK TABLE %s IN ACCESS EXCLUSIVE MODE", table_name); if (!(lock_exclusive(connection, params[1], sql.data, true))) { elog(WARNING, "lock_exclusive() failed in connection for %s", table_name); goto drop_idx; } for (i = 0; i < num; i++) { index = getoid(index_details, i, 1); if (repacked_indexes[i]) { params[0] = utoa(index, buffer[0]); pgut_command(connection, "SELECT repack.repack_index_swap($1)", 1, params); } else elog(INFO, "Skipping index swap for index_%u", index); } pgut_command(connection, "COMMIT", 0, NULL); ret = true; drop_idx: resetStringInfo(&sql); initStringInfo(&sql_drop); appendStringInfoString(&sql, "DROP INDEX CONCURRENTLY "); appendStringInfo(&sql, "\"%s\".", schema_name); for (i = 0; i < num; i++) { index = getoid(index_details, i, 1); if (repacked_indexes[i]) { initStringInfo(&sql_drop); appendStringInfo(&sql_drop, "%s\"index_%u\"", sql.data, index); command(sql_drop.data, 0, NULL); } else elog(INFO, "Skipping drop of index_%u", index); } termStringInfo(&sql_drop); termStringInfo(&sql); done: CLEARPGRES(res); free(repacked_indexes); return ret; } /* * Call repack_table_indexes for each of the tables */ static bool repack_all_indexes(char *errbuf, size_t errsize) { bool ret = false; PGresult *res = NULL; StringInfoData sql; SimpleStringListCell *cell = NULL; const char *params[1]; initStringInfo(&sql); reconnect(ERROR); assert(r_index.head || table_list.head || parent_table_list.head); if (!preliminary_checks(errbuf, errsize)) goto cleanup; if (!is_requested_relation_exists(errbuf, errsize)) goto cleanup; if (r_index.head) { appendStringInfoString(&sql, "SELECT repack.oid2text(i.oid), idx.indexrelid, idx.indisvalid, idx.indrelid, repack.oid2text(idx.indrelid), n.nspname" " FROM pg_index idx JOIN pg_class i ON i.oid = idx.indexrelid" " JOIN pg_namespace n ON n.oid = i.relnamespace" " WHERE idx.indexrelid = $1::regclass ORDER BY indisvalid DESC, i.relname, n.nspname"); cell = r_index.head; } else if (table_list.head || parent_table_list.head) { appendStringInfoString(&sql, "SELECT repack.oid2text(i.oid), idx.indexrelid, idx.indisvalid, idx.indrelid, $1::text, n.nspname" " FROM pg_index idx JOIN pg_class i ON i.oid = idx.indexrelid" " JOIN pg_namespace n ON n.oid = i.relnamespace" " WHERE idx.indrelid = $1::regclass ORDER BY indisvalid DESC, i.relname, n.nspname"); for (cell = parent_table_list.head; cell; cell = cell->next) { int nchildren, i; params[0] = cell->val; /* find children of this parent table */ res = execute_elevel("SELECT quote_ident(n.nspname) || '.' || quote_ident(c.relname)" " FROM pg_class c JOIN pg_namespace n on n.oid = c.relnamespace" " WHERE c.oid = ANY (repack.get_table_and_inheritors($1::regclass))" " ORDER BY n.nspname, c.relname", 1, params, DEBUG2); if (PQresultStatus(res) != PGRES_TUPLES_OK) { elog(WARNING, "%s", PQerrorMessage(connection)); continue; } nchildren = PQntuples(res); if (nchildren == 0) { elog(WARNING, "relation \"%s\" does not exist", cell->val); continue; } /* append new tables to 'table_list' */ for (i = 0; i < nchildren; i++) simple_string_list_append(&table_list, getstr(res, i, 0)); } CLEARPGRES(res); cell = table_list.head; } for (; cell; cell = cell->next) { params[0] = cell->val; res = execute_elevel(sql.data, 1, params, DEBUG2); if (PQresultStatus(res) != PGRES_TUPLES_OK) { elog(WARNING, "%s", PQerrorMessage(connection)); continue; } if (PQntuples(res) == 0) { if(table_list.head) elog(WARNING, "\"%s\" does not have any indexes", cell->val); else if(r_index.head) elog(WARNING, "\"%s\" is not a valid index", cell->val); continue; } if(table_list.head) elog(INFO, "repacking indexes of \"%s\"", cell->val); if (!repack_table_indexes(res)) elog(WARNING, "repack failed for \"%s\"", cell->val); CLEARPGRES(res); } ret = true; cleanup: disconnect(); termStringInfo(&sql); return ret; } void pgut_help(bool details) { printf("%s re-organizes a PostgreSQL database.\n\n", PROGRAM_NAME); printf("Usage:\n"); printf(" %s [OPTION]... [DBNAME]\n", PROGRAM_NAME); if (!details) return; printf("Options:\n"); printf(" -a, --all repack all databases\n"); printf(" -t, --table=TABLE repack specific table only\n"); printf(" -I, --parent-table=TABLE repack specific parent table and its inheritors\n"); printf(" -c, --schema=SCHEMA repack tables in specific schema only\n"); printf(" -s, --tablespace=TBLSPC move repacked tables to a new tablespace\n"); printf(" -S, --moveidx move repacked indexes to TBLSPC too\n"); printf(" -o, --order-by=COLUMNS order by columns instead of cluster keys\n"); printf(" -n, --no-order do vacuum full instead of cluster\n"); printf(" -N, --dry-run print what would have been repacked\n"); printf(" -j, --jobs=NUM Use this many parallel jobs for each table\n"); printf(" -i, --index=INDEX move only the specified index\n"); printf(" -x, --only-indexes move only indexes of the specified table\n"); printf(" -T, --wait-timeout=SECS timeout to cancel other backends on conflict\n"); printf(" -D, --no-kill-backend don't kill other backends when timed out\n"); printf(" -Z, --no-analyze don't analyze at end\n"); printf(" -k, --no-superuser-check skip superuser checks in client\n"); printf(" -C, --exclude-extension don't repack tables which belong to specific extension\n"); printf(" --error-on-invalid-index don't repack tables which belong to specific extension\n"); printf(" --switch-threshold switch tables when that many tuples are left to catchup\n"); }
92a41ca3d21bcd375b75bc00e8a8af18cf56a54a
9ceacf33fd96913cac7ef15492c126d96cae6911
/usr.bin/sdiff/common.c
0b568b9722797a87a1cb928bde3bfe7d33236e5e
[]
no_license
openbsd/src
ab97ef834fd2d5a7f6729814665e9782b586c130
9e79f3a0ebd11a25b4bff61e900cb6de9e7795e9
refs/heads/master
2023-09-02T18:54:56.624627
2023-09-02T15:16:12
2023-09-02T15:16:12
66,966,208
3,394
1,235
null
2023-08-08T02:42:25
2016-08-30T18:18:25
C
UTF-8
C
false
false
325
c
common.c
/* $OpenBSD: common.c,v 1.4 2006/05/25 03:20:32 ray Exp $ */ /* * Written by Raymond Lai <ray@cyth.net>. * Public domain. */ #include <err.h> #include <stdlib.h> #include <unistd.h> #include "common.h" void cleanup(const char *filename) { if (unlink(filename)) err(2, "could not delete: %s", filename); exit(2); }
95e9c4bf0b11407fdd554f737955ea6a26bf5eb6
1efb2283837c9b70bc6449cec877799e4efa3268
/examples/spawn_merge_parent.c
b52487252b8ce02f62a98e1e75427cc73ed7559c
[ "mpich2" ]
permissive
pmodels/mpich
d2392e8e30536cad3e500c16aa1e71211101d83f
2d265f9f5f93ebdd07ad547423bc6212868262a4
refs/heads/main
2023-09-04T05:50:15.041823
2023-09-01T23:07:33
2023-09-01T23:07:33
70,918,679
506
313
NOASSERTION
2023-09-14T14:38:36
2016-10-14T14:39:42
C
UTF-8
C
false
false
1,707
c
spawn_merge_parent.c
/* * Copyright (C) by Argonne National Laboratory * See COPYRIGHT in top-level directory */ #include <stdio.h> #include "mpi.h" int main(int argc, char *argv[]) { char str[10]; int err = 0, errcodes[256], rank, rank1, nprocs; MPI_Comm intercomm1, intercomm2, intracomm; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &nprocs); MPI_Comm_rank(MPI_COMM_WORLD, &rank1); if (nprocs != 2) { printf("Run this program with 2 processes\n"); MPI_Abort(MPI_COMM_WORLD, 1); } if (rank1 == 0) { printf("Parents spawning 2 children...\n"); fflush(stdout); } err = MPI_Comm_spawn("spawn_merge_child1", MPI_ARGV_NULL, 2, MPI_INFO_NULL, 1, MPI_COMM_WORLD, &intercomm1, errcodes); if (err) printf("Error in MPI_Comm_spawn\n"); if (rank1 == 0) { printf("Parents and children merging to form new intracommunicator...\n"); fflush(stdout); } MPI_Intercomm_merge(intercomm1, 0, &intracomm); if (rank1 == 0) { printf("Merged parents spawning 2 more children and communicating with them...\n"); fflush(stdout); } err = MPI_Comm_spawn("spawn_merge_child2", MPI_ARGV_NULL, 2, MPI_INFO_NULL, 2, intracomm, &intercomm2, errcodes); if (err) printf("Error in MPI_Comm_spawn\n"); MPI_Comm_rank(intercomm2, &rank); if (rank == 2) { err = MPI_Recv(str, 3, MPI_CHAR, 1, 0, intercomm2, MPI_STATUS_IGNORE); printf("Parent received from child: %s\n", str); fflush(stdout); err = MPI_Send("bye", 4, MPI_CHAR, 1, 0, intercomm2); } MPI_Finalize(); return 0; }
7e83cbf7e5bfd2c0ab21891e6036a789a03595d8
3225f903ab65e9e242f250a02b3b74fc7e34b098
/firmware/telnet.h
549bb08da383e0acc7e74b6db180934d3bd8b4e0
[ "MIT", "BSD-2-Clause" ]
permissive
timvideos/litex-buildenv
6f7657a0d2836f66bbc8ad29f89f1f975eda7832
fafb0f1c645a0d36ff4947686b4d2d8e3433f686
refs/heads/master
2022-06-04T18:02:22.567089
2022-05-21T15:21:25
2022-05-21T15:21:25
115,785,208
217
88
BSD-2-Clause
2022-05-21T15:21:26
2017-12-30T08:50:22
Python
UTF-8
C
false
false
1,084
h
telnet.h
// This file is Copyright (c) 2015 Florent Kermarrec <florent@enjoy-digital.fr> // License: BSD #ifndef __TELNET_H #define __TELNET_H #include <stdarg.h> #include "contiki.h" #include "contiki-net.h" //#define TELNET_DEBUG #ifdef TELNET_DEBUG #define print_debug(...) printf(__VA_ARGS__) #else #define print_debug(...) {} #endif #define TELNET_PORT 23 #define TELNET_BUFFER_SIZE_RX 4096 #define TELNET_BUFFER_SIZE_TX 4096 int telnet_active; struct tcp_socket telnet_socket; uint8_t telnet_rx_buffer[TELNET_BUFFER_SIZE_RX]; uint8_t telnet_tx_buffer[TELNET_BUFFER_SIZE_TX]; void telnet_init(void); int telnet_event_callback(struct tcp_socket *s, void *ptr, tcp_socket_event_t event); int telnet_data_callback(struct tcp_socket *s, void *ptr, const char *rxbuf, int rxlen); char telnet_readchar(void); int telnet_readchar_nonblock(void); int telnet_putchar(char c); int telnet_puts(const char *s); void telnet_putsnonl(const char *s); int telnet_vprintf(const char *fmt, va_list argp); int telnet_printf(const char *fmt, ...) __attribute__((format(printf, 1, 2))); #endif
5e7a9183fd8c116d00bb0ff20e9b73f4156d8b2f
13e2a9bf3ebb4d2c6cdcc5b3cadaa9d87d94933e
/tools/shared/conversions.h
08ae620949a5f23c8c0be87cca03122cffb30533
[ "MIT" ]
permissive
omf2097/openomf
5421fa6702efa16c33b4154bfacd36a1a9127aae
4287067184d9f16d02035f6cf0abcafb0f9755be
refs/heads/master
2023-08-26T00:39:11.531162
2023-07-27T14:49:11
2023-07-27T14:49:11
7,473,802
299
40
MIT
2023-07-27T14:49:13
2013-01-06T22:58:13
C
UTF-8
C
false
false
355
h
conversions.h
#ifndef CONVERSIONS_H #define CONVERSIONS_H #include <stdint.h> uint8_t conv_ubyte(const char *data); int8_t conv_byte(const char *data); uint16_t conv_uword(const char *data); int16_t conv_word(const char *data); uint32_t conv_udword(const char *data); int32_t conv_dword(const char *data); float conv_float(const char *data); #endif // CONVERSIONS_H
fd731b9ade7f63baab875930f72e2ea046c192ca
10a8580aa44d33b7458429023c00de8c01ceda98
/axiom/nr_segment_terms.h
51c57be5e5176c3866652cbfc64103de6be567b0
[ "BSD-4-Clause-UC", "Apache-2.0" ]
permissive
newrelic/newrelic-php-agent
87ad20e0a5abf0d2855e7d27a25c36454ae4389a
dfb359f0dbb53e4cbc5106b52c8f3807c7fc8d42
refs/heads/main
2023-08-15T10:28:24.372352
2023-08-14T17:29:31
2023-08-14T17:29:31
302,112,572
116
67
Apache-2.0
2023-09-13T18:33:47
2020-10-07T17:35:01
C
UTF-8
C
false
false
2,604
h
nr_segment_terms.h
/* * Copyright 2020 New Relic Corporation. All rights reserved. * SPDX-License-Identifier: Apache-2.0 */ /* * This file contains functions for dealing with transaction segment terms * returned by the collector. */ #ifndef NR_SEGMENT_TERMS_HDR #define NR_SEGMENT_TERMS_HDR #include "util_object.h" /* * Forward declaration of our opaque segment terms "object" type. */ typedef struct _nr_segment_terms_t nr_segment_terms_t; /* * Purpose : Creates a new segment terms object. These contain sets of rules * that should be applied to transaction names. * * Params : 1. The maximum number of rules that the object can contain. * * Returns : A new segment terms object. */ extern nr_segment_terms_t* nr_segment_terms_create(int size); /* * Purpose : Creates a new segment terms object from the JSON returned by the * collector. * * Params : 1. The JSON. * * Returns : A new segment terms object. */ extern nr_segment_terms_t* nr_segment_terms_create_from_obj(const nrobj_t* obj); /* * Purpose : Destroys a segment terms object. * * Params : 1. A pointer to the object, which will be set to NULL once * destroyed. */ extern void nr_segment_terms_destroy(nr_segment_terms_t** terms_ptr); /* * Purpose : Adds a rule to the given segment terms object. * * Params : 1. The segment terms object. * 2. The rule prefix. * 3. An array containing the whitelist of terms to apply. * * Returns : NR_SUCCESS if the rule was valid and added, NR_FAILURE otherwise. */ extern nr_status_t nr_segment_terms_add(nr_segment_terms_t* segment_terms, const char* prefix, const nrobj_t* terms); /* * Purpose : Adds a rule to the segment terms object based on a JSON rule in * the correct format. * * Params : 1. The segment terms object. * 2. A JSON object containing "prefix" and "terms" keys. * * Returns : NR_SUCCESS or NR_FAILURE. */ extern nr_status_t nr_segment_terms_add_from_obj( nr_segment_terms_t* segment_terms, const nrobj_t* rule); /* * Purpose : Applies the transaction segment terms ruleset to the given * transaction name. * * Params : 1. The segment terms object. * 2. The transaction name. * * Returns : A newly allocated string containing the transformed transaction * name, or NULL if the parameters are invalid. */ extern char* nr_segment_terms_apply(const nr_segment_terms_t* segment_terms, const char* name); #endif
b31caff7a833fb9c746ab82deea062afb60ae93b
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
/devel/got/files/patch-libexec_got-index-pack_got-index-pack.c
bc07b3bdb9bc127458f1460de178a2a5cd1b36b9
[ "BSD-2-Clause" ]
permissive
freebsd/freebsd-ports
86f2e89d43913412c4f6b2be3e255bc0945eac12
605a2983f245ac63f5420e023e7dce56898ad801
refs/heads/main
2023-08-30T21:46:28.720924
2023-08-30T19:33:44
2023-08-30T19:33:44
1,803,961
916
918
NOASSERTION
2023-09-08T04:06:26
2011-05-26T11:15:35
null
UTF-8
C
false
false
667
c
patch-libexec_got-index-pack_got-index-pack.c
--- libexec/got-index-pack/got-index-pack.c.orig 2022-10-20 14:40:52 UTC +++ libexec/got-index-pack/got-index-pack.c @@ -15,6 +15,7 @@ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +#include <sys/capsicum.h> #include <sys/types.h> #include <sys/queue.h> #include <sys/mman.h> @@ -110,6 +111,11 @@ main(int argc, char **argv) /* revoke access to most system calls */ if (pledge("stdio recvfd", NULL) == -1) { err = got_error_from_errno("pledge"); + got_privsep_send_error(&ibuf, err); + return 1; + } + if (cap_enter() == -1) { + err = got_error_from_errno("cap_enter"); got_privsep_send_error(&ibuf, err); return 1; }
8773916dc8eb62003f469d39c91989f7446d5701
6ff85b80c6fe1b3ad5416a304b93551a5e80de10
/C/Array/Copy.c
ef55354871e34a776c72edc1c747e8ec35fc0d6a
[ "MIT" ]
permissive
maniero/SOpt
c600cc2333e0a47ce013be3516bbb8080502ff2a
5d17e1a9cbf115eaea6d30af2079d0c92ffff7a3
refs/heads/master
2023-08-10T16:48:46.058739
2023-08-10T13:42:17
2023-08-10T13:42:17
78,631,930
1,002
136
MIT
2023-01-28T12:10:01
2017-01-11T11:19:24
C#
UTF-8
C
false
false
169
c
Copy.c
memcpy(e1, e2, sizeof(events) * 100); copy(begin(e1), end(e1), begin(e2)); for (auto i = 0; i < 100; i++) e2[i] = e1[i]; //https://pt.stackoverflow.com/q/322684/101
6246ae4e5e969373d433052500571975c7a737b3
f8c0a188d1cf8ae5221c4cd11552c221a86e259a
/Firmware/BuildAX/Firmware/BAX1/Shared/Network.h
a3dee424cdb899e1058a14ed51ca8207db052d13
[ "BSD-2-Clause", "CC-BY-3.0" ]
permissive
digitalinteraction/openmovement
6310abf35b379655073485e84719cc2521733c0e
9c2ee2eeb5eae457673e60699b2842c6df82abb1
refs/heads/master
2023-08-03T23:48:42.973605
2023-07-26T17:52:37
2023-07-26T17:52:37
27,082,024
135
86
null
2018-06-21T23:32:43
2014-11-24T15:38:43
C
UTF-8
C
false
false
5,184
h
Network.h
/* * Copyright (c) 2012, Newcastle University, UK. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE 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. */ // Network Code #ifndef NETWORK_H #define NETWORK_H extern char radioPresent; // In local patched version of MRF24J40.c void PrintMenu(void); void ProcessMenu(void); BOOL Reconnect(void); void RadioOn(void); void RadioOff(void); void NetworkDumpMessage(void); extern BYTE myLongAddress[MY_ADDRESS_LENGTH]; #define SLIP_END 0xC0 // End of packet indicator #define SLIP_ESC 0xDB // Escape character, next character will be a substitution #define SLIP_ESC_END 0xDC // Escaped sustitution for the END data byte #define SLIP_ESC_ESC 0xDD // Escaped sustitution for the ESC data byte void usb_putchar(unsigned char c); unsigned char usb_slip_encoded(void *buffer, unsigned char length); #define DATA_TEDDI_REPORT_ID 0x54 // ASCII 'T' #define DATA_TEDDI_PAYLOAD_VERSION 0x04 // 4 #if (DATA_TEDDI_PAYLOAD_VERSION == 0x04) #include "Utils/BitPack.h" #define DATA_MAX_INTERVAL 24 #define DEFAULT_DATA_INTERVAL 24 // (24 = 6 seconds) #define DATA_INTERVAL (settings.dataInterval) #define DATA_OFFSET 18 #define ADDITIONAL_OFFSET(interval) (DATA_OFFSET + BITPACK10_SIZEOF(interval * 2)) #define ADDITIONAL_LENGTH 4 // 'V4' TEDDI Data payload -- all WORD/DWORD stored as little-endian (LSB first) typedef struct { unsigned char reportType; // @ 0 [1] USER_REPORT_TYPE (0x12) unsigned char reportId; // @ 1 [1] Report identifier (0x54, ASCII 'T') unsigned short deviceId; // @ 2 [2] Device identifier (16-bit) unsigned char version; // @ 4 [1] Low nibble = packet version (0x3), high nibble = config (0x0) unsigned char sampleCount; // @ 5 [1] Sample count (default config is a sample unit of 250 msec interval with an equal number of PIR and audio samples; 24 = 6 seconds) unsigned short sequence; // @ 6 [2] Sequence number (16-bit) unsigned short unsent; // @ 8 [2] Number of unsent samples on device (default config is a sample unit of 250 msec) unsigned short temp; // @10 [2] Temperature reading (if top bit set, humidicon sensor, otherwise old sensor) unsigned short light; // @12 [2] Light reading unsigned short battery; // @14 [2] Battery reading unsigned short humidity; // @16 [2] Humidity reading unsigned char data[BITPACK10_SIZEOF(DATA_MAX_INTERVAL * 2)]; // @18 [50] PIR and audio energy (4 Hz, 20x 2x 10-bit samples) unsigned short parentAddress; // @ADDITIONAL_OFFSET+0 [2] (optional) Parent address unsigned short parentAltAddress; // @ADDITIONAL_OFFSET+2 [2] (optional) Parent alt. address } __attribute__ ((packed, aligned(1))) dataPacket_t; // Bit-pack 4x 10-bit samples into 5-byte groups (stored little-endian): // AAAAAAAA BBBBBBAA CCCCBBBB DDCCCCCC DDDDDDDD // 76543210 54321098 32109876 10987654 98765432 #endif #define MAX_PACKETS 12 #define DEFAULT_TRANSMIT_THRESHOLD 1 // Number of packets buffered before start of transmission #define TRANSMIT_THRESHOLD (settings.transmitThreshold) // Number of packets buffered before start of transmission // TODO: Move this -- not in the right palce at all typedef struct { unsigned short temp; unsigned short light; unsigned short battery; unsigned short humidity; unsigned short pir[DATA_MAX_INTERVAL]; unsigned short audio[DATA_MAX_INTERVAL]; } reading_t; extern reading_t reading; void DumpPacket(dataPacket_t *dp); #endif
fd29e41978c145255a44f965876afe0026419910
a8194cf6ffd12f7551eaba53572744080a0bfef3
/test/unit/lib/iscsi/iscsi.c/iscsi_ut.c
282dd121416fe463b28464b2e298b5874b6a6a44
[ "Intel", "BSD-2-Clause", "BSD-3-Clause" ]
permissive
spdk/spdk
51294f67104b8c3d18f19147d63a212e9486c687
d62a3810364cb87be352c66acf7c7f968508ca17
refs/heads/master
2023-08-08T16:07:41.263000
2023-08-02T09:06:56
2023-08-08T07:01:20
39,042,157
2,708
1,158
NOASSERTION
2023-08-11T09:50:50
2015-07-13T23:15:15
C
UTF-8
C
false
false
81,751
c
iscsi_ut.c
/* SPDX-License-Identifier: BSD-3-Clause * Copyright (C) 2016 Intel Corporation. * All rights reserved. */ #include "spdk/stdinc.h" #include "spdk/endian.h" #include "spdk/scsi.h" #include "spdk_internal/cunit.h" #include "CUnit/Basic.h" #include "iscsi/iscsi.c" #include "../common.c" #include "iscsi/portal_grp.h" #include "scsi/scsi_internal.h" #include "common/lib/test_env.c" #include "spdk_internal/mock.h" #define UT_TARGET_NAME1 "iqn.2017-11.spdk.io:t0001" #define UT_TARGET_NAME2 "iqn.2017-11.spdk.io:t0002" #define UT_INITIATOR_NAME1 "iqn.2017-11.spdk.io:i0001" #define UT_INITIATOR_NAME2 "iqn.2017-11.spdk.io:i0002" #define UT_ISCSI_TSIH 256 struct spdk_iscsi_tgt_node g_tgt = { .mutex = PTHREAD_MUTEX_INITIALIZER }; struct spdk_iscsi_tgt_node * iscsi_find_tgt_node(const char *target_name) { if (strcasecmp(target_name, UT_TARGET_NAME1) == 0) { g_tgt.dev = NULL; return (struct spdk_iscsi_tgt_node *)&g_tgt; } else { return NULL; } } bool iscsi_tgt_node_access(struct spdk_iscsi_conn *conn, struct spdk_iscsi_tgt_node *target, const char *iqn, const char *addr) { if (strcasecmp(conn->initiator_name, UT_INITIATOR_NAME1) == 0) { return true; } else { return false; } } DEFINE_STUB(iscsi_tgt_node_is_redirected, bool, (struct spdk_iscsi_conn *conn, struct spdk_iscsi_tgt_node *target, char *buf, int buf_len), false); DEFINE_STUB(iscsi_send_tgts, int, (struct spdk_iscsi_conn *conn, const char *iiqn, const char *tiqn, uint8_t *data, int alloc_len, int data_len), 0); DEFINE_STUB(iscsi_tgt_node_is_destructed, bool, (struct spdk_iscsi_tgt_node *target), false); DEFINE_STUB_V(iscsi_portal_grp_close_all, (void)); DEFINE_STUB_V(iscsi_conn_schedule, (struct spdk_iscsi_conn *conn)); DEFINE_STUB_V(iscsi_conn_free_pdu, (struct spdk_iscsi_conn *conn, struct spdk_iscsi_pdu *pdu)); DEFINE_STUB_V(iscsi_conn_pdu_generic_complete, (void *cb_arg)); DEFINE_STUB(iscsi_conn_handle_queued_datain_tasks, int, (struct spdk_iscsi_conn *conn), 0); DEFINE_STUB(iscsi_conn_abort_queued_datain_task, int, (struct spdk_iscsi_conn *conn, uint32_t ref_task_tag), 0); DEFINE_STUB(iscsi_conn_abort_queued_datain_tasks, int, (struct spdk_iscsi_conn *conn, struct spdk_scsi_lun *lun, struct spdk_iscsi_pdu *pdu), 0); DEFINE_STUB(iscsi_chap_get_authinfo, int, (struct iscsi_chap_auth *auth, const char *authuser, int ag_tag), 0); DEFINE_STUB(spdk_sock_set_recvbuf, int, (struct spdk_sock *sock, int sz), 0); int spdk_scsi_lun_get_id(const struct spdk_scsi_lun *lun) { return lun->id; } DEFINE_STUB(spdk_scsi_lun_is_removing, bool, (const struct spdk_scsi_lun *lun), true); struct spdk_scsi_lun * spdk_scsi_dev_get_lun(struct spdk_scsi_dev *dev, int lun_id) { struct spdk_scsi_lun *lun; TAILQ_FOREACH(lun, &dev->luns, tailq) { if (lun->id == lun_id) { break; } } return lun; } DEFINE_STUB(spdk_scsi_lun_id_int_to_fmt, uint64_t, (int lun_id), 0); DEFINE_STUB(spdk_scsi_lun_id_fmt_to_int, int, (uint64_t lun_fmt), 0); DEFINE_STUB(spdk_scsi_lun_get_dif_ctx, bool, (struct spdk_scsi_lun *lun, struct spdk_scsi_task *task, struct spdk_dif_ctx *dif_ctx), false); static void alloc_mock_mobj(struct spdk_mobj *mobj, int len) { mobj->buf = calloc(1, SPDK_BDEV_BUF_SIZE_WITH_MD(len)); SPDK_CU_ASSERT_FATAL(mobj->buf != NULL); g_iscsi.pdu_immediate_data_pool = (struct spdk_mempool *)100; g_iscsi.pdu_data_out_pool = (struct spdk_mempool *)200; if (len == SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH) { mobj->mp = g_iscsi.pdu_data_out_pool; } else { mobj->mp = g_iscsi.pdu_immediate_data_pool; } } static void op_login_check_target_test(void) { struct spdk_iscsi_conn conn = {}; struct spdk_iscsi_pdu rsp_pdu = {}; struct spdk_iscsi_tgt_node *target; int rc; /* expect success */ snprintf(conn.initiator_name, sizeof(conn.initiator_name), "%s", UT_INITIATOR_NAME1); rc = iscsi_op_login_check_target(&conn, &rsp_pdu, UT_TARGET_NAME1, &target); CU_ASSERT(rc == 0); /* expect failure */ snprintf(conn.initiator_name, sizeof(conn.initiator_name), "%s", UT_INITIATOR_NAME1); rc = iscsi_op_login_check_target(&conn, &rsp_pdu, UT_TARGET_NAME2, &target); CU_ASSERT(rc != 0); /* expect failure */ snprintf(conn.initiator_name, sizeof(conn.initiator_name), "%s", UT_INITIATOR_NAME2); rc = iscsi_op_login_check_target(&conn, &rsp_pdu, UT_TARGET_NAME1, &target); CU_ASSERT(rc != 0); } static void op_login_session_normal_test(void) { struct spdk_iscsi_conn conn = {}; struct spdk_iscsi_portal portal = {}; struct spdk_iscsi_portal_grp group = {}; struct spdk_iscsi_pdu rsp_pdu = {}; struct iscsi_bhs_login_rsp *rsph; struct spdk_iscsi_sess sess = {}; struct iscsi_param param = {}; int rc; /* setup related data structures */ rsph = (struct iscsi_bhs_login_rsp *)&rsp_pdu.bhs; rsph->tsih = 0; memset(rsph->isid, 0, sizeof(rsph->isid)); conn.portal = &portal; portal.group = &group; conn.portal->group->tag = 0; conn.params = NULL; /* expect failure: NULL params for target name */ rc = iscsi_op_login_session_normal(&conn, &rsp_pdu, UT_INITIATOR_NAME1, NULL, 0); CU_ASSERT(rc != 0); CU_ASSERT(rsph->status_class == ISCSI_CLASS_INITIATOR_ERROR); CU_ASSERT(rsph->status_detail == ISCSI_LOGIN_MISSING_PARMS); /* expect failure: incorrect key for target name */ param.next = NULL; rc = iscsi_op_login_session_normal(&conn, &rsp_pdu, UT_INITIATOR_NAME1, &param, 0); CU_ASSERT(rc != 0); CU_ASSERT(rsph->status_class == ISCSI_CLASS_INITIATOR_ERROR); CU_ASSERT(rsph->status_detail == ISCSI_LOGIN_MISSING_PARMS); /* expect failure: NULL target name */ param.key = "TargetName"; param.val = NULL; rc = iscsi_op_login_session_normal(&conn, &rsp_pdu, UT_INITIATOR_NAME1, &param, 0); CU_ASSERT(rc != 0); CU_ASSERT(rsph->status_class == ISCSI_CLASS_INITIATOR_ERROR); CU_ASSERT(rsph->status_detail == ISCSI_LOGIN_MISSING_PARMS); /* expect failure: session not found */ param.key = "TargetName"; param.val = "iqn.2017-11.spdk.io:t0001"; snprintf(conn.initiator_name, sizeof(conn.initiator_name), "%s", UT_INITIATOR_NAME1); rsph->tsih = 1; /* to append the session */ rc = iscsi_op_login_session_normal(&conn, &rsp_pdu, UT_INITIATOR_NAME1, &param, 0); CU_ASSERT(conn.target_port == NULL); CU_ASSERT(rc != 0); CU_ASSERT(rsph->status_class == ISCSI_CLASS_INITIATOR_ERROR); CU_ASSERT(rsph->status_detail == ISCSI_LOGIN_CONN_ADD_FAIL); /* expect failure: session found while tag is wrong */ g_iscsi.MaxSessions = UT_ISCSI_TSIH * 2; g_iscsi.session = calloc(1, sizeof(void *) * g_iscsi.MaxSessions); g_iscsi.session[UT_ISCSI_TSIH - 1] = &sess; sess.tsih = UT_ISCSI_TSIH; rsph->tsih = UT_ISCSI_TSIH >> 8; /* to append the session */ sess.tag = 1; rc = iscsi_op_login_session_normal(&conn, &rsp_pdu, UT_INITIATOR_NAME1, &param, 0); CU_ASSERT(conn.target_port == NULL); CU_ASSERT(rc != 0); CU_ASSERT(rsph->status_class == ISCSI_CLASS_INITIATOR_ERROR); CU_ASSERT(rsph->status_detail == ISCSI_LOGIN_CONN_ADD_FAIL); /* expect success: drop the session */ rsph->tsih = 0; /* to create the session */ g_iscsi.AllowDuplicateIsid = false; rc = iscsi_op_login_session_normal(&conn, &rsp_pdu, UT_INITIATOR_NAME1, &param, 0); CU_ASSERT(rc == 0); /* expect success: create the session */ rsph->tsih = 0; /* to create the session */ g_iscsi.AllowDuplicateIsid = true; rc = iscsi_op_login_session_normal(&conn, &rsp_pdu, UT_INITIATOR_NAME1, &param, 0); CU_ASSERT(rc == 0); free(g_iscsi.session); } static void maxburstlength_test(void) { struct spdk_iscsi_sess sess = {}; struct spdk_iscsi_conn conn = {}; struct spdk_scsi_dev dev = {}; struct spdk_scsi_lun lun = {}; struct spdk_iscsi_pdu *req_pdu, *data_out_pdu, *r2t_pdu; struct iscsi_bhs_scsi_req *req; struct iscsi_bhs_r2t *r2t; struct iscsi_bhs_data_out *data_out; struct spdk_iscsi_pdu *response_pdu; int rc; g_iscsi.MaxR2TPerConnection = DEFAULT_MAXR2T; req_pdu = iscsi_get_pdu(&conn); data_out_pdu = iscsi_get_pdu(&conn); sess.ExpCmdSN = 0; sess.MaxCmdSN = 64; sess.session_type = SESSION_TYPE_NORMAL; sess.MaxBurstLength = 1024; lun.id = 0; TAILQ_INIT(&dev.luns); TAILQ_INSERT_TAIL(&dev.luns, &lun, tailq); conn.full_feature = 1; conn.sess = &sess; conn.dev = &dev; conn.state = ISCSI_CONN_STATE_RUNNING; TAILQ_INIT(&conn.write_pdu_list); TAILQ_INIT(&conn.active_r2t_tasks); req_pdu->bhs.opcode = ISCSI_OP_SCSI; req_pdu->data_segment_len = 0; req = (struct iscsi_bhs_scsi_req *)&req_pdu->bhs; to_be32(&req->cmd_sn, 0); to_be32(&req->expected_data_xfer_len, 1028); to_be32(&req->itt, 0x1234); req->write_bit = 1; req->final_bit = 1; rc = iscsi_pdu_hdr_handle(&conn, req_pdu); if (rc == 0 && !req_pdu->is_rejected) { rc = iscsi_pdu_payload_handle(&conn, req_pdu); } CU_ASSERT(rc == 0); response_pdu = TAILQ_FIRST(&g_write_pdu_list); SPDK_CU_ASSERT_FATAL(response_pdu != NULL); /* * Confirm that a correct R2T reply was sent in response to the * SCSI request. */ TAILQ_REMOVE(&g_write_pdu_list, response_pdu, tailq); CU_ASSERT(response_pdu->bhs.opcode == ISCSI_OP_R2T); r2t = (struct iscsi_bhs_r2t *)&response_pdu->bhs; CU_ASSERT(from_be32(&r2t->desired_xfer_len) == 1024); CU_ASSERT(from_be32(&r2t->buffer_offset) == 0); CU_ASSERT(from_be32(&r2t->itt) == 0x1234); data_out_pdu->bhs.opcode = ISCSI_OP_SCSI_DATAOUT; data_out_pdu->bhs.flags = ISCSI_FLAG_FINAL; data_out_pdu->data_segment_len = 1028; data_out = (struct iscsi_bhs_data_out *)&data_out_pdu->bhs; data_out->itt = r2t->itt; data_out->ttt = r2t->ttt; DSET24(data_out->data_segment_len, 1028); rc = iscsi_pdu_hdr_handle(&conn, data_out_pdu); if (rc == 0 && !data_out_pdu->is_rejected) { rc = iscsi_pdu_payload_handle(&conn, data_out_pdu); } CU_ASSERT(rc == SPDK_ISCSI_CONNECTION_FATAL); SPDK_CU_ASSERT_FATAL(response_pdu->task != NULL); iscsi_task_disassociate_pdu(response_pdu->task); iscsi_task_put(response_pdu->task); iscsi_put_pdu(response_pdu); r2t_pdu = TAILQ_FIRST(&g_write_pdu_list); CU_ASSERT(r2t_pdu != NULL); TAILQ_REMOVE(&g_write_pdu_list, r2t_pdu, tailq); iscsi_put_pdu(r2t_pdu); iscsi_put_pdu(data_out_pdu); iscsi_put_pdu(req_pdu); } static void underflow_for_read_transfer_test(void) { struct spdk_iscsi_sess sess = {}; struct spdk_iscsi_conn conn = {}; struct spdk_iscsi_task task = {}; struct spdk_scsi_dev dev = {}; struct spdk_scsi_lun lun = {}; struct spdk_iscsi_pdu *pdu; struct iscsi_bhs_scsi_req *scsi_req; struct iscsi_bhs_data_in *datah; uint32_t residual_count = 0; sess.MaxBurstLength = SPDK_ISCSI_MAX_BURST_LENGTH; conn.sess = &sess; conn.MaxRecvDataSegmentLength = 8192; TAILQ_INIT(&dev.luns); TAILQ_INSERT_TAIL(&dev.luns, &lun, tailq); conn.dev = &dev; pdu = iscsi_get_pdu(&conn); SPDK_CU_ASSERT_FATAL(pdu != NULL); scsi_req = (struct iscsi_bhs_scsi_req *)&pdu->bhs; scsi_req->read_bit = 1; iscsi_task_set_pdu(&task, pdu); task.parent = NULL; task.scsi.iovs = &task.scsi.iov; task.scsi.iovcnt = 1; task.scsi.length = 512; task.scsi.transfer_len = 512; task.bytes_completed = 512; task.scsi.data_transferred = 256; task.scsi.status = SPDK_SCSI_STATUS_GOOD; iscsi_task_response(&conn, &task); iscsi_put_pdu(pdu); /* * In this case, a SCSI Data-In PDU should contain the Status * for the data transfer. */ to_be32(&residual_count, 256); pdu = TAILQ_FIRST(&g_write_pdu_list); SPDK_CU_ASSERT_FATAL(pdu != NULL); CU_ASSERT(pdu->bhs.opcode == ISCSI_OP_SCSI_DATAIN); datah = (struct iscsi_bhs_data_in *)&pdu->bhs; CU_ASSERT(datah->flags == (ISCSI_DATAIN_UNDERFLOW | ISCSI_FLAG_FINAL | ISCSI_DATAIN_STATUS)); CU_ASSERT(datah->res_cnt == residual_count); TAILQ_REMOVE(&g_write_pdu_list, pdu, tailq); iscsi_put_pdu(pdu); CU_ASSERT(TAILQ_EMPTY(&g_write_pdu_list)); } static void underflow_for_zero_read_transfer_test(void) { struct spdk_iscsi_sess sess = {}; struct spdk_iscsi_conn conn = {}; struct spdk_iscsi_task task = {}; struct spdk_scsi_dev dev = {}; struct spdk_scsi_lun lun = {}; struct spdk_iscsi_pdu *pdu; struct iscsi_bhs_scsi_req *scsi_req; struct iscsi_bhs_scsi_resp *resph; uint32_t residual_count = 0, data_segment_len; sess.MaxBurstLength = SPDK_ISCSI_MAX_BURST_LENGTH; conn.sess = &sess; conn.MaxRecvDataSegmentLength = 8192; TAILQ_INIT(&dev.luns); TAILQ_INSERT_TAIL(&dev.luns, &lun, tailq); conn.dev = &dev; pdu = iscsi_get_pdu(&conn); SPDK_CU_ASSERT_FATAL(pdu != NULL); scsi_req = (struct iscsi_bhs_scsi_req *)&pdu->bhs; scsi_req->read_bit = 1; iscsi_task_set_pdu(&task, pdu); task.parent = NULL; task.scsi.length = 512; task.scsi.transfer_len = 512; task.bytes_completed = 512; task.scsi.data_transferred = 0; task.scsi.status = SPDK_SCSI_STATUS_GOOD; iscsi_task_response(&conn, &task); iscsi_put_pdu(pdu); /* * In this case, only a SCSI Response PDU is expected and * underflow must be set in it. * */ to_be32(&residual_count, 512); pdu = TAILQ_FIRST(&g_write_pdu_list); SPDK_CU_ASSERT_FATAL(pdu != NULL); CU_ASSERT(pdu->bhs.opcode == ISCSI_OP_SCSI_RSP); resph = (struct iscsi_bhs_scsi_resp *)&pdu->bhs; CU_ASSERT(resph->flags == (ISCSI_SCSI_UNDERFLOW | 0x80)); data_segment_len = DGET24(resph->data_segment_len); CU_ASSERT(data_segment_len == 0); CU_ASSERT(resph->res_cnt == residual_count); TAILQ_REMOVE(&g_write_pdu_list, pdu, tailq); iscsi_put_pdu(pdu); CU_ASSERT(TAILQ_EMPTY(&g_write_pdu_list)); } static void underflow_for_request_sense_test(void) { struct spdk_iscsi_sess sess = {}; struct spdk_iscsi_conn conn = {}; struct spdk_iscsi_task task = {}; struct spdk_scsi_dev dev = {}; struct spdk_scsi_lun lun = {}; struct spdk_iscsi_pdu *pdu1, *pdu2; struct iscsi_bhs_scsi_req *scsi_req; struct iscsi_bhs_data_in *datah; struct iscsi_bhs_scsi_resp *resph; uint32_t residual_count = 0, data_segment_len; sess.MaxBurstLength = SPDK_ISCSI_MAX_BURST_LENGTH; conn.sess = &sess; conn.MaxRecvDataSegmentLength = 8192; TAILQ_INIT(&dev.luns); TAILQ_INSERT_TAIL(&dev.luns, &lun, tailq); conn.dev = &dev; pdu1 = iscsi_get_pdu(&conn); SPDK_CU_ASSERT_FATAL(pdu1 != NULL); scsi_req = (struct iscsi_bhs_scsi_req *)&pdu1->bhs; scsi_req->read_bit = 1; iscsi_task_set_pdu(&task, pdu1); task.parent = NULL; task.scsi.iovs = &task.scsi.iov; task.scsi.iovcnt = 1; task.scsi.length = 512; task.scsi.transfer_len = 512; task.bytes_completed = 512; task.scsi.sense_data_len = 18; task.scsi.data_transferred = 18; task.scsi.status = SPDK_SCSI_STATUS_GOOD; iscsi_task_response(&conn, &task); iscsi_put_pdu(pdu1); /* * In this case, a SCSI Data-In PDU and a SCSI Response PDU are returned. * Sense data are set both in payload and sense area. * The SCSI Data-In PDU sets FINAL and the SCSI Response PDU sets UNDERFLOW. * * Probably there will be different implementation but keeping current SPDK * implementation by adding UT will be valuable for any implementation. */ to_be32(&residual_count, 494); pdu1 = TAILQ_FIRST(&g_write_pdu_list); SPDK_CU_ASSERT_FATAL(pdu1 != NULL); CU_ASSERT(pdu1->bhs.opcode == ISCSI_OP_SCSI_DATAIN); datah = (struct iscsi_bhs_data_in *)&pdu1->bhs; CU_ASSERT(datah->flags == ISCSI_FLAG_FINAL); data_segment_len = DGET24(datah->data_segment_len); CU_ASSERT(data_segment_len == 18); CU_ASSERT(datah->res_cnt == 0); TAILQ_REMOVE(&g_write_pdu_list, pdu1, tailq); iscsi_put_pdu(pdu1); pdu2 = TAILQ_FIRST(&g_write_pdu_list); /* inform scan-build (clang 6) that these pointers are not the same */ SPDK_CU_ASSERT_FATAL(pdu1 != pdu2); SPDK_CU_ASSERT_FATAL(pdu2 != NULL); CU_ASSERT(pdu2->bhs.opcode == ISCSI_OP_SCSI_RSP); resph = (struct iscsi_bhs_scsi_resp *)&pdu2->bhs; CU_ASSERT(resph->flags == (ISCSI_SCSI_UNDERFLOW | 0x80)); data_segment_len = DGET24(resph->data_segment_len); CU_ASSERT(data_segment_len == task.scsi.sense_data_len + 2); CU_ASSERT(resph->res_cnt == residual_count); TAILQ_REMOVE(&g_write_pdu_list, pdu2, tailq); iscsi_put_pdu(pdu2); CU_ASSERT(TAILQ_EMPTY(&g_write_pdu_list)); } static void underflow_for_check_condition_test(void) { struct spdk_iscsi_sess sess = {}; struct spdk_iscsi_conn conn = {}; struct spdk_iscsi_task task = {}; struct spdk_scsi_dev dev = {}; struct spdk_scsi_lun lun = {}; struct spdk_iscsi_pdu *pdu; struct iscsi_bhs_scsi_req *scsi_req; struct iscsi_bhs_scsi_resp *resph; uint32_t data_segment_len; sess.MaxBurstLength = SPDK_ISCSI_MAX_BURST_LENGTH; conn.sess = &sess; conn.MaxRecvDataSegmentLength = 8192; TAILQ_INIT(&dev.luns); TAILQ_INSERT_TAIL(&dev.luns, &lun, tailq); conn.dev = &dev; pdu = iscsi_get_pdu(&conn); SPDK_CU_ASSERT_FATAL(pdu != NULL); scsi_req = (struct iscsi_bhs_scsi_req *)&pdu->bhs; scsi_req->read_bit = 1; iscsi_task_set_pdu(&task, pdu); task.parent = NULL; task.scsi.iovs = &task.scsi.iov; task.scsi.iovcnt = 1; task.scsi.length = 512; task.scsi.transfer_len = 512; task.bytes_completed = 512; task.scsi.sense_data_len = 18; task.scsi.data_transferred = 18; task.scsi.status = SPDK_SCSI_STATUS_CHECK_CONDITION; iscsi_task_response(&conn, &task); iscsi_put_pdu(pdu); /* * In this case, a SCSI Response PDU is returned. * Sense data is set in sense area. * Underflow is not set. */ pdu = TAILQ_FIRST(&g_write_pdu_list); SPDK_CU_ASSERT_FATAL(pdu != NULL); CU_ASSERT(pdu->bhs.opcode == ISCSI_OP_SCSI_RSP); resph = (struct iscsi_bhs_scsi_resp *)&pdu->bhs; CU_ASSERT(resph->flags == 0x80); data_segment_len = DGET24(resph->data_segment_len); CU_ASSERT(data_segment_len == task.scsi.sense_data_len + 2); CU_ASSERT(resph->res_cnt == 0); TAILQ_REMOVE(&g_write_pdu_list, pdu, tailq); iscsi_put_pdu(pdu); CU_ASSERT(TAILQ_EMPTY(&g_write_pdu_list)); } static void add_transfer_task_test(void) { struct spdk_iscsi_sess sess = {}; struct spdk_iscsi_conn conn = {}; struct spdk_iscsi_task task = {}; struct spdk_iscsi_pdu *pdu, *tmp; struct iscsi_bhs_r2t *r2th; int rc, count = 0; uint32_t buffer_offset, desired_xfer_len; g_iscsi.MaxR2TPerConnection = DEFAULT_MAXR2T; sess.MaxBurstLength = SPDK_ISCSI_MAX_BURST_LENGTH; /* 1M */ sess.MaxOutstandingR2T = DEFAULT_MAXR2T; /* 4 */ conn.sess = &sess; TAILQ_INIT(&conn.queued_r2t_tasks); TAILQ_INIT(&conn.active_r2t_tasks); pdu = iscsi_get_pdu(&conn); SPDK_CU_ASSERT_FATAL(pdu != NULL); pdu->data_segment_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; /* 64K */ task.scsi.transfer_len = 16 * 1024 * 1024; iscsi_task_set_pdu(&task, pdu); /* The following tests if the task is queued because R2T tasks are full. */ conn.pending_r2t = DEFAULT_MAXR2T; rc = add_transfer_task(&conn, &task); CU_ASSERT(rc == 0); CU_ASSERT(TAILQ_FIRST(&conn.queued_r2t_tasks) == &task); TAILQ_REMOVE(&conn.queued_r2t_tasks, &task, link); CU_ASSERT(TAILQ_EMPTY(&conn.queued_r2t_tasks)); /* The following tests if multiple R2Ts are issued. */ conn.pending_r2t = 0; rc = add_transfer_task(&conn, &task); CU_ASSERT(rc == 0); CU_ASSERT(TAILQ_FIRST(&conn.active_r2t_tasks) == &task); TAILQ_REMOVE(&conn.active_r2t_tasks, &task, link); CU_ASSERT(TAILQ_EMPTY(&conn.active_r2t_tasks)); CU_ASSERT(conn.data_out_cnt == 255); CU_ASSERT(conn.pending_r2t == 1); CU_ASSERT(conn.ttt == 1); CU_ASSERT(task.data_out_cnt == 255); CU_ASSERT(task.ttt == 1); CU_ASSERT(task.outstanding_r2t == sess.MaxOutstandingR2T); CU_ASSERT(task.next_r2t_offset == pdu->data_segment_len + sess.MaxBurstLength * sess.MaxOutstandingR2T); while (!TAILQ_EMPTY(&g_write_pdu_list)) { tmp = TAILQ_FIRST(&g_write_pdu_list); TAILQ_REMOVE(&g_write_pdu_list, tmp, tailq); r2th = (struct iscsi_bhs_r2t *)&tmp->bhs; buffer_offset = from_be32(&r2th->buffer_offset); CU_ASSERT(buffer_offset == pdu->data_segment_len + sess.MaxBurstLength * count); desired_xfer_len = from_be32(&r2th->desired_xfer_len); CU_ASSERT(desired_xfer_len == sess.MaxBurstLength); iscsi_put_pdu(tmp); count++; } CU_ASSERT(count == DEFAULT_MAXR2T); iscsi_put_pdu(pdu); } static void get_transfer_task_test(void) { struct spdk_iscsi_sess sess = {}; struct spdk_iscsi_conn conn = {}; struct spdk_iscsi_task task1 = {}, task2 = {}, *task; struct spdk_iscsi_pdu *pdu1, *pdu2, *pdu; int rc; sess.MaxBurstLength = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; sess.MaxOutstandingR2T = 1; conn.sess = &sess; TAILQ_INIT(&conn.active_r2t_tasks); pdu1 = iscsi_get_pdu(&conn); SPDK_CU_ASSERT_FATAL(pdu1 != NULL); pdu1->data_segment_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; task1.scsi.transfer_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; iscsi_task_set_pdu(&task1, pdu1); rc = add_transfer_task(&conn, &task1); CU_ASSERT(rc == 0); pdu2 = iscsi_get_pdu(&conn); SPDK_CU_ASSERT_FATAL(pdu2 != NULL); pdu2->data_segment_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; task2.scsi.transfer_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; iscsi_task_set_pdu(&task2, pdu2); rc = add_transfer_task(&conn, &task2); CU_ASSERT(rc == 0); task = get_transfer_task(&conn, 1); CU_ASSERT(task == &task1); task = get_transfer_task(&conn, 2); CU_ASSERT(task == &task2); while (!TAILQ_EMPTY(&conn.active_r2t_tasks)) { task = TAILQ_FIRST(&conn.active_r2t_tasks); TAILQ_REMOVE(&conn.active_r2t_tasks, task, link); } while (!TAILQ_EMPTY(&g_write_pdu_list)) { pdu = TAILQ_FIRST(&g_write_pdu_list); TAILQ_REMOVE(&g_write_pdu_list, pdu, tailq); iscsi_put_pdu(pdu); } iscsi_put_pdu(pdu2); iscsi_put_pdu(pdu1); } static void del_transfer_task_test(void) { struct spdk_iscsi_sess sess = {}; struct spdk_iscsi_conn conn = {}; struct spdk_iscsi_task *task1, *task2, *task3, *task4, *task5; struct spdk_iscsi_pdu *pdu1, *pdu2, *pdu3, *pdu4, *pdu5, *pdu; int rc; sess.MaxBurstLength = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; sess.MaxOutstandingR2T = 1; conn.sess = &sess; TAILQ_INIT(&conn.active_r2t_tasks); TAILQ_INIT(&conn.queued_r2t_tasks); pdu1 = iscsi_get_pdu(&conn); SPDK_CU_ASSERT_FATAL(pdu1 != NULL); pdu1->data_segment_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; task1 = iscsi_task_get(&conn, NULL, NULL); SPDK_CU_ASSERT_FATAL(task1 != NULL); task1->scsi.transfer_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; iscsi_task_set_pdu(task1, pdu1); task1->tag = 11; rc = add_transfer_task(&conn, task1); CU_ASSERT(rc == 0); pdu2 = iscsi_get_pdu(&conn); SPDK_CU_ASSERT_FATAL(pdu2 != NULL); pdu2->data_segment_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; task2 = iscsi_task_get(&conn, NULL, NULL); SPDK_CU_ASSERT_FATAL(task2 != NULL); task2->scsi.transfer_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; iscsi_task_set_pdu(task2, pdu2); task2->tag = 12; rc = add_transfer_task(&conn, task2); CU_ASSERT(rc == 0); pdu3 = iscsi_get_pdu(&conn); SPDK_CU_ASSERT_FATAL(pdu3 != NULL); pdu3->data_segment_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; task3 = iscsi_task_get(&conn, NULL, NULL); SPDK_CU_ASSERT_FATAL(task3 != NULL); task3->scsi.transfer_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; iscsi_task_set_pdu(task3, pdu3); task3->tag = 13; rc = add_transfer_task(&conn, task3); CU_ASSERT(rc == 0); pdu4 = iscsi_get_pdu(&conn); SPDK_CU_ASSERT_FATAL(pdu4 != NULL); pdu4->data_segment_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; task4 = iscsi_task_get(&conn, NULL, NULL); SPDK_CU_ASSERT_FATAL(task4 != NULL); task4->scsi.transfer_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; iscsi_task_set_pdu(task4, pdu4); task4->tag = 14; rc = add_transfer_task(&conn, task4); CU_ASSERT(rc == 0); pdu5 = iscsi_get_pdu(&conn); SPDK_CU_ASSERT_FATAL(pdu5 != NULL); pdu5->data_segment_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; task5 = iscsi_task_get(&conn, NULL, NULL); SPDK_CU_ASSERT_FATAL(task5 != NULL); task5->scsi.transfer_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; iscsi_task_set_pdu(task5, pdu5); task5->tag = 15; rc = add_transfer_task(&conn, task5); CU_ASSERT(rc == 0); CU_ASSERT(get_transfer_task(&conn, 1) == task1); CU_ASSERT(get_transfer_task(&conn, 5) == NULL); iscsi_del_transfer_task(&conn, 11); CU_ASSERT(get_transfer_task(&conn, 1) == NULL); CU_ASSERT(get_transfer_task(&conn, 5) == task5); CU_ASSERT(get_transfer_task(&conn, 2) == task2); iscsi_del_transfer_task(&conn, 12); CU_ASSERT(get_transfer_task(&conn, 2) == NULL); CU_ASSERT(get_transfer_task(&conn, 3) == task3); iscsi_del_transfer_task(&conn, 13); CU_ASSERT(get_transfer_task(&conn, 3) == NULL); CU_ASSERT(get_transfer_task(&conn, 4) == task4); iscsi_del_transfer_task(&conn, 14); CU_ASSERT(get_transfer_task(&conn, 4) == NULL); CU_ASSERT(get_transfer_task(&conn, 5) == task5); iscsi_del_transfer_task(&conn, 15); CU_ASSERT(get_transfer_task(&conn, 5) == NULL); CU_ASSERT(TAILQ_EMPTY(&conn.active_r2t_tasks)); while (!TAILQ_EMPTY(&g_write_pdu_list)) { pdu = TAILQ_FIRST(&g_write_pdu_list); TAILQ_REMOVE(&g_write_pdu_list, pdu, tailq); iscsi_put_pdu(pdu); } iscsi_put_pdu(pdu5); iscsi_put_pdu(pdu4); iscsi_put_pdu(pdu3); iscsi_put_pdu(pdu2); iscsi_put_pdu(pdu1); } static void clear_all_transfer_tasks_test(void) { struct spdk_iscsi_sess sess = {}; struct spdk_iscsi_conn conn = {}; struct spdk_iscsi_task *task1, *task2, *task3, *task4, *task5, *task6; struct spdk_iscsi_pdu *pdu1, *pdu2, *pdu3, *pdu4, *pdu5, *pdu6, *pdu; struct spdk_iscsi_pdu *mgmt_pdu1, *mgmt_pdu2; struct spdk_scsi_lun lun1 = {}, lun2 = {}; uint32_t alloc_cmd_sn; int rc; sess.MaxBurstLength = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; sess.MaxOutstandingR2T = 1; conn.sess = &sess; TAILQ_INIT(&conn.active_r2t_tasks); TAILQ_INIT(&conn.queued_r2t_tasks); alloc_cmd_sn = 10; task1 = iscsi_task_get(&conn, NULL, NULL); SPDK_CU_ASSERT_FATAL(task1 != NULL); pdu1 = iscsi_get_pdu(&conn); SPDK_CU_ASSERT_FATAL(pdu1 != NULL); pdu1->data_segment_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; pdu1->cmd_sn = alloc_cmd_sn; alloc_cmd_sn++; task1->scsi.transfer_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; task1->scsi.lun = &lun1; iscsi_task_set_pdu(task1, pdu1); rc = add_transfer_task(&conn, task1); CU_ASSERT(rc == 0); mgmt_pdu1 = iscsi_get_pdu(&conn); SPDK_CU_ASSERT_FATAL(mgmt_pdu1 != NULL); mgmt_pdu1->cmd_sn = alloc_cmd_sn; alloc_cmd_sn++; task2 = iscsi_task_get(&conn, NULL, NULL); SPDK_CU_ASSERT_FATAL(task2 != NULL); pdu2 = iscsi_get_pdu(&conn); SPDK_CU_ASSERT_FATAL(pdu2 != NULL); pdu2->data_segment_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; pdu2->cmd_sn = alloc_cmd_sn; alloc_cmd_sn++; task2->scsi.transfer_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; task2->scsi.lun = &lun1; iscsi_task_set_pdu(task2, pdu2); rc = add_transfer_task(&conn, task2); CU_ASSERT(rc == 0); task3 = iscsi_task_get(&conn, NULL, NULL); SPDK_CU_ASSERT_FATAL(task3 != NULL); pdu3 = iscsi_get_pdu(&conn); SPDK_CU_ASSERT_FATAL(pdu3 != NULL); pdu3->data_segment_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; pdu3->cmd_sn = alloc_cmd_sn; alloc_cmd_sn++; task3->scsi.transfer_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; task3->scsi.lun = &lun1; iscsi_task_set_pdu(task3, pdu3); rc = add_transfer_task(&conn, task3); CU_ASSERT(rc == 0); task4 = iscsi_task_get(&conn, NULL, NULL); SPDK_CU_ASSERT_FATAL(task4 != NULL); pdu4 = iscsi_get_pdu(&conn); SPDK_CU_ASSERT_FATAL(pdu4 != NULL); pdu4->data_segment_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; pdu4->cmd_sn = alloc_cmd_sn; alloc_cmd_sn++; task4->scsi.transfer_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; task4->scsi.lun = &lun2; iscsi_task_set_pdu(task4, pdu4); rc = add_transfer_task(&conn, task4); CU_ASSERT(rc == 0); task5 = iscsi_task_get(&conn, NULL, NULL); SPDK_CU_ASSERT_FATAL(task5 != NULL); pdu5 = iscsi_get_pdu(&conn); SPDK_CU_ASSERT_FATAL(pdu5 != NULL); pdu5->data_segment_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; pdu5->cmd_sn = alloc_cmd_sn; alloc_cmd_sn++; task5->scsi.transfer_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; task5->scsi.lun = &lun2; iscsi_task_set_pdu(task5, pdu5); rc = add_transfer_task(&conn, task5); CU_ASSERT(rc == 0); mgmt_pdu2 = iscsi_get_pdu(&conn); SPDK_CU_ASSERT_FATAL(mgmt_pdu2 != NULL); mgmt_pdu2->cmd_sn = alloc_cmd_sn; alloc_cmd_sn++; task6 = iscsi_task_get(&conn, NULL, NULL); SPDK_CU_ASSERT_FATAL(task6 != NULL); pdu6 = iscsi_get_pdu(&conn); SPDK_CU_ASSERT_FATAL(pdu6 != NULL); pdu6->data_segment_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; pdu6->cmd_sn = alloc_cmd_sn; alloc_cmd_sn++; task5->scsi.transfer_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; task6->scsi.lun = &lun2; iscsi_task_set_pdu(task6, pdu6); rc = add_transfer_task(&conn, task6); CU_ASSERT(rc == 0); CU_ASSERT(conn.ttt == 4); CU_ASSERT(get_transfer_task(&conn, 1) == task1); CU_ASSERT(get_transfer_task(&conn, 2) == task2); CU_ASSERT(get_transfer_task(&conn, 3) == task3); CU_ASSERT(get_transfer_task(&conn, 4) == task4); CU_ASSERT(get_transfer_task(&conn, 5) == NULL); iscsi_clear_all_transfer_task(&conn, &lun1, mgmt_pdu1); CU_ASSERT(!TAILQ_EMPTY(&conn.queued_r2t_tasks)); CU_ASSERT(get_transfer_task(&conn, 1) == NULL); CU_ASSERT(get_transfer_task(&conn, 2) == task2); CU_ASSERT(get_transfer_task(&conn, 3) == task3); CU_ASSERT(get_transfer_task(&conn, 4) == task4); CU_ASSERT(get_transfer_task(&conn, 5) == task5); CU_ASSERT(get_transfer_task(&conn, 6) == NULL); iscsi_clear_all_transfer_task(&conn, &lun1, NULL); CU_ASSERT(TAILQ_EMPTY(&conn.queued_r2t_tasks)); CU_ASSERT(get_transfer_task(&conn, 1) == NULL); CU_ASSERT(get_transfer_task(&conn, 2) == NULL); CU_ASSERT(get_transfer_task(&conn, 3) == NULL); CU_ASSERT(get_transfer_task(&conn, 4) == task4); CU_ASSERT(get_transfer_task(&conn, 5) == task5); CU_ASSERT(get_transfer_task(&conn, 6) == task6); iscsi_clear_all_transfer_task(&conn, &lun2, mgmt_pdu2); CU_ASSERT(get_transfer_task(&conn, 4) == NULL); CU_ASSERT(get_transfer_task(&conn, 5) == NULL); CU_ASSERT(get_transfer_task(&conn, 6) == task6); iscsi_clear_all_transfer_task(&conn, NULL, NULL); CU_ASSERT(get_transfer_task(&conn, 6) == NULL); CU_ASSERT(TAILQ_EMPTY(&conn.active_r2t_tasks)); while (!TAILQ_EMPTY(&g_write_pdu_list)) { pdu = TAILQ_FIRST(&g_write_pdu_list); TAILQ_REMOVE(&g_write_pdu_list, pdu, tailq); iscsi_put_pdu(pdu); } iscsi_put_pdu(mgmt_pdu2); iscsi_put_pdu(mgmt_pdu1); iscsi_put_pdu(pdu6); iscsi_put_pdu(pdu5); iscsi_put_pdu(pdu4); iscsi_put_pdu(pdu3); iscsi_put_pdu(pdu2); iscsi_put_pdu(pdu1); } static void build_iovs_test(void) { struct spdk_iscsi_conn conn = {}; struct spdk_iscsi_pdu pdu = {}; struct iovec iovs[5] = {}; uint8_t *data; uint32_t mapped_length = 0; int rc; conn.header_digest = true; conn.data_digest = true; DSET24(&pdu.bhs.data_segment_len, 512); data = calloc(1, 512); SPDK_CU_ASSERT_FATAL(data != NULL); pdu.data = data; pdu.bhs.total_ahs_len = 0; pdu.bhs.opcode = ISCSI_OP_SCSI; pdu.writev_offset = 0; rc = iscsi_build_iovs(&conn, iovs, 5, &pdu, &mapped_length); CU_ASSERT(rc == 4); CU_ASSERT(iovs[0].iov_base == (void *)&pdu.bhs); CU_ASSERT(iovs[0].iov_len == ISCSI_BHS_LEN); CU_ASSERT(iovs[1].iov_base == (void *)pdu.header_digest); CU_ASSERT(iovs[1].iov_len == ISCSI_DIGEST_LEN); CU_ASSERT(iovs[2].iov_base == (void *)pdu.data); CU_ASSERT(iovs[2].iov_len == 512); CU_ASSERT(iovs[3].iov_base == (void *)pdu.data_digest); CU_ASSERT(iovs[3].iov_len == ISCSI_DIGEST_LEN); CU_ASSERT(mapped_length == ISCSI_BHS_LEN + ISCSI_DIGEST_LEN + 512 + ISCSI_DIGEST_LEN); pdu.writev_offset = ISCSI_BHS_LEN / 2; rc = iscsi_build_iovs(&conn, iovs, 5, &pdu, &mapped_length); CU_ASSERT(rc == 4); CU_ASSERT(iovs[0].iov_base == (void *)((uint8_t *)&pdu.bhs + ISCSI_BHS_LEN / 2)); CU_ASSERT(iovs[0].iov_len == ISCSI_BHS_LEN / 2); CU_ASSERT(iovs[1].iov_base == (void *)pdu.header_digest); CU_ASSERT(iovs[1].iov_len == ISCSI_DIGEST_LEN); CU_ASSERT(iovs[2].iov_base == (void *)pdu.data); CU_ASSERT(iovs[2].iov_len == 512); CU_ASSERT(iovs[3].iov_base == (void *)pdu.data_digest); CU_ASSERT(iovs[3].iov_len == ISCSI_DIGEST_LEN); CU_ASSERT(mapped_length == ISCSI_BHS_LEN / 2 + ISCSI_DIGEST_LEN + 512 + ISCSI_DIGEST_LEN); pdu.writev_offset = ISCSI_BHS_LEN; rc = iscsi_build_iovs(&conn, iovs, 5, &pdu, &mapped_length); CU_ASSERT(rc == 3); CU_ASSERT(iovs[0].iov_base == (void *)pdu.header_digest); CU_ASSERT(iovs[0].iov_len == ISCSI_DIGEST_LEN); CU_ASSERT(iovs[1].iov_base == (void *)pdu.data); CU_ASSERT(iovs[1].iov_len == 512); CU_ASSERT(iovs[2].iov_base == (void *)pdu.data_digest); CU_ASSERT(iovs[2].iov_len == ISCSI_DIGEST_LEN); CU_ASSERT(mapped_length == ISCSI_DIGEST_LEN + 512 + ISCSI_DIGEST_LEN); pdu.writev_offset = ISCSI_BHS_LEN + ISCSI_DIGEST_LEN / 2; rc = iscsi_build_iovs(&conn, iovs, 5, &pdu, &mapped_length); CU_ASSERT(rc == 3); CU_ASSERT(iovs[0].iov_base == (void *)((uint8_t *)pdu.header_digest + ISCSI_DIGEST_LEN / 2)); CU_ASSERT(iovs[0].iov_len == ISCSI_DIGEST_LEN / 2); CU_ASSERT(iovs[1].iov_base == (void *)pdu.data); CU_ASSERT(iovs[1].iov_len == 512); CU_ASSERT(iovs[2].iov_base == (void *)pdu.data_digest); CU_ASSERT(iovs[2].iov_len == ISCSI_DIGEST_LEN); CU_ASSERT(mapped_length == ISCSI_DIGEST_LEN / 2 + 512 + ISCSI_DIGEST_LEN); pdu.writev_offset = ISCSI_BHS_LEN + ISCSI_DIGEST_LEN; rc = iscsi_build_iovs(&conn, iovs, 5, &pdu, &mapped_length); CU_ASSERT(rc == 2); CU_ASSERT(iovs[0].iov_base == (void *)pdu.data); CU_ASSERT(iovs[0].iov_len == 512); CU_ASSERT(iovs[1].iov_base == (void *)pdu.data_digest); CU_ASSERT(iovs[1].iov_len == ISCSI_DIGEST_LEN); CU_ASSERT(mapped_length == 512 + ISCSI_DIGEST_LEN); pdu.writev_offset = ISCSI_BHS_LEN + ISCSI_DIGEST_LEN + 512; rc = iscsi_build_iovs(&conn, iovs, 5, &pdu, &mapped_length); CU_ASSERT(rc == 1); CU_ASSERT(iovs[0].iov_base == (void *)pdu.data_digest); CU_ASSERT(iovs[0].iov_len == ISCSI_DIGEST_LEN); CU_ASSERT(mapped_length == ISCSI_DIGEST_LEN); pdu.writev_offset = ISCSI_BHS_LEN + ISCSI_DIGEST_LEN + 512 + ISCSI_DIGEST_LEN / 2; rc = iscsi_build_iovs(&conn, iovs, 5, &pdu, &mapped_length); CU_ASSERT(rc == 1); CU_ASSERT(iovs[0].iov_base == (void *)((uint8_t *)pdu.data_digest + ISCSI_DIGEST_LEN / 2)); CU_ASSERT(iovs[0].iov_len == ISCSI_DIGEST_LEN / 2); CU_ASSERT(mapped_length == ISCSI_DIGEST_LEN / 2); pdu.writev_offset = ISCSI_BHS_LEN + ISCSI_DIGEST_LEN + 512 + ISCSI_DIGEST_LEN; rc = iscsi_build_iovs(&conn, iovs, 5, &pdu, &mapped_length); CU_ASSERT(rc == 0); CU_ASSERT(mapped_length == 0); pdu.writev_offset = 0; rc = iscsi_build_iovs(&conn, iovs, 1, &pdu, &mapped_length); CU_ASSERT(rc == 1); CU_ASSERT(iovs[0].iov_base == (void *)&pdu.bhs); CU_ASSERT(iovs[0].iov_len == ISCSI_BHS_LEN); CU_ASSERT(mapped_length == ISCSI_BHS_LEN); rc = iscsi_build_iovs(&conn, iovs, 2, &pdu, &mapped_length); CU_ASSERT(rc == 2); CU_ASSERT(iovs[0].iov_base == (void *)&pdu.bhs); CU_ASSERT(iovs[0].iov_len == ISCSI_BHS_LEN); CU_ASSERT(iovs[1].iov_base == (void *)pdu.header_digest); CU_ASSERT(iovs[1].iov_len == ISCSI_DIGEST_LEN); CU_ASSERT(mapped_length == ISCSI_BHS_LEN + ISCSI_DIGEST_LEN); rc = iscsi_build_iovs(&conn, iovs, 3, &pdu, &mapped_length); CU_ASSERT(rc == 3); CU_ASSERT(iovs[0].iov_base == (void *)&pdu.bhs); CU_ASSERT(iovs[0].iov_len == ISCSI_BHS_LEN); CU_ASSERT(iovs[1].iov_base == (void *)pdu.header_digest); CU_ASSERT(iovs[1].iov_len == ISCSI_DIGEST_LEN); CU_ASSERT(iovs[2].iov_base == (void *)pdu.data); CU_ASSERT(iovs[2].iov_len == 512); CU_ASSERT(mapped_length == ISCSI_BHS_LEN + ISCSI_DIGEST_LEN + 512); rc = iscsi_build_iovs(&conn, iovs, 4, &pdu, &mapped_length); CU_ASSERT(rc == 4); CU_ASSERT(iovs[0].iov_base == (void *)&pdu.bhs); CU_ASSERT(iovs[0].iov_len == ISCSI_BHS_LEN); CU_ASSERT(iovs[1].iov_base == (void *)pdu.header_digest); CU_ASSERT(iovs[1].iov_len == ISCSI_DIGEST_LEN); CU_ASSERT(iovs[2].iov_base == (void *)pdu.data); CU_ASSERT(iovs[2].iov_len == 512); CU_ASSERT(iovs[3].iov_base == (void *)pdu.data_digest); CU_ASSERT(iovs[3].iov_len == ISCSI_DIGEST_LEN); CU_ASSERT(mapped_length == ISCSI_BHS_LEN + ISCSI_DIGEST_LEN + 512 + ISCSI_DIGEST_LEN); free(data); } static void build_iovs_with_md_test(void) { struct spdk_iscsi_conn conn = {}; struct spdk_iscsi_pdu pdu = {}; struct iovec iovs[6] = {}; uint8_t *data; uint32_t mapped_length = 0; int rc; struct spdk_dif_ctx_init_ext_opts dif_opts; conn.header_digest = true; conn.data_digest = true; DSET24(&pdu.bhs.data_segment_len, 4096 * 2); data = calloc(1, (4096 + 128) * 2); SPDK_CU_ASSERT_FATAL(data != NULL); pdu.data = data; pdu.data_buf_len = (4096 + 128) * 2; pdu.bhs.total_ahs_len = 0; pdu.bhs.opcode = ISCSI_OP_SCSI; dif_opts.size = SPDK_SIZEOF(&dif_opts, dif_pi_format); dif_opts.dif_pi_format = SPDK_DIF_PI_FORMAT_16; rc = spdk_dif_ctx_init(&pdu.dif_ctx, 4096 + 128, 128, true, false, SPDK_DIF_TYPE1, 0, 0, 0, 0, 0, 0, &dif_opts); CU_ASSERT(rc == 0); pdu.dif_insert_or_strip = true; pdu.writev_offset = 0; rc = iscsi_build_iovs(&conn, iovs, 6, &pdu, &mapped_length); CU_ASSERT(rc == 5); CU_ASSERT(iovs[0].iov_base == (void *)&pdu.bhs); CU_ASSERT(iovs[0].iov_len == ISCSI_BHS_LEN); CU_ASSERT(iovs[1].iov_base == (void *)pdu.header_digest); CU_ASSERT(iovs[1].iov_len == ISCSI_DIGEST_LEN); CU_ASSERT(iovs[2].iov_base == (void *)pdu.data); CU_ASSERT(iovs[2].iov_len == 4096); CU_ASSERT(iovs[3].iov_base == (void *)(pdu.data + 4096 + 128)); CU_ASSERT(iovs[3].iov_len == 4096); CU_ASSERT(iovs[4].iov_base == (void *)pdu.data_digest); CU_ASSERT(iovs[4].iov_len == ISCSI_DIGEST_LEN); CU_ASSERT(mapped_length == ISCSI_BHS_LEN + ISCSI_DIGEST_LEN + 4096 * 2 + ISCSI_DIGEST_LEN); pdu.writev_offset = ISCSI_BHS_LEN + ISCSI_DIGEST_LEN + 2048; rc = iscsi_build_iovs(&conn, iovs, 6, &pdu, &mapped_length); CU_ASSERT(rc == 3); CU_ASSERT(iovs[0].iov_base == (void *)(pdu.data + 2048)); CU_ASSERT(iovs[0].iov_len == 2048); CU_ASSERT(iovs[1].iov_base == (void *)(pdu.data + 4096 + 128)); CU_ASSERT(iovs[1].iov_len == 4096); CU_ASSERT(iovs[2].iov_base == (void *)pdu.data_digest); CU_ASSERT(iovs[2].iov_len == ISCSI_DIGEST_LEN); CU_ASSERT(mapped_length == 2048 + 4096 + ISCSI_DIGEST_LEN); pdu.writev_offset = ISCSI_BHS_LEN + ISCSI_DIGEST_LEN + 4096 * 2; rc = iscsi_build_iovs(&conn, iovs, 6, &pdu, &mapped_length); CU_ASSERT(rc == 1); CU_ASSERT(iovs[0].iov_base == (void *)pdu.data_digest); CU_ASSERT(iovs[0].iov_len == ISCSI_DIGEST_LEN); CU_ASSERT(mapped_length == ISCSI_DIGEST_LEN); pdu.writev_offset = 0; rc = iscsi_build_iovs(&conn, iovs, 3, &pdu, &mapped_length); CU_ASSERT(rc == 3); CU_ASSERT(iovs[0].iov_base == (void *)&pdu.bhs); CU_ASSERT(iovs[0].iov_len == ISCSI_BHS_LEN); CU_ASSERT(iovs[1].iov_base == (void *)pdu.header_digest); CU_ASSERT(iovs[1].iov_len == ISCSI_DIGEST_LEN); CU_ASSERT(iovs[2].iov_base == (void *)pdu.data); CU_ASSERT(iovs[2].iov_len == 4096); CU_ASSERT(mapped_length == ISCSI_BHS_LEN + ISCSI_DIGEST_LEN + 4096); free(data); } static void check_iscsi_reject(struct spdk_iscsi_pdu *pdu, uint8_t reason) { struct spdk_iscsi_pdu *rsp_pdu; struct iscsi_bhs_reject *reject_bhs; CU_ASSERT(pdu->is_rejected == true); rsp_pdu = TAILQ_FIRST(&g_write_pdu_list); CU_ASSERT(rsp_pdu != NULL); reject_bhs = (struct iscsi_bhs_reject *)&rsp_pdu->bhs; CU_ASSERT(reject_bhs->reason == reason); TAILQ_REMOVE(&g_write_pdu_list, rsp_pdu, tailq); iscsi_put_pdu(rsp_pdu); pdu->is_rejected = false; } static void check_login_response(uint8_t status_class, uint8_t status_detail) { struct spdk_iscsi_pdu *rsp_pdu; struct iscsi_bhs_login_rsp *login_rsph; rsp_pdu = TAILQ_FIRST(&g_write_pdu_list); CU_ASSERT(rsp_pdu != NULL); login_rsph = (struct iscsi_bhs_login_rsp *)&rsp_pdu->bhs; CU_ASSERT(login_rsph->status_class == status_class); CU_ASSERT(login_rsph->status_detail == status_detail); TAILQ_REMOVE(&g_write_pdu_list, rsp_pdu, tailq); iscsi_put_pdu(rsp_pdu); } static void pdu_hdr_op_login_test(void) { struct spdk_iscsi_sess sess = {}; struct spdk_iscsi_conn conn = {}; struct spdk_iscsi_pdu pdu = {}; struct iscsi_bhs_login_req *login_reqh; int rc; login_reqh = (struct iscsi_bhs_login_req *)&pdu.bhs; /* Case 1 - On discovery session, target only accepts text requests with the * SendTargets key and logout request with reason "close the session". */ sess.session_type = SESSION_TYPE_DISCOVERY; conn.full_feature = true; conn.sess = &sess; rc = iscsi_pdu_hdr_op_login(&conn, &pdu); CU_ASSERT(rc == SPDK_ISCSI_CONNECTION_FATAL); /* Case 2 - Data segment length is limited to be not more than 8KB, the default * FirstBurstLength, for login request. */ sess.session_type = SESSION_TYPE_INVALID; conn.full_feature = false; conn.sess = NULL; pdu.data_segment_len = SPDK_ISCSI_FIRST_BURST_LENGTH + 1; rc = iscsi_pdu_hdr_op_login(&conn, &pdu); CU_ASSERT(rc == 0); check_iscsi_reject(&pdu, ISCSI_REASON_PROTOCOL_ERROR); /* Case 3 - PDU pool is empty */ pdu.data_segment_len = SPDK_ISCSI_FIRST_BURST_LENGTH; g_pdu_pool_is_empty = true; rc = iscsi_pdu_hdr_op_login(&conn, &pdu); CU_ASSERT(rc == SPDK_ISCSI_CONNECTION_FATAL); /* Case 4 - A login request with the C bit set to 1 must have the T bit set to 0. */ g_pdu_pool_is_empty = false; login_reqh->flags |= ISCSI_LOGIN_TRANSIT; login_reqh->flags |= ISCSI_LOGIN_CONTINUE; rc = iscsi_pdu_hdr_op_login(&conn, &pdu); CU_ASSERT(rc == 0); check_login_response(ISCSI_CLASS_INITIATOR_ERROR, ISCSI_LOGIN_INITIATOR_ERROR); /* Case 5 - Both version-min and version-max must be set to 0x00. */ login_reqh->flags = 0; login_reqh->version_min = ISCSI_VERSION + 1; rc = iscsi_pdu_hdr_op_login(&conn, &pdu); CU_ASSERT(rc == 0); check_login_response(ISCSI_CLASS_INITIATOR_ERROR, ISCSI_LOGIN_UNSUPPORTED_VERSION); /* Case 6 - T bit is set to 1 correctly but invalid stage code is set to NSG. */ login_reqh->version_min = ISCSI_VERSION; login_reqh->flags |= ISCSI_LOGIN_TRANSIT; login_reqh->flags |= ISCSI_NSG_RESERVED_CODE; rc = iscsi_pdu_hdr_op_login(&conn, &pdu); CU_ASSERT(rc == 0); check_login_response(ISCSI_CLASS_INITIATOR_ERROR, ISCSI_LOGIN_INITIATOR_ERROR); /* Case 7 - Login request is correct. Login response is initialized and set to * the current connection. */ login_reqh->flags = 0; rc = iscsi_pdu_hdr_op_login(&conn, &pdu); CU_ASSERT(rc == 0); CU_ASSERT(conn.login_rsp_pdu != NULL); iscsi_put_pdu(conn.login_rsp_pdu); } static void pdu_hdr_op_text_test(void) { struct spdk_iscsi_sess sess = {}; struct spdk_iscsi_conn conn = {}; struct spdk_iscsi_pdu pdu = {}; struct iscsi_bhs_text_req *text_reqh; int rc; text_reqh = (struct iscsi_bhs_text_req *)&pdu.bhs; conn.sess = &sess; /* Case 1 - Data segment length for text request must not be more than * FirstBurstLength plus extra space to account for digests. */ pdu.data_segment_len = iscsi_get_max_immediate_data_size() + 1; rc = iscsi_pdu_hdr_op_text(&conn, &pdu); CU_ASSERT(rc == 0); check_iscsi_reject(&pdu, ISCSI_REASON_PROTOCOL_ERROR); /* Case 2 - A text request with the C bit set to 1 must have the F bit set to 0. */ pdu.data_segment_len = iscsi_get_max_immediate_data_size(); text_reqh->flags |= ISCSI_FLAG_FINAL; text_reqh->flags |= ISCSI_TEXT_CONTINUE; rc = iscsi_pdu_hdr_op_text(&conn, &pdu); CU_ASSERT(rc == -1); /* Case 3 - ExpStatSN of the text request is expected to match StatSN of the current * connection. But StarPort iSCSI initiator didn't follow the expectation. In this * case we overwrite StatSN by ExpStatSN and processes the request as correct. */ text_reqh->flags = 0; to_be32(&text_reqh->exp_stat_sn, 1234); to_be32(&conn.StatSN, 4321); rc = iscsi_pdu_hdr_op_text(&conn, &pdu); CU_ASSERT(rc == 0); CU_ASSERT(conn.StatSN == 1234); /* Case 4 - Text request is the first in the sequence of text requests and responses, * and so its ITT is hold to the current connection. */ sess.current_text_itt = 0xffffffffU; to_be32(&text_reqh->itt, 5678); rc = iscsi_pdu_hdr_op_text(&conn, &pdu); CU_ASSERT(rc == 0); CU_ASSERT(sess.current_text_itt == 5678); /* Case 5 - If text request is sent as part of a sequence of text requests and responses, * its ITT must be the same for all the text requests. But it was not. */ sess.current_text_itt = 5679; rc = iscsi_pdu_hdr_op_text(&conn, &pdu); CU_ASSERT(rc == 0); check_iscsi_reject(&pdu, ISCSI_REASON_PROTOCOL_ERROR); /* Case 6 - Different from case 5, its ITT matches the value saved in the connection. */ text_reqh->flags = 0; sess.current_text_itt = 5678; rc = iscsi_pdu_hdr_op_text(&conn, &pdu); CU_ASSERT(rc == 0); } static void check_logout_response(uint8_t response, uint32_t stat_sn, uint32_t exp_cmd_sn, uint32_t max_cmd_sn) { struct spdk_iscsi_pdu *rsp_pdu; struct iscsi_bhs_logout_resp *logout_rsph; rsp_pdu = TAILQ_FIRST(&g_write_pdu_list); CU_ASSERT(rsp_pdu != NULL); logout_rsph = (struct iscsi_bhs_logout_resp *)&rsp_pdu->bhs; CU_ASSERT(logout_rsph->response == response); CU_ASSERT(from_be32(&logout_rsph->stat_sn) == stat_sn); CU_ASSERT(from_be32(&logout_rsph->exp_cmd_sn) == exp_cmd_sn); CU_ASSERT(from_be32(&logout_rsph->max_cmd_sn) == max_cmd_sn); TAILQ_REMOVE(&g_write_pdu_list, rsp_pdu, tailq); iscsi_put_pdu(rsp_pdu); } static void pdu_hdr_op_logout_test(void) { struct spdk_iscsi_sess sess = {}; struct spdk_iscsi_conn conn = {}; struct spdk_iscsi_pdu pdu = {}; struct iscsi_bhs_logout_req *logout_reqh; int rc; logout_reqh = (struct iscsi_bhs_logout_req *)&pdu.bhs; /* Case 1 - Target can accept logout request only with the reason "close the session" * on discovery session. */ logout_reqh->reason = 1; conn.sess = &sess; sess.session_type = SESSION_TYPE_DISCOVERY; rc = iscsi_pdu_hdr_op_logout(&conn, &pdu); CU_ASSERT(rc == SPDK_ISCSI_CONNECTION_FATAL); /* Case 2 - Session is not established yet but connection was closed successfully. */ conn.sess = NULL; conn.StatSN = 1234; to_be32(&logout_reqh->exp_stat_sn, 1234); pdu.cmd_sn = 5678; rc = iscsi_pdu_hdr_op_logout(&conn, &pdu); CU_ASSERT(rc == 0); check_logout_response(0, 1234, 5678, 5678); CU_ASSERT(conn.StatSN == 1235); /* Case 3 - Session type is normal but CID was not found. Hence connection or session * was not closed. */ sess.session_type = SESSION_TYPE_NORMAL; sess.ExpCmdSN = 5679; sess.connections = 1; conn.sess = &sess; conn.cid = 1; rc = iscsi_pdu_hdr_op_logout(&conn, &pdu); CU_ASSERT(rc == 0); check_logout_response(1, 1235, 5679, 1); CU_ASSERT(conn.StatSN == 1236); CU_ASSERT(sess.MaxCmdSN == 1); /* Case 4 - Session type is normal and CID was found. Connection or session was closed * successfully. */ to_be16(&logout_reqh->cid, 1); rc = iscsi_pdu_hdr_op_logout(&conn, &pdu); CU_ASSERT(rc == 0); check_logout_response(0, 1236, 5679, 2); CU_ASSERT(conn.StatSN == 1237); CU_ASSERT(sess.MaxCmdSN == 2); /* Case 5 - PDU pool is empty. */ g_pdu_pool_is_empty = true; rc = iscsi_pdu_hdr_op_logout(&conn, &pdu); CU_ASSERT(rc == SPDK_ISCSI_CONNECTION_FATAL); g_pdu_pool_is_empty = false; } static void check_scsi_task(struct spdk_iscsi_pdu *pdu, enum spdk_scsi_data_dir dir) { struct spdk_iscsi_task *task; task = pdu->task; CU_ASSERT(task != NULL); CU_ASSERT(task->pdu == pdu); CU_ASSERT(task->scsi.dxfer_dir == (uint32_t)dir); iscsi_task_put(task); pdu->task = NULL; } static void pdu_hdr_op_scsi_test(void) { struct spdk_iscsi_sess sess = {}; struct spdk_iscsi_conn conn = {}; struct spdk_iscsi_pdu pdu = {}; struct spdk_scsi_dev dev = {}; struct spdk_scsi_lun lun = {}; struct iscsi_bhs_scsi_req *scsi_reqh; int rc; scsi_reqh = (struct iscsi_bhs_scsi_req *)&pdu.bhs; conn.sess = &sess; conn.dev = &dev; /* Case 1 - SCSI command is acceptable only on normal session. */ sess.session_type = SESSION_TYPE_DISCOVERY; rc = iscsi_pdu_hdr_op_scsi(&conn, &pdu); CU_ASSERT(rc == SPDK_ISCSI_CONNECTION_FATAL); /* Case 2 - Task pool is empty. */ g_task_pool_is_empty = true; rc = iscsi_pdu_hdr_op_scsi(&conn, &pdu); CU_ASSERT(rc == SPDK_ISCSI_CONNECTION_FATAL); g_task_pool_is_empty = false; /* Case 3 - bidirectional operations (both R and W flags are set to 1) are not supported. */ sess.session_type = SESSION_TYPE_NORMAL; scsi_reqh->read_bit = 1; scsi_reqh->write_bit = 1; rc = iscsi_pdu_hdr_op_scsi(&conn, &pdu); CU_ASSERT(rc == SPDK_ISCSI_CONNECTION_FATAL); /* Case 4 - LUN is hot-removed, and return immediately. */ scsi_reqh->write_bit = 0; rc = iscsi_pdu_hdr_op_scsi(&conn, &pdu); CU_ASSERT(rc == 0); CU_ASSERT(pdu.task == NULL); /* Case 5 - SCSI read command PDU is correct, and the configured iSCSI task is set to the PDU. */ TAILQ_INIT(&dev.luns); TAILQ_INSERT_TAIL(&dev.luns, &lun, tailq); rc = iscsi_pdu_hdr_op_scsi(&conn, &pdu); CU_ASSERT(rc == 0); check_scsi_task(&pdu, SPDK_SCSI_DIR_FROM_DEV); /* Case 6 - For SCSI write command PDU, its data segment length must not be more than * FirstBurstLength plus extra space to account for digests. */ scsi_reqh->read_bit = 0; scsi_reqh->write_bit = 1; pdu.data_segment_len = iscsi_get_max_immediate_data_size() + 1; rc = iscsi_pdu_hdr_op_scsi(&conn, &pdu); CU_ASSERT(rc == 0); check_iscsi_reject(&pdu, ISCSI_REASON_PROTOCOL_ERROR); /* Case 7 - For SCSI write command PDU, its data segment length must not be more than * Expected Data Transfer Length (EDTL). */ pdu.data_segment_len = iscsi_get_max_immediate_data_size(); to_be32(&scsi_reqh->expected_data_xfer_len, pdu.data_segment_len - 1); rc = iscsi_pdu_hdr_op_scsi(&conn, &pdu); CU_ASSERT(rc == 0); check_iscsi_reject(&pdu, ISCSI_REASON_PROTOCOL_ERROR); /* Case 8 - If ImmediateData is not enabled for the session, SCSI write command PDU * cannot have data segment. */ to_be32(&scsi_reqh->expected_data_xfer_len, pdu.data_segment_len); rc = iscsi_pdu_hdr_op_scsi(&conn, &pdu); CU_ASSERT(rc == 0); check_iscsi_reject(&pdu, ISCSI_REASON_PROTOCOL_ERROR); /* Case 9 - For SCSI write command PDU, its data segment length must not be more * than FirstBurstLength. */ sess.ImmediateData = true; rc = iscsi_pdu_hdr_op_scsi(&conn, &pdu); CU_ASSERT(rc == 0); check_iscsi_reject(&pdu, ISCSI_REASON_PROTOCOL_ERROR); /* Case 10 - SCSI write command PDU is correct, and the configured iSCSI task is set to the PDU. */ sess.FirstBurstLength = pdu.data_segment_len; rc = iscsi_pdu_hdr_op_scsi(&conn, &pdu); CU_ASSERT(rc == 0); check_scsi_task(&pdu, SPDK_SCSI_DIR_TO_DEV); /* Case 11 - R and W must not both be 0 when EDTL is not 0. */ scsi_reqh->write_bit = 0; rc = iscsi_pdu_hdr_op_scsi(&conn, &pdu); CU_ASSERT(rc == 0); check_iscsi_reject(&pdu, ISCSI_REASON_INVALID_PDU_FIELD); /* Case 11 - R and W are both 0 and EDTL is also 0, and hence SCSI command PDU is accepted. */ to_be32(&scsi_reqh->expected_data_xfer_len, 0); rc = iscsi_pdu_hdr_op_scsi(&conn, &pdu); CU_ASSERT(rc == 0); check_scsi_task(&pdu, SPDK_SCSI_DIR_NONE); } static void check_iscsi_task_mgmt_response(uint8_t response, uint32_t task_tag, uint32_t stat_sn, uint32_t exp_cmd_sn, uint32_t max_cmd_sn) { struct spdk_iscsi_pdu *rsp_pdu; struct iscsi_bhs_task_resp *rsph; rsp_pdu = TAILQ_FIRST(&g_write_pdu_list); CU_ASSERT(rsp_pdu != NULL); rsph = (struct iscsi_bhs_task_resp *)&rsp_pdu->bhs; CU_ASSERT(rsph->response == response); CU_ASSERT(from_be32(&rsph->itt) == task_tag); CU_ASSERT(from_be32(&rsph->exp_cmd_sn) == exp_cmd_sn); CU_ASSERT(from_be32(&rsph->max_cmd_sn) == max_cmd_sn); TAILQ_REMOVE(&g_write_pdu_list, rsp_pdu, tailq); iscsi_put_pdu(rsp_pdu); } static void pdu_hdr_op_task_mgmt_test(void) { struct spdk_iscsi_sess sess = {}; struct spdk_iscsi_conn conn = {}; struct spdk_iscsi_pdu pdu = {}; struct spdk_scsi_dev dev = {}; struct spdk_scsi_lun lun = {}; struct iscsi_bhs_task_req *task_reqh; int rc; /* TBD: This test covers only error paths before creating iSCSI task for now. * Testing iSCSI task creation in iscsi_pdu_hdr_op_task() by UT is not simple * and do it separately later. */ task_reqh = (struct iscsi_bhs_task_req *)&pdu.bhs; conn.sess = &sess; conn.dev = &dev; /* Case 1 - Task Management Function request PDU is acceptable only on normal session. */ sess.session_type = SESSION_TYPE_DISCOVERY; rc = iscsi_pdu_hdr_op_task(&conn, &pdu); CU_ASSERT(rc == SPDK_ISCSI_CONNECTION_FATAL); /* Case 2 - LUN is hot removed. "LUN does not exist" response is sent. */ sess.session_type = SESSION_TYPE_NORMAL; task_reqh->immediate = 0; to_be32(&task_reqh->itt, 1234); rc = iscsi_pdu_hdr_op_task(&conn, &pdu); CU_ASSERT(rc == 0); check_iscsi_task_mgmt_response(ISCSI_TASK_FUNC_RESP_LUN_NOT_EXIST, 1234, 0, 0, 1); /* Case 3 - Unassigned function is specified. "Function rejected" response is sent. */ TAILQ_INIT(&dev.luns); TAILQ_INSERT_TAIL(&dev.luns, &lun, tailq); task_reqh->flags = 0; rc = iscsi_pdu_hdr_op_task(&conn, &pdu); CU_ASSERT(rc == 0); check_iscsi_task_mgmt_response(ISCSI_TASK_FUNC_REJECTED, 1234, 0, 0, 2); /* Case 4 - CLEAR TASK SET is not supported. "Task management function not supported" * response is sent. */ task_reqh->flags = ISCSI_TASK_FUNC_CLEAR_TASK_SET; rc = iscsi_pdu_hdr_op_task(&conn, &pdu); CU_ASSERT(rc == 0); check_iscsi_task_mgmt_response(ISCSI_TASK_FUNC_RESP_FUNC_NOT_SUPPORTED, 1234, 0, 0, 3); /* Case 5 - CLEAR ACA is not supported. "Task management function not supported" is sent. */ task_reqh->flags = ISCSI_TASK_FUNC_CLEAR_ACA; rc = iscsi_pdu_hdr_op_task(&conn, &pdu); CU_ASSERT(rc == 0); check_iscsi_task_mgmt_response(ISCSI_TASK_FUNC_RESP_FUNC_NOT_SUPPORTED, 1234, 0, 0, 4); /* Case 6 - TARGET WARM RESET is not supported. "Task management function not supported * is sent. */ task_reqh->flags = ISCSI_TASK_FUNC_TARGET_WARM_RESET; rc = iscsi_pdu_hdr_op_task(&conn, &pdu); CU_ASSERT(rc == 0); check_iscsi_task_mgmt_response(ISCSI_TASK_FUNC_RESP_FUNC_NOT_SUPPORTED, 1234, 0, 0, 5); /* Case 7 - TARGET COLD RESET is not supported. "Task management function not supported * is sent. */ task_reqh->flags = ISCSI_TASK_FUNC_TARGET_COLD_RESET; rc = iscsi_pdu_hdr_op_task(&conn, &pdu); CU_ASSERT(rc == 0); check_iscsi_task_mgmt_response(ISCSI_TASK_FUNC_RESP_FUNC_NOT_SUPPORTED, 1234, 0, 0, 6); /* Case 8 - TASK REASSIGN is not supported. "Task management function not supported" is sent. */ task_reqh->flags = ISCSI_TASK_FUNC_TASK_REASSIGN; rc = iscsi_pdu_hdr_op_task(&conn, &pdu); CU_ASSERT(rc == 0); check_iscsi_task_mgmt_response(ISCSI_TASK_FUNC_RESP_FUNC_NOT_SUPPORTED, 1234, 0, 0, 7); } static void pdu_hdr_op_nopout_test(void) { struct spdk_iscsi_sess sess = {}; struct spdk_iscsi_conn conn = {}; struct spdk_iscsi_pdu pdu = {}; struct iscsi_bhs_nop_out *nopout_reqh; int rc; nopout_reqh = (struct iscsi_bhs_nop_out *)&pdu.bhs; conn.sess = &sess; /* Case 1 - NOP-Out PDU is acceptable only on normal session. */ sess.session_type = SESSION_TYPE_DISCOVERY; rc = iscsi_pdu_hdr_op_nopout(&conn, &pdu); CU_ASSERT(rc == SPDK_ISCSI_CONNECTION_FATAL); /* Case 2 - The length of the reflected ping data is limited to MaxRecvDataSegmentLength. */ sess.session_type = SESSION_TYPE_NORMAL; pdu.data_segment_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH + 1; rc = iscsi_pdu_hdr_op_nopout(&conn, &pdu); CU_ASSERT(rc == 0); check_iscsi_reject(&pdu, ISCSI_REASON_PROTOCOL_ERROR); /* Case 3 - If Initiator Task Tag contains 0xffffffff, the I bit must be set * to 1 and Target Transfer Tag should be copied from NOP-In PDU. This case * satisfies the former but doesn't satisfy the latter, but ignore the error * for now. */ pdu.data_segment_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; conn.id = 1234; to_be32(&nopout_reqh->ttt, 1235); to_be32(&nopout_reqh->itt, 0xffffffffU); nopout_reqh->immediate = 1; rc = iscsi_pdu_hdr_op_nopout(&conn, &pdu); CU_ASSERT(rc == 0); /* Case 4 - This case doesn't satisfy the above former. This error is not ignored. */ nopout_reqh->immediate = 0; rc = iscsi_pdu_hdr_op_nopout(&conn, &pdu); CU_ASSERT(rc == SPDK_ISCSI_CONNECTION_FATAL); } static void check_iscsi_r2t(struct spdk_iscsi_task *task, uint32_t len) { struct spdk_iscsi_pdu *rsp_pdu; struct iscsi_bhs_r2t *rsph; rsp_pdu = TAILQ_FIRST(&g_write_pdu_list); CU_ASSERT(rsp_pdu != NULL); rsph = (struct iscsi_bhs_r2t *)&rsp_pdu->bhs; CU_ASSERT(rsph->opcode == ISCSI_OP_R2T); CU_ASSERT(from_be64(&rsph->lun) == spdk_scsi_lun_id_int_to_fmt(task->lun_id)); CU_ASSERT(from_be32(&rsph->buffer_offset) + len == task->next_r2t_offset); CU_ASSERT(from_be32(&rsph->desired_xfer_len) == len); TAILQ_REMOVE(&g_write_pdu_list, rsp_pdu, tailq); iscsi_put_pdu(rsp_pdu); } static void pdu_hdr_op_data_test(void) { struct spdk_iscsi_sess sess = {}; struct spdk_iscsi_conn conn = {}; struct spdk_iscsi_pdu pdu = {}; struct spdk_iscsi_task primary = {}; struct spdk_scsi_dev dev = {}; struct spdk_scsi_lun lun = {}; struct iscsi_bhs_data_out *data_reqh; int rc; data_reqh = (struct iscsi_bhs_data_out *)&pdu.bhs; conn.sess = &sess; conn.dev = &dev; TAILQ_INIT(&conn.active_r2t_tasks); /* Case 1 - SCSI Data-Out PDU is acceptable only on normal session. */ sess.session_type = SESSION_TYPE_DISCOVERY; rc = iscsi_pdu_hdr_op_data(&conn, &pdu); CU_ASSERT(rc == SPDK_ISCSI_CONNECTION_FATAL); /* Case 2 - Data segment length must not be more than MaxRecvDataSegmentLength. */ sess.session_type = SESSION_TYPE_NORMAL; pdu.data_segment_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH + 1; rc = iscsi_pdu_hdr_op_data(&conn, &pdu); CU_ASSERT(rc == 0); check_iscsi_reject(&pdu, ISCSI_REASON_PROTOCOL_ERROR); /* Case 3 - R2T task whose Target Transfer Tag matches is not found. */ pdu.data_segment_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; rc = iscsi_pdu_hdr_op_data(&conn, &pdu); CU_ASSERT(rc == 0); check_iscsi_reject(&pdu, ISCSI_REASON_INVALID_PDU_FIELD); /* Case 4 - R2T task whose Target Transfer Tag matches is found but data segment length * is more than Desired Data Transfer Length of the R2T. */ primary.desired_data_transfer_length = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH - 1; conn.pending_r2t = 1; TAILQ_INSERT_TAIL(&conn.active_r2t_tasks, &primary, link); rc = iscsi_pdu_hdr_op_data(&conn, &pdu); CU_ASSERT(rc == SPDK_ISCSI_CONNECTION_FATAL); /* Case 5 - Initiator task tag doesn't match tag of R2T task. */ primary.desired_data_transfer_length = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; to_be32(&data_reqh->itt, 1); rc = iscsi_pdu_hdr_op_data(&conn, &pdu); CU_ASSERT(rc == 0); check_iscsi_reject(&pdu, ISCSI_REASON_INVALID_PDU_FIELD); /* Case 6 - DataSN doesn't match the Data-Out PDU number within the current * output sequence. */ to_be32(&data_reqh->itt, 0); to_be32(&data_reqh->data_sn, 1); rc = iscsi_pdu_hdr_op_data(&conn, &pdu); CU_ASSERT(rc == 0); check_iscsi_reject(&pdu, ISCSI_REASON_PROTOCOL_ERROR); /* Case 7 - Output sequence must be in increasing buffer offset and must not * be overlaid but they are not satisfied. */ to_be32(&data_reqh->data_sn, 0); to_be32(&data_reqh->buffer_offset, 4096); rc = iscsi_pdu_hdr_op_data(&conn, &pdu); CU_ASSERT(rc == SPDK_ISCSI_CONNECTION_FATAL); /* Case 8 - Data segment length must not exceed MaxBurstLength. */ to_be32(&data_reqh->buffer_offset, 0); sess.MaxBurstLength = pdu.data_segment_len - 1; rc = iscsi_pdu_hdr_op_data(&conn, &pdu); CU_ASSERT(rc == SPDK_ISCSI_CONNECTION_FATAL); /* Case 9 - LUN is hot removed. */ sess.MaxBurstLength = pdu.data_segment_len * 4; to_be32(&data_reqh->data_sn, primary.r2t_datasn); to_be32(&data_reqh->buffer_offset, primary.next_expected_r2t_offset); rc = iscsi_pdu_hdr_op_data(&conn, &pdu); CU_ASSERT(rc == 0); check_iscsi_reject(&pdu, ISCSI_REASON_PROTOCOL_ERROR); /* Case 10 - SCSI Data-Out PDU is correct and processed. Its F bit is 0 and hence * R2T is not sent. */ TAILQ_INIT(&dev.luns); TAILQ_INSERT_TAIL(&dev.luns, &lun, tailq); to_be32(&data_reqh->data_sn, primary.r2t_datasn); to_be32(&data_reqh->buffer_offset, primary.next_expected_r2t_offset); rc = iscsi_pdu_hdr_op_data(&conn, &pdu); CU_ASSERT(rc == 0); CU_ASSERT(!pdu.is_rejected); CU_ASSERT(pdu.data_buf_len == SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH); pdu.task = NULL; /* Case 11 - SCSI Data-Out PDU is correct and processed. Its F bit is 1 and hence * R2T is sent. */ data_reqh->flags |= ISCSI_FLAG_FINAL; to_be32(&data_reqh->data_sn, primary.r2t_datasn); to_be32(&data_reqh->buffer_offset, primary.next_expected_r2t_offset); primary.scsi.transfer_len = pdu.data_segment_len * 5; rc = iscsi_pdu_hdr_op_data(&conn, &pdu); CU_ASSERT(rc == 0); CU_ASSERT(!pdu.is_rejected); check_iscsi_r2t(&primary, pdu.data_segment_len * 4); } /* Test an ISCSI_OP_TEXT PDU with CONTINUE bit set but * no data. */ static void empty_text_with_cbit_test(void) { struct spdk_iscsi_sess sess = {}; struct spdk_iscsi_conn conn = {}; struct spdk_scsi_dev dev = {}; struct spdk_iscsi_pdu *req_pdu; int rc; req_pdu = iscsi_get_pdu(&conn); sess.ExpCmdSN = 0; sess.MaxCmdSN = 64; sess.session_type = SESSION_TYPE_NORMAL; sess.MaxBurstLength = 1024; conn.full_feature = 1; conn.sess = &sess; conn.dev = &dev; conn.state = ISCSI_CONN_STATE_RUNNING; memset(&req_pdu->bhs, 0, sizeof(req_pdu->bhs)); req_pdu->bhs.opcode = ISCSI_OP_TEXT; req_pdu->bhs.flags = ISCSI_TEXT_CONTINUE; rc = iscsi_pdu_hdr_handle(&conn, req_pdu); CU_ASSERT(rc == 0); CU_ASSERT(!req_pdu->is_rejected); rc = iscsi_pdu_payload_handle(&conn, req_pdu); CU_ASSERT(rc == 0); iscsi_put_pdu(req_pdu); } static void check_pdu_payload_read(struct spdk_iscsi_pdu *pdu, struct spdk_mobj *mobj, int rc, int index, uint32_t read_offset) { uint64_t buf_offset; uint32_t *data; uint32_t i; data = (uint32_t *)pdu->data; buf_offset = (uint64_t)pdu->data - (uint64_t)mobj->buf; CU_ASSERT(pdu->mobj[index] == mobj); CU_ASSERT(pdu->data_from_mempool == true); CU_ASSERT(buf_offset == 0 || pdu->data_offset == 0); CU_ASSERT(mobj->data_len + pdu->data_offset == buf_offset + pdu->data_valid_bytes); CU_ASSERT(rc > 0 || pdu->data_valid_bytes == pdu->data_segment_len); for (i = 0; i < pdu->data_valid_bytes - pdu->data_offset; i += 4) { CU_ASSERT(data[i / 4] == (uint32_t)(read_offset + i)); } } static void pdu_payload_read_test(void) { struct spdk_iscsi_conn conn = {}; struct spdk_iscsi_pdu pdu = {}; struct spdk_mobj mobj1 = {}, mobj2 = {}; int rc; g_iscsi.FirstBurstLength = SPDK_ISCSI_FIRST_BURST_LENGTH; alloc_mock_mobj(&mobj1, SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH); alloc_mock_mobj(&mobj2, SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH); MOCK_SET(spdk_mempool_get, &mobj1); /* The following tests assume that a iscsi_conn_read_data() call could read * the required length of the data and all read lengths are 4 bytes multiples. * The latter is to verify data is copied to the correct offset by using data patterns. */ /* Case 1: data segment size is equal with max immediate data size. */ pdu.data_segment_len = iscsi_get_max_immediate_data_size(); pdu.data_buf_len = pdu.data_segment_len; g_conn_read_len = 0; rc = iscsi_pdu_payload_read(&conn, &pdu); check_pdu_payload_read(&pdu, &mobj1, rc, 0, 0); memset(&pdu, 0, sizeof(pdu)); mobj1.data_len = 0; /* Case 2: data segment size is equal with SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH. */ pdu.data_segment_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; pdu.data_buf_len = pdu.data_segment_len; g_conn_read_len = 0; rc = iscsi_pdu_payload_read(&conn, &pdu); check_pdu_payload_read(&pdu, &mobj1, rc, 0, 0); memset(&pdu, 0, sizeof(pdu)); mobj1.data_len = 0; /* Case 3: data segment size is larger than SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH. * This should result in error. */ pdu.data_segment_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH + 1; pdu.data_buf_len = pdu.data_segment_len; g_conn_read_len = 0; rc = iscsi_pdu_payload_read(&conn, &pdu); CU_ASSERT(rc < 0); /* Case 4: read starts from the middle of the 1st data buffer, the 1st data buffer * ran out, allocate the 2nd data buffer, and read the remaining data to the 2nd * data buffer. */ mobj1.data_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH / 2; pdu.data_segment_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; pdu.data_buf_len = SPDK_BDEV_BUF_SIZE_WITH_MD(SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH); pdu.mobj[0] = &mobj1; pdu.data = (void *)((uint64_t)mobj1.buf + SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH / 2); pdu.data_from_mempool = true; g_conn_read_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH / 2; rc = iscsi_pdu_payload_read(&conn, &pdu); check_pdu_payload_read(&pdu, &mobj1, rc, 0, SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH / 2); MOCK_SET(spdk_mempool_get, &mobj2); rc = iscsi_pdu_payload_read(&conn, &pdu); check_pdu_payload_read(&pdu, &mobj2, rc, 1, SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH); /* Case 5: data segment size is SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH, data digest * is enabled, and reading PDU data is split between data segment and data digest. */ conn.data_digest = true; memset(&pdu, 0, sizeof(pdu)); pdu.crc32c = SPDK_CRC32C_INITIAL; pdu.data = mobj1.buf; pdu.data_segment_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; pdu.mobj[0] = &mobj1; pdu.data_valid_bytes = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; mobj1.data_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; /* generate data digest. */ g_data_digest = spdk_crc32c_update(mobj1.buf, SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH, SPDK_CRC32C_INITIAL); g_data_digest ^= SPDK_CRC32C_XOR; g_conn_read_data_digest = true; rc = iscsi_pdu_payload_read(&conn, &pdu); CU_ASSERT(rc == 0); CU_ASSERT(pdu.ddigest_valid_bytes == ISCSI_DIGEST_LEN); CU_ASSERT(pdu.mobj[1] == NULL); g_conn_read_data_digest = false; g_conn_read_len = 0; MOCK_SET(spdk_mempool_get, &mobj1); mobj1.data_len = 0; g_conn_read_len = 0; MOCK_CLEAR(spdk_mempool_get); free(mobj1.buf); free(mobj2.buf); } static void check_pdu_hdr_handle(struct spdk_iscsi_pdu *pdu, struct spdk_mobj *mobj, uint32_t offset, struct spdk_iscsi_task *primary) { CU_ASSERT(pdu->mobj[0] == mobj); CU_ASSERT(pdu->data == NULL || pdu->data == (void *)((uint64_t)mobj->buf + offset)); CU_ASSERT(primary->mobj == NULL); } static void check_pdu_payload_handle(struct spdk_iscsi_pdu *pdu, struct spdk_iscsi_task *primary, struct spdk_mobj *pdu_mobj0, struct spdk_mobj *pdu_mobj1, struct spdk_mobj *primary_mobj, uint32_t primary_offset) { CU_ASSERT(pdu->mobj[0] == pdu_mobj0); CU_ASSERT(pdu->mobj[1] == pdu_mobj1); CU_ASSERT(primary->mobj == primary_mobj); CU_ASSERT(primary->current_data_offset == primary_offset); } static void check_write_subtask_submit(struct spdk_scsi_lun *lun, struct spdk_mobj *mobj, struct spdk_iscsi_pdu *pdu, int index, uint32_t offset, uint32_t length) { struct spdk_scsi_task *scsi_task; struct spdk_iscsi_task *subtask; uint32_t *data; uint32_t i; scsi_task = TAILQ_FIRST(&lun->tasks); SPDK_CU_ASSERT_FATAL(scsi_task != NULL); TAILQ_REMOVE(&lun->tasks, scsi_task, scsi_link); subtask = iscsi_task_from_scsi_task(scsi_task); CU_ASSERT(iscsi_task_get_pdu(subtask) == pdu); CU_ASSERT(pdu->mobj[index] == mobj); CU_ASSERT(subtask->scsi.offset == offset); CU_ASSERT(subtask->scsi.length == length); CU_ASSERT(subtask->scsi.iovs[0].iov_base == mobj->buf); CU_ASSERT(subtask->scsi.iovs[0].iov_len == length); data = (uint32_t *)mobj->buf; for (i = 0; i < length; i += 4) { CU_ASSERT(data[i / 4] == offset + i); } free(subtask); } static void data_out_pdu_sequence_test(void) { struct spdk_scsi_lun lun = { .tasks = TAILQ_HEAD_INITIALIZER(lun.tasks), }; struct spdk_scsi_dev dev = { .luns = TAILQ_HEAD_INITIALIZER(dev.luns), }; struct spdk_iscsi_sess sess = { .session_type = SESSION_TYPE_NORMAL, .MaxBurstLength = SPDK_ISCSI_MAX_BURST_LENGTH, }; struct spdk_iscsi_conn conn = { .full_feature = true, .state = ISCSI_CONN_STATE_RUNNING, .sess = &sess, .dev = &dev, .active_r2t_tasks = TAILQ_HEAD_INITIALIZER(conn.active_r2t_tasks), }; struct spdk_iscsi_task primary = {}; struct spdk_iscsi_pdu pdu = {}; struct spdk_mobj mobj1 = {}, mobj2 = {}, mobj3 = {}; struct iscsi_bhs_data_out *data_reqh; int rc; TAILQ_INSERT_TAIL(&dev.luns, &lun, tailq); alloc_mock_mobj(&mobj1, SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH); alloc_mock_mobj(&mobj2, SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH); alloc_mock_mobj(&mobj3, SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH); /* Test scenario is as follows. * * Some iSCSI initiator sends a Data-OUT PDU sequence such that the size of * the data segment of any Data-OUT PDU is not block size multiples. * Test if such complex Data-OUT PDU sequence is processed correctly. * * Desired Data Transfer Length is 5 * SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH / 2. * Number of Data-OUT PDUs is 4. Length of the data segment of the first two PDUs are * SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH / 2 - 4. Length of the data segment of the * third PDU is SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH. Length of the data segment * of the final PDU is SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH / 2 + 8. * * Three data buffers should be used and three subtasks should be created and submitted. * * The test scenario assume that a iscsi_conn_read_data() call could read * the required length of the data and all read lengths are 4 bytes multiples. * The latter is to verify data is copied to the correct offset by using data patterns. */ primary.scsi.transfer_len = 5 * SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH / 2; primary.desired_data_transfer_length = primary.scsi.transfer_len; TAILQ_INSERT_TAIL(&conn.active_r2t_tasks, &primary, link); conn.pending_r2t = 1; g_conn_read_len = 0; /* The 1st Data-OUT PDU */ data_reqh = (struct iscsi_bhs_data_out *)&pdu.bhs; pdu.bhs.opcode = ISCSI_OP_SCSI_DATAOUT; pdu.data_segment_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH / 2 - 4; rc = iscsi_pdu_hdr_handle(&conn, &pdu); CU_ASSERT(rc == 0); check_pdu_hdr_handle(&pdu, NULL, 0, &primary); MOCK_SET(spdk_mempool_get, &mobj1); rc = iscsi_pdu_payload_read(&conn, &pdu); CU_ASSERT(rc == 0); check_pdu_payload_read(&pdu, &mobj1, rc, 0, 0); rc = iscsi_pdu_payload_handle(&conn, &pdu); CU_ASSERT(rc == 0); check_pdu_payload_handle(&pdu, &primary, NULL, NULL, &mobj1, 0); /* The 2nd Data-OUT PDU */ memset(&pdu, 0, sizeof(pdu)); pdu.bhs.opcode = ISCSI_OP_SCSI_DATAOUT; pdu.data_segment_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH / 2 - 4; to_be32(&data_reqh->data_sn, 1); to_be32(&data_reqh->buffer_offset, SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH / 2 - 4); rc = iscsi_pdu_hdr_handle(&conn, &pdu); CU_ASSERT(rc == 0); check_pdu_hdr_handle(&pdu, &mobj1, SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH / 2 - 4, &primary); rc = iscsi_pdu_payload_read(&conn, &pdu); CU_ASSERT(rc == 0); check_pdu_payload_read(&pdu, &mobj1, rc, 0, SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH / 2 - 4); rc = iscsi_pdu_payload_handle(&conn, &pdu); CU_ASSERT(rc == 0); check_pdu_payload_handle(&pdu, &primary, NULL, NULL, &mobj1, 0); /* The 3rd Data-OUT PDU */ memset(&pdu, 0, sizeof(pdu)); pdu.bhs.opcode = ISCSI_OP_SCSI_DATAOUT; pdu.data_segment_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH; to_be32(&data_reqh->data_sn, 2); to_be32(&data_reqh->buffer_offset, SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH - 8); rc = iscsi_pdu_hdr_handle(&conn, &pdu); CU_ASSERT(rc == 0); check_pdu_hdr_handle(&pdu, &mobj1, SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH - 8, &primary); rc = iscsi_pdu_payload_read(&conn, &pdu); CU_ASSERT(rc > 0); check_pdu_payload_read(&pdu, &mobj1, rc, 0, SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH - 8); MOCK_SET(spdk_mempool_get, &mobj2); rc = iscsi_pdu_payload_read(&conn, &pdu); CU_ASSERT(rc == 0); check_pdu_payload_read(&pdu, &mobj2, rc, 1, SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH); rc = iscsi_pdu_payload_handle(&conn, &pdu); CU_ASSERT(rc == 0); check_pdu_payload_handle(&pdu, &primary, &mobj1, NULL, &mobj2, SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH); check_write_subtask_submit(&lun, &mobj1, &pdu, 0, 0, SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH); /* The 4th and final Data-OUT PDU */ memset(&pdu, 0, sizeof(pdu)); pdu.bhs.opcode = ISCSI_OP_SCSI_DATAOUT; pdu.data_segment_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH / 2 + 8; data_reqh->flags |= ISCSI_FLAG_FINAL; to_be32(&data_reqh->data_sn, 3); to_be32(&data_reqh->buffer_offset, 2 * SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH - 8); rc = iscsi_pdu_hdr_handle(&conn, &pdu); CU_ASSERT(rc == 0); check_pdu_hdr_handle(&pdu, &mobj2, SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH - 8, &primary); rc = iscsi_pdu_payload_read(&conn, &pdu); CU_ASSERT(rc > 0); check_pdu_payload_read(&pdu, &mobj2, rc, 0, 2 * SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH - 8); MOCK_SET(spdk_mempool_get, &mobj3); rc = iscsi_pdu_payload_read(&conn, &pdu); CU_ASSERT(rc == 0); check_pdu_payload_read(&pdu, &mobj3, rc, 1, 2 * SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH); rc = iscsi_pdu_payload_handle(&conn, &pdu); CU_ASSERT(rc == 0); check_pdu_payload_handle(&pdu, &primary, &mobj2, &mobj3, NULL, 5 * SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH / 2); check_write_subtask_submit(&lun, &mobj2, &pdu, 0, SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH, SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH); check_write_subtask_submit(&lun, &mobj3, &pdu, 1, 2 * SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH, SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH / 2); CU_ASSERT(TAILQ_EMPTY(&lun.tasks)); MOCK_CLEAR(spdk_mempool_get); free(mobj1.buf); free(mobj2.buf); free(mobj3.buf); } static void immediate_data_and_data_out_pdu_sequence_test(void) { struct spdk_scsi_lun lun = { .tasks = TAILQ_HEAD_INITIALIZER(lun.tasks), }; struct spdk_scsi_dev dev = { .luns = TAILQ_HEAD_INITIALIZER(dev.luns), }; struct spdk_iscsi_sess sess = { .session_type = SESSION_TYPE_NORMAL, .MaxBurstLength = SPDK_ISCSI_MAX_BURST_LENGTH, .ImmediateData = true, .FirstBurstLength = SPDK_ISCSI_FIRST_BURST_LENGTH, }; struct spdk_iscsi_conn conn = { .full_feature = true, .state = ISCSI_CONN_STATE_RUNNING, .sess = &sess, .dev = &dev, .active_r2t_tasks = TAILQ_HEAD_INITIALIZER(conn.active_r2t_tasks), .ttt = 1, }; struct spdk_iscsi_pdu pdu = {}; struct spdk_mobj mobj = {}; struct spdk_iscsi_task *primary; struct iscsi_bhs_scsi_req *scsi_reqh; struct iscsi_bhs_data_out *data_reqh; int rc; TAILQ_INSERT_TAIL(&dev.luns, &lun, tailq); alloc_mock_mobj(&mobj, SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH); /* Test scenario is as follows. * * Some iSCSI initiator sends an immediate data and more solicited data * through R2T within the same SCSI write such that the size of the data * segment of a SCSI Write PDU or any Data-OUT PDU is not block size multiples. * Test if such complex SCSI write is processed correctly. * * Desired Data Transfer Length of a SCSI Write is 65536. * PDU sequences are: * Host sent SCSI Write with 5792 bytes and F = 1 * Target sent a R2T * Host sent Data-OUT with 15880 bytes * Host sent Data-OUT with 11536 bytes * Host sent Data-OUT with 2848 bytes * Host sent Data-OUT with 11536 bytes * Host sent Data-OUT with 5744 bytes * Host sent Data-OUT with 12200 bytes and F = 1 * * One data buffer should be used and one subtask should be created and submitted. * * The test scenario assume that a iscsi_conn_read_data() call could read * the required length of the data and all read lengths are 4 bytes multiples. * The latter is to verify data is copied to the correct offset by using data patterns. */ g_conn_read_len = 0; /* SCSI Write PDU with immediate data */ scsi_reqh = (struct iscsi_bhs_scsi_req *)&pdu.bhs; scsi_reqh->opcode = ISCSI_OP_SCSI; scsi_reqh->write_bit = 1; scsi_reqh->final_bit = 1; pdu.data_segment_len = 5792; to_be32(&scsi_reqh->expected_data_xfer_len, 65536); rc = iscsi_pdu_hdr_handle(&conn, &pdu); CU_ASSERT(rc == 0); primary = pdu.task; SPDK_CU_ASSERT_FATAL(primary != NULL); CU_ASSERT(primary->scsi.transfer_len == 65536); CU_ASSERT(primary->scsi.dxfer_dir == SPDK_SCSI_DIR_TO_DEV); CU_ASSERT(pdu.data_buf_len == 65536); MOCK_SET(spdk_mempool_get, &mobj); rc = iscsi_pdu_payload_read(&conn, &pdu); CU_ASSERT(rc == 0); check_pdu_payload_read(&pdu, &mobj, rc, 0, 0); rc = iscsi_pdu_payload_handle(&conn, &pdu); CU_ASSERT(rc == 0); CU_ASSERT(primary->next_expected_r2t_offset == 5792); CU_ASSERT(primary->current_r2t_length == 0); CU_ASSERT(primary->next_r2t_offset == 65536); CU_ASSERT(primary->ttt == 2); CU_ASSERT(primary == TAILQ_FIRST(&conn.active_r2t_tasks)); check_pdu_payload_handle(&pdu, primary, NULL, NULL, &mobj, 0); data_reqh = (struct iscsi_bhs_data_out *)&pdu.bhs; /* The 1st Data-OUT PDU */ memset(&pdu, 0, sizeof(pdu)); data_reqh->opcode = ISCSI_OP_SCSI_DATAOUT; to_be32(&data_reqh->ttt, 2); to_be32(&data_reqh->buffer_offset, 5792); pdu.data_segment_len = 15880; rc = iscsi_pdu_hdr_handle(&conn, &pdu); CU_ASSERT(rc == 0); check_pdu_hdr_handle(&pdu, &mobj, 5792, primary); rc = iscsi_pdu_payload_read(&conn, &pdu); CU_ASSERT(rc == 0); check_pdu_payload_read(&pdu, &mobj, rc, 0, 5792); rc = iscsi_pdu_payload_handle(&conn, &pdu); CU_ASSERT(rc == 0); check_pdu_payload_handle(&pdu, primary, NULL, NULL, &mobj, 0); /* The 2nd Data-OUT PDU */ memset(&pdu, 0, sizeof(pdu)); data_reqh->opcode = ISCSI_OP_SCSI_DATAOUT; to_be32(&data_reqh->ttt, 2); to_be32(&data_reqh->buffer_offset, 21672); to_be32(&data_reqh->data_sn, 1); pdu.data_segment_len = 11536; rc = iscsi_pdu_hdr_handle(&conn, &pdu); CU_ASSERT(rc == 0); check_pdu_hdr_handle(&pdu, &mobj, 21672, primary); rc = iscsi_pdu_payload_read(&conn, &pdu); CU_ASSERT(rc == 0); check_pdu_payload_read(&pdu, &mobj, rc, 0, 21672); rc = iscsi_pdu_payload_handle(&conn, &pdu); CU_ASSERT(rc == 0); check_pdu_payload_handle(&pdu, primary, NULL, NULL, &mobj, 0); /* The 3rd Data-OUT PDU */ memset(&pdu, 0, sizeof(pdu)); data_reqh->opcode = ISCSI_OP_SCSI_DATAOUT; to_be32(&data_reqh->ttt, 2); to_be32(&data_reqh->buffer_offset, 33208); to_be32(&data_reqh->data_sn, 2); pdu.data_segment_len = 2848; rc = iscsi_pdu_hdr_handle(&conn, &pdu); CU_ASSERT(rc == 0); check_pdu_hdr_handle(&pdu, &mobj, 33208, primary); rc = iscsi_pdu_payload_read(&conn, &pdu); CU_ASSERT(rc == 0); check_pdu_payload_read(&pdu, &mobj, rc, 0, 33208); rc = iscsi_pdu_payload_handle(&conn, &pdu); CU_ASSERT(rc == 0); check_pdu_payload_handle(&pdu, primary, NULL, NULL, &mobj, 0); /* The 4th Data-OUT PDU */ memset(&pdu, 0, sizeof(pdu)); data_reqh->opcode = ISCSI_OP_SCSI_DATAOUT; to_be32(&data_reqh->ttt, 2); to_be32(&data_reqh->buffer_offset, 36056); to_be32(&data_reqh->data_sn, 3); pdu.data_segment_len = 11536; rc = iscsi_pdu_hdr_handle(&conn, &pdu); CU_ASSERT(rc == 0); check_pdu_hdr_handle(&pdu, &mobj, 36056, primary); rc = iscsi_pdu_payload_read(&conn, &pdu); CU_ASSERT(rc == 0); check_pdu_payload_read(&pdu, &mobj, rc, 0, 36056); rc = iscsi_pdu_payload_handle(&conn, &pdu); CU_ASSERT(rc == 0); check_pdu_payload_handle(&pdu, primary, NULL, NULL, &mobj, 0); /* The 5th Data-OUT PDU */ memset(&pdu, 0, sizeof(pdu)); data_reqh->opcode = ISCSI_OP_SCSI_DATAOUT; to_be32(&data_reqh->ttt, 2); to_be32(&data_reqh->buffer_offset, 47592); to_be32(&data_reqh->data_sn, 4); pdu.data_segment_len = 5744; rc = iscsi_pdu_hdr_handle(&conn, &pdu); CU_ASSERT(rc == 0); check_pdu_hdr_handle(&pdu, &mobj, 47592, primary); rc = iscsi_pdu_payload_read(&conn, &pdu); CU_ASSERT(rc == 0); check_pdu_payload_read(&pdu, &mobj, rc, 0, 47592); rc = iscsi_pdu_payload_handle(&conn, &pdu); CU_ASSERT(rc == 0); check_pdu_payload_handle(&pdu, primary, NULL, NULL, &mobj, 0); /* The 6th and final Data-OUT PDU */ memset(&pdu, 0, sizeof(pdu)); pdu.bhs.opcode = ISCSI_OP_SCSI_DATAOUT; data_reqh->flags |= ISCSI_FLAG_FINAL; to_be32(&data_reqh->ttt, 2); to_be32(&data_reqh->buffer_offset, 53336); to_be32(&data_reqh->data_sn, 5); pdu.data_segment_len = 12200; rc = iscsi_pdu_hdr_handle(&conn, &pdu); CU_ASSERT(rc == 0); check_pdu_hdr_handle(&pdu, &mobj, 53336, primary); rc = iscsi_pdu_payload_read(&conn, &pdu); CU_ASSERT(rc == 0); check_pdu_payload_read(&pdu, &mobj, rc, 0, 53336); rc = iscsi_pdu_payload_handle(&conn, &pdu); CU_ASSERT(rc == 0); check_pdu_payload_handle(&pdu, primary, &mobj, NULL, NULL, 65536); check_write_subtask_submit(&lun, &mobj, &pdu, 0, 0, 65536); CU_ASSERT(TAILQ_EMPTY(&lun.tasks)); MOCK_CLEAR(spdk_mempool_get); free(primary); free(mobj.buf); } int main(int argc, char **argv) { CU_pSuite suite = NULL; unsigned int num_failures; CU_initialize_registry(); suite = CU_add_suite("iscsi_suite", NULL, NULL); CU_ADD_TEST(suite, op_login_check_target_test); CU_ADD_TEST(suite, op_login_session_normal_test); CU_ADD_TEST(suite, maxburstlength_test); CU_ADD_TEST(suite, underflow_for_read_transfer_test); CU_ADD_TEST(suite, underflow_for_zero_read_transfer_test); CU_ADD_TEST(suite, underflow_for_request_sense_test); CU_ADD_TEST(suite, underflow_for_check_condition_test); CU_ADD_TEST(suite, add_transfer_task_test); CU_ADD_TEST(suite, get_transfer_task_test); CU_ADD_TEST(suite, del_transfer_task_test); CU_ADD_TEST(suite, clear_all_transfer_tasks_test); CU_ADD_TEST(suite, build_iovs_test); CU_ADD_TEST(suite, build_iovs_with_md_test); CU_ADD_TEST(suite, pdu_hdr_op_login_test); CU_ADD_TEST(suite, pdu_hdr_op_text_test); CU_ADD_TEST(suite, pdu_hdr_op_logout_test); CU_ADD_TEST(suite, pdu_hdr_op_scsi_test); CU_ADD_TEST(suite, pdu_hdr_op_task_mgmt_test); CU_ADD_TEST(suite, pdu_hdr_op_nopout_test); CU_ADD_TEST(suite, pdu_hdr_op_data_test); CU_ADD_TEST(suite, empty_text_with_cbit_test); CU_ADD_TEST(suite, pdu_payload_read_test); CU_ADD_TEST(suite, data_out_pdu_sequence_test); CU_ADD_TEST(suite, immediate_data_and_data_out_pdu_sequence_test); num_failures = spdk_ut_run_tests(argc, argv, NULL); CU_cleanup_registry(); return num_failures; }
3726e6325b8c92014648723e035ff5a3a5cd7511
e7df6d41d7e04dc1c4f4ed169bf530a8a89ff17c
/OpenSim/Utilities/simmToOpenSim/wefunctions.h
d92165b496418b7e540fd36b5ead7bb3cbbc5422
[ "Apache-2.0" ]
permissive
opensim-org/opensim-core
2ba11c815df3072166644af2f34770162d8fc467
aeaaf93b052d598247dd7d7922fdf8f2f2f4c0bb
refs/heads/main
2023-09-04T05:50:54.783630
2023-09-01T22:44:04
2023-09-01T22:44:04
20,775,600
701
328
Apache-2.0
2023-09-14T17:45:19
2014-06-12T16:57:56
C++
UTF-8
C
false
false
4,462
h
wefunctions.h
/******************************************************************************* WEFUNCTIONS.H - this header declares the Wrap Editor's public functions as well as the 3 wrapping algorithm public functions: calc_line_intersect_ellipsoid calc_line_intersect_cylinder calc_line_intersect_sphere Author: Kenny Smith (based on pmfunctions.h by Peter Loan) Date: 22-OCT-98 Copyright (c) 1998 MusculoGraphics, Inc. All rights reserved. Portions of this source code are copyrighted by MusculoGraphics, Inc. *******************************************************************************/ #ifndef WEFUNCTIONS_H #define WEFUNCTIONS_H void makewrapeditormenus(void); void we_entervalue(SimmEvent se); void update_we_forms(void); void move_we_help_text(int dummy_int, double slider_value, double delta); void we_track_cb(void* data, SimmEvent se); void inval_model_wrapping(ModelStruct* model, dpWrapObject* wrap_object); int get_wrap_object_index(ModelStruct* model, dpWrapObject* wrap_object); int is_current_wrap_object(ModelStruct*, dpWrapObject*); void select_wrapping_object(int wrapobj, SBoolean redisplay); void convert_to_wrap_object_frame(dpWrapObject*, double* pt); void convert_from_wrap_object_frame(dpWrapObject*, double* pt); void reset_wrapobj_xform(); void recalc_xforms(dpWrapObject*); void apply_xform_to_wrapobj(double factor); void clear_we_xform_form(); void save_all_wrap_objects(ModelStruct* ms); SBoolean query_muscle_wrap_association(dpMuscleStruct* muscle, dpWrapObject* wrap_object); void add_muscle_wrap_association(dpMuscleStruct* muscle, MuscWrapAssoc* mwa, dpWrapObject* wrap_object); void remove_muscle_wrap_association(dpMuscleStruct* muscle, dpWrapObject* wrap_object); void update_we_win_status(); #define VISUAL_WRAPPING_DEBUG 0 #define USER_SPECIFIED_WRAP_METHOD 1 /* wrapping algorithms */ #define WE_HYBRID_ALGORITHM 0 /* Frans + fan algorithm */ #define WE_MIDPOINT_ALGORITHM 1 /* midpoint algorithm */ #define WE_AXIAL_ALGORITHM 2 /* Frans only algorithm */ #define WE_NUM_WRAP_ALGORITHMS 3 #define WE_FAN_ALGORITHM 4 /* fan only algorithm */ const char* get_wrap_type_name (int i); const char* get_wrap_algorithm_name(int wrap_algorithm); int calc_line_intersect_ellipsoid(double p1[], double p2[], double m[], double a[], double *rlen, double r1[], double r2[], double** wrap_pts, int *num_wrap_pts, int wrap_axis, int wrap_sign, dpMuscleWrapStruct*, int* p_flag, dpWrapObject*); int calc_line_intersect_cylinder(double p1[], double p2[], double p0[], double dn[], double r, double len, double *rlen, double r1[], double r2[], double** wrap_pts, int *num_wrap_pts, int wrap_axis, int wrap_sign, dpMuscleWrapStruct*, int* p_flag, dpWrapObject*); int calc_line_intersect_sphere(double p1[], double p2[], double m[], double r, double *rlen, double r1[], double r2[], double** wrap_pts, int *num_wrap_pts, int wrap_axis, int wrap_sign, dpMuscleWrapStruct*, int* p_flag, dpWrapObject*); int calc_line_intersect_torus(double p1[], double p2[], double m[], double a[], double *rlen, double r1[], double r2[], double** wrap_pts, int *num_wrap_pts, int wrap_axis, int wrap_sign, dpMuscleWrapStruct*, int* p_flag, dpWrapObject*); void enable_debug_shapes(SBoolean); #if VISUAL_WRAPPING_DEBUG void add_debug_point( dpWrapObject* wo, double factor, double pt[], float radius, const char* name, const float* color); void add_debug_line( dpWrapObject* wo, double factor, double pt1[], double pt2[], float lineWidth, const char* name1, const char* name2, const float* color); float* lerp_clr(const float start[3], const float end[3], double t, float color[3]); #endif /* VISUAL_WRAPPING_DEBUG */ #endif /* WEFUNCTIONS_H */
fd6d0db0189ee7edee20c08fc92234de0a005b65
99bdb3251fecee538e0630f15f6574054dfc1468
/bsp/at32/libraries/AT32F435_437_Firmware_Library/drivers/inc/at32f435_437_crm.h
5358d720d38e92abf45c7135850007262fee0820
[ "Apache-2.0", "Zlib", "LicenseRef-scancode-proprietary-license", "MIT", "BSD-3-Clause", "X11", "BSD-4-Clause-UC", "LicenseRef-scancode-unknown-license-reference" ]
permissive
RT-Thread/rt-thread
03a7c52c2aeb1b06a544143b0e803d72f47d1ece
3602f891211904a27dcbd51e5ba72fefce7326b2
refs/heads/master
2023-09-01T04:10:20.295801
2023-08-31T16:20:55
2023-08-31T16:20:55
7,408,108
9,599
5,805
Apache-2.0
2023-09-14T13:37:26
2013-01-02T14:49:21
C
UTF-8
C
false
false
82,352
h
at32f435_437_crm.h
/** ************************************************************************** * @file at32f435_437_crm.h * @version v2.0.8 * @date 2022-04-25 * @brief at32f435_437 crm header file ************************************************************************** * Copyright notice & Disclaimer * * The software Board Support Package (BSP) that is made available to * download from Artery official website is the copyrighted work of Artery. * Artery authorizes customers to use, copy, and distribute the BSP * software and its related documentation for the purpose of design and * development in conjunction with Artery microcontrollers. Use of the * software is governed by this copyright notice and the following disclaimer. * * THIS SOFTWARE IS PROVIDED ON "AS IS" BASIS WITHOUT WARRANTIES, * GUARANTEES OR REPRESENTATIONS OF ANY KIND. ARTERY EXPRESSLY DISCLAIMS, * TO THE FULLEST EXTENT PERMITTED BY LAW, ALL EXPRESS, IMPLIED OR * STATUTORY OR OTHER WARRANTIES, GUARANTEES OR REPRESENTATIONS, * INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. * ************************************************************************** */ /* define to prevent recursive inclusion -------------------------------------*/ #ifndef __AT32F435_437_CRM_H #define __AT32F435_437_CRM_H #ifdef __cplusplus extern "C" { #endif /* includes ------------------------------------------------------------------*/ #include "at32f435_437.h" /** @addtogroup AT32F435_437_periph_driver * @{ */ /** @addtogroup CRM * @{ */ #define CRM_REG(value) PERIPH_REG(CRM_BASE, value) #define CRM_REG_BIT(value) PERIPH_REG_BIT(value) /** @defgroup CRM_flags_definition * @brief crm flag * @{ */ #define CRM_HICK_STABLE_FLAG MAKE_VALUE(0x00, 1) /*!< high speed internal clock stable flag */ #define CRM_HEXT_STABLE_FLAG MAKE_VALUE(0x00, 17) /*!< high speed external crystal stable flag */ #define CRM_PLL_STABLE_FLAG MAKE_VALUE(0x00, 25) /*!< phase locking loop stable flag */ #define CRM_LEXT_STABLE_FLAG MAKE_VALUE(0x70, 1) /*!< low speed external crystal stable flag */ #define CRM_LICK_STABLE_FLAG MAKE_VALUE(0x74, 1) /*!< low speed internal clock stable flag */ #define CRM_ALL_RESET_FLAG MAKE_VALUE(0x74, 24) /*!< all reset flag */ #define CRM_NRST_RESET_FLAG MAKE_VALUE(0x74, 26) /*!< nrst pin reset flag */ #define CRM_POR_RESET_FLAG MAKE_VALUE(0x74, 27) /*!< power on reset flag */ #define CRM_SW_RESET_FLAG MAKE_VALUE(0x74, 28) /*!< software reset flag */ #define CRM_WDT_RESET_FLAG MAKE_VALUE(0x74, 29) /*!< watchdog timer reset flag */ #define CRM_WWDT_RESET_FLAG MAKE_VALUE(0x74, 30) /*!< window watchdog timer reset flag */ #define CRM_LOWPOWER_RESET_FLAG MAKE_VALUE(0x74, 31) /*!< low-power reset flag */ #define CRM_LICK_READY_INT_FLAG MAKE_VALUE(0x0C, 0) /*!< low speed internal clock stable interrupt ready flag */ #define CRM_LEXT_READY_INT_FLAG MAKE_VALUE(0x0C, 1) /*!< low speed external crystal stable interrupt ready flag */ #define CRM_HICK_READY_INT_FLAG MAKE_VALUE(0x0C, 2) /*!< high speed internal clock stable interrupt ready flag */ #define CRM_HEXT_READY_INT_FLAG MAKE_VALUE(0x0C, 3) /*!< high speed external crystal stable interrupt ready flag */ #define CRM_PLL_READY_INT_FLAG MAKE_VALUE(0x0C, 4) /*!< phase locking loop stable interrupt ready flag */ #define CRM_CLOCK_FAILURE_INT_FLAG MAKE_VALUE(0x0C, 7) /*!< clock failure interrupt ready flag */ /** * @} */ /** @defgroup CRM_interrupts_definition * @brief crm interrupt * @{ */ #define CRM_LICK_STABLE_INT ((uint32_t)0x00000100) /*!< low speed internal clock stable interrupt */ #define CRM_LEXT_STABLE_INT ((uint32_t)0x00000200) /*!< low speed external crystal stable interrupt */ #define CRM_HICK_STABLE_INT ((uint32_t)0x00000400) /*!< high speed internal clock stable interrupt */ #define CRM_HEXT_STABLE_INT ((uint32_t)0x00000800) /*!< high speed external crystal stable interrupt */ #define CRM_PLL_STABLE_INT ((uint32_t)0x00001000) /*!< phase locking loop stable interrupt */ #define CRM_CLOCK_FAILURE_INT ((uint32_t)0x00800000) /*!< clock failure interrupt */ /** * @} */ /** @defgroup CRM_exported_types * @{ */ /** * @brief crm periph clock */ typedef enum { #if defined (AT32F435xx) /* ahb periph1 */ CRM_GPIOA_PERIPH_CLOCK = MAKE_VALUE(0x30, 0), /*!< gpioa periph clock */ CRM_GPIOB_PERIPH_CLOCK = MAKE_VALUE(0x30, 1), /*!< gpiob periph clock */ CRM_GPIOC_PERIPH_CLOCK = MAKE_VALUE(0x30, 2), /*!< gpioc periph clock */ CRM_GPIOD_PERIPH_CLOCK = MAKE_VALUE(0x30, 3), /*!< gpiod periph clock */ CRM_GPIOE_PERIPH_CLOCK = MAKE_VALUE(0x30, 4), /*!< gpioe periph clock */ CRM_GPIOF_PERIPH_CLOCK = MAKE_VALUE(0x30, 5), /*!< gpiof periph clock */ CRM_GPIOG_PERIPH_CLOCK = MAKE_VALUE(0x30, 6), /*!< gpiog periph clock */ CRM_GPIOH_PERIPH_CLOCK = MAKE_VALUE(0x30, 7), /*!< gpioh periph clock */ CRM_CRC_PERIPH_CLOCK = MAKE_VALUE(0x30, 12), /*!< crc periph clock */ CRM_EDMA_PERIPH_CLOCK = MAKE_VALUE(0x30, 21), /*!< edma periph clock */ CRM_DMA1_PERIPH_CLOCK = MAKE_VALUE(0x30, 22), /*!< dma1 periph clock */ CRM_DMA2_PERIPH_CLOCK = MAKE_VALUE(0x30, 24), /*!< dma2 periph clock */ CRM_OTGFS2_PERIPH_CLOCK = MAKE_VALUE(0x30, 29), /*!< otgfs2 periph clock */ /* ahb periph2 */ CRM_DVP_PERIPH_CLOCK = MAKE_VALUE(0x34, 0), /*!< dvp periph clock */ CRM_OTGFS1_PERIPH_CLOCK = MAKE_VALUE(0x34, 7), /*!< otgfs1 periph clock */ CRM_SDIO1_PERIPH_CLOCK = MAKE_VALUE(0x34, 15), /*!< sdio1 periph clock */ /* ahb periph3 */ CRM_XMC_PERIPH_CLOCK = MAKE_VALUE(0x38, 0), /*!< xmc periph clock */ CRM_QSPI1_PERIPH_CLOCK = MAKE_VALUE(0x38, 1), /*!< qspi1 periph clock */ CRM_QSPI2_PERIPH_CLOCK = MAKE_VALUE(0x38, 14), /*!< qspi2 periph clock */ CRM_SDIO2_PERIPH_CLOCK = MAKE_VALUE(0x38, 15), /*!< sdio2 periph clock */ /* apb1 periph */ CRM_TMR2_PERIPH_CLOCK = MAKE_VALUE(0x40, 0), /*!< tmr2 periph clock */ CRM_TMR3_PERIPH_CLOCK = MAKE_VALUE(0x40, 1), /*!< tmr3 periph clock */ CRM_TMR4_PERIPH_CLOCK = MAKE_VALUE(0x40, 2), /*!< tmr4 periph clock */ CRM_TMR5_PERIPH_CLOCK = MAKE_VALUE(0x40, 3), /*!< tmr5 periph clock */ CRM_TMR6_PERIPH_CLOCK = MAKE_VALUE(0x40, 4), /*!< tmr6 periph clock */ CRM_TMR7_PERIPH_CLOCK = MAKE_VALUE(0x40, 5), /*!< tmr7 periph clock */ CRM_TMR12_PERIPH_CLOCK = MAKE_VALUE(0x40, 6), /*!< tmr12 periph clock */ CRM_TMR13_PERIPH_CLOCK = MAKE_VALUE(0x40, 7), /*!< tmr13 periph clock */ CRM_TMR14_PERIPH_CLOCK = MAKE_VALUE(0x40, 8), /*!< tmr14 periph clock */ CRM_WWDT_PERIPH_CLOCK = MAKE_VALUE(0x40, 11), /*!< wwdt periph clock */ CRM_SPI2_PERIPH_CLOCK = MAKE_VALUE(0x40, 14), /*!< spi2 periph clock */ CRM_SPI3_PERIPH_CLOCK = MAKE_VALUE(0x40, 15), /*!< spi3 periph clock */ CRM_USART2_PERIPH_CLOCK = MAKE_VALUE(0x40, 17), /*!< usart2 periph clock */ CRM_USART3_PERIPH_CLOCK = MAKE_VALUE(0x40, 18), /*!< usart3 periph clock */ CRM_UART4_PERIPH_CLOCK = MAKE_VALUE(0x40, 19), /*!< uart4 periph clock */ CRM_UART5_PERIPH_CLOCK = MAKE_VALUE(0x40, 20), /*!< uart5 periph clock */ CRM_I2C1_PERIPH_CLOCK = MAKE_VALUE(0x40, 21), /*!< i2c1 periph clock */ CRM_I2C2_PERIPH_CLOCK = MAKE_VALUE(0x40, 22), /*!< i2c2 periph clock */ CRM_I2C3_PERIPH_CLOCK = MAKE_VALUE(0x40, 23), /*!< i2c3 periph clock */ CRM_CAN1_PERIPH_CLOCK = MAKE_VALUE(0x40, 25), /*!< can1 periph clock */ CRM_CAN2_PERIPH_CLOCK = MAKE_VALUE(0x40, 26), /*!< can2 periph clock */ CRM_PWC_PERIPH_CLOCK = MAKE_VALUE(0x40, 28), /*!< pwc periph clock */ CRM_DAC_PERIPH_CLOCK = MAKE_VALUE(0x40, 29), /*!< dac periph clock */ CRM_UART7_PERIPH_CLOCK = MAKE_VALUE(0x40, 30), /*!< uart7 periph clock */ CRM_UART8_PERIPH_CLOCK = MAKE_VALUE(0x40, 31), /*!< uart8 periph clock */ /* apb2 periph */ CRM_TMR1_PERIPH_CLOCK = MAKE_VALUE(0x44, 0), /*!< tmr1 periph clock */ CRM_TMR8_PERIPH_CLOCK = MAKE_VALUE(0x44, 1), /*!< tmr8 periph clock */ CRM_USART1_PERIPH_CLOCK = MAKE_VALUE(0x44, 4), /*!< usart1 periph clock */ CRM_USART6_PERIPH_CLOCK = MAKE_VALUE(0x44, 5), /*!< usart6 periph clock */ CRM_ADC1_PERIPH_CLOCK = MAKE_VALUE(0x44, 8), /*!< adc1 periph clock */ CRM_ADC2_PERIPH_CLOCK = MAKE_VALUE(0x44, 9), /*!< adc2 periph clock */ CRM_ADC3_PERIPH_CLOCK = MAKE_VALUE(0x44, 10), /*!< adc3 periph clock */ CRM_SPI1_PERIPH_CLOCK = MAKE_VALUE(0x44, 12), /*!< spi1 periph clock */ CRM_SPI4_PERIPH_CLOCK = MAKE_VALUE(0x44, 13), /*!< spi4 periph clock */ CRM_SCFG_PERIPH_CLOCK = MAKE_VALUE(0x44, 14), /*!< scfg periph clock */ CRM_TMR9_PERIPH_CLOCK = MAKE_VALUE(0x44, 16), /*!< tmr9 periph clock */ CRM_TMR10_PERIPH_CLOCK = MAKE_VALUE(0x44, 17), /*!< tmr10 periph clock */ CRM_TMR11_PERIPH_CLOCK = MAKE_VALUE(0x44, 18), /*!< tmr11 periph clock */ CRM_TMR20_PERIPH_CLOCK = MAKE_VALUE(0x44, 20), /*!< tmr20 periph clock */ CRM_ACC_PERIPH_CLOCK = MAKE_VALUE(0x44, 29) /*!< acc periph clock */ #endif #if defined (AT32F437xx) /* ahb periph1 */ CRM_GPIOA_PERIPH_CLOCK = MAKE_VALUE(0x30, 0), /*!< gpioa periph clock */ CRM_GPIOB_PERIPH_CLOCK = MAKE_VALUE(0x30, 1), /*!< gpiob periph clock */ CRM_GPIOC_PERIPH_CLOCK = MAKE_VALUE(0x30, 2), /*!< gpioc periph clock */ CRM_GPIOD_PERIPH_CLOCK = MAKE_VALUE(0x30, 3), /*!< gpiod periph clock */ CRM_GPIOE_PERIPH_CLOCK = MAKE_VALUE(0x30, 4), /*!< gpioe periph clock */ CRM_GPIOF_PERIPH_CLOCK = MAKE_VALUE(0x30, 5), /*!< gpiof periph clock */ CRM_GPIOG_PERIPH_CLOCK = MAKE_VALUE(0x30, 6), /*!< gpiog periph clock */ CRM_GPIOH_PERIPH_CLOCK = MAKE_VALUE(0x30, 7), /*!< gpioh periph clock */ CRM_CRC_PERIPH_CLOCK = MAKE_VALUE(0x30, 12), /*!< crc periph clock */ CRM_EDMA_PERIPH_CLOCK = MAKE_VALUE(0x30, 21), /*!< edma periph clock */ CRM_DMA1_PERIPH_CLOCK = MAKE_VALUE(0x30, 22), /*!< dma1 periph clock */ CRM_DMA2_PERIPH_CLOCK = MAKE_VALUE(0x30, 24), /*!< dma2 periph clock */ CRM_EMAC_PERIPH_CLOCK = MAKE_VALUE(0x30, 25), /*!< emac periph clock */ CRM_EMACTX_PERIPH_CLOCK = MAKE_VALUE(0x30, 26), /*!< emac tx periph clock */ CRM_EMACRX_PERIPH_CLOCK = MAKE_VALUE(0x30, 27), /*!< emac rx periph clock */ CRM_EMACPTP_PERIPH_CLOCK = MAKE_VALUE(0x30, 28), /*!< emac ptp periph clock */ CRM_OTGFS2_PERIPH_CLOCK = MAKE_VALUE(0x30, 29), /*!< otgfs2 periph clock */ /* ahb periph2 */ CRM_DVP_PERIPH_CLOCK = MAKE_VALUE(0x34, 0), /*!< dvp periph clock */ CRM_OTGFS1_PERIPH_CLOCK = MAKE_VALUE(0x34, 7), /*!< otgfs1 periph clock */ CRM_SDIO1_PERIPH_CLOCK = MAKE_VALUE(0x34, 15), /*!< sdio1 periph clock */ /* ahb periph3 */ CRM_XMC_PERIPH_CLOCK = MAKE_VALUE(0x38, 0), /*!< xmc periph clock */ CRM_QSPI1_PERIPH_CLOCK = MAKE_VALUE(0x38, 1), /*!< qspi1 periph clock */ CRM_QSPI2_PERIPH_CLOCK = MAKE_VALUE(0x38, 14), /*!< qspi2 periph clock */ CRM_SDIO2_PERIPH_CLOCK = MAKE_VALUE(0x38, 15), /*!< sdio2 periph clock */ /* apb1 periph */ CRM_TMR2_PERIPH_CLOCK = MAKE_VALUE(0x40, 0), /*!< tmr2 periph clock */ CRM_TMR3_PERIPH_CLOCK = MAKE_VALUE(0x40, 1), /*!< tmr3 periph clock */ CRM_TMR4_PERIPH_CLOCK = MAKE_VALUE(0x40, 2), /*!< tmr4 periph clock */ CRM_TMR5_PERIPH_CLOCK = MAKE_VALUE(0x40, 3), /*!< tmr5 periph clock */ CRM_TMR6_PERIPH_CLOCK = MAKE_VALUE(0x40, 4), /*!< tmr6 periph clock */ CRM_TMR7_PERIPH_CLOCK = MAKE_VALUE(0x40, 5), /*!< tmr7 periph clock */ CRM_TMR12_PERIPH_CLOCK = MAKE_VALUE(0x40, 6), /*!< tmr12 periph clock */ CRM_TMR13_PERIPH_CLOCK = MAKE_VALUE(0x40, 7), /*!< tmr13 periph clock */ CRM_TMR14_PERIPH_CLOCK = MAKE_VALUE(0x40, 8), /*!< tmr14 periph clock */ CRM_WWDT_PERIPH_CLOCK = MAKE_VALUE(0x40, 11), /*!< wwdt periph clock */ CRM_SPI2_PERIPH_CLOCK = MAKE_VALUE(0x40, 14), /*!< spi2 periph clock */ CRM_SPI3_PERIPH_CLOCK = MAKE_VALUE(0x40, 15), /*!< spi3 periph clock */ CRM_USART2_PERIPH_CLOCK = MAKE_VALUE(0x40, 17), /*!< usart2 periph clock */ CRM_USART3_PERIPH_CLOCK = MAKE_VALUE(0x40, 18), /*!< usart3 periph clock */ CRM_UART4_PERIPH_CLOCK = MAKE_VALUE(0x40, 19), /*!< uart4 periph clock */ CRM_UART5_PERIPH_CLOCK = MAKE_VALUE(0x40, 20), /*!< uart5 periph clock */ CRM_I2C1_PERIPH_CLOCK = MAKE_VALUE(0x40, 21), /*!< i2c1 periph clock */ CRM_I2C2_PERIPH_CLOCK = MAKE_VALUE(0x40, 22), /*!< i2c2 periph clock */ CRM_I2C3_PERIPH_CLOCK = MAKE_VALUE(0x40, 23), /*!< i2c3 periph clock */ CRM_CAN1_PERIPH_CLOCK = MAKE_VALUE(0x40, 25), /*!< can1 periph clock */ CRM_CAN2_PERIPH_CLOCK = MAKE_VALUE(0x40, 26), /*!< can2 periph clock */ CRM_PWC_PERIPH_CLOCK = MAKE_VALUE(0x40, 28), /*!< pwc periph clock */ CRM_DAC_PERIPH_CLOCK = MAKE_VALUE(0x40, 29), /*!< dac periph clock */ CRM_UART7_PERIPH_CLOCK = MAKE_VALUE(0x40, 30), /*!< uart7 periph clock */ CRM_UART8_PERIPH_CLOCK = MAKE_VALUE(0x40, 31), /*!< uart8 periph clock */ /* apb2 periph */ CRM_TMR1_PERIPH_CLOCK = MAKE_VALUE(0x44, 0), /*!< tmr1 periph clock */ CRM_TMR8_PERIPH_CLOCK = MAKE_VALUE(0x44, 1), /*!< tmr8 periph clock */ CRM_USART1_PERIPH_CLOCK = MAKE_VALUE(0x44, 4), /*!< usart1 periph clock */ CRM_USART6_PERIPH_CLOCK = MAKE_VALUE(0x44, 5), /*!< usart6 periph clock */ CRM_ADC1_PERIPH_CLOCK = MAKE_VALUE(0x44, 8), /*!< adc1 periph clock */ CRM_ADC2_PERIPH_CLOCK = MAKE_VALUE(0x44, 9), /*!< adc2 periph clock */ CRM_ADC3_PERIPH_CLOCK = MAKE_VALUE(0x44, 10), /*!< adc3 periph clock */ CRM_SPI1_PERIPH_CLOCK = MAKE_VALUE(0x44, 12), /*!< spi1 periph clock */ CRM_SPI4_PERIPH_CLOCK = MAKE_VALUE(0x44, 13), /*!< spi4 periph clock */ CRM_SCFG_PERIPH_CLOCK = MAKE_VALUE(0x44, 14), /*!< scfg periph clock */ CRM_TMR9_PERIPH_CLOCK = MAKE_VALUE(0x44, 16), /*!< tmr9 periph clock */ CRM_TMR10_PERIPH_CLOCK = MAKE_VALUE(0x44, 17), /*!< tmr10 periph clock */ CRM_TMR11_PERIPH_CLOCK = MAKE_VALUE(0x44, 18), /*!< tmr11 periph clock */ CRM_TMR20_PERIPH_CLOCK = MAKE_VALUE(0x44, 20), /*!< tmr20 periph clock */ CRM_ACC_PERIPH_CLOCK = MAKE_VALUE(0x44, 29) /*!< acc periph clock */ #endif } crm_periph_clock_type; /** * @brief crm periph reset */ typedef enum { #if defined (AT32F435xx) /* ahb periph1 */ CRM_GPIOA_PERIPH_RESET = MAKE_VALUE(0x10, 0), /*!< gpioa periph reset */ CRM_GPIOB_PERIPH_RESET = MAKE_VALUE(0x10, 1), /*!< gpiob periph reset */ CRM_GPIOC_PERIPH_RESET = MAKE_VALUE(0x10, 2), /*!< gpioc periph reset */ CRM_GPIOD_PERIPH_RESET = MAKE_VALUE(0x10, 3), /*!< gpiod periph reset */ CRM_GPIOE_PERIPH_RESET = MAKE_VALUE(0x10, 4), /*!< gpioe periph reset */ CRM_GPIOF_PERIPH_RESET = MAKE_VALUE(0x10, 5), /*!< gpiof periph reset */ CRM_GPIOG_PERIPH_RESET = MAKE_VALUE(0x10, 6), /*!< gpiog periph reset */ CRM_GPIOH_PERIPH_RESET = MAKE_VALUE(0x10, 7), /*!< gpioh periph reset */ CRM_CRC_PERIPH_RESET = MAKE_VALUE(0x10, 12), /*!< crc periph reset */ CRM_EDMA_PERIPH_RESET = MAKE_VALUE(0x10, 21), /*!< edma periph reset */ CRM_DMA1_PERIPH_RESET = MAKE_VALUE(0x10, 22), /*!< dma1 periph reset */ CRM_DMA2_PERIPH_RESET = MAKE_VALUE(0x10, 24), /*!< dma2 periph reset */ CRM_OTGFS2_PERIPH_RESET = MAKE_VALUE(0x10, 29), /*!< otgfs2 periph reset */ /* ahb periph2 */ CRM_DVP_PERIPH_RESET = MAKE_VALUE(0x14, 0), /*!< dvp periph reset */ CRM_OTGFS1_PERIPH_RESET = MAKE_VALUE(0x14, 7), /*!< otgfs1 periph reset */ CRM_SDIO1_PERIPH_RESET = MAKE_VALUE(0x14, 15), /*!< sdio1 periph reset */ /* ahb periph3 */ CRM_XMC_PERIPH_RESET = MAKE_VALUE(0x18, 0), /*!< xmc periph reset */ CRM_QSPI1_PERIPH_RESET = MAKE_VALUE(0x18, 1), /*!< qspi1 periph reset */ CRM_QSPI2_PERIPH_RESET = MAKE_VALUE(0x18, 14), /*!< qspi2 periph reset */ CRM_SDIO2_PERIPH_RESET = MAKE_VALUE(0x18, 15), /*!< sdio2 periph reset */ /* apb1 periph */ CRM_TMR2_PERIPH_RESET = MAKE_VALUE(0x20, 0), /*!< tmr2 periph reset */ CRM_TMR3_PERIPH_RESET = MAKE_VALUE(0x20, 1), /*!< tmr3 periph reset */ CRM_TMR4_PERIPH_RESET = MAKE_VALUE(0x20, 2), /*!< tmr4 periph reset */ CRM_TMR5_PERIPH_RESET = MAKE_VALUE(0x20, 3), /*!< tmr5 periph reset */ CRM_TMR6_PERIPH_RESET = MAKE_VALUE(0x20, 4), /*!< tmr6 periph reset */ CRM_TMR7_PERIPH_RESET = MAKE_VALUE(0x20, 5), /*!< tmr7 periph reset */ CRM_TMR12_PERIPH_RESET = MAKE_VALUE(0x20, 6), /*!< tmr12 periph reset */ CRM_TMR13_PERIPH_RESET = MAKE_VALUE(0x20, 7), /*!< tmr13 periph reset */ CRM_TMR14_PERIPH_RESET = MAKE_VALUE(0x20, 8), /*!< tmr14 periph reset */ CRM_WWDT_PERIPH_RESET = MAKE_VALUE(0x20, 11), /*!< wwdt periph reset */ CRM_SPI2_PERIPH_RESET = MAKE_VALUE(0x20, 14), /*!< spi2 periph reset */ CRM_SPI3_PERIPH_RESET = MAKE_VALUE(0x20, 15), /*!< spi3 periph reset */ CRM_USART2_PERIPH_RESET = MAKE_VALUE(0x20, 17), /*!< usart2 periph reset */ CRM_USART3_PERIPH_RESET = MAKE_VALUE(0x20, 18), /*!< usart3 periph reset */ CRM_UART4_PERIPH_RESET = MAKE_VALUE(0x20, 19), /*!< uart4 periph reset */ CRM_UART5_PERIPH_RESET = MAKE_VALUE(0x20, 20), /*!< uart5 periph reset */ CRM_I2C1_PERIPH_RESET = MAKE_VALUE(0x20, 21), /*!< i2c1 periph reset */ CRM_I2C2_PERIPH_RESET = MAKE_VALUE(0x20, 22), /*!< i2c2 periph reset */ CRM_I2C3_PERIPH_RESET = MAKE_VALUE(0x20, 23), /*!< i2c3 periph reset */ CRM_CAN1_PERIPH_RESET = MAKE_VALUE(0x20, 25), /*!< can1 periph reset */ CRM_CAN2_PERIPH_RESET = MAKE_VALUE(0x20, 26), /*!< can2 periph reset */ CRM_PWC_PERIPH_RESET = MAKE_VALUE(0x20, 28), /*!< pwc periph reset */ CRM_DAC_PERIPH_RESET = MAKE_VALUE(0x20, 29), /*!< dac periph reset */ CRM_UART7_PERIPH_RESET = MAKE_VALUE(0x20, 30), /*!< uart7 periph reset */ CRM_UART8_PERIPH_RESET = MAKE_VALUE(0x20, 31), /*!< uart8 periph reset */ /* apb2 periph */ CRM_TMR1_PERIPH_RESET = MAKE_VALUE(0x24, 0), /*!< tmr1 periph reset */ CRM_TMR8_PERIPH_RESET = MAKE_VALUE(0x24, 1), /*!< tmr8 periph reset */ CRM_USART1_PERIPH_RESET = MAKE_VALUE(0x24, 4), /*!< usart1 periph reset */ CRM_USART6_PERIPH_RESET = MAKE_VALUE(0x24, 5), /*!< usart6 periph reset */ CRM_ADC_PERIPH_RESET = MAKE_VALUE(0x24, 8), /*!< adc periph reset */ CRM_SPI1_PERIPH_RESET = MAKE_VALUE(0x24, 12), /*!< spi1 periph reset */ CRM_SPI4_PERIPH_RESET = MAKE_VALUE(0x24, 13), /*!< spi4 periph reset */ CRM_SCFG_PERIPH_RESET = MAKE_VALUE(0x24, 14), /*!< scfg periph reset */ CRM_TMR9_PERIPH_RESET = MAKE_VALUE(0x24, 16), /*!< tmr9 periph reset */ CRM_TMR10_PERIPH_RESET = MAKE_VALUE(0x24, 17), /*!< tmr10 periph reset */ CRM_TMR11_PERIPH_RESET = MAKE_VALUE(0x24, 18), /*!< tmr11 periph reset */ CRM_TMR20_PERIPH_RESET = MAKE_VALUE(0x24, 20), /*!< tmr20 periph reset */ CRM_ACC_PERIPH_RESET = MAKE_VALUE(0x24, 29) /*!< acc periph reset */ #endif #if defined (AT32F437xx) /* ahb periph1 */ CRM_GPIOA_PERIPH_RESET = MAKE_VALUE(0x10, 0), /*!< gpioa periph reset */ CRM_GPIOB_PERIPH_RESET = MAKE_VALUE(0x10, 1), /*!< gpiob periph reset */ CRM_GPIOC_PERIPH_RESET = MAKE_VALUE(0x10, 2), /*!< gpioc periph reset */ CRM_GPIOD_PERIPH_RESET = MAKE_VALUE(0x10, 3), /*!< gpiod periph reset */ CRM_GPIOE_PERIPH_RESET = MAKE_VALUE(0x10, 4), /*!< gpioe periph reset */ CRM_GPIOF_PERIPH_RESET = MAKE_VALUE(0x10, 5), /*!< gpiof periph reset */ CRM_GPIOG_PERIPH_RESET = MAKE_VALUE(0x10, 6), /*!< gpiog periph reset */ CRM_GPIOH_PERIPH_RESET = MAKE_VALUE(0x10, 7), /*!< gpioh periph reset */ CRM_CRC_PERIPH_RESET = MAKE_VALUE(0x10, 12), /*!< crc periph reset */ CRM_EDMA_PERIPH_RESET = MAKE_VALUE(0x10, 21), /*!< edma periph reset */ CRM_DMA1_PERIPH_RESET = MAKE_VALUE(0x10, 22), /*!< dma1 periph reset */ CRM_DMA2_PERIPH_RESET = MAKE_VALUE(0x10, 24), /*!< dma2 periph reset */ CRM_EMAC_PERIPH_RESET = MAKE_VALUE(0x10, 25), /*!< emac periph reset */ CRM_OTGFS2_PERIPH_RESET = MAKE_VALUE(0x10, 29), /*!< otgfs2 periph reset */ /* ahb periph2 */ CRM_DVP_PERIPH_RESET = MAKE_VALUE(0x14, 0), /*!< dvp periph reset */ CRM_OTGFS1_PERIPH_RESET = MAKE_VALUE(0x14, 7), /*!< otgfs1 periph reset */ CRM_SDIO1_PERIPH_RESET = MAKE_VALUE(0x14, 15), /*!< sdio1 periph reset */ /* ahb periph3 */ CRM_XMC_PERIPH_RESET = MAKE_VALUE(0x18, 0), /*!< xmc periph reset */ CRM_QSPI1_PERIPH_RESET = MAKE_VALUE(0x18, 1), /*!< qspi1 periph reset */ CRM_QSPI2_PERIPH_RESET = MAKE_VALUE(0x18, 14), /*!< qspi2 periph reset */ CRM_SDIO2_PERIPH_RESET = MAKE_VALUE(0x18, 15), /*!< sdio2 periph reset */ /* apb1 periph */ CRM_TMR2_PERIPH_RESET = MAKE_VALUE(0x20, 0), /*!< tmr2 periph reset */ CRM_TMR3_PERIPH_RESET = MAKE_VALUE(0x20, 1), /*!< tmr3 periph reset */ CRM_TMR4_PERIPH_RESET = MAKE_VALUE(0x20, 2), /*!< tmr4 periph reset */ CRM_TMR5_PERIPH_RESET = MAKE_VALUE(0x20, 3), /*!< tmr5 periph reset */ CRM_TMR6_PERIPH_RESET = MAKE_VALUE(0x20, 4), /*!< tmr6 periph reset */ CRM_TMR7_PERIPH_RESET = MAKE_VALUE(0x20, 5), /*!< tmr7 periph reset */ CRM_TMR12_PERIPH_RESET = MAKE_VALUE(0x20, 6), /*!< tmr12 periph reset */ CRM_TMR13_PERIPH_RESET = MAKE_VALUE(0x20, 7), /*!< tmr13 periph reset */ CRM_TMR14_PERIPH_RESET = MAKE_VALUE(0x20, 8), /*!< tmr14 periph reset */ CRM_WWDT_PERIPH_RESET = MAKE_VALUE(0x20, 11), /*!< wwdt periph reset */ CRM_SPI2_PERIPH_RESET = MAKE_VALUE(0x20, 14), /*!< spi2 periph reset */ CRM_SPI3_PERIPH_RESET = MAKE_VALUE(0x20, 15), /*!< spi3 periph reset */ CRM_USART2_PERIPH_RESET = MAKE_VALUE(0x20, 17), /*!< usart2 periph reset */ CRM_USART3_PERIPH_RESET = MAKE_VALUE(0x20, 18), /*!< usart3 periph reset */ CRM_UART4_PERIPH_RESET = MAKE_VALUE(0x20, 19), /*!< uart4 periph reset */ CRM_UART5_PERIPH_RESET = MAKE_VALUE(0x20, 20), /*!< uart5 periph reset */ CRM_I2C1_PERIPH_RESET = MAKE_VALUE(0x20, 21), /*!< i2c1 periph reset */ CRM_I2C2_PERIPH_RESET = MAKE_VALUE(0x20, 22), /*!< i2c2 periph reset */ CRM_I2C3_PERIPH_RESET = MAKE_VALUE(0x20, 23), /*!< i2c3 periph reset */ CRM_CAN1_PERIPH_RESET = MAKE_VALUE(0x20, 25), /*!< can1 periph reset */ CRM_CAN2_PERIPH_RESET = MAKE_VALUE(0x20, 26), /*!< can2 periph reset */ CRM_PWC_PERIPH_RESET = MAKE_VALUE(0x20, 28), /*!< pwc periph reset */ CRM_DAC_PERIPH_RESET = MAKE_VALUE(0x20, 29), /*!< dac periph reset */ CRM_UART7_PERIPH_RESET = MAKE_VALUE(0x20, 30), /*!< uart7 periph reset */ CRM_UART8_PERIPH_RESET = MAKE_VALUE(0x20, 31), /*!< uart8 periph reset */ /* apb2 periph */ CRM_TMR1_PERIPH_RESET = MAKE_VALUE(0x24, 0), /*!< tmr1 periph reset */ CRM_TMR8_PERIPH_RESET = MAKE_VALUE(0x24, 1), /*!< tmr8 periph reset */ CRM_USART1_PERIPH_RESET = MAKE_VALUE(0x24, 4), /*!< usart1 periph reset */ CRM_USART6_PERIPH_RESET = MAKE_VALUE(0x24, 5), /*!< usart6 periph reset */ CRM_ADC_PERIPH_RESET = MAKE_VALUE(0x24, 8), /*!< adc periph reset */ CRM_SPI1_PERIPH_RESET = MAKE_VALUE(0x24, 12), /*!< spi1 periph reset */ CRM_SPI4_PERIPH_RESET = MAKE_VALUE(0x24, 13), /*!< spi4 periph reset */ CRM_SCFG_PERIPH_RESET = MAKE_VALUE(0x24, 14), /*!< scfg periph reset */ CRM_TMR9_PERIPH_RESET = MAKE_VALUE(0x24, 16), /*!< tmr9 periph reset */ CRM_TMR10_PERIPH_RESET = MAKE_VALUE(0x24, 17), /*!< tmr10 periph reset */ CRM_TMR11_PERIPH_RESET = MAKE_VALUE(0x24, 18), /*!< tmr11 periph reset */ CRM_TMR20_PERIPH_RESET = MAKE_VALUE(0x24, 20), /*!< tmr20 periph reset */ CRM_ACC_PERIPH_RESET = MAKE_VALUE(0x24, 29) /*!< acc periph reset */ #endif } crm_periph_reset_type; /** * @brief crm periph clock in low power mode */ typedef enum { #if defined (AT32F435xx) /* ahb periph1 */ CRM_GPIOA_PERIPH_LOWPOWER = MAKE_VALUE(0x50, 0), /*!< gpioa sleep mode periph clock */ CRM_GPIOB_PERIPH_LOWPOWER = MAKE_VALUE(0x50, 1), /*!< gpiob sleep mode periph clock */ CRM_GPIOC_PERIPH_LOWPOWER = MAKE_VALUE(0x50, 2), /*!< gpioc sleep mode periph clock */ CRM_GPIOD_PERIPH_LOWPOWER = MAKE_VALUE(0x50, 3), /*!< gpiod sleep mode periph clock */ CRM_GPIOE_PERIPH_LOWPOWER = MAKE_VALUE(0x50, 4), /*!< gpioe sleep mode periph clock */ CRM_GPIOF_PERIPH_LOWPOWER = MAKE_VALUE(0x50, 5), /*!< gpiof sleep mode periph clock */ CRM_GPIOG_PERIPH_LOWPOWER = MAKE_VALUE(0x50, 6), /*!< gpiog sleep mode periph clock */ CRM_GPIOH_PERIPH_LOWPOWER = MAKE_VALUE(0x50, 7), /*!< gpioh sleep mode periph clock */ CRM_CRC_PERIPH_LOWPOWER = MAKE_VALUE(0x50, 12), /*!< crc sleep mode periph clock */ CRM_EDMA_PERIPH_LOWPOWER = MAKE_VALUE(0x50, 21), /*!< edma sleep mode periph clock */ CRM_DMA1_PERIPH_LOWPOWER = MAKE_VALUE(0x50, 22), /*!< dma1 sleep mode periph clock */ CRM_DMA2_PERIPH_LOWPOWER = MAKE_VALUE(0x50, 24), /*!< dma2 sleep mode periph clock */ CRM_EMAC_PERIPH_LOWPOWER = MAKE_VALUE(0x50, 25), /*!< emac sleep mode periph clock */ CRM_EMACTX_PERIPH_LOWPOWER = MAKE_VALUE(0x50, 26), /*!< emac tx sleep mode periph clock */ CRM_EMACRX_PERIPH_LOWPOWER = MAKE_VALUE(0x50, 27), /*!< emac rx sleep mode periph clock */ CRM_EMACPTP_PERIPH_LOWPOWER = MAKE_VALUE(0x50, 28), /*!< emac ptp sleep mode periph clock */ CRM_OTGFS2_PERIPH_LOWPOWER = MAKE_VALUE(0x50, 29), /*!< otgfs2 sleep mode periph clock */ /* ahb periph2 */ CRM_DVP_PERIPH_LOWPOWER = MAKE_VALUE(0x54, 0), /*!< dvp sleep mode periph clock */ CRM_OTGFS1_PERIPH_LOWPOWER = MAKE_VALUE(0x54, 7), /*!< otgfs1 sleep mode periph clock */ CRM_SDIO1_PERIPH_LOWPOWER = MAKE_VALUE(0x54, 15), /*!< sdio1 sleep mode periph clock */ /* ahb periph3 */ CRM_XMC_PERIPH_LOWPOWER = MAKE_VALUE(0x58, 0), /*!< xmc sleep mode periph clock */ CRM_QSPI1_PERIPH_LOWPOWER = MAKE_VALUE(0x58, 1), /*!< qspi1 sleep mode periph clock */ CRM_QSPI2_PERIPH_LOWPOWER = MAKE_VALUE(0x58, 14), /*!< qspi2 sleep mode periph clock */ CRM_SDIO2_PERIPH_LOWPOWER = MAKE_VALUE(0x58, 15), /*!< sdio2 sleep mode periph clock */ /* apb1 periph */ CRM_TMR2_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 0), /*!< tmr2 sleep mode periph clock */ CRM_TMR3_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 1), /*!< tmr3 sleep mode periph clock */ CRM_TMR4_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 2), /*!< tmr4 sleep mode periph clock */ CRM_TMR5_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 3), /*!< tmr5 sleep mode periph clock */ CRM_TMR6_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 4), /*!< tmr6 sleep mode periph clock */ CRM_TMR7_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 5), /*!< tmr7 sleep mode periph clock */ CRM_TMR12_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 6), /*!< tmr12 sleep mode periph clock */ CRM_TMR13_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 7), /*!< tmr13 sleep mode periph clock */ CRM_TMR14_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 8), /*!< tmr14 sleep mode periph clock */ CRM_WWDT_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 11), /*!< wwdt sleep mode periph clock */ CRM_SPI2_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 14), /*!< spi2 sleep mode periph clock */ CRM_SPI3_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 15), /*!< spi3 sleep mode periph clock */ CRM_USART2_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 17), /*!< usart2 sleep mode periph clock */ CRM_USART3_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 18), /*!< usart3 sleep mode periph clock */ CRM_UART4_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 19), /*!< uart4 sleep mode periph clock */ CRM_UART5_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 20), /*!< uart5 sleep mode periph clock */ CRM_I2C1_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 21), /*!< i2c1 sleep mode periph clock */ CRM_I2C2_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 22), /*!< i2c2 sleep mode periph clock */ CRM_I2C3_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 23), /*!< i2c3 sleep mode periph clock */ CRM_CAN1_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 25), /*!< can1 sleep mode periph clock */ CRM_CAN2_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 26), /*!< can2 sleep mode periph clock */ CRM_PWC_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 28), /*!< pwc sleep mode periph clock */ CRM_DAC_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 29), /*!< dac sleep mode periph clock */ CRM_UART7_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 30), /*!< uart7 sleep mode periph clock */ CRM_UART8_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 31), /*!< uart8 sleep mode periph clock */ /* apb2 periph */ CRM_TMR1_PERIPH_LOWPOWER = MAKE_VALUE(0x64, 0), /*!< tmr1 sleep mode periph clock */ CRM_TMR8_PERIPH_LOWPOWER = MAKE_VALUE(0x64, 1), /*!< tmr8 sleep mode periph clock */ CRM_USART1_PERIPH_LOWPOWER = MAKE_VALUE(0x64, 4), /*!< usart1 sleep mode periph clock */ CRM_USART6_PERIPH_LOWPOWER = MAKE_VALUE(0x64, 5), /*!< usart6 sleep mode periph clock */ CRM_ADC1_PERIPH_LOWPOWER = MAKE_VALUE(0x64, 8), /*!< adc1 sleep mode periph clock */ CRM_ADC2_PERIPH_LOWPOWER = MAKE_VALUE(0x64, 9), /*!< adc2 sleep mode periph clock */ CRM_ADC3_PERIPH_LOWPOWER = MAKE_VALUE(0x64, 10), /*!< adc3 sleep mode periph clock */ CRM_SPI1_PERIPH_LOWPOWER = MAKE_VALUE(0x64, 12), /*!< spi1 sleep mode periph clock */ CRM_SPI4_PERIPH_LOWPOWER = MAKE_VALUE(0x64, 13), /*!< spi4 sleep mode periph clock */ CRM_SCFG_PERIPH_LOWPOWER = MAKE_VALUE(0x64, 14), /*!< scfg sleep mode periph clock */ CRM_TMR9_PERIPH_LOWPOWER = MAKE_VALUE(0x64, 16), /*!< tmr9 sleep mode periph clock */ CRM_TMR10_PERIPH_LOWPOWER = MAKE_VALUE(0x64, 17), /*!< tmr10 sleep mode periph clock */ CRM_TMR11_PERIPH_LOWPOWER = MAKE_VALUE(0x64, 18), /*!< tmr11 sleep mode periph clock */ CRM_TMR20_PERIPH_LOWPOWER = MAKE_VALUE(0x64, 20), /*!< tmr20 sleep mode periph clock */ CRM_ACC_PERIPH_LOWPOWER = MAKE_VALUE(0x64, 29) /*!< acc sleep mode periph clock */ #endif #if defined (AT32F437xx) /* ahb periph1 */ CRM_GPIOA_PERIPH_LOWPOWER = MAKE_VALUE(0x50, 0), /*!< gpioa sleep mode periph clock */ CRM_GPIOB_PERIPH_LOWPOWER = MAKE_VALUE(0x50, 1), /*!< gpiob sleep mode periph clock */ CRM_GPIOC_PERIPH_LOWPOWER = MAKE_VALUE(0x50, 2), /*!< gpioc sleep mode periph clock */ CRM_GPIOD_PERIPH_LOWPOWER = MAKE_VALUE(0x50, 3), /*!< gpiod sleep mode periph clock */ CRM_GPIOE_PERIPH_LOWPOWER = MAKE_VALUE(0x50, 4), /*!< gpioe sleep mode periph clock */ CRM_GPIOF_PERIPH_LOWPOWER = MAKE_VALUE(0x50, 5), /*!< gpiof sleep mode periph clock */ CRM_GPIOG_PERIPH_LOWPOWER = MAKE_VALUE(0x50, 6), /*!< gpiog sleep mode periph clock */ CRM_GPIOH_PERIPH_LOWPOWER = MAKE_VALUE(0x50, 7), /*!< gpioh sleep mode periph clock */ CRM_CRC_PERIPH_LOWPOWER = MAKE_VALUE(0x50, 12), /*!< crc sleep mode periph clock */ CRM_EDMA_PERIPH_LOWPOWER = MAKE_VALUE(0x50, 21), /*!< edma sleep mode periph clock */ CRM_DMA1_PERIPH_LOWPOWER = MAKE_VALUE(0x50, 22), /*!< dma1 sleep mode periph clock */ CRM_DMA2_PERIPH_LOWPOWER = MAKE_VALUE(0x50, 24), /*!< dma2 sleep mode periph clock */ CRM_OTGFS2_PERIPH_LOWPOWER = MAKE_VALUE(0x50, 29), /*!< otgfs2 sleep mode periph clock */ /* ahb periph2 */ CRM_DVP_PERIPH_LOWPOWER = MAKE_VALUE(0x54, 0), /*!< dvp sleep mode periph clock */ CRM_OTGFS1_PERIPH_LOWPOWER = MAKE_VALUE(0x54, 7), /*!< otgfs1 sleep mode periph clock */ CRM_SDIO1_PERIPH_LOWPOWER = MAKE_VALUE(0x54, 15), /*!< sdio1 sleep mode periph clock */ /* ahb periph3 */ CRM_XMC_PERIPH_LOWPOWER = MAKE_VALUE(0x58, 0), /*!< xmc sleep mode periph clock */ CRM_QSPI1_PERIPH_LOWPOWER = MAKE_VALUE(0x58, 1), /*!< qspi1 sleep mode periph clock */ CRM_QSPI2_PERIPH_LOWPOWER = MAKE_VALUE(0x58, 14), /*!< qspi2 sleep mode periph clock */ CRM_SDIO2_PERIPH_LOWPOWER = MAKE_VALUE(0x58, 15), /*!< sdio2 sleep mode periph clock */ /* apb1 periph */ CRM_TMR2_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 0), /*!< tmr2 sleep mode periph clock */ CRM_TMR3_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 1), /*!< tmr3 sleep mode periph clock */ CRM_TMR4_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 2), /*!< tmr4 sleep mode periph clock */ CRM_TMR5_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 3), /*!< tmr5 sleep mode periph clock */ CRM_TMR6_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 4), /*!< tmr6 sleep mode periph clock */ CRM_TMR7_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 5), /*!< tmr7 sleep mode periph clock */ CRM_TMR12_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 6), /*!< tmr12 sleep mode periph clock */ CRM_TMR13_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 7), /*!< tmr13 sleep mode periph clock */ CRM_TMR14_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 8), /*!< tmr14 sleep mode periph clock */ CRM_WWDT_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 11), /*!< wwdt sleep mode periph clock */ CRM_SPI2_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 14), /*!< spi2 sleep mode periph clock */ CRM_SPI3_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 15), /*!< spi3 sleep mode periph clock */ CRM_USART2_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 17), /*!< usart2 sleep mode periph clock */ CRM_USART3_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 18), /*!< usart3 sleep mode periph clock */ CRM_UART4_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 19), /*!< uart4 sleep mode periph clock */ CRM_UART5_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 20), /*!< uart5 sleep mode periph clock */ CRM_I2C1_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 21), /*!< i2c1 sleep mode periph clock */ CRM_I2C2_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 22), /*!< i2c2 sleep mode periph clock */ CRM_I2C3_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 23), /*!< i2c3 sleep mode periph clock */ CRM_CAN1_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 25), /*!< can1 sleep mode periph clock */ CRM_CAN2_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 26), /*!< can2 sleep mode periph clock */ CRM_PWC_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 28), /*!< pwc sleep mode periph clock */ CRM_DAC_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 29), /*!< dac sleep mode periph clock */ CRM_UART7_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 30), /*!< uart7 sleep mode periph clock */ CRM_UART8_PERIPH_LOWPOWER = MAKE_VALUE(0x60, 31), /*!< uart8 sleep mode periph clock */ /* apb2 periph */ CRM_TMR1_PERIPH_LOWPOWER = MAKE_VALUE(0x64, 0), /*!< tmr1 sleep mode periph clock */ CRM_TMR8_PERIPH_LOWPOWER = MAKE_VALUE(0x64, 1), /*!< tmr8 sleep mode periph clock */ CRM_USART1_PERIPH_LOWPOWER = MAKE_VALUE(0x64, 4), /*!< usart1 sleep mode periph clock */ CRM_USART6_PERIPH_LOWPOWER = MAKE_VALUE(0x64, 5), /*!< usart6 sleep mode periph clock */ CRM_ADC1_PERIPH_LOWPOWER = MAKE_VALUE(0x64, 8), /*!< adc1 sleep mode periph clock */ CRM_ADC2_PERIPH_LOWPOWER = MAKE_VALUE(0x64, 9), /*!< adc2 sleep mode periph clock */ CRM_ADC3_PERIPH_LOWPOWER = MAKE_VALUE(0x64, 10), /*!< adc3 sleep mode periph clock */ CRM_SPI1_PERIPH_LOWPOWER = MAKE_VALUE(0x64, 12), /*!< spi1 sleep mode periph clock */ CRM_SPI4_PERIPH_LOWPOWER = MAKE_VALUE(0x64, 13), /*!< spi4 sleep mode periph clock */ CRM_SCFG_PERIPH_LOWPOWER = MAKE_VALUE(0x64, 14), /*!< scfg sleep mode periph clock */ CRM_TMR9_PERIPH_LOWPOWER = MAKE_VALUE(0x64, 16), /*!< tmr9 sleep mode periph clock */ CRM_TMR10_PERIPH_LOWPOWER = MAKE_VALUE(0x64, 17), /*!< tmr10 sleep mode periph clock */ CRM_TMR11_PERIPH_LOWPOWER = MAKE_VALUE(0x64, 18), /*!< tmr11 sleep mode periph clock */ CRM_TMR20_PERIPH_LOWPOWER = MAKE_VALUE(0x64, 20), /*!< tmr20 sleep mode periph clock */ CRM_ACC_PERIPH_LOWPOWER = MAKE_VALUE(0x64, 29) /*!< acc sleep mode periph clock */ #endif } crm_periph_clock_lowpower_type; /** * @brief crm pll clock source */ typedef enum { CRM_PLL_SOURCE_HICK = 0x00, /*!< high speed internal clock as pll reference clock source */ CRM_PLL_SOURCE_HEXT = 0x01 /*!< high speed external crystal as pll reference clock source */ } crm_pll_clock_source_type; /** * @brief crm pll fr */ typedef enum { CRM_PLL_FR_1 = 0x00, /*!< pll post-division div1 */ CRM_PLL_FR_2 = 0x01, /*!< pll post-division div2 */ CRM_PLL_FR_4 = 0x02, /*!< pll post-division div4 */ CRM_PLL_FR_8 = 0x03, /*!< pll post-division div8 */ CRM_PLL_FR_16 = 0x04, /*!< pll post-division div16 */ CRM_PLL_FR_32 = 0x05 /*!< pll post-division div32 */ } crm_pll_fr_type; /** * @brief crm clock source */ typedef enum { CRM_CLOCK_SOURCE_HICK = 0x00, /*!< high speed internal clock */ CRM_CLOCK_SOURCE_HEXT = 0x01, /*!< high speed external crystal */ CRM_CLOCK_SOURCE_PLL = 0x02, /*!< phase locking loop */ CRM_CLOCK_SOURCE_LEXT = 0x03, /*!< low speed external crystal */ CRM_CLOCK_SOURCE_LICK = 0x04 /*!< low speed internal clock */ } crm_clock_source_type; /** * @brief crm ahb division */ typedef enum { CRM_AHB_DIV_1 = 0x00, /*!< sclk div1 to ahbclk */ CRM_AHB_DIV_2 = 0x08, /*!< sclk div2 to ahbclk */ CRM_AHB_DIV_4 = 0x09, /*!< sclk div4 to ahbclk */ CRM_AHB_DIV_8 = 0x0A, /*!< sclk div8 to ahbclk */ CRM_AHB_DIV_16 = 0x0B, /*!< sclk div16 to ahbclk */ CRM_AHB_DIV_64 = 0x0C, /*!< sclk div64 to ahbclk */ CRM_AHB_DIV_128 = 0x0D, /*!< sclk div128 to ahbclk */ CRM_AHB_DIV_256 = 0x0E, /*!< sclk div256 to ahbclk */ CRM_AHB_DIV_512 = 0x0F /*!< sclk div512 to ahbclk */ } crm_ahb_div_type; /** * @brief crm apb1 division */ typedef enum { CRM_APB1_DIV_1 = 0x00, /*!< ahbclk div1 to apb1clk */ CRM_APB1_DIV_2 = 0x04, /*!< ahbclk div2 to apb1clk */ CRM_APB1_DIV_4 = 0x05, /*!< ahbclk div4 to apb1clk */ CRM_APB1_DIV_8 = 0x06, /*!< ahbclk div8 to apb1clk */ CRM_APB1_DIV_16 = 0x07 /*!< ahbclk div16 to apb1clk */ } crm_apb1_div_type; /** * @brief crm apb2 division */ typedef enum { CRM_APB2_DIV_1 = 0x00, /*!< ahbclk div1 to apb2clk */ CRM_APB2_DIV_2 = 0x04, /*!< ahbclk div2 to apb2clk */ CRM_APB2_DIV_4 = 0x05, /*!< ahbclk div4 to apb2clk */ CRM_APB2_DIV_8 = 0x06, /*!< ahbclk div8 to apb2clk */ CRM_APB2_DIV_16 = 0x07 /*!< ahbclk div16 to apb2clk */ } crm_apb2_div_type; /** * @brief crm usb division */ typedef enum { CRM_USB_DIV_1_5 = 0x00, /*!< pllclk div1.5 to usbclk */ CRM_USB_DIV_1 = 0x01, /*!< pllclk div1 to usbclk */ CRM_USB_DIV_2_5 = 0x02, /*!< pllclk div2.5 to usbclk */ CRM_USB_DIV_2 = 0x03, /*!< pllclk div2 to usbclk */ CRM_USB_DIV_3_5 = 0x04, /*!< pllclk div3.5 to usbclk */ CRM_USB_DIV_3 = 0x05, /*!< pllclk div3 to usbclk */ CRM_USB_DIV_4_5 = 0x06, /*!< pllclk div4.5 to usbclk */ CRM_USB_DIV_4 = 0x07, /*!< pllclk div4 to usbclk */ CRM_USB_DIV_5_5 = 0x08, /*!< pllclk div5.5 to usbclk */ CRM_USB_DIV_5 = 0x09, /*!< pllclk div5 to usbclk */ CRM_USB_DIV_6_5 = 0x0A, /*!< pllclk div6.5 to usbclk */ CRM_USB_DIV_6 = 0x0B, /*!< pllclk div6 to usbclk */ CRM_USB_DIV_7 = 0x0C /*!< pllclk div7 to usbclk */ } crm_usb_div_type; /** * @brief crm ertc clock */ typedef enum { CRM_ERTC_CLOCK_NOCLK = 0x000, /*!< no clock as ertc clock source */ CRM_ERTC_CLOCK_LEXT = 0x001, /*!< low speed external crystal as ertc clock source */ CRM_ERTC_CLOCK_LICK = 0x002, /*!< low speed internal clock as ertc clock source */ CRM_ERTC_CLOCK_HEXT_DIV_2 = 0x023, /*!< high speed external crystal div2 as ertc clock source */ CRM_ERTC_CLOCK_HEXT_DIV_3 = 0x033, /*!< high speed external crystal div3 as ertc clock source */ CRM_ERTC_CLOCK_HEXT_DIV_4 = 0x043, /*!< high speed external crystal div4 as ertc clock source */ CRM_ERTC_CLOCK_HEXT_DIV_5 = 0x053, /*!< high speed external crystal div5 as ertc clock source */ CRM_ERTC_CLOCK_HEXT_DIV_6 = 0x063, /*!< high speed external crystal div6 as ertc clock source */ CRM_ERTC_CLOCK_HEXT_DIV_7 = 0x073, /*!< high speed external crystal div7 as ertc clock source */ CRM_ERTC_CLOCK_HEXT_DIV_8 = 0x083, /*!< high speed external crystal div8 as ertc clock source */ CRM_ERTC_CLOCK_HEXT_DIV_9 = 0x093, /*!< high speed external crystal div9 as ertc clock source */ CRM_ERTC_CLOCK_HEXT_DIV_10 = 0x0A3, /*!< high speed external crystal div10 as ertc clock source */ CRM_ERTC_CLOCK_HEXT_DIV_11 = 0x0B3, /*!< high speed external crystal div11 as ertc clock source */ CRM_ERTC_CLOCK_HEXT_DIV_12 = 0x0C3, /*!< high speed external crystal div12 as ertc clock source */ CRM_ERTC_CLOCK_HEXT_DIV_13 = 0x0D3, /*!< high speed external crystal div13 as ertc clock source */ CRM_ERTC_CLOCK_HEXT_DIV_14 = 0x0E3, /*!< high speed external crystal div14 as ertc clock source */ CRM_ERTC_CLOCK_HEXT_DIV_15 = 0x0F3, /*!< high speed external crystal div15 as ertc clock source */ CRM_ERTC_CLOCK_HEXT_DIV_16 = 0x103, /*!< high speed external crystal div16 as ertc clock source */ CRM_ERTC_CLOCK_HEXT_DIV_17 = 0x113, /*!< high speed external crystal div17 as ertc clock source */ CRM_ERTC_CLOCK_HEXT_DIV_18 = 0x123, /*!< high speed external crystal div18 as ertc clock source */ CRM_ERTC_CLOCK_HEXT_DIV_19 = 0x133, /*!< high speed external crystal div19 as ertc clock source */ CRM_ERTC_CLOCK_HEXT_DIV_20 = 0x143, /*!< high speed external crystal div20 as ertc clock source */ CRM_ERTC_CLOCK_HEXT_DIV_21 = 0x153, /*!< high speed external crystal div21 as ertc clock source */ CRM_ERTC_CLOCK_HEXT_DIV_22 = 0x163, /*!< high speed external crystal div22 as ertc clock source */ CRM_ERTC_CLOCK_HEXT_DIV_23 = 0x173, /*!< high speed external crystal div23 as ertc clock source */ CRM_ERTC_CLOCK_HEXT_DIV_24 = 0x183, /*!< high speed external crystal div24 as ertc clock source */ CRM_ERTC_CLOCK_HEXT_DIV_25 = 0x193, /*!< high speed external crystal div25 as ertc clock source */ CRM_ERTC_CLOCK_HEXT_DIV_26 = 0x1A3, /*!< high speed external crystal div26 as ertc clock source */ CRM_ERTC_CLOCK_HEXT_DIV_27 = 0x1B3, /*!< high speed external crystal div27 as ertc clock source */ CRM_ERTC_CLOCK_HEXT_DIV_28 = 0x1C3, /*!< high speed external crystal div28 as ertc clock source */ CRM_ERTC_CLOCK_HEXT_DIV_29 = 0x1D3, /*!< high speed external crystal div29 as ertc clock source */ CRM_ERTC_CLOCK_HEXT_DIV_30 = 0x1E3, /*!< high speed external crystal div30 as ertc clock source */ CRM_ERTC_CLOCK_HEXT_DIV_31 = 0x1F3 /*!< high speed external crystal div31 as ertc clock source */ } crm_ertc_clock_type; /** * @brief crm hick 48mhz division */ typedef enum { CRM_HICK48_DIV6 = 0x00, /*!< fixed 8 mhz when hick is selected as sclk */ CRM_HICK48_NODIV = 0x01 /*!< 8 mhz or 48 mhz depend on hickdiv when hick is selected as sclk */ } crm_hick_div_6_type; /** * @brief crm sclk select */ typedef enum { CRM_SCLK_HICK = 0x00, /*!< select high speed internal clock as sclk */ CRM_SCLK_HEXT = 0x01, /*!< select high speed external crystal as sclk */ CRM_SCLK_PLL = 0x02 /*!< select phase locking loop clock as sclk */ } crm_sclk_type; /** * @brief crm clkout index */ typedef enum { CRM_CLKOUT_INDEX_1 = 0x00, /*!< clkout1 */ CRM_CLKOUT_INDEX_2 = 0x01 /*!< clkout2 */ } crm_clkout_index_type; /** * @brief crm clkout1 select */ typedef enum { CRM_CLKOUT1_HICK = 0x00, /*!< output high speed internal clock to clkout1 pin */ CRM_CLKOUT1_LEXT = 0x01, /*!< output low speed external crystal to clkout1 pin */ CRM_CLKOUT1_HEXT = 0x02, /*!< output high speed external crystal to clkout1 pin */ CRM_CLKOUT1_PLL = 0x03 /*!< output phase locking loop clock to clkout1 pin */ } crm_clkout1_select_type; /** * @brief crm clkout2 select */ typedef enum { CRM_CLKOUT2_SCLK = 0x00, /*!< output system clock to clkout2 pin */ CRM_CLKOUT2_HEXT = 0x02, /*!< output high speed external crystal to clkout2 pin */ CRM_CLKOUT2_PLL = 0x03, /*!< output phase locking loop clock to clkout2 pin */ CRM_CLKOUT2_USB = 0x10, /*!< output usbclk to clkout2 pin */ CRM_CLKOUT2_ADC = 0x11, /*!< output adcclk to clkout2 pin */ CRM_CLKOUT2_HICK = 0x12, /*!< output high speed internal clock to clkout2 pin */ CRM_CLKOUT2_LICK = 0x13, /*!< output low speed internal clock to clkout2 pin */ CRM_CLKOUT2_LEXT = 0x14 /*!< output low speed external crystal to clkout2 pin */ } crm_clkout2_select_type; /** * @brief crm clkout division1 */ typedef enum { CRM_CLKOUT_DIV1_1 = 0x00, /*!< clkout division1 div1 */ CRM_CLKOUT_DIV1_2 = 0x04, /*!< clkout division1 div2 */ CRM_CLKOUT_DIV1_3 = 0x05, /*!< clkout division1 div3 */ CRM_CLKOUT_DIV1_4 = 0x06, /*!< clkout division1 div4 */ CRM_CLKOUT_DIV1_5 = 0x07 /*!< clkout division1 div5 */ } crm_clkout_div1_type; /** * @brief crm clkout division2 */ typedef enum { CRM_CLKOUT_DIV2_1 = 0x00, /*!< clkout division2 div1 */ CRM_CLKOUT_DIV2_2 = 0x08, /*!< clkout division2 div2 */ CRM_CLKOUT_DIV2_4 = 0x09, /*!< clkout division2 div4 */ CRM_CLKOUT_DIV2_8 = 0x0A, /*!< clkout division2 div8 */ CRM_CLKOUT_DIV2_16 = 0x0B, /*!< clkout division2 div16 */ CRM_CLKOUT_DIV2_64 = 0x0C, /*!< clkout division2 div64 */ CRM_CLKOUT_DIV2_128 = 0x0D, /*!< clkout division2 div128 */ CRM_CLKOUT_DIV2_256 = 0x0E, /*!< clkout division2 div256 */ CRM_CLKOUT_DIV2_512 = 0x0F /*!< clkout division2 div512 */ } crm_clkout_div2_type; /** * @brief crm auto step mode */ typedef enum { CRM_AUTO_STEP_MODE_DISABLE = 0x00, /*!< disable auto step mode */ CRM_AUTO_STEP_MODE_ENABLE = 0x03 /*!< enable auto step mode */ } crm_auto_step_mode_type; /** * @brief crm usb 48 mhz clock source select */ typedef enum { CRM_USB_CLOCK_SOURCE_PLL = 0x00, /*!< select phase locking loop clock as usb clock source */ CRM_USB_CLOCK_SOURCE_HICK = 0x01 /*!< select high speed internal clock as usb clock source */ } crm_usb_clock_source_type; /** * @brief crm hick as system clock frequency select */ typedef enum { CRM_HICK_SCLK_8MHZ = 0x00, /*!< fixed 8 mhz when hick is selected as sclk */ CRM_HICK_SCLK_48MHZ = 0x01 /*!< 8 mhz or 48 mhz depend on hickdiv when hick is selected as sclk */ } crm_hick_sclk_frequency_type; /** * @brief crm emac output pulse width */ typedef enum { CRM_EMAC_PULSE_125MS = 0x00, /*!< emac output pulse width 125ms */ CRM_EMAC_PULSE_1SCLK = 0x01 /*!< emac output pulse width 1 system clock */ } crm_emac_output_pulse_type; /** * @brief crm clocks freqency structure */ typedef struct { uint32_t sclk_freq; /*!< system clock frequency */ uint32_t ahb_freq; /*!< ahb bus clock frequency */ uint32_t apb2_freq; /*!< apb2 bus clock frequency */ uint32_t apb1_freq; /*!< apb1 bus clock frequency */ } crm_clocks_freq_type; /** * @brief type define crm register all */ typedef struct { /** * @brief crm ctrl register, offset:0x00 */ union { __IO uint32_t ctrl; struct { __IO uint32_t hicken : 1; /* [0] */ __IO uint32_t hickstbl : 1; /* [1] */ __IO uint32_t hicktrim : 6; /* [7:2] */ __IO uint32_t hickcal : 8; /* [15:8] */ __IO uint32_t hexten : 1; /* [16] */ __IO uint32_t hextstbl : 1; /* [17] */ __IO uint32_t hextbyps : 1; /* [18] */ __IO uint32_t cfden : 1; /* [19] */ __IO uint32_t reserved1 : 4; /* [23:20] */ __IO uint32_t pllen : 1; /* [24] */ __IO uint32_t pllstbl : 1; /* [25] */ __IO uint32_t reserved2 : 6; /* [31:26] */ } ctrl_bit; }; /** * @brief crm pllcfg register, offset:0x04 */ union { __IO uint32_t pllcfg; struct { __IO uint32_t pllms : 4; /* [3:0] */ __IO uint32_t reserved1 : 2; /* [5:4] */ __IO uint32_t pllns : 9; /* [14:6] */ __IO uint32_t reserved2 : 1; /* [15] */ __IO uint32_t pllfr : 3; /* [18:16] */ __IO uint32_t reserved3 : 3; /* [21:19] */ __IO uint32_t pllrcs : 1; /* [22] */ __IO uint32_t reserved4 : 9; /* [31:23] */ } pllcfg_bit; }; /** * @brief crm cfg register, offset:0x08 */ union { __IO uint32_t cfg; struct { __IO uint32_t sclksel : 2; /* [1:0] */ __IO uint32_t sclksts : 2; /* [3:2] */ __IO uint32_t ahbdiv : 4; /* [7:4] */ __IO uint32_t reserved1 : 2; /* [9:8] */ __IO uint32_t apb1div : 3; /* [12:10] */ __IO uint32_t apb2div : 3; /* [15:13] */ __IO uint32_t ertcdiv : 5; /* [20:16] */ __IO uint32_t clkout1_sel : 2; /* [22:21] */ __IO uint32_t reserved2 : 1; /* [23] */ __IO uint32_t clkout1div1 : 3; /* [26:24] */ __IO uint32_t clkout2div1 : 3; /* [29:27] */ __IO uint32_t clkout2_sel1 : 2; /* [31:30] */ } cfg_bit; }; /** * @brief crm clkint register, offset:0x0C */ union { __IO uint32_t clkint; struct { __IO uint32_t lickstblf : 1; /* [0] */ __IO uint32_t lextstblf : 1; /* [1] */ __IO uint32_t hickstblf : 1; /* [2] */ __IO uint32_t hextstblf : 1; /* [3] */ __IO uint32_t pllstblf : 1; /* [4] */ __IO uint32_t reserved1 : 2; /* [6:5] */ __IO uint32_t cfdf : 1; /* [7] */ __IO uint32_t lickstblien : 1; /* [8] */ __IO uint32_t lextstblien : 1; /* [9] */ __IO uint32_t hickstblien : 1; /* [10] */ __IO uint32_t hextstblien : 1; /* [11] */ __IO uint32_t pllstblien : 1; /* [12] */ __IO uint32_t reserved2 : 3; /* [15:13] */ __IO uint32_t lickstblfc : 1; /* [16] */ __IO uint32_t lextstblfc : 1; /* [17] */ __IO uint32_t hickstblfc : 1; /* [18] */ __IO uint32_t hextstblfc : 1; /* [19] */ __IO uint32_t pllstblfc : 1; /* [20] */ __IO uint32_t reserved3 : 2; /* [22:21] */ __IO uint32_t cfdfc : 1; /* [23] */ __IO uint32_t reserved4 : 8; /* [31:24] */ } clkint_bit; }; /** * @brief crm ahbrst1 register, offset:0x10 */ union { __IO uint32_t ahbrst1; #if defined (AT32F435xx) struct { __IO uint32_t gpioarst : 1; /* [0] */ __IO uint32_t gpiobrst : 1; /* [1] */ __IO uint32_t gpiocrst : 1; /* [2] */ __IO uint32_t gpiodrst : 1; /* [3] */ __IO uint32_t gpioerst : 1; /* [4] */ __IO uint32_t gpiofrst : 1; /* [5] */ __IO uint32_t gpiogrst : 1; /* [6] */ __IO uint32_t gpiohrst : 1; /* [7] */ __IO uint32_t reserved1 : 4; /* [11:8] */ __IO uint32_t crcrst : 1; /* [12] */ __IO uint32_t reserved2 : 8; /* [20:13] */ __IO uint32_t edmarst : 1; /* [21] */ __IO uint32_t dma1rst : 1; /* [22] */ __IO uint32_t reserved3 : 1; /* [23] */ __IO uint32_t dma2rst : 1; /* [24] */ __IO uint32_t reserved4 : 4; /* [28:25] */ __IO uint32_t otgfs2rst : 1; /* [29] */ __IO uint32_t reserved5 : 2; /* [31:30] */ } ahbrst1_bit; #endif #if defined (AT32F437xx) struct { __IO uint32_t gpioarst : 1; /* [0] */ __IO uint32_t gpiobrst : 1; /* [1] */ __IO uint32_t gpiocrst : 1; /* [2] */ __IO uint32_t gpiodrst : 1; /* [3] */ __IO uint32_t gpioerst : 1; /* [4] */ __IO uint32_t gpiofrst : 1; /* [5] */ __IO uint32_t gpiogrst : 1; /* [6] */ __IO uint32_t gpiohrst : 1; /* [7] */ __IO uint32_t reserved1 : 4; /* [11:8] */ __IO uint32_t crcrst : 1; /* [12] */ __IO uint32_t reserved2 : 8; /* [20:13] */ __IO uint32_t edmarst : 1; /* [21] */ __IO uint32_t dma1rst : 1; /* [22] */ __IO uint32_t reserved3 : 1; /* [23] */ __IO uint32_t dma2rst : 1; /* [24] */ __IO uint32_t emacrst : 1; /* [25] */ __IO uint32_t reserved4 : 3; /* [28:26] */ __IO uint32_t otgfs2rst : 1; /* [29] */ __IO uint32_t reserved5 : 2; /* [31:30] */ } ahbrst1_bit; #endif }; /** * @brief crm ahbrst2 register, offset:0x14 */ union { __IO uint32_t ahbrst2; struct { __IO uint32_t dvprst : 1; /* [0] */ __IO uint32_t reserved1 : 6; /* [6:1] */ __IO uint32_t otgfs1rst : 1; /* [7] */ __IO uint32_t reserved2 : 7; /* [14:8] */ __IO uint32_t sdio1rst : 1; /* [15] */ __IO uint32_t reserved3 : 16;/* [31:16] */ } ahbrst2_bit; }; /** * @brief crm ahbrst3 register, offset:0x18 */ union { __IO uint32_t ahbrst3; struct { __IO uint32_t xmcrst : 1; /* [0] */ __IO uint32_t qspi1rst : 1; /* [1] */ __IO uint32_t reserved1 : 12;/* [13:2] */ __IO uint32_t qspi2rst : 1; /* [14] */ __IO uint32_t sdio2rst : 1; /* [15] */ __IO uint32_t reserved3 : 16;/* [31:16] */ } ahbrst3_bit; }; /** * @brief crm reserved1 register, offset:0x1C */ __IO uint32_t reserved1; /** * @brief crm apb1rst register, offset:0x20 */ union { __IO uint32_t apb1rst; struct { __IO uint32_t tmr2rst : 1; /* [0] */ __IO uint32_t tmr3rst : 1; /* [1] */ __IO uint32_t tmr4rst : 1; /* [2] */ __IO uint32_t tmr5rst : 1; /* [3] */ __IO uint32_t tmr6rst : 1; /* [4] */ __IO uint32_t tmr7rst : 1; /* [5] */ __IO uint32_t tmr12rst : 1; /* [6] */ __IO uint32_t tmr13rst : 1; /* [7] */ __IO uint32_t adc14rst : 1; /* [8] */ __IO uint32_t reserved1 : 2; /* [10:9] */ __IO uint32_t wwdtrst : 1; /* [11] */ __IO uint32_t reserved2 : 2; /* [13:12] */ __IO uint32_t spi2rst : 1; /* [14] */ __IO uint32_t spi3rst : 1; /* [15] */ __IO uint32_t reserved3 : 1; /* [16] */ __IO uint32_t usart2rst : 1; /* [17] */ __IO uint32_t usart3rst : 1; /* [18] */ __IO uint32_t uart4rst : 1; /* [19] */ __IO uint32_t uart5rst : 1; /* [20] */ __IO uint32_t i2c1rst : 1; /* [21] */ __IO uint32_t i2c2rst : 1; /* [22] */ __IO uint32_t i2c3rst : 1; /* [23] */ __IO uint32_t reserved4 : 1; /* [24] */ __IO uint32_t can1rst : 1; /* [25] */ __IO uint32_t can2rst : 1; /* [26] */ __IO uint32_t reserved5 : 1; /* [27] */ __IO uint32_t pwcrst : 1; /* [28] */ __IO uint32_t dacrst : 1; /* [29] */ __IO uint32_t uart7rst : 1; /* [30] */ __IO uint32_t uart8rst : 1; /* [31] */ } apb1rst_bit; }; /** * @brief crm apb2rst register, offset:0x24 */ union { __IO uint32_t apb2rst; struct { __IO uint32_t tmr1rst : 1; /* [0] */ __IO uint32_t tmr8rst : 1; /* [1] */ __IO uint32_t reserved1 : 2; /* [3:2] */ __IO uint32_t usart1rst : 1; /* [4] */ __IO uint32_t usart6rst : 1; /* [5] */ __IO uint32_t reserved2 : 2; /* [7:6] */ __IO uint32_t adcrst : 1; /* [8] */ __IO uint32_t reserved3 : 3; /* [11:9] */ __IO uint32_t spi1rst : 1; /* [12] */ __IO uint32_t spi4rst : 1; /* [13] */ __IO uint32_t scfgrst : 1; /* [14] */ __IO uint32_t reserved4 : 1; /* [15] */ __IO uint32_t tmr9rst : 1; /* [16] */ __IO uint32_t tmr10rst : 1; /* [17] */ __IO uint32_t tmr11rst : 1; /* [18] */ __IO uint32_t reserved5 : 1; /* [19] */ __IO uint32_t tmr20rst : 1; /* [20] */ __IO uint32_t reserved6 : 8; /* [28:21] */ __IO uint32_t accrst : 1; /* [29] */ __IO uint32_t reserved7 : 2; /* [31:30] */ } apb2rst_bit; }; /** * @brief crm reserved2 register, offset:0x28~0x2C */ __IO uint32_t reserved2[2]; /** * @brief crm ahben1 register, offset:0x30 */ union { __IO uint32_t ahben1; #if defined (AT32F435xx) struct { __IO uint32_t gpioaen : 1; /* [0] */ __IO uint32_t gpioben : 1; /* [1] */ __IO uint32_t gpiocen : 1; /* [2] */ __IO uint32_t gpioden : 1; /* [3] */ __IO uint32_t gpioeen : 1; /* [4] */ __IO uint32_t gpiofen : 1; /* [5] */ __IO uint32_t gpiogen : 1; /* [6] */ __IO uint32_t gpiohen : 1; /* [7] */ __IO uint32_t reserved1 : 4; /* [11:8] */ __IO uint32_t crcen : 1; /* [12] */ __IO uint32_t reserved2 : 8; /* [20:13] */ __IO uint32_t edmaen : 1; /* [21] */ __IO uint32_t dma1en : 1; /* [22] */ __IO uint32_t reserved3 : 1; /* [23] */ __IO uint32_t dma2en : 1; /* [24] */ __IO uint32_t reserved4 : 4; /* [28:25] */ __IO uint32_t otgfs2en : 1; /* [29] */ __IO uint32_t reserved5 : 2; /* [31:30] */ } ahben1_bit; #endif #if defined (AT32F437xx) struct { __IO uint32_t gpioaen : 1; /* [0] */ __IO uint32_t gpioben : 1; /* [1] */ __IO uint32_t gpiocen : 1; /* [2] */ __IO uint32_t gpioden : 1; /* [3] */ __IO uint32_t gpioeen : 1; /* [4] */ __IO uint32_t gpiofen : 1; /* [5] */ __IO uint32_t gpiogen : 1; /* [6] */ __IO uint32_t gpiohen : 1; /* [7] */ __IO uint32_t reserved1 : 4; /* [11:8] */ __IO uint32_t crcen : 1; /* [12] */ __IO uint32_t reserved2 : 8; /* [20:13] */ __IO uint32_t edmaen : 1; /* [21] */ __IO uint32_t dma1en : 1; /* [22] */ __IO uint32_t reserved3 : 1; /* [23] */ __IO uint32_t dma2en : 1; /* [24] */ __IO uint32_t emacen : 1; /* [25] */ __IO uint32_t reserved4 : 3; /* [28:26] */ __IO uint32_t otgfs2en : 1; /* [29] */ __IO uint32_t reserved5 : 2; /* [31:30] */ } ahben1_bit; #endif }; /** * @brief crm ahben2 register, offset:0x34 */ union { __IO uint32_t ahben2; struct { __IO uint32_t dvpen : 1; /* [0] */ __IO uint32_t reserved1 : 6; /* [6:1] */ __IO uint32_t otgfs1en : 1; /* [7] */ __IO uint32_t reserved2 : 7; /* [14:8] */ __IO uint32_t sdio1en : 1; /* [15] */ __IO uint32_t reserved3 : 16;/* [31:16] */ } ahben2_bit; }; /** * @brief crm ahben3 register, offset:0x38 */ union { __IO uint32_t ahben3; struct { __IO uint32_t xmcen : 1; /* [0] */ __IO uint32_t qspi1en : 1; /* [1] */ __IO uint32_t reserved1 : 12;/* [13:2] */ __IO uint32_t qspi2en : 1; /* [14] */ __IO uint32_t sdio2en : 1; /* [15] */ __IO uint32_t reserved3 : 16;/* [31:16] */ } ahben3_bit; }; /** * @brief crm reserved3 register, offset:0x3C */ __IO uint32_t reserved3; /** * @brief crm apb1en register, offset:0x40 */ union { __IO uint32_t apb1en; struct { __IO uint32_t tmr2en : 1; /* [0] */ __IO uint32_t tmr3en : 1; /* [1] */ __IO uint32_t tmr4en : 1; /* [2] */ __IO uint32_t tmr5en : 1; /* [3] */ __IO uint32_t tmr6en : 1; /* [4] */ __IO uint32_t tmr7en : 1; /* [5] */ __IO uint32_t tmr12en : 1; /* [6] */ __IO uint32_t tmr13en : 1; /* [7] */ __IO uint32_t adc14en : 1; /* [8] */ __IO uint32_t reserved1 : 2; /* [10:9] */ __IO uint32_t wwdten : 1; /* [11] */ __IO uint32_t reserved2 : 2; /* [13:12] */ __IO uint32_t spi2en : 1; /* [14] */ __IO uint32_t spi3en : 1; /* [15] */ __IO uint32_t reserved3 : 1; /* [16] */ __IO uint32_t usart2en : 1; /* [17] */ __IO uint32_t usart3en : 1; /* [18] */ __IO uint32_t uart4en : 1; /* [19] */ __IO uint32_t uart5en : 1; /* [20] */ __IO uint32_t i2c1en : 1; /* [21] */ __IO uint32_t i2c2en : 1; /* [22] */ __IO uint32_t i2c3en : 1; /* [23] */ __IO uint32_t reserved4 : 1; /* [24] */ __IO uint32_t can1en : 1; /* [25] */ __IO uint32_t can2en : 1; /* [26] */ __IO uint32_t reserved5 : 1; /* [27] */ __IO uint32_t pwcen : 1; /* [28] */ __IO uint32_t dacen : 1; /* [29] */ __IO uint32_t uart7en : 1; /* [30] */ __IO uint32_t uart8en : 1; /* [31] */ } apb1en_bit; }; /** * @brief crm apb2en register, offset:0x44 */ union { __IO uint32_t apb2en; struct { __IO uint32_t tmr1en : 1; /* [0] */ __IO uint32_t tmr8en : 1; /* [1] */ __IO uint32_t reserved1 : 2; /* [3:2] */ __IO uint32_t usart1en : 1; /* [4] */ __IO uint32_t usart6en : 1; /* [5] */ __IO uint32_t reserved2 : 2; /* [7:6] */ __IO uint32_t adcen : 1; /* [8] */ __IO uint32_t reserved3 : 3; /* [11:9] */ __IO uint32_t spi1en : 1; /* [12] */ __IO uint32_t spi4en : 1; /* [13] */ __IO uint32_t scfgen : 1; /* [14] */ __IO uint32_t reserved4 : 1; /* [15] */ __IO uint32_t tmr9en : 1; /* [16] */ __IO uint32_t tmr10en : 1; /* [17] */ __IO uint32_t tmr11en : 1; /* [18] */ __IO uint32_t reserved5 : 1; /* [19] */ __IO uint32_t tmr20en : 1; /* [20] */ __IO uint32_t reserved6 : 8; /* [28:21] */ __IO uint32_t accen : 1; /* [29] */ __IO uint32_t reserved7 : 2; /* [31:30] */ } apb2en_bit; }; /** * @brief crm reserved4 register, offset:0x48~0x4C */ __IO uint32_t reserved4[2]; /** * @brief crm ahblpen1 register, offset:0x50 */ union { __IO uint32_t ahblpen1; #if defined (AT32F435xx) struct { __IO uint32_t gpioalpen : 1; /* [0] */ __IO uint32_t gpioblpen : 1; /* [1] */ __IO uint32_t gpioclpen : 1; /* [2] */ __IO uint32_t gpiodlpen : 1; /* [3] */ __IO uint32_t gpioelpen : 1; /* [4] */ __IO uint32_t gpioflpen : 1; /* [5] */ __IO uint32_t gpioglpen : 1; /* [6] */ __IO uint32_t gpiohlpen : 1; /* [7] */ __IO uint32_t reserved1 : 4; /* [11:8] */ __IO uint32_t crclpen : 1; /* [12] */ __IO uint32_t reserved2 : 8; /* [20:13] */ __IO uint32_t edmalpen : 1; /* [21] */ __IO uint32_t dma1lpen : 1; /* [22] */ __IO uint32_t reserved3 : 1; /* [23] */ __IO uint32_t dma2lpen : 1; /* [24] */ __IO uint32_t reserved4 : 4; /* [28:25] */ __IO uint32_t otgfs2lpen : 1; /* [29] */ __IO uint32_t reserved5 : 2; /* [31:30] */ } ahblpen1_bit; #endif #if defined (AT32F437xx) struct { __IO uint32_t gpioalpen : 1; /* [0] */ __IO uint32_t gpioblpen : 1; /* [1] */ __IO uint32_t gpioclpen : 1; /* [2] */ __IO uint32_t gpiodlpen : 1; /* [3] */ __IO uint32_t gpioelpen : 1; /* [4] */ __IO uint32_t gpioflpen : 1; /* [5] */ __IO uint32_t gpioglpen : 1; /* [6] */ __IO uint32_t gpiohlpen : 1; /* [7] */ __IO uint32_t reserved1 : 4; /* [11:8] */ __IO uint32_t crclpen : 1; /* [12] */ __IO uint32_t reserved2 : 8; /* [20:13] */ __IO uint32_t edmalpen : 1; /* [21] */ __IO uint32_t dma1lpen : 1; /* [22] */ __IO uint32_t reserved3 : 1; /* [23] */ __IO uint32_t dma2lpen : 1; /* [24] */ __IO uint32_t emaclpen : 1; /* [25] */ __IO uint32_t reserved4 : 3; /* [28:26] */ __IO uint32_t otgfs2lpen : 1; /* [29] */ __IO uint32_t reserved5 : 2; /* [31:30] */ } ahblpen1_bit; #endif }; /** * @brief crm ahblpen2 register, offset:0x54 */ union { __IO uint32_t ahblpen2; struct { __IO uint32_t dvplpen : 1; /* [0] */ __IO uint32_t reserved1 : 6; /* [6:1] */ __IO uint32_t otgfs1lpen : 1; /* [7] */ __IO uint32_t reserved2 : 7; /* [14:8] */ __IO uint32_t sdio1lpen : 1; /* [15] */ __IO uint32_t reserved3 : 16;/* [31:16] */ } ahblpen2_bit; }; /** * @brief crm ahblpen3 register, offset:0x58 */ union { __IO uint32_t ahblpen3; struct { __IO uint32_t xmclpen : 1; /* [0] */ __IO uint32_t qspi1lpen : 1; /* [1] */ __IO uint32_t reserved1 : 12;/* [13:2] */ __IO uint32_t qspi2lpen : 1; /* [14] */ __IO uint32_t sdio2lpen : 1; /* [15] */ __IO uint32_t reserved3 : 16;/* [31:16] */ } ahblpen3_bit; }; /** * @brief crm reserved5 register, offset:0x5C */ __IO uint32_t reserved5; /** * @brief crm apb1lpen register, offset:0x60 */ union { __IO uint32_t apb1lpen; struct { __IO uint32_t tmr2lpen : 1; /* [0] */ __IO uint32_t tmr3lpen : 1; /* [1] */ __IO uint32_t tmr4lpen : 1; /* [2] */ __IO uint32_t tmr5lpen : 1; /* [3] */ __IO uint32_t tmr6lpen : 1; /* [4] */ __IO uint32_t tmr7lpen : 1; /* [5] */ __IO uint32_t tmr12lpen : 1; /* [6] */ __IO uint32_t tmr13lpen : 1; /* [7] */ __IO uint32_t adc14lpen : 1; /* [8] */ __IO uint32_t reserved1 : 2; /* [10:9] */ __IO uint32_t wwdtlpen : 1; /* [11] */ __IO uint32_t reserved2 : 2; /* [13:12] */ __IO uint32_t spi2lpen : 1; /* [14] */ __IO uint32_t spi3lpen : 1; /* [15] */ __IO uint32_t reserved3 : 1; /* [16] */ __IO uint32_t usart2lpen : 1; /* [17] */ __IO uint32_t usart3lpen : 1; /* [18] */ __IO uint32_t uart4lpen : 1; /* [19] */ __IO uint32_t uart5lpen : 1; /* [20] */ __IO uint32_t i2c1lpen : 1; /* [21] */ __IO uint32_t i2c2lpen : 1; /* [22] */ __IO uint32_t i2c3lpen : 1; /* [23] */ __IO uint32_t reserved4 : 1; /* [24] */ __IO uint32_t can1lpen : 1; /* [25] */ __IO uint32_t can2lpen : 1; /* [26] */ __IO uint32_t reserved5 : 1; /* [27] */ __IO uint32_t pwclpen : 1; /* [28] */ __IO uint32_t daclpen : 1; /* [29] */ __IO uint32_t uart7lpen : 1; /* [30] */ __IO uint32_t uart8lpen : 1; /* [31] */ } apb1lpen_bit; }; /** * @brief crm apb2lpen register, offset:0x64 */ union { __IO uint32_t apb2lpen; struct { __IO uint32_t tmr1lpen : 1; /* [0] */ __IO uint32_t tmr8lpen : 1; /* [1] */ __IO uint32_t reserved1 : 2; /* [3:2] */ __IO uint32_t usart1lpen : 1; /* [4] */ __IO uint32_t usart6lpen : 1; /* [5] */ __IO uint32_t reserved2 : 2; /* [7:6] */ __IO uint32_t adclpen : 1; /* [8] */ __IO uint32_t reserved3 : 3; /* [11:9] */ __IO uint32_t spi1lpen : 1; /* [12] */ __IO uint32_t spi4lpen : 1; /* [13] */ __IO uint32_t scfglpen : 1; /* [14] */ __IO uint32_t reserved4 : 1; /* [15] */ __IO uint32_t tmr9lpen : 1; /* [16] */ __IO uint32_t tmr10lpen : 1; /* [17] */ __IO uint32_t tmr11lpen : 1; /* [18] */ __IO uint32_t reserved5 : 1; /* [19] */ __IO uint32_t tmr20lpen : 1; /* [20] */ __IO uint32_t reserved6 : 8; /* [28:21] */ __IO uint32_t acclpen : 1; /* [29] */ __IO uint32_t reserved7 : 2; /* [31:30] */ } apb2lpen_bit; }; /** * @brief crm reserved6 register, offset:0x68~0x6C */ __IO uint32_t reserved6[2]; /** * @brief crm bpdc register, offset:0x70 */ union { __IO uint32_t bpdc; struct { __IO uint32_t lexten : 1; /* [0] */ __IO uint32_t lextstbl : 1; /* [1] */ __IO uint32_t lextbyps : 1; /* [2] */ __IO uint32_t reserved1 : 5; /* [7:3] */ __IO uint32_t ertcsel : 2; /* [9:8] */ __IO uint32_t reserved2 : 5; /* [14:10] */ __IO uint32_t ertcen : 1; /* [15] */ __IO uint32_t bpdrst : 1; /* [16] */ __IO uint32_t reserved3 : 15;/* [31:17] */ } bpdc_bit; }; /** * @brief crm ctrlsts register, offset:0x74 */ union { __IO uint32_t ctrlsts; struct { __IO uint32_t licken : 1; /* [0] */ __IO uint32_t lickstbl : 1; /* [1] */ __IO uint32_t reserved1 : 22;/* [23:2] */ __IO uint32_t rstfc : 1; /* [24] */ __IO uint32_t reserved2 : 1; /* [25] */ __IO uint32_t nrstf : 1; /* [26] */ __IO uint32_t porrstf : 1; /* [27] */ __IO uint32_t swrstf : 1; /* [28] */ __IO uint32_t wdtrstf : 1; /* [29] */ __IO uint32_t wwdtrstf : 1; /* [30] */ __IO uint32_t lprstf : 1; /* [31] */ } ctrlsts_bit; }; /** * @brief crm reserved7 register, offset:0x78~0x9C */ __IO uint32_t reserved7[10]; /** * @brief crm misc1 register, offset:0xA0 */ union { __IO uint32_t misc1; struct { __IO uint32_t hickcal_key : 8; /* [7:0] */ __IO uint32_t reserved1 : 4; /* [11:8] */ __IO uint32_t hickdiv : 1; /* [12] */ __IO uint32_t hick_to_usb : 1; /* [13] */ __IO uint32_t hick_to_sclk : 1; /* [14] */ __IO uint32_t reserved2 : 1; /* [15] */ __IO uint32_t clkout2_sel2 : 4; /* [19:16] */ __IO uint32_t reserved3 : 4; /* [23:20] */ __IO uint32_t clkout1div2 : 4; /* [27:24] */ __IO uint32_t clkout2div2 : 4; /* [31:28] */ } misc1_bit; }; /** * @brief crm misc2 register, offset:0xA4 */ union { __IO uint32_t misc2; struct { __IO uint32_t reserved1 : 4; /* [3:0] */ __IO uint32_t auto_step_en : 2; /* [5:4] */ __IO uint32_t reserved2 : 2; /* [7:6] */ __IO uint32_t clk_to_tmr : 1; /* [8] */ __IO uint32_t emac_pps_sel : 1; /* [9] */ __IO uint32_t reserved3 : 2; /* [11:10] */ __IO uint32_t usbdiv : 4; /* [15:12] */ __IO uint32_t reserved4 : 16;/* [31:16] */ } misc2_bit; }; } crm_type; /** * @} */ #define CRM ((crm_type *) CRM_BASE) /** @defgroup CRM_exported_functions * @{ */ void crm_reset(void); void crm_lext_bypass(confirm_state new_state); void crm_hext_bypass(confirm_state new_state); flag_status crm_flag_get(uint32_t flag); error_status crm_hext_stable_wait(void); void crm_hick_clock_trimming_set(uint8_t trim_value); void crm_hick_clock_calibration_set(uint8_t cali_value); void crm_periph_clock_enable(crm_periph_clock_type value, confirm_state new_state); void crm_periph_reset(crm_periph_reset_type value, confirm_state new_state); void crm_periph_lowpower_mode_enable(crm_periph_clock_lowpower_type value, confirm_state new_state); void crm_clock_source_enable(crm_clock_source_type source, confirm_state new_state); void crm_flag_clear(uint32_t flag); void crm_ertc_clock_select(crm_ertc_clock_type value); void crm_ertc_clock_enable(confirm_state new_state); void crm_ahb_div_set(crm_ahb_div_type value); void crm_apb1_div_set(crm_apb1_div_type value); void crm_apb2_div_set(crm_apb2_div_type value); void crm_usb_clock_div_set(crm_usb_div_type value); void crm_clock_failure_detection_enable(confirm_state new_state); void crm_battery_powered_domain_reset(confirm_state new_state); void crm_auto_step_mode_enable(confirm_state new_state); void crm_hick_divider_select(crm_hick_div_6_type value); void crm_hick_sclk_frequency_select(crm_hick_sclk_frequency_type value); void crm_usb_clock_source_select(crm_usb_clock_source_type value); void crm_clkout_to_tmr10_enable(confirm_state new_state); void crm_pll_config(crm_pll_clock_source_type clock_source, uint16_t pll_ns, \ uint16_t pll_ms, crm_pll_fr_type pll_fr); void crm_sysclk_switch(crm_sclk_type value); crm_sclk_type crm_sysclk_switch_status_get(void); void crm_clocks_freq_get(crm_clocks_freq_type *clocks_struct); void crm_clock_out1_set(crm_clkout1_select_type clkout); void crm_clock_out2_set(crm_clkout2_select_type clkout); void crm_clkout_div_set(crm_clkout_index_type index, crm_clkout_div1_type div1, crm_clkout_div2_type div2); void crm_emac_output_pulse_set(crm_emac_output_pulse_type width); void crm_interrupt_enable(uint32_t crm_int, confirm_state new_state); error_status crm_pll_parameter_calculate(crm_pll_clock_source_type pll_rcs, uint32_t target_sclk_freq, \ uint16_t *ret_ms, uint16_t *ret_ns, uint16_t *ret_fr); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif
bdf30adb3184e0e2b5575634d29b27f1d7b818e8
5ff4b6986e6799bc0e143e060bafc14369030d8b
/toolchain/riscv-isa-sim/riscv/insns/vl1re32_v.h
e72ca02a3def392683550f03270a38d1033c2aea
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "GPL-1.0-or-later", "LLVM-exception", "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-bsd-3-clause-jtag", "GPL-3.0-or-later" ]
permissive
pulp-platform/mempool
7583204b2436cfc12ed95599463e51ad4df51557
c98fb3ada4f255623eaf9b09861f397a60c3d96b
refs/heads/main
2023-08-08T09:07:56.696580
2023-07-27T17:24:38
2023-07-27T17:24:38
223,218,149
178
28
Apache-2.0
2023-07-27T17:24:39
2019-11-21T16:34:37
C
UTF-8
C
false
false
44
h
vl1re32_v.h
// vl1re32.v vd, (rs1) VI_LD_WHOLE(uint32);
6fae01a972b24c30bb4dc4da099d2c7439874cdb
487c8455b34e2b312da42bf8a43162aa5c5027df
/Target/Demo/TRICORE_TC3_TC375_Lite_Kit_ADS/Prog/Libraries/iLLD/TC37A/Tricore/Msc/Msc/IfxMsc_Msc.c
9bf83e72388d40cf44a8525938b14d6a1770efcc
[]
no_license
feaser/openblt
bf3a72e7beb998cb635a67db85fa68100d048bb8
57b517eabeb37d945606e18736e106bde34010bc
refs/heads/master
2023-08-31T23:54:09.030534
2023-07-07T10:29:56
2023-07-07T10:29:56
102,110,352
534
236
null
2023-09-14T11:11:56
2017-09-01T12:26:08
C
UTF-8
C
false
false
28,957
c
IfxMsc_Msc.c
/** * \file IfxMsc_Msc.c * \brief MSC MSC details * * \version iLLD_1_0_1_12_0_1 * \copyright Copyright (c) 2019 Infineon Technologies AG. All rights reserved. * * * * IMPORTANT NOTICE * * Use of this file is subject to the terms of use agreed between (i) you or * the company in which ordinary course of business you are acting and (ii) * Infineon Technologies AG or its licensees. If and as long as no such terms * of use are agreed, use of this file is subject to following: * * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, must * be included in all copies of the Software, in whole or in part, and all * derivative works of the Software, unless such copies or derivative works are * solely in the form of machine-executable object code generated by a source * language processor. * * 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * * */ /******************************************************************************/ /*----------------------------------Includes----------------------------------*/ /******************************************************************************/ #include "IfxMsc_Msc.h" /******************************************************************************/ /*-------------------------Function Implementations---------------------------*/ /******************************************************************************/ void IfxMsc_Msc_deInitModule(IfxMsc_Msc *msc) { IfxMsc_resetModule(msc->msc); } IfxMsc_Target IfxMsc_Msc_getTarget(IfxMsc_Msc *msc, IfxMsc_Msc_Target target) { Ifx_MSC *mscSfr = msc->msc; IfxMsc_Target enX = IfxMsc_Target_en0; if (target == IfxMsc_Msc_Target_low) { enX = IfxMsc_getDataLowTarget(mscSfr); } else if (target == IfxMsc_Msc_Target_high) { enX = IfxMsc_getDataHighTarget(mscSfr); } return enX; } void IfxMsc_Msc_initModule(IfxMsc_Msc *msc, const IfxMsc_Msc_Config *config) { Ifx_MSC *mscSfr = config->msc; msc->msc = mscSfr; uint16 passwd = IfxScuWdt_getCpuWatchdogPassword(); IfxScuWdt_clearCpuEndinit(passwd); /* Enable the MSCx Clock */ IfxMsc_enableModule(mscSfr); /* Configure MSC hadrware enable and set the divider mode */ { Ifx_MSC_FDR fdr; /* Read the FDR register content */ fdr.U = mscSfr->FDR.U; /* Select the divider mode */ fdr.B.DM = config->clockConfig.dividerMode; /* Enable Hardware Clock Control */ fdr.B.ENHW = IfxMsc_HardwareClock_enabled; mscSfr->FDR.U = fdr.U; } /* Configure Upstream Channel Data Format */ { Ifx_MSC_USR usr; /* Read the USR register content */ usr.U = mscSfr->USR.U; /* Service Request Delay Control */ usr.B.SRDC = config->upstreamConfig.serviceRequestDelay; /* Select parity control Even - 0, Odd - 1 */ usr.B.PCTR = config->upstreamConfig.parity; /* Select upstream baud rate fMSC/xx */ usr.B.URR = config->upstreamConfig.upstreamChannelReceivingRate; /* Select 12 bit or 16 bit frame */ usr.B.UFT = config->upstreamConfig.upstreamChannelFrameType; mscSfr->USR.U = usr.U; } /* Normal divider */ if (config->clockConfig.dividerMode == 1) { /* Initialize MSC BaudRate at 6.25MHz, Fsys = 100MHz */ mscSfr->FDR.B.STEP = IfxMsc_upstreamNormalBaudCalculator(mscSfr, config->clockConfig.baudrate); } /* Fractional divider */ else { /* Initialize MSC BaudRate at 6.25MHz, Fsys = 100MHz */ mscSfr->FDR.B.STEP = (uint32)IfxMsc_upstreamFractionalBaudCalculator(mscSfr, config->clockConfig.baudrate); } IfxScuWdt_setCpuEndinit(passwd); /* Configure IOs */ { IfxMsc_Msc_Io *io = (IfxMsc_Msc_Io *)&config->io; IfxMsc_Fclp_Out *fclp = io->fclp.pin; if (fclp != NULL_PTR) { IfxMsc_initFclpPin(fclp, io->fclp.mode, io->pinDriver); } IfxMsc_Fcln_Out *fcln = io->fcln.pin; if (fcln != NULL_PTR) { IfxMsc_initFclnPin(fcln, io->fcln.mode, io->pinDriver); } IfxMsc_Sop_Out *sop = io->sop.pin; if (sop != NULL_PTR) { IfxMsc_initSopPin(sop, io->sop.mode, io->pinDriver); } IfxMsc_Son_Out *son = io->son.pin; if (son != NULL_PTR) { IfxMsc_initSonPin(son, io->son.mode, io->pinDriver); } IfxMsc_En_Out *en0 = io->en0.pin; if (en0 != NULL_PTR) { IfxMsc_initEnPin(en0, io->en0.mode, io->pinDriver); } IfxMsc_En_Out *en1 = io->en1.pin; if (en1 != NULL_PTR) { IfxMsc_initEnPin(en1, io->en1.mode, io->pinDriver); } IfxMsc_En_Out *en2 = io->en2.pin; if (en2 != NULL_PTR) { IfxMsc_initEnPin(en2, io->en2.mode, io->pinDriver); } IfxMsc_En_Out *en3 = io->en3.pin; if (en3 != NULL_PTR) { IfxMsc_initEnPin(en3, io->en3.mode, io->pinDriver); } IfxMsc_Sdi_In *sdi = io->sdi.pin; if (sdi != NULL_PTR) { IfxMsc_initSdiPin(sdi, io->sdi.mode, io->pinDriver); } IfxMsc_Inj_In *inj0 = io->inj0.pin; if (inj0 != NULL_PTR) { IfxMsc_initInjPin(inj0, io->inj0.mode, io->pinDriver); } IfxMsc_Inj_In *inj1 = io->inj1.pin; if (inj1 != NULL_PTR) { IfxMsc_initInjPin(inj1, io->inj1.mode, io->pinDriver); } } /* Configure the control of upstream channel timeout feature */ { Ifx_MSC_USCE usce; /* Read the USCE register content */ usce.U = mscSfr->USCE.U; /* Upstream Timeout Value */ usce.B.USTOVAL = config->upstreamConfig.upstreamTimeoutValue; /* Upstream Timeout Prescaler */ usce.B.USTOPRE = config->upstreamConfig.upstreamTimeoutPrescaler; /* Upstream Timeout Interrupt */ usce.B.USTOIP = config->interruptConfig.upstreamTimeoutInterruptNode, usce.B.USTOEN = config->interruptConfig.upstreamTimeoutInterrupt, mscSfr->USCE.U = usce.U; } /* Control the operation mode and frame layout of the downstream channel transmission */ { Ifx_MSC_DSC dsc; /* Read the DSC register content */ dsc.U = mscSfr->DSC.U; /* Passive Phase Length */ dsc.B.PPD = config->downstreamConfig.dataFramePassivePhaseLength; /* Number of command bits transmitted */ dsc.B.NBC = config->downstreamConfig.commandFrameLength; /* SRH Selection Bit */ dsc.B.ENSELH = config->downstreamConfig.srhActivePhaseSelection; /* SRL Selection Bit */ dsc.B.ENSELL = config->downstreamConfig.srlActivePhaseSelection; /* Number of SRH Bits transmitted */ dsc.B.NDBH = config->downstreamConfig.srhDataFrameLength; /* Number of SRL Bits transmitted */ dsc.B.NDBL = config->downstreamConfig.srlDataFrameLength; /* Transmission Mode - Triggered or data repetition */ dsc.B.TM = config->downstreamConfig.transmissionMode; mscSfr->DSC.U = dsc.U; } /* Number Of Passive Time Frames */ mscSfr->DSS.B.NPTF = config->downstreamConfig.passiveTimeFrameCount; /* Select Source for SRL */ mscSfr->DSDSL.U = config->downstreamConfig.downstreamDataSourcesLow; /* Select Source for SRH */ mscSfr->DSDSH.U = config->downstreamConfig.downstreamDataSourcesHigh; /* Emergency Stop Enable for Bits */ mscSfr->ESR.U = config->downstreamConfig.emergencyStopEnableBits; /* Interrupt configuration */ { Ifx_MSC_ICR icr; icr.U = mscSfr->ICR.U; icr.B.EDIP = config->interruptConfig.dataFrameInterruptNode; icr.B.EDIE = config->interruptConfig.dataFrameInterrupt; icr.B.ECIP = config->interruptConfig.commandFrameInterruptNode; icr.B.ECIE = config->interruptConfig.commandFrameInterrupt; icr.B.TFIP = config->interruptConfig.timeFrameInterruptNode; icr.B.TFIE = config->interruptConfig.timeFrameInterrupt; icr.B.RDIP = config->interruptConfig.receiveDataInterruptNode; icr.B.RDIE = config->interruptConfig.receiveDataInterrupt; /* additional interrupt configured in USCE for Upstream Interrupt node SR4 */ Ifx_MSC_USCE usce; /* Read the USCE register content */ usce.U = mscSfr->USCE.U; if (config->interruptConfig.upstreamTimeoutInterruptNode == IfxMsc_UpstreamTimeoutInterruptNode_SR4) { usce.B.USTOIP = 0; usce.B.UTASR = 1; } else { usce.B.USTOIP = config->interruptConfig.upstreamTimeoutInterruptNode; usce.B.UTASR = 0; } usce.B.USTOEN = config->interruptConfig.upstreamTimeoutInterrupt; mscSfr->USCE.U = usce.U; mscSfr->ICR.U = icr.U; /* ABRA */ Ifx_MSC_ABC abc; abc.U = mscSfr->ABC.U; if (config->interruptConfig.overflowInterruptNode == IfxMsc_OverflowInterruptNode_SR4) { abc.B.OIP = 0; abc.B.OASR = 1; } else { abc.B.OIP = config->interruptConfig.overflowInterruptNode; abc.B.OASR = 0; } abc.B.OIE = config->interruptConfig.overflowInterrupt; if (config->interruptConfig.underflowInterruptNode == IfxMsc_UnderflowInterruptNode_SR4) { abc.B.UIP = 0; abc.B.UASR = 1; } else { abc.B.UIP = config->interruptConfig.underflowInterruptNode; abc.B.UASR = 0; } abc.B.UIE = config->interruptConfig.underflowInterrupt; mscSfr->ABC.U = abc.U; } /* MSC inputs/outputs signal polarities */ { Ifx_MSC_OCR ocr; /* Read the OCR register content */ ocr.U = mscSfr->OCR.U; /* FCL is activated during active phases or always */ ocr.B.CLKCTRL = config->outputControlConfig.fclClockControl; /* SDI Line Polarity - SDI and SI */ ocr.B.ILP = config->outputControlConfig.sdiLinePolarity; /* Chip Selection Lines Polarity - EN[0:3, ENL, ENH and ENC */ ocr.B.CSLP = config->outputControlConfig.cslpPolarity; /* SOP Line Polarity - SOP, SON, SO */ ocr.B.SLP = config->outputControlConfig.sopPolarity; /* FCLP Line Polarity - FCLP, FCLN and FCL */ ocr.B.CLP = config->outputControlConfig.fclpPolarity; mscSfr->OCR.U = ocr.U; } /* Chip Enable Selection for ENL */ IfxMsc_setDataLowTarget(mscSfr, config->target[0]); /* Chip Enable Selection for ENH */ IfxMsc_setDataHighTarget(mscSfr, config->target[0]); /* Chip Enable Selection for ENC */ IfxMsc_setCommandTarget(mscSfr, IfxMsc_Msc_getTarget(msc, IfxMsc_Msc_Target_low)); /* Configure the Injection Enable and number of SRHE, SRLE Bits transmitted and Extension Enable */ { Ifx_MSC_DSCE dsce; /* Read the DSCE register content */ dsce.U = mscSfr->DSCE.U; /* Command-Data-Command in Data Repetition Mode */ dsce.B.CDCM = config->downstreamConfig.commandDataCommandReceptionMode; /* Injection Position of the Pin 1 Signal */ dsce.B.INJPOSP1 = config->downstreamConfig.injectionPositionPin1; /* Injection Enable of the Pin 1 Signal */ dsce.B.INJENP1 = config->downstreamConfig.externalSignalInjectionPin1; /* Injection Position of the Pin 0 Signal */ dsce.B.INJPOSP0 = config->downstreamConfig.injectionPositionPin0; /* Injection Enable of the Pin 0 Signal */ dsce.B.INJENP0 = config->downstreamConfig.externalSignalInjectionPin0; mscSfr->DSCE.U = dsce.U; } /* If enabled configure extension registers */ if (config->downstreamExtensionConfig.extension == IfxMsc_Extension_enabled) { IfxMsc_Msc_initializeDataExtension(msc, config); } /* If enabled, configure ABRA block */ if (config->abraConfig.abraBlockBypass != IfxMsc_AsynchronousBlock_bypassed) { IfxMsc_Msc_initializeAbra(msc, config); } /* If enabled, configure command extension mode */ if (config->commandExtensionConfig.extension == IfxMsc_Extension_enabled) { IfxMsc_Msc_initializeCommandExtension(msc, config); } } void IfxMsc_Msc_initModuleConfig(IfxMsc_Msc_Config *config, Ifx_MSC *msc) { const IfxMsc_Msc_Config defaultConfig = { .msc = NULL_PTR, .clockConfig = { .baudrate = 3125000, .dividerMode = IfxMsc_DividerMode_normal, .step = 0 }, .upstreamConfig = { .upstreamChannelFrameType = IfxMsc_UpstreamChannelFrameType_12bit, .upstreamChannelReceivingRate = IfxMsc_UpstreamChannelReceivingRate_16, .parity = IfxMsc_Parity_even, .serviceRequestDelay = IfxMsc_ServiceRequestDelay_noDelay, .upstreamTimeoutPrescaler = IfxMsc_UpstreamTimeoutPrescaler_32768, .upstreamTimeoutValue = IfxMsc_UpstreamTimeoutValue_16 }, .interruptConfig = { .dataFrameInterruptNode = IfxMsc_DataFrameInterruptNode_SR0, .dataFrameInterrupt = IfxMsc_DataFrameInterrupt_disabled, .commandFrameInterruptNode = IfxMsc_CommandFrameInterruptNode_SR0, .commandFrameInterrupt = IfxMsc_CommandFrameInterrupt_disabled, .timeFrameInterruptNode = IfxMsc_TimeFrameInterruptNode_SR0, .timeFrameInterrupt = IfxMsc_TimeFrameInterrupt_disabled, .receiveDataInterruptNode = IfxMsc_ReceiveDataInterruptNode_SR0, .receiveDataInterrupt = IfxMsc_ReceiveDataInterrupt_disabled, .upstreamTimeoutInterruptNode = IfxMsc_UpstreamTimeoutInterruptNode_SR0, .upstreamTimeoutInterrupt = IfxMsc_UpstreamTimeoutInterrupt_disabled, .overflowInterruptNode = IfxMsc_OverflowInterruptNode_SR0, .overflowInterrupt = IfxMsc_OverflowInterrupt_disabled, .underflowInterruptNode = IfxMsc_UnderflowInterruptNode_SR0, .underflowInterrupt = IfxMsc_UnderflowInterrupt_disabled }, .outputControlConfig = { .fclpPolarity = IfxMsc_FclLinePolarity_nonInverted, .sopPolarity = IfxMsc_SoLinePolarity_nonInverted, .cslpPolarity = IfxMsc_ChipSelectActiveState_low, .sdiLinePolarity = IfxMsc_SdiLinePolarity_likeSi, .fclClockControl = IfxMsc_FclClockControlEnabled_activePhaseOnly }, .downstreamConfig = { .transmissionMode = IfxMsc_TransmissionMode_triggered, .srlDataFrameLength = IfxMsc_DataFrameLength_16, .srhDataFrameLength = IfxMsc_DataFrameLength_16, .srlActivePhaseSelection = IfxMsc_ActivePhaseSelection_none, .srhActivePhaseSelection = IfxMsc_ActivePhaseSelection_none, .commandFrameLength = IfxMsc_CommandFrameLength_32, .dataFramePassivePhaseLength = IfxMsc_DataFramePassivePhaseLength_2, .passiveTimeFrameCount = IfxMsc_PassiveTimeFrameCount_0, .externalSignalInjectionPin0 = IfxMsc_ExternalSignalInjection_disabled, .injectionPositionPin0 = IfxMsc_ExternalBitInjectionPosition_0, .externalSignalInjectionPin1 = IfxMsc_ExternalSignalInjection_disabled, .injectionPositionPin1 = IfxMsc_ExternalBitInjectionPosition_0, .commandDataCommandReceptionMode = IfxMsc_CommandDataCommandRepetitionMode_disabled, .downstreamDataSourcesLow = 0, .downstreamDataSourcesHigh = 0, .emergencyStopEnableBits = 0 }, .downstreamExtensionConfig = { .extension = IfxMsc_Extension_disabled, .srlBitsShiftedAtDataFramesExtension = IfxMsc_MsbBitDataExtension_notPresent, .srhBitsShiftedAtDataFramesExtension = IfxMsc_MsbBitDataExtension_notPresent, .downstreamExtensionDataSourcesLow = 0, .downstreamExtensionDataSourcesHigh = 0, .emergencyStopExtensionEnableBits = 0, .dataFrameExtensionPassivePhaseLength = IfxMsc_DataFrameExtensionPassivePhaseLength_0, .controlFrameExtensionPassivePhaseLength = IfxMsc_ControlFrameExtensionPassivePhaseLength_0, .nDividerDownstream = IfxMsc_NDividerDownstream_1 }, .abraConfig = { .abraDownstreamBlockBaudrate = 500000, .lowPhaseOfShiftClock = IfxMsc_ShiftClockPhaseDuration_1, .highPhaseOfShiftClock = IfxMsc_ShiftClockPhaseDuration_1, .clockSelectAbra = IfxMsc_ClockSelect_fper, .nDividerAbra = IfxMsc_NDividerAbra_1, .abraBlockBypass = IfxMsc_AsynchronousBlock_bypassed }, .io = { .fclp = { .pin = NULL_PTR, .mode = IfxPort_OutputMode_pushPull }, .fcln = { .pin = NULL_PTR, .mode = IfxPort_OutputMode_pushPull }, .sop = { .pin = NULL_PTR, .mode = IfxPort_OutputMode_pushPull }, .son = { .pin = NULL_PTR, .mode = IfxPort_OutputMode_pushPull }, .en0 = { .pin = NULL_PTR, .mode = IfxPort_OutputMode_pushPull }, .en1 = { .pin = NULL_PTR, .mode = IfxPort_OutputMode_pushPull }, .en2 = { .pin = NULL_PTR, .mode = IfxPort_OutputMode_pushPull }, .en3 = { .pin = NULL_PTR, .mode = IfxPort_OutputMode_pushPull }, .sdi = { .pin = NULL_PTR, .mode = IfxPort_InputMode_pullUp }, .inj0 = { .pin = NULL_PTR, .mode = IfxPort_InputMode_pullUp }, .inj1 = { .pin = NULL_PTR, .mode = IfxPort_InputMode_pullUp }, .pinDriver = IfxPort_PadDriver_cmosAutomotiveSpeed3 }, .commandExtensionConfig = { .extension = IfxMsc_Extension_disabled, .commandFrameLength = IfxMsc_CommandFrameLength_32, .commandFramePassivePhaseLength = IfxMsc_ControlFrameExtensionPassivePhaseLength_0, .srlActivePhaseSelection = IfxMsc_ActivePhaseSelection_none, .srhActivePhaseSelection = IfxMsc_ActivePhaseSelection_none, .srlDataFrameLength = IfxMsc_DataFrameLength_16, .srhDataFrameLength = IfxMsc_DataFrameLength_16, .srlBitsShiftedAtDataFramesExtension = IfxMsc_MsbBitDataExtension_notPresent, .srhBitsShiftedAtDataFramesExtension = IfxMsc_MsbBitDataExtension_notPresent, .fastMode = IfxMsc_FastMode_disabled, .nDividerDownstream = IfxMsc_NDividerDownstream_1 } }; /* Default Configuration */ *config = defaultConfig; /* take over module pointer */ config->msc = msc; } void IfxMsc_Msc_initializeAbra(IfxMsc_Msc *msc, const IfxMsc_Msc_Config *config) { Ifx_MSC *mscSfr = msc->msc; /* N Divider Downstream */ mscSfr->DSTE.B.NDD = IfxMsc_downstreamAbraBaudCalculator(config->abraConfig.abraDownstreamBlockBaudrate); /* Configure Asynchronous block */ { Ifx_MSC_ABC abc; /* Read the ABC register content */ abc.U = mscSfr->ABC.U; /* Asynchronous Block Bypass */ abc.B.ABB = config->abraConfig.abraBlockBypass; /* Clock Select */ abc.B.CLKSEL = config->abraConfig.clockSelectAbra; /* N Divider ABRA */ abc.B.NDA = config->abraConfig.nDividerAbra; /* Duration of the High Phase of the Shift Clock */ abc.B.HIGH = config->abraConfig.highPhaseOfShiftClock; /* Duration of the Low Phase of the Shift Clock */ abc.B.LOW = config->abraConfig.lowPhaseOfShiftClock; mscSfr->ABC.U = abc.U; } } void IfxMsc_Msc_initializeDataExtension(IfxMsc_Msc *msc, const IfxMsc_Msc_Config *config) { Ifx_MSC *mscSfr = msc->msc; /* Configure the number of SRHE, SRLE Bits transmitted and Extension Enable */ { Ifx_MSC_DSCE dsce; /* Read the DSCE register content */ dsce.U = mscSfr->DSCE.U; /* Extension Enable */ dsce.B.EXEN = config->downstreamExtensionConfig.extension; /* Configure the number of SRLE Bits transmitted */ dsce.B.NDBLE = config->downstreamExtensionConfig.srlBitsShiftedAtDataFramesExtension; /* Configure the number of SRHE Bits transmitted */ dsce.B.NDBHE = config->downstreamExtensionConfig.srhBitsShiftedAtDataFramesExtension; mscSfr->DSCE.U = dsce.U; } /* Select Source for SRLE */ mscSfr->DSDSLE.U = config->downstreamExtensionConfig.downstreamExtensionDataSourcesLow; /* Select Source for SRHE */ mscSfr->DSDSHE.U = config->downstreamExtensionConfig.downstreamExtensionDataSourcesHigh; /* Emergency Stop Enable for Bit */ mscSfr->ESRE.U = config->downstreamExtensionConfig.emergencyStopExtensionEnableBits; /* Passive Phase Length at Data and Control Frames Extension */ { Ifx_MSC_DSTE dste; /* Read the DSTE register content */ dste.U = mscSfr->DSTE.U; /* Passive Phase Length at Control Frames Extension */ dste.B.PPCE = config->downstreamExtensionConfig.controlFrameExtensionPassivePhaseLength; /* Passive Phase Length at Data Frames Extension */ dste.B.PPDE = config->downstreamExtensionConfig.dataFrameExtensionPassivePhaseLength; /* N Divider for Downstream */ dste.B.NDD = config->downstreamExtensionConfig.nDividerDownstream; mscSfr->DSTE.U = dste.U; } } uint32 IfxMsc_Msc_receiveData(IfxMsc_Msc *msc, uint8 upstreamIdx) { Ifx_MSC *mscSfr = msc->msc; uint16 data = 0; /* Check for valid flag */ if (!IfxMsc_getUpstreamValidFlag(mscSfr, upstreamIdx)) { return (uint32)0xFFFFFFFF; } /* Clear the flag */ IfxMsc_clearUpstreamValidFlag(mscSfr, upstreamIdx); /* Read the data */ data = IfxMsc_getData(mscSfr, upstreamIdx); return data; } void IfxMsc_Msc_sendCommand(IfxMsc_Msc *msc, uint32 command) { Ifx_MSC *mscSfr = msc->msc; /* Downstream command */ mscSfr->DC.U = command; } void IfxMsc_Msc_sendData(IfxMsc_Msc *msc, uint16 dataLow, uint16 dataHigh) { Ifx_MSC *mscSfr = msc->msc; { Ifx_MSC_DD dd; dd.B.DDL = dataLow; dd.B.DDH = dataHigh; /* Downstream Data */ mscSfr->DD.U = dd.U; } /* Send data */ mscSfr->ISC.B.SDP = 1; } void IfxMsc_Msc_sendDataExtension(IfxMsc_Msc *msc, uint32 data, uint32 dataExtension) { Ifx_MSC *mscSfr = msc->msc; /* Downstream Data (mirror) + extension */ mscSfr->DDE.U = dataExtension; mscSfr->DDM.U = data; /* Send data */ mscSfr->ISC.B.SDP = 1; } void IfxMsc_Msc_sendDataHigh(IfxMsc_Msc *msc, uint16 data) { Ifx_MSC *mscSfr = msc->msc; /* Downstream Data High only */ mscSfr->DD.B.DDH = data; /* Send data */ mscSfr->ISC.B.SDP = 1; } void IfxMsc_Msc_sendDataLow(IfxMsc_Msc *msc, uint16 data) { Ifx_MSC *mscSfr = msc->msc; /* Downstream Data Low only */ mscSfr->DD.B.DDL = data; /* Send data */ mscSfr->ISC.B.SDP = 1; } void IfxMsc_Msc_setCommandTarget(IfxMsc_Msc *msc, IfxMsc_Target enX) { Ifx_MSC *mscSfr = msc->msc; IfxMsc_setCommandTarget(mscSfr, enX); } void IfxMsc_Msc_setDataTarget(IfxMsc_Msc *msc, IfxMsc_Target enXHigh, IfxMsc_Target enXLow) { Ifx_MSC *mscSfr = msc->msc; /* Set data low target */ IfxMsc_setDataLowTarget(mscSfr, enXLow); /* Set data high target */ IfxMsc_setDataHighTarget(mscSfr, enXHigh); } void IfxMsc_Msc_initializeCommandExtension(IfxMsc_Msc *msc, const IfxMsc_Msc_Config *config) { Ifx_MSC *mscSfr = msc->msc; /*Configure the command related settings*/ Ifx_MSC_DSCE dsce; Ifx_MSC_DSC dsc; Ifx_MSC_DSTE dste; /* Read the DSTE & DSC register contents */ dste.U = mscSfr->DSTE.U; dsc.U = mscSfr->DSC.U; dsce.U = mscSfr->DSCE.U; /* Extension Enable */ dste.B.UL1 = 1; //Unlocking for writing into CX register.Write of 1 to UL1 & CX must be done in the same cycle. dste.B.CX = config->commandExtensionConfig.extension; dste.B.FM = config->commandExtensionConfig.fastMode; /* Configure the command passive phase length */ if (config->commandExtensionConfig.commandFramePassivePhaseLength > IfxMsc_ControlFrameExtensionPassivePhaseLength_63) { // MSB extension dste.B.PPCEM = 1; //Logic behind this is that passive phase length(PPL) = [PPCEM PPCE]+2.So the value [PPCEM PPCE] = PPL - 2.When PPCEM = 1,the equation is 64 + PPCE = PPL -2 => PPCE = PPL - 66 //Another way to look at it is that PPCE_max is 65...add one and MSB(PPCEM)becomes 1.So next whatever we incrase will start from 0 in PPCE.So PPCE = PPL - 66 dste.B.PPCE = config->commandExtensionConfig.commandFramePassivePhaseLength - 66; } else { dste.B.PPCE = config->commandExtensionConfig.commandFramePassivePhaseLength; } /* Data Frame related configurations*/ //SRH Selection Bit dsc.B.ENSELH = config->commandExtensionConfig.srhActivePhaseSelection; //SRL Selection Bit dsc.B.ENSELL = config->commandExtensionConfig.srlActivePhaseSelection; //Number of SRH Bits transmitted dsc.B.NDBH = config->commandExtensionConfig.srhDataFrameLength; //Number of SRL Bits transmitted dsc.B.NDBL = config->commandExtensionConfig.srlDataFrameLength; //Extension of number of SRL Bits transmitted in EXEN mode dsce.B.NDBLE = config->commandExtensionConfig.srlBitsShiftedAtDataFramesExtension; //Number of SRL Bits transmitted in EXEN mode dsce.B.NDBHE = config->commandExtensionConfig.srlBitsShiftedAtDataFramesExtension; //N Divider for Downstream dste.B.NDD = config->commandExtensionConfig.nDividerDownstream; mscSfr->DSC.U = dsc.U; mscSfr->DSCE.U = dsce.U; mscSfr->DSTE.U = dste.U; }
fb7de6b33d16fd938b22480cc2aff95e63428140
38bd1cf9e52ea23b43223d53d8139aad52bb1c70
/cpp/iedriverserver/stdafx.h
f05fa0e2fbe7e5ecf015c8696b9f5a8980403bb0
[ "Apache-2.0" ]
permissive
SeleniumHQ/selenium
46d9553e3a45412a7540dd3f7d1f34be6ef42b1b
cc41a883b5138962c6b4408a0fdf4e932bd08071
refs/heads/trunk
2023-09-03T22:56:56.403484
2023-09-02T19:20:45
2023-09-02T19:20:45
7,613,257
30,383
9,671
Apache-2.0
2023-09-14T18:47:42
2013-01-14T21:40:56
Java
UTF-8
C
false
false
1,497
h
stdafx.h
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once #include "targetver.h" #include <stdio.h> #include <tchar.h> #define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit #include <atlbase.h> #include <atlstr.h> // A macro to disallow the copy constructor and operator= functions // This should be used in the private: declarations for a class #define DISALLOW_COPY_AND_ASSIGN(TypeName) \ TypeName(const TypeName&); \ void operator=(const TypeName&) // TODO: reference additional headers your program requires here
0ab99341c67c571f2501854d20983797d8d8c905
fbe68d84e97262d6d26dd65c704a7b50af2b3943
/third_party/virtualbox/include/VBox/Graphics/HGSMIChannels.h
2bb703e6af6bab8176bf878cf666f922b096dce9
[ "MIT", "GPL-2.0-only", "LicenseRef-scancode-unknown-license-reference", "CDDL-1.0", "LicenseRef-scancode-warranty-disclaimer", "GPL-1.0-or-later", "LGPL-2.1-or-later", "GPL-2.0-or-later", "MPL-1.0", "LicenseRef-scancode-generic-exception", "Apache-2.0", "OpenSSL" ]
permissive
thalium/icebox
c4e6573f2b4f0973b6c7bb0bf068fe9e795fdcfb
6f78952d58da52ea4f0e55b2ab297f28e80c1160
refs/heads/master
2022-08-14T00:19:36.984579
2022-02-22T13:10:31
2022-02-22T13:10:31
190,019,914
585
109
MIT
2022-01-13T20:58:15
2019-06-03T14:18:12
C++
UTF-8
C
false
false
2,632
h
HGSMIChannels.h
/* $Id: HGSMIChannels.h $ */ /** @file * * VBox Host Guest Shared Memory Interface (HGSMI). * Host/Guest shared part. * Channel identifiers. */ /* * Copyright (C) 2006-2017 Oracle Corporation * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #ifndef __HGSMIChannels_h__ #define __HGSMIChannels_h__ /* * Each channel has an 8 bit identifier. There are a number of predefined * (hardcoded) channels. * * HGSMI_CH_HGSMI channel can be used to map a string channel identifier * to a free 16 bit numerical value. values are allocated in range * [HGSMI_CH_STRING_FIRST;HGSMI_CH_STRING_LAST]. */ /* Predefined channel identifiers. Used internally by VBOX to simplify the channel setup. */ /* A reserved channel value */ #define HGSMI_CH_RESERVED 0x00 /* HGCMI: setup and configuration */ #define HGSMI_CH_HGSMI 0x01 /* Graphics: VBVA */ #define HGSMI_CH_VBVA 0x02 /* Graphics: Seamless with a single guest region */ #define HGSMI_CH_SEAMLESS 0x03 /* Graphics: Seamless with separate host windows */ #define HGSMI_CH_SEAMLESS2 0x04 /* Graphics: OpenGL HW acceleration */ #define HGSMI_CH_OPENGL 0x05 /* Dynamically allocated channel identifiers. */ /* The first channel index to be used for string mappings (inclusive) */ #define HGSMI_CH_STRING_FIRST 0x20 /* The last channel index for string mappings (inclusive) */ #define HGSMI_CH_STRING_LAST 0xff /* Check whether the channel identifier is allocated for a dynamic channel */ #define HGSMI_IS_DYNAMIC_CHANNEL(_channel) (((uint8_t)(_channel) & 0xE0) != 0) #endif /* !__HGSMIChannels_h__*/
9a98221e71a4c87a3c726e3408a5c3c6cf3226eb
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/arch/mips/include/asm/mipsprom.h
e93943fabeac7ba4877b2f79a8c7ab262f674dc0
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
2,107
h
mipsprom.h
#ifndef __ASM_MIPSPROM_H #define __ASM_MIPSPROM_H #define PROM_RESET 0 #define PROM_EXEC 1 #define PROM_RESTART 2 #define PROM_REINIT 3 #define PROM_REBOOT 4 #define PROM_AUTOBOOT 5 #define PROM_OPEN 6 #define PROM_READ 7 #define PROM_WRITE 8 #define PROM_IOCTL 9 #define PROM_CLOSE 10 #define PROM_GETCHAR 11 #define PROM_PUTCHAR 12 #define PROM_SHOWCHAR 13 /* XXX */ #define PROM_GETS 14 /* XXX */ #define PROM_PUTS 15 /* XXX */ #define PROM_PRINTF 16 /* XXX */ /* What are these for? */ #define PROM_INITPROTO 17 /* XXX */ #define PROM_PROTOENABLE 18 /* XXX */ #define PROM_PROTODISABLE 19 /* XXX */ #define PROM_GETPKT 20 /* XXX */ #define PROM_PUTPKT 21 /* XXX */ /* More PROM shit. Probably has to do with VME RMW cycles??? */ #define PROM_ORW_RMW 22 /* XXX */ #define PROM_ORH_RMW 23 /* XXX */ #define PROM_ORB_RMW 24 /* XXX */ #define PROM_ANDW_RMW 25 /* XXX */ #define PROM_ANDH_RMW 26 /* XXX */ #define PROM_ANDB_RMW 27 /* XXX */ /* Cache handling stuff */ #define PROM_FLUSHCACHE 28 /* XXX */ #define PROM_CLEARCACHE 29 /* XXX */ /* Libc alike stuff */ #define PROM_SETJMP 30 /* XXX */ #define PROM_LONGJMP 31 /* XXX */ #define PROM_BEVUTLB 32 /* XXX */ #define PROM_GETENV 33 /* XXX */ #define PROM_SETENV 34 /* XXX */ #define PROM_ATOB 35 /* XXX */ #define PROM_STRCMP 36 /* XXX */ #define PROM_STRLEN 37 /* XXX */ #define PROM_STRCPY 38 /* XXX */ #define PROM_STRCAT 39 /* XXX */ /* Misc stuff */ #define PROM_PARSER 40 /* XXX */ #define PROM_RANGE 41 /* XXX */ #define PROM_ARGVIZE 42 /* XXX */ #define PROM_HELP 43 /* XXX */ /* Entry points for some PROM commands */ #define PROM_DUMPCMD 44 /* XXX */ #define PROM_SETENVCMD 45 /* XXX */ #define PROM_UNSETENVCMD 46 /* XXX */ #define PROM_PRINTENVCMD 47 /* XXX */ #define PROM_BEVEXCEPT 48 /* XXX */ #define PROM_ENABLECMD 49 /* XXX */ #define PROM_DISABLECMD 50 /* XXX */ #define PROM_CLEARNOFAULT 51 /* XXX */ #define PROM_NOTIMPLEMENT 52 /* XXX */ #define PROM_NV_GET 53 /* XXX */ #define PROM_NV_SET 54 /* XXX */ extern char *prom_getenv(char *); #endif /* __ASM_MIPSPROM_H */
cc7994d4b50446b65bc84ed47abcbd9382762aee
79e95f653d5cf6677c45cad8be2090f8431309ae
/src/sensesp/net/web/index.h
03bb2b367d863d152f0368512153c09dc68262db
[ "Apache-2.0" ]
permissive
SignalK/SensESP
16c85caf9e6c2177e191ea4a4f0fd1ff9995d694
d8d87fa7e10fe18d2fbbfb0dbd2a680ba1ba7c4f
refs/heads/main
2023-07-09T06:57:16.418477
2023-07-03T09:34:08
2023-07-03T09:34:08
188,882,737
126
99
Apache-2.0
2023-07-03T09:34:10
2019-05-27T17:16:46
C
UTF-8
C
false
false
6,422
h
index.h
#include <pgmspace.h> const uint8_t PAGE_index[] PROGMEM = { 0x1f,0x8b,0x8,0x0,0x62,0x38,0x8f,0x64, 0x2,0xff,0xdd,0x58,0x4f,0x6f,0xeb,0x36, 0xc,0xbf,0xf7,0x53,0x70,0xda,0x65,0x3, 0xa6,0x3a,0x76,0x52,0x37,0xe9,0xec,0x1c, 0xd6,0xed,0x96,0x0,0x3,0x7a,0xeb,0x4d, 0xb1,0x95,0x58,0xad,0x6d,0x19,0x92,0xdc, 0x34,0xfb,0xf4,0x23,0x25,0xbb,0x2f,0xc9, 0x7b,0x1d,0x5e,0xb0,0x5d,0x96,0xd6,0xa1, 0x49,0x89,0x92,0xa8,0x1f,0x49,0xfd,0x71, 0x56,0xb9,0xa6,0x5e,0xde,0xdc,0x64,0x95, 0x14,0xe5,0xf2,0x6,0xf0,0x2f,0x6b,0xa4, 0x13,0xd0,0x8a,0x46,0xe6,0xec,0x4d,0xc9, 0x7d,0xa7,0x8d,0x63,0x50,0xe8,0xd6,0xc9, 0xd6,0xe5,0x6c,0xaf,0x4a,0x57,0xe5,0xa5, 0x7c,0x53,0x85,0xe4,0x5e,0xf8,0x5,0x54, 0xab,0x9c,0x12,0x35,0xb7,0x85,0xa8,0x65, 0x1e,0xb3,0xa1,0x23,0xa7,0x5c,0x2d,0x97, 0x4f,0xb2,0xb5,0x7f,0x3c,0xfd,0x9,0xbf, 0xfb,0x26,0x59,0x14,0x4a,0x83,0x46,0xad, 0xda,0x57,0x30,0xb2,0xce,0x99,0x75,0x87, 0x5a,0xda,0x4a,0x4a,0x1c,0xab,0x32,0x72, 0x9b,0xb3,0xc2,0xda,0x68,0xa3,0xb5,0xb3, 0xce,0x88,0xee,0xb6,0x51,0xed,0x2d,0x96, 0x8c,0x5d,0xdb,0xc2,0xa8,0xce,0x81,0x35, 0x45,0xce,0xa2,0x17,0x8b,0x8f,0x6e,0x65, 0xa9,0x9c,0x36,0x5e,0xf3,0x5,0x15,0xb3, 0x28,0x28,0x7d,0xd2,0xc2,0xa2,0x59,0xd2, 0x76,0x67,0xaa,0x59,0x14,0x80,0xc8,0x36, 0xba,0x3c,0x80,0x6e,0x6b,0x2d,0xca,0x9c, 0xd,0xf3,0x53,0x7f,0xc9,0x9f,0x7e,0x1e, 0x2d,0xf8,0x81,0x73,0x50,0x88,0x8a,0x85, 0xad,0xd1,0xd,0x54,0xce,0x75,0xf6,0x21, 0x8a,0x76,0xca,0x55,0xfd,0xe6,0xb6,0xd0, 0x4d,0x54,0x8a,0xf6,0xb5,0x16,0x4d,0x23, 0x4d,0xb4,0x39,0x38,0x69,0xb1,0x39,0xf, 0x2d,0x38,0x1f,0x8d,0x7a,0xdb,0xc1,0x7b, 0x53,0xb7,0x36,0x67,0xd4,0x1,0xb6,0xdf, 0xef,0xf7,0xb7,0xfb,0xe9,0xad,0x36,0xbb, 0x28,0x99,0x4c,0x26,0x11,0x6a,0x30,0xf0, 0xe0,0xe4,0xac,0x54,0xb6,0xab,0xc5,0xe1, 0x1,0x5a,0x9c,0xec,0xaf,0x83,0x21,0xa1, 0x9f,0x43,0xb3,0xd1,0x35,0x28,0xb2,0x95, 0xeb,0xce,0x29,0x1c,0x85,0x7d,0x4f,0xcf, 0xe4,0xe0,0xdf,0xf4,0x7b,0xce,0x26,0x30, 0x81,0x69,0x82,0xf,0x83,0xe0,0x61,0x46, 0x6c,0x25,0xd5,0xae,0x72,0x81,0xdf,0xaa, 0x1a,0xfd,0x44,0x43,0x93,0x41,0x46,0xbf, 0xa2,0x45,0x45,0x6f,0xc,0x46,0x45,0xa1, 0x6b,0x6d,0xc6,0x52,0x8e,0x4e,0x95,0x85, 0xe8,0x72,0x66,0x74,0xdf,0x96,0x27,0xc5, 0x2f,0x5a,0xb5,0xe7,0xe5,0xc3,0x70,0xc9, 0xd1,0x7c,0xfc,0x9c,0x3a,0xe1,0x2a,0xc0, 0x9,0xad,0x93,0x39,0xa4,0xb0,0x9a,0x21, 0x21,0x36,0xf6,0x7c,0x1c,0x84,0xc4,0xb, 0x9,0x9,0x33,0x98,0xc2,0xa,0xe9,0x2, 0xd6,0xa8,0x84,0x3c,0x52,0xe4,0x93,0x9, 0x24,0x54,0x81,0xaf,0x5,0x83,0xe8,0x8, 0xb3,0x28,0x80,0xf6,0x19,0x8a,0x56,0x3a, 0xa7,0xda,0xdd,0xf5,0xc0,0x88,0x98,0x24, 0xb0,0x42,0x9a,0x42,0x1c,0xc3,0x3d,0xcc, 0x61,0x86,0xff,0x73,0xe4,0x50,0x4c,0xc1, 0x57,0x7,0xb2,0x20,0x71,0x81,0x15,0x49, 0x8c,0x1a,0x9,0x29,0x11,0xf0,0x31,0x24, 0x77,0x5e,0xc3,0x2b,0x4f,0x27,0xa4,0x13, 0x28,0x96,0x24,0xbe,0x16,0x75,0x13,0xaf, 0x4c,0xcc,0x9d,0x2f,0x4c,0xbf,0xa8,0x11, 0x1d,0x9b,0x53,0x57,0x31,0x69,0x7a,0xdd, 0x19,0xa9,0xde,0x7f,0x8c,0x9c,0xc0,0xf3, 0x89,0xaf,0xfc,0x44,0xa,0x65,0x8a,0x5a, 0x42,0x81,0x28,0xc7,0x29,0x2e,0x48,0x87, 0xf0,0x36,0x39,0x9b,0x5d,0xe4,0xd8,0x4a, 0x37,0xf2,0x7a,0x9c,0x9a,0x0,0x86,0xf6, 0xa,0x5f,0x8,0xee,0x2c,0x10,0x14,0x30, 0x3d,0x12,0xef,0x33,0x4f,0xb1,0x14,0x95, 0x2,0xc5,0xe7,0xf9,0x22,0xb8,0x70,0xf5, 0xb5,0xd5,0x95,0xad,0x25,0x29,0x92,0x0, 0x8b,0x87,0x2c,0x21,0xd9,0xaf,0x2f,0x88, 0x5b,0x4c,0x49,0x92,0x52,0xcd,0x1a,0x63, 0x92,0xa4,0xc4,0xeb,0xad,0xe3,0x20,0x11, 0xa4,0x24,0x25,0xd4,0xd1,0x98,0x2f,0xde, 0xb,0xe9,0x45,0xb8,0xd6,0x84,0x46,0x8b, 0x2b,0xcc,0xf5,0xc4,0x62,0x58,0x77,0x69, 0x31,0x0,0xcf,0xc6,0xb3,0x90,0xd1,0x1, 0x68,0x64,0x2f,0x8b,0x3c,0xda,0xcf,0xaf, 0x6,0x1c,0xc4,0xe0,0x1e,0xb1,0xc1,0x35, 0x11,0xf0,0x87,0x36,0xe2,0x7e,0x4,0x31, 0x2,0x73,0xf,0xcf,0x3e,0xd2,0x52,0x8f, 0x1c,0x6,0x19,0x8a,0x5e,0x63,0x35,0xd4, 0x5e,0x84,0x19,0x9e,0xbf,0xcc,0xf5,0x80, 0x86,0x79,0x88,0x1,0x45,0xe1,0xe3,0x53, 0x6c,0x41,0xd8,0xc4,0x1e,0x24,0x4a,0x51, 0xda,0xde,0x29,0x53,0xa7,0x21,0x61,0xef, 0x2e,0x2,0x4a,0xb5,0x5b,0x7d,0x4d,0x38, 0x61,0xae,0xad,0x2,0x18,0x24,0xcd,0x3, 0x40,0x93,0x4b,0x76,0xd1,0xf8,0xb2,0x6d, 0x14,0x4f,0xed,0x78,0x36,0xbe,0x9e,0x8d, 0x61,0x41,0x9b,0xe6,0x23,0x5,0x9a,0x5f, 0xe0,0x83,0x8c,0x74,0x4e,0x64,0x1a,0x52, 0xd6,0xc7,0x23,0xa6,0xe5,0x7c,0xe4,0x31, 0x6f,0xfd,0x51,0x26,0xa5,0x4c,0xd,0xa7, 0x4d,0xac,0x5e,0x79,0x81,0x4e,0x41,0x17, 0x21,0xba,0x95,0xf2,0x7f,0x8f,0xe7,0x51, 0x78,0xd,0xd1,0x95,0x84,0xe8,0xfa,0xb0, 0x65,0x18,0xfd,0x31,0x8c,0x1e,0x7d,0xe6, 0xf,0xdc,0x2f,0xee,0xe0,0x91,0xf6,0x5c, 0x3c,0x28,0xfa,0x93,0x28,0xd1,0x39,0xac, 0x69,0x9f,0x7e,0x44,0x3e,0xf5,0x7,0xc9, 0x3b,0x7f,0xf6,0x9c,0xff,0x3,0xce,0x19, 0x61,0x86,0x37,0xdc,0x70,0xb5,0x15,0xaa, 0x3d,0x52,0x2c,0xd5,0x1b,0x14,0xb5,0xb0, 0x88,0x37,0xdd,0x6f,0xb1,0x52,0x9a,0x93, 0x19,0xf9,0x6b,0xb1,0x34,0xa3,0x52,0xc9, 0xb7,0xb5,0x7c,0x7,0x22,0x7c,0x8f,0xb7, 0x52,0x78,0xe9,0xad,0x53,0xdb,0x3,0x1f, 0x6e,0xc7,0xbc,0x40,0x82,0xea,0xdd,0x81, 0x4f,0xa1,0xd9,0xf0,0x19,0x6c,0xb4,0xc1, 0xf6,0x7c,0xa3,0x9d,0xd3,0xcd,0x39,0x58, 0x62,0xb8,0xe9,0xfe,0x18,0x16,0xa3,0xd3, 0x41,0xf0,0xba,0xb9,0x6b,0xb9,0x72,0xb2, 0xb1,0x63,0xb7,0xd8,0xa3,0xef,0xb6,0x29, 0xf9,0x4,0x1a,0x49,0x6f,0xd1,0x3b,0xd, 0x4e,0xbe,0x3b,0x5e,0xa,0xf3,0x3a,0x70, 0xb2,0xd0,0x46,0xd0,0x1d,0x90,0x7b,0xc7, 0x9f,0x8e,0x3a,0xdc,0x3a,0x7,0x7,0xce, 0x26,0x27,0xf1,0xb2,0xcc,0x7a,0x2b,0xe1, 0x9d,0xae,0xe5,0xf,0xa3,0x6d,0xe1,0xc0, 0x1c,0x2d,0x7,0x20,0xcf,0xfb,0xea,0x44, 0xeb,0xe3,0x37,0x7c,0x11,0xa0,0xcf,0x6, 0x1f,0x33,0xd9,0x5a,0x44,0x0,0xed,0x9c, 0xb2,0x65,0x39,0x5c,0xfe,0x49,0xfd,0xc, 0x85,0x48,0x9c,0x15,0xf4,0x21,0x21,0xc8, 0x57,0x8d,0x6c,0xfb,0x8f,0xee,0x5a,0xf1, 0x6,0xf8,0xe3,0x1d,0xc6,0x91,0xfd,0x7a, 0x56,0xb5,0x3a,0x52,0xf4,0xc0,0xe1,0x74, 0x3e,0x20,0x66,0x50,0xa,0x27,0xb8,0x13, 0x66,0x27,0x1d,0x7d,0x6e,0x10,0xae,0xb7, 0xc7,0x5d,0x53,0xa8,0xbf,0x32,0x10,0x46, 0x9,0x3e,0xc4,0x68,0xce,0x3a,0xb1,0x43, 0xfc,0x9e,0xbc,0x32,0x19,0x9a,0x45,0xb5, 0xfa,0x77,0x3,0x63,0xa4,0x6c,0xd5,0xae, 0xf,0xfe,0xf9,0xce,0xf1,0x1f,0x8f,0xdb, 0xfc,0x67,0x66,0x60,0x22,0xd7,0x5f,0x1b, 0x40,0x83,0x51,0xcd,0xb7,0x87,0xc9,0xa2, 0xbe,0x3e,0xc9,0x8f,0x28,0x24,0xc8,0x71, 0xf2,0x61,0x52,0x8d,0x99,0xf7,0x85,0xa5, 0x4c,0x23,0xa7,0xe,0x89,0xc2,0xbe,0x95, 0x76,0xc7,0x8d,0xb2,0x88,0x3e,0xc0,0xf8, 0xef,0x31,0xfe,0x3,0xd5,0xdf,0x54,0xbd, 0x2c,0x6c,0xa8,0x12,0x0,0x0,}; const uint PAGE_index_size = 1190;
13dc97481c4d2927a0ab885efb0c55eb24ac3147
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
/sys/arch/prep/include/openpicreg.h
a63e7d312d124c4405194e04060cc755465ea432
[]
no_license
NetBSD/src
1a9cbc22ed778be638b37869ed4fb5c8dd616166
23ee83f7c0aea0777bd89d8ebd7f0cde9880d13c
refs/heads/trunk
2023-08-31T13:24:58.105962
2023-08-27T15:50:47
2023-08-27T15:50:47
88,439,547
656
348
null
2023-07-20T20:07:24
2017-04-16T20:03:43
null
UTF-8
C
false
false
137
h
openpicreg.h
/* $NetBSD: openpicreg.h,v 1.1 2002/05/30 16:10:05 nonaka Exp $ */ void openpic_init(unsigned char *); #include <powerpc/openpicreg.h>
784e1cfae0d4daea9db6f4849aa8e81cbf9d5a99
e683a0b8dbb87c7ceb99e0d06896174a559d2c67
/Tools/include/hash.h
71215a85a75d5c6e972b6bb81d2078ac102fc33c
[ "Apache-2.0" ]
permissive
bluewaysw/pcgeos
f093d79567d977d992f47065056d14d5a04b9f14
c6ae4c8e77b54b9ff654c3916f2191f8b1a1b65d
refs/heads/master
2023-08-31T00:17:54.481175
2023-08-29T19:00:49
2023-08-29T19:00:49
157,968,410
603
88
Apache-2.0
2023-09-13T07:44:06
2018-11-17T09:09:55
Assembly
UTF-8
C
false
false
5,111
h
hash.h
/*********************************************************************** * * Copyright (c) Berkeley Softworks 1988 -- All Rights Reserved * * PROJECT: PCGEOS * MODULE: Swat -- Hash Table Declarations * FILE: hash.h * * AUTHOR: Adam de Boor: Mar 23, 1989 * * REVISION HISTORY: * Date Name Description * ---- ---- ----------- * 3/23/89 ardeb Initial version * * DESCRIPTION: * Hash table declarations * * * $Id: hash.h,v 1.3 93/09/02 19:56:07 jimmy Exp $ * ***********************************************************************/ #ifndef _HASH_H_ #define _HASH_H_ /* * If not making SWAT, define the few constants needed to allow this * module to be used elsewhere (uic to be specific) */ #ifndef ISSWAT #ifndef FALSE #define FALSE (0) #endif #ifndef TRUE #define TRUE (!FALSE) #endif #include <stdio.h> #define malloc_tagged(a,b) malloc(a) #if defined(__HIGHC__) typedef unsigned long Opaque; #else typedef void *Opaque; #endif typedef char *Address; typedef int Boolean; #endif /* !ISSWAT */ /* * Structure for the insque and remque calls */ typedef struct { struct Hash_Entry *next; struct Hash_Entry *prev; } HashLink; /* * The following defines one entry in the hash table. */ typedef struct Hash_Entry { HashLink links; /* Used to link together all the * entries associated with the same * bucket. */ Opaque data; /* Arbitrary piece of data associated * with key. */ union { Address ptr; /* One-word key value to identify entry. */ int words[1]; /* N-word key value. Note: the actual * size may be longer if necessary to * hold the entire key. */ char name[4]; /* Text name of this entry. Note: the * actual size may be longer if * necessary to hold the whole string. * This MUST be the last entry in the * structure!!! */ } key; /* Union of possible keys--all the same size */ } Hash_Entry; #define NullHash_Entry (Hash_Entry *) NULL /* * A hash table consists of an array of pointers to hash * lists. Tables can be organized in either of three ways, depending * on the type of comparison keys: * * Strings: these are NULL-terminated; their address * is passed to HashFind as a (char *). * Single-word keys: these may be anything, but must be passed * to Hash_Find as an Address. * Multi-word keys: these may also be anything; their address * is passed to HashFind as an Address. * * Single-word keys are fastest, but most restrictive. */ #define HASH_STRING_KEYS 0 #define HASH_ONE_WORD_KEYS 1 typedef struct Hash_Table { HashLink *bucketPtr; /* Pointer to array of HashLink, one * for each bucket in the table. */ int size; /* Actual size of array. */ int limit; /* Average chain-length at which the table * is expanded */ int numEntries; /* Number of entries in the table. */ int downShift; /* Shift count, used in hashing function. */ int mask; /* Used to select bits for hashing. */ int keyType; /* Type of keys used in table: * HASH_STRING_KEYS, HASH_ONE_WORD_KEYS, * or >1 means keyType gives number of words * in keys. */ } Hash_Table; /* * The following structure is used by the searching routines * to record where we are in the search. */ typedef struct Hash_Search { Hash_Table *tablePtr; /* Table being searched. */ int nextIndex; /* Next bucket to check (after current). */ Hash_Entry *hashEntryPtr; /* Next entry to check in current bucket. */ HashLink *hashList; /* Hash chain currently being checked. */ } Hash_Search; /* * Macros. */ /* * Opaque Hash_GetValue(Hash_Entry *h); */ #define Hash_GetValue(h) ((h)->data) /* * Hash_SetValue(HashEntry *h, Opaque val); */ #define Hash_SetValue(h, val) ((h)->data = (Opaque) (val)) /* * Hash_Size(n) returns the number of words in an object of n bytes */ #define Hash_Size(n) (((n) + sizeof (int) - 1) / sizeof (int)) /* * The following procedure declarations and macros * are the only things that should be needed outside * the implementation code. */ extern Hash_Entry * Hash_CreateEntry(Hash_Table *tablePtr, Address key, Boolean *newPtr); extern void Hash_DeleteTable(Hash_Table *tablePtr); extern void Hash_DeleteEntry(Hash_Table *tablePtr, Hash_Entry *hashEntryPtr); extern Hash_Entry * Hash_EnumFirst(Hash_Table *tablePtr, Hash_Search *searchPtr); extern Hash_Entry * Hash_EnumNext(Hash_Search *searchPtr); extern Hash_Entry * Hash_FindEntry(Hash_Table *tablePtr, Address key); extern void Hash_InitTable(Hash_Table *tablePtr, int numBuckets, int keyType, int limit); extern void Hash_PrintStats(Hash_Table *tablePtr, void (*proc)(Opaque data, char *msg), Opaque data); #endif /* _HASH_H_ */
64dafcc17b016e480eeb61200d6372ade9b442df
46f992ec5ac6ad7bda1ef3e19cb7a6d601b5d680
/misc/exampleSafv3.c
a4215ac2c081900b67b0f86af18783293788baa6
[]
no_license
ANGSD/angsd
b4bfdb03fb6887e19835b0f461d3dea84828216c
8a58e179d23a3230adf2fa4115e16ecf057a9695
refs/heads/master
2023-09-03T18:29:16.676109
2023-08-20T22:49:37
2023-08-20T22:49:37
21,312,324
194
70
null
2023-08-20T07:45:41
2014-06-28T22:38:46
C++
UTF-8
C
false
false
1,684
c
exampleSafv3.c
/* norm<-function(x) x/sum(x) sim1<-function(x,ndip){ d<-c(0,1/(1:(2*ndip))) d <- c(0,1/(1:(2*ndip)))+ rnorm(2*ndip+1,sd=0.01)+1000 d <- norm(d) log(d)-max(log(d)) } d <- t(sapply(1:1000,sim1,ndip=20)) write.table(d,file='small.txt',row.names=F,col.names=F,quote=F) gcc convert.c -lhts cat small.txt|./a.out */ #include <htslib/bgzf.h> #include <stdio.h> #include <zlib.h> #include <string.h> #include <stdlib.h> #define NMAX 96 int main(){ FILE *fpindex = fopen("test.saf.idx","wb"); BGZF *pos = bgzf_open("test.saf.pos.gz","wb"); BGZF *saf = bgzf_open("test.saf.gz","wb"); const char *magic="safv3"; //write magic fwrite(magic,sizeof(char),8,fpindex); bgzf_write(pos,magic,8*sizeof(char)); bgzf_write(saf,magic,8*sizeof(char)); bgzf_flush(pos);bgzf_flush(saf); int64_t offs[2]={bgzf_tell(pos),bgzf_tell(saf)}; char buffer[4096]; float data[NMAX]; size_t nbin=-1; size_t nsites =0; while(fgets(buffer,4096,stdin)){ int at=0; data[at++] =atof(strtok(buffer,"\t\n ")); char *tok=NULL; while(((tok=strtok(NULL,"\t\n ")))){ data[at++] = atof(tok); } if(nbin==-1) nbin=at; if(at!=nbin) exit(1); bgzf_write(saf,data,sizeof(float)*nbin); nsites++; } for(int i=0;i<nsites;i++) bgzf_write(pos,&i,sizeof(int)*1); //write index nbin--; fwrite(&nbin,sizeof(size_t),1,fpindex); const char* nam="chr1X"; size_t clen = strlen(nam); fwrite(&clen,sizeof(size_t),1,fpindex); fwrite(nam,sizeof(char),clen,fpindex); fwrite(&nsites,sizeof(size_t),1,fpindex); fwrite(offs,sizeof(int64_t),2,fpindex); fclose(fpindex); bgzf_close(pos); bgzf_close(saf); return 0; }
f4c6aed36df8a88199eaf82f6deff14b7770dc8d
9ceacf33fd96913cac7ef15492c126d96cae6911
/sys/dev/pci/if_liireg.h
bca8b156a8f5b8817920216185d89412db133630
[]
no_license
openbsd/src
ab97ef834fd2d5a7f6729814665e9782b586c130
9e79f3a0ebd11a25b4bff61e900cb6de9e7795e9
refs/heads/master
2023-09-02T18:54:56.624627
2023-09-02T15:16:12
2023-09-02T15:16:12
66,966,208
3,394
1,235
null
2023-08-08T02:42:25
2016-08-30T18:18:25
C
UTF-8
C
false
false
11,611
h
if_liireg.h
/* $OpenBSD: if_liireg.h,v 1.4 2008/09/01 14:38:31 brad Exp $ */ /* * Copyright (c) 2007 The NetBSD Foundation. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE 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. */ /* * PCI configuration space seems to be mapped in the first 0x100 bytes of * the register area. */ /* SPI Flash Control register */ #define LII_SFC 0x0200 #define SFC_STS_NON_RDY 0x00000001 #define SFC_STS_WEN 0x00000002 #define SFC_STS_WPEN 0x00000080 #define SFC_DEV_STS_MASK 0x000000ff #define SFC_DEV_STS_SHIFT 0 #define SFC_INS_MASK 0x07 #define SFC_INS_SHIFT 8 #define SFC_START 0x00000800 #define SFC_EN_VPD 0x00002000 #define SFC_LDSTART 0x00008000 #define SFC_CS_HI_MASK 0x03 #define SFC_CS_HI_SHIFT 16 #define SFC_CS_HOLD_MASK 0x03 #define SFC_CS_HOLD_SHIFT 18 #define SFC_CLK_LO_MASK 0x03 #define SFC_CLK_LO_SHIFT 20 #define SFC_CLK_HI_MASK 0x03 #define SFC_CLK_HI_SHIFT 22 #define SFC_CS_SETUP_MASK 0x03 #define SFC_CS_SETUP_SHIFT 24 #define SFC_EROMPGSZ_MASK 0x03 #define SFC_EROMPGSZ_SHIFT 26 #define SFC_WAIT_READY 0x10000000 /* SPI Flash Address register */ #define LII_SF_ADDR 0x0204 /* SPI Flash Data register */ #define LII_SF_DATA 0x0208 /* SPI Flash Configuration register */ #define LII_SFCF 0x020c #define SFCF_LD_ADDR_MASK 0x00ffffff #define SFCF_LD_ADDR_SHIFT 0 #define SFCF_VPD_ADDR_MASK 0x03 #define SFCF_VPD_ADDR_SHIFT 24 #define SFCF_LD_EXISTS 0x04000000 /* SPI Flash op codes programmation registers */ #define LII_SFOP_PROGRAM 0x0210 #define LII_SFOP_SC_ERASE 0x0211 #define LII_SFOP_CHIP_ERASE 0x0212 #define LII_SFOP_RDID 0x0213 #define LII_SFOP_WREN 0x0214 #define LII_SFOP_RDSR 0x0215 #define LII_SFOP_WRSR 0x0216 #define LII_SFOP_READ 0x0217 /* TWSI Control register, whatever that is */ #define LII_TWSIC 0x0218 #define TWSIC_LD_OFFSET_MASK 0x000000ff #define TWSIC_LD_OFFSET_SHIFT 0 #define TWSIC_LD_SLV_ADDR_MASK 0x07 #define TWSIC_LD_SLV_ADDR_SHIFT 8 #define TWSIC_SW_LDSTART 0x00000800 #define TWSIC_HW_LDSTART 0x00001000 #define TWSIC_SMB_SLV_ADDR_MASK 0x7F #define TWSIC_SMB_SLV_ADDR_SHIFT 15 #define TWSIC_LD_EXIST 0x00400000 #define TWSIC_READ_FREQ_SEL_MASK 0x03 #define TWSIC_READ_FREQ_SEL_SHIFT 23 #define TWSIC_FREQ_SEL_100K 0 #define TWSIC_FREQ_SEL_200K 1 #define TWSIC_FREQ_SEL_300K 2 #define TWSIC_FREQ_SEL_400K 3 #define TWSIC_WRITE_FREQ_SEL_MASK 0x03 #define TWSIC_WRITE_FREQ_SEL_SHIFT 24 /* PCI-Express Device Misc. Control register? (size unknown) */ #define LII_PCEDMC 0x021c #define PCEDMC_RETRY_BUFDIS 0x01 #define PCEDMC_EXT_PIPE 0x02 #define PCEDMC_SPIROM_EXISTS 0x04 #define PCEDMC_SERDES_ENDIAN 0x08 #define PCEDMC_SERDES_SEL_DIN 0x10 /* PCI-Express PHY Miscellaneous register (size unknown) */ #define LII_PCEPM 0x1000 #define PCEPM_FORCE_RCV_DET 0x04 /* Selene Master Control register */ #define LII_SMC 0x1400 #define SMC_SOFT_RST 0x00000001 #define SMC_MTIMER_EN 0x00000002 #define SMC_ITIMER_EN 0x00000004 #define SMC_MANUAL_INT 0x00000008 #define SMC_REV_NUM_MASK 0xff #define SMC_REV_NUM_SHIFT 16 #define SMC_DEV_ID_MASK 0xff #define SMC_DEV_ID_SHIFT 24 /* Timer Initial Value register */ #define LII_TIV 0x1404 /* IRQ Moderator Timer Initial Value register */ #define LII_IMTIV 0x1408 /* PHY Control register */ #define LII_PHYC 0x140c #define PHYC_ENABLE 0x0001 /* IRQ Anti-Lost Timer Initial Value register --> Time allowed for software to clear the interrupt */ #define LII_IALTIV 0x140e /* Block Idle Status register --> Bit set if matching state machine is not idle */ #define LII_BIS 0x1410 #define BIS_RXMAC 0x00000001 #define BIS_TXMAC 0x00000002 #define BIS_DMAR 0x00000004 #define BIS_DMAW 0x00000008 /* MDIO Control register */ #define LII_MDIOC 0x1414 #define MDIOC_DATA_MASK 0x0000ffff #define MDIOC_DATA_SHIFT 0 #define MDIOC_REG_MASK 0x1f #define MDIOC_REG_SHIFT 16 #define MDIOC_WRITE 0x00000000 #define MDIOC_READ 0x00200000 #define MDIOC_SUP_PREAMBLE 0x00400000 #define MDIOC_START 0x00800000 #define MDIOC_CLK_SEL_MASK 0x07 #define MDIOC_CLK_SEL_SHIFT 24 #define MDIOC_CLK_25_4 0 #define MDIOC_CLK_25_6 2 #define MDIOC_CLK_25_8 3 #define MDIOC_CLK_25_10 4 #define MDIOC_CLK_25_14 5 #define MDIOC_CLK_25_20 6 #define MDIOC_CLK_25_28 7 #define MDIOC_BUSY 0x08000000 /* Time to wait for MDIO, waiting for 2us in-between */ #define MDIO_WAIT_TIMES 10 /* SerDes Lock Detect Control and Status register */ #define LII_SERDES 0x1424 #define SERDES_LOCK_DETECT 0x01 #define SERDES_LOCK_DETECT_EN 0x02 /* MAC Control register */ #define LII_MACC 0x1480 #define MACC_TX_EN 0x00000001 #define MACC_RX_EN 0x00000002 #define MACC_TX_FLOW_EN 0x00000004 #define MACC_RX_FLOW_EN 0x00000008 #define MACC_LOOPBACK 0x00000010 #define MACC_FDX 0x00000020 #define MACC_ADD_CRC 0x00000040 #define MACC_PAD 0x00000080 #define MACC_PREAMBLE_LEN_MASK 0x0f #define MACC_PREAMBLE_LEN_SHIFT 10 #define MACC_STRIP_VLAN 0x00004000 #define MACC_PROMISC_EN 0x00008000 #define MACC_DBG_TX_BKPRESSURE 0x00100000 #define MACC_ALLMULTI_EN 0x02000000 #define MACC_BCAST_EN 0x04000000 #define MACC_MACLP_CLK_PHY 0x08000000 #define MACC_HDX_LEFT_BUF_MASK 0x0f #define MACC_HDX_LEFT_BUF_SHIFT 28 /* MAC IPG/IFG Control register */ #define LII_MIPFG 0x1484 #define MIPFG_IPGT_MASK 0x0000007f #define MIPFG_IPGT_SHIFT 0 #define MIPFG_MIFG_MASK 0xff #define MIPFG_MIFG_SHIFT 8 #define MIPFG_IPGR1_MASK 0x7f #define MIPFG_IPGR1_SHIFT 16 #define MIPFG_IPGR2_MASK 0x7f #define MIPFG_IPGR2_SHIFT 24 /* MAC Address registers */ #define LII_MAC_ADDR_0 0x1488 #define LII_MAC_ADDR_1 0x148c /* Multicast Hash Table register */ #define LII_MHT 0x1490 /* MAC Half-Duplex Control register */ #define LII_MHDC 0x1498 #define MHDC_LCOL_MASK 0x000003ff #define MHDC_LCOL_SHIFT 0 #define MHDC_RETRY_MASK 0x0f #define MHDC_RETRY_SHIFT 12 #define MHDC_EXC_DEF_EN 0x00010000 #define MHDC_NO_BACK_C 0x00020000 #define MHDC_NO_BACK_P 0x00040000 #define MHDC_ABEDE 0x00080000 #define MHDC_ABEBT_MASK 0x0f #define MHDC_ABEBT_SHIFT 20 #define MHDC_JAMIPG_MASK 0x0f #define MHDC_JAMIPG_SHIFT 24 /* MTU Control register */ #define LII_MTU 0x149c /* WOL Control register */ #define LII_WOLC #define WOLC_PATTERN_EN 0x00000001 #define WOLC_PATTERN_PME_EN 0x00000002 #define WOLC_MAGIC_EN 0x00000004 #define WOLC_MAGIC_PME_EN 0x00000008 #define WOLC_LINK_CHG_EN 0x00000010 #define WOLC_LINK_CHG_PME_EN 0x00000020 #define WOLC_PATTERN_ST 0x00000100 #define WOLC_MAGIC_ST 0x00000200 #define WOLC_LINK_CHG_ST 0x00000400 #define WOLC_PT0_EN 0x00010000 #define WOLC_PT1_EN 0x00020000 #define WOLC_PT2_EN 0x00040000 #define WOLC_PT3_EN 0x00080000 #define WOLC_PT4_EN 0x00100000 #define WOLC_PT0_MATCH 0x01000000 #define WOLC_PT1_MATCH 0x02000000 #define WOLC_PT2_MATCH 0x04000000 #define WOLC_PT3_MATCH 0x08000000 #define WOLC_PT4_MATCH 0x10000000 /* Internal SRAM Partition register */ #define LII_SRAM_TXRAM_END 0x1500 #define LII_SRAM_RXRAM_END 0x1502 /* Descriptor Control registers */ #define LII_DESC_BASE_ADDR_HI 0x1540 #define LII_TXD_BASE_ADDR_LO 0x1544 #define LII_TXD_BUFFER_SIZE 0x1548 #define LII_TXS_BASE_ADDR_LO 0x154c #define LII_TXS_NUM_ENTRIES 0x1550 #define LII_RXD_BASE_ADDR_LO 0x1554 #define LII_RXD_NUM_ENTRIES 0x1558 /* DMAR Control register */ #define LII_DMAR 0x1580 #define DMAR_EN 0x01 /* TX Cur-Through Control register */ #define LII_TX_CUT_THRESH 0x1590 /* DMAW Control register */ #define LII_DMAW 0x15a0 #define DMAW_EN 0x01 /* Flow Control registers */ #define LII_PAUSE_ON_TH 0x15a8 #define LII_PAUSE_OFF_TH 0x15aa /* Mailbox registers */ #define LII_MB_TXD_WR_IDX 0x15f0 #define LII_MB_RXD_RD_IDX 0x15f4 /* Interrupt Status register */ #define LII_ISR 0x1600 #define ISR_TIMER 0x00000001 #define ISR_MANUAL 0x00000002 #define ISR_RXF_OV 0x00000004 #define ISR_TXF_UR 0x00000008 #define ISR_TXS_OV 0x00000010 #define ISR_RXS_OV 0x00000020 #define ISR_LINK_CHG 0x00000040 #define ISR_HOST_TXD_UR 0x00000080 #define ISR_HOST_RXD_OV 0x00000100 #define ISR_DMAR_TO_RST 0x00000200 #define ISR_DMAW_TO_RST 0x00000400 #define ISR_PHY 0x00000800 #define ISR_TS_UPDATE 0x00010000 #define ISR_RS_UPDATE 0x00020000 #define ISR_TX_EARLY 0x00040000 #define ISR_UR_DETECTED 0x01000000 #define ISR_FERR_DETECTED 0x02000000 #define ISR_NFERR_DETECTED 0x04000000 #define ISR_CERR_DETECTED 0x08000000 #define ISR_PHY_LINKDOWN 0x10000000 #define ISR_DIS_INT 0x80000000 #define ISR_TX_EVENT (ISR_TXF_UR | ISR_TXS_OV | \ ISR_HOST_TXD_UR | ISR_TS_UPDATE | \ ISR_TX_EARLY) #define ISR_RX_EVENT (ISR_RXF_OV | ISR_RXS_OV | \ ISR_HOST_RXD_OV | ISR_RS_UPDATE) /* Interrupt Mask register */ #define LII_IMR 0x1604 #define IMR_NORMAL_MASK (ISR_DMAR_TO_RST | ISR_DMAW_TO_RST | \ ISR_PHY | ISR_PHY_LINKDOWN | \ ISR_TS_UPDATE | ISR_RS_UPDATE) /* MAC RX Statistics registers */ #define LII_STS_RX_PAUSE 0x1700 #define LII_STS_RXD_OV 0x1704 #define LII_STS_RXS_OV 0x1708 #define LII_STS_RX_FILTER 0x170c struct tx_pkt_header { uint16_t txph_size; #define LII_TXH_ADD_VLAN_TAG 0x8000 uint16_t txph_vlan; } __packed; struct tx_pkt_status { uint16_t txps_size; uint16_t txps_flags :15; #define LII_TXF_SUCCESS 0x0001 #define LII_TXF_BCAST 0x0002 #define LII_TXF_MCAST 0x0004 #define LII_TXF_PAUSE 0x0008 #define LII_TXF_CTRL 0x0010 #define LII_TXF_DEFER 0x0020 #define LII_TXF_EXC_DEFER 0x0040 #define LII_TXF_SINGLE_COL 0x0080 #define LII_TXF_MULTI_COL 0x0100 #define LII_TXF_LATE_COL 0x0200 #define LII_TXF_ABORT_COL 0x0400 #define LII_TXF_UNDERRUN 0x0800 uint16_t txps_update:1; } __packed; struct rx_pkt { uint16_t rxp_size; uint16_t rxp_flags :15; #define LII_RXF_SUCCESS 0x0001 #define LII_RXF_BCAST 0x0002 #define LII_RXF_MCAST 0x0004 #define LII_RXF_PAUSE 0x0008 #define LII_RXF_CTRL 0x0010 #define LII_RXF_CRC 0x0020 #define LII_RXF_CODE 0x0040 #define LII_RXF_RUNT 0x0080 #define LII_RXF_FRAG 0x0100 #define LII_RXF_TRUNC 0x0200 #define LII_RXF_ALIGN 0x0400 #define LII_RXF_VLAN 0x0800 uint16_t rxp_update:1; uint16_t rxp_vlan; uint16_t __pad; uint8_t rxp_data[1528]; } __packed;
9af08fdbf41c78d6b1d4d40307d200717ce53bb8
8e9b21f8b0e8bae10e333b2cdc45c0c70df361fe
/kernel/fs/char_dev.c
4bd7211d1891cec00cdc7cd59b51b3f525eaa753
[ "GPL-3.0-only" ]
permissive
tyler569/nightingale
6173abf28d1e5399d77ec3d9977ab7c9562d0913
ea07ccb768105d942b4391c79fde2089c06dcea7
refs/heads/master
2023-08-04T20:49:28.852042
2023-07-27T16:31:20
2023-07-27T17:06:43
80,633,386
147
13
MIT
2019-04-12T01:31:33
2017-02-01T15:28:03
C
UTF-8
C
false
false
1,309
c
char_dev.c
#include <basic.h> #include <ng/fs/char_dev.h> #include <ng/fs/file.h> #include <ng/fs/inode.h> #include <ng/random.h> #include <string.h> #include <errno.h> ssize_t basic_char_dev_read(struct file *file, char *buffer, size_t len) { size_t i; switch (file->inode->device_minor) { case FS_DEV_NULL: return 0; case FS_DEV_ZERO: memset(buffer, 0, len); return len; case FS_DEV_RANDOM: return get_random(buffer, len); case FS_DEV_INC: for (i = 0; i < len / sizeof(unsigned); i++) { ((unsigned *)buffer)[i] = i; } return i * sizeof(unsigned); default: return -ENODEV; } } ssize_t basic_char_dev_write(struct file *file, const char *buffer, size_t len) { switch (file->inode->device_minor) { case FS_DEV_NULL: return len; case FS_DEV_ZERO: return len; case FS_DEV_RANDOM: add_to_random(buffer, len); return len; case FS_DEV_INC: return len; default: return -ENODEV; } } struct file_operations basic_char_dev_ops = { .read = basic_char_dev_read, .write = basic_char_dev_write, }; extern struct file_operations tty_ops; struct file_operations *char_drivers[256] = { [0] = &basic_char_dev_ops, [1] = &tty_ops, };
ae59f8d404d8c705cc1e7f533c71e419d0ec36c7
03b2c80dbc41e904b167d504666e27d798da5447
/test/test_quote.c
1b3eb9aac1990607b41c96a92ea02c8e537df8b1
[ "Unlicense" ]
permissive
nptcl/npt
7c1570b497cdce0b8971cb445fbc04cb500232d3
aa714a2370ac9fa5348c2fc96159b40b9de3de07
refs/heads/master
2023-03-20T09:13:54.669118
2022-07-02T11:17:44
2022-07-02T11:17:44
171,985,905
160
12
Unlicense
2023-03-11T01:36:37
2019-02-22T03:11:34
C
UTF-8
C
false
false
25,078
c
test_quote.c
#include "quote.c" #include "character.h" #include "clos.h" #include "common.h" #include "degrade.h" #include "package.h" #include "pathname.h" #include "print.h" #include "reader.h" #include "stream.h" #include "symbol.h" #include "syscall.h" #include "type.h" #include "type_table.h" static int test_quote_heap(void) { addr pos, check; quote_heap(&pos, QuoteExecute_Nconc, T); test(GetType(pos) == LISPTYPE_QUOTE, "quote_heap1"); test(RefQuoteType(pos) == QuoteExecute_Nconc, "quote_heap2"); GetQuote(pos, QuoteIndex_Value, &check); test(check == T, "quote_heap3"); GetQuote(pos, QuoteIndex_Print, &check); test(check == T, "quote_heap4"); test(quote_nconc_p(pos), "quote_heap5"); test(! quote_back_p(pos), "quote_heap6"); quote_heap(&pos, QuoteType_Back, Nil); test(quote_back_p(pos), "quote_heap7"); quote_heap(&pos, QuoteType_Comma, Nil); test(quote_comma_p(pos), "quote_heap8"); quote_heap(&pos, QuoteType_AtSign, Nil); test(quote_atsign_p(pos), "quote_heap9"); quote_heap(&pos, QuoteType_Dot, Nil); test(quote_dot_p(pos), "quote_heap10"); RETURN; } /* * bq_process */ static int test_bq_atom(void) { addr pos; fixnum_heap(&pos, 10); test(bq_atom(pos), "bq_atom1"); consnil_heap(&pos); test(! bq_atom(pos), "bq_atom2"); quote_heap(&pos, QuoteExecute_Append, Nil); test(! bq_atom(pos), "bq_atom3"); RETURN; } static int test_bq_bracket(void) { addr pos, check; fixnum_heap(&pos, 10); bq_bracket_(pos, &pos); test(quote_list_p(pos), "bq_bracket1"); getvalue_quote(pos, &pos); test(consp(pos), "bq_bracket2"); GetCons(pos, &check, &pos); test(quote_quote_p(check), "bq_bracket3"); test(pos == Nil, "bq_bracket4"); getvalue_quote(check, &check); test(RefFixnum(check) == 10, "bq_bracket5"); fixnum_heap(&pos, 20); quote_heap(&pos, QuoteType_Comma, pos); bq_bracket_(pos, &pos); test(quote_list_p(pos), "bq_bracket6"); getvalue_quote(pos, &pos); test(consp(pos), "bq_bracket7"); GetCons(pos, &check, &pos); test(RefFixnum(check) == 20, "bq_bracket8"); test(pos == Nil, "bq_bracket9"); fixnum_heap(&pos, 30); quote_heap(&pos, QuoteType_AtSign, pos); bq_bracket_(pos, &pos); test(RefFixnum(pos) == 30, "bq_bracket10"); fixnum_heap(&pos, 40); quote_heap(&pos, QuoteType_Dot, pos); bq_bracket_(pos, &pos); test(quote_clobberable_p(pos), "bq_bracket11"); getvalue_quote(pos, &pos); test(RefFixnum(pos) == 40, "bq_bracket12"); fixnum_heap(&pos, 10); list_heap(&pos, pos, NULL); bq_bracket_(pos, &pos); test(quote_list_p(pos), "bq_bracket13"); getvalue_quote(pos, &pos); RETURN; } static int test_bq_process_list(void) { addr pos, check, value; readstring_debug(&pos, "(10 20)"); bq_process_list_(pos, &pos); test(quote_append_p(pos), "bq_process_list1"); getvalue_quote(pos, &pos); test(length_list_unsafe(pos) == 2, "bq_process_list2"); GetCons(pos, &check, &pos); test(quote_list_p(check), "bq_process_list3"); getvalue_quote(check, &check); test(consp(check), "bq_process_list4"); GetCons(check, &value, &check); test(quote_quote_p(value), "bq_process_list5"); getvalue_quote(value, &value); test(RefFixnum(value) == 10, "bq_process_list6"); test(check == Nil, "bq_process_list7"); GetCons(pos, &check, &pos); test(quote_list_p(check), "bq_process_list8"); getvalue_quote(check, &check); test(consp(check), "bq_process_list9"); GetCons(check, &value, &check); test(quote_quote_p(value), "bq_process_list10"); getvalue_quote(value, &value); test(RefFixnum(value) == 20, "bq_process_list11"); test(check == Nil, "bq_process_list12"); readstring_debug(&pos, "(10 . 20)"); bq_process_list_(pos, &pos); test(quote_append_p(pos), "bq_process_list13"); getvalue_quote(pos, &pos); test(length_list_unsafe(pos) == 2, "bq_process_list14"); GetCons(pos, &check, &pos); test(quote_list_p(check), "bq_process_list15"); getvalue_quote(check, &check); test(consp(check), "bq_process_list16"); GetCons(check, &value, &check); test(quote_quote_p(value), "bq_process_list17"); getvalue_quote(value, &value); test(RefFixnum(value) == 10, "bq_process_list18"); test(check == Nil, "bq_process_list19"); GetCons(pos, &check, &pos); test(quote_quote_p(check), "bq_process_list20"); getvalue_quote(check, &check); test(RefFixnum(check) == 20, "bq_process_list21"); quote_heap(&pos, QuoteType_Comma, readr_debug("20")); cons_heap(&pos, readr_debug("10"), pos); bq_process_list_(pos, &pos); test(quote_append_p(pos), "bq_process_list22"); getvalue_quote(pos, &pos); test(length_list_unsafe(pos) == 2, "bq_process_list23"); GetCons(pos, &check, &pos); test(quote_list_p(check), "bq_process_list24"); getvalue_quote(check, &check); test(consp(check), "bq_process_list25"); GetCons(check, &value, &check); test(quote_quote_p(value), "bq_process_list26"); getvalue_quote(value, &value); test(RefFixnum(value) == 10, "bq_process_list27"); test(check == Nil, "bq_process_list28"); GetCons(pos, &check, &pos); test(RefFixnum(check) == 20, "bq_process_list29"); RETURN; } static int test_bq_process(void) { addr pos, check, value; bq_process_(readr_debug("10"), &pos); test(quote_quote_p(pos), "bq_process1"); getvalue_quote(pos, &pos); test(RefFixnum(pos) == 10, "bq_process2"); quote_heap(&pos, QuoteType_Comma, readr_debug("10")); bq_process_(pos, &pos); test(RefFixnum(pos) == 10, "bq_process3"); readstring_debug(&pos, "(10 20)"); bq_process_(pos, &pos); test(quote_append_p(pos), "bq_process4"); getvalue_quote(pos, &pos); test(length_list_unsafe(pos) == 2, "bq_process5"); GetCons(pos, &check, &pos); test(quote_list_p(check), "bq_process6"); getvalue_quote(check, &check); test(consp(check), "bq_process7"); GetCons(check, &value, &check); test(quote_quote_p(value), "bq_process8"); getvalue_quote(value, &value); test(RefFixnum(value) == 10, "bq_process9"); test(check == Nil, "bq_process10"); RETURN; } /* * bq_simplify */ static int test_bq_maptree1(addr pos, addr *ret) { if (GetType(pos) == LISPTYPE_FIXNUM) fixnum_heap(ret, RefFixnum(pos) + 1); else *ret = pos; return 0; } static int test_bq_maptree(void) { addr pos, check; fixnum_heap(&pos, 10); bq_maptree_(test_bq_maptree1, pos, &pos); test(RefFixnum(pos) == 11, "bq_maptree1"); fixnum_heap(&pos, 20); quote_heap(&pos, QuoteExecute_Quote, pos); bq_maptree_(test_bq_maptree1, pos, &pos); test(quote_quote_p(pos), "bq_maptree2"); getvalue_quote(pos, &pos); test(RefFixnum(pos) == 21, "bq_maptree3"); readstring_debug(&pos, "(10 20)"); bq_maptree_(test_bq_maptree1, pos, &pos); GetCons(pos, &check, &pos); test(RefFixnum(check) == 11, "bq_maptree4"); GetCons(pos, &check, &pos); test(RefFixnum(check) == 21, "bq_maptree5"); test(pos == Nil, "bq_maptree6"); RETURN; } static int test_bq_null_or_quoted(void) { addr pos; test(bq_null_or_quoted(Nil), "bq_null_or_quoted1"); test(! bq_null_or_quoted(T), "bq_null_or_quoted2"); quote_heap(&pos, QuoteExecute_Quote, T); test(bq_null_or_quoted(pos), "bq_null_or_quoted3"); RETURN; } static int test_getvalue_null_or_quoted(void) { addr pos; getvalue_null_or_quoted(Nil, &pos); test(pos == Nil, "getvalue_null_or_quoted1"); quote_heap(&pos, QuoteExecute_Quote, T); getvalue_null_or_quoted(pos, &pos); test(pos == T, "getvalue_null_or_quoted2"); RETURN; } static int test_quote_nil_p(void) { addr pos; quote_heap(&pos, QuoteExecute_Quote, Nil); test(quote_nil_p(pos), "quote_nil_p1"); quote_heap(&pos, QuoteExecute_Quote, T); test(! quote_nil_p(pos), "quote_nil_p2"); test(! quote_nil_p(T), "quote_nil_p3"); test(! quote_nil_p(Nil), "quote_nil_p4"); RETURN; } static int test_bq_splicing_frob(void) { addr pos; quote_heap(&pos, QuoteType_AtSign, Nil); test(bq_splicing_frob(pos), "bq_splicing_frob1"); quote_heap(&pos, QuoteType_Dot, Nil); test(bq_splicing_frob(pos), "bq_splicing_frob2"); quote_heap(&pos, QuoteType_Comma, Nil); test(! bq_splicing_frob(pos), "bq_splicing_frob3"); test(! bq_splicing_frob(Nil), "bq_splicing_frob4"); RETURN; } static int test_bq_attach_append(void) { addr pos, left, right; pos = NULL; bq_attach_append_(readr_debug("10"), Nil, &pos); test(RefFixnum(pos) == 10, "bq_attach_append1"); quote_heap(&pos, QuoteExecute_Quote, Nil); bq_attach_append_(readr_debug("20"), pos, &pos); test(RefFixnum(pos) == 20, "bq_attach_append2"); quote_heap(&pos, QuoteType_AtSign, readr_debug("30")); bq_attach_append_(pos, Nil, &pos); test(quote_append_p(pos), "bq_attach_append3"); getvalue_quote(pos, &pos); test(singlep(pos), "bq_attach_append4"); GetCar(pos, &pos); test(quote_atsign_p(pos), "bq_attach_append5"); getvalue_quote(pos, &pos); test(RefFixnum(pos) == 30, "bq_attach_append6"); quote_heap(&left, QuoteExecute_Quote, readr_debug("(a b)")); quote_heap(&right, QuoteExecute_Quote, readr_debug("(c d e)")); bq_attach_append_(left, right, &pos); test(quote_quote_p(pos), "bq_attach_append7"); getvalue_quote(pos, &pos); test(length_list_unsafe(pos) == 5, "bq_attach_append8"); GetCons(pos, &left, &pos); test(left == readr_debug("a"), "bq_attach_append9"); GetCons(pos, &left, &pos); test(left == readr_debug("b"), "bq_attach_append10"); GetCons(pos, &left, &pos); test(left == readr_debug("c"), "bq_attach_append11"); GetCons(pos, &left, &pos); test(left == readr_debug("d"), "bq_attach_append12"); GetCons(pos, &left, &pos); test(left == readr_debug("e"), "bq_attach_append13"); test(pos == Nil, "bq_attach_append14"); readstring_debug(&left, "a"); quote_heap(&right, QuoteExecute_Append, readr_debug("(b c)")); bq_attach_append_(left, right, &pos); test(quote_append_p(pos), "bq_attach_append15"); getvalue_quote(pos, &pos); test(length_list_unsafe(pos) == 3, "bq_attach_append16"); GetCons(pos, &left, &pos); test(left == readr_debug("a"), "bq_attach_append17"); GetCons(pos, &left, &pos); test(left == readr_debug("b"), "bq_attach_append18"); GetCons(pos, &left, &pos); test(left == readr_debug("c"), "bq_attach_append19"); test(pos == Nil, "bq_attach_append20"); bq_attach_append_(readr_debug("a"), readr_debug("b"), &pos); test(quote_append_p(pos), "bq_attach_append21"); getvalue_quote(pos, &pos); test(length_list_unsafe(pos) == 2, "bq_attach_append22"); GetCons(pos, &left, &pos); test(left == readr_debug("a"), "bq_attach_append23"); GetCons(pos, &left, &pos); test(left == readr_debug("b"), "bq_attach_append24"); test(pos == Nil, "bq_attach_append25"); RETURN; } static int test_bq_notany_splicing_frob(void) { int check; addr pos, a; check = 0; pos = NULL; quote_heap(&pos, QuoteExecute_List, Nil); bq_notany_splicing_frob_(pos, &check); test(check, "bq_notany_splicing_frob1"); quote_heap(&a, QuoteType_AtSign, Nil); list_heap(&a, a, NULL); quote_heap(&pos, QuoteExecute_List, a); bq_notany_splicing_frob_(pos, &check); test(! check, "bq_notany_splicing_frob2"); list_heap(&a, T, NULL); quote_heap(&pos, QuoteExecute_List, a); bq_notany_splicing_frob_(pos, &check); test(check, "bq_notany_splicing_frob3"); quote_heap(&a, QuoteType_AtSign, Nil); list_heap(&a, T, a, NULL); quote_heap(&pos, QuoteExecute_List, a); bq_notany_splicing_frob_(pos, &check); test(! check, "bq_notany_splicing_frob4"); quote_heap(&a, QuoteType_AtSign, Nil); list_heap(&a, T, T, NULL); quote_heap(&pos, QuoteExecute_List, a); bq_notany_splicing_frob_(pos, &check); test(check, "bq_notany_splicing_frob5"); RETURN; } static int test_bq_every_null_or_quoted(void) { int check; addr pos; bq_every_null_or_quoted_(Nil, &check); test(check, "bq_every_null_or_quoted1"); readstring_debug(&pos, "(nil)"); bq_every_null_or_quoted_(pos, &check); test(check, "bq_every_null_or_quoted2"); readstring_debug(&pos, "(t)"); bq_every_null_or_quoted_(pos, &check); test(! check, "bq_every_null_or_quoted3"); quote_heap(&pos, QuoteExecute_Quote, T); list_heap(&pos, Nil, pos, NULL); bq_every_null_or_quoted_(pos, &check); test(check, "bq_every_null_or_quoted4"); readstring_debug(&pos, "(nil t)"); bq_every_null_or_quoted_(pos, &check); test(! check, "bq_every_null_or_quoted5"); RETURN; } static int test_bq_attach_conses_mapcar(void) { addr a, b, c, pos, check; quote_heap(&a, QuoteExecute_Quote, readr_debug("a")); quote_heap(&b, QuoteExecute_Quote, readr_debug("b")); quote_heap(&c, QuoteExecute_Quote, readr_debug("c")); list_heap(&pos, a, b, Nil, NULL); bq_attach_conses_mapcar_(pos, c, &pos); test(quote_quote_p(pos), "bq_attach_conses_mapcar1"); getvalue_quote(pos, &pos); GetCons(pos, &check, &pos); test(check == readr_debug("a"), "bq_attach_conses_mapcar2"); GetCons(pos, &check, &pos); test(check == readr_debug("b"), "bq_attach_conses_mapcar3"); GetCons(pos, &check, &pos); test(check == Nil, "bq_attach_conses_mapcar4"); test(pos == readr_debug("c"), "bq_attach_conses_mapcar5"); RETURN; } static int test_bq_attach_conses(void) { addr a, b, pos, check; quote_heap(&a, QuoteExecute_Quote, readr_debug("a")); quote_heap(&b, QuoteExecute_Quote, readr_debug("b")); list_heap(&pos, a, NULL); bq_attach_conses_(pos, b, &pos); test(quote_quote_p(pos), "bq_attach_conses1"); getvalue_quote(pos, &pos); GetCons(pos, &check, &pos); test(check == readr_debug("a"), "bq_attach_conses2"); test(pos == readr_debug("b"), "bq_attach_conses3"); list_heap(&pos, readr_debug("a"), NULL); bq_attach_conses_(pos, Nil, &pos); test(quote_list_p(pos), "bq_attach_conses4"); getvalue_quote(pos, &pos); GetCons(pos, &check, &pos); test(check == readr_debug("a"), "bq_attach_conses5"); test(pos == Nil, "bq_attach_conses6"); list_heap(&a, readr_debug("a"), readr_debug("b"), NULL); list_heap(&b, readr_debug("c"), readr_debug("d"), NULL); quote_heap(&b, QuoteExecute_Lista, b); bq_attach_conses_(a, b, &pos); test(quote_lista_p(pos), "bq_attach_conses7"); getvalue_quote(pos, &pos); readstring_debug(&check, "(a b c d)"); test(equal_debug(pos, check), "bq_attach_conses8"); list_heap(&a, readr_debug("a"), readr_debug("b"), NULL); list_heap(&b, readr_debug("c"), readr_debug("d"), NULL); quote_heap(&b, QuoteExecute_List, b); bq_attach_conses_(a, b, &pos); test(quote_list_p(pos), "bq_attach_conses9"); getvalue_quote(pos, &pos); readstring_debug(&check, "(a b c d)"); test(equal_debug(pos, check), "bq_attach_conses10"); list_heap(&a, readr_debug("a"), readr_debug("b"), NULL); readstring_debug(&b, "c"); bq_attach_conses_(a, b, &pos); test(quote_lista_p(pos), "bq_attach_conses11"); getvalue_quote(pos, &pos); readstring_debug(&check, "(a b c)"); test(equal_debug(pos, check), "bq_attach_conses12"); RETURN; } static int test_bq_attach_conses_lista(void) { addr a, b, pos, check; readstring_debug(&a, "(a b c)"); readstring_debug(&b, "d"); quote_heap(&a, QuoteExecute_List, a); bq_attach_conses_lista_(a, b, &pos); test(quote_lista_p(pos), "bq_attach_conses_lista1"); getvalue_quote(pos, &pos); GetCons(pos, &check, &pos); test(check == readr_debug("a"), "bq_attach_conses_lista2"); GetCons(pos, &check, &pos); test(check == readr_debug("b"), "bq_attach_conses_lista3"); GetCons(pos, &check, &pos); test(quote_append_p(check), "bq_attach_conses_lista4"); test(pos == Nil, "bq_attach_conses_lista5"); getvalue_quote(check, &pos); GetCons(pos, &check, &pos); test(check == readr_debug("c"), "bq_attach_conses_lista6"); GetCons(pos, &check, &pos); test(check == readr_debug("d"), "bq_attach_conses_lista7"); test(pos == Nil, "bq_attach_conses_lista8"); RETURN; } static int test_bq_frob(void) { addr pos; quote_heap(&pos, QuoteType_Comma, T); test(bq_frob(pos), "bq_frob1"); quote_heap(&pos, QuoteType_AtSign, Nil); test(bq_frob(pos), "bq_frob2"); quote_heap(&pos, QuoteType_Dot, T); test(bq_frob(pos), "bq_frob3"); quote_heap(&pos, QuoteExecute_Quote, T); test(! bq_frob(pos), "bq_frob4"); test(! bq_frob(T), "bq_frob5"); RETURN; } static int test_bq_simplify_quote_p(void) { addr pos; list_heap(&pos, readr_debug("x"), NULL); quote_heap(&pos, QuoteExecute_Quote, pos); test(bq_simplify_quote_p(pos, &pos), "bq_simplify_quote_p1"); test(pos == readr_debug("x"), "bq_simplify_quote_p2"); list_heap(&pos, readr_debug("x"), NULL); quote_heap(&pos, QuoteExecute_Append, pos); test(! bq_simplify_quote_p(pos, &pos), "bq_simplify_quote_p3"); list_heap(&pos, readr_debug("x"), readr_debug("y"), NULL); quote_heap(&pos, QuoteExecute_Quote, pos); test(! bq_simplify_quote_p(pos, &pos), "bq_simplify_quote_p4"); RETURN; } static int test_bq_simplify_args(void) { addr a, b, pos, check; bq_simplify_args_(Nil, &pos); test(pos == Nil, "bq_simplify_args1"); readstring_debug(&pos, "(a)"); bq_simplify_args_(pos, &pos); test(pos == readr_debug("a"), "bq_simplify_args2"); readstring_debug(&pos, "(a b)"); bq_simplify_args_(pos, &pos); test(quote_append_p(pos), "bq_simplify_args3"); getvalue_quote(pos, &pos); GetCons(pos, &check, &pos); test(check == readr_debug("a"), "bq_simplify_args4"); GetCons(pos, &check, &pos); test(check == readr_debug("b"), "bq_simplify_args5"); test(pos == Nil, "bq_simplify_args6"); readstring_debug(&a, "(a b)"); quote_heap(&a, QuoteExecute_List, a); readstring_debug(&b, "c"); list_heap(&pos, a, b, NULL); bq_simplify_args_(pos, &pos); test(quote_lista_p(pos), "bq_simplify_args7"); getvalue_quote(pos, &pos); test(equal_debug(pos, readr_debug("(a b c)")), "bq_simplify_args8"); readstring_debug(&a, "(a b)"); quote_heap(&a, QuoteExecute_Lista, a); readstring_debug(&b, "c"); list_heap(&pos, a, b, NULL); bq_simplify_args_(pos, &pos); test(quote_lista_p(pos), "bq_simplify_args9"); getvalue_quote(pos, &pos); GetCons(pos, &check, &pos); test(check == readr_debug("a"), "bq_simplify_args10"); GetCons(pos, &check, &pos); test(quote_append_p(check), "bq_simplify_args11"); test(pos == Nil, "bq_simplify_args12"); getvalue_quote(check, &pos); GetCons(pos, &check, &pos); test(check == readr_debug("b"), "bq_simplify_args13"); GetCons(pos, &check, &pos); test(check == readr_debug("c"), "bq_simplify_args14"); test(pos == Nil, "bq_simplify_args15"); readstring_debug(&a, "(a)"); quote_heap(&a, QuoteExecute_Quote, a); readstring_debug(&b, "b"); list_heap(&pos, a, b, NULL); bq_simplify_args_(pos, &pos); test(quote_lista_p(pos), "bq_simplify_args16"); getvalue_quote(pos, &pos); GetCons(pos, &check, &pos); test(quote_quote_p(check), "bq_simplify_args17"); getvalue_quote(check, &check); test(check == readr_debug("a"), "bq_simplify_args18"); GetCons(pos, &check, &pos); test(check == readr_debug("b"), "bq_simplify_args19"); test(pos == Nil, "bq_simplify_args20"); quote_heap(&a, QuoteExecute_Clobberable, readr_debug("a")); readstring_debug(&b, "b"); list_heap(&pos, a, b, NULL); bq_simplify_args_(pos, &pos); test(quote_nconc_p(pos), "bq_simplify_args21"); getvalue_quote(pos, &pos); GetCons(pos, &check, &pos); test(check == readr_debug("a"), "bq_simplify_args22"); GetCons(pos, &check, &pos); test(check == readr_debug("b"), "bq_simplify_args23"); test(pos == Nil, "bq_simplify_args24"); quote_heap(&a, QuoteType_Comma, readr_debug("a")); readstring_debug(&b, "b"); list_heap(&pos, a, b, NULL); bq_simplify_args_(pos, &pos); test(quote_append_p(pos), "bq_simplify_args25"); getvalue_quote(pos, &pos); GetCons(pos, &check, &pos); test(quote_comma_p(check), "bq_simplify_args26"); GetCons(pos, &check, &pos); test(check == readr_debug("b"), "bq_simplify_args27"); test(pos == Nil, "bq_simplify_args28"); RETURN; } static int test_bq_simplify(void) { addr pos; bq_simplify_(readr_debug("10"), &pos); test(RefFixnum(pos) == 10, "bq_simplify1"); readstring_debug(&pos, "(a b c)"); quote_heap(&pos, QuoteExecute_Quote, pos); bq_simplify_(pos, &pos); test(quote_quote_p(pos), "bq_simplify2"); getvalue_quote(pos, &pos); test(equal_debug(pos, readr_debug("(a b c)")), "bq_simplify3"); RETURN; } /* * bq_remove_tokens */ static int test_bq_remove_tokens_list(void) { addr pos; readstring_debug(&pos, "(a b c)"); quote_heap(&pos, QuoteExecute_List, pos); bq_remove_tokens_list_(CONSTANT_COMMON_LIST, pos, &pos); test(equal_debug(pos, readr_debug("(list a b c)")), "bq_remove_tokens_list1"); RETURN; } static int test_quote_lista_cons_p(void) { addr pos; readstring_debug(&pos, "(a b)"); quote_heap(&pos, QuoteExecute_Lista, pos); test(quote_lista_cons_p(pos), "quote_lista_cons_p1"); readstring_debug(&pos, "(a b)"); quote_heap(&pos, QuoteExecute_List, pos); test(! quote_lista_cons_p(pos), "quote_lista_cons_p2"); readstring_debug(&pos, "(a)"); quote_heap(&pos, QuoteExecute_Lista, pos); test(! quote_lista_cons_p(pos), "quote_lista_cons_p3"); readstring_debug(&pos, "(a b c)"); quote_heap(&pos, QuoteExecute_Lista, pos); test(! quote_lista_cons_p(pos), "quote_lista_cons_p4"); RETURN; } static int test_bq_remove_tokens_cons(void) { addr pos; readstring_debug(&pos, "(a b)"); quote_heap(&pos, QuoteExecute_Lista, pos); bq_remove_tokens_cons_(pos, &pos); test(equal_debug(pos, readr_debug("(cons a b)")), "bq_remove_tokens_cons1"); RETURN; } static int test_bq_remove_tokens(void) { addr pos; readstring_debug(&pos, "(a b c)"); quote_heap(&pos, QuoteExecute_List, pos); bq_remove_tokens_(pos, &pos); test(equal_debug(pos, readr_debug("(list a b c)")), "bq_remove_tokens1"); readstring_debug(&pos, "(a b c)"); quote_heap(&pos, QuoteExecute_Append, pos); bq_remove_tokens_(pos, &pos); test(equal_debug(pos, readr_debug("(append a b c)")), "bq_remove_tokens2"); readstring_debug(&pos, "(a b c)"); quote_heap(&pos, QuoteExecute_Nconc, pos); bq_remove_tokens_(pos, &pos); test(equal_debug(pos, readr_debug("(nconc a b c)")), "bq_remove_tokens3"); readstring_debug(&pos, "(a b)"); quote_heap(&pos, QuoteExecute_Lista, pos); bq_remove_tokens_(pos, &pos); test(equal_debug(pos, readr_debug("(cons a b)")), "bq_remove_tokens4"); readstring_debug(&pos, "(a b c)"); quote_heap(&pos, QuoteExecute_Lista, pos); bq_remove_tokens_(pos, &pos); test(equal_debug(pos, readr_debug("(list* a b c)")), "bq_remove_tokens5"); readstring_debug(&pos, "(a b c)"); quote_heap(&pos, QuoteExecute_Quote, pos); bq_remove_tokens_(pos, &pos); test(equal_debug(pos, readr_debug("(quote (a b c))")), "bq_remove_tokens6"); readstring_debug(&pos, "(a b c)"); quote_heap(&pos, QuoteExecute_Clobberable, pos); bq_remove_tokens_(pos, &pos); test(equal_debug(pos, readr_debug("(a b c)")), "bq_remove_tokens7"); readstring_debug(&pos, "a"); bq_remove_tokens_(pos, &pos); test(equal_debug(pos, readr_debug("a")), "bq_remove_tokens8"); readstring_debug(&pos, "(a . b)"); bq_remove_tokens_(pos, &pos); test(equal_debug(pos, readr_debug("(a . b)")), "bq_remove_tokens9"); RETURN; } /* * interface */ static int test_quote_back_heap(void) { addr pos; readstring_debug(&pos, "`(a ,b)"); getvalue_quote(pos, &pos); test(equal_debug(pos, readr_debug("(list 'a b)")), "quote_back_heap1"); readstring_debug(&pos, "`(10 20 ,(+ 10 20))"); getvalue_quote(pos, &pos); test(equal_debug(pos, readr_debug("(list '10 '20 (+ 10 20))")), "quote_back_heap2"); readstring_debug(&pos, "`(10 20 ,@(list 30 40))"); getvalue_quote(pos, &pos); test(equal_debug(pos, readr_debug("(list* '10 '20 (list 30 40))")), "quote_back_heap3"); readstring_debug(&pos, "``(,,q)"); getvalue_quote(pos, &pos); test(equal_debug(pos, readr_debug("(list 'list q)")), "quote_back_heap4"); readstring_debug(&pos, "``(,@,q)"); getvalue_quote(pos, &pos); test(equal_debug(pos, readr_debug("q")), "quote_back_heap5"); readstring_debug(&pos, "``(,,@q)"); getvalue_quote(pos, &pos); test(equal_debug(pos, readr_debug("(cons 'list q)")), "quote_back_heap6"); readstring_debug(&pos, "``(,@,@q)"); getvalue_quote(pos, &pos); test(equal_debug(pos, readr_debug("(cons 'append q)")), "quote_back_heap7"); RETURN; } /* * main */ static int testcase_quote(void) { TestBreak(test_quote_heap); /* bq_process */ TestBreak(test_bq_atom); TestBreak(test_bq_bracket); TestBreak(test_bq_process_list); TestBreak(test_bq_process); /* bq_simplify */ TestBreak(test_bq_maptree); TestBreak(test_bq_null_or_quoted); TestBreak(test_getvalue_null_or_quoted); TestBreak(test_quote_nil_p); TestBreak(test_bq_splicing_frob); TestBreak(test_bq_attach_append); TestBreak(test_bq_notany_splicing_frob); TestBreak(test_bq_every_null_or_quoted); TestBreak(test_bq_attach_conses_mapcar); TestBreak(test_bq_attach_conses); TestBreak(test_bq_attach_conses_lista); TestBreak(test_bq_frob); TestBreak(test_bq_simplify_quote_p); TestBreak(test_bq_simplify_args); TestBreak(test_bq_simplify); /* bq_remove_tokens */ TestBreak(test_bq_remove_tokens_list); TestBreak(test_quote_lista_cons_p); TestBreak(test_bq_remove_tokens_cons); TestBreak(test_bq_remove_tokens); /* interface */ TestBreak(test_quote_back_heap); return 0; } static void testinit_quote(Execute ptr) { build_lisproot(ptr); build_constant(); build_object(); build_character(); build_package(); build_stream(); build_symbol(); build_clos(ptr); build_condition(ptr); build_type(); build_syscall(); build_common(); build_reader(); } int test_quote(void) { DegradeTitle; return DegradeCode(quote); }
4b5f14f9d3676b66ad6b0d160fe5b7ec8956b49c
010279e2ba272d09e9d2c4e903722e5faba2cf7a
/contrib/libs/qhull/libqhull_r/global_r.c
04b9b4d74ec24659e5331a3c03ee80b2f7f8d02e
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
catboost/catboost
854c1a1f439a96f1ae6b48e16644be20aa04dba2
f5042e35b945aded77b23470ead62d7eacefde92
refs/heads/master
2023-09-01T12:14:14.174108
2023-09-01T10:01:01
2023-09-01T10:22:12
97,556,265
8,012
1,425
Apache-2.0
2023-09-11T03:32:32
2017-07-18T05:29:04
Python
UTF-8
C
false
false
83,678
c
global_r.c
/*<html><pre> -<a href="qh-globa_r.htm" >-------------------------------</a><a name="TOP">-</a> global_r.c initializes all the globals of the qhull application see README see libqhull_r.h for qh.globals and function prototypes see qhull_ra.h for internal functions Copyright (c) 1993-2020 The Geometry Center. $Id: //main/2019/qhull/src/libqhull_r/global_r.c#19 $$Change: 3037 $ $DateTime: 2020/09/03 17:28:32 $$Author: bbarber $ */ #include "qhull_ra.h" /*========= qh->definition -- globals defined in libqhull_r.h =======================*/ /*-<a href ="qh-globa_r.htm#TOC" >--------------------------------</a><a name="version">-</a> qh_version version string by year and date qh_version2 for Unix users and -V the revision increases on code changes only notes: change date: Changes.txt, Announce.txt, index.htm, README.txt, qhull-news.html, Eudora signatures, CMakeLists.txt change version: README.txt, qh-get.htm, File_id.diz, Makefile.txt, CMakeLists.txt check that CMakeLists.txt @version is the same as qh_version2 change year: Copying.txt check download size recompile user_eg_r.c, rbox_r.c, libqhull_r.c, qconvex_r.c, qdelaun_r.c qvoronoi_r.c, qhalf_r.c, testqset_r.c */ const char qh_version[]= "2020.2.r 2020/08/31"; const char qh_version2[]= "qhull_r 8.0.2 (2020.2.r 2020/08/31)"; /*-<a href="qh-globa_r.htm#TOC" >-------------------------------</a><a name="appendprint">-</a> qh_appendprint(qh, printFormat ) append printFormat to qh.PRINTout unless already defined */ void qh_appendprint(qhT *qh, qh_PRINT format) { int i; for (i=0; i < qh_PRINTEND; i++) { if (qh->PRINTout[i] == format && format != qh_PRINTqhull) break; if (!qh->PRINTout[i]) { qh->PRINTout[i]= format; break; } } } /* appendprint */ /*-<a href="qh-globa_r.htm#TOC" >-------------------------------</a><a name="checkflags">-</a> qh_checkflags(qh, commandStr, hiddenFlags ) errors if commandStr contains hiddenFlags hiddenFlags starts and ends with a space and is space delimited (checked) notes: ignores first word (e.g., "qconvex i") use qh_strtol/strtod since strtol/strtod may or may not skip trailing spaces see: qh_initflags() initializes Qhull according to commandStr */ void qh_checkflags(qhT *qh, char *command, char *hiddenflags) { char *s= command, *t, *chkerr; /* qh_skipfilename is non-const */ char key, opt, prevopt; char chkkey[]= " "; /* check one character options ('s') */ char chkopt[]= " "; /* check two character options ('Ta') */ char chkopt2[]= " "; /* check three character options ('Q12') */ boolT waserr= False; if (*hiddenflags != ' ' || hiddenflags[strlen(hiddenflags)-1] != ' ') { qh_fprintf(qh, qh->ferr, 6026, "qhull internal error (qh_checkflags): hiddenflags must start and end with a space: \"%s\"\n", hiddenflags); qh_errexit(qh, qh_ERRqhull, NULL, NULL); } if (strpbrk(hiddenflags, ",\n\r\t")) { qh_fprintf(qh, qh->ferr, 6027, "qhull internal error (qh_checkflags): hiddenflags contains commas, newlines, or tabs: \"%s\"\n", hiddenflags); qh_errexit(qh, qh_ERRqhull, NULL, NULL); } while (*s && !isspace(*s)) /* skip program name */ s++; while (*s) { while (*s && isspace(*s)) s++; if (*s == '-') s++; if (!*s) break; key= *s++; chkerr= NULL; if (key == 'T' && (*s == 'I' || *s == 'O')) { /* TI or TO 'file name' */ s= qh_skipfilename(qh, ++s); continue; } chkkey[1]= key; if (strstr(hiddenflags, chkkey)) { chkerr= chkkey; }else if (isupper(key)) { opt= ' '; prevopt= ' '; chkopt[1]= key; chkopt2[1]= key; while (!chkerr && *s && !isspace(*s)) { opt= *s++; if (isalpha(opt)) { chkopt[2]= opt; if (strstr(hiddenflags, chkopt)) chkerr= chkopt; if (prevopt != ' ') { chkopt2[2]= prevopt; chkopt2[3]= opt; if (strstr(hiddenflags, chkopt2)) chkerr= chkopt2; } }else if (key == 'Q' && isdigit(opt) && prevopt != 'b' && (prevopt == ' ' || islower(prevopt))) { if (isdigit(*s)) { /* Q12 */ chkopt2[2]= opt; chkopt2[3]= *s++; if (strstr(hiddenflags, chkopt2)) chkerr= chkopt2; }else { chkopt[2]= opt; if (strstr(hiddenflags, chkopt)) chkerr= chkopt; } }else { qh_strtod(s-1, &t); if (s < t) s= t; } prevopt= opt; } } if (chkerr) { *chkerr= '\''; chkerr[strlen(chkerr)-1]= '\''; qh_fprintf(qh, qh->ferr, 6029, "qhull option error: option %s is not used with this program.\n It may be used with qhull.\n", chkerr); waserr= True; } } if (waserr) qh_errexit(qh, qh_ERRinput, NULL, NULL); } /* checkflags */ /*-<a href="qh-globa_r.htm#TOC" >-------------------------------</a><a name="clear_outputflags">-</a> qh_clear_outputflags(qh) Clear output flags for QhullPoints */ void qh_clear_outputflags(qhT *qh) { int i,k; qh->ANNOTATEoutput= False; qh->DOintersections= False; qh->DROPdim= -1; qh->FORCEoutput= False; qh->GETarea= False; qh->GOODpoint= 0; qh->GOODpointp= NULL; qh->GOODthreshold= False; qh->GOODvertex= 0; qh->GOODvertexp= NULL; qh->IStracing= 0; qh->KEEParea= False; qh->KEEPmerge= False; qh->KEEPminArea= REALmax; qh->PRINTcentrums= False; qh->PRINTcoplanar= False; qh->PRINTdots= False; qh->PRINTgood= False; qh->PRINTinner= False; qh->PRINTneighbors= False; qh->PRINTnoplanes= False; qh->PRINToptions1st= False; qh->PRINTouter= False; qh->PRINTprecision= True; qh->PRINTridges= False; qh->PRINTspheres= False; qh->PRINTstatistics= False; qh->PRINTsummary= False; qh->PRINTtransparent= False; qh->SPLITthresholds= False; qh->TRACElevel= 0; qh->TRInormals= False; qh->USEstdout= False; qh->VERIFYoutput= False; for (k=qh->input_dim+1; k--; ) { /* duplicated in qh_initqhull_buffers and qh_clear_outputflags */ qh->lower_threshold[k]= -REALmax; qh->upper_threshold[k]= REALmax; qh->lower_bound[k]= -REALmax; qh->upper_bound[k]= REALmax; } for (i=0; i < qh_PRINTEND; i++) { qh->PRINTout[i]= qh_PRINTnone; } if (!qh->qhull_commandsiz2) qh->qhull_commandsiz2= (int)strlen(qh->qhull_command); /* WARN64 */ else { qh->qhull_command[qh->qhull_commandsiz2]= '\0'; } if (!qh->qhull_optionsiz2) qh->qhull_optionsiz2= (int)strlen(qh->qhull_options); /* WARN64 */ else { qh->qhull_options[qh->qhull_optionsiz2]= '\0'; qh->qhull_optionlen= qh_OPTIONline; /* start a new line */ } } /* clear_outputflags */ /*-<a href="qh-globa_r.htm#TOC" >-------------------------------</a><a name="clock">-</a> qh_clock() return user CPU time in 100ths (qh_SECtick) only defined for qh_CLOCKtype == 2 notes: use first value to determine time 0 from Stevens '92 8.15 */ unsigned long qh_clock(qhT *qh) { #if (qh_CLOCKtype == 2) struct tms time; static long clktck; /* initialized first call and never updated */ double ratio, cpu; unsigned long ticks; if (!clktck) { if ((clktck= sysconf(_SC_CLK_TCK)) < 0) { qh_fprintf(qh, qh->ferr, 6030, "qhull internal error (qh_clock): sysconf() failed. Use qh_CLOCKtype 1 in user_r.h\n"); qh_errexit(qh, qh_ERRqhull, NULL, NULL); } } if (times(&time) == -1) { qh_fprintf(qh, qh->ferr, 6031, "qhull internal error (qh_clock): times() failed. Use qh_CLOCKtype 1 in user_r.h\n"); qh_errexit(qh, qh_ERRqhull, NULL, NULL); } ratio= qh_SECticks / (double)clktck; ticks= time.tms_utime * ratio; return ticks; #else qh_fprintf(qh, qh->ferr, 6032, "qhull internal error (qh_clock): use qh_CLOCKtype 2 in user_r.h\n"); qh_errexit(qh, qh_ERRqhull, NULL, NULL); /* never returns */ return 0; #endif } /* clock */ /*-<a href="qh-globa_r.htm#TOC" >-------------------------------</a><a name="freebuffers">-</a> qh_freebuffers() free up global memory buffers notes: must match qh_initbuffers() */ void qh_freebuffers(qhT *qh) { trace5((qh, qh->ferr, 5001, "qh_freebuffers: freeing up global memory buffers\n")); /* allocated by qh_initqhull_buffers */ qh_setfree(qh, &qh->other_points); qh_setfree(qh, &qh->del_vertices); qh_setfree(qh, &qh->coplanarfacetset); qh_memfree(qh, qh->NEARzero, qh->hull_dim * (int)sizeof(realT)); qh_memfree(qh, qh->lower_threshold, (qh->input_dim+1) * (int)sizeof(realT)); qh_memfree(qh, qh->upper_threshold, (qh->input_dim+1) * (int)sizeof(realT)); qh_memfree(qh, qh->lower_bound, (qh->input_dim+1) * (int)sizeof(realT)); qh_memfree(qh, qh->upper_bound, (qh->input_dim+1) * (int)sizeof(realT)); qh_memfree(qh, qh->gm_matrix, (qh->hull_dim+1) * qh->hull_dim * (int)sizeof(coordT)); qh_memfree(qh, qh->gm_row, (qh->hull_dim+1) * (int)sizeof(coordT *)); qh->NEARzero= qh->lower_threshold= qh->upper_threshold= NULL; qh->lower_bound= qh->upper_bound= NULL; qh->gm_matrix= NULL; qh->gm_row= NULL; if (qh->line) /* allocated by qh_readinput, freed if no error */ qh_free(qh->line); if (qh->half_space) qh_free(qh->half_space); if (qh->temp_malloc) qh_free(qh->temp_malloc); if (qh->feasible_point) /* allocated by qh_readfeasible */ qh_free(qh->feasible_point); if (qh->feasible_string) /* allocated by qh_initflags */ qh_free(qh->feasible_string); qh->line= qh->feasible_string= NULL; qh->half_space= qh->feasible_point= qh->temp_malloc= NULL; /* usually allocated by qh_readinput */ if (qh->first_point && qh->POINTSmalloc) { qh_free(qh->first_point); qh->first_point= NULL; } if (qh->input_points && qh->input_malloc) { /* set by qh_joggleinput */ qh_free(qh->input_points); qh->input_points= NULL; } trace5((qh, qh->ferr, 5002, "qh_freebuffers: finished\n")); } /* freebuffers */ /*-<a href="qh-globa_r.htm#TOC" >-------------------------------</a><a name="freebuild">-</a> qh_freebuild(qh, allmem ) free global memory used by qh_initbuild and qh_buildhull if !allmem, does not free short memory (e.g., facetT, freed by qh_memfreeshort) design: free centrums free each vertex for each facet free ridges free outside set, coplanar set, neighbor set, ridge set, vertex set free facet free hash table free interior point free merge sets free temporary sets */ void qh_freebuild(qhT *qh, boolT allmem) { facetT *facet, *previousfacet= NULL; vertexT *vertex, *previousvertex= NULL; ridgeT *ridge, **ridgep, *previousridge= NULL; mergeT *merge, **mergep; int newsize; boolT freeall; /* free qhT global sets first, includes references from qh_buildhull */ trace5((qh, qh->ferr, 5004, "qh_freebuild: free global sets\n")); FOREACHmerge_(qh->facet_mergeset) /* usually empty */ qh_memfree(qh, merge, (int)sizeof(mergeT)); FOREACHmerge_(qh->degen_mergeset) /* usually empty */ qh_memfree(qh, merge, (int)sizeof(mergeT)); FOREACHmerge_(qh->vertex_mergeset) /* usually empty */ qh_memfree(qh, merge, (int)sizeof(mergeT)); qh->facet_mergeset= NULL; /* temp set freed by qh_settempfree_all */ qh->degen_mergeset= NULL; /* temp set freed by qh_settempfree_all */ qh->vertex_mergeset= NULL; /* temp set freed by qh_settempfree_all */ qh_setfree(qh, &(qh->hash_table)); trace5((qh, qh->ferr, 5003, "qh_freebuild: free temporary sets (qh_settempfree_all)\n")); qh_settempfree_all(qh); trace1((qh, qh->ferr, 1005, "qh_freebuild: free memory from qh_inithull and qh_buildhull\n")); if (qh->del_vertices) qh_settruncate(qh, qh->del_vertices, 0); if (allmem) { while ((vertex= qh->vertex_list)) { if (vertex->next) qh_delvertex(qh, vertex); else { qh_memfree(qh, vertex, (int)sizeof(vertexT)); /* sentinel */ qh->newvertex_list= qh->vertex_list= NULL; break; } previousvertex= vertex; /* in case of memory fault */ QHULL_UNUSED(previousvertex) } }else if (qh->VERTEXneighbors) { FORALLvertices qh_setfreelong(qh, &(vertex->neighbors)); } qh->VERTEXneighbors= False; qh->GOODclosest= NULL; if (allmem) { FORALLfacets { FOREACHridge_(facet->ridges) ridge->seen= False; } while ((facet= qh->facet_list)) { if (!facet->newfacet || !qh->NEWtentative || qh_setsize(qh, facet->ridges) > 1) { /* skip tentative horizon ridges */ trace4((qh, qh->ferr, 4095, "qh_freebuild: delete the previously-seen ridges of f%d\n", facet->id)); FOREACHridge_(facet->ridges) { if (ridge->seen) qh_delridge(qh, ridge); else ridge->seen= True; previousridge= ridge; /* in case of memory fault */ QHULL_UNUSED(previousridge) } } qh_setfree(qh, &(facet->outsideset)); qh_setfree(qh, &(facet->coplanarset)); qh_setfree(qh, &(facet->neighbors)); qh_setfree(qh, &(facet->ridges)); qh_setfree(qh, &(facet->vertices)); if (facet->next) qh_delfacet(qh, facet); else { qh_memfree(qh, facet, (int)sizeof(facetT)); qh->visible_list= qh->newfacet_list= qh->facet_list= NULL; } previousfacet= facet; /* in case of memory fault */ QHULL_UNUSED(previousfacet) } }else { freeall= True; if (qh_setlarger_quick(qh, qh->hull_dim + 1, &newsize)) freeall= False; FORALLfacets { qh_setfreelong(qh, &(facet->outsideset)); qh_setfreelong(qh, &(facet->coplanarset)); if (!facet->simplicial || freeall) { qh_setfreelong(qh, &(facet->neighbors)); qh_setfreelong(qh, &(facet->ridges)); qh_setfreelong(qh, &(facet->vertices)); } } } /* qh internal constants */ qh_memfree(qh, qh->interior_point, qh->normal_size); qh->interior_point= NULL; } /* freebuild */ /*-<a href="qh-globa_r.htm#TOC" >-------------------------------</a><a name="freeqhull">-</a> qh_freeqhull(qh, allmem ) free global memory and set qhT to 0 if !allmem, does not free short memory (freed by qh_memfreeshort unless qh_NOmem) notes: sets qh.NOerrexit in case caller forgets to Does not throw errors see: see qh_initqhull_start2() For libqhull_r, qhstatT is part of qhT design: free global and temporary memory from qh_initbuild and qh_buildhull free buffers */ void qh_freeqhull(qhT *qh, boolT allmem) { qh->NOerrexit= True; /* no more setjmp since called at exit and ~QhullQh */ trace1((qh, qh->ferr, 1006, "qh_freeqhull: free global memory\n")); qh_freebuild(qh, allmem); qh_freebuffers(qh); trace1((qh, qh->ferr, 1061, "qh_freeqhull: clear qhT except for qh.qhmem and qh.qhstat\n")); /* memset is the same in qh_freeqhull() and qh_initqhull_start2() */ memset((char *)qh, 0, sizeof(qhT)-sizeof(qhmemT)-sizeof(qhstatT)); qh->NOerrexit= True; } /* freeqhull */ /*-<a href="qh-globa_r.htm#TOC" >-------------------------------</a><a name="init_A">-</a> qh_init_A(qh, infile, outfile, errfile, argc, argv ) initialize memory and stdio files convert input options to option string (qh.qhull_command) notes: infile may be NULL if qh_readpoints() is not called errfile should always be defined. It is used for reporting errors. outfile is used for output and format options. argc/argv may be 0/NULL called before error handling initialized qh_errexit() may not be used */ void qh_init_A(qhT *qh, FILE *infile, FILE *outfile, FILE *errfile, int argc, char *argv[]) { qh_meminit(qh, errfile); qh_initqhull_start(qh, infile, outfile, errfile); qh_init_qhull_command(qh, argc, argv); } /* init_A */ /*-<a href="qh-globa_r.htm#TOC" >-------------------------------</a><a name="init_B">-</a> qh_init_B(qh, points, numpoints, dim, ismalloc ) initialize globals for points array points has numpoints dim-dimensional points points[0] is the first coordinate of the first point points[1] is the second coordinate of the first point points[dim] is the first coordinate of the second point ismalloc=True Qhull will call qh_free(points) on exit or input transformation ismalloc=False Qhull will allocate a new point array if needed for input transformation qh.qhull_command is the option string. It is defined by qh_init_B(), qh_qhull_command(), or qh_initflags returns: if qh.PROJECTinput or (qh.DELAUNAY and qh.PROJECTdelaunay) projects the input to a new point array if qh.DELAUNAY, qh.hull_dim is increased by one if qh.ATinfinity, qh_projectinput adds point-at-infinity for Delaunay tri. if qh.SCALEinput changes the upper and lower bounds of the input, see qh_scaleinput if qh.ROTATEinput rotates the input by a random rotation, see qh_rotateinput if qh.DELAUNAY rotates about the last coordinate notes: called after points are defined qh_errexit() may be used */ void qh_init_B(qhT *qh, coordT *points, int numpoints, int dim, boolT ismalloc) { qh_initqhull_globals(qh, points, numpoints, dim, ismalloc); if (qh->qhmem.LASTsize == 0) qh_initqhull_mem(qh); /* mem_r.c and qset_r.c are initialized */ qh_initqhull_buffers(qh); qh_initthresholds(qh, qh->qhull_command); if (qh->PROJECTinput || (qh->DELAUNAY && qh->PROJECTdelaunay)) qh_projectinput(qh); if (qh->SCALEinput) qh_scaleinput(qh); if (qh->ROTATErandom >= 0) { qh_randommatrix(qh, qh->gm_matrix, qh->hull_dim, qh->gm_row); if (qh->DELAUNAY) { int k, lastk= qh->hull_dim-1; for (k=0; k < lastk; k++) { qh->gm_row[k][lastk]= 0.0; qh->gm_row[lastk][k]= 0.0; } qh->gm_row[lastk][lastk]= 1.0; } qh_gram_schmidt(qh, qh->hull_dim, qh->gm_row); qh_rotateinput(qh, qh->gm_row); } } /* init_B */ /*-<a href="qh-globa_r.htm#TOC" >-------------------------------</a><a name="init_qhull_command">-</a> qh_init_qhull_command(qh, argc, argv ) build qh.qhull_command from argc/argv Calls qh_exit if qhull_command is too short returns: a space-delimited string of options (just as typed) notes: makes option string easy to input and output argc/argv may be 0/NULL */ void qh_init_qhull_command(qhT *qh, int argc, char *argv[]) { if (!qh_argv_to_command(argc, argv, qh->qhull_command, (int)sizeof(qh->qhull_command))){ /* Assumes qh.ferr is defined. */ qh_fprintf(qh, qh->ferr, 6033, "qhull input error: more than %d characters in command line.\n", (int)sizeof(qh->qhull_command)); qh_exit(qh_ERRinput); /* error reported, can not use qh_errexit */ } } /* init_qhull_command */ /*-<a href="qh-globa_r.htm#TOC" >-------------------------------</a><a name="initflags">-</a> qh_initflags(qh, commandStr ) set flags and initialized constants from commandStr calls qh_exit() if qh.NOerrexit returns: sets qh.qhull_command to command if needed notes: ignores first word (e.g., 'qhull' in "qhull d") use qh_strtol/strtod since strtol/strtod may or may not skip trailing spaces see: qh_initthresholds() continues processing of 'Pdn' and 'PDn' 'prompt' in unix_r.c for documentation design: for each space-delimited option group if top-level option check syntax append appropriate option to option string set appropriate global variable or append printFormat to print options else for each sub-option check syntax append appropriate option to option string set appropriate global variable or append printFormat to print options */ void qh_initflags(qhT *qh, char *command) { int k, i, lastproject; char *s= command, *t, *prev_s, *start, key, *lastwarning= NULL; boolT isgeom= False, wasproject; realT r; if(qh->NOerrexit){ qh_fprintf(qh, qh->ferr, 6245, "qhull internal error (qh_initflags): qh.NOerrexit was not cleared before calling qh_initflags(). It should be cleared after setjmp(). Exit qhull.\n"); qh_exit(qh_ERRqhull); } #ifdef qh_RANDOMdist qh->RANDOMfactor= qh_RANDOMdist; qh_option(qh, "Random-qh_RANDOMdist", NULL, &qh->RANDOMfactor); qh->RANDOMdist= True; #endif if (command <= &qh->qhull_command[0] || command > &qh->qhull_command[0] + sizeof(qh->qhull_command)) { if (command != &qh->qhull_command[0]) { *qh->qhull_command= '\0'; strncat(qh->qhull_command, command, sizeof(qh->qhull_command)-strlen(qh->qhull_command)-1); } while (*s && !isspace(*s)) /* skip program name */ s++; } while (*s) { while (*s && isspace(*s)) s++; if (*s == '-') s++; if (!*s) break; prev_s= s; switch (*s++) { case 'd': qh_option(qh, "delaunay", NULL, NULL); qh->DELAUNAY= True; break; case 'f': qh_option(qh, "facets", NULL, NULL); qh_appendprint(qh, qh_PRINTfacets); break; case 'i': qh_option(qh, "incidence", NULL, NULL); qh_appendprint(qh, qh_PRINTincidences); break; case 'm': qh_option(qh, "mathematica", NULL, NULL); qh_appendprint(qh, qh_PRINTmathematica); break; case 'n': qh_option(qh, "normals", NULL, NULL); qh_appendprint(qh, qh_PRINTnormals); break; case 'o': qh_option(qh, "offFile", NULL, NULL); qh_appendprint(qh, qh_PRINToff); break; case 'p': qh_option(qh, "points", NULL, NULL); qh_appendprint(qh, qh_PRINTpoints); break; case 's': qh_option(qh, "summary", NULL, NULL); qh->PRINTsummary= True; break; case 'v': qh_option(qh, "voronoi", NULL, NULL); qh->VORONOI= True; qh->DELAUNAY= True; break; case 'A': if (!isdigit(*s) && *s != '.' && *s != '-') { qh_fprintf(qh, qh->ferr, 7002, "qhull input warning: no maximum cosine angle given for option 'An'. A1.0 is coplanar\n"); lastwarning= s-1; }else { if (*s == '-') { qh->premerge_cos= -qh_strtod(s, &s); qh_option(qh, "Angle-premerge-", NULL, &qh->premerge_cos); qh->PREmerge= True; }else { qh->postmerge_cos= qh_strtod(s, &s); qh_option(qh, "Angle-postmerge", NULL, &qh->postmerge_cos); qh->POSTmerge= True; } qh->MERGING= True; } break; case 'C': if (!isdigit(*s) && *s != '.' && *s != '-') { qh_fprintf(qh, qh->ferr, 7003, "qhull input warning: no centrum radius given for option 'Cn'\n"); lastwarning= s-1; }else { if (*s == '-') { qh->premerge_centrum= -qh_strtod(s, &s); qh_option(qh, "Centrum-premerge-", NULL, &qh->premerge_centrum); qh->PREmerge= True; }else { qh->postmerge_centrum= qh_strtod(s, &s); qh_option(qh, "Centrum-postmerge", NULL, &qh->postmerge_centrum); qh->POSTmerge= True; } qh->MERGING= True; } break; case 'E': if (*s == '-') { qh_fprintf(qh, qh->ferr, 6363, "qhull option error: expecting a positive number for maximum roundoff 'En'. Got '%s'\n", s-1); qh_errexit(qh, qh_ERRinput, NULL, NULL); }else if (!isdigit(*s)) { qh_fprintf(qh, qh->ferr, 7005, "qhull option warning: no maximum roundoff given for option 'En'\n"); lastwarning= s-1; }else { qh->DISTround= qh_strtod(s, &s); qh_option(qh, "Distance-roundoff", NULL, &qh->DISTround); qh->SETroundoff= True; } break; case 'H': start= s; qh->HALFspace= True; qh_strtod(s, &t); while (t > s) { if (*t && !isspace(*t)) { if (*t == ',') t++; else { qh_fprintf(qh, qh->ferr, 6364, "qhull option error: expecting 'Hn,n,n,...' for feasible point of halfspace intersection. Got '%s'\n", start-1); qh_errexit(qh, qh_ERRinput, NULL, NULL); } } s= t; qh_strtod(s, &t); } if (start < t) { if (!(qh->feasible_string= (char *)calloc((size_t)(t-start+1), (size_t)1))) { qh_fprintf(qh, qh->ferr, 6034, "qhull error: insufficient memory for 'Hn,n,n'\n"); qh_errexit(qh, qh_ERRmem, NULL, NULL); } strncpy(qh->feasible_string, start, (size_t)(t-start)); qh_option(qh, "Halfspace-about", NULL, NULL); qh_option(qh, qh->feasible_string, NULL, NULL); }else qh_option(qh, "Halfspace", NULL, NULL); break; case 'R': if (!isdigit(*s)) { qh_fprintf(qh, qh->ferr, 7007, "qhull option warning: missing random perturbation for option 'Rn'\n"); lastwarning= s-1; }else { qh->RANDOMfactor= qh_strtod(s, &s); qh_option(qh, "Random-perturb", NULL, &qh->RANDOMfactor); qh->RANDOMdist= True; } break; case 'V': if (!isdigit(*s) && *s != '-') { qh_fprintf(qh, qh->ferr, 7008, "qhull option warning: missing visible distance for option 'Vn'\n"); lastwarning= s-1; }else { qh->MINvisible= qh_strtod(s, &s); qh_option(qh, "Visible", NULL, &qh->MINvisible); } break; case 'U': if (!isdigit(*s) && *s != '-') { qh_fprintf(qh, qh->ferr, 7009, "qhull option warning: missing coplanar distance for option 'Un'\n"); lastwarning= s-1; }else { qh->MAXcoplanar= qh_strtod(s, &s); qh_option(qh, "U-coplanar", NULL, &qh->MAXcoplanar); } break; case 'W': if (*s == '-') { qh_fprintf(qh, qh->ferr, 6365, "qhull option error: expecting a positive number for outside width 'Wn'. Got '%s'\n", s-1); qh_errexit(qh, qh_ERRinput, NULL, NULL); }else if (!isdigit(*s)) { qh_fprintf(qh, qh->ferr, 7011, "qhull option warning: missing outside width for option 'Wn'\n"); lastwarning= s-1; }else { qh->MINoutside= qh_strtod(s, &s); qh_option(qh, "W-outside", NULL, &qh->MINoutside); qh->APPROXhull= True; } break; /************ sub menus ***************/ case 'F': while (*s && !isspace(*s)) { switch (*s++) { case 'a': qh_option(qh, "Farea", NULL, NULL); qh_appendprint(qh, qh_PRINTarea); qh->GETarea= True; break; case 'A': qh_option(qh, "FArea-total", NULL, NULL); qh->GETarea= True; break; case 'c': qh_option(qh, "Fcoplanars", NULL, NULL); qh_appendprint(qh, qh_PRINTcoplanars); break; case 'C': qh_option(qh, "FCentrums", NULL, NULL); qh_appendprint(qh, qh_PRINTcentrums); break; case 'd': qh_option(qh, "Fd-cdd-in", NULL, NULL); qh->CDDinput= True; break; case 'D': qh_option(qh, "FD-cdd-out", NULL, NULL); qh->CDDoutput= True; break; case 'F': qh_option(qh, "FFacets-xridge", NULL, NULL); qh_appendprint(qh, qh_PRINTfacets_xridge); break; case 'i': qh_option(qh, "Finner", NULL, NULL); qh_appendprint(qh, qh_PRINTinner); break; case 'I': qh_option(qh, "FIDs", NULL, NULL); qh_appendprint(qh, qh_PRINTids); break; case 'm': qh_option(qh, "Fmerges", NULL, NULL); qh_appendprint(qh, qh_PRINTmerges); break; case 'M': qh_option(qh, "FMaple", NULL, NULL); qh_appendprint(qh, qh_PRINTmaple); break; case 'n': qh_option(qh, "Fneighbors", NULL, NULL); qh_appendprint(qh, qh_PRINTneighbors); break; case 'N': qh_option(qh, "FNeighbors-vertex", NULL, NULL); qh_appendprint(qh, qh_PRINTvneighbors); break; case 'o': qh_option(qh, "Fouter", NULL, NULL); qh_appendprint(qh, qh_PRINTouter); break; case 'O': if (qh->PRINToptions1st) { qh_option(qh, "FOptions", NULL, NULL); qh_appendprint(qh, qh_PRINToptions); }else qh->PRINToptions1st= True; break; case 'p': qh_option(qh, "Fpoint-intersect", NULL, NULL); qh_appendprint(qh, qh_PRINTpointintersect); break; case 'P': qh_option(qh, "FPoint-nearest", NULL, NULL); qh_appendprint(qh, qh_PRINTpointnearest); break; case 'Q': qh_option(qh, "FQhull", NULL, NULL); qh_appendprint(qh, qh_PRINTqhull); break; case 's': qh_option(qh, "Fsummary", NULL, NULL); qh_appendprint(qh, qh_PRINTsummary); break; case 'S': qh_option(qh, "FSize", NULL, NULL); qh_appendprint(qh, qh_PRINTsize); qh->GETarea= True; break; case 't': qh_option(qh, "Ftriangles", NULL, NULL); qh_appendprint(qh, qh_PRINTtriangles); break; case 'v': /* option set in qh_initqhull_globals */ qh_appendprint(qh, qh_PRINTvertices); break; case 'V': qh_option(qh, "FVertex-average", NULL, NULL); qh_appendprint(qh, qh_PRINTaverage); break; case 'x': qh_option(qh, "Fxtremes", NULL, NULL); qh_appendprint(qh, qh_PRINTextremes); break; default: s--; qh_fprintf(qh, qh->ferr, 7012, "qhull option warning: unknown 'F' output option 'F%c', skip to next space\n", (int)s[0]); lastwarning= s-1; while (*++s && !isspace(*s)); break; } } break; case 'G': isgeom= True; qh_appendprint(qh, qh_PRINTgeom); while (*s && !isspace(*s)) { switch (*s++) { case 'a': qh_option(qh, "Gall-points", NULL, NULL); qh->PRINTdots= True; break; case 'c': qh_option(qh, "Gcentrums", NULL, NULL); qh->PRINTcentrums= True; break; case 'h': qh_option(qh, "Gintersections", NULL, NULL); qh->DOintersections= True; break; case 'i': qh_option(qh, "Ginner", NULL, NULL); qh->PRINTinner= True; break; case 'n': qh_option(qh, "Gno-planes", NULL, NULL); qh->PRINTnoplanes= True; break; case 'o': qh_option(qh, "Gouter", NULL, NULL); qh->PRINTouter= True; break; case 'p': qh_option(qh, "Gpoints", NULL, NULL); qh->PRINTcoplanar= True; break; case 'r': qh_option(qh, "Gridges", NULL, NULL); qh->PRINTridges= True; break; case 't': qh_option(qh, "Gtransparent", NULL, NULL); qh->PRINTtransparent= True; break; case 'v': qh_option(qh, "Gvertices", NULL, NULL); qh->PRINTspheres= True; break; case 'D': if (!isdigit(*s)) { qh_fprintf(qh, qh->ferr, 7004, "qhull option warning: missing dimension for option 'GDn'\n"); lastwarning= s-2; }else { if (qh->DROPdim >= 0) { qh_fprintf(qh, qh->ferr, 7013, "qhull option warning: can only drop one dimension. Previous 'GD%d' ignored\n", qh->DROPdim); lastwarning= s-2; } qh->DROPdim= qh_strtol(s, &s); qh_option(qh, "GDrop-dim", &qh->DROPdim, NULL); } break; default: s--; qh_fprintf(qh, qh->ferr, 7014, "qhull option warning: unknown 'G' geomview option 'G%c', skip to next space\n", (int)s[0]); lastwarning= s-1; while (*++s && !isspace(*s)); break; } } break; case 'P': while (*s && !isspace(*s)) { switch (*s++) { case 'd': case 'D': /* see qh_initthresholds() */ key= s[-1]; i= qh_strtol(s, &s); r= 0; if (*s == ':') { s++; r= qh_strtod(s, &s); } if (key == 'd') qh_option(qh, "Pdrop-facets-dim-less", &i, &r); else qh_option(qh, "PDrop-facets-dim-more", &i, &r); break; case 'g': qh_option(qh, "Pgood-facets", NULL, NULL); qh->PRINTgood= True; break; case 'G': qh_option(qh, "PGood-facet-neighbors", NULL, NULL); qh->PRINTneighbors= True; break; case 'o': qh_option(qh, "Poutput-forced", NULL, NULL); qh->FORCEoutput= True; break; case 'p': qh_option(qh, "Pprecision-ignore", NULL, NULL); qh->PRINTprecision= False; break; case 'A': if (!isdigit(*s)) { qh_fprintf(qh, qh->ferr, 7006, "qhull option warning: missing facet count for keep area option 'PAn'\n"); lastwarning= s-2; }else { qh->KEEParea= qh_strtol(s, &s); qh_option(qh, "PArea-keep", &qh->KEEParea, NULL); qh->GETarea= True; } break; case 'F': if (!isdigit(*s)) { qh_fprintf(qh, qh->ferr, 7010, "qhull option warning: missing facet area for option 'PFn'\n"); lastwarning= s-2; }else { qh->KEEPminArea= qh_strtod(s, &s); qh_option(qh, "PFacet-area-keep", NULL, &qh->KEEPminArea); qh->GETarea= True; } break; case 'M': if (!isdigit(*s)) { qh_fprintf(qh, qh->ferr, 7090, "qhull option warning: missing merge count for option 'PMn'\n"); lastwarning= s-2; }else { qh->KEEPmerge= qh_strtol(s, &s); qh_option(qh, "PMerge-keep", &qh->KEEPmerge, NULL); } break; default: s--; qh_fprintf(qh, qh->ferr, 7015, "qhull option warning: unknown 'P' print option 'P%c', skip to next space\n", (int)s[0]); lastwarning= s-1; while (*++s && !isspace(*s)); break; } } break; case 'Q': lastproject= -1; while (*s && !isspace(*s)) { switch (*s++) { case 'a': qh_option(qh, "Qallow-short", NULL, NULL); qh->ALLOWshort= True; break; case 'b': case 'B': /* handled by qh_initthresholds */ key= s[-1]; if (key == 'b' && *s == 'B') { s++; r= qh_DEFAULTbox; qh->SCALEinput= True; qh_option(qh, "QbBound-unit-box", NULL, &r); break; } if (key == 'b' && *s == 'b') { s++; qh->SCALElast= True; qh_option(qh, "Qbbound-last", NULL, NULL); break; } k= qh_strtol(s, &s); r= 0.0; wasproject= False; if (*s == ':') { s++; if ((r= qh_strtod(s, &s)) == 0.0) { t= s; /* need true dimension for memory allocation */ while (*t && !isspace(*t)) { if (toupper(*t++) == 'B' && k == qh_strtol(t, &t) && *t++ == ':' && qh_strtod(t, &t) == 0.0) { qh->PROJECTinput++; trace2((qh, qh->ferr, 2004, "qh_initflags: project dimension %d\n", k)); qh_option(qh, "Qb-project-dim", &k, NULL); wasproject= True; lastproject= k; break; } } } } if (!wasproject) { if (lastproject == k && r == 0.0) lastproject= -1; /* doesn't catch all possible sequences */ else if (key == 'b') { qh->SCALEinput= True; if (r == 0.0) r= -qh_DEFAULTbox; qh_option(qh, "Qbound-dim-low", &k, &r); }else { qh->SCALEinput= True; if (r == 0.0) r= qh_DEFAULTbox; qh_option(qh, "QBound-dim-high", &k, &r); } } break; case 'c': qh_option(qh, "Qcoplanar-keep", NULL, NULL); qh->KEEPcoplanar= True; break; case 'f': qh_option(qh, "Qfurthest-outside", NULL, NULL); qh->BESToutside= True; break; case 'g': qh_option(qh, "Qgood-facets-only", NULL, NULL); qh->ONLYgood= True; break; case 'i': qh_option(qh, "Qinterior-keep", NULL, NULL); qh->KEEPinside= True; break; case 'm': qh_option(qh, "Qmax-outside-only", NULL, NULL); qh->ONLYmax= True; break; case 'r': qh_option(qh, "Qrandom-outside", NULL, NULL); qh->RANDOMoutside= True; break; case 's': qh_option(qh, "Qsearch-initial-simplex", NULL, NULL); qh->ALLpoints= True; break; case 't': qh_option(qh, "Qtriangulate", NULL, NULL); qh->TRIangulate= True; break; case 'T': qh_option(qh, "QTestPoints", NULL, NULL); if (!isdigit(*s)) { qh_fprintf(qh, qh->ferr, 7091, "qhull option warning: missing number of test points for option 'QTn'\n"); lastwarning= s-2; }else { qh->TESTpoints= qh_strtol(s, &s); qh_option(qh, "QTestPoints", &qh->TESTpoints, NULL); } break; case 'u': qh_option(qh, "QupperDelaunay", NULL, NULL); qh->UPPERdelaunay= True; break; case 'v': qh_option(qh, "Qvertex-neighbors-convex", NULL, NULL); qh->TESTvneighbors= True; break; case 'x': qh_option(qh, "Qxact-merge", NULL, NULL); qh->MERGEexact= True; break; case 'z': qh_option(qh, "Qz-infinity-point", NULL, NULL); qh->ATinfinity= True; break; case '0': qh_option(qh, "Q0-no-premerge", NULL, NULL); qh->NOpremerge= True; break; case '1': if (!isdigit(*s)) { qh_option(qh, "Q1-angle-merge", NULL, NULL); qh->ANGLEmerge= True; break; } switch (*s++) { case '0': qh_option(qh, "Q10-no-narrow", NULL, NULL); qh->NOnarrow= True; break; case '1': qh_option(qh, "Q11-trinormals Qtriangulate", NULL, NULL); qh->TRInormals= True; qh->TRIangulate= True; break; case '2': qh_option(qh, "Q12-allow-wide", NULL, NULL); qh->ALLOWwide= True; break; case '4': #ifndef qh_NOmerge qh_option(qh, "Q14-merge-pinched-vertices", NULL, NULL); qh->MERGEpinched= True; #else /* ignore 'Q14' for q_benchmark testing of difficult cases for Qhull */ qh_fprintf(qh, qh->ferr, 7099, "qhull option warning: option 'Q14-merge-pinched' disabled due to qh_NOmerge\n"); #endif break; case '7': qh_option(qh, "Q15-check-duplicates", NULL, NULL); qh->CHECKduplicates= True; break; default: s--; qh_fprintf(qh, qh->ferr, 7016, "qhull option warning: unknown 'Q' qhull option 'Q1%c', skip to next space\n", (int)s[0]); lastwarning= s-1; while (*++s && !isspace(*s)); break; } break; case '2': qh_option(qh, "Q2-no-merge-independent", NULL, NULL); qh->MERGEindependent= False; goto LABELcheckdigit; break; /* no gcc warnings */ case '3': qh_option(qh, "Q3-no-merge-vertices", NULL, NULL); qh->MERGEvertices= False; LABELcheckdigit: if (isdigit(*s)) { qh_fprintf(qh, qh->ferr, 7017, "qhull option warning: can not follow '1', '2', or '3' with a digit. 'Q%c%c' skipped\n", *(s-1), *s); lastwarning= s-2; s++; } break; case '4': qh_option(qh, "Q4-avoid-old-into-new", NULL, NULL); qh->AVOIDold= True; break; case '5': qh_option(qh, "Q5-no-check-outer", NULL, NULL); qh->SKIPcheckmax= True; break; case '6': qh_option(qh, "Q6-no-concave-merge", NULL, NULL); qh->SKIPconvex= True; break; case '7': qh_option(qh, "Q7-no-breadth-first", NULL, NULL); qh->VIRTUALmemory= True; break; case '8': qh_option(qh, "Q8-no-near-inside", NULL, NULL); qh->NOnearinside= True; break; case '9': qh_option(qh, "Q9-pick-furthest", NULL, NULL); qh->PICKfurthest= True; break; case 'G': i= qh_strtol(s, &t); if (qh->GOODpoint) { qh_fprintf(qh, qh->ferr, 7018, "qhull option warning: good point already defined for option 'QGn'. Ignored\n"); lastwarning= s-2; }else if (s == t) { qh_fprintf(qh, qh->ferr, 7019, "qhull option warning: missing good point id for option 'QGn'. Ignored\n"); lastwarning= s-2; }else if (i < 0 || *s == '-') { qh->GOODpoint= i-1; qh_option(qh, "QGood-if-dont-see-point", &i, NULL); }else { qh->GOODpoint= i+1; qh_option(qh, "QGood-if-see-point", &i, NULL); } s= t; break; case 'J': if (!isdigit(*s) && *s != '-') qh->JOGGLEmax= 0.0; else { qh->JOGGLEmax= (realT) qh_strtod(s, &s); qh_option(qh, "QJoggle", NULL, &qh->JOGGLEmax); } break; case 'R': if (!isdigit(*s) && *s != '-') { qh_fprintf(qh, qh->ferr, 7020, "qhull option warning: missing random seed for option 'QRn'\n"); lastwarning= s-2; }else { qh->ROTATErandom= i= qh_strtol(s, &s); if (i > 0) qh_option(qh, "QRotate-id", &i, NULL ); else if (i < -1) qh_option(qh, "QRandom-seed", &i, NULL ); } break; case 'V': i= qh_strtol(s, &t); if (qh->GOODvertex) { qh_fprintf(qh, qh->ferr, 7021, "qhull option warning: good vertex already defined for option 'QVn'. Ignored\n"); lastwarning= s-2; }else if (s == t) { qh_fprintf(qh, qh->ferr, 7022, "qhull option warning: no good point id given for option 'QVn'. Ignored\n"); lastwarning= s-2; }else if (i < 0) { qh->GOODvertex= i - 1; qh_option(qh, "QV-good-facets-not-point", &i, NULL); }else { qh_option(qh, "QV-good-facets-point", &i, NULL); qh->GOODvertex= i + 1; } s= t; break; case 'w': qh_option(qh, "Qwarn-allow", NULL, NULL); qh->ALLOWwarning= True; break; default: s--; qh_fprintf(qh, qh->ferr, 7023, "qhull option warning: unknown 'Q' qhull option 'Q%c', skip to next space\n", (int)s[0]); lastwarning= s-1; while (*++s && !isspace(*s)); break; } } break; case 'T': while (*s && !isspace(*s)) { if (isdigit(*s) || *s == '-') qh->IStracing= qh_strtol(s, &s); else switch (*s++) { case 'a': qh_option(qh, "Tannotate-output", NULL, NULL); qh->ANNOTATEoutput= True; break; case 'c': qh_option(qh, "Tcheck-frequently", NULL, NULL); qh->CHECKfrequently= True; break; case 'f': qh_option(qh, "Tflush", NULL, NULL); qh->FLUSHprint= True; break; case 's': qh_option(qh, "Tstatistics", NULL, NULL); qh->PRINTstatistics= True; break; case 'v': qh_option(qh, "Tverify", NULL, NULL); qh->VERIFYoutput= True; break; case 'z': if (qh->ferr == qh_FILEstderr) { /* The C++ interface captures the output in qh_fprint_qhull() */ qh_option(qh, "Tz-stdout", NULL, NULL); qh->USEstdout= True; }else if (!qh->fout) { qh_fprintf(qh, qh->ferr, 7024, "qhull option warning: output file undefined(stdout). Option 'Tz' ignored.\n"); lastwarning= s-2; }else { qh_option(qh, "Tz-stdout", NULL, NULL); qh->USEstdout= True; qh->ferr= qh->fout; qh->qhmem.ferr= qh->fout; } break; case 'C': if (!isdigit(*s)) { qh_fprintf(qh, qh->ferr, 7025, "qhull option warning: missing point id for cone for trace option 'TCn'\n"); lastwarning= s-2; }else { i= qh_strtol(s, &s); qh_option(qh, "TCone-stop", &i, NULL); qh->STOPcone= i + 1; } break; case 'F': if (!isdigit(*s)) { qh_fprintf(qh, qh->ferr, 7026, "qhull option warning: missing frequency count for trace option 'TFn'\n"); lastwarning= s-2; }else { qh->REPORTfreq= qh_strtol(s, &s); qh_option(qh, "TFacet-log", &qh->REPORTfreq, NULL); qh->REPORTfreq2= qh->REPORTfreq/2; /* for tracemerging() */ } break; case 'I': while (isspace(*s)) s++; t= qh_skipfilename(qh, s); { char filename[qh_FILENAMElen]; qh_copyfilename(qh, filename, (int)sizeof(filename), s, (int)(t-s)); /* WARN64 */ s= t; if (!freopen(filename, "r", stdin)) { qh_fprintf(qh, qh->ferr, 6041, "qhull option error: cannot open 'TI' file \"%s\"\n", filename); qh_errexit(qh, qh_ERRinput, NULL, NULL); }else { qh_option(qh, "TInput-file", NULL, NULL); qh_option(qh, filename, NULL, NULL); } } break; case 'O': while (isspace(*s)) s++; t= qh_skipfilename(qh, s); { char filename[qh_FILENAMElen]; qh_copyfilename(qh, filename, (int)sizeof(filename), s, (int)(t-s)); /* WARN64 */ if (!qh->fout) { qh_fprintf(qh, qh->ferr, 7092, "qhull option warning: qh.fout was not set by caller of qh_initflags. Cannot use option 'TO' to redirect output. Ignoring option 'TO'\n"); lastwarning= s-2; }else if (!freopen(filename, "w", qh->fout)) { qh_fprintf(qh, qh->ferr, 6044, "qhull option error: cannot open file \"%s\" for writing as option 'TO'. It is already in use or read-only\n", filename); qh_errexit(qh, qh_ERRinput, NULL, NULL); }else { qh_option(qh, "TOutput-file", NULL, NULL); qh_option(qh, filename, NULL, NULL); } s= t; } break; case 'A': if (!isdigit(*s)) { qh_fprintf(qh, qh->ferr, 7093, "qhull option warning: missing count of added points for trace option 'TAn'\n"); lastwarning= s-2; }else { i= qh_strtol(s, &t); qh->STOPadd= i + 1; qh_option(qh, "TA-stop-add", &i, NULL); } s= t; break; case 'P': if (*s == '-') { if (s[1] == '1' && !isdigit(s[2])) { s += 2; qh->TRACEpoint= qh_IDunknown; /* qh_buildhull done */ qh_option(qh, "Trace-point", &qh->TRACEpoint, NULL); }else { qh_fprintf(qh, qh->ferr, 7100, "qhull option warning: negative point id for trace option 'TPn'. Expecting 'TP-1' for tracing after qh_buildhull and qh_postmerge\n"); lastwarning= s-2; while (isdigit(*(++s))) ; /* skip digits */ } }else if (!isdigit(*s)) { qh_fprintf(qh, qh->ferr, 7029, "qhull option warning: missing point id or -1 for trace option 'TPn'\n"); lastwarning= s-2; }else { qh->TRACEpoint= qh_strtol(s, &s); qh_option(qh, "Trace-point", &qh->TRACEpoint, NULL); } break; case 'M': if (!isdigit(*s)) { qh_fprintf(qh, qh->ferr, 7030, "qhull option warning: missing merge id for trace option 'TMn'\n"); lastwarning= s-2; }else { qh->TRACEmerge= qh_strtol(s, &s); qh_option(qh, "Trace-merge", &qh->TRACEmerge, NULL); } break; case 'R': if (!isdigit(*s)) { qh_fprintf(qh, qh->ferr, 7031, "qhull option warning: missing rerun count for trace option 'TRn'\n"); lastwarning= s-2; }else { qh->RERUN= qh_strtol(s, &s); qh_option(qh, "TRerun", &qh->RERUN, NULL); } break; case 'V': i= qh_strtol(s, &t); if (s == t) { qh_fprintf(qh, qh->ferr, 7032, "qhull option warning: missing furthest point id for trace option 'TVn'\n"); lastwarning= s-2; }else if (i < 0) { qh->STOPpoint= i - 1; qh_option(qh, "TV-stop-before-point", &i, NULL); }else { qh->STOPpoint= i + 1; qh_option(qh, "TV-stop-after-point", &i, NULL); } s= t; break; case 'W': if (!isdigit(*s)) { qh_fprintf(qh, qh->ferr, 7033, "qhull option warning: missing max width for trace option 'TWn'\n"); lastwarning= s-2; }else { qh->TRACEdist= (realT) qh_strtod(s, &s); qh_option(qh, "TWide-trace", NULL, &qh->TRACEdist); } break; default: s--; qh_fprintf(qh, qh->ferr, 7034, "qhull option warning: unknown 'T' trace option 'T%c', skip to next space\n", (int)s[0]); lastwarning= s-2; while (*++s && !isspace(*s)); break; } } break; default: qh_fprintf(qh, qh->ferr, 7094, "qhull option warning: unknown option '%c'(%x)\n", (int)s[-1], (int)s[-1]); lastwarning= s-2; break; } if (s-1 == prev_s && *s && !isspace(*s)) { qh_fprintf(qh, qh->ferr, 7036, "qhull option warning: missing space after option '%c'(%x), reserved for sub-options, ignoring '%c' options to next space\n", (int)*prev_s, (int)*prev_s, (int)*prev_s); lastwarning= s-1; while (*s && !isspace(*s)) s++; } } if (qh->STOPcone && qh->JOGGLEmax < REALmax/2) { qh_fprintf(qh, qh->ferr, 7078, "qhull option warning: 'TCn' (stopCone) ignored when used with 'QJn' (joggle)\n"); lastwarning= command; } if (isgeom && !qh->FORCEoutput && qh->PRINTout[1]) { qh_fprintf(qh, qh->ferr, 7037, "qhull option warning: additional output formats ('Fc',etc.) are not compatible with Geomview ('G'). Use option 'Po' to override\n"); lastwarning= command; } if (lastwarning && !qh->ALLOWwarning) { qh_fprintf(qh, qh->ferr, 6035, "qhull option error: see previous warnings, use 'Qw' to override: '%s' (last offset %d)\n", command, (int)(lastwarning-command)); qh_errexit(qh, qh_ERRinput, NULL, NULL); } trace4((qh, qh->ferr, 4093, "qh_initflags: option flags initialized\n")); /* set derived values in qh_initqhull_globals */ } /* initflags */ /*-<a href="qh-globa_r.htm#TOC" >-------------------------------</a><a name="initqhull_buffers">-</a> qh_initqhull_buffers(qh) initialize global memory buffers notes: must match qh_freebuffers() */ void qh_initqhull_buffers(qhT *qh) { int k; qh->TEMPsize= (qh->qhmem.LASTsize - (int)sizeof(setT))/SETelemsize; if (qh->TEMPsize <= 0 || qh->TEMPsize > qh->qhmem.LASTsize) qh->TEMPsize= 8; /* e.g., if qh_NOmem */ qh->other_points= qh_setnew(qh, qh->TEMPsize); qh->del_vertices= qh_setnew(qh, qh->TEMPsize); qh->coplanarfacetset= qh_setnew(qh, qh->TEMPsize); qh->NEARzero= (realT *)qh_memalloc(qh, qh->hull_dim * (int)sizeof(realT)); qh->lower_threshold= (realT *)qh_memalloc(qh, (qh->input_dim+1) * (int)sizeof(realT)); qh->upper_threshold= (realT *)qh_memalloc(qh, (qh->input_dim+1) * (int)sizeof(realT)); qh->lower_bound= (realT *)qh_memalloc(qh, (qh->input_dim+1) * (int)sizeof(realT)); qh->upper_bound= (realT *)qh_memalloc(qh, (qh->input_dim+1) * (int)sizeof(realT)); for (k=qh->input_dim+1; k--; ) { /* duplicated in qh_initqhull_buffers and qh_clear_outputflags */ qh->lower_threshold[k]= -REALmax; qh->upper_threshold[k]= REALmax; qh->lower_bound[k]= -REALmax; qh->upper_bound[k]= REALmax; } qh->gm_matrix= (coordT *)qh_memalloc(qh, (qh->hull_dim+1) * qh->hull_dim * (int)sizeof(coordT)); qh->gm_row= (coordT **)qh_memalloc(qh, (qh->hull_dim+1) * (int)sizeof(coordT *)); } /* initqhull_buffers */ /*-<a href="qh-globa_r.htm#TOC" >-------------------------------</a><a name="initqhull_globals">-</a> qh_initqhull_globals(qh, points, numpoints, dim, ismalloc ) initialize globals if ismalloc points were malloc'd and qhull should free at end returns: sets qh.first_point, num_points, input_dim, hull_dim and others seeds random number generator (seed=1 if tracing) modifies qh.hull_dim if ((qh.DELAUNAY and qh.PROJECTdelaunay) or qh.PROJECTinput) adjust user flags as needed also checks DIM3 dependencies and constants notes: do not use qh_point() since an input transformation may move them elsewhere qh_initqhull_start() sets default values for non-zero globals consider duplicate error checks in qh_readpoints. It is called before qh_initqhull_globals design: initialize points array from input arguments test for qh.ZEROcentrum (i.e., use opposite vertex instead of cetrum for convexity testing) initialize qh.CENTERtype, qh.normal_size, qh.center_size, qh.TRACEpoint/level, initialize and test random numbers qh_initqhull_outputflags() -- adjust and test output flags */ void qh_initqhull_globals(qhT *qh, coordT *points, int numpoints, int dim, boolT ismalloc) { int seed, pointsneeded, extra= 0, i, randi, k; realT randr; realT factorial; time_t timedata; trace0((qh, qh->ferr, 13, "qh_initqhull_globals: for %s | %s\n", qh->rbox_command, qh->qhull_command)); if (numpoints < 1 || numpoints > qh_POINTSmax) { qh_fprintf(qh, qh->ferr, 6412, "qhull input error (qh_initqhull_globals): expecting between 1 and %d points. Got %d %d-d points\n", qh_POINTSmax, numpoints, dim); qh_errexit(qh, qh_ERRinput, NULL, NULL); /* same error message in qh_readpoints */ } qh->POINTSmalloc= ismalloc; qh->first_point= points; qh->num_points= numpoints; qh->hull_dim= qh->input_dim= dim; if (!qh->NOpremerge && !qh->MERGEexact && !qh->PREmerge && qh->JOGGLEmax > REALmax/2) { qh->MERGING= True; if (qh->hull_dim <= 4) { qh->PREmerge= True; qh_option(qh, "_pre-merge", NULL, NULL); }else { qh->MERGEexact= True; qh_option(qh, "Qxact-merge", NULL, NULL); } }else if (qh->MERGEexact) qh->MERGING= True; if (qh->NOpremerge && (qh->MERGEexact || qh->PREmerge)) qh_fprintf(qh, qh->ferr, 7095, "qhull option warning: 'Q0-no-premerge' ignored due to exact merge ('Qx') or pre-merge ('C-n' or 'A-n')\n"); if (!qh->NOpremerge && qh->JOGGLEmax > REALmax/2) { #ifdef qh_NOmerge qh->JOGGLEmax= 0.0; #endif } if (qh->TRIangulate && qh->JOGGLEmax < REALmax/2 && !qh->PREmerge && !qh->POSTmerge && qh->PRINTprecision) qh_fprintf(qh, qh->ferr, 7038, "qhull option warning: joggle ('QJ') produces simplicial output (i.e., triangles in 2-D). Unless merging is requested, option 'Qt' has no effect\n"); if (qh->JOGGLEmax < REALmax/2 && qh->DELAUNAY && !qh->SCALEinput && !qh->SCALElast) { qh->SCALElast= True; qh_option(qh, "Qbbound-last-qj", NULL, NULL); } if (qh->MERGING && !qh->POSTmerge && qh->premerge_cos > REALmax/2 && qh->premerge_centrum == 0.0) { qh->ZEROcentrum= True; qh->ZEROall_ok= True; qh_option(qh, "_zero-centrum", NULL, NULL); } if (qh->JOGGLEmax < REALmax/2 && REALepsilon > 2e-8 && qh->PRINTprecision) qh_fprintf(qh, qh->ferr, 7039, "qhull warning: real epsilon, %2.2g, is probably too large for joggle('QJn')\nRecompile with double precision reals(see user_r.h).\n", REALepsilon); #ifdef qh_NOmerge if (qh->MERGING) { qh_fprintf(qh, qh->ferr, 6045, "qhull option error: merging not installed (qh_NOmerge) for 'Qx', 'Cn' or 'An')\n"); qh_errexit(qh, qh_ERRinput, NULL, NULL); } #endif if (qh->DELAUNAY && qh->KEEPcoplanar && !qh->KEEPinside) { qh->KEEPinside= True; qh_option(qh, "Qinterior-keep", NULL, NULL); } if (qh->VORONOI && !qh->DELAUNAY) { qh_fprintf(qh, qh->ferr, 6038, "qhull internal error (qh_initqhull_globals): if qh.VORONOI is set, qh.DELAUNAY must be set. Qhull constructs the Delaunay triangulation in order to compute the Voronoi diagram\n"); qh_errexit(qh, qh_ERRqhull, NULL, NULL); } if (qh->DELAUNAY && qh->HALFspace) { qh_fprintf(qh, qh->ferr, 6046, "qhull option error: can not use Delaunay('d') or Voronoi('v') with halfspace intersection('H')\n"); qh_errexit(qh, qh_ERRinput, NULL, NULL); /* same error message in qh_readpoints */ } if (!qh->DELAUNAY && (qh->UPPERdelaunay || qh->ATinfinity)) { qh_fprintf(qh, qh->ferr, 6047, "qhull option error: use upper-Delaunay('Qu') or infinity-point('Qz') with Delaunay('d') or Voronoi('v')\n"); qh_errexit(qh, qh_ERRinput, NULL, NULL); } if (qh->UPPERdelaunay && qh->ATinfinity) { qh_fprintf(qh, qh->ferr, 6048, "qhull option error: can not use infinity-point('Qz') with upper-Delaunay('Qu')\n"); qh_errexit(qh, qh_ERRinput, NULL, NULL); } if (qh->MERGEpinched && qh->ONLYgood) { qh_fprintf(qh, qh->ferr, 6362, "qhull option error: can not use merge-pinched-vertices ('Q14') with good-facets-only ('Qg')\n"); qh_errexit(qh, qh_ERRinput, NULL, NULL); } if (qh->MERGEpinched && qh->hull_dim == 2) { trace2((qh, qh->ferr, 2108, "qh_initqhull_globals: disable qh.MERGEpinched for 2-d. It has no effect")) qh->MERGEpinched= False; } if (qh->SCALElast && !qh->DELAUNAY && qh->PRINTprecision) qh_fprintf(qh, qh->ferr, 7040, "qhull option warning: option 'Qbb' (scale-last-coordinate) is normally used with 'd' or 'v'\n"); qh->DOcheckmax= (!qh->SKIPcheckmax && (qh->MERGING || qh->APPROXhull)); qh->KEEPnearinside= (qh->DOcheckmax && !(qh->KEEPinside && qh->KEEPcoplanar) && !qh->NOnearinside); if (qh->MERGING) qh->CENTERtype= qh_AScentrum; else if (qh->VORONOI) qh->CENTERtype= qh_ASvoronoi; if (qh->TESTvneighbors && !qh->MERGING) { qh_fprintf(qh, qh->ferr, 6049, "qhull option error: test vertex neighbors('Qv') needs a merge option\n"); qh_errexit(qh, qh_ERRinput, NULL ,NULL); } if (qh->PROJECTinput || (qh->DELAUNAY && qh->PROJECTdelaunay)) { qh->hull_dim -= qh->PROJECTinput; if (qh->DELAUNAY) { qh->hull_dim++; if (qh->ATinfinity) extra= 1; } } if (qh->hull_dim <= 1) { qh_fprintf(qh, qh->ferr, 6050, "qhull error: dimension %d must be > 1\n", qh->hull_dim); qh_errexit(qh, qh_ERRinput, NULL, NULL); } for (k=2, factorial=1.0; k < qh->hull_dim; k++) factorial *= k; qh->AREAfactor= 1.0 / factorial; trace2((qh, qh->ferr, 2005, "qh_initqhull_globals: initialize globals. input_dim %d, numpoints %d, malloc? %d, projected %d to hull_dim %d\n", qh->input_dim, numpoints, ismalloc, qh->PROJECTinput, qh->hull_dim)); qh->normal_size= qh->hull_dim * (int)sizeof(coordT); qh->center_size= qh->normal_size - (int)sizeof(coordT); pointsneeded= qh->hull_dim+1; if (qh->hull_dim > qh_DIMmergeVertex) { qh->MERGEvertices= False; qh_option(qh, "Q3-no-merge-vertices-dim-high", NULL, NULL); } if (qh->GOODpoint) pointsneeded++; #ifdef qh_NOtrace if (qh->IStracing || qh->TRACEmerge || qh->TRACEpoint != qh_IDnone || qh->TRACEdist < REALmax/2) { qh_fprintf(qh, qh->ferr, 6051, "qhull option error: tracing is not installed (qh_NOtrace in user_r.h). Trace options 'Tn', 'TMn', 'TPn' and 'TWn' mostly removed. Continue with 'Qw' (allow warning)\n"); if (!qh->ALLOWwarning) qh_errexit(qh, qh_ERRinput, NULL, NULL); } #endif if (qh->RERUN > 1) { qh->TRACElastrun= qh->IStracing; /* qh_build_withrestart duplicates next conditional */ if (qh->IStracing && qh->IStracing != -1) { qh_fprintf(qh, qh->ferr, 8162, "qh_initqhull_globals: trace last of TR%d runs at level %d\n", qh->RERUN, qh->IStracing); qh->IStracing= 0; } }else if (qh->TRACEpoint != qh_IDnone || qh->TRACEdist < REALmax/2 || qh->TRACEmerge) { qh->TRACElevel= (qh->IStracing ? qh->IStracing : 3); qh->IStracing= 0; } if (qh->ROTATErandom == 0 || qh->ROTATErandom == -1) { seed= (int)time(&timedata); if (qh->ROTATErandom == -1) { seed= -seed; qh_option(qh, "QRandom-seed", &seed, NULL ); }else qh_option(qh, "QRotate-random", &seed, NULL); qh->ROTATErandom= seed; } seed= qh->ROTATErandom; if (seed == INT_MIN) /* default value */ seed= 1; else if (seed < 0) seed= -seed; qh_RANDOMseed_(qh, seed); randr= 0.0; for (i=1000; i--; ) { randi= qh_RANDOMint; randr += randi; if (randi > qh_RANDOMmax) { qh_fprintf(qh, qh->ferr, 8036, "\ qhull configuration error (qh_RANDOMmax in user_r.h): random integer %d > qh_RANDOMmax (%.8g)\n", randi, qh_RANDOMmax); qh_errexit(qh, qh_ERRinput, NULL, NULL); } } qh_RANDOMseed_(qh, seed); randr= randr/1000; if (randr < qh_RANDOMmax * 0.1 || randr > qh_RANDOMmax * 0.9) qh_fprintf(qh, qh->ferr, 8037, "\ qhull configuration warning (qh_RANDOMmax in user_r.h): average of 1000 random integers (%.2g) is much different than expected (%.2g). Is qh_RANDOMmax (%.2g) wrong?\n", randr, qh_RANDOMmax * 0.5, qh_RANDOMmax); qh->RANDOMa= 2.0 * qh->RANDOMfactor/qh_RANDOMmax; qh->RANDOMb= 1.0 - qh->RANDOMfactor; if (qh_HASHfactor < 1.1) { qh_fprintf(qh, qh->ferr, 6052, "qhull internal error (qh_initqhull_globals): qh_HASHfactor %d must be at least 1.1. Qhull uses linear hash probing\n", qh_HASHfactor); qh_errexit(qh, qh_ERRqhull, NULL, NULL); } if (numpoints+extra < pointsneeded) { qh_fprintf(qh, qh->ferr, 6214, "qhull input error: not enough points(%d) to construct initial simplex (need %d)\n", numpoints, pointsneeded); qh_errexit(qh, qh_ERRinput, NULL, NULL); } qh_initqhull_outputflags(qh); } /* initqhull_globals */ /*-<a href="qh-globa_r.htm#TOC" >-------------------------------</a><a name="initqhull_mem">-</a> qh_initqhull_mem(qh ) initialize mem_r.c for qhull qh.hull_dim and qh.normal_size determine some of the allocation sizes if qh.MERGING, includes ridgeT calls qh_user_memsizes (user_r.c) to add up to 10 additional sizes for quick allocation (see numsizes below) returns: mem_r.c already for qh_memalloc/qh_memfree (errors if called beforehand) notes: qh_produceoutput() prints memsizes */ void qh_initqhull_mem(qhT *qh) { int numsizes; int i; numsizes= 8+10; qh_meminitbuffers(qh, qh->IStracing, qh_MEMalign, numsizes, qh_MEMbufsize, qh_MEMinitbuf); qh_memsize(qh, (int)sizeof(vertexT)); if (qh->MERGING) { qh_memsize(qh, (int)sizeof(ridgeT)); qh_memsize(qh, (int)sizeof(mergeT)); } qh_memsize(qh, (int)sizeof(facetT)); i= (int)sizeof(setT) + (qh->hull_dim - 1) * SETelemsize; /* ridge.vertices */ qh_memsize(qh, i); qh_memsize(qh, qh->normal_size); /* normal */ i += SETelemsize; /* facet.vertices, .ridges, .neighbors */ qh_memsize(qh, i); qh_user_memsizes(qh); qh_memsetup(qh); } /* initqhull_mem */ /*-<a href="qh-globa_r.htm#TOC" >-------------------------------</a><a name="initqhull_outputflags">-</a> qh_initqhull_outputflags initialize flags concerned with output returns: adjust user flags as needed see: qh_clear_outputflags() resets the flags design: test for qh.PRINTgood (i.e., only print 'good' facets) check for conflicting print output options */ void qh_initqhull_outputflags(qhT *qh) { boolT printgeom= False, printmath= False, printcoplanar= False; int i; trace3((qh, qh->ferr, 3024, "qh_initqhull_outputflags: %s\n", qh->qhull_command)); if (!(qh->PRINTgood || qh->PRINTneighbors)) { if (qh->DELAUNAY || qh->KEEParea || qh->KEEPminArea < REALmax/2 || qh->KEEPmerge || (!qh->ONLYgood && (qh->GOODvertex || qh->GOODpoint))) { qh->PRINTgood= True; qh_option(qh, "Pgood", NULL, NULL); } } if (qh->PRINTtransparent) { if (qh->hull_dim != 4 || !qh->DELAUNAY || qh->VORONOI || qh->DROPdim >= 0) { qh_fprintf(qh, qh->ferr, 6215, "qhull option error: transparent Delaunay('Gt') needs 3-d Delaunay('d') w/o 'GDn'\n"); qh_errexit(qh, qh_ERRinput, NULL, NULL); } qh->DROPdim= 3; qh->PRINTridges= True; } for (i=qh_PRINTEND; i--; ) { if (qh->PRINTout[i] == qh_PRINTgeom) printgeom= True; else if (qh->PRINTout[i] == qh_PRINTmathematica || qh->PRINTout[i] == qh_PRINTmaple) printmath= True; else if (qh->PRINTout[i] == qh_PRINTcoplanars) printcoplanar= True; else if (qh->PRINTout[i] == qh_PRINTpointnearest) printcoplanar= True; else if (qh->PRINTout[i] == qh_PRINTpointintersect && !qh->HALFspace) { qh_fprintf(qh, qh->ferr, 6053, "qhull option error: option 'Fp' is only used for \nhalfspace intersection('Hn,n,n').\n"); qh_errexit(qh, qh_ERRinput, NULL, NULL); }else if (qh->PRINTout[i] == qh_PRINTtriangles && (qh->HALFspace || qh->VORONOI)) { qh_fprintf(qh, qh->ferr, 6054, "qhull option error: option 'Ft' is not available for Voronoi vertices ('v') or halfspace intersection ('H')\n"); qh_errexit(qh, qh_ERRinput, NULL, NULL); }else if (qh->PRINTout[i] == qh_PRINTcentrums && qh->VORONOI) { qh_fprintf(qh, qh->ferr, 6055, "qhull option error: option 'FC' is not available for Voronoi vertices('v')\n"); qh_errexit(qh, qh_ERRinput, NULL, NULL); }else if (qh->PRINTout[i] == qh_PRINTvertices) { if (qh->VORONOI) qh_option(qh, "Fvoronoi", NULL, NULL); else qh_option(qh, "Fvertices", NULL, NULL); } } if (printcoplanar && qh->DELAUNAY && qh->JOGGLEmax < REALmax/2) { if (qh->PRINTprecision) qh_fprintf(qh, qh->ferr, 7041, "qhull option warning: 'QJ' (joggle) will usually prevent coincident input sites for options 'Fc' and 'FP'\n"); } if (printmath && (qh->hull_dim > 3 || qh->VORONOI)) { qh_fprintf(qh, qh->ferr, 6056, "qhull option error: Mathematica and Maple output is only available for 2-d and 3-d convex hulls and 2-d Delaunay triangulations\n"); qh_errexit(qh, qh_ERRinput, NULL, NULL); } if (printgeom) { if (qh->hull_dim > 4) { qh_fprintf(qh, qh->ferr, 6057, "qhull option error: Geomview output is only available for 2-d, 3-d and 4-d\n"); qh_errexit(qh, qh_ERRinput, NULL, NULL); } if (qh->PRINTnoplanes && !(qh->PRINTcoplanar + qh->PRINTcentrums + qh->PRINTdots + qh->PRINTspheres + qh->DOintersections + qh->PRINTridges)) { qh_fprintf(qh, qh->ferr, 6058, "qhull option error: no output specified for Geomview\n"); qh_errexit(qh, qh_ERRinput, NULL, NULL); } if (qh->VORONOI && (qh->hull_dim > 3 || qh->DROPdim >= 0)) { qh_fprintf(qh, qh->ferr, 6059, "qhull option error: Geomview output for Voronoi diagrams only for 2-d\n"); qh_errexit(qh, qh_ERRinput, NULL, NULL); } /* can not warn about furthest-site Geomview output: no lower_threshold */ if (qh->hull_dim == 4 && qh->DROPdim == -1 && (qh->PRINTcoplanar || qh->PRINTspheres || qh->PRINTcentrums)) { qh_fprintf(qh, qh->ferr, 7042, "qhull option warning: coplanars, vertices, and centrums output not available for 4-d output(ignored). Could use 'GDn' instead.\n"); qh->PRINTcoplanar= qh->PRINTspheres= qh->PRINTcentrums= False; } } if (!qh->KEEPcoplanar && !qh->KEEPinside && !qh->ONLYgood) { if ((qh->PRINTcoplanar && qh->PRINTspheres) || printcoplanar) { if (qh->QHULLfinished) { qh_fprintf(qh, qh->ferr, 7072, "qhull output warning: ignoring coplanar points, option 'Qc' was not set for the first run of qhull.\n"); }else { qh->KEEPcoplanar= True; qh_option(qh, "Qcoplanar", NULL, NULL); } } } qh->PRINTdim= qh->hull_dim; if (qh->DROPdim >=0) { /* after Geomview checks */ if (qh->DROPdim < qh->hull_dim) { qh->PRINTdim--; if (!printgeom || qh->hull_dim < 3) qh_fprintf(qh, qh->ferr, 7043, "qhull option warning: drop dimension 'GD%d' is only available for 3-d/4-d Geomview\n", qh->DROPdim); }else qh->DROPdim= -1; }else if (qh->VORONOI) { qh->DROPdim= qh->hull_dim-1; qh->PRINTdim= qh->hull_dim-1; } } /* qh_initqhull_outputflags */ /*-<a href="qh-globa_r.htm#TOC" >-------------------------------</a><a name="initqhull_start">-</a> qh_initqhull_start(qh, infile, outfile, errfile ) allocate memory if needed and call qh_initqhull_start2() */ void qh_initqhull_start(qhT *qh, FILE *infile, FILE *outfile, FILE *errfile) { qh_initstatistics(qh); qh_initqhull_start2(qh, infile, outfile, errfile); } /* initqhull_start */ /*-<a href="qh-globa_r.htm#TOC" >-------------------------------</a><a name="initqhull_start2">-</a> qh_initqhull_start2(qh, infile, outfile, errfile ) start initialization of qhull initialize statistics, stdio, default values for global variables assumes qh is allocated notes: report errors elsewhere, error handling and g_qhull_output [Qhull.cpp, QhullQh()] not in initialized see: qh_maxmin() determines the precision constants qh_freeqhull() */ void qh_initqhull_start2(qhT *qh, FILE *infile, FILE *outfile, FILE *errfile) { time_t timedata; int seed; qh_CPUclock; /* start the clock(for qh_clock). One-shot. */ /* memset is the same in qh_freeqhull() and qh_initqhull_start2() */ memset((char *)qh, 0, sizeof(qhT)-sizeof(qhmemT)-sizeof(qhstatT)); /* every field is 0, FALSE, NULL */ qh->NOerrexit= True; qh->DROPdim= -1; qh->ferr= errfile; qh->fin= infile; qh->fout= outfile; qh->furthest_id= qh_IDunknown; #ifndef qh_NOmerge qh->JOGGLEmax= REALmax; #else qh->JOGGLEmax= 0.0; /* Joggle ('QJ') if qh_NOmerge */ #endif qh->KEEPminArea= REALmax; qh->last_low= REALmax; qh->last_high= REALmax; qh->last_newhigh= REALmax; qh->last_random= 1; /* reentrant only */ qh->lastcpu= 0.0; qh->max_outside= 0.0; qh->max_vertex= 0.0; qh->MAXabs_coord= 0.0; qh->MAXsumcoord= 0.0; qh->MAXwidth= -REALmax; qh->MERGEindependent= True; qh->MINdenom_1= fmax_(1.0/REALmax, REALmin); /* used by qh_scalepoints */ qh->MINoutside= 0.0; qh->MINvisible= REALmax; qh->MAXcoplanar= REALmax; qh->outside_err= REALmax; qh->premerge_centrum= 0.0; qh->premerge_cos= REALmax; qh->PRINTprecision= True; qh->PRINTradius= 0.0; qh->postmerge_cos= REALmax; qh->postmerge_centrum= 0.0; qh->ROTATErandom= INT_MIN; qh->MERGEvertices= True; qh->totarea= 0.0; qh->totvol= 0.0; qh->TRACEdist= REALmax; qh->TRACEpoint= qh_IDnone; /* recompile to trace a point, or use 'TPn' */ qh->tracefacet_id= UINT_MAX; /* recompile to trace a facet, set to UINT_MAX when done, see userprintf_r.c/qh_fprintf */ qh->traceridge_id= UINT_MAX; /* recompile to trace a ridge, set to UINT_MAX when done, see userprintf_r.c/qh_fprintf */ qh->tracevertex_id= UINT_MAX; /* recompile to trace a vertex, set to UINT_MAX when done, see userprintf_r.c/qh_fprintf */ seed= (int)time(&timedata); qh_RANDOMseed_(qh, seed); qh->run_id= qh_RANDOMint; if(!qh->run_id) qh->run_id++; /* guarantee non-zero */ qh_option(qh, "run-id", &qh->run_id, NULL); strcat(qh->qhull, "qhull"); } /* initqhull_start2 */ /*-<a href="qh-globa_r.htm#TOC" >-------------------------------</a><a name="initthresholds">-</a> qh_initthresholds(qh, commandString ) set thresholds for printing and scaling from commandString returns: sets qh.GOODthreshold or qh.SPLITthreshold if 'Pd0D1' used see: qh_initflags(), 'Qbk' 'QBk' 'Pdk' and 'PDk' qh_inthresholds() design: for each 'Pdn' or 'PDn' option check syntax set qh.lower_threshold or qh.upper_threshold set qh.GOODthreshold if an unbounded threshold is used set qh.SPLITthreshold if a bounded threshold is used */ void qh_initthresholds(qhT *qh, char *command) { realT value; int idx, maxdim, k; char *s= command; /* non-const due to strtol */ char *lastoption, *lastwarning= NULL; char key; maxdim= qh->input_dim; if (qh->DELAUNAY && (qh->PROJECTdelaunay || qh->PROJECTinput)) maxdim++; while (*s) { if (*s == '-') s++; if (*s == 'P') { lastoption= s++; while (*s && !isspace(key= *s++)) { if (key == 'd' || key == 'D') { if (!isdigit(*s)) { qh_fprintf(qh, qh->ferr, 7044, "qhull option warning: no dimension given for Print option 'P%c' at: %s. Ignored\n", key, s-1); lastwarning= lastoption; continue; } idx= qh_strtol(s, &s); if (idx >= qh->hull_dim) { qh_fprintf(qh, qh->ferr, 7045, "qhull option warning: dimension %d for Print option 'P%c' is >= %d. Ignored\n", idx, key, qh->hull_dim); lastwarning= lastoption; continue; } if (*s == ':') { s++; value= qh_strtod(s, &s); if (fabs((double)value) > 1.0) { qh_fprintf(qh, qh->ferr, 7046, "qhull option warning: value %2.4g for Print option 'P%c' is > +1 or < -1. Ignored\n", value, key); lastwarning= lastoption; continue; } }else value= 0.0; if (key == 'd') qh->lower_threshold[idx]= value; else qh->upper_threshold[idx]= value; } } }else if (*s == 'Q') { lastoption= s++; while (*s && !isspace(key= *s++)) { if (key == 'b' && *s == 'B') { s++; for (k=maxdim; k--; ) { qh->lower_bound[k]= -qh_DEFAULTbox; qh->upper_bound[k]= qh_DEFAULTbox; } }else if (key == 'b' && *s == 'b') s++; else if (key == 'b' || key == 'B') { if (!isdigit(*s)) { qh_fprintf(qh, qh->ferr, 7047, "qhull option warning: no dimension given for Qhull option 'Q%c'\n", key); lastwarning= lastoption; continue; } idx= qh_strtol(s, &s); if (idx >= maxdim) { qh_fprintf(qh, qh->ferr, 7048, "qhull option warning: dimension %d for Qhull option 'Q%c' is >= %d. Ignored\n", idx, key, maxdim); lastwarning= lastoption; continue; } if (*s == ':') { s++; value= qh_strtod(s, &s); }else if (key == 'b') value= -qh_DEFAULTbox; else value= qh_DEFAULTbox; if (key == 'b') qh->lower_bound[idx]= value; else qh->upper_bound[idx]= value; } } }else { while (*s && !isspace(*s)) s++; } while (isspace(*s)) s++; } for (k=qh->hull_dim; k--; ) { if (qh->lower_threshold[k] > -REALmax/2) { qh->GOODthreshold= True; if (qh->upper_threshold[k] < REALmax/2) { qh->SPLITthresholds= True; qh->GOODthreshold= False; break; } }else if (qh->upper_threshold[k] < REALmax/2) qh->GOODthreshold= True; } if (lastwarning && !qh->ALLOWwarning) { qh_fprintf(qh, qh->ferr, 6036, "qhull option error: see previous warnings, use 'Qw' to override: '%s' (last offset %d)\n", command, (int)(lastwarning-command)); qh_errexit(qh, qh_ERRinput, NULL, NULL); } } /* initthresholds */ /*-<a href="qh-globa_r.htm#TOC" >-------------------------------</a><a name="lib_check">-</a> qh_lib_check( qhullLibraryType, qhTsize, vertexTsize, ridgeTsize, facetTsize, setTsize, qhmemTsize ) Report error if library does not agree with caller notes: NOerrors -- qh_lib_check can not call qh_errexit() */ void qh_lib_check(int qhullLibraryType, int qhTsize, int vertexTsize, int ridgeTsize, int facetTsize, int setTsize, int qhmemTsize) { int last_errcode= qh_ERRnone; #if defined(_MSC_VER) && defined(_DEBUG) && defined(QHULL_CRTDBG) /* user_r.h */ /*_CrtSetBreakAlloc(744);*/ /* Break at memalloc {744}, or 'watch' _crtBreakAlloc */ _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_DELAY_FREE_MEM_DF | _CRTDBG_LEAK_CHECK_DF | _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) ); _CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG ); _CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDERR ); _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG ); _CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDERR ); _CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG ); _CrtSetReportFile( _CRT_ASSERT, _CRTDBG_FILE_STDERR ); #endif if (qhullLibraryType==QHULL_NON_REENTRANT) { /* 0 */ qh_fprintf_stderr(6257, "qh_lib_check: Incorrect qhull library called. Caller uses non-reentrant Qhull with a static qhT. Qhull library is reentrant.\n"); last_errcode= 6257; }else if (qhullLibraryType==QHULL_QH_POINTER) { /* 1 */ qh_fprintf_stderr(6258, "qh_lib_check: Incorrect qhull library called. Caller uses non-reentrant Qhull with a dynamic qhT via qh_QHpointer. Qhull library is reentrant.\n"); last_errcode= 6258; }else if (qhullLibraryType != QHULL_REENTRANT) { /* 2 */ qh_fprintf_stderr(6262, "qh_lib_check: Expecting qhullLibraryType QHULL_NON_REENTRANT(0), QHULL_QH_POINTER(1), or QHULL_REENTRANT(2). Got %d\n", qhullLibraryType); last_errcode= 6262; } if (qhTsize != (int)sizeof(qhT)) { qh_fprintf_stderr(6249, "qh_lib_check: Incorrect qhull library called. Size of qhT for caller is %d, but for qhull library is %d.\n", qhTsize, (int)sizeof(qhT)); last_errcode= 6249; } if (vertexTsize != (int)sizeof(vertexT)) { qh_fprintf_stderr(6250, "qh_lib_check: Incorrect qhull library called. Size of vertexT for caller is %d, but for qhull library is %d.\n", vertexTsize, (int)sizeof(vertexT)); last_errcode= 6250; } if (ridgeTsize != (int)sizeof(ridgeT)) { qh_fprintf_stderr(6251, "qh_lib_check: Incorrect qhull library called. Size of ridgeT for caller is %d, but for qhull library is %d.\n", ridgeTsize, (int)sizeof(ridgeT)); last_errcode= 6251; } if (facetTsize != (int)sizeof(facetT)) { qh_fprintf_stderr(6252, "qh_lib_check: Incorrect qhull library called. Size of facetT for caller is %d, but for qhull library is %d.\n", facetTsize, (int)sizeof(facetT)); last_errcode= 6252; } if (setTsize && setTsize != (int)sizeof(setT)) { qh_fprintf_stderr(6253, "qh_lib_check: Incorrect qhull library called. Size of setT for caller is %d, but for qhull library is %d.\n", setTsize, (int)sizeof(setT)); last_errcode= 6253; } if (qhmemTsize && qhmemTsize != sizeof(qhmemT)) { qh_fprintf_stderr(6254, "qh_lib_check: Incorrect qhull library called. Size of qhmemT for caller is %d, but for qhull library is %d.\n", qhmemTsize, sizeof(qhmemT)); last_errcode= 6254; } if (last_errcode) { qh_fprintf_stderr(6259, "qhull internal error (qh_lib_check): Cannot continue due to QH%d. '%s' is not reentrant (e.g., qhull.so) or out-of-date. Exit with %d\n", last_errcode, qh_version2, last_errcode - 6200); qh_exit(last_errcode - 6200); /* can not use qh_errexit(), must be less than 255 */ } } /* lib_check */ /*-<a href="qh-globa_r.htm#TOC" >-------------------------------</a><a name="option">-</a> qh_option(qh, option, intVal, realVal ) add an option description to qh.qhull_options notes: NOerrors -- qh_option can not call qh_errexit() [qh_initqhull_start2] will be printed with statistics ('Ts') and errors strlen(option) < 40 */ void qh_option(qhT *qh, const char *option, int *i, realT *r) { char buf[200]; int buflen, remainder; if (strlen(option) > sizeof(buf)-30-30) { qh_fprintf(qh, qh->ferr, 6408, "qhull internal error (qh_option): option (%d chars) has more than %d chars. May overflow temporary buffer. Option '%s'\n", (int)strlen(option), (int)sizeof(buf)-30-30, option); qh_errexit(qh, qh_ERRqhull, NULL, NULL); } sprintf(buf, " %s", option); if (i) sprintf(buf+strlen(buf), " %d", *i); if (r) sprintf(buf+strlen(buf), " %2.2g", *r); buflen= (int)strlen(buf); /* WARN64 */ qh->qhull_optionlen += buflen; remainder= (int)(sizeof(qh->qhull_options) - strlen(qh->qhull_options)) - 1; /* WARN64 */ maximize_(remainder, 0); if (qh->qhull_optionlen >= qh_OPTIONline && remainder > 0) { strncat(qh->qhull_options, "\n", (unsigned int)remainder); --remainder; qh->qhull_optionlen= buflen; } if (buflen > remainder) { trace1((qh, qh->ferr, 1058, "qh_option: option would overflow qh.qhull_options. Truncated '%s'\n", buf)); } strncat(qh->qhull_options, buf, (unsigned int)remainder); } /* option */ /*-<a href="qh-globa_r.htm#TOC" >-------------------------------</a><a name="zero">-</a> qh_zero( qh, errfile ) Initialize and zero Qhull's memory for qh_new_qhull() notes: Not needed in global_r.c because static variables are initialized to zero */ void qh_zero(qhT *qh, FILE *errfile) { memset((char *)qh, 0, sizeof(qhT)); /* every field is 0, FALSE, NULL */ qh->NOerrexit= True; qh_meminit(qh, errfile); } /* zero */
0654e1f60501e7c0bfaf5fa3adee574807e58c69
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
/sys/dev/pci/pci_calls.h
9d0fd8975cbdc98b8bd31995ba79f863d4579f71
[]
no_license
NetBSD/src
1a9cbc22ed778be638b37869ed4fb5c8dd616166
23ee83f7c0aea0777bd89d8ebd7f0cde9880d13c
refs/heads/trunk
2023-08-31T13:24:58.105962
2023-08-27T15:50:47
2023-08-27T15:50:47
88,439,547
656
348
null
2023-07-20T20:07:24
2017-04-16T20:03:43
null
UTF-8
C
false
false
3,092
h
pci_calls.h
/* $NetBSD: pci_calls.h,v 1.1 2021/09/15 17:33:08 thorpej Exp $ */ /* * THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. * * generated from: * NetBSD: pci_calls,v 1.1 2021/09/15 17:26:07 thorpej Exp */ /*- * Copyright (c) 2021 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Jason R. Thorpe. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE 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. */ /* * Device calls used by the PCI subsystem. */ #ifndef _PCI_CALLS_H_ #define _PCI_CALLS_H_ #include <sys/device.h> #include <dev/pci/pcivar.h> /* * pci-bus-get-child-devhandle * * Retrieve the devhandle for the PCI device represented by 'tag' * in the PCI segment represented by 'pc'. The PCI bus's device_t * is the one that's passed in the call, and the device whose handle * is being requested must be a direct child of that bus, otherwise * behavior is undefined. * * Call returns 0 if successful, or an error code upon failure: * * ENOTSUP The device handle implementation for the * PCI bus does not support this device call. * * ENODEV The PCI device represented by the pcitag_t * was not found in a bus-scoped search of the * platform device tree. */ struct pci_bus_get_child_devhandle_args { pci_chipset_tag_t pc; /* IN */ pcitag_t tag; /* IN */ devhandle_t devhandle; /* OUT */ }; union pci_bus_get_child_devhandle_binding { struct device_call_generic generic; struct { const char *name; struct pci_bus_get_child_devhandle_args *args; } binding; }; #define PCI_BUS_GET_CHILD_DEVHANDLE_STR "pci-bus-get-child-devhandle" #define PCI_BUS_GET_CHILD_DEVHANDLE(_args_) \ &((const union pci_bus_get_child_devhandle_binding){ \ .binding.name = "pci-bus-get-child-devhandle", \ .binding.args = (_args_), \ }) #endif /* _PCI_CALLS_H_ */
b705d467a00facc75486d5609171aae82f9bfc6e
1f399edf85d995443d01f66d77eca0723886d0ff
/devicemodel/include/mei.h
5c85994352c063ff383b82e18456d8a69baefe05
[ "BSD-3-Clause" ]
permissive
projectacrn/acrn-hypervisor
f9c5864d54929a5d2fa36b5e78c08f19b46b8f98
390740aa1b1e9d62c51f8e3afa0c29e07e43fa23
refs/heads/master
2023-08-18T05:07:01.310327
2023-08-11T07:49:36
2023-08-16T13:20:27
123,983,554
1,059
686
BSD-3-Clause
2023-09-14T09:51:10
2018-03-05T21:52:25
C
UTF-8
C
false
false
12,678
h
mei.h
/* * Copyright (C) 2018-2022 Intel Corporation. * * SPDX-License-Identifier: BSD-3-Clause * */ #ifndef _MEI_HBM_H_ #define _MEI_HBM_H_ #include <linux/uuid.h> #include <linux/mei.h> #ifndef guid_t #define guid_t uuid_le #endif /* * Timeouts in Seconds */ #define MEI_HW_READY_TIMEOUT 2 /* Timeout on ready message */ #define MEI_CONNECT_TIMEOUT 3 /* HPS: at least 2 seconds */ #define MEI_CL_CONNECT_TIMEOUT 15 /* HPS: Client Connect Timeout */ #define MEI_CLIENTS_INIT_TIMEOUT 15 /* HPS: Clients Enumeration Timeout */ #define MEI_PGI_TIMEOUT 1 /* PG Isolation time response 1 sec */ #define MEI_D0I3_TIMEOUT 5 /* D0i3 set/unset max response time */ #define MEI_HBM_TIMEOUT 1 /* 1 second */ /* * MEI Version */ #define MEI_HBM_MINOR_VERSION 0 #define MEI_HBM_MAJOR_VERSION 2 /* * MEI version with PGI support */ #define MEI_HBM_MINOR_VERSION_PGI 1 #define MEI_HBM_MAJOR_VERSION_PGI 1 /* * MEI version with Dynamic clients support */ #define MEI_HBM_MINOR_VERSION_DC 0 #define MEI_HBM_MAJOR_VERSION_DC 2 /* * MEI version with immediate reply to enum request support */ #define MEI_HBM_MINOR_VERSION_IE 0 #define MEI_HBM_MAJOR_VERSION_IE 2 /* * MEI version with disconnect on connection timeout support */ #define MEI_HBM_MINOR_VERSION_DOT 0 #define MEI_HBM_MAJOR_VERSION_DOT 2 /* * MEI version with notification support */ #define MEI_HBM_MINOR_VERSION_EV 0 #define MEI_HBM_MAJOR_VERSION_EV 2 /* * MEI version with fixed address client support */ #define MEI_HBM_MINOR_VERSION_FA 0 #define MEI_HBM_MAJOR_VERSION_FA 2 /* * MEI version with OS ver message support */ #define MEI_HBM_MINOR_VERSION_OS 0 #define MEI_HBM_MAJOR_VERSION_OS 2 /* * MEI version with dma ring support */ #define MEI_HBM_MINOR_VERSION_DR 1 #define HMEI_BM_MAJOR_VERSION_DR 2 /* Host bus message command opcode */ #define MEI_HBM_CMD_OP_MSK 0x7f /* Host bus message command RESPONSE */ #define MEI_HBM_CMD_RES_MSK 0x80 #define MEI_HBM_HOST_START 0x01 #define MEI_HBM_HOST_START_RES 0x81 #define MEI_HBM_HOST_STOP 0x02 #define MEI_HBM_HOST_STO_RES 0x82 #define MEI_HBM_ME_STOP 0x03 #define MEI_HBM_HOST_ENUM 0x04 #define MEI_HBM_HOST_ENUM_RES 0x84 #define MEI_HBM_HOST_CLIENT_PROP 0x05 #define MEI_HBM_HOST_CLIENT_PROP_RES 0x85 #define MEI_HBM_CLIENT_CONNECT 0x06 #define MEI_HBM_CLIENT_CONNECT_RES 0x86 #define MEI_HBM_CLIENT_DISCONNECT 0x07 #define MEI_HBM_CLIENT_DISCONNECT_RES 0x87 #define MEI_HBM_FLOW_CONTROL 0x08 #define MEI_HBM_CLIENT_CONNECTION_RESET 0x09 #define MEI_HBM_PG_ISOLATION_ENTRY 0x0a #define MEI_HBM_PG_ISOLATION_ENTRY_RES 0x8a #define MEI_HBM_PG_ISOLATION_EXIT 0x0b #define MEI_HBM_PG_ISOLATION_EXIT_RES 0x8b #define MEI_HBM_CLIENT_ADD 0x0f #define MEI_HBM_CLIENT_ADD_RES 0x8f #define MEI_HBM_NOTIFY 0x10 #define MEI_HBM_NOTIFY_RES 0x90 #define MEI_HBM_NOTIFICATION 0x11 #define MEI_HBM_DMA_SETUP 0x12 #define MEI_HBM_DMA_SETUP_RES 0x92 /* * MEI Stop Reason * used by hbm_host_stop_request.reason */ enum mei_stop_reason_types { DRIVER_STOP_REQUEST = 0x00, DEVICE_D1_ENTRY = 0x01, DEVICE_D2_ENTRY = 0x02, DEVICE_D3_ENTRY = 0x03, SYSTEM_S1_ENTRY = 0x04, SYSTEM_S2_ENTRY = 0x05, SYSTEM_S3_ENTRY = 0x06, SYSTEM_S4_ENTRY = 0x07, SYSTEM_S5_ENTRY = 0x08 }; /* * enum mei_hbm_status - mei host bus messages return values * * @MEI_HBM_SUCCESS : status success * @MEI_HBM_CLIENT_NOT_FOUND : client not found * @MEI_HBM_ALREADY_EXISTS : connection already established * @MEI_HBM_REJECTED : connection is rejected * @MEI_HBM_INVALID_PARAMETER : invalid parameter * @MEI_HBM_NOT_ALLOWED : operation not allowed * @MEI_HBM_ALREADY_STARTED : system is already started * @MEI_HBM_NOT_STARTED : system not started * */ enum mei_hbm_status { MEI_HBM_SUCCESS = 0, MEI_HBM_CLIENT_NOT_FOUND = 1, MEI_HBM_ALREADY_EXISTS = 2, MEI_HBM_REJECTED = 3, MEI_HBM_INVALID_PARAMETER = 4, MEI_HBM_NOT_ALLOWED = 5, MEI_HBM_ALREADY_STARTED = 6, MEI_HBM_NOT_STARTED = 7, MEI_HBM_MAX }; /* * Client Connect Status * used by hbm_client_connect_response.status */ enum mei_cl_connect_status { MEI_CL_CONN_SUCCESS = MEI_HBM_SUCCESS, MEI_CL_CONN_NOT_FOUND = MEI_HBM_CLIENT_NOT_FOUND, MEI_CL_CONN_ALREADY_STARTED = MEI_HBM_ALREADY_EXISTS, MEI_CL_CONN_OUT_OF_RESOURCES = MEI_HBM_REJECTED, MEI_CL_CONN_MESSAGE_SMALL = MEI_HBM_INVALID_PARAMETER, MEI_CL_CONN_NOT_ALLOWED = MEI_HBM_NOT_ALLOWED, }; /* * Client Disconnect Status */ enum mei_cl_disconnect_status { MEI_CL_DISCONN_SUCCESS = MEI_HBM_SUCCESS }; struct mei_enumerate_me_clients { uint8_t valid_addresses[32]; }; struct mei_client_properties { guid_t protocol_name; uint8_t protocol_version; uint8_t max_connections; uint8_t fixed_address; uint8_t single_recv_buf; uint32_t max_msg_length; } __attribute__((packed)); /* message header is same in native and virtual */ struct mei_msg_hdr { uint32_t me_addr:8; uint32_t host_addr:8; uint32_t length:9; uint32_t reserved:5; uint32_t internal:1; uint32_t msg_complete:1; } __attribute__((packed)); struct mei_hbm_cmd { uint8_t cmd:7; uint8_t is_response:1; } __attribute__((packed)); struct mei_hbm_host_ver_req { struct mei_hbm_cmd hbm_cmd; uint8_t reserved; uint8_t minor; uint8_t major; } __attribute__((packed)); struct mei_hbm_host_ver_res { struct mei_hbm_cmd hbm_cmd; uint8_t host_ver_support; uint8_t minor; uint8_t major; } __attribute__((packed)); struct mei_hbm_host_stop_req { struct mei_hbm_cmd hbm_cmd; uint8_t reason; uint8_t reserved[2]; } __attribute__((packed)); struct mei_hbm_host_stop_res { struct mei_hbm_cmd hbm_cmd; uint8_t reserved[3]; } __attribute__((packed)); struct mei_hbm_me_stop_res { struct mei_hbm_cmd hbm_cmd; uint8_t reason; uint8_t reserved[2]; } __attribute__((packed)); struct mei_hbm_me_stop_req { struct mei_hbm_cmd hbm_cmd; uint8_t reserved[3]; } __attribute__((packed)); /** * enum hbm_host_enum_flags - enumeration request flags (HBM version >= 2.0) * * @MEI_HBM_ENUM_F_ALLOW_ADD: allow dynamic clients add * @MEI_HBM_ENUM_F_IMMEDIATE_ENUM: allow FW to send answer immediately */ enum mei_hbm_host_enum_flags { MEI_HBM_ENUM_F_ALLOW_ADD = 0, MEI_HBM_ENUM_F_IMMEDIATE_ENUM = 1, }; struct mei_hbm_host_enum_req { struct mei_hbm_cmd hbm_cmd; uint8_t flags; uint8_t reserved[2]; } __attribute__((packed)); struct mei_hbm_host_enum_res { struct mei_hbm_cmd hbm_cmd; uint8_t reserved[3]; uint8_t valid_addresses[32]; }; struct mei_hbm_host_client_prop_req { struct mei_hbm_cmd hbm_cmd; uint8_t address; uint8_t reserved[2]; } __attribute__((packed)); struct mei_hbm_host_client_prop_res { struct mei_hbm_cmd hbm_cmd; uint8_t address; uint8_t status; uint8_t reserved[1]; struct mei_client_properties props; } __attribute__((packed)); /** * struct mei_hbm_add_client_req - request to add a client * might be sent by fw after enumeration has already completed * * @hbm_cmd: bus message command header * @me_addr: address of the client in ME * @reserved: reserved * @client_properties: client properties */ struct mei_hbm_add_client_req { struct mei_hbm_cmd hbm_cmd; uint8_t me_addr; uint8_t reserved[2]; struct mei_client_properties client_properties; } __attribute__((packed)); /** * struct mei_hbm_add_client_res - response to add a client * sent by the host to report client addition status to fw * * @hbm_cmd: bus message command header * @me_addr: address of the client in ME * @status: if HBM_SUCCESS then the client can now accept connections. * @reserved: reserved */ struct hbm_add_client_res { struct mei_hbm_cmd hbm_cmd; uint8_t me_addr; uint8_t status; uint8_t reserved[1]; } __attribute__((packed)); /** * struct mei_hbm_power_gate - power gate request/response * * @hbm_cmd: bus message command header * @reserved: reserved */ struct mei_hbm_power_gate { struct mei_hbm_cmd hbm_cmd; uint8_t reserved[3]; } __attribute__((packed)); struct mei_hbm_client_connect_req { struct mei_hbm_cmd hbm_cmd; uint8_t me_addr; uint8_t host_addr; uint8_t reserved; } __attribute__((packed)); struct mei_hbm_client_connect_res { struct mei_hbm_cmd hbm_cmd; uint8_t me_addr; uint8_t host_addr; uint8_t status; } __attribute__((packed)); struct mei_hbm_client_disconnect_req { struct mei_hbm_cmd hbm_cmd; uint8_t me_addr; uint8_t host_addr; uint8_t status; } __attribute__((packed)); struct mei_hbm_client_disconnect_res { struct mei_hbm_cmd hbm_cmd; uint8_t me_addr; uint8_t host_addr; uint8_t status; } __attribute__((packed)); struct mei_hbm_flow_ctl { struct mei_hbm_cmd hbm_cmd; uint8_t me_addr; uint8_t host_addr; uint8_t reserved[5]; } __attribute__((packed)); /** * struct mei_hbm_notification_req - start/stop notification request * * @hbm_cmd: bus message command header * @me_addr: address of the client in ME * @host_addr: address of the client in the driver * @start: start = 1 or stop = 0 asynchronous notifications */ struct mei_hbm_notification_req { struct mei_hbm_cmd hbm_cmd; uint8_t me_addr; uint8_t host_addr; uint8_t start; } __attribute__((packed)); /** * struct mei_hbm_notification_res - start/stop notification response * * @hbm_cmd: bus message command header * @me_addr: address of the client in ME * @host_addr: - address of the client in the driver * @status: (mei_hbm_status) response status for the request * - MEI_HBM_SUCCESS: successful stop/start * - MEI_HBM_CLIENT_NOT_FOUND: if the connection could not be found. * - MEI_HBM_ALREADY_STARTED: for start requests for a previously * started notification. * - MEI_HBM_NOT_STARTED: for stop request for a connected client for whom * asynchronous notifications are currently disabled. * * @start: start = 1 or stop = 0 asynchronous notifications * @reserved: reserved */ struct mei_hbm_notification_res { struct mei_hbm_cmd hbm_cmd; uint8_t me_addr; uint8_t host_addr; uint8_t status; uint8_t start; uint8_t reserved[3]; } __attribute__((packed)); /** * struct mei_hbm_notification - notification event * * @hbm_cmd: bus message command header * @me_addr: address of the client in ME * @host_addr: address of the client in the driver * @reserved: reserved for alignment */ struct mei_hbm_notification { struct mei_hbm_cmd hbm_cmd; uint8_t me_addr; uint8_t host_addr; uint8_t reserved[1]; } __attribute__((packed)); /** * struct mei_hbm_dma_mem_dscr - dma ring * * @addr_hi: the high 32bits of 64 bit address * @addr_lo: the low 32bits of 64 bit address * @size : size in bytes (must be power of 2) */ struct mei_hbm_dma_mem_dscr { uint32_t addr_hi; uint32_t addr_lo; uint32_t size; } __attribute__((packed)); enum { MEI_DMA_DSCR_HOST = 0, MEI_DMA_DSCR_DEVICE = 1, MEI_DMA_DSCR_CTRL = 2, MEI_DMA_DSCR_NUM, }; /** * struct mei_hbm_dma_setup_req - dma setup request * * @hbm_cmd: bus message command header * @reserved: reserved for alignment * @dma_dscr: dma descriptor for HOST, DEVICE, and CTRL */ struct mei_hbm_dma_setup_req { struct mei_hbm_cmd hbm_cmd; uint8_t reserved[3]; struct mei_hbm_dma_mem_dscr dma_dscr[MEI_DMA_DSCR_NUM]; } __attribute__((packed)); /** * struct mei_hbm_dma_setup_res - dma setup response * * @hbm_cmd: bus message command header * @status: 0 on success; otherwise DMA setup failed. * @reserved: reserved for alignment */ struct mei_hbm_dma_setup_res { struct mei_hbm_cmd hbm_cmd; uint8_t status; uint8_t reserved[2]; } __attribute__((packed)); #ifndef IOCTL_MEI_CONNECT_CLIENT_VTAG /* * IOCTL Connect Client Data structure with vtag */ struct mei_connect_client_vtag { uuid_le in_client_uuid; __u8 vtag; __u8 reserved[3]; }; struct mei_connect_client_data_vtag { union { struct mei_connect_client_vtag connect; struct mei_client out_client_properties; }; }; #define IOCTL_MEI_CONNECT_CLIENT_VTAG \ _IOWR('H', 0x04, struct mei_connect_client_data_vtag) #endif /* IOCTL_MEI_CONNECT_CLIENT_VTAG */ #endif /* _MEI_HBM_H_ */
2b13ea0426a899afab458acccc2ab33b566c7711
e1cddfd754d952134e72dfd03522c5ea4fb6008e
/src/vnet/qos/qos_store.c
1e8a53bbdfc23bac6ecdec3fa7932a5794404cc0
[ "Apache-2.0" ]
permissive
FDio/vpp
0ad30fa1bec2975ffa6b66b45c9f4f32163123b6
f234b0d4626d7e686422cc9dfd25958584f4931e
refs/heads/master
2023-08-31T16:09:04.068646
2022-03-14T09:49:15
2023-08-31T09:50:00
96,556,718
1,048
630
Apache-2.0
2023-06-21T05:39:17
2017-07-07T16:29:40
C
UTF-8
C
false
false
7,100
c
qos_store.c
/* * Copyright (c) 2018 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <vnet/qos/qos_store.h> #include <vnet/ip/ip.h> #include <vnet/feature/feature.h> /** * QoS Store configuration */ typedef struct qos_store_t_ { u8 qst_n_cfgs; qos_bits_t qst_value; } qos_store_t; /** * Per-interface, per-protocol vector of feature on/off configurations */ qos_store_t *qos_store_configs[QOS_N_SOURCES]; static void qos_store_feature_config (u32 sw_if_index, qos_source_t input_source, u8 enable, qos_bits_t value) { switch (input_source) { case QOS_SOURCE_IP: vnet_feature_enable_disable ("ip6-unicast", "ip6-qos-store", sw_if_index, enable, &value, sizeof (value)); vnet_feature_enable_disable ("ip6-multicast", "ip6-qos-store", sw_if_index, enable, &value, sizeof (value)); vnet_feature_enable_disable ("ip4-unicast", "ip4-qos-store", sw_if_index, enable, &value, sizeof (value)); vnet_feature_enable_disable ("ip4-multicast", "ip4-qos-store", sw_if_index, enable, &value, sizeof (value)); break; case QOS_SOURCE_MPLS: case QOS_SOURCE_VLAN: case QOS_SOURCE_EXT: /* not a valid option for storing */ break; } } int qos_store_enable (u32 sw_if_index, qos_source_t input_source, qos_bits_t value) { qos_store_t *qst; if (QOS_SOURCE_IP != input_source) return VNET_API_ERROR_UNIMPLEMENTED; vec_validate (qos_store_configs[input_source], sw_if_index); qst = &qos_store_configs[input_source][sw_if_index]; if (0 == qst->qst_n_cfgs) { qst->qst_value = value; qos_store_feature_config (sw_if_index, input_source, 1, value); } qst->qst_n_cfgs++; return (0); } int qos_store_disable (u32 sw_if_index, qos_source_t input_source) { qos_store_t *qst; if (vec_len (qos_store_configs[input_source]) <= sw_if_index) return VNET_API_ERROR_NO_MATCHING_INTERFACE; qst = &qos_store_configs[input_source][sw_if_index]; if (0 == qst->qst_n_cfgs) return VNET_API_ERROR_VALUE_EXIST; qst->qst_n_cfgs--; if (0 == qst->qst_n_cfgs) { qos_store_feature_config (sw_if_index, input_source, 0, qst->qst_value); } return (0); } void qos_store_walk (qos_store_walk_cb_t fn, void *c) { qos_source_t qs; FOR_EACH_QOS_SOURCE (qs) { qos_store_t *qst; u32 sw_if_index; vec_foreach_index (sw_if_index, qos_store_configs[qs]) { qst = &qos_store_configs[qs][sw_if_index]; if (0 != qst->qst_n_cfgs) fn (sw_if_index, qs, qst->qst_value, c); } } } /* * Disable storing feature for all protocols when the interface * is deleted */ static clib_error_t * qos_store_ip_interface_add_del (vnet_main_t * vnm, u32 sw_if_index, u32 is_add) { if (!is_add) { qos_source_t qs; FOR_EACH_QOS_SOURCE (qs) { while (qos_store_disable (sw_if_index, qs) == 0); } } return (NULL); } VNET_SW_INTERFACE_ADD_DEL_FUNCTION (qos_store_ip_interface_add_del); clib_error_t * qos_store_init (vlib_main_t * vm) { return 0; } VLIB_INIT_FUNCTION (qos_store_init); static clib_error_t * qos_store_cli (vlib_main_t * vm, unformat_input_t * input, vlib_cli_command_t * cmd) { vnet_main_t *vnm = vnet_get_main (); u32 sw_if_index, qs, value; u8 enable; qs = 0xff; enable = 1; sw_if_index = ~0; value = ~0; while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT) { if (unformat (input, "%U", unformat_vnet_sw_interface, vnm, &sw_if_index)) ; else if (unformat (input, "%U", unformat_qos_source, &qs)) ; else if (unformat (input, "enable")) enable = 1; else if (unformat (input, "disable")) enable = 0; else if (unformat (input, "value &d", &value)) ; else break; } if (~0 == sw_if_index) return clib_error_return (0, "interface must be specified"); if (~0 == value) return clib_error_return (0, "value to be stored must be specified"); if (0xff == qs) return clib_error_return (0, "input location must be specified"); if (enable) qos_store_enable (sw_if_index, qs, value); else qos_store_disable (sw_if_index, qs); return (NULL); } /*? * Enable QoS bit storing on an interface using the packet's input DSCP bits * Which input QoS bits to use are either; IP, MPLS or VLAN. If more than * one protocol is chosen (which is foolish) the higher layers override the * lower. * * @cliexpar * @cliexcmd{qos store ip GigEthernet0/1/0} ?*/ /* *INDENT-OFF* */ VLIB_CLI_COMMAND (qos_store_command, static) = { .path = "qos store", .short_help = "qos store <store-source> <INTERFACE> [disable]", .function = qos_store_cli, .is_mp_safe = 1, }; /* *INDENT-ON* */ static void qos_store_show_one_interface (vlib_main_t * vm, u32 sw_if_index) { u8 n_cfgs[QOS_N_SOURCES] = { }; qos_source_t qs; bool set; set = false; FOR_EACH_QOS_SOURCE (qs) { if (vec_len (qos_store_configs[qs]) <= sw_if_index) continue; if (0 != (n_cfgs[qs] = qos_store_configs[qs][sw_if_index].qst_n_cfgs)) set = true; } if (set) { vlib_cli_output (vm, " %U:", format_vnet_sw_if_index_name, vnet_get_main (), sw_if_index); FOR_EACH_QOS_SOURCE (qs) { if (n_cfgs[qs] != 0) vlib_cli_output (vm, " %U -> %d", format_qos_source, qs, qos_store_configs[qs][sw_if_index].qst_value); } } } static clib_error_t * qos_store_show (vlib_main_t * vm, unformat_input_t * input, vlib_cli_command_t * cmd) { vnet_main_t *vnm = vnet_get_main (); qos_source_t qs; u32 sw_if_index; sw_if_index = ~0; while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT) { if (unformat (input, "%U", unformat_vnet_sw_interface, vnm, &sw_if_index)) ; } if (~0 == sw_if_index) { u32 ii, n_ints = 0; FOR_EACH_QOS_SOURCE (qs) { n_ints = clib_max (n_ints, vec_len (qos_store_configs[qs])); } for (ii = 0; ii < n_ints; ii++) { qos_store_show_one_interface (vm, ii); } } else qos_store_show_one_interface (vm, sw_if_index); return (NULL); } /*? * Show Egress Qos Maps * * @cliexpar * @cliexcmd{show qos egress map} ?*/ /* *INDENT-OFF* */ VLIB_CLI_COMMAND (qos_store_show_command, static) = { .path = "show qos store", .short_help = "show qos store [interface]", .function = qos_store_show, .is_mp_safe = 1, }; /* *INDENT-ON* */ /* * fd.io coding-style-patch-verification: ON * * Local Variables: * eval: (c-set-style "gnu") * End: */
ec0bbb06976dff4a8d055c65c753632ec322deab
9eedaea06306b20520151321854f989a73c7daf8
/src/video/emscripten/SDL_emscriptenframebuffer.c
b620d554ecc8b3efc82190e91128401b0d674832
[ "Zlib" ]
permissive
libsdl-org/SDL
cf56bdc8a9e198e9735201674118c822d0e3edf3
8387fae698745969ce366c4de9bcc1b4a364a7dd
refs/heads/main
2023-09-04T06:58:34.316952
2023-09-03T15:11:13
2023-09-03T15:11:13
330,008,801
6,912
1,605
Zlib
2023-09-13T19:12:26
2021-01-15T19:55:54
C
UTF-8
C
false
false
5,210
c
SDL_emscriptenframebuffer.c
/* Simple DirectMedia Layer Copyright (C) 1997-2023 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "SDL_internal.h" #ifdef SDL_VIDEO_DRIVER_EMSCRIPTEN #include "SDL_emscriptenvideo.h" #include "SDL_emscriptenframebuffer.h" #include <emscripten/threading.h> int Emscripten_CreateWindowFramebuffer(SDL_VideoDevice *_this, SDL_Window *window, Uint32 *format, void **pixels, int *pitch) { SDL_Surface *surface; const Uint32 surface_format = SDL_PIXELFORMAT_XBGR8888; int w, h; /* Free the old framebuffer surface */ SDL_WindowData *data = window->driverdata; surface = data->surface; SDL_DestroySurface(surface); /* Create a new one */ SDL_GetWindowSizeInPixels(window, &w, &h); surface = SDL_CreateSurface(w, h, surface_format); if (surface == NULL) { return -1; } /* Save the info and return! */ data->surface = surface; *format = surface_format; *pixels = surface->pixels; *pitch = surface->pitch; return 0; } int Emscripten_UpdateWindowFramebuffer(SDL_VideoDevice *_this, SDL_Window *window, const SDL_Rect *rects, int numrects) { SDL_Surface *surface; SDL_WindowData *data = window->driverdata; surface = data->surface; if (surface == NULL) { return SDL_SetError("Couldn't find framebuffer surface for window"); } /* Send the data to the display */ /* *INDENT-OFF* */ /* clang-format off */ MAIN_THREAD_EM_ASM({ var w = $0; var h = $1; var pixels = $2; var canvasId = UTF8ToString($3); var canvas = document.querySelector(canvasId); //TODO: this should store a context per canvas if (!Module['SDL3']) Module['SDL3'] = {}; var SDL3 = Module['SDL3']; if (SDL3.ctxCanvas !== canvas) { SDL3.ctx = Module['createContext'](canvas, false, true); SDL3.ctxCanvas = canvas; } if (SDL3.w !== w || SDL3.h !== h || SDL3.imageCtx !== SDL3.ctx) { SDL3.image = SDL3.ctx.createImageData(w, h); SDL3.w = w; SDL3.h = h; SDL3.imageCtx = SDL3.ctx; } var data = SDL3.image.data; var src = pixels >> 2; var dst = 0; var num; if (SDL3.data32Data !== data) { SDL3.data32 = new Int32Array(data.buffer); SDL3.data8 = new Uint8Array(data.buffer); SDL3.data32Data = data; } var data32 = SDL3.data32; num = data32.length; // logically we need to do // while (dst < num) { // data32[dst++] = HEAP32[src++] | 0xff000000 // } // the following code is faster though, because // .set() is almost free - easily 10x faster due to // native SDL_memcpy efficiencies, and the remaining loop // just stores, not load + store, so it is faster data32.set(HEAP32.subarray(src, src + num)); var data8 = SDL3.data8; var i = 3; var j = i + 4*num; if (num % 8 == 0) { // unrolling gives big speedups while (i < j) { data8[i] = 0xff; i = i + 4 | 0; data8[i] = 0xff; i = i + 4 | 0; data8[i] = 0xff; i = i + 4 | 0; data8[i] = 0xff; i = i + 4 | 0; data8[i] = 0xff; i = i + 4 | 0; data8[i] = 0xff; i = i + 4 | 0; data8[i] = 0xff; i = i + 4 | 0; data8[i] = 0xff; i = i + 4 | 0; } } else { while (i < j) { data8[i] = 0xff; i = i + 4 | 0; } } SDL3.ctx.putImageData(SDL3.image, 0, 0); }, surface->w, surface->h, surface->pixels, data->canvas_id); /* *INDENT-ON* */ /* clang-format on */ if (emscripten_has_asyncify() && SDL_GetHintBoolean(SDL_HINT_EMSCRIPTEN_ASYNCIFY, SDL_TRUE)) { /* give back control to browser for screen refresh */ emscripten_sleep(0); } return 0; } void Emscripten_DestroyWindowFramebuffer(SDL_VideoDevice *_this, SDL_Window *window) { SDL_WindowData *data = window->driverdata; SDL_DestroySurface(data->surface); data->surface = NULL; } #endif /* SDL_VIDEO_DRIVER_EMSCRIPTEN */
a0138792df585ca57ed50b7474bf93a096103e61
e5f4f37d941ceb8145d65f92028cc54658b1ac01
/Code/Engine/Core/CoreInternal.h
ba1c186ff45f1c3e2d16716eb0735e026b4aab00
[ "MIT" ]
permissive
ezEngine/ezEngine
19983d2733a5409fb2665c6c3a0a575dadcefb50
c46e3b4b2cd46798e4abb4938fbca281c054b039
refs/heads/dev
2023-09-06T02:17:28.152665
2023-09-05T18:25:43
2023-09-05T18:25:43
18,179,848
1,050
165
MIT
2023-09-14T21:44:39
2014-03-27T15:02:16
C++
UTF-8
C
false
false
303
h
CoreInternal.h
#pragma once #ifdef BUILDSYSTEM_BUILDING_CORE_LIB # define EZ_CORE_INTERNAL_HEADER_ALLOWED 1 #else # define EZ_CORE_INTERNAL_HEADER_ALLOWED 0 #endif #define EZ_CORE_INTERNAL_HEADER static_assert(EZ_CORE_INTERNAL_HEADER_ALLOWED, "This is an internal ez header. Please do not #include it directly.");
871b7a563764be6d1323efc1fc137661beb92fd3
25c64fb97b7cdb30ec1b6ddd2acf9a755fc33adf
/src/analyze.h
be4393c76e27995db85e722f512cfc5eded877b2
[ "MIT" ]
permissive
arminbiere/kissat
386c1cfadf43562d36fccc47064c95296c9b812f
630d64d4d63c2816fc79a1a0340286b39677e97d
refs/heads/master
2023-09-04T01:39:44.293487
2023-06-24T15:51:43
2023-06-24T15:51:43
267,257,286
350
63
MIT
2022-06-23T12:15:24
2020-05-27T07:57:59
C
UTF-8
C
false
false
233
h
analyze.h
#ifndef _analyze_h_INCLUDED #define _analyze_h_INCLUDED #include <stdbool.h> struct clause; struct kissat; int kissat_analyze (struct kissat *, struct clause *); void kissat_reset_only_analyzed_literals (struct kissat *); #endif
3a1d1ab60cc93a3d134590af05ad7b6aec2e57a9
8149d6751e142ecbc200b43c2da2d5a94c0735df
/modules/vp9/encode.c
979b739c126e588bdee119759df48b202cc1d207
[ "BSD-3-Clause" ]
permissive
baresip/baresip
3c8ebef031f6a01a1462a9f36264197f90ce6ffe
5ace2f75b317bba60d46030ca3fd5e8fa045fecf
refs/heads/main
2023-08-25T12:55:24.860248
2023-08-17T06:56:31
2023-08-17T06:56:31
16,664,594
834
205
BSD-3-Clause
2023-09-14T12:47:57
2014-02-09T10:44:09
C
UTF-8
C
false
false
6,561
c
encode.c
/** * @file vp9/encode.c VP9 Encode * * Copyright (C) 2010 - 2016 Alfred E. Heggestad */ #include <string.h> #include <re.h> #include <rem.h> #include <baresip.h> #include <vpx/vpx_encoder.h> #include <vpx/vp8cx.h> #include "vp9.h" enum { HDR_SIZE = 3, }; struct videnc_state { vpx_codec_ctx_t ctx; struct vidsz size; unsigned fps; unsigned bitrate; unsigned pktsize; bool ctxup; uint16_t picid; videnc_packet_h *pkth; void *arg; unsigned n_frames; unsigned n_key_frames; size_t n_bytes; }; static void destructor(void *arg) { struct videnc_state *ves = arg; if (ves->ctxup) { debug("vp9: encoder stats:" " frames=%u, key_frames=%u, bytes=%zu\n", ves->n_frames, ves->n_key_frames, ves->n_bytes); vpx_codec_destroy(&ves->ctx); } } int vp9_encode_update(struct videnc_state **vesp, const struct vidcodec *vc, struct videnc_param *prm, const char *fmtp, videnc_packet_h *pkth, void *arg) { const struct vp9_vidcodec *vp9 = (struct vp9_vidcodec *)vc; struct videnc_state *ves; uint32_t max_fs; (void)vp9; if (!vesp || !vc || !prm || prm->pktsize < (HDR_SIZE + 1)) return EINVAL; ves = *vesp; if (!ves) { ves = mem_zalloc(sizeof(*ves), destructor); if (!ves) return ENOMEM; ves->picid = rand_u16(); *vesp = ves; } else { if (ves->ctxup && (ves->bitrate != prm->bitrate || ves->fps != prm->fps)) { vpx_codec_destroy(&ves->ctx); ves->ctxup = false; } } ves->bitrate = prm->bitrate; ves->pktsize = prm->pktsize; ves->fps = prm->fps; ves->pkth = pkth; ves->arg = arg; max_fs = vp9_max_fs(fmtp); if (max_fs > 0) prm->max_fs = max_fs * 256; return 0; } static int open_encoder(struct videnc_state *ves, const struct vidsz *size) { vpx_codec_enc_cfg_t cfg; vpx_codec_err_t res; res = vpx_codec_enc_config_default(&vpx_codec_vp9_cx_algo, &cfg, 0); if (res) return EPROTO; /* Profile 0 = 8 bit yuv420p Profile 1 = 8 bit yuv422/440/444p Profile 2 = 10/12 bit yuv420p Profile 3 = 10/12 bit yuv422/440/444p */ cfg.g_profile = 0; cfg.g_w = size->w; cfg.g_h = size->h; cfg.g_timebase.num = 1; cfg.g_timebase.den = ves->fps; cfg.rc_target_bitrate = ves->bitrate / 1000; cfg.g_error_resilient = VPX_ERROR_RESILIENT_DEFAULT; cfg.g_pass = VPX_RC_ONE_PASS; cfg.g_lag_in_frames = 0; cfg.rc_end_usage = VPX_VBR; cfg.kf_mode = VPX_KF_AUTO; if (ves->ctxup) { debug("vp9: re-opening encoder\n"); vpx_codec_destroy(&ves->ctx); ves->ctxup = false; } res = vpx_codec_enc_init(&ves->ctx, &vpx_codec_vp9_cx_algo, &cfg, 0); if (res) { warning("vp9: enc init: %s\n", vpx_codec_err_to_string(res)); return EPROTO; } ves->ctxup = true; res = vpx_codec_control(&ves->ctx, VP8E_SET_CPUUSED, 8); if (res) { warning("vp9: codec ctrl: %s\n", vpx_codec_err_to_string(res)); } #ifdef VP9E_SET_NOISE_SENSITIVITY res = vpx_codec_control(&ves->ctx, VP9E_SET_NOISE_SENSITIVITY, 0); if (res) { warning("vp9: codec ctrl: %s\n", vpx_codec_err_to_string(res)); } #endif info("vp9: encoder opened, picture size %u x %u\n", size->w, size->h); return 0; } static inline void hdr_encode(uint8_t hdr[HDR_SIZE], bool start, bool end, uint16_t picid) { hdr[0] = 1<<7 | start<<3 | end<<2; hdr[1] = 1<<7 | (picid>>8 & 0x7f); hdr[2] = picid & 0xff; } static int send_packet(struct videnc_state *ves, bool marker, const uint8_t *hdr, size_t hdr_len, const uint8_t *pld, size_t pld_len, uint64_t rtp_ts) { ves->n_bytes += (hdr_len + pld_len); return ves->pkth(marker, rtp_ts, hdr, hdr_len, pld, pld_len, ves->arg); } static inline int packetize(struct videnc_state *ves, bool marker, const uint8_t *buf, size_t len, size_t maxlen, uint16_t picid, uint64_t rtp_ts) { uint8_t hdr[HDR_SIZE]; bool start = true; int err = 0; maxlen -= sizeof(hdr); while (len > maxlen) { hdr_encode(hdr, start, false, picid); err |= send_packet(ves, false, hdr, sizeof(hdr), buf, maxlen, rtp_ts); buf += maxlen; len -= maxlen; start = false; } hdr_encode(hdr, start, true, picid); err |= send_packet(ves, marker, hdr, sizeof(hdr), buf, len, rtp_ts); return err; } int vp9_encode(struct videnc_state *ves, bool update, const struct vidframe *frame, uint64_t timestamp) { vpx_enc_frame_flags_t flags = 0; vpx_codec_iter_t iter = NULL; vpx_codec_err_t res; vpx_image_t *img = NULL; vpx_img_fmt_t img_fmt; int err = 0, i; if (!ves || !frame) return EINVAL; switch (frame->fmt) { case VID_FMT_YUV420P: img_fmt = VPX_IMG_FMT_I420; break; default: warning("vp9: pixel format not supported (%s)\n", vidfmt_name(frame->fmt)); return EINVAL; } if (!ves->ctxup || !vidsz_cmp(&ves->size, &frame->size)) { err = open_encoder(ves, &frame->size); if (err) return err; ves->size = frame->size; } ++ves->n_frames; if (update) { /* debug("vp9: picture update\n"); */ flags |= VPX_EFLAG_FORCE_KF; } img = vpx_img_wrap(NULL, img_fmt, frame->size.w, frame->size.h, 16, NULL); if (!img) { warning("vp9: encoder: could not allocate image\n"); err = ENOMEM; goto out; } for (i=0; i<4; i++) { img->stride[i] = frame->linesize[i]; img->planes[i] = frame->data[i]; } res = vpx_codec_encode(&ves->ctx, img, timestamp, 1, flags, VPX_DL_REALTIME); if (res) { warning("vp9: enc error: %s\n", vpx_codec_err_to_string(res)); err = ENOMEM; goto out; } ++ves->picid; for (;;) { bool marker = true; const vpx_codec_cx_pkt_t *pkt; uint64_t ts; pkt = vpx_codec_get_cx_data(&ves->ctx, &iter); if (!pkt) break; if (pkt->kind != VPX_CODEC_CX_FRAME_PKT) { continue; } if (pkt->data.frame.flags & VPX_FRAME_IS_KEY) { ++ves->n_key_frames; } if (pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT) marker = false; ts = video_calc_rtp_timestamp_fix(pkt->data.frame.pts); err = packetize(ves, marker, pkt->data.frame.buf, pkt->data.frame.sz, ves->pktsize, ves->picid, ts); if (err) return err; } out: if (img) vpx_img_free(img); return err; } int vp9_encode_packetize(struct videnc_state *ves, const struct vidpacket *pkt) { uint64_t rtp_ts; int err; if (!ves || !pkt) return EINVAL; ++ves->picid; rtp_ts = video_calc_rtp_timestamp_fix(pkt->timestamp); err = packetize(ves, true, pkt->buf, pkt->size, ves->pktsize, ves->picid, rtp_ts); if (err) return err; return 0; }
db0a43239f56a99bbe18a2362f22f9d94181b720
ecce427678ecff2a93a47f3b1b664202c7d27617
/levels/bitfs/areas/1/5/model.inc.c
f9d76e7b551e1efe4d9303ea7057bfee3cb69a88
[]
no_license
sm64pc/sm64ex
ecf37f31b3f7426c4874254660d856030d789714
54cd27ccee45a2403b45f07a00d6043c51149969
refs/heads/nightly
2023-08-11T12:14:34.424168
2023-07-01T11:45:50
2023-07-01T11:45:50
262,091,731
795
238
null
2023-07-01T11:45:51
2020-05-07T15:43:27
C
UTF-8
C
false
false
5,893
c
model.inc.c
// 0x07003CF8 - 0x07003DF8 static const Vtx bitfs_seg7_vertex_07003CF8[] = { {{{ 2560, 0, 1147}, 0, { 9352, 990}, {0x44, 0x44, 0x44, 0xff}}}, {{{ -4, 0, -5}, 0, { 4698, 222}, {0x44, 0x44, 0x44, 0xff}}}, {{{ 2560, 0, -1163}, 0, { 9352, -514}, {0x44, 0x44, 0x44, 0xff}}}, {{{ -2610, 0, 1147}, 0, { 0, 990}, {0x44, 0x44, 0x44, 0xff}}}, {{{ -2610, 0, -1163}, 0, { 0, -548}, {0x44, 0x44, 0x44, 0xff}}}, {{{ -2610, 256, 1147}, 0, { 0, 478}, {0xff, 0xff, 0xff, 0xff}}}, {{{ 2560, 256, 1147}, 0, { 10290, 478}, {0xff, 0xff, 0xff, 0xff}}}, {{{ 2560, 256, 1096}, 0, { 10290, 478}, {0xff, 0xff, 0xff, 0xff}}}, {{{ -2585, 256, 1121}, 0, { 20, 478}, {0xff, 0xff, 0xff, 0xff}}}, {{{ -2610, 256, 1147}, 0, { 326, 478}, {0xff, 0xff, 0xff, 0xff}}}, {{{ -2585, 256, -1137}, 0, { 4886, 478}, {0xff, 0xff, 0xff, 0xff}}}, {{{ -2610, 256, -1163}, 0, { 4938, 478}, {0xff, 0xff, 0xff, 0xff}}}, {{{ -2585, 256, 1121}, 0, { 376, 478}, {0xff, 0xff, 0xff, 0xff}}}, {{{ 2560, 256, -1163}, 0, { 10290, 478}, {0xff, 0xff, 0xff, 0xff}}}, {{{ -2585, 256, -1137}, 0, { 20, 478}, {0xff, 0xff, 0xff, 0xff}}}, {{{ 2560, 256, -1112}, 0, { 10290, 478}, {0xff, 0xff, 0xff, 0xff}}}, }; // 0x07003DF8 - 0x07003ED8 static const Vtx bitfs_seg7_vertex_07003DF8[] = { {{{ 2560, 256, -1163}, 0, { 10290, 478}, {0xff, 0xff, 0xff, 0xff}}}, {{{ -2610, 256, -1163}, 0, { 0, 478}, {0xff, 0xff, 0xff, 0xff}}}, {{{ -2585, 256, -1137}, 0, { 20, 478}, {0xff, 0xff, 0xff, 0xff}}}, {{{ -2610, 0, 1147}, 0, { 326, 990}, {0x64, 0x64, 0x64, 0xff}}}, {{{ -2610, 256, 1147}, 0, { 326, 478}, {0x64, 0x64, 0x64, 0xff}}}, {{{ -2610, 256, -1163}, 0, { 4938, 478}, {0x64, 0x64, 0x64, 0xff}}}, {{{ -2610, 0, -1163}, 0, { 4938, 990}, {0x64, 0x64, 0x64, 0xff}}}, {{{ -2585, 256, 1121}, 0, { 376, 478}, {0x64, 0x64, 0x64, 0xff}}}, {{{ -2533, 205, -1086}, 0, { 4784, 582}, {0x64, 0x64, 0x64, 0xff}}}, {{{ -2585, 256, -1137}, 0, { 4886, 478}, {0x64, 0x64, 0x64, 0xff}}}, {{{ -2533, 205, 1070}, 0, { 480, 582}, {0x64, 0x64, 0x64, 0xff}}}, {{{ -2610, 256, -1163}, 0, { 0, 478}, {0x8c, 0x8c, 0x8c, 0xff}}}, {{{ 2560, 256, -1163}, 0, { 10290, 478}, {0x8c, 0x8c, 0x8c, 0xff}}}, {{{ -2610, 0, -1163}, 0, { 0, 990}, {0x8c, 0x8c, 0x8c, 0xff}}}, }; // 0x07003ED8 - 0x07003FC8 static const Vtx bitfs_seg7_vertex_07003ED8[] = { {{{ -2585, 256, 1121}, 0, { 20, 478}, {0x8c, 0x8c, 0x8c, 0xff}}}, {{{ 2560, 205, 1044}, 0, { 10290, 582}, {0x8c, 0x8c, 0x8c, 0xff}}}, {{{ -2533, 205, 1070}, 0, { 122, 582}, {0x8c, 0x8c, 0x8c, 0xff}}}, {{{ 2560, 256, 1096}, 0, { 10290, 478}, {0x8c, 0x8c, 0x8c, 0xff}}}, {{{ -2610, 0, 1147}, 0, { 0, 990}, {0x8c, 0x8c, 0x8c, 0xff}}}, {{{ 2560, 256, 1147}, 0, { 10290, 478}, {0x8c, 0x8c, 0x8c, 0xff}}}, {{{ -2610, 256, 1147}, 0, { 0, 478}, {0x8c, 0x8c, 0x8c, 0xff}}}, {{{ 2560, 0, 1147}, 0, { 10290, 990}, {0x8c, 0x8c, 0x8c, 0xff}}}, {{{ -2533, 205, -1086}, 0, { 122, 582}, {0x8c, 0x8c, 0x8c, 0xff}}}, {{{ 2560, 256, -1112}, 0, { 10290, 478}, {0x8c, 0x8c, 0x8c, 0xff}}}, {{{ -2585, 256, -1137}, 0, { 20, 478}, {0x8c, 0x8c, 0x8c, 0xff}}}, {{{ 2560, 205, -1060}, 0, { 10290, 582}, {0x8c, 0x8c, 0x8c, 0xff}}}, {{{ 2560, 256, -1163}, 0, { 10290, 478}, {0x8c, 0x8c, 0x8c, 0xff}}}, {{{ 2560, 0, -1163}, 0, { 10290, 990}, {0x8c, 0x8c, 0x8c, 0xff}}}, {{{ -2610, 0, -1163}, 0, { 0, 990}, {0x8c, 0x8c, 0x8c, 0xff}}}, }; // 0x07003FC8 - 0x070040B0 static const Gfx bitfs_seg7_dl_07003FC8[] = { gsDPSetTextureImage(G_IM_FMT_RGBA, G_IM_SIZ_16b, 1, sky_09001000), gsDPLoadSync(), gsDPLoadBlock(G_TX_LOADTILE, 0, 0, 32 * 32 - 1, CALC_DXT(32, G_IM_SIZ_16b_BYTES)), gsSPVertex(bitfs_seg7_vertex_07003CF8, 16, 0), gsSP2Triangles( 0, 1, 2, 0x0, 1, 0, 3, 0x0), gsSP2Triangles( 2, 1, 4, 0x0, 4, 1, 3, 0x0), gsSP2Triangles( 5, 6, 7, 0x0, 5, 7, 8, 0x0), gsSP2Triangles( 9, 10, 11, 0x0, 9, 12, 10, 0x0), gsSP1Triangle(13, 14, 15, 0x0), gsSPVertex(bitfs_seg7_vertex_07003DF8, 14, 0), gsSP2Triangles( 0, 1, 2, 0x0, 3, 4, 5, 0x0), gsSP2Triangles( 3, 5, 6, 0x0, 7, 8, 9, 0x0), gsSP2Triangles( 7, 10, 8, 0x0, 11, 12, 13, 0x0), gsSPVertex(bitfs_seg7_vertex_07003ED8, 15, 0), gsSP2Triangles( 0, 1, 2, 0x0, 0, 3, 1, 0x0), gsSP2Triangles( 4, 5, 6, 0x0, 4, 7, 5, 0x0), gsSP2Triangles( 8, 9, 10, 0x0, 8, 11, 9, 0x0), gsSP1Triangle(12, 13, 14, 0x0), gsSPEndDisplayList(), }; // 0x070040B0 - 0x07004120 const Gfx bitfs_seg7_dl_070040B0[] = { gsDPPipeSync(), gsDPSetCombineMode(G_CC_MODULATERGB, G_CC_MODULATERGB), gsSPClearGeometryMode(G_LIGHTING | G_CULL_BACK), gsDPSetTile(G_IM_FMT_RGBA, G_IM_SIZ_16b, 0, 0, G_TX_LOADTILE, 0, G_TX_WRAP | G_TX_NOMIRROR, G_TX_NOMASK, G_TX_NOLOD, G_TX_WRAP | G_TX_NOMIRROR, G_TX_NOMASK, G_TX_NOLOD), gsSPTexture(0xFFFF, 0xFFFF, 0, G_TX_RENDERTILE, G_ON), gsDPTileSync(), gsDPSetTile(G_IM_FMT_RGBA, G_IM_SIZ_16b, 8, 0, G_TX_RENDERTILE, 0, G_TX_WRAP | G_TX_NOMIRROR, 5, G_TX_NOLOD, G_TX_WRAP | G_TX_NOMIRROR, 5, G_TX_NOLOD), gsDPSetTileSize(0, 0, 0, (32 - 1) << G_TEXTURE_IMAGE_FRAC, (32 - 1) << G_TEXTURE_IMAGE_FRAC), gsSPDisplayList(bitfs_seg7_dl_07003FC8), gsSPTexture(0xFFFF, 0xFFFF, 0, G_TX_RENDERTILE, G_OFF), gsDPPipeSync(), gsDPSetCombineMode(G_CC_SHADE, G_CC_SHADE), gsSPSetGeometryMode(G_LIGHTING | G_CULL_BACK), gsSPEndDisplayList(), };
d2006aad8cf412d5d7077c279f3c09600715f54d
69db0de8c61c7cba691193edd3f087fdb54351c2
/src/field_effect.c
84a4cff88587e12afa08c6919eb88f37587a31c5
[]
no_license
pret/pokefirered
5363c332321c7650d4c85be6aa2e8baf3acda162
f8741615bfa0123e38680f30103f217c269ec96a
refs/heads/master
2023-08-31T15:22:19.498797
2023-08-31T15:15:29
2023-08-31T15:15:29
115,841,713
847
709
null
2023-09-12T22:48:38
2017-12-31T04:07:51
C
UTF-8
C
false
false
125,892
c
field_effect.c
#include "global.h" #include "gflib.h" #include "decompress.h" #include "event_data.h" #include "event_object_movement.h" #include "field_camera.h" #include "field_control_avatar.h" #include "field_effect.h" #include "field_effect_helpers.h" #include "field_effect_scripts.h" #include "field_fadetransition.h" #include "field_player_avatar.h" #include "field_weather.h" #include "fieldmap.h" #include "help_system.h" #include "metatile_behavior.h" #include "new_menu_helpers.h" #include "overworld.h" #include "party_menu.h" #include "quest_log.h" #include "script.h" #include "special_field_anim.h" #include "task.h" #include "trainer_pokemon_sprites.h" #include "trig.h" #include "util.h" #include "constants/event_object_movement.h" #include "constants/metatile_behaviors.h" #include "constants/songs.h" #include "constants/sound.h" extern struct CompressedSpritePalette gMonPaletteTable[]; // Intentionally declared (incorrectly) without const in order to match extern const struct CompressedSpritePalette gTrainerFrontPicPaletteTable[]; extern const struct CompressedSpriteSheet gTrainerFrontPicTable[]; #define subsprite_table(ptr) {.subsprites = ptr, .subspriteCount = (sizeof ptr) / (sizeof(struct Subsprite))} #define FIELD_EFFECT_COUNT 32 EWRAM_DATA u32 gFieldEffectArguments[8] = {0}; static u8 sFieldEffectActiveList[FIELD_EFFECT_COUNT]; static void FieldEffectActiveListAdd(u8 fldeff); static bool8 FieldEffectCmd_loadtiles(const u8 **script, u32 *result); static bool8 FieldEffectCmd_loadfadedpal(const u8 **script, u32 *result); static bool8 FieldEffectCmd_loadpal(const u8 **script, u32 *result); static bool8 FieldEffectCmd_callnative(const u8 **script, u32 *result); static bool8 FieldEffectCmd_end(const u8 **script, u32 *result); static bool8 FieldEffectCmd_loadgfx_callnative(const u8 **script, u32 *result); static bool8 FieldEffectCmd_loadtiles_callnative(const u8 **script, u32 *result); static bool8 FieldEffectCmd_loadfadedpal_callnative(const u8 **script, u32 *result); static void FieldEffectScript_LoadTiles(const u8 **script); static void FieldEffectScript_LoadFadedPal(const u8 **script); static void FieldEffectScript_LoadPal(const u8 **script); static void FieldEffectScript_CallNative(const u8 **script, u32 *result); static void FieldEffectFreeTilesIfUnused(u16 tilesTag); static void FieldEffectFreePaletteIfUnused(u8 paletteNum); static void Task_PokecenterHeal(u8 taskId); static void SpriteCB_PokeballGlow(struct Sprite *sprite); static void SpriteCB_PokecenterMonitor(struct Sprite *sprite); static void SpriteCB_HallOfFameMonitor(struct Sprite *sprite); // Unused static const u16 sNewGameOakObject_Gfx[] = INCBIN_U16("graphics/field_effects/pics/new_game_oak.4bpp"); static const u16 sNewGameOakObject_Pal[] = INCBIN_U16("graphics/field_effects/pics/new_game_oak.gbapal"); static const u16 sPokeballGlow_Gfx[] = INCBIN_U16("graphics/field_effects/pics/pokeball_glow.4bpp"); static const u16 sPokeballGlow_Pal[] = INCBIN_U16("graphics/field_effects/pics/pokeball_glow.gbapal"); static const u16 sPokecenterMonitor_Gfx[] = INCBIN_U16("graphics/field_effects/pics/pokemoncenter_monitor.4bpp"); static const u16 sHofMonitor_Pal[] = INCBIN_U16("graphics/field_effects/pics/hof_monitor.gbapal"); static const u16 sHofMonitor_Gfx[] = INCBIN_U16("graphics/field_effects/pics/hof_monitor.4bpp"); static const u16 sFieldMoveStreaksOutdoors_Gfx[] = INCBIN_U16("graphics/field_effects/pics/field_move_streaks_outdoors.4bpp"); static const u16 sFieldMoveStreaksOutdoors_Pal[] = INCBIN_U16("graphics/field_effects/pics/field_move_streaks_outdoors.gbapal"); static const u16 sFieldMoveStreaksOutdoors_Tilemap[] = INCBIN_U16("graphics/field_effects/pics/field_move_streaks_outdoors.bin"); static const u16 sFieldMoveStreaksIndoors_Gfx[] = INCBIN_U16("graphics/field_effects/pics/field_move_streaks_indoors.4bpp"); static const u16 sFieldMoveStreaksIndoors_Pal[] = INCBIN_U16("graphics/field_effects/pics/field_move_streaks_indoors.gbapal"); static const u16 sFieldMoveStreaksIndoors_Tilemap[] = INCBIN_U16("graphics/field_effects/pics/field_move_streaks_indoors.bin"); static const u16 sRockFragment_TopLeft[] = INCBIN_U16("graphics/field_effects/pics/deoxys_rock_fragment_top_left.4bpp"); static const u16 sRockFragment_TopRight[] = INCBIN_U16("graphics/field_effects/pics/deoxys_rock_fragment_top_right.4bpp"); static const u16 sRockFragment_BottomLeft[] = INCBIN_U16("graphics/field_effects/pics/deoxys_rock_fragment_bottom_left.4bpp"); static const u16 sRockFragment_BottomRight[] = INCBIN_U16("graphics/field_effects/pics/deoxys_rock_fragment_bottom_right.4bpp"); static bool8 (*const sFldEffScrcmdTable[])(const u8 **script, u32 *result) = { FieldEffectCmd_loadtiles, FieldEffectCmd_loadfadedpal, FieldEffectCmd_loadpal, FieldEffectCmd_callnative, FieldEffectCmd_end, FieldEffectCmd_loadgfx_callnative, FieldEffectCmd_loadtiles_callnative, FieldEffectCmd_loadfadedpal_callnative }; static const struct OamData sNewGameOakOamAttributes = { .y = 0, .affineMode = ST_OAM_AFFINE_OFF, .objMode = ST_OAM_OBJ_NORMAL, .mosaic = FALSE, .bpp = ST_OAM_4BPP, .shape = SPRITE_SHAPE(64x64), .x = 0, .matrixNum = 0, .size = SPRITE_SIZE(64x64), .tileNum = 0x000, .priority = 0, .paletteNum = 0, .affineParam = 0 }; static const struct OamData sOamData_8x8 = { .y = 0, .affineMode = ST_OAM_AFFINE_OFF, .objMode = ST_OAM_OBJ_NORMAL, .mosaic = FALSE, .bpp = ST_OAM_4BPP, .shape = SPRITE_SHAPE(8x8), .x = 0, .matrixNum = 0, .size = SPRITE_SIZE(8x8), .tileNum = 0x000, .priority = 0, .paletteNum = 0, .affineParam = 0 }; static const struct OamData sOamData_16x16 = { .y = 0, .affineMode = ST_OAM_AFFINE_OFF, .objMode = ST_OAM_OBJ_NORMAL, .mosaic = FALSE, .bpp = ST_OAM_4BPP, .shape = SPRITE_SHAPE(16x16), .x = 0, .matrixNum = 0, .size = SPRITE_SIZE(16x16), .tileNum = 0x000, .priority = 0, .paletteNum = 0, .affineParam = 0 }; static const struct SpriteFrameImage sNewGameOakObjectSpriteFrames[] = { {sNewGameOakObject_Gfx, 0x800} }; static const struct SpritePalette sNewGameOakObjectPaletteInfo = { sNewGameOakObject_Pal, 4102 }; static const union AnimCmd sNewGameOakAnim[] = { ANIMCMD_FRAME(0, 1), ANIMCMD_END }; static const union AnimCmd *const sNewGameOakAnimTable[] = { sNewGameOakAnim }; static const struct SpriteTemplate sNewGameOakObjectTemplate = { .tileTag = TAG_NONE, .paletteTag = 0x1006, .oam = &sNewGameOakOamAttributes, .anims = sNewGameOakAnimTable, .images = sNewGameOakObjectSpriteFrames, .affineAnims = gDummySpriteAffineAnimTable, .callback = SpriteCallbackDummy }; const struct SpritePalette gSpritePalette_PokeballGlow = { sPokeballGlow_Pal, 4103 }; const struct SpritePalette gSpritePalette_HofMonitor = { sHofMonitor_Pal, 4112 }; static const struct OamData sOamData_32x16 = { .y = 0, .affineMode = ST_OAM_AFFINE_OFF, .objMode = ST_OAM_OBJ_NORMAL, .mosaic = FALSE, .bpp = ST_OAM_4BPP, .shape = SPRITE_SHAPE(32x16), .x = 0, .matrixNum = 0, .size = SPRITE_SIZE(32x16), .tileNum = 0x000, .priority = 0, .paletteNum = 0, .affineParam = 0 }; static const struct SpriteFrameImage sPicTable_PokeballGlow[] = { {sPokeballGlow_Gfx, 0x20} }; static const struct SpriteFrameImage sPicTable_PokecenterMonitor[] = { {sPokecenterMonitor_Gfx + 0x000, 0x100}, {sPokecenterMonitor_Gfx + 0x080, 0x100}, {sPokecenterMonitor_Gfx + 0x100, 0x100}, {sPokecenterMonitor_Gfx + 0x180, 0x100} }; static const struct SpriteFrameImage sPicTable_HofMonitor[] = { {sHofMonitor_Gfx + 0x00, 0x80}, {sHofMonitor_Gfx + 0x40, 0x80}, {sHofMonitor_Gfx + 0x80, 0x80}, {sHofMonitor_Gfx + 0xC0, 0x80} }; // Unused, leftover from RSE static const struct Subsprite sSubsprites_PokecenterMonitor[] = { { .x = -12, .y = -8, .shape = SPRITE_SHAPE(16x8), .size = SPRITE_SIZE(16x8), .tileOffset = 0, .priority = 2 }, { .x = 4, .y = -8, .shape = SPRITE_SHAPE(8x8), .size = SPRITE_SIZE(8x8), .tileOffset = 2, .priority = 2 }, { .x = -12, .y = 0, .shape = SPRITE_SHAPE(16x8), .size = SPRITE_SIZE(16x8), .tileOffset = 3, .priority = 2 }, { .x = 4, .y = 0, .shape = SPRITE_SHAPE(8x8), .size = SPRITE_SIZE(8x8), .tileOffset = 5, .priority = 2 } }; // Unused, leftover from RSE static const struct SubspriteTable sSubspriteTable_PokecenterMonitor = subsprite_table(sSubsprites_PokecenterMonitor); // Unused, leftover from RSE static const struct Subsprite sSubsprites_HofMonitorBig[] = { { .x = -32, .y = -8, .shape = SPRITE_SHAPE(32x8), .size = SPRITE_SIZE(32x8), .tileOffset = 0, .priority = 2 }, { .x = 0, .y = -8, .shape = SPRITE_SHAPE(32x8), .size = SPRITE_SIZE(32x8), .tileOffset = 4, .priority = 2 }, { .x = -32, .y = 0, .shape = SPRITE_SHAPE(32x8), .size = SPRITE_SIZE(32x8), .tileOffset = 8, .priority = 2 }, { .x = 0, .y = 0, .shape = SPRITE_SHAPE(32x8), .size = SPRITE_SIZE(32x8), .tileOffset = 12, .priority = 2 } }; // Unused, leftover from RSE static const struct SubspriteTable sSubspriteTable_HofMonitorBig = subsprite_table(sSubsprites_HofMonitorBig); static const union AnimCmd sAnim_Static[] = { ANIMCMD_FRAME(0, 1), ANIMCMD_JUMP(0) }; static const union AnimCmd sAnim_Flicker[] = { ANIMCMD_FRAME(1, 5), ANIMCMD_FRAME(2, 5), ANIMCMD_FRAME(3, 7), ANIMCMD_FRAME(2, 5), ANIMCMD_FRAME(1, 5), ANIMCMD_FRAME(0, 5), ANIMCMD_LOOP(3), ANIMCMD_END }; static const union AnimCmd *const sAnims_Flicker[] = { sAnim_Static, sAnim_Flicker }; static const union AnimCmd sAnim_HofMonitor[] = { ANIMCMD_FRAME(3, 8), ANIMCMD_FRAME(2, 8), ANIMCMD_FRAME(1, 8), ANIMCMD_FRAME(0, 8), ANIMCMD_FRAME(1, 8), ANIMCMD_FRAME(2, 8), ANIMCMD_LOOP(2), ANIMCMD_FRAME(1, 8), ANIMCMD_FRAME(0, 8), ANIMCMD_END }; static const union AnimCmd *const sAnims_HofMonitor[] = { sAnim_HofMonitor }; static const struct SpriteTemplate sSpriteTemplate_PokeballGlow = { .tileTag = TAG_NONE, .paletteTag = 4103, .oam = &sOamData_8x8, .anims = sAnims_Flicker, .images = sPicTable_PokeballGlow, .affineAnims = gDummySpriteAffineAnimTable, .callback = SpriteCB_PokeballGlow }; static const struct SpriteTemplate sSpriteTemplate_PokecenterMonitor = { .tileTag = TAG_NONE, .paletteTag = 4103, .oam = &sOamData_32x16, .anims = sAnims_Flicker, .images = sPicTable_PokecenterMonitor, .affineAnims = gDummySpriteAffineAnimTable, .callback = SpriteCB_PokecenterMonitor }; static const struct SpriteTemplate sSpriteTemplate_HofMonitor = { .tileTag = TAG_NONE, .paletteTag = 4112, .oam = &sOamData_16x16, .anims = sAnims_HofMonitor, .images = sPicTable_HofMonitor, .affineAnims = gDummySpriteAffineAnimTable, .callback = SpriteCB_HallOfFameMonitor }; u32 FieldEffectStart(u8 fldeff) { const u8 *script; u32 result; FieldEffectActiveListAdd(fldeff); script = gFieldEffectScriptPointers[fldeff]; while (sFldEffScrcmdTable[*script](&script, &result)) ; return result; } static bool8 FieldEffectCmd_loadtiles(const u8 **script, u32 *result) { (*script)++; FieldEffectScript_LoadTiles(script); return TRUE; } static bool8 FieldEffectCmd_loadfadedpal(const u8 **script, u32 *result) { (*script)++; FieldEffectScript_LoadFadedPal(script); return TRUE; } static bool8 FieldEffectCmd_loadpal(const u8 **script, u32 *result) { (*script)++; FieldEffectScript_LoadPal(script); return TRUE; } static bool8 FieldEffectCmd_callnative(const u8 **script, u32 *result) { (*script)++; FieldEffectScript_CallNative(script, result); return TRUE; } static bool8 FieldEffectCmd_end(const u8 **script, u32 *result) { return FALSE; } static bool8 FieldEffectCmd_loadgfx_callnative(const u8 **script, u32 *result) { (*script)++; FieldEffectScript_LoadTiles(script); FieldEffectScript_LoadFadedPal(script); FieldEffectScript_CallNative(script, result); return TRUE; } static bool8 FieldEffectCmd_loadtiles_callnative(const u8 **script, u32 *result) { (*script)++; FieldEffectScript_LoadTiles(script); FieldEffectScript_CallNative(script, result); return TRUE; } static bool8 FieldEffectCmd_loadfadedpal_callnative(const u8 **script, u32 *result) { (*script)++; FieldEffectScript_LoadFadedPal(script); FieldEffectScript_CallNative(script, result); return TRUE; } static u32 FieldEffectScript_ReadWord(const u8 **script) { return T2_READ_32(*script); } static void FieldEffectScript_LoadTiles(const u8 **script) { const struct SpriteSheet * spriteSheet = (const struct SpriteSheet * )FieldEffectScript_ReadWord(script); if (GetSpriteTileStartByTag(spriteSheet->tag) == 0xFFFF) LoadSpriteSheet(spriteSheet); *script += sizeof(u32); } void ApplyGlobalFieldPaletteTint(u8 paletteIdx) { switch (gGlobalFieldTintMode) { case 0: return; case 1: TintPalette_GrayScale(&gPlttBufferUnfaded[OBJ_PLTT_ID2(paletteIdx)], 16); break; case 2: TintPalette_SepiaTone(&gPlttBufferUnfaded[OBJ_PLTT_ID2(paletteIdx)], 16); break; case 3: QuestLog_BackUpPalette(OBJ_PLTT_ID2(paletteIdx), 16); TintPalette_GrayScale(&gPlttBufferUnfaded[OBJ_PLTT_ID2(paletteIdx)], 16); break; default: return; } CpuFastCopy(&gPlttBufferUnfaded[OBJ_PLTT_ID2(paletteIdx)], &gPlttBufferFaded[OBJ_PLTT_ID2(paletteIdx)], PLTT_SIZE_4BPP); } static void FieldEffectScript_LoadFadedPal(const u8 **script) { const struct SpritePalette * spritePalette = (const struct SpritePalette * )FieldEffectScript_ReadWord(script); u8 idx = IndexOfSpritePaletteTag(spritePalette->tag); LoadSpritePalette(spritePalette); if (idx == 0xFF) ApplyGlobalFieldPaletteTint(IndexOfSpritePaletteTag(spritePalette->tag)); UpdateSpritePaletteWithWeather(IndexOfSpritePaletteTag(spritePalette->tag)); *script += sizeof(u32); } static void FieldEffectScript_LoadPal(const u8 **script) { const struct SpritePalette * spritePalette = (const struct SpritePalette * )FieldEffectScript_ReadWord(script); u8 idx = IndexOfSpritePaletteTag(spritePalette->tag); LoadSpritePalette(spritePalette); if (idx != 0xFF) ApplyGlobalFieldPaletteTint(IndexOfSpritePaletteTag(spritePalette->tag)); *script += sizeof(u32); } static void FieldEffectScript_CallNative(const u8 **script, u32 *result) { u32 (*func)(void) = (u32 (*)(void))FieldEffectScript_ReadWord(script); *result = func(); *script += sizeof(u32); } static void FieldEffectFreeGraphicsResources(struct Sprite *sprite) { u16 tileStart = sprite->sheetTileStart; u8 paletteNum = sprite->oam.paletteNum; DestroySprite(sprite); FieldEffectFreeTilesIfUnused(tileStart); FieldEffectFreePaletteIfUnused(paletteNum); } void FieldEffectStop(struct Sprite *sprite, u8 fldeff) { FieldEffectFreeGraphicsResources(sprite); FieldEffectActiveListRemove(fldeff); } static void FieldEffectFreeTilesIfUnused(u16 tileStart) { u8 i; u16 tileTag = GetSpriteTileTagByTileStart(tileStart); if (tileTag == TAG_NONE) return; for (i = 0; i < MAX_SPRITES; i++) { if (gSprites[i].inUse && gSprites[i].usingSheet && tileStart == gSprites[i].sheetTileStart) return; } FreeSpriteTilesByTag(tileTag); } static void FieldEffectFreePaletteIfUnused(u8 paletteNum) { u8 i; u16 paletteTag = GetSpritePaletteTagByPaletteNum(paletteNum); if (paletteTag == TAG_NONE) return; for (i = 0; i < MAX_SPRITES; i++) { if (gSprites[i].inUse && gSprites[i].oam.paletteNum == paletteNum) return; } FreeSpritePaletteByTag(paletteTag); } void FieldEffectActiveListClear(void) { u8 i; for (i = 0; i < FIELD_EFFECT_COUNT; i++) { sFieldEffectActiveList[i] = 0xFF; } } static void FieldEffectActiveListAdd(u8 fldeff) { u8 i; for (i = 0; i < FIELD_EFFECT_COUNT; i++) { if (sFieldEffectActiveList[i] == 0xFF) { sFieldEffectActiveList[i] = fldeff; return; } } } void FieldEffectActiveListRemove(u8 fldeff) { u8 i; for (i = 0; i < FIELD_EFFECT_COUNT; i++) { if (sFieldEffectActiveList[i] == fldeff) { sFieldEffectActiveList[i] = 0xFF; return; } } } bool8 FieldEffectActiveListContains(u8 fldeff) { u8 i; for (i = 0; i < FIELD_EFFECT_COUNT; i++) { if (sFieldEffectActiveList[i] == fldeff) { return TRUE; } } return FALSE; } u8 CreateTrainerSprite(u8 trainerSpriteID, s16 x, s16 y, u8 subpriority, u8 *buffer) { struct SpriteTemplate spriteTemplate; LoadCompressedSpritePaletteOverrideBuffer(&gTrainerFrontPicPaletteTable[trainerSpriteID], buffer); LoadCompressedSpriteSheetOverrideBuffer(&gTrainerFrontPicTable[trainerSpriteID], buffer); spriteTemplate.tileTag = gTrainerFrontPicTable[trainerSpriteID].tag; spriteTemplate.paletteTag = gTrainerFrontPicPaletteTable[trainerSpriteID].tag; spriteTemplate.oam = &sNewGameOakOamAttributes; spriteTemplate.anims = gDummySpriteAnimTable; spriteTemplate.images = NULL; spriteTemplate.affineAnims = gDummySpriteAffineAnimTable; spriteTemplate.callback = SpriteCallbackDummy; return CreateSprite(&spriteTemplate, x, y, subpriority); } // Unused static void LoadTrainerGfx_TrainerCard(u8 gender, u16 palOffset, u8 *dest) { LZDecompressVram(gTrainerFrontPicTable[gender].data, dest); LoadCompressedPalette(gTrainerFrontPicPaletteTable[gender].data, palOffset, PLTT_SIZE_4BPP); } // Unused static u8 AddNewGameBirchObject(s16 x, s16 y, u8 subpriority) { LoadSpritePalette(&sNewGameOakObjectPaletteInfo); return CreateSprite(&sNewGameOakObjectTemplate, x, y, subpriority); } u8 CreateMonSprite_PicBox(u16 species, s16 x, s16 y, u8 subpriority) { u16 spriteId = CreateMonPicSprite_HandleDeoxys(species, 0, 0x8000, TRUE, x, y, 0, gMonPaletteTable[species].tag); PreservePaletteInWeather(IndexOfSpritePaletteTag(gMonPaletteTable[species].tag) + 0x10); if (spriteId == 0xFFFF) return MAX_SPRITES; else return spriteId; } static u8 CreateMonSprite_FieldMove(u16 species, u32 otId, u32 personality, s16 x, s16 y, u8 subpriority) { const struct CompressedSpritePalette * spritePalette = GetMonSpritePalStructFromOtIdPersonality(species, otId, personality); u16 spriteId = CreateMonPicSprite_HandleDeoxys(species, otId, personality, 1, x, y, 0, spritePalette->tag); PreservePaletteInWeather(IndexOfSpritePaletteTag(spritePalette->tag) + 0x10); if (spriteId == 0xFFFF) return MAX_SPRITES; else return spriteId; } void FreeResourcesAndDestroySprite(struct Sprite *sprite, u8 spriteId) { ResetPreservedPalettesInWeather(); if (sprite->oam.affineMode != ST_OAM_AFFINE_OFF) { FreeOamMatrix(sprite->oam.matrixNum); } FreeAndDestroyMonPicSprite(spriteId); } // r, g, b are between 0 and 16 void MultiplyInvertedPaletteRGBComponents(u16 i, u8 r, u8 g, u8 b) { int curRed; int curGreen; int curBlue; u16 outPal; outPal = gPlttBufferUnfaded[i]; curRed = outPal & 0x1f; curGreen = (outPal & (0x1f << 5)) >> 5; curBlue = (outPal & (0x1f << 10)) >> 10; curRed += (((0x1f - curRed) * r) >> 4); curGreen += (((0x1f - curGreen) * g) >> 4); curBlue += (((0x1f - curBlue) * b) >> 4); outPal = curRed; outPal |= curGreen << 5; outPal |= curBlue << 10; gPlttBufferFaded[i] = outPal; } // r, g, b are between 0 and 16 static void MultiplyPaletteRGBComponents(u16 i, u8 r, u8 g, u8 b) { int curRed; int curGreen; int curBlue; u16 outPal; outPal = gPlttBufferUnfaded[i]; curRed = outPal & 0x1f; curGreen = (outPal & (0x1f << 5)) >> 5; curBlue = (outPal & (0x1f << 10)) >> 10; curRed -= ((curRed * r) >> 4); curGreen -= ((curGreen * g) >> 4); curBlue -= ((curBlue * b) >> 4); outPal = curRed; outPal |= curGreen << 5; outPal |= curBlue << 10; gPlttBufferFaded[i] = outPal; } static void PokecenterHealEffect_Init(struct Task *task); static void PokecenterHealEffect_WaitForBallPlacement(struct Task *task); static void PokecenterHealEffect_WaitForBallFlashing(struct Task *task); static void PokecenterHealEffect_WaitForSoundAndEnd(struct Task *task); static void HallOfFameRecordEffect_Init(struct Task *task); static void HallOfFameRecordEffect_WaitForBallPlacement(struct Task *task); static void HallOfFameRecordEffect_WaitForBallFlashing(struct Task *task); static void HallOfFameRecordEffect_WaitForSoundAndEnd(struct Task *task); static void Task_HallOfFameRecord(u8 taskId); static u8 CreateGlowingPokeballsEffect(s16 duration, s16 x, s16 y, bool16 fanfare); static void SpriteCB_PokeballGlowEffect(struct Sprite *sprite); static void PokeballGlowEffect_PlaceBalls(struct Sprite *sprite); static void PokeballGlowEffect_TryPlaySe(struct Sprite *sprite); static void PokeballGlowEffect_FlashFirstThree(struct Sprite *sprite); static void PokeballGlowEffect_FlashLast(struct Sprite *sprite); static void PokeballGlowEffect_WaitAfterFlash(struct Sprite *sprite); static void PokeballGlowEffect_Dummy(struct Sprite *sprite); static void PokeballGlowEffect_WaitForSound(struct Sprite *sprite); static void PokeballGlowEffect_Idle(struct Sprite *sprite); static u8 CreatePokecenterMonitorSprite(s32 x, s32 y); static void CreateHofMonitorSprite(s32 x, s32 y); static void (*const sPokecenterHealEffectFuncs[])(struct Task *) = { PokecenterHealEffect_Init, PokecenterHealEffect_WaitForBallPlacement, PokecenterHealEffect_WaitForBallFlashing, PokecenterHealEffect_WaitForSoundAndEnd }; static void (*const sHallOfFameRecordEffectFuncs[])(struct Task *) = { HallOfFameRecordEffect_Init, HallOfFameRecordEffect_WaitForBallPlacement, HallOfFameRecordEffect_WaitForBallFlashing, HallOfFameRecordEffect_WaitForSoundAndEnd }; static void (*const sPokeballGlowEffectFuncs[])(struct Sprite *) = { PokeballGlowEffect_PlaceBalls, PokeballGlowEffect_TryPlaySe, PokeballGlowEffect_FlashFirstThree, PokeballGlowEffect_FlashLast, PokeballGlowEffect_WaitAfterFlash, PokeballGlowEffect_Dummy, PokeballGlowEffect_WaitForSound, PokeballGlowEffect_Idle }; // Task data for Task_PokecenterHeal and Task_HallOfFameRecord #define tState data[0] #define tNumMons data[1] #define tFirstBallX data[2] #define tFirstBallY data[3] #define tMonitorX data[4] #define tMonitorY data[5] #define tGlowEffectSpriteId data[6] #define tMonitorSpriteId data[7] // Sprite data for SpriteCB_PokeballGlowEffect #define sState data[0] #define sTimer data[1] #define sCounter data[2] #define sNumFlashed data[3] #define sPlayHealSe data[5] #define sNumMons data[6] #define sSpriteId data[7] // Sprite data for SpriteCB_PokeballGlow #define sGlowEffectSpriteId data[0] // Sprite data for SpriteCB_PokecenterMonitor #define sStartFlash data[0] bool8 FldEff_PokecenterHeal(void) { u8 nPokemon; struct Task *task; nPokemon = CalculatePlayerPartyCount(); task = &gTasks[CreateTask(Task_PokecenterHeal, 0xFF)]; task->tNumMons = nPokemon; task->tFirstBallX = 93; task->tFirstBallY = 36; task->tMonitorX = 128; task->tMonitorY = 24; return FALSE; } static void Task_PokecenterHeal(u8 taskId) { struct Task *task = &gTasks[taskId]; sPokecenterHealEffectFuncs[task->tState](task); } static void PokecenterHealEffect_Init(struct Task *task) { task->tState++; task->tGlowEffectSpriteId = CreateGlowingPokeballsEffect(task->tNumMons, task->tFirstBallX, task->tFirstBallY, TRUE); task->tMonitorSpriteId = CreatePokecenterMonitorSprite(task->tMonitorX, task->tMonitorY); } static void PokecenterHealEffect_WaitForBallPlacement(struct Task *task) { if (gSprites[task->tGlowEffectSpriteId].sState >= 2) { gSprites[task->tMonitorSpriteId].sStartFlash++; task->tState++; } } static void PokecenterHealEffect_WaitForBallFlashing(struct Task *task) { if (gSprites[task->tGlowEffectSpriteId].sState > 4) task->tState++; } static void PokecenterHealEffect_WaitForSoundAndEnd(struct Task *task) { if (gSprites[task->tGlowEffectSpriteId].sState > 6) { DestroySprite(&gSprites[task->tGlowEffectSpriteId]); FieldEffectActiveListRemove(FLDEFF_POKECENTER_HEAL); DestroyTask(FindTaskIdByFunc(Task_PokecenterHeal)); } } bool8 FldEff_HallOfFameRecord(void) { u8 nPokemon; struct Task *task; nPokemon = CalculatePlayerPartyCount(); task = &gTasks[CreateTask(Task_HallOfFameRecord, 0xFF)]; task->tNumMons = nPokemon; task->tFirstBallX = 117; task->tFirstBallY = 60; return FALSE; } static void Task_HallOfFameRecord(u8 taskId) { struct Task *task; task = &gTasks[taskId]; sHallOfFameRecordEffectFuncs[task->tState](task); } static void HallOfFameRecordEffect_Init(struct Task *task) { u8 taskId; task->tState++; task->tGlowEffectSpriteId = CreateGlowingPokeballsEffect(task->tNumMons, task->tFirstBallX, task->tFirstBallY, FALSE); } static void HallOfFameRecordEffect_WaitForBallPlacement(struct Task *task) { if (gSprites[task->tGlowEffectSpriteId].sState > 1) { CreateHofMonitorSprite(120, 25); task->data[15]++; // unused, leftover from RSE task->tState++; } } static void HallOfFameRecordEffect_WaitForBallFlashing(struct Task *task) { if (gSprites[task->tGlowEffectSpriteId].sState > 4) task->tState++; } static void HallOfFameRecordEffect_WaitForSoundAndEnd(struct Task *task) { if (gSprites[task->tGlowEffectSpriteId].sState > 6) { DestroySprite(&gSprites[task->tGlowEffectSpriteId]); FieldEffectActiveListRemove(FLDEFF_HALL_OF_FAME_RECORD); DestroyTask(FindTaskIdByFunc(Task_HallOfFameRecord)); } } #undef tState #undef tNumMons #undef tFirstBallX #undef tFirstBallY #undef tMonitorX #undef tMonitorY #undef tGlowEffectSpriteId #undef tMonitorSpriteId static u8 CreateGlowingPokeballsEffect(s16 numMons, s16 x, s16 y, bool16 playHealSe) { u8 spriteId; struct Sprite *sprite; spriteId = CreateInvisibleSprite(SpriteCB_PokeballGlowEffect); sprite = &gSprites[spriteId]; sprite->x2 = x; sprite->y2 = y; sprite->subpriority = 0xFF; sprite->sPlayHealSe = playHealSe; sprite->sNumMons = numMons; sprite->sSpriteId = spriteId; return spriteId; } static void SpriteCB_PokeballGlowEffect(struct Sprite *sprite) { sPokeballGlowEffectFuncs[sprite->sState](sprite); } static const struct Coords16 sPokeballCoordOffsets[] = { {0, 0}, {6, 0}, {0, 4}, {6, 4}, {0, 8}, {6, 8} }; static const u8 sPokeballGlowReds[] = {16, 12, 8, 0}; static const u8 sPokeballGlowGreens[] = {16, 12, 8, 0}; static const u8 sPokeballGlowBlues[] = { 0, 0, 0, 0}; static void PokeballGlowEffect_PlaceBalls(struct Sprite *sprite) { u8 spriteId; if (sprite->sTimer == 0 || (--sprite->sTimer) == 0) { sprite->sTimer = 25; spriteId = CreateSpriteAtEnd(&sSpriteTemplate_PokeballGlow, sPokeballCoordOffsets[sprite->sCounter].x + sprite->x2, sPokeballCoordOffsets[sprite->sCounter].y + sprite->y2, 0xFF); gSprites[spriteId].oam.priority = 2; gSprites[spriteId].sGlowEffectSpriteId = sprite->sSpriteId; sprite->sCounter++; sprite->sNumMons--; PlaySE(SE_BALL); } if (sprite->sNumMons == 0) { sprite->sTimer = 32; sprite->sState++; } } static void PokeballGlowEffect_TryPlaySe(struct Sprite *sprite) { if ((--sprite->sTimer) == 0) { sprite->sState++; sprite->sTimer = 8; sprite->sCounter = 0; sprite->sNumFlashed = 0; if (sprite->sPlayHealSe) PlayFanfare(MUS_HEAL); } } static void PokeballGlowEffect_FlashFirstThree(struct Sprite *sprite) { u8 phase; if ((--sprite->sTimer) == 0) { sprite->sTimer = 8; sprite->sCounter++; sprite->sCounter &= 3; if (sprite->sCounter == 0) sprite->sNumFlashed++; } phase = (sprite->sCounter + 3) & 3; MultiplyInvertedPaletteRGBComponents(OBJ_PLTT_ID(IndexOfSpritePaletteTag(0x1007)) + 8, sPokeballGlowReds[phase], sPokeballGlowGreens[phase], sPokeballGlowBlues[phase]); phase = (sprite->sCounter + 2) & 3; MultiplyInvertedPaletteRGBComponents(OBJ_PLTT_ID(IndexOfSpritePaletteTag(0x1007)) + 6, sPokeballGlowReds[phase], sPokeballGlowGreens[phase], sPokeballGlowBlues[phase]); phase = (sprite->sCounter + 1) & 3; MultiplyInvertedPaletteRGBComponents(OBJ_PLTT_ID(IndexOfSpritePaletteTag(0x1007)) + 2, sPokeballGlowReds[phase], sPokeballGlowGreens[phase], sPokeballGlowBlues[phase]); phase = sprite->sCounter; MultiplyInvertedPaletteRGBComponents(OBJ_PLTT_ID(IndexOfSpritePaletteTag(0x1007)) + 5, sPokeballGlowReds[phase], sPokeballGlowGreens[phase], sPokeballGlowBlues[phase]); MultiplyInvertedPaletteRGBComponents(OBJ_PLTT_ID(IndexOfSpritePaletteTag(0x1007)) + 3, sPokeballGlowReds[phase], sPokeballGlowGreens[phase], sPokeballGlowBlues[phase]); if (sprite->sNumFlashed >= 3) { sprite->sState++; sprite->sTimer = 8; sprite->sCounter = 0; } } static void PokeballGlowEffect_FlashLast(struct Sprite *sprite) { u8 phase; if ((--sprite->sTimer) == 0) { sprite->sTimer = 8; sprite->sCounter++; sprite->sCounter &= 3; if (sprite->sCounter == 3) { sprite->sState++; sprite->sTimer = 30; } } phase = sprite->sCounter; MultiplyInvertedPaletteRGBComponents(OBJ_PLTT_ID(IndexOfSpritePaletteTag(0x1007)) + 8, sPokeballGlowReds[phase], sPokeballGlowGreens[phase], sPokeballGlowBlues[phase]); MultiplyInvertedPaletteRGBComponents(OBJ_PLTT_ID(IndexOfSpritePaletteTag(0x1007)) + 6, sPokeballGlowReds[phase], sPokeballGlowGreens[phase], sPokeballGlowBlues[phase]); MultiplyInvertedPaletteRGBComponents(OBJ_PLTT_ID(IndexOfSpritePaletteTag(0x1007)) + 2, sPokeballGlowReds[phase], sPokeballGlowGreens[phase], sPokeballGlowBlues[phase]); MultiplyInvertedPaletteRGBComponents(OBJ_PLTT_ID(IndexOfSpritePaletteTag(0x1007)) + 5, sPokeballGlowReds[phase], sPokeballGlowGreens[phase], sPokeballGlowBlues[phase]); MultiplyInvertedPaletteRGBComponents(OBJ_PLTT_ID(IndexOfSpritePaletteTag(0x1007)) + 3, sPokeballGlowReds[phase], sPokeballGlowGreens[phase], sPokeballGlowBlues[phase]); } static void PokeballGlowEffect_WaitAfterFlash(struct Sprite *sprite) { if ((--sprite->sTimer) == 0) sprite->sState++; } static void PokeballGlowEffect_Dummy(struct Sprite *sprite) { sprite->sState++; } static void PokeballGlowEffect_WaitForSound(struct Sprite *sprite) { if (sprite->sPlayHealSe == FALSE || IsFanfareTaskInactive()) sprite->sState++; } static void PokeballGlowEffect_Idle(struct Sprite *sprite) { } static void SpriteCB_PokeballGlow(struct Sprite *sprite) { if (gSprites[sprite->sGlowEffectSpriteId].sState > 4) FieldEffectFreeGraphicsResources(sprite); } #undef sState #undef sTimer #undef sCounter #undef sNumFlashed #undef sPlayHealSe #undef sNumMons #undef sSpriteId #undef sGlowEffectSpriteId static u8 CreatePokecenterMonitorSprite(s32 x, s32 y) { u8 spriteId; struct Sprite *sprite; spriteId = CreateSpriteAtEnd(&sSpriteTemplate_PokecenterMonitor, x, y, 0); sprite = &gSprites[spriteId]; sprite->oam.priority = 2; sprite->invisible = TRUE; return spriteId; } static void SpriteCB_PokecenterMonitor(struct Sprite *sprite) { if (sprite->sStartFlash != FALSE) { sprite->sStartFlash = FALSE; sprite->invisible = FALSE; StartSpriteAnim(sprite, 1); } if (sprite->animEnded) FieldEffectFreeGraphicsResources(sprite); } #undef sStartFlash static void CreateHofMonitorSprite(s32 x, s32 y) { CreateSpriteAtEnd(&sSpriteTemplate_HofMonitor, x, y, 0); } static void SpriteCB_HallOfFameMonitor(struct Sprite *sprite) { if (sprite->animEnded) FieldEffectFreeGraphicsResources(sprite); } static void FieldCallback_UseFly(void); static void Task_UseFly(u8 taskId); static void FieldCallback_FlyIntoMap(void); static void Task_FlyIntoMap(u8 taskId); void ReturnToFieldFromFlyMapSelect(void) { SetMainCallback2(CB2_ReturnToField); gFieldCallback = FieldCallback_UseFly; } static void FieldCallback_UseFly(void) { FadeInFromBlack(); CreateTask(Task_UseFly, 0); LockPlayerFieldControls(); FreezeObjectEvents(); gFieldCallback = NULL; } static void Task_UseFly(u8 taskId) { struct Task *task; task = &gTasks[taskId]; if (task->data[0] == 0) { if (!IsWeatherNotFadingIn()) return; gFieldEffectArguments[0] = GetCursorSelectionMonId(); if ((int)gFieldEffectArguments[0] >= PARTY_SIZE) gFieldEffectArguments[0] = 0; FieldEffectStart(FLDEFF_FLY_OUT); task->data[0]++; } if (!FieldEffectActiveListContains(FLDEFF_FLY_OUT)) { Overworld_ResetStateAfterFly(); WarpIntoMap(); SetMainCallback2(CB2_LoadMap); gFieldCallback = FieldCallback_FlyIntoMap; DestroyTask(taskId); } } static void FieldCallback_FlyIntoMap(void) { Overworld_PlaySpecialMapMusic(); FadeInFromBlack(); CreateTask(Task_FlyIntoMap, 0); gObjectEvents[gPlayerAvatar.objectEventId].invisible = TRUE; if (gPlayerAvatar.flags & PLAYER_AVATAR_FLAG_SURFING) ObjectEventTurn(&gObjectEvents[gPlayerAvatar.objectEventId], DIR_WEST); LockPlayerFieldControls(); FreezeObjectEvents(); gFieldCallback = NULL; } static void Task_FlyIntoMap(u8 taskId) { struct Task *task; task = &gTasks[taskId]; if (task->data[0] == 0) { if (gPaletteFade.active) return; FieldEffectStart(FLDEFF_FLY_IN); task->data[0]++; } if (!FieldEffectActiveListContains(FLDEFF_FLY_IN)) { UnlockPlayerFieldControls(); UnfreezeObjectEvents(); DestroyTask(taskId); } } static void Task_FallWarpFieldEffect(u8 taskId); static bool8 FallWarpEffect_1(struct Task *task); static bool8 FallWarpEffect_2(struct Task *task); static bool8 FallWarpEffect_3(struct Task *task); static bool8 FallWarpEffect_4(struct Task *task); static bool8 FallWarpEffect_5(struct Task *task); static bool8 FallWarpEffect_6(struct Task *task); static bool8 FallWarpEffect_7(struct Task *task); static bool8 (*const sFallWarpEffectCBPtrs[])(struct Task *task) = { FallWarpEffect_1, FallWarpEffect_2, FallWarpEffect_3, FallWarpEffect_4, FallWarpEffect_5, FallWarpEffect_6, FallWarpEffect_7 }; void FieldCB_FallWarpExit(void) { Overworld_PlaySpecialMapMusic(); WarpFadeInScreen(); QuestLog_DrawPreviouslyOnQuestHeaderIfInPlaybackMode(); LockPlayerFieldControls(); FreezeObjectEvents(); CreateTask(Task_FallWarpFieldEffect, 0); gFieldCallback = NULL; } static void Task_FallWarpFieldEffect(u8 taskId) { struct Task *task = &gTasks[taskId]; while (sFallWarpEffectCBPtrs[task->data[0]](task)) ; } static bool8 FallWarpEffect_1(struct Task *task) { struct ObjectEvent * playerObject; struct Sprite *playerSprite; playerObject = &gObjectEvents[gPlayerAvatar.objectEventId]; playerSprite = &gSprites[gPlayerAvatar.spriteId]; CameraObjectReset2(); gObjectEvents[gPlayerAvatar.objectEventId].invisible = TRUE; gPlayerAvatar.preventStep = TRUE; ObjectEventSetHeldMovement(playerObject, GetFaceDirectionMovementAction(GetPlayerFacingDirection())); task->data[4] = playerSprite->subspriteMode; playerObject->fixedPriority = TRUE; playerSprite->oam.priority = 1; playerSprite->subspriteMode = SUBSPRITES_IGNORE_PRIORITY; task->data[0]++; return TRUE; } static bool8 FallWarpEffect_2(struct Task *task) { if (IsWeatherNotFadingIn()) { task->data[0]++; } return FALSE; } static bool8 FallWarpEffect_3(struct Task *task) { struct Sprite *sprite; s16 centerToCornerVecY; sprite = &gSprites[gPlayerAvatar.spriteId]; centerToCornerVecY = -(sprite->centerToCornerVecY << 1); sprite->y2 = -(sprite->y + sprite->centerToCornerVecY + gSpriteCoordOffsetY + centerToCornerVecY); task->data[1] = 1; task->data[2] = 0; gObjectEvents[gPlayerAvatar.objectEventId].invisible = FALSE; PlaySE(SE_FALL); task->data[0]++; return FALSE; } static bool8 FallWarpEffect_4(struct Task *task) { struct ObjectEvent * objectEvent; struct Sprite *sprite; objectEvent = &gObjectEvents[gPlayerAvatar.objectEventId]; sprite = &gSprites[gPlayerAvatar.spriteId]; sprite->y2 += task->data[1]; if (task->data[1] < 8) { task->data[2] += task->data[1]; if (task->data[2] & 0xf) { task->data[1] <<= 1; } } if (task->data[3] == 0 && sprite->y2 >= -16) { task->data[3]++; objectEvent->fixedPriority = FALSE; sprite->subspriteMode = task->data[4]; objectEvent->triggerGroundEffectsOnMove = TRUE; } if (sprite->y2 >= 0) { PlaySE(SE_M_STRENGTH); objectEvent->triggerGroundEffectsOnStop = TRUE; objectEvent->landingJump = TRUE; sprite->y2 = 0; task->data[0]++; } return FALSE; } static bool8 FallWarpEffect_5(struct Task *task) { task->data[0]++; task->data[1] = 4; task->data[2] = 0; SetCameraPanningCallback(NULL); return TRUE; } static bool8 FallWarpEffect_6(struct Task *task) { SetCameraPanning(0, task->data[1]); task->data[1] = -task->data[1]; task->data[2]++; if ((task->data[2] & 3) == 0) { task->data[1] >>= 1; } if (task->data[1] == 0) { task->data[0]++; } return FALSE; } static bool8 FallWarpEffect_7(struct Task *task) { s16 x, y; gPlayerAvatar.preventStep = FALSE; UnlockPlayerFieldControls(); CameraObjectReset1(); UnfreezeObjectEvents(); InstallCameraPanAheadCallback(); PlayerGetDestCoords(&x, &y); if (MetatileBehavior_IsSurfableInSeafoamIslands(MapGridGetMetatileBehaviorAt(x, y)) == TRUE) { VarSet(VAR_TEMP_1, 1); SetPlayerAvatarTransitionFlags(PLAYER_AVATAR_FLAG_SURFING); SetHelpContext(HELPCONTEXT_SURFING); } DestroyTask(FindTaskIdByFunc(Task_FallWarpFieldEffect)); return FALSE; } static void Task_EscalatorWarpFieldEffect(u8 taskId); static bool8 EscalatorWarpEffect_1(struct Task *task); static bool8 EscalatorWarpEffect_2(struct Task *task); static bool8 EscalatorWarpEffect_3(struct Task *task); static bool8 EscalatorWarpEffect_4(struct Task *task); static bool8 EscalatorWarpEffect_5(struct Task *task); static bool8 EscalatorWarpEffect_6(struct Task *task); static void Escalator_AnimatePlayerGoingDown(struct Task *task); static void Escalator_AnimatePlayerGoingUp(struct Task *task); static void Escalator_BeginFadeOutToNewMap(void); static void Escalator_TransitionToWarpInEffect(void); static void FieldCB_EscalatorWarpIn(void); static void Task_EscalatorWarpInFieldEffect(u8 taskId); static bool8 EscalatorWarpInEffect_1(struct Task *task); static bool8 EscalatorWarpInEffect_2(struct Task *task); static bool8 EscalatorWarpInEffect_3(struct Task *task); static bool8 EscalatorWarpInEffect_4(struct Task *task); static bool8 EscalatorWarpInEffect_5(struct Task *task); static bool8 EscalatorWarpInEffect_6(struct Task *task); static bool8 EscalatorWarpInEffect_7(struct Task *task); static bool8 (*const sEscalatorWarpFieldEffectFuncs[])(struct Task *task) = { EscalatorWarpEffect_1, EscalatorWarpEffect_2, EscalatorWarpEffect_3, EscalatorWarpEffect_4, EscalatorWarpEffect_5, EscalatorWarpEffect_6 }; void StartEscalatorWarp(u8 metatileBehavior, u8 priority) { u8 taskId = CreateTask(Task_EscalatorWarpFieldEffect, priority); gTasks[taskId].data[1] = 0; if (metatileBehavior == MB_UP_ESCALATOR) gTasks[taskId].data[1] = 1; } static void Task_EscalatorWarpFieldEffect(u8 taskId) { struct Task *task = &gTasks[taskId]; while (sEscalatorWarpFieldEffectFuncs[task->data[0]](task)) ; } static bool8 EscalatorWarpEffect_1(struct Task *task) { FreezeObjectEvents(); CameraObjectReset2(); StartEscalator(task->data[1]); QuestLog_OnEscalatorWarp(QL_ESCALATOR_OUT); task->data[0]++; return FALSE; } static bool8 EscalatorWarpEffect_2(struct Task *task) { struct ObjectEvent * objectEvent; objectEvent = &gObjectEvents[gPlayerAvatar.objectEventId]; if (!ObjectEventIsMovementOverridden(objectEvent) || ObjectEventClearHeldMovementIfFinished(objectEvent)) { ObjectEventSetHeldMovement(objectEvent, GetFaceDirectionMovementAction(GetPlayerFacingDirection())); task->data[0]++; task->data[2] = 0; task->data[3] = 0; if ((u8)task->data[1] == 0) { task->data[0] = 4; } PlaySE(SE_ESCALATOR); } return FALSE; } static bool8 EscalatorWarpEffect_3(struct Task *task) { Escalator_AnimatePlayerGoingDown(task); if (task->data[2] > 3) { Escalator_BeginFadeOutToNewMap(); task->data[0]++; } return FALSE; } static bool8 EscalatorWarpEffect_4(struct Task *task) { Escalator_AnimatePlayerGoingDown(task); Escalator_TransitionToWarpInEffect(); return FALSE; } static bool8 EscalatorWarpEffect_5(struct Task *task) { Escalator_AnimatePlayerGoingUp(task); if (task->data[2] > 3) { Escalator_BeginFadeOutToNewMap(); task->data[0]++; } return FALSE; } static bool8 EscalatorWarpEffect_6(struct Task *task) { Escalator_AnimatePlayerGoingUp(task); Escalator_TransitionToWarpInEffect(); return FALSE; } static void Escalator_AnimatePlayerGoingDown(struct Task *task) { struct Sprite *sprite; sprite = &gSprites[gPlayerAvatar.spriteId]; sprite->x2 = Cos(0x84, task->data[2]); sprite->y2 = Sin(0x94, task->data[2]); task->data[3]++; if (task->data[3] & 1) { task->data[2]++; } } static void Escalator_AnimatePlayerGoingUp(struct Task *task) { struct Sprite *sprite; sprite = &gSprites[gPlayerAvatar.spriteId]; sprite->x2 = Cos(0x7c, task->data[2]); sprite->y2 = Sin(0x76, task->data[2]); task->data[3]++; if (task->data[3] & 1) { task->data[2]++; } } static void Escalator_BeginFadeOutToNewMap(void) { TryFadeOutOldMapMusic(); WarpFadeOutScreen(); } static void Escalator_TransitionToWarpInEffect(void) { if (!gPaletteFade.active && BGMusicStopped() == TRUE) { StopEscalator(); WarpIntoMap(); gFieldCallback = FieldCB_EscalatorWarpIn; SetMainCallback2(CB2_LoadMap); DestroyTask(FindTaskIdByFunc(Task_EscalatorWarpFieldEffect)); } } static bool8 (*const sEscalatorWarpInFieldEffectFuncs[])(struct Task *task) = { EscalatorWarpInEffect_1, EscalatorWarpInEffect_2, EscalatorWarpInEffect_3, EscalatorWarpInEffect_4, EscalatorWarpInEffect_5, EscalatorWarpInEffect_6, EscalatorWarpInEffect_7 }; static void FieldCB_EscalatorWarpIn(void) { Overworld_PlaySpecialMapMusic(); WarpFadeInScreen(); QuestLog_DrawPreviouslyOnQuestHeaderIfInPlaybackMode(); LockPlayerFieldControls(); FreezeObjectEvents(); CreateTask(Task_EscalatorWarpInFieldEffect, 0); gFieldCallback = NULL; } static void Task_EscalatorWarpInFieldEffect(u8 taskId) { struct Task *task = &gTasks[taskId]; while (sEscalatorWarpInFieldEffectFuncs[task->data[0]](task)) ; } static bool8 EscalatorWarpInEffect_1(struct Task *task) { struct ObjectEvent * objectEvent; s16 x; s16 y; u8 behavior; CameraObjectReset2(); objectEvent = &gObjectEvents[gPlayerAvatar.objectEventId]; ObjectEventSetHeldMovement(objectEvent, GetFaceDirectionMovementAction(DIR_EAST)); PlayerGetDestCoords(&x, &y); behavior = MapGridGetMetatileBehaviorAt(x, y); task->data[0]++; task->data[1] = 16; if (behavior == MB_DOWN_ESCALATOR) { behavior = 1; task->data[0] = 3; } else { behavior = 0; } StartEscalator(behavior); return TRUE; } static bool8 EscalatorWarpInEffect_2(struct Task *task) { struct Sprite *sprite; sprite = &gSprites[gPlayerAvatar.spriteId]; sprite->x2 = Cos(0x84, task->data[1]); sprite->y2 = Sin(0x94, task->data[1]); task->data[0]++; return FALSE; } static bool8 EscalatorWarpInEffect_3(struct Task *task) { struct Sprite *sprite; sprite = &gSprites[gPlayerAvatar.spriteId]; sprite->x2 = Cos(0x84, task->data[1]); sprite->y2 = Sin(0x94, task->data[1]); task->data[2]++; if (task->data[2] & 1) { task->data[1]--; } if (task->data[1] == 0) { sprite->x2 = 0; sprite->y2 = 0; task->data[0] = 5; } return FALSE; } static bool8 EscalatorWarpInEffect_4(struct Task *task) { struct Sprite *sprite; sprite = &gSprites[gPlayerAvatar.spriteId]; sprite->x2 = Cos(0x7c, task->data[1]); sprite->y2 = Sin(0x76, task->data[1]); task->data[0]++; return FALSE; } static bool8 EscalatorWarpInEffect_5(struct Task *task) { struct Sprite *sprite; sprite = &gSprites[gPlayerAvatar.spriteId]; sprite->x2 = Cos(0x7c, task->data[1]); sprite->y2 = Sin(0x76, task->data[1]); task->data[2]++; if (task->data[2] & 1) { task->data[1]--; } if (task->data[1] == 0) { sprite->x2 = 0; sprite->y2 = 0; task->data[0]++; } return FALSE; } static bool8 EscalatorWarpInEffect_6(struct Task *task) { if (IsEscalatorMoving()) { return FALSE; } StopEscalator(); task->data[0]++; return TRUE; } static bool8 EscalatorWarpInEffect_7(struct Task *task) { struct ObjectEvent * objectEvent; objectEvent = &gObjectEvents[gPlayerAvatar.objectEventId]; if (ObjectEventClearHeldMovementIfFinished(objectEvent)) { CameraObjectReset1(); UnlockPlayerFieldControls(); UnfreezeObjectEvents(); ObjectEventSetHeldMovement(objectEvent, GetWalkNormalMovementAction(DIR_EAST)); DestroyTask(FindTaskIdByFunc(Task_EscalatorWarpInFieldEffect)); QuestLog_OnEscalatorWarp(QL_ESCALATOR_IN); } return FALSE; } static void Task_UseWaterfall(u8 taskId); static bool8 waterfall_0_setup(struct Task *task, struct ObjectEvent * playerObj); static bool8 waterfall_1_do_anim_probably(struct Task *task, struct ObjectEvent * playerObj); static bool8 waterfall_2_wait_anim_finish_probably(struct Task *task, struct ObjectEvent * playerObj); static bool8 waterfall_3_move_player_probably(struct Task *task, struct ObjectEvent * playerObj); static bool8 waterfall_4_wait_player_move_probably(struct Task *task, struct ObjectEvent * playerObj); static bool8 (*const sUseWaterfallFieldEffectFuncs[])(struct Task *task, struct ObjectEvent * playerObj) = { waterfall_0_setup, waterfall_1_do_anim_probably, waterfall_2_wait_anim_finish_probably, waterfall_3_move_player_probably, waterfall_4_wait_player_move_probably }; u32 FldEff_UseWaterfall(void) { u8 taskId = CreateTask(Task_UseWaterfall, 0xFF); gTasks[taskId].data[1] = gFieldEffectArguments[0]; Task_UseWaterfall(taskId); return 0; } static void Task_UseWaterfall(u8 taskId) { while (sUseWaterfallFieldEffectFuncs[gTasks[taskId].data[0]](&gTasks[taskId], &gObjectEvents[gPlayerAvatar.objectEventId])) ; } static bool8 waterfall_0_setup(struct Task *task, struct ObjectEvent * playerObj) { LockPlayerFieldControls(); gPlayerAvatar.preventStep = TRUE; task->data[0]++; return FALSE; } static bool8 waterfall_1_do_anim_probably(struct Task *task, struct ObjectEvent * playerObj) { LockPlayerFieldControls(); if (!ObjectEventIsMovementOverridden(playerObj)) { ObjectEventClearHeldMovementIfFinished(playerObj); gFieldEffectArguments[0] = task->data[1]; FieldEffectStart(FLDEFF_FIELD_MOVE_SHOW_MON_INIT); task->data[0]++; } return FALSE; } static bool8 waterfall_2_wait_anim_finish_probably(struct Task *task, struct ObjectEvent * playerObj) { if (FieldEffectActiveListContains(FLDEFF_FIELD_MOVE_SHOW_MON)) return FALSE; task->data[0]++; return TRUE; } static bool8 waterfall_3_move_player_probably(struct Task *task, struct ObjectEvent * playerObj) { ObjectEventSetHeldMovement(playerObj, GetWalkSlowerMovementAction(DIR_NORTH)); task->data[0]++; return FALSE; } static bool8 waterfall_4_wait_player_move_probably(struct Task *task, struct ObjectEvent * playerObj) { if (!ObjectEventClearHeldMovementIfFinished(playerObj)) return FALSE; if (MetatileBehavior_IsWaterfall(playerObj->currentMetatileBehavior)) { task->data[0] = 3; return TRUE; } UnlockPlayerFieldControls(); gPlayerAvatar.preventStep = FALSE; DestroyTask(FindTaskIdByFunc(Task_UseWaterfall)); FieldEffectActiveListRemove(FLDEFF_USE_WATERFALL); return FALSE; } static void Task_UseDive(u8 taskId); static bool8 DiveFieldEffect_Init(struct Task *task); static bool8 DiveFieldEffect_ShowMon(struct Task *task); static bool8 DiveFieldEffect_TryWarp(struct Task *task); static bool8 (*const sDiveFieldEffectFuncs[])(struct Task *task) = { DiveFieldEffect_Init, DiveFieldEffect_ShowMon, DiveFieldEffect_TryWarp }; u32 FldEff_UseDive(void) { u8 taskId = CreateTask(Task_UseDive, 0xFF); gTasks[taskId].data[15] = gFieldEffectArguments[0]; // party index of pokemon with dive gTasks[taskId].data[14] = gFieldEffectArguments[1]; // unused Task_UseDive(taskId); return 0; } static void Task_UseDive(u8 taskId) { while (sDiveFieldEffectFuncs[gTasks[taskId].data[0]](&gTasks[taskId])); } static bool8 DiveFieldEffect_Init(struct Task *task) { gPlayerAvatar.preventStep = TRUE; task->data[0]++; return FALSE; } static bool8 DiveFieldEffect_ShowMon(struct Task *task) { LockPlayerFieldControls(); gFieldEffectArguments[0] = task->data[15]; FieldEffectStart(FLDEFF_FIELD_MOVE_SHOW_MON_INIT); task->data[0]++; return FALSE; } static bool8 DiveFieldEffect_TryWarp(struct Task *task) { struct MapPosition pos; PlayerGetDestCoords(&pos.x, &pos.y); if (!FieldEffectActiveListContains(FLDEFF_FIELD_MOVE_SHOW_MON)) { dive_warp(&pos, gObjectEvents[gPlayerAvatar.objectEventId].currentMetatileBehavior); DestroyTask(FindTaskIdByFunc(Task_UseDive)); FieldEffectActiveListRemove(FLDEFF_USE_DIVE); } return FALSE; } static void Task_LavaridgeGymB1FWarp(u8 taskId); static bool8 LavaridgeGymB1FWarpEffect_1(struct Task *task, struct ObjectEvent * objectEvent, struct Sprite *sprite); static bool8 LavaridgeGymB1FWarpEffect_2(struct Task *task, struct ObjectEvent * objectEvent, struct Sprite *sprite); static bool8 LavaridgeGymB1FWarpEffect_3(struct Task *task, struct ObjectEvent * objectEvent, struct Sprite *sprite); static bool8 LavaridgeGymB1FWarpEffect_4(struct Task *task, struct ObjectEvent * objectEvent, struct Sprite *sprite); static bool8 LavaridgeGymB1FWarpEffect_5(struct Task *task, struct ObjectEvent * objectEvent, struct Sprite *sprite); static bool8 LavaridgeGymB1FWarpEffect_6(struct Task *task, struct ObjectEvent * objectEvent, struct Sprite *sprite); static void FieldCB_LavaridgeGymB1FWarpExit(void); static void Task_LavaridgeGymB1FWarpExit(u8 taskId); static bool8 LavaridgeGymB1FWarpExitEffect_1(struct Task *task, struct ObjectEvent * objectEvent, struct Sprite *sprite); static bool8 LavaridgeGymB1FWarpExitEffect_2(struct Task *task, struct ObjectEvent * objectEvent, struct Sprite *sprite); static bool8 LavaridgeGymB1FWarpExitEffect_3(struct Task *task, struct ObjectEvent * objectEvent, struct Sprite *sprite); static bool8 LavaridgeGymB1FWarpExitEffect_4(struct Task *task, struct ObjectEvent * objectEvent, struct Sprite *sprite); static bool8 (*const sLavaridgeGymB1FWarpEffectFuncs[])(struct Task *task, struct ObjectEvent * objectEvent, struct Sprite *sprite) = { LavaridgeGymB1FWarpEffect_1, LavaridgeGymB1FWarpEffect_2, LavaridgeGymB1FWarpEffect_3, LavaridgeGymB1FWarpEffect_4, LavaridgeGymB1FWarpEffect_5, LavaridgeGymB1FWarpEffect_6 }; void StartLavaridgeGymB1FWarp(u8 priority) { CreateTask(Task_LavaridgeGymB1FWarp, priority); } static void Task_LavaridgeGymB1FWarp(u8 taskId) { while (sLavaridgeGymB1FWarpEffectFuncs[gTasks[taskId].data[0]](&gTasks[taskId], &gObjectEvents[gPlayerAvatar.objectEventId], &gSprites[gPlayerAvatar.spriteId])); } static bool8 LavaridgeGymB1FWarpEffect_1(struct Task *task, struct ObjectEvent * objectEvent, struct Sprite *sprite) { FreezeObjectEvents(); CameraObjectReset2(); SetCameraPanningCallback(NULL); gPlayerAvatar.preventStep = TRUE; objectEvent->fixedPriority = TRUE; task->data[1] = 1; task->data[0]++; return TRUE; } static bool8 LavaridgeGymB1FWarpEffect_2(struct Task *task, struct ObjectEvent * objectEvent, struct Sprite *sprite) { SetCameraPanning(0, task->data[1]); task->data[1] = -task->data[1]; task->data[2]++; if (task->data[2] > 7) { task->data[2] = 0; task->data[0]++; } return FALSE; } static bool8 LavaridgeGymB1FWarpEffect_3(struct Task *task, struct ObjectEvent * objectEvent, struct Sprite *sprite) { sprite->y2 = 0; task->data[3] = 1; gFieldEffectArguments[0] = objectEvent->currentCoords.x; gFieldEffectArguments[1] = objectEvent->currentCoords.y; gFieldEffectArguments[2] = sprite->subpriority - 1; gFieldEffectArguments[3] = sprite->oam.priority; FieldEffectStart(FLDEFF_LAVARIDGE_GYM_WARP); PlaySE(SE_M_EXPLOSION); task->data[0]++; return TRUE; } static bool8 LavaridgeGymB1FWarpEffect_4(struct Task *task, struct ObjectEvent * objectEvent, struct Sprite *sprite) { s16 centerToCornerVecY; SetCameraPanning(0, task->data[1]); if (task->data[1] = -task->data[1], ++task->data[2] <= 17) { if (!(task->data[2] & 1) && (task->data[1] <= 3)) { task->data[1] <<= 1; } } else if (!(task->data[2] & 4) && (task->data[1] > 0)) { task->data[1] >>= 1; } if (task->data[2] > 6) { centerToCornerVecY = -(sprite->centerToCornerVecY << 1); if (sprite->y2 > -(sprite->y + sprite->centerToCornerVecY + gSpriteCoordOffsetY + centerToCornerVecY)) { sprite->y2 -= task->data[3]; if (task->data[3] <= 7) { task->data[3]++; } } else { task->data[4] = 1; } } if (task->data[5] == 0 && sprite->y2 < -0x10) { task->data[5]++; objectEvent->fixedPriority = TRUE; sprite->oam.priority = 1; sprite->subspriteMode = SUBSPRITES_IGNORE_PRIORITY; } if (task->data[1] == 0 && task->data[4] != 0) { task->data[0]++; } return FALSE; } static bool8 LavaridgeGymB1FWarpEffect_5(struct Task *task, struct ObjectEvent * objectEvent, struct Sprite *sprite) { TryFadeOutOldMapMusic(); WarpFadeOutScreen(); task->data[0]++; return FALSE; } static bool8 LavaridgeGymB1FWarpEffect_6(struct Task *task, struct ObjectEvent * objectEvent, struct Sprite *sprite) { if (!gPaletteFade.active && BGMusicStopped() == TRUE) { WarpIntoMap(); gFieldCallback = FieldCB_LavaridgeGymB1FWarpExit; SetMainCallback2(CB2_LoadMap); DestroyTask(FindTaskIdByFunc(Task_LavaridgeGymB1FWarp)); } return FALSE; } static bool8 (*const sLavaridgeGymB1FWarpExitEffectFuncs[])(struct Task *task, struct ObjectEvent * objectEvent, struct Sprite *sprite) = { LavaridgeGymB1FWarpExitEffect_1, LavaridgeGymB1FWarpExitEffect_2, LavaridgeGymB1FWarpExitEffect_3, LavaridgeGymB1FWarpExitEffect_4 }; static void FieldCB_LavaridgeGymB1FWarpExit(void) { Overworld_PlaySpecialMapMusic(); WarpFadeInScreen(); QuestLog_DrawPreviouslyOnQuestHeaderIfInPlaybackMode(); LockPlayerFieldControls(); gFieldCallback = NULL; CreateTask(Task_LavaridgeGymB1FWarpExit, 0); } static void Task_LavaridgeGymB1FWarpExit(u8 taskId) { while (sLavaridgeGymB1FWarpExitEffectFuncs[gTasks[taskId].data[0]](&gTasks[taskId], &gObjectEvents[gPlayerAvatar.objectEventId], &gSprites[gPlayerAvatar.spriteId])); } static bool8 LavaridgeGymB1FWarpExitEffect_1(struct Task *task, struct ObjectEvent * objectEvent, struct Sprite *sprite) { CameraObjectReset2(); FreezeObjectEvents(); gPlayerAvatar.preventStep = TRUE; objectEvent->invisible = TRUE; task->data[0]++; return FALSE; } static bool8 LavaridgeGymB1FWarpExitEffect_2(struct Task *task, struct ObjectEvent * objectEvent, struct Sprite *sprite) { if (IsWeatherNotFadingIn()) { gFieldEffectArguments[0] = objectEvent->currentCoords.x; gFieldEffectArguments[1] = objectEvent->currentCoords.y; gFieldEffectArguments[2] = sprite->subpriority - 1; gFieldEffectArguments[3] = sprite->oam.priority; task->data[1] = FieldEffectStart(FLDEFF_POP_OUT_OF_ASH); task->data[0]++; } return FALSE; } static bool8 LavaridgeGymB1FWarpExitEffect_3(struct Task *task, struct ObjectEvent * objectEvent, struct Sprite *sprite) { sprite = &gSprites[task->data[1]]; if (sprite->animCmdIndex > 1) { task->data[0]++; objectEvent->invisible = FALSE; CameraObjectReset1(); PlaySE(SE_M_DIG); ObjectEventSetHeldMovement(objectEvent, GetJumpMovementAction(DIR_EAST)); } return FALSE; } static bool8 LavaridgeGymB1FWarpExitEffect_4(struct Task *task, struct ObjectEvent * objectEvent, struct Sprite *sprite) { if (ObjectEventClearHeldMovementIfFinished(objectEvent)) { gPlayerAvatar.preventStep = FALSE; UnlockPlayerFieldControls(); UnfreezeObjectEvents(); DestroyTask(FindTaskIdByFunc(Task_LavaridgeGymB1FWarpExit)); } return FALSE; } static void Task_LavaridgeGym1FWarp(u8 taskId); static bool8 LavaridgeGym1FWarpEffect_1(struct Task *task, struct ObjectEvent * objectEvent, struct Sprite *sprite); static bool8 LavaridgeGym1FWarpEffect_2(struct Task *task, struct ObjectEvent * objectEvent, struct Sprite *sprite); static bool8 LavaridgeGym1FWarpEffect_3(struct Task *task, struct ObjectEvent * objectEvent, struct Sprite *sprite); static bool8 LavaridgeGym1FWarpEffect_4(struct Task *task, struct ObjectEvent * objectEvent, struct Sprite *sprite); static bool8 LavaridgeGym1FWarpEffect_5(struct Task *task, struct ObjectEvent * objectEvent, struct Sprite *sprite); static bool8 (*const sLavaridgeGym1FWarpEffectFuncs[])(struct Task *task, struct ObjectEvent * objectEvent, struct Sprite *sprite) = { LavaridgeGym1FWarpEffect_1, LavaridgeGym1FWarpEffect_2, LavaridgeGym1FWarpEffect_3, LavaridgeGym1FWarpEffect_4, LavaridgeGym1FWarpEffect_5 }; // For the ash puff effect when warping off the B1F ash tiles u8 FldEff_LavaridgeGymWarp(void) { u8 spriteId; SetSpritePosToOffsetMapCoords((s16 *)&gFieldEffectArguments[0], (s16 *)&gFieldEffectArguments[1], 8, 8); spriteId = CreateSpriteAtEnd(gFieldEffectObjectTemplatePointers[FLDEFFOBJ_ASH_LAUNCH], gFieldEffectArguments[0], gFieldEffectArguments[1], gFieldEffectArguments[2]); gSprites[spriteId].oam.priority = gFieldEffectArguments[3]; gSprites[spriteId].coordOffsetEnabled = TRUE; return spriteId; } void SpriteCB_AshLaunch(struct Sprite *sprite) { if (sprite->animEnded) { FieldEffectStop(sprite, FLDEFF_LAVARIDGE_GYM_WARP); } } void StartLavaridgeGym1FWarp(u8 priority) { CreateTask(Task_LavaridgeGym1FWarp, priority); } static void Task_LavaridgeGym1FWarp(u8 taskId) { while(sLavaridgeGym1FWarpEffectFuncs[gTasks[taskId].data[0]](&gTasks[taskId], &gObjectEvents[gPlayerAvatar.objectEventId], &gSprites[gPlayerAvatar.spriteId])); } static bool8 LavaridgeGym1FWarpEffect_1(struct Task *task, struct ObjectEvent * objectEvent, struct Sprite *sprite) { FreezeObjectEvents(); CameraObjectReset2(); gPlayerAvatar.preventStep = TRUE; objectEvent->fixedPriority = TRUE; task->data[0]++; return FALSE; } static bool8 LavaridgeGym1FWarpEffect_2(struct Task *task, struct ObjectEvent * objectEvent, struct Sprite *sprite) { if (ObjectEventClearHeldMovementIfFinished(objectEvent)) { if (task->data[1] > 3) { gFieldEffectArguments[0] = objectEvent->currentCoords.x; gFieldEffectArguments[1] = objectEvent->currentCoords.y; gFieldEffectArguments[2] = sprite->subpriority - 1; gFieldEffectArguments[3] = sprite->oam.priority; task->data[1] = FieldEffectStart(FLDEFF_POP_OUT_OF_ASH); task->data[0]++; } else { task->data[1]++; ObjectEventSetHeldMovement(objectEvent, GetWalkInPlaceFasterMovementAction(objectEvent->facingDirection)); PlaySE(SE_LAVARIDGE_FALL_WARP); } } return FALSE; } static bool8 LavaridgeGym1FWarpEffect_3(struct Task *task, struct ObjectEvent * objectEvent, struct Sprite *sprite) { if (gSprites[task->data[1]].animCmdIndex == 2) { objectEvent->invisible = TRUE; task->data[0]++; } return FALSE; } static bool8 LavaridgeGym1FWarpEffect_4(struct Task *task, struct ObjectEvent * objectEvent, struct Sprite *sprite) { if (!FieldEffectActiveListContains(FLDEFF_POP_OUT_OF_ASH)) { TryFadeOutOldMapMusic(); WarpFadeOutScreen(); task->data[0]++; } return FALSE; } static bool8 LavaridgeGym1FWarpEffect_5(struct Task *task, struct ObjectEvent * objectEvent, struct Sprite *sprite) { if (!gPaletteFade.active && BGMusicStopped() == TRUE) { WarpIntoMap(); gFieldCallback = FieldCB_FallWarpExit; SetMainCallback2(CB2_LoadMap); DestroyTask(FindTaskIdByFunc(Task_LavaridgeGym1FWarp)); } return FALSE; } u8 FldEff_PopOutOfAsh(void) { u8 spriteId; SetSpritePosToOffsetMapCoords((s16 *)&gFieldEffectArguments[0], (s16 *)&gFieldEffectArguments[1], 8, 8); spriteId = CreateSpriteAtEnd(gFieldEffectObjectTemplatePointers[FLDEFFOBJ_ASH_PUFF], gFieldEffectArguments[0], gFieldEffectArguments[1], gFieldEffectArguments[2]); gSprites[spriteId].oam.priority = gFieldEffectArguments[3]; gSprites[spriteId].coordOffsetEnabled = TRUE; return spriteId; } void SpriteCB_PopOutOfAsh(struct Sprite *sprite) { if (sprite->animEnded) { FieldEffectStop(sprite, FLDEFF_POP_OUT_OF_ASH); } } // Task data for Task_EscapeRopeWarpOut #define tState data[0] #define tSpinDelay data[1] #define tNumTurns data[2] #define tTimer data[3] #define tOffscreen data[4] #define tMovingState data[5] #define tOffsetY data[6] #define tDirection data[15] static void Task_EscapeRopeWarpOut(u8 taskId); static void EscapeRopeWarpOutEffect_Init(struct Task *task); static void EscapeRopeWarpOutEffect_Spin(struct Task *task); static u8 SpinObjectEvent(struct ObjectEvent *playerObj, s16 *timer, s16 *numTurns); static bool32 WarpOutObjectEventUpwards(struct ObjectEvent *playerObj, s16 *movingState, s16 *offsetY); static void FieldCallback_EscapeRopeExit(void); static void Task_EscapeRopeWarpIn(u8 taskId); static void EscapeRopeWarpInEffect_Init(struct Task *task); static void EscapeRopeWarpInEffect_Spin(struct Task *task); static void (*const sEscapeRopeWarpOutEffectFuncs[])(struct Task *task) = { EscapeRopeWarpOutEffect_Init, EscapeRopeWarpOutEffect_Spin }; void StartEscapeRopeFieldEffect(void) { LockPlayerFieldControls(); FreezeObjectEvents(); CreateTask(Task_EscapeRopeWarpOut, 80); } static void Task_EscapeRopeWarpOut(u8 taskId) { sEscapeRopeWarpOutEffectFuncs[gTasks[taskId].tState](&gTasks[taskId]); } static void EscapeRopeWarpOutEffect_Init(struct Task *task) { task->tState++; task->data[13] = 64; // unused task->data[14] = GetPlayerFacingDirection(); // unused task->tDirection = DIR_NONE; } static void EscapeRopeWarpOutEffect_Spin(struct Task *task) { struct ObjectEvent *playerObj = &gObjectEvents[gPlayerAvatar.objectEventId]; s16 *data = task->data; SpinObjectEvent(playerObj, &task->tSpinDelay, &task->tNumTurns); if (tTimer < 60) { tTimer++; if (tTimer == 20) PlaySE(SE_WARP_IN); } else if (tOffscreen == FALSE && !WarpOutObjectEventUpwards(playerObj, &task->tMovingState, &task->tOffsetY)) { TryFadeOutOldMapMusic(); WarpFadeOutScreen(); tOffscreen = TRUE; } if (tOffscreen == TRUE && !gPaletteFade.active && BGMusicStopped() == TRUE) { SetObjectEventDirection(playerObj, task->tDirection); // always DIR_NONE SetWarpDestinationToEscapeWarp(); WarpIntoMap(); gFieldCallback = FieldCallback_EscapeRopeExit; SetMainCallback2(CB2_LoadMap); DestroyTask(FindTaskIdByFunc(Task_EscapeRopeWarpOut)); } } static const u8 sSpinDirections[] = { [DIR_NONE] = DIR_SOUTH, [DIR_SOUTH] = DIR_WEST, [DIR_NORTH] = DIR_EAST, [DIR_WEST] = DIR_NORTH, [DIR_EAST] = DIR_SOUTH, }; static u8 SpinObjectEvent(struct ObjectEvent *playerObj, s16 *spinDelay, s16 *numTurns) { if (!ObjectEventIsMovementOverridden(playerObj) || ObjectEventClearHeldMovementIfFinished(playerObj)) { if (*spinDelay != 0 && --(*spinDelay) != 0) return playerObj->facingDirection; ObjectEventSetHeldMovement(playerObj, GetFaceDirectionMovementAction(sSpinDirections[playerObj->facingDirection])); if (*numTurns < 12) (*numTurns)++; *spinDelay = 12 >> (*numTurns); return sSpinDirections[playerObj->facingDirection]; } return playerObj->facingDirection; } static bool32 WarpOutObjectEventUpwards(struct ObjectEvent *playerObj, s16 *movingState, s16 *offsetY) { struct Sprite *sprite = &gSprites[playerObj->spriteId]; switch (*movingState) { case 0: CameraObjectReset2(); (*movingState)++; // fallthrough case 1: sprite->y2 -= 8; (*offsetY) -= 8; if (*offsetY <= -16) { playerObj->fixedPriority = TRUE; sprite->oam.priority = 1; sprite->subpriority = 0; sprite->subspriteMode = SUBSPRITES_OFF; (*movingState)++; } break; case 2: sprite->y2 -= 8; (*offsetY) -= 8; if (*offsetY <= -88) { (*movingState)++; return FALSE; } break; case 3: return FALSE; } return TRUE; } #undef tState #undef tSpinDelay #undef tNumTurns #undef tTimer #undef tOffscreen #undef tMovingState #undef tOffsetY #undef tDirection // Task data for Task_EscapeRopeWarpIn #define tState data[0] #define tMovingState data[1] #define tOffsetY data[2] #define tPriority data[3] #define tSubpriority data[4] #define tSubspriteMode data[5] #define tTimer data[6] #define tSpinEnded data[7] #define tCurrentDir data[8] #define tSpinDelay data[9] #define tNumTurns data[10] #define tOriginalDir data[15] static void (*const sEscapeRopeWarpInEffectFuncs[])(struct Task *task) = { EscapeRopeWarpInEffect_Init, EscapeRopeWarpInEffect_Spin }; static bool32 WarpInObjectEventDownwards(struct ObjectEvent *playerObj, s16 *movingState, s16 *offsetY, s16 *priority, s16 *subpriority, s16 *subspriteMode) { struct Sprite *sprite = &gSprites[playerObj->spriteId]; switch (*movingState) { case 0: CameraObjectReset2(); *offsetY = -88; sprite->y2 -= 88; *priority = sprite->oam.priority; *subpriority = sprite->subpriority; *subspriteMode = sprite->subspriteMode; playerObj->fixedPriority = TRUE; sprite->oam.priority = 1; sprite->subpriority = 0; sprite->subspriteMode = SUBSPRITES_OFF; (*movingState)++; // fallthrough case 1: sprite->y2 += 4; (*offsetY) += 4; if (*offsetY >= -16) { sprite->oam.priority = *priority; sprite->subpriority = *subpriority; sprite->subspriteMode = *subspriteMode; (*movingState)++; } break; case 2: sprite->y2 += 4; (*offsetY) += 4; if (*offsetY >= 0) { PlaySE(SE_CLICK); CameraObjectReset1(); (*movingState)++; return FALSE; } break; case 3: return FALSE; } return TRUE; } static void FieldCallback_EscapeRopeExit(void) { Overworld_PlaySpecialMapMusic(); WarpFadeInScreen(); QuestLog_DrawPreviouslyOnQuestHeaderIfInPlaybackMode(); LockPlayerFieldControls(); FreezeObjectEvents(); gFieldCallback = NULL; gObjectEvents[gPlayerAvatar.objectEventId].invisible = TRUE; CreateTask(Task_EscapeRopeWarpIn, 0); } static void Task_EscapeRopeWarpIn(u8 taskId) { sEscapeRopeWarpInEffectFuncs[gTasks[taskId].tState](&gTasks[taskId]); } static void EscapeRopeWarpInEffect_Init(struct Task *task) { if (IsWeatherNotFadingIn()) { PlaySE(SE_WARP_OUT); task->tOriginalDir = GetPlayerFacingDirection(); task->tState++; } } static void EscapeRopeWarpInEffect_Spin(struct Task *task) { s16 *data = task->data; struct ObjectEvent *playerObj = &gObjectEvents[gPlayerAvatar.objectEventId]; bool32 moving = WarpInObjectEventDownwards(playerObj, &tMovingState, &tOffsetY, &tPriority, &tSubpriority, &tSubspriteMode); playerObj->invisible = FALSE; if (tTimer < 8) tTimer++; else if (tSpinEnded == FALSE) { tTimer++; tCurrentDir = SpinObjectEvent(playerObj, &tSpinDelay, &tNumTurns); if (tTimer >= 50 && tCurrentDir == tOriginalDir) tSpinEnded = TRUE; } if (!moving && tCurrentDir == tOriginalDir && ObjectEventCheckHeldMovementStatus(playerObj) == TRUE) { playerObj->invisible = FALSE; playerObj->fixedPriority = FALSE; UnlockPlayerFieldControls(); UnfreezeObjectEvents(); DestroyTask(FindTaskIdByFunc(Task_EscapeRopeWarpIn)); } } #undef tState #undef tMovingState #undef tOffsetY #undef tPriority #undef tSubpriority #undef tSubspriteMode #undef tTimer #undef tSpinEnded #undef tCurrentDir #undef tSpinDelay #undef tNumTurns #undef tOriginalDir static void Task_DoTeleportFieldEffect(u8 taskId); static void TeleportFieldEffectTask1(struct Task *task); static void TeleportFieldEffectTask2(struct Task *task); static void TeleportFieldEffectTask3(struct Task *task); static void TeleportFieldEffectTask4(struct Task *task); static void FieldCallback_TeleportIn(void); static void Task_DoTeleportInFieldEffect(u8 taskId); static void TeleportInFieldEffectTask1(struct Task *task); static void TeleportInFieldEffectTask2(struct Task *task); static void TeleportInFieldEffectTask3(struct Task *task); static void (*const sTeleportEffectFuncs[])(struct Task *) = { TeleportFieldEffectTask1, TeleportFieldEffectTask2, TeleportFieldEffectTask3, TeleportFieldEffectTask4 }; void CreateTeleportFieldEffectTask(void) { CreateTask(Task_DoTeleportFieldEffect, 0); } static void Task_DoTeleportFieldEffect(u8 taskId) { sTeleportEffectFuncs[gTasks[taskId].data[0]](&gTasks[taskId]); } static void TeleportFieldEffectTask1(struct Task *task) { LockPlayerFieldControls(); FreezeObjectEvents(); CameraObjectReset2(); task->data[15] = GetPlayerFacingDirection(); task->data[0]++; } static void TeleportFieldEffectTask2(struct Task *task) { u8 spinDirections[5] = { [DIR_NONE] = DIR_SOUTH, [DIR_SOUTH] = DIR_WEST, [DIR_WEST] = DIR_NORTH, [DIR_NORTH] = DIR_EAST, [DIR_EAST] = DIR_SOUTH }; struct ObjectEvent * objectEvent = &gObjectEvents[gPlayerAvatar.objectEventId]; if (task->data[1] == 0 || (--task->data[1]) == 0) { ObjectEventTurn(objectEvent, spinDirections[objectEvent->facingDirection]); task->data[1] = 8; task->data[2]++; } if (task->data[2] > 7 && task->data[15] == objectEvent->facingDirection) { task->data[0]++; task->data[1] = 4; task->data[2] = 8; task->data[3] = 1; PlaySE(SE_WARP_IN); } } static void TeleportFieldEffectTask3(struct Task *task) { u8 spinDirections[5] = {DIR_SOUTH, DIR_WEST, DIR_EAST, DIR_NORTH, DIR_SOUTH}; struct ObjectEvent * objectEvent = &gObjectEvents[gPlayerAvatar.objectEventId]; struct Sprite *sprite = &gSprites[gPlayerAvatar.spriteId]; if ((--task->data[1]) <= 0) { task->data[1] = 4; ObjectEventTurn(objectEvent, spinDirections[objectEvent->facingDirection]); } sprite->y -= task->data[3]; task->data[4] += task->data[3]; if ((--task->data[2]) <= 0 && (task->data[2] = 4, task->data[3] < 8)) { task->data[3] <<= 1; } if (task->data[4] > 8 && (sprite->oam.priority = 1, sprite->subspriteMode != SUBSPRITES_OFF)) { sprite->subspriteMode = SUBSPRITES_IGNORE_PRIORITY; } if (task->data[4] >= 0xa8) { task->data[0]++; TryFadeOutOldMapMusic(); WarpFadeOutScreen(); } } static void TeleportFieldEffectTask4(struct Task *task) { if (!gPaletteFade.active) { if (BGMusicStopped() == TRUE) { SetWarpDestinationToLastHealLocation(); WarpIntoMap(); SetMainCallback2(CB2_LoadMap); gFieldCallback = FieldCallback_TeleportIn; DestroyTask(FindTaskIdByFunc(Task_DoTeleportFieldEffect)); } } } static void (*const sTeleportInEffectFuncs[])(struct Task *) = { TeleportInFieldEffectTask1, TeleportInFieldEffectTask2, TeleportInFieldEffectTask3 }; static void FieldCallback_TeleportIn(void) { Overworld_PlaySpecialMapMusic(); WarpFadeInScreen(); QuestLog_DrawPreviouslyOnQuestHeaderIfInPlaybackMode(); LockPlayerFieldControls(); FreezeObjectEvents(); gFieldCallback = NULL; gObjectEvents[gPlayerAvatar.objectEventId].invisible = TRUE; CameraObjectReset2(); CreateTask(Task_DoTeleportInFieldEffect, 0); } static void Task_DoTeleportInFieldEffect(u8 taskId) { sTeleportInEffectFuncs[gTasks[taskId].data[0]](&gTasks[taskId]); } static void TeleportInFieldEffectTask1(struct Task *task) { struct Sprite *sprite; s16 centerToCornerVecY; if (IsWeatherNotFadingIn()) { sprite = &gSprites[gPlayerAvatar.spriteId]; centerToCornerVecY = -(sprite->centerToCornerVecY << 1); sprite->y2 = -(sprite->y + sprite->centerToCornerVecY + gSpriteCoordOffsetY + centerToCornerVecY); gObjectEvents[gPlayerAvatar.objectEventId].invisible = FALSE; task->data[0]++; task->data[1] = 8; task->data[2] = 1; task->data[14] = sprite->subspriteMode; task->data[15] = GetPlayerFacingDirection(); PlaySE(SE_WARP_IN); } } static void TeleportInFieldEffectTask2(struct Task *task) { u8 spinDirections[5] = {1, 3, 4, 2, 1}; struct ObjectEvent * objectEvent = &gObjectEvents[gPlayerAvatar.objectEventId]; struct Sprite *sprite = &gSprites[gPlayerAvatar.spriteId]; if ((sprite->y2 += task->data[1]) >= -8) { if (task->data[13] == 0) { task->data[13]++; objectEvent->triggerGroundEffectsOnMove = TRUE; sprite->subspriteMode = task->data[14]; } } else { sprite->oam.priority = 1; if (sprite->subspriteMode != SUBSPRITES_OFF) { sprite->subspriteMode = SUBSPRITES_IGNORE_PRIORITY; } } if (sprite->y2 >= -0x30 && task->data[1] > 1 && !(sprite->y2 & 1)) { task->data[1]--; } if ((--task->data[2]) == 0) { task->data[2] = 4; ObjectEventTurn(objectEvent, spinDirections[objectEvent->facingDirection]); } if (sprite->y2 >= 0) { sprite->y2 = 0; task->data[0]++; task->data[1] = 1; task->data[2] = 0; } } static void TeleportInFieldEffectTask3(struct Task *task) { u8 spinDirections[5] = {1, 3, 4, 2, 1}; struct ObjectEvent * objectEvent = &gObjectEvents[gPlayerAvatar.objectEventId]; if ((--task->data[1]) == 0) { ObjectEventTurn(objectEvent, spinDirections[objectEvent->facingDirection]); task->data[1] = 8; if ((++task->data[2]) > 4 && task->data[14] == objectEvent->facingDirection) { UnlockPlayerFieldControls(); CameraObjectReset1(); UnfreezeObjectEvents(); DestroyTask(FindTaskIdByFunc(Task_DoTeleportInFieldEffect)); } } } static void Task_ShowMon_Outdoors(u8 taskId); static void ShowMonEffect_Outdoors_1(struct Task *task); static void ShowMonEffect_Outdoors_2(struct Task *task); static void ShowMonEffect_Outdoors_3(struct Task *task); static void ShowMonEffect_Outdoors_4(struct Task *task); static void ShowMonEffect_Outdoors_5(struct Task *task); static void ShowMonEffect_Outdoors_6(struct Task *task); static void ShowMonEffect_Outdoors_7(struct Task *task); static void VBlankCB_ShowMonEffect_Outdoors(void); static void LoadFieldMoveStreaksTilemapToVram(u16 screenbase); static void Task_ShowMon_Indoors(u8 taskId); static void ShowMonEffect_Indoors_1(struct Task *task); static void ShowMonEffect_Indoors_2(struct Task *task); static void ShowMonEffect_Indoors_3(struct Task *task); static void ShowMonEffect_Indoors_4(struct Task *task); static void ShowMonEffect_Indoors_5(struct Task *task); static void ShowMonEffect_Indoors_6(struct Task *task); static void ShowMonEffect_Indoors_7(struct Task *task); static void VBlankCB_ShowMonEffect_Indoors(void); static void AnimateIndoorShowMonBg(struct Task *task); static bool8 SlideIndoorBannerOnscreen(struct Task *task); static bool8 SlideIndoorBannerOffscreen(struct Task *task); static u8 InitFieldMoveMonSprite(u32 species, u32 otId, u32 personality); static void SpriteCB_FieldMoveMonSlideOnscreen(struct Sprite *sprite); static void SpriteCB_FieldMoveMonWaitAfterCry(struct Sprite *sprite); static void SpriteCB_FieldMoveMonSlideOffscreen(struct Sprite *sprite); static void (*const sShowMonOutdoorsEffectFuncs[])(struct Task *task) = { ShowMonEffect_Outdoors_1, ShowMonEffect_Outdoors_2, ShowMonEffect_Outdoors_3, ShowMonEffect_Outdoors_4, ShowMonEffect_Outdoors_5, ShowMonEffect_Outdoors_6, ShowMonEffect_Outdoors_7 }; u32 FldEff_FieldMoveShowMon(void) { u8 taskId; if (IsMapTypeOutdoors(GetCurrentMapType()) == TRUE) taskId = CreateTask(Task_ShowMon_Outdoors, 0xFF); else taskId = CreateTask(Task_ShowMon_Indoors, 0xFF); gTasks[taskId].data[15] = InitFieldMoveMonSprite(gFieldEffectArguments[0], gFieldEffectArguments[1], gFieldEffectArguments[2]); return 0; } u32 FldEff_FieldMoveShowMonInit(void) { u32 r6 = gFieldEffectArguments[0] & 0x80000000; u8 partyIdx = gFieldEffectArguments[0]; gFieldEffectArguments[0] = GetMonData(&gPlayerParty[partyIdx], MON_DATA_SPECIES); gFieldEffectArguments[1] = GetMonData(&gPlayerParty[partyIdx], MON_DATA_OT_ID); gFieldEffectArguments[2] = GetMonData(&gPlayerParty[partyIdx], MON_DATA_PERSONALITY); gFieldEffectArguments[0] |= r6; FieldEffectStart(FLDEFF_FIELD_MOVE_SHOW_MON); FieldEffectActiveListRemove(FLDEFF_FIELD_MOVE_SHOW_MON_INIT); return 0; } static void Task_ShowMon_Outdoors(u8 taskId) { sShowMonOutdoorsEffectFuncs[gTasks[taskId].data[0]](&gTasks[taskId]); } static void ShowMonEffect_Outdoors_1(struct Task *task) { task->data[11] = GetGpuReg(REG_OFFSET_WININ); task->data[12] = GetGpuReg(REG_OFFSET_WINOUT); StoreWordInTwoHalfwords((u16 *)&task->data[13], (u32)gMain.vblankCallback); task->data[1] = WIN_RANGE(0xF0, 0xF1); task->data[2] = WIN_RANGE(0x50, 0x51); task->data[3] = WININ_WIN0_BG_ALL | WININ_WIN0_OBJ | WININ_WIN0_CLR; task->data[4] = WINOUT_WIN01_BG1 | WINOUT_WIN01_BG2 | WINOUT_WIN01_BG3 | WINOUT_WIN01_OBJ | WINOUT_WIN01_CLR; SetGpuReg(REG_OFFSET_WIN0H, task->data[1]); SetGpuReg(REG_OFFSET_WIN0V, task->data[2]); SetGpuReg(REG_OFFSET_WININ, task->data[3]); SetGpuReg(REG_OFFSET_WINOUT, task->data[4]); SetVBlankCallback(VBlankCB_ShowMonEffect_Outdoors); task->data[0]++; } static void ShowMonEffect_Outdoors_2(struct Task *task) { u16 charbase = ((GetGpuReg(REG_OFFSET_BG0CNT) >> 2) << 14); u16 screenbase = ((GetGpuReg(REG_OFFSET_BG0CNT) >> 8) << 11); CpuCopy16(sFieldMoveStreaksOutdoors_Gfx, (void *)(VRAM + charbase), 0x200); CpuFill32(0, (void *)(VRAM + screenbase), 0x800); LoadPalette(sFieldMoveStreaksOutdoors_Pal, BG_PLTT_ID(15), sizeof(sFieldMoveStreaksOutdoors_Pal)); LoadFieldMoveStreaksTilemapToVram(screenbase); task->data[0]++; } static void ShowMonEffect_Outdoors_3(struct Task *task) { s16 win0h_lo; s16 win0v_lo; s16 win0v_hi; task->data[5] -= 16; win0h_lo = ((u16)task->data[1] >> 8); win0v_lo = ((u16)task->data[2] >> 8); win0v_hi = ((u16)task->data[2] & 0xff); win0h_lo -= 16; win0v_lo -= 2; win0v_hi += 2; if (win0h_lo < 0) { win0h_lo = 0; } if (win0v_lo < 0x28) { win0v_lo = 0x28; } if (win0v_hi > 0x78) { win0v_hi = 0x78; } task->data[1] = WIN_RANGE(win0h_lo, task->data[1] & 0xff); task->data[2] = WIN_RANGE(win0v_lo, win0v_hi); if (win0h_lo == 0 && win0v_lo == 0x28 && win0v_hi == 0x78) { gSprites[task->data[15]].callback = SpriteCB_FieldMoveMonSlideOnscreen; task->data[0]++; } } static void ShowMonEffect_Outdoors_4(struct Task *task) { task->data[5] -= 16; if (gSprites[task->data[15]].data[7]) { task->data[0]++; } } static void ShowMonEffect_Outdoors_5(struct Task *task) { s16 win0v_lo; s16 win0v_hi; task->data[5] -= 16; win0v_lo = (task->data[2] >> 8); win0v_hi = (task->data[2] & 0xff); win0v_lo += 6; win0v_hi -= 6; if (win0v_lo > 0x50) { win0v_lo = 0x50; } if (win0v_hi < 0x51) { win0v_hi = 0x51; } task->data[2] = WIN_RANGE(win0v_lo, win0v_hi); if (win0v_lo == 0x50 && win0v_hi == 0x51) { task->data[0]++; } } static void ShowMonEffect_Outdoors_6(struct Task *task) { u16 bg0cnt = (GetGpuReg(REG_OFFSET_BG0CNT) >> 8) << 11; CpuFill32(0, (void *)VRAM + bg0cnt, 0x800); task->data[1] = WIN_RANGE(0x00, 0xf1); task->data[2] = WIN_RANGE(0x00, 0xa1); task->data[3] = task->data[11]; task->data[4] = task->data[12]; task->data[0]++; } static void ShowMonEffect_Outdoors_7(struct Task *task) { IntrCallback callback; LoadWordFromTwoHalfwords((u16 *)&task->data[13], (uintptr_t *)&callback); SetVBlankCallback(callback); ChangeBgX(0, 0, 0); ChangeBgY(0, 0, 0); Menu_LoadStdPal(); FreeResourcesAndDestroySprite(&gSprites[task->data[15]], task->data[15]); FieldEffectActiveListRemove(FLDEFF_FIELD_MOVE_SHOW_MON); DestroyTask(FindTaskIdByFunc(Task_ShowMon_Outdoors)); } static void VBlankCB_ShowMonEffect_Outdoors(void) { IntrCallback callback; struct Task *task = &gTasks[FindTaskIdByFunc(Task_ShowMon_Outdoors)]; LoadWordFromTwoHalfwords((u16 *)&task->data[13], (uintptr_t *)&callback); callback(); SetGpuReg(REG_OFFSET_WIN0H, task->data[1]); SetGpuReg(REG_OFFSET_WIN0V, task->data[2]); SetGpuReg(REG_OFFSET_WININ, task->data[3]); SetGpuReg(REG_OFFSET_WINOUT, task->data[4]); SetGpuReg(REG_OFFSET_BG0HOFS, task->data[5]); SetGpuReg(REG_OFFSET_BG0VOFS, task->data[6]); } static void LoadFieldMoveStreaksTilemapToVram(u16 screenbase) { u16 i; u16 *dest; dest = (u16 *)(VRAM + (10 * 32) + screenbase); for (i = 0; i < (10 * 32); i++, dest++) *dest = sFieldMoveStreaksOutdoors_Tilemap[i] | 0xF000; } static void (*const sShowMonIndoorsEffectFuncs[])(struct Task *) = { ShowMonEffect_Indoors_1, ShowMonEffect_Indoors_2, ShowMonEffect_Indoors_3, ShowMonEffect_Indoors_4, ShowMonEffect_Indoors_5, ShowMonEffect_Indoors_6, ShowMonEffect_Indoors_7 }; static void Task_ShowMon_Indoors(u8 taskId) { sShowMonIndoorsEffectFuncs[gTasks[taskId].data[0]](&gTasks[taskId]); } static void ShowMonEffect_Indoors_1(struct Task *task) { SetGpuReg(REG_OFFSET_BG0HOFS, task->data[1]); SetGpuReg(REG_OFFSET_BG0VOFS, task->data[2]); StoreWordInTwoHalfwords((u16 *)&task->data[13], (u32)gMain.vblankCallback); SetVBlankCallback(VBlankCB_ShowMonEffect_Indoors); task->data[0]++; } static void ShowMonEffect_Indoors_2(struct Task *task) { u16 charbase; u16 screenbase; charbase = ((GetGpuReg(REG_OFFSET_BG0CNT) >> 2) << 14); screenbase = ((GetGpuReg(REG_OFFSET_BG0CNT) >> 8) << 11); task->data[12] = screenbase; CpuCopy16(sFieldMoveStreaksIndoors_Gfx, (void *)(VRAM + charbase), 0x80); CpuFill32(0, (void *)(VRAM + screenbase), 0x800); LoadPalette(sFieldMoveStreaksIndoors_Pal, BG_PLTT_ID(15), sizeof(sFieldMoveStreaksIndoors_Pal)); task->data[0]++; } static void ShowMonEffect_Indoors_3(struct Task *task) { if (SlideIndoorBannerOnscreen(task)) { task->data[5] = GetGpuReg(REG_OFFSET_WININ); SetGpuReg(REG_OFFSET_WININ, (task->data[5] & 0xFF) | WININ_WIN1_BG0 | WININ_WIN1_OBJ); SetGpuReg(REG_OFFSET_WIN1H, WIN_RANGE(0x00, 0xf0)); SetGpuReg(REG_OFFSET_WIN1V, WIN_RANGE(0x28, 0x78)); gSprites[task->data[15]].callback = SpriteCB_FieldMoveMonSlideOnscreen; task->data[0]++; } AnimateIndoorShowMonBg(task); } static void ShowMonEffect_Indoors_4(struct Task *task) { AnimateIndoorShowMonBg(task); if (gSprites[task->data[15]].data[7]) { task->data[0]++; } } static void ShowMonEffect_Indoors_5(struct Task *task) { AnimateIndoorShowMonBg(task); task->data[3] = task->data[1] & 7; task->data[4] = 0; SetGpuReg(REG_OFFSET_WIN1H, WIN_RANGE(0xff, 0xff)); SetGpuReg(REG_OFFSET_WIN1V, WIN_RANGE(0xff, 0xff)); SetGpuReg(REG_OFFSET_WININ, task->data[5]); task->data[0]++; } static void ShowMonEffect_Indoors_6(struct Task *task) { AnimateIndoorShowMonBg(task); if (SlideIndoorBannerOffscreen(task)) { task->data[0]++; } } static void ShowMonEffect_Indoors_7(struct Task *task) { IntrCallback intrCallback; u16 charbase; charbase = (GetGpuReg(REG_OFFSET_BG0CNT) >> 8) << 11; CpuFill32(0, (void *)VRAM + charbase, 0x800); LoadWordFromTwoHalfwords((u16 *)&task->data[13], (uintptr_t *)&intrCallback); SetVBlankCallback(intrCallback); ChangeBgX(0, 0, 0); ChangeBgY(0, 0, 0); Menu_LoadStdPal(); FreeResourcesAndDestroySprite(&gSprites[task->data[15]], task->data[15]); FieldEffectActiveListRemove(FLDEFF_FIELD_MOVE_SHOW_MON); DestroyTask(FindTaskIdByFunc(Task_ShowMon_Indoors)); } static void VBlankCB_ShowMonEffect_Indoors(void) { IntrCallback intrCallback; struct Task *task; task = &gTasks[FindTaskIdByFunc(Task_ShowMon_Indoors)]; LoadWordFromTwoHalfwords((u16 *)&task->data[13], (uintptr_t *)&intrCallback); intrCallback(); SetGpuReg(REG_OFFSET_BG0HOFS, task->data[1]); SetGpuReg(REG_OFFSET_BG0VOFS, task->data[2]); } static void AnimateIndoorShowMonBg(struct Task *task) { task->data[1] -= 16; task->data[3] += 16; } static bool8 SlideIndoorBannerOnscreen(struct Task *task) { u16 i; u16 srcOffs; u16 dstOffs; u16 *dest; if (task->data[4] >= 32) { return TRUE; } dstOffs = (task->data[3] >> 3) & 0x1f; if (dstOffs >= task->data[4]) { dstOffs = (32 - dstOffs) & 0x1f; srcOffs = (32 - task->data[4]) & 0x1f; dest = (u16 *)(VRAM + 0x140 + (u16)task->data[12]); for (i = 0; i < 10; i++) { dest[dstOffs + i * 32] = sFieldMoveStreaksIndoors_Tilemap[srcOffs + i * 32]; dest[dstOffs + i * 32] |= 0xf000; dest[((dstOffs + 1) & 0x1f) + i * 32] = sFieldMoveStreaksIndoors_Tilemap[((srcOffs + 1) & 0x1f) + i * 32] | 0xf000; dest[((dstOffs + 1) & 0x1f) + i * 32] |= 0xf000; } task->data[4] += 2; } return FALSE; } static bool8 SlideIndoorBannerOffscreen(struct Task *task) { u16 i; u16 dstOffs; u16 *dest; if (task->data[4] >= 32) { return TRUE; } dstOffs = task->data[3] >> 3; if (dstOffs >= task->data[4]) { dstOffs = (task->data[1] >> 3) & 0x1f; dest = (u16 *)(VRAM + 0x140 + (u16)task->data[12]); for (i = 0; i < 10; i++) { dest[dstOffs + i * 32] = 0xf000; dest[((dstOffs + 1) & 0x1f) + i * 32] = 0xf000; } task->data[4] += 2; } return FALSE; } static u8 InitFieldMoveMonSprite(u32 species, u32 otId, u32 personality) { bool16 playCry; u8 monSprite; struct Sprite *sprite; playCry = (species & 0x80000000) >> 16; species &= 0x7fffffff; monSprite = CreateMonSprite_FieldMove(species, otId, personality, 0x140, 0x50, 0); sprite = &gSprites[monSprite]; sprite->callback = SpriteCallbackDummy; sprite->oam.priority = 0; sprite->data[0] = species; sprite->data[6] = playCry; return monSprite; } static void SpriteCB_FieldMoveMonSlideOnscreen(struct Sprite *sprite) { if ((sprite->x -= 20) <= 0x78) { sprite->x = 0x78; sprite->data[1] = 30; sprite->callback = SpriteCB_FieldMoveMonWaitAfterCry; if (sprite->data[6]) { PlayCry_NormalNoDucking(sprite->data[0], 0, CRY_VOLUME_RS, CRY_PRIORITY_NORMAL); } else { PlayCry_Normal(sprite->data[0], 0); } } } static void SpriteCB_FieldMoveMonWaitAfterCry(struct Sprite *sprite) { if ((--sprite->data[1]) == 0) { sprite->callback = SpriteCB_FieldMoveMonSlideOffscreen; } } static void SpriteCB_FieldMoveMonSlideOffscreen(struct Sprite *sprite) { if (sprite->x < -0x40) { sprite->data[7] = 1; } else { sprite->x -= 20; } } static void Task_FldEffUseSurf(u8 taskId); static void UseSurfEffect_1(struct Task *task); static void UseSurfEffect_2(struct Task *task); static void UseSurfEffect_3(struct Task *task); static void UseSurfEffect_4(struct Task *task); static void UseSurfEffect_5(struct Task *task); static void (*const sUseSurfEffectFuncs[])(struct Task *) = { UseSurfEffect_1, UseSurfEffect_2, UseSurfEffect_3, UseSurfEffect_4, UseSurfEffect_5, }; u8 FldEff_UseSurf(void) { u8 taskId = CreateTask(Task_FldEffUseSurf, 0xff); gTasks[taskId].data[15] = gFieldEffectArguments[0]; Overworld_ClearSavedMusic(); if (Overworld_MusicCanOverrideMapMusic(MUS_SURF)) Overworld_ChangeMusicTo(MUS_SURF); return FALSE; } static void Task_FldEffUseSurf(u8 taskId) { sUseSurfEffectFuncs[gTasks[taskId].data[0]](&gTasks[taskId]); } static void UseSurfEffect_1(struct Task *task) { LockPlayerFieldControls(); FreezeObjectEvents(); gPlayerAvatar.preventStep = TRUE; SetPlayerAvatarStateMask(PLAYER_AVATAR_FLAG_SURFING); PlayerGetDestCoords(&task->data[1], &task->data[2]); MoveCoords(gObjectEvents[gPlayerAvatar.objectEventId].movementDirection, &task->data[1], &task->data[2]); task->data[0]++; } static void UseSurfEffect_2(struct Task *task) { struct ObjectEvent * objectEvent; objectEvent = &gObjectEvents[gPlayerAvatar.objectEventId]; if (!ObjectEventIsMovementOverridden(objectEvent) || ObjectEventClearHeldMovementIfFinished(objectEvent)) { StartPlayerAvatarSummonMonForFieldMoveAnim(); ObjectEventSetHeldMovement(objectEvent, MOVEMENT_ACTION_START_ANIM_IN_DIRECTION); task->data[0]++; } } static void UseSurfEffect_3(struct Task *task) { struct ObjectEvent * objectEvent; objectEvent = &gObjectEvents[gPlayerAvatar.objectEventId]; if (ObjectEventCheckHeldMovementStatus(objectEvent)) { gFieldEffectArguments[0] = task->data[15] | 0x80000000; FieldEffectStart(FLDEFF_FIELD_MOVE_SHOW_MON_INIT); task->data[0]++; } } static void UseSurfEffect_4(struct Task *task) { struct ObjectEvent * objectEvent; if (!FieldEffectActiveListContains(FLDEFF_FIELD_MOVE_SHOW_MON)) { objectEvent = &gObjectEvents[gPlayerAvatar.objectEventId]; ObjectEventSetGraphicsId(objectEvent, GetPlayerAvatarGraphicsIdByStateId(PLAYER_AVATAR_GFX_RIDE)); ObjectEventClearHeldMovementIfFinished(objectEvent); ObjectEventSetHeldMovement(objectEvent, GetJumpSpecialMovementAction(objectEvent->movementDirection)); gFieldEffectArguments[0] = task->data[1]; gFieldEffectArguments[1] = task->data[2]; gFieldEffectArguments[2] = gPlayerAvatar.objectEventId; objectEvent->fieldEffectSpriteId = FieldEffectStart(FLDEFF_SURF_BLOB); task->data[0]++; } } static void UseSurfEffect_5(struct Task *task) { struct ObjectEvent * objectEvent; objectEvent = &gObjectEvents[gPlayerAvatar.objectEventId]; if (ObjectEventClearHeldMovementIfFinished(objectEvent)) { gPlayerAvatar.preventStep = FALSE; gPlayerAvatar.flags &= ~PLAYER_AVATAR_FLAG_CONTROLLABLE; ObjectEventSetHeldMovement(objectEvent, GetFaceDirectionMovementAction(objectEvent->movementDirection)); SetSurfBlob_BobState(objectEvent->fieldEffectSpriteId, BOB_PLAYER_AND_MON); UnfreezeObjectEvents(); UnlockPlayerFieldControls(); FieldEffectActiveListRemove(FLDEFF_USE_SURF); DestroyTask(FindTaskIdByFunc(Task_FldEffUseSurf)); SetHelpContext(HELPCONTEXT_SURFING); } } static void Task_FldEffUseVsSeeker(u8 taskId); static void UseVsSeekerEffect_1(struct Task *task); static void UseVsSeekerEffect_2(struct Task *task); static void UseVsSeekerEffect_3(struct Task *task); static void UseVsSeekerEffect_4(struct Task *task); static void (*const sUseVsSeekerEffectFuncs[])(struct Task *task) = { UseVsSeekerEffect_1, UseVsSeekerEffect_2, UseVsSeekerEffect_3, UseVsSeekerEffect_4 }; u32 FldEff_UseVsSeeker(void) { if (gQuestLogState == QL_STATE_RECORDING) QuestLogRecordPlayerAvatarGfxTransitionWithDuration(8, 89); CreateTask(Task_FldEffUseVsSeeker, 0xFF); return 0; } static void Task_FldEffUseVsSeeker(u8 taskId) { sUseVsSeekerEffectFuncs[gTasks[taskId].data[0]](&gTasks[taskId]); } static void UseVsSeekerEffect_1(struct Task *task) { LockPlayerFieldControls(); FreezeObjectEvents(); gPlayerAvatar.preventStep = TRUE; task->data[0]++; } static void UseVsSeekerEffect_2(struct Task *task) { struct ObjectEvent * playerObj = &gObjectEvents[gPlayerAvatar.objectEventId]; if (!ObjectEventIsMovementOverridden(playerObj) || ObjectEventClearHeldMovementIfFinished(playerObj)) { StartPlayerAvatarVsSeekerAnim(); ObjectEventSetHeldMovement(playerObj, MOVEMENT_ACTION_START_ANIM_IN_DIRECTION); task->data[0]++; } } static void UseVsSeekerEffect_3(struct Task *task) { struct ObjectEvent * playerObj = &gObjectEvents[gPlayerAvatar.objectEventId]; if (ObjectEventClearHeldMovementIfFinished(playerObj)) { if (gPlayerAvatar.flags & (PLAYER_AVATAR_FLAG_ACRO_BIKE | PLAYER_AVATAR_FLAG_MACH_BIKE)) ObjectEventSetGraphicsId(playerObj, GetPlayerAvatarGraphicsIdByStateId(PLAYER_AVATAR_GFX_BIKE)); else if (gPlayerAvatar.flags & PLAYER_AVATAR_FLAG_SURFING) ObjectEventSetGraphicsId(playerObj, GetPlayerAvatarGraphicsIdByStateId(PLAYER_AVATAR_GFX_RIDE)); else ObjectEventSetGraphicsId(playerObj, GetPlayerAvatarGraphicsIdByStateId(PLAYER_AVATAR_GFX_NORMAL)); ObjectEventForceSetHeldMovement(playerObj, GetFaceDirectionMovementAction(playerObj->facingDirection)); task->data[0]++; } } static void UseVsSeekerEffect_4(struct Task *task) { struct ObjectEvent * playerObj = &gObjectEvents[gPlayerAvatar.objectEventId]; if (ObjectEventClearHeldMovementIfFinished(playerObj)) { gPlayerAvatar.preventStep = FALSE; FieldEffectActiveListRemove(FLDEFF_USE_VS_SEEKER); DestroyTask(FindTaskIdByFunc(Task_FldEffUseVsSeeker)); } } static void SpriteCB_NPCFlyOut(struct Sprite *sprite); u8 FldEff_NpcFlyOut(void) { u8 spriteId = CreateSprite(gFieldEffectObjectTemplatePointers[FLDEFFOBJ_BIRD], 0x78, 0, 1); struct Sprite *sprite = &gSprites[spriteId]; sprite->oam.paletteNum = 0; sprite->oam.priority = 1; sprite->callback = SpriteCB_NPCFlyOut; sprite->data[1] = gFieldEffectArguments[0]; PlaySE(SE_M_FLY); return spriteId; } static void SpriteCB_NPCFlyOut(struct Sprite *sprite) { struct Sprite *npcSprite; sprite->x2 = Cos(sprite->data[2], 0x8c); sprite->y2 = Sin(sprite->data[2], 0x48); sprite->data[2] = (sprite->data[2] + 4) & 0xff; if (sprite->data[0]) { npcSprite = &gSprites[sprite->data[1]]; npcSprite->coordOffsetEnabled = FALSE; npcSprite->x = sprite->x + sprite->x2; npcSprite->y = sprite->y + sprite->y2 - 8; npcSprite->x2 = 0; npcSprite->y2 = 0; } if (sprite->data[2] >= 0x80) { FieldEffectStop(sprite, FLDEFF_NPCFLY_OUT); } } // Task data for Task_FlyOut / Task_FlyIn #define tState data[0] #define tMonPartyId data[1] #define tBirdSpriteId data[1] // re-used #define tTimer data[2] #define tAvatarFlags data[15] static void Task_FlyOut(u8 taskId); static void FlyOutFieldEffect_FieldMovePose(struct Task *task); static void FlyOutFieldEffect_ShowMon(struct Task *task); static void FlyOutFieldEffect_BirdLeaveBall(struct Task *task); static void FlyOutFieldEffect_WaitBirdLeave(struct Task *task); static void FlyOutFieldEffect_BirdSwoopDown(struct Task *task); static void FlyOutFieldEffect_JumpOnBird(struct Task *task); static void FlyOutFieldEffect_FlyOffWithBird(struct Task *task); static void FlyOutFieldEffect_WaitFlyOff(struct Task *task); static void FlyOutFieldEffect_End(struct Task *task); static u8 CreateFlyBirdSprite(void); static bool8 GetFlyBirdAnimCompleted(u8 flyBlobSpriteId); static void StartFlyBirdSwoopDown(u8 flyBlobSpriteId); static void SetFlyBirdPlayerSpriteId(u8 flyBlobSpriteId, u8 playerSpriteId); static void SpriteCB_FlyBirdLeaveBall(struct Sprite *sprite); static void SpriteCB_FlyBirdSwoopDown(struct Sprite *sprite); static void DoBirdSpriteWithPlayerAffineAnim(struct Sprite *sprite, u8 affineAnimId); static void SpriteCB_FlyBirdWithPlayer(struct Sprite *sprite); static void (*const sFlyOutFieldEffectFuncs[])(struct Task *) = { FlyOutFieldEffect_FieldMovePose, FlyOutFieldEffect_ShowMon, FlyOutFieldEffect_BirdLeaveBall, FlyOutFieldEffect_WaitBirdLeave, FlyOutFieldEffect_BirdSwoopDown, FlyOutFieldEffect_JumpOnBird, FlyOutFieldEffect_FlyOffWithBird, FlyOutFieldEffect_WaitFlyOff, FlyOutFieldEffect_End }; u8 FldEff_FlyOut(void) { u8 taskId = CreateTask(Task_FlyOut, 0xFE); gTasks[taskId].tMonPartyId = gFieldEffectArguments[0]; return 0; } static void Task_FlyOut(u8 taskId) { sFlyOutFieldEffectFuncs[gTasks[taskId].tState](&gTasks[taskId]); } static void FlyOutFieldEffect_FieldMovePose(struct Task *task) { struct ObjectEvent *objectEvent = &gObjectEvents[gPlayerAvatar.objectEventId]; if (!ObjectEventIsMovementOverridden(objectEvent) || ObjectEventClearHeldMovementIfFinished(objectEvent)) { task->tAvatarFlags = gPlayerAvatar.flags; gPlayerAvatar.preventStep = TRUE; SetPlayerAvatarStateMask(PLAYER_AVATAR_FLAG_ON_FOOT); StartPlayerAvatarSummonMonForFieldMoveAnim(); ObjectEventSetHeldMovement(objectEvent, MOVEMENT_ACTION_START_ANIM_IN_DIRECTION); task->tState++; } } static void FlyOutFieldEffect_ShowMon(struct Task *task) { struct ObjectEvent *objectEvent = &gObjectEvents[gPlayerAvatar.objectEventId]; if (ObjectEventClearHeldMovementIfFinished(objectEvent)) { task->tState++; gFieldEffectArguments[0] = task->tMonPartyId; FieldEffectStart(FLDEFF_FIELD_MOVE_SHOW_MON_INIT); } } static void FlyOutFieldEffect_BirdLeaveBall(struct Task *task) { if (!FieldEffectActiveListContains(FLDEFF_FIELD_MOVE_SHOW_MON)) { struct ObjectEvent *objectEvent = &gObjectEvents[gPlayerAvatar.objectEventId]; if (task->tAvatarFlags & PLAYER_AVATAR_FLAG_SURFING) { SetSurfBlob_BobState(objectEvent->fieldEffectSpriteId, BOB_MON_ONLY); SetSurfBlob_DontSyncAnim(objectEvent->fieldEffectSpriteId, FALSE); } task->tBirdSpriteId = CreateFlyBirdSprite(); task->tState++; } } static void FlyOutFieldEffect_WaitBirdLeave(struct Task *task) { if (GetFlyBirdAnimCompleted(task->tBirdSpriteId)) { task->tState++; task->tTimer = 16; SetPlayerAvatarTransitionFlags(PLAYER_AVATAR_FLAG_ON_FOOT); ObjectEventSetHeldMovement(&gObjectEvents[gPlayerAvatar.objectEventId], MOVEMENT_ACTION_FACE_LEFT); } } static void FlyOutFieldEffect_BirdSwoopDown(struct Task *task) { struct ObjectEvent *objectEvent = &gObjectEvents[gPlayerAvatar.objectEventId]; if ((task->tTimer == 0 || (--task->tTimer) == 0) && ObjectEventClearHeldMovementIfFinished(objectEvent)) { task->tState++; PlaySE(SE_M_FLY); StartFlyBirdSwoopDown(task->tBirdSpriteId); } } static void FlyOutFieldEffect_JumpOnBird(struct Task *task) { if ((++task->tTimer) >= 8) { struct ObjectEvent *objectEvent = &gObjectEvents[gPlayerAvatar.objectEventId]; ObjectEventSetGraphicsId(objectEvent, GetPlayerAvatarGraphicsIdByStateId(PLAYER_AVATAR_GFX_RIDE)); StartSpriteAnim(&gSprites[objectEvent->spriteId], ANIM_GET_ON_OFF_POKEMON_WEST); objectEvent->inanimate = TRUE; ObjectEventSetHeldMovement(objectEvent, MOVEMENT_ACTION_JUMP_IN_PLACE_LEFT); task->tState++; task->tTimer = 0; } } static void FlyOutFieldEffect_FlyOffWithBird(struct Task *task) { if ((++task->tTimer) >= 10) { struct ObjectEvent *objectEvent = &gObjectEvents[gPlayerAvatar.objectEventId]; ObjectEventClearHeldMovementIfActive(objectEvent); objectEvent->inanimate = FALSE; objectEvent->hasShadow = FALSE; SetFlyBirdPlayerSpriteId(task->tBirdSpriteId, objectEvent->spriteId); StartSpriteAnim(&gSprites[task->tBirdSpriteId], gSaveBlock2Ptr->playerGender * 2 + 1); DoBirdSpriteWithPlayerAffineAnim(&gSprites[task->tBirdSpriteId], 0); gSprites[task->tBirdSpriteId].callback = SpriteCB_FlyBirdWithPlayer; CameraObjectReset2(); task->tState++; } } static void FlyOutFieldEffect_WaitFlyOff(struct Task *task) { if (GetFlyBirdAnimCompleted(task->tBirdSpriteId)) { WarpFadeOutScreen(); task->tState++; } } static void FlyOutFieldEffect_End(struct Task *task) { if (!gPaletteFade.active) { FieldEffectActiveListRemove(FLDEFF_FLY_OUT); DestroyTask(FindTaskIdByFunc(Task_FlyOut)); } } static u8 CreateFlyBirdSprite(void) { u8 spriteId; struct Sprite *sprite; spriteId = CreateSprite(gFieldEffectObjectTemplatePointers[FLDEFFOBJ_BIRD], 255, 180, 1); sprite = &gSprites[spriteId]; sprite->oam.paletteNum = 0; sprite->oam.priority = 1; sprite->callback = SpriteCB_FlyBirdLeaveBall; return spriteId; } // Sprite data for the bird sprite #define sInitData data[0] #define sPlayerSpriteId data[6] #define sAnimCompleted data[7] static bool8 GetFlyBirdAnimCompleted(u8 spriteId) { return gSprites[spriteId].sAnimCompleted; } static void StartFlyBirdSwoopDown(u8 spriteId) { struct Sprite *sprite; sprite = &gSprites[spriteId]; sprite->callback = SpriteCB_FlyBirdSwoopDown; sprite->x = 120; sprite->y = 0; sprite->x2 = 0; sprite->y2 = 0; memset(&sprite->data[0], 0, 8 * sizeof(u16) /* zero all data cells */); sprite->data[6] = MAX_SPRITES; } static void SetFlyBirdPlayerSpriteId(u8 flyBlobSpriteId, u8 playerSpriteId) { gSprites[flyBlobSpriteId].sPlayerSpriteId = playerSpriteId; } static const union AffineAnimCmd sAffineAnim_FlyBirdLeaveBall[] = { AFFINEANIMCMD_FRAME( 8, 8, -30, 0), AFFINEANIMCMD_FRAME(28, 28, 0, 30), AFFINEANIMCMD_END }; static const union AffineAnimCmd sAffineAnim_FlyBirdReturnToBall[] = { AFFINEANIMCMD_FRAME(256, 256, 64, 0), AFFINEANIMCMD_FRAME(-10, -10, 0, 22), AFFINEANIMCMD_END }; static const union AffineAnimCmd *const sAffineAnims_FlyBirdBall[] = { sAffineAnim_FlyBirdLeaveBall, sAffineAnim_FlyBirdReturnToBall }; static void SpriteCB_FlyBirdLeaveBall(struct Sprite *sprite) { if (sprite->sAnimCompleted == FALSE) { if (sprite->sInitData == FALSE) { sprite->oam.affineMode = ST_OAM_AFFINE_DOUBLE; sprite->affineAnims = sAffineAnims_FlyBirdBall; InitSpriteAffineAnim(sprite); StartSpriteAffineAnim(sprite, 0); if (gSaveBlock2Ptr->playerGender == MALE) sprite->x = 128; else sprite->x = 118; sprite->y = -48; sprite->sInitData++; sprite->data[1] = 64; sprite->data[2] = 256; } sprite->data[1] += (sprite->data[2] >> 8); sprite->x2 = Cos(sprite->data[1], 120); sprite->y2 = Sin(sprite->data[1], 120); if (sprite->data[2] < 2048) sprite->data[2] += 96; if (sprite->data[1] > 129) { sprite->sAnimCompleted++; sprite->oam.affineMode = ST_OAM_AFFINE_OFF; FreeOamMatrix(sprite->oam.matrixNum); CalcCenterToCornerVec(sprite, sprite->oam.shape, sprite->oam.size, ST_OAM_AFFINE_OFF); } } } static void SpriteCB_FlyBirdSwoopDown(struct Sprite *sprite) { sprite->x2 = Cos(sprite->data[2], 140); sprite->y2 = Sin(sprite->data[2], 72); sprite->data[2] = (sprite->data[2] + 4) & 0xFF; if (sprite->sPlayerSpriteId != MAX_SPRITES) { struct Sprite *playerSprite = &gSprites[sprite->sPlayerSpriteId]; playerSprite->coordOffsetEnabled = FALSE; playerSprite->x = sprite->x + sprite->x2; playerSprite->y = sprite->y + sprite->y2 - 8; playerSprite->x2 = 0; playerSprite->y2 = 0; } if (sprite->data[2] >= 128) sprite->sAnimCompleted = TRUE; } static void SpriteCB_FlyBirdReturnToBall(struct Sprite *sprite) { if (sprite->sAnimCompleted == FALSE) { if (sprite->sInitData == FALSE) { sprite->oam.affineMode = ST_OAM_AFFINE_DOUBLE; sprite->affineAnims = sAffineAnims_FlyBirdBall; InitSpriteAffineAnim(sprite); StartSpriteAffineAnim(sprite, 1); if (gSaveBlock2Ptr->playerGender == MALE) sprite->x = 112; else sprite->x = 100; sprite->y = -32; sprite->sInitData++; sprite->data[1] = 240; sprite->data[2] = 2048; sprite->data[4] = 128; } sprite->data[1] += sprite->data[2] >> 8; sprite->data[3] += sprite->data[2] >> 8; sprite->data[1] &= 0xFF; sprite->x2 = Cos(sprite->data[1], 32); sprite->y2 = Sin(sprite->data[1], 120); if (sprite->data[2] > 256) sprite->data[2] -= sprite->data[4]; if (sprite->data[4] < 256) sprite->data[4] += 24; if (sprite->data[2] < 256) sprite->data[2] = 256; if (sprite->data[3] >= 60) { sprite->sAnimCompleted++; sprite->oam.affineMode = ST_OAM_AFFINE_OFF; FreeOamMatrix(sprite->oam.matrixNum); sprite->invisible = TRUE; } } } static void StartFlyBirdReturnToBall(u8 spriteId) { StartFlyBirdSwoopDown(spriteId); gSprites[spriteId].callback = SpriteCB_FlyBirdReturnToBall; } static void Task_FlyIn(u8 taskId); static void FlyInFieldEffect_BirdSwoopDown(struct Task *task); static void FlyInFieldEffect_FlyInWithBird(struct Task *task); static void FlyInFieldEffect_JumpOffBird(struct Task *task); static void FlyInFieldEffect_FieldMovePose(struct Task *task); static void FlyInFieldEffect_BirdReturnToBall(struct Task *task); static void FlyInFieldEffect_WaitBirdReturn(struct Task *task); static void FlyInFieldEffect_End(struct Task *task); static void TryChangeBirdSprite(struct Sprite *sprite); static void (*const sFlyInFieldEffectFuncs[])(struct Task *task) = { FlyInFieldEffect_BirdSwoopDown, FlyInFieldEffect_FlyInWithBird, FlyInFieldEffect_JumpOffBird, FlyInFieldEffect_FieldMovePose, FlyInFieldEffect_BirdReturnToBall, FlyInFieldEffect_WaitBirdReturn, FlyInFieldEffect_End }; u32 FldEff_FlyIn(void) { CreateTask(Task_FlyIn, 0xFE); return 0; } static void Task_FlyIn(u8 taskId) { sFlyInFieldEffectFuncs[gTasks[taskId].tState](&gTasks[taskId]); } static void FlyInFieldEffect_BirdSwoopDown(struct Task *task) { struct ObjectEvent *playerObj; playerObj = &gObjectEvents[gPlayerAvatar.objectEventId]; if (!ObjectEventIsMovementOverridden(playerObj) || ObjectEventClearHeldMovementIfFinished(playerObj)) { task->tState++; task->tTimer = 33; task->tAvatarFlags = gPlayerAvatar.flags; gPlayerAvatar.preventStep = TRUE; SetPlayerAvatarStateMask(PLAYER_AVATAR_FLAG_ON_FOOT); if (task->tAvatarFlags & PLAYER_AVATAR_FLAG_SURFING) SetSurfBlob_BobState(playerObj->fieldEffectSpriteId, BOB_NONE); ObjectEventSetGraphicsId(playerObj, GetPlayerAvatarGraphicsIdByStateId(PLAYER_AVATAR_GFX_RIDE)); CameraObjectReset2(); ObjectEventTurn(playerObj, DIR_WEST); StartSpriteAnim(&gSprites[playerObj->spriteId], ANIM_GET_ON_OFF_POKEMON_WEST); playerObj->invisible = FALSE; task->tBirdSpriteId = CreateFlyBirdSprite(); StartFlyBirdSwoopDown(task->tBirdSpriteId); SetFlyBirdPlayerSpriteId(task->tBirdSpriteId, playerObj->spriteId); StartSpriteAnim(&gSprites[task->tBirdSpriteId], gSaveBlock2Ptr->playerGender * 2 + 2); DoBirdSpriteWithPlayerAffineAnim(&gSprites[task->tBirdSpriteId], 1); gSprites[task->tBirdSpriteId].callback = SpriteCB_FlyBirdWithPlayer; } } static void FlyInFieldEffect_FlyInWithBird(struct Task *task) { struct ObjectEvent *playerObj; struct Sprite *playerSprite; TryChangeBirdSprite(&gSprites[task->tBirdSpriteId]); if (task->tTimer == 0 || (--task->tTimer) == 0) { playerObj= &gObjectEvents[gPlayerAvatar.objectEventId]; playerSprite = &gSprites[playerObj->spriteId]; SetFlyBirdPlayerSpriteId(task->tBirdSpriteId, MAX_SPRITES); playerSprite->x += playerSprite->x2; playerSprite->y += playerSprite->y2; playerSprite->x2 = 0; playerSprite->y2 = 0; task->tState++; task->tTimer = 0; } } static void FlyInFieldEffect_JumpOffBird(struct Task *task) { s16 yOffsets[18] = {-2, -4, -5, -6, -7, -8, -8, -8, -7, -7, -6, -5, -3, -2, 0, 2, 4, 8}; struct Sprite *sprite = &gSprites[gPlayerAvatar.spriteId]; sprite->y2 = yOffsets[task->tTimer]; if ((++task->tTimer) >= 18) task->tState++; } static void FlyInFieldEffect_FieldMovePose(struct Task *task) { struct ObjectEvent *playerObj; struct Sprite *playerSprite; if (GetFlyBirdAnimCompleted(task->tBirdSpriteId)) { playerObj= &gObjectEvents[gPlayerAvatar.objectEventId]; playerSprite = &gSprites[playerObj->spriteId]; playerObj->inanimate = FALSE; MoveObjectEventToMapCoords(playerObj, playerObj->currentCoords.x, playerObj->currentCoords.y); playerSprite->x2 = 0; playerSprite->y2 = 0; playerSprite->coordOffsetEnabled = TRUE; StartPlayerAvatarSummonMonForFieldMoveAnim(); ObjectEventSetHeldMovement(playerObj, MOVEMENT_ACTION_START_ANIM_IN_DIRECTION); task->tState++; } } static void FlyInFieldEffect_BirdReturnToBall(struct Task *task) { if (ObjectEventClearHeldMovementIfFinished(&gObjectEvents[gPlayerAvatar.objectEventId])) { task->tState++; StartFlyBirdReturnToBall(task->tBirdSpriteId); } } static void FlyInFieldEffect_WaitBirdReturn(struct Task *task) { if (GetFlyBirdAnimCompleted(task->tBirdSpriteId)) { DestroySprite(&gSprites[task->tBirdSpriteId]); task->tState++; task->data[1] = 16; } } static void FlyInFieldEffect_End(struct Task *task) { struct ObjectEvent *playerObj; u8 state; if ((--task->data[1]) == 0) { playerObj = &gObjectEvents[gPlayerAvatar.objectEventId]; state = PLAYER_AVATAR_GFX_NORMAL; if (task->tAvatarFlags & PLAYER_AVATAR_FLAG_SURFING) { state = PLAYER_AVATAR_GFX_RIDE; SetSurfBlob_BobState(playerObj->fieldEffectSpriteId, BOB_PLAYER_AND_MON); } ObjectEventSetGraphicsId(playerObj, GetPlayerAvatarGraphicsIdByStateId(state)); ObjectEventTurn(playerObj, DIR_SOUTH); gPlayerAvatar.flags = task->tAvatarFlags; gPlayerAvatar.preventStep = FALSE; FieldEffectActiveListRemove(FLDEFF_FLY_IN); DestroyTask(FindTaskIdByFunc(Task_FlyIn)); } } #undef tState #undef tMonPartyId #undef tBirdSpriteId #undef tTimer #undef tAvatarFlags static const union AffineAnimCmd sAffineAnim_FlyBirdOutOfMap[] = { AFFINEANIMCMD_FRAME(24, 24, 0, 1), AFFINEANIMCMD_JUMP(0) }; static const union AffineAnimCmd sAffineAnim_FlyBirdIntoMap[] = { AFFINEANIMCMD_FRAME(512, 512, 0, 1), AFFINEANIMCMD_FRAME(-16, -16, 0, 1), AFFINEANIMCMD_JUMP(1) }; static const union AffineAnimCmd *const sAffineAnims_FlyBirdWithPlayer[] = { sAffineAnim_FlyBirdOutOfMap, sAffineAnim_FlyBirdIntoMap }; static void DoBirdSpriteWithPlayerAffineAnim(struct Sprite *sprite, u8 affineAnimId) { sprite->oam.affineMode = ST_OAM_AFFINE_DOUBLE; sprite->affineAnims = sAffineAnims_FlyBirdWithPlayer; InitSpriteAffineAnim(sprite); StartSpriteAffineAnim(sprite, affineAnimId); } static void SpriteCB_FlyBirdWithPlayer(struct Sprite *sprite) { sprite->x2 = Cos(sprite->data[2], 180); sprite->y2 = Sin(sprite->data[2], 72); sprite->data[2] = (sprite->data[2] + 2) & 0xFF; if (sprite->sPlayerSpriteId != MAX_SPRITES) { struct Sprite *playerSprite; playerSprite = &gSprites[sprite->sPlayerSpriteId]; playerSprite->coordOffsetEnabled = FALSE; playerSprite->x = sprite->x + sprite->x2; playerSprite->y = sprite->y + sprite->y2 - 8; playerSprite->x2 = 0; playerSprite->y2 = 0; } if (sprite->data[2] >= 128) { sprite->sAnimCompleted = TRUE; sprite->oam.affineMode = ST_OAM_AFFINE_OFF; FreeOamMatrix(sprite->oam.matrixNum); CalcCenterToCornerVec(sprite, sprite->oam.shape, sprite->oam.size, ST_OAM_AFFINE_OFF); } } #undef sInitData #undef sPlayerSpriteId #undef sAnimCompleted static void TryChangeBirdSprite(struct Sprite *sprite) { if (sprite->oam.affineMode != ST_OAM_AFFINE_OFF) { if (gOamMatrices[sprite->oam.matrixNum].a == 0x100 || gOamMatrices[sprite->oam.matrixNum].d == 0x100) { sprite->oam.affineMode = ST_OAM_AFFINE_OFF; FreeOamMatrix(sprite->oam.matrixNum); CalcCenterToCornerVec(sprite, sprite->oam.shape, sprite->oam.size, ST_OAM_AFFINE_OFF); StartSpriteAnim(sprite, 0); sprite->callback = SpriteCB_FlyBirdSwoopDown; } } } static void Task_MoveDeoxysRock_Step(u8 taskId); u32 FldEff_MoveDeoxysRock(void) { u8 taskId; u8 objectEventIdBuffer; s32 x; s32 y; struct ObjectEvent * objectEvent; if (!TryGetObjectEventIdByLocalIdAndMap(gFieldEffectArguments[0], gFieldEffectArguments[1], gFieldEffectArguments[2], &objectEventIdBuffer)) { objectEvent = &gObjectEvents[objectEventIdBuffer]; x = objectEvent->currentCoords.x - 7; y = objectEvent->currentCoords.y - 7; x = (gFieldEffectArguments[3] - x) * 16; y = (gFieldEffectArguments[4] - y) * 16; ShiftObjectEventCoords(objectEvent, gFieldEffectArguments[3] + 7, gFieldEffectArguments[4] + 7); taskId = CreateTask(Task_MoveDeoxysRock_Step, 0x50); gTasks[taskId].data[1] = objectEvent->spriteId; gTasks[taskId].data[2] = gSprites[objectEvent->spriteId].x + x; gTasks[taskId].data[3] = gSprites[objectEvent->spriteId].y + y; gTasks[taskId].data[8] = gFieldEffectArguments[5]; gTasks[taskId].data[9] = objectEventIdBuffer; } return FALSE; } static void Task_MoveDeoxysRock_Step(u8 taskId) { s16 *data = gTasks[taskId].data; struct Sprite *sprite = &gSprites[data[1]]; struct ObjectEvent * objectEvent; switch (data[0]) { case 0: data[4] = sprite->x << 4; data[5] = sprite->y << 4; // UB: Possible divide by zero data[6] = SAFE_DIV(((data[2] << 4) - data[4]), data[8]); data[7] = SAFE_DIV(((data[3] << 4) - data[5]), data[8]); data[0]++; // fallthrough case 1: if (data[8] != 0) { data[8]--; data[4] += data[6]; data[5] += data[7]; sprite->x = data[4] >> 4; sprite->y = data[5] >> 4; } else { objectEvent = &gObjectEvents[data[9]]; sprite->x = data[2]; sprite->y = data[3]; ShiftStillObjectEventCoords(objectEvent); objectEvent->triggerGroundEffectsOnStop = TRUE; FieldEffectActiveListRemove(FLDEFF_MOVE_DEOXYS_ROCK); DestroyTask(taskId); } break; } } static void Task_DestroyDeoxysRock(u8 taskId); static void DestroyDeoxysRockEffect_CameraShake(s16 *data, u8 taskId); static void DestroyDeoxysRockEffect_RockFragments(s16 *data, u8 taskId); static void DestroyDeoxysRockEffect_WaitAndEnd(s16 *data, u8 taskId); static void CreateDeoxysRockFragments(struct Sprite *sprite); static void SpriteCB_DeoxysRockFragment(struct Sprite *sprite); static void (*const sDestroyDeoxysRockEffectFuncs[])(s16 *data, u8 taskId) = { DestroyDeoxysRockEffect_CameraShake, DestroyDeoxysRockEffect_RockFragments, DestroyDeoxysRockEffect_WaitAndEnd }; static const struct SpriteFrameImage sImages_DeoxysRockFragment[] = { {sRockFragment_TopLeft, 0x20}, {sRockFragment_TopRight, 0x20}, {sRockFragment_BottomLeft, 0x20}, {sRockFragment_BottomRight, 0x20} }; static const union AnimCmd sAnim_RockFragment_TopLeft[] = { ANIMCMD_FRAME(0, 0), ANIMCMD_END }; static const union AnimCmd sAnim_RockFragment_TopRight[] = { ANIMCMD_FRAME(1, 0), ANIMCMD_END }; static const union AnimCmd sAnim_RockFragment_BottomLeft[] = { ANIMCMD_FRAME(2, 0), ANIMCMD_END }; static const union AnimCmd sAnim_RockFragment_BottomRight[] = { ANIMCMD_FRAME(3, 0), ANIMCMD_END }; static const union AnimCmd *const sAnims_DeoxysRockFragment[] = { sAnim_RockFragment_TopLeft, sAnim_RockFragment_TopRight, sAnim_RockFragment_BottomLeft, sAnim_RockFragment_BottomRight }; static const struct SpriteTemplate sSpriteTemplate_DeoxysRockFragment = { .tileTag = TAG_NONE, .paletteTag = 4371, .oam = &sOamData_8x8, .anims = sAnims_DeoxysRockFragment, .images = sImages_DeoxysRockFragment, .affineAnims = gDummySpriteAffineAnimTable, .callback = SpriteCB_DeoxysRockFragment }; // Task data for Task_DestroyDeoxysRock #define tState data[1] #define tObjectEventId data[2] #define tTimer data[3] #define tCameraTaskId data[5] #define tLocalId data[6] #define tMapNum data[7] #define tMapGroup data[8] u32 FldEff_DestroyDeoxysRock(void) { u8 taskId; u8 objectEventId; if (!TryGetObjectEventIdByLocalIdAndMap(gFieldEffectArguments[0], gFieldEffectArguments[1], gFieldEffectArguments[2], &objectEventId)) { taskId = CreateTask(Task_DestroyDeoxysRock, 80); gTasks[taskId].data[2] = objectEventId; gTasks[taskId].tLocalId = gFieldEffectArguments[0]; gTasks[taskId].tMapNum = gFieldEffectArguments[1]; gTasks[taskId].tMapGroup = gFieldEffectArguments[2]; } else FieldEffectActiveListRemove(FLDEFF_DESTROY_DEOXYS_ROCK); return FALSE; } // Task data for Task_DeoxysRockCameraShake #define tShakeDelay data[0] #define tShakeUp data[1] #define tShake data[5] #define tEndDelay data[6] #define tEnding data[7] static void Task_DeoxysRockCameraShake(u8 taskId) { s16 *data = gTasks[taskId].data; if (data[7] != 0) { if (++data[6] > 20) { data[6] = 0; if (data[5] != 0) data[5]--; } } else data[5] = 4; if (++data[0] > 1) { data[0] = 0; if (++data[1] & 1) SetCameraPanning(0, -data[5]); else SetCameraPanning(0, data[5]); } UpdateCameraPanning(); if (data[5] == 0) DestroyTask(taskId); } static void StartEndingDeoxysRockCameraShake(u8 taskId) { gTasks[taskId].data[7] = 1; } #undef tShakeDelay #undef tShakeUp #undef tShake #undef tEndDelay #undef tEnding static void Task_DestroyDeoxysRock(u8 taskId) { s16 *data = gTasks[taskId].data; InstallCameraPanAheadCallback(); SetCameraPanningCallback(NULL); sDestroyDeoxysRockEffectFuncs[tState](data, taskId); } static void DestroyDeoxysRockEffect_CameraShake(s16 *data, u8 taskId) { u8 newTaskId = CreateTask(Task_DeoxysRockCameraShake, 90); PlaySE(SE_THUNDER2); tCameraTaskId = newTaskId; tState++; } static void DestroyDeoxysRockEffect_RockFragments(s16 *data, u8 taskId) { if (++tTimer > 120) { struct Sprite *sprite = &gSprites[gObjectEvents[tObjectEventId].spriteId]; gObjectEvents[tObjectEventId].invisible = TRUE; BlendPalettes(PALETTES_BG, 0x10, RGB_WHITE); BeginNormalPaletteFade(PALETTES_BG, 0, 0x10, 0, RGB_WHITE); CreateDeoxysRockFragments(sprite); PlaySE(SE_THUNDER); StartEndingDeoxysRockCameraShake(tCameraTaskId); tTimer = 0; tState++; } } static void DestroyDeoxysRockEffect_WaitAndEnd(s16 *data, u8 taskId) { if (!gPaletteFade.active && !FuncIsActiveTask(Task_DeoxysRockCameraShake)) { InstallCameraPanAheadCallback(); RemoveObjectEventByLocalIdAndMap(tLocalId, tMapNum, tMapGroup); FieldEffectActiveListRemove(FLDEFF_DESTROY_DEOXYS_ROCK); DestroyTask(taskId); } } #undef tState #undef tObjectEventId #undef tTimer #undef tCameraTaskId #undef tLocalId #undef tMapNum #undef tMapGroup static void CreateDeoxysRockFragments(struct Sprite *sprite) { int i; int xPos = (s16)gTotalCameraPixelOffsetX + sprite->x + sprite->x2; int yPos = (s16)gTotalCameraPixelOffsetY + sprite->y + sprite->y2 - 4; for (i = 0; i < 4; i++) { u8 spriteId = CreateSprite(&sSpriteTemplate_DeoxysRockFragment, xPos, yPos, 0); if (spriteId != MAX_SPRITES) { StartSpriteAnim(&gSprites[spriteId], i); gSprites[spriteId].data[0] = i; gSprites[spriteId].oam.paletteNum = sprite->oam.paletteNum; } } } static void SpriteCB_DeoxysRockFragment(struct Sprite *sprite) { switch (sprite->data[0]) { case 0: sprite->x -= 16; sprite->y -= 12; break; case 1: sprite->x += 16; sprite->y -= 12; break; case 2: sprite->x -= 16; sprite->y += 12; break; case 3: sprite->x += 16; sprite->y += 12; break; } if (sprite->x < -4 || sprite->x > DISPLAY_WIDTH + 4 || sprite->y < -4 || sprite->y > DISPLAY_HEIGHT + 4) DestroySprite(sprite); } static void Task_PhotoFlash(u8 taskId) { if (!gPaletteFade.active) { FieldEffectActiveListRemove(FLDEFF_PHOTO_FLASH); DestroyTask(taskId); } } // Bug: Return value should be u32, not void void FldEff_PhotoFlash(void) { BlendPalettes(PALETTES_ALL, 0x10, RGB_WHITE); BeginNormalPaletteFade(PALETTES_ALL, -1, 0x0F, 0x00, RGB_WHITE); CreateTask(Task_PhotoFlash, 90); }
770160bb8136c97dcdaa0b06947d145039624f37
8a51a96f61699f0318315ccc89cef39f6866f2b5
/src/backend/utils/adt/varlena.c
72e1e24fe02c24217f354e931808bed941843dc0
[ "PostgreSQL" ]
permissive
postgres/postgres
979febf2b41c00090d1256228f768f33e7ef3b6f
b5934bfd6071fed3a38cea0cfaa93afda63d9c0c
refs/heads/master
2023-08-31T00:10:01.373472
2023-08-30T23:07:48
2023-08-30T23:07:48
927,442
13,691
4,807
NOASSERTION
2023-09-09T13:59:15
2010-09-21T11:35:45
C
UTF-8
C
false
false
168,314
c
varlena.c
/*------------------------------------------------------------------------- * * varlena.c * Functions for the variable-length built-in types. * * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * * IDENTIFICATION * src/backend/utils/adt/varlena.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include <ctype.h> #include <limits.h> #include "access/detoast.h" #include "access/toast_compression.h" #include "catalog/pg_collation.h" #include "catalog/pg_type.h" #include "common/hashfn.h" #include "common/int.h" #include "common/unicode_norm.h" #include "funcapi.h" #include "lib/hyperloglog.h" #include "libpq/pqformat.h" #include "miscadmin.h" #include "nodes/execnodes.h" #include "parser/scansup.h" #include "port/pg_bswap.h" #include "regex/regex.h" #include "utils/builtins.h" #include "utils/bytea.h" #include "utils/guc.h" #include "utils/lsyscache.h" #include "utils/memutils.h" #include "utils/pg_locale.h" #include "utils/sortsupport.h" #include "utils/varlena.h" /* GUC variable */ int bytea_output = BYTEA_OUTPUT_HEX; typedef struct varlena VarString; /* * State for text_position_* functions. */ typedef struct { bool is_multibyte_char_in_char; /* need to check char boundaries? */ char *str1; /* haystack string */ char *str2; /* needle string */ int len1; /* string lengths in bytes */ int len2; /* Skip table for Boyer-Moore-Horspool search algorithm: */ int skiptablemask; /* mask for ANDing with skiptable subscripts */ int skiptable[256]; /* skip distance for given mismatched char */ char *last_match; /* pointer to last match in 'str1' */ /* * Sometimes we need to convert the byte position of a match to a * character position. These store the last position that was converted, * so that on the next call, we can continue from that point, rather than * count characters from the very beginning. */ char *refpoint; /* pointer within original haystack string */ int refpos; /* 0-based character offset of the same point */ } TextPositionState; typedef struct { char *buf1; /* 1st string, or abbreviation original string * buf */ char *buf2; /* 2nd string, or abbreviation strxfrm() buf */ int buflen1; /* Allocated length of buf1 */ int buflen2; /* Allocated length of buf2 */ int last_len1; /* Length of last buf1 string/strxfrm() input */ int last_len2; /* Length of last buf2 string/strxfrm() blob */ int last_returned; /* Last comparison result (cache) */ bool cache_blob; /* Does buf2 contain strxfrm() blob, etc? */ bool collate_c; Oid typid; /* Actual datatype (text/bpchar/bytea/name) */ hyperLogLogState abbr_card; /* Abbreviated key cardinality state */ hyperLogLogState full_card; /* Full key cardinality state */ double prop_card; /* Required cardinality proportion */ pg_locale_t locale; } VarStringSortSupport; /* * Output data for split_text(): we output either to an array or a table. * tupstore and tupdesc must be set up in advance to output to a table. */ typedef struct { ArrayBuildState *astate; Tuplestorestate *tupstore; TupleDesc tupdesc; } SplitTextOutputData; /* * This should be large enough that most strings will fit, but small enough * that we feel comfortable putting it on the stack */ #define TEXTBUFLEN 1024 #define DatumGetVarStringP(X) ((VarString *) PG_DETOAST_DATUM(X)) #define DatumGetVarStringPP(X) ((VarString *) PG_DETOAST_DATUM_PACKED(X)) static int varstrfastcmp_c(Datum x, Datum y, SortSupport ssup); static int bpcharfastcmp_c(Datum x, Datum y, SortSupport ssup); static int namefastcmp_c(Datum x, Datum y, SortSupport ssup); static int varlenafastcmp_locale(Datum x, Datum y, SortSupport ssup); static int namefastcmp_locale(Datum x, Datum y, SortSupport ssup); static int varstrfastcmp_locale(char *a1p, int len1, char *a2p, int len2, SortSupport ssup); static Datum varstr_abbrev_convert(Datum original, SortSupport ssup); static bool varstr_abbrev_abort(int memtupcount, SortSupport ssup); static int32 text_length(Datum str); static text *text_catenate(text *t1, text *t2); static text *text_substring(Datum str, int32 start, int32 length, bool length_not_specified); static text *text_overlay(text *t1, text *t2, int sp, int sl); static int text_position(text *t1, text *t2, Oid collid); static void text_position_setup(text *t1, text *t2, Oid collid, TextPositionState *state); static bool text_position_next(TextPositionState *state); static char *text_position_next_internal(char *start_ptr, TextPositionState *state); static char *text_position_get_match_ptr(TextPositionState *state); static int text_position_get_match_pos(TextPositionState *state); static void text_position_cleanup(TextPositionState *state); static void check_collation_set(Oid collid); static int text_cmp(text *arg1, text *arg2, Oid collid); static bytea *bytea_catenate(bytea *t1, bytea *t2); static bytea *bytea_substring(Datum str, int S, int L, bool length_not_specified); static bytea *bytea_overlay(bytea *t1, bytea *t2, int sp, int sl); static void appendStringInfoText(StringInfo str, const text *t); static bool split_text(FunctionCallInfo fcinfo, SplitTextOutputData *tstate); static void split_text_accum_result(SplitTextOutputData *tstate, text *field_value, text *null_string, Oid collation); static text *array_to_text_internal(FunctionCallInfo fcinfo, ArrayType *v, const char *fldsep, const char *null_string); static StringInfo makeStringAggState(FunctionCallInfo fcinfo); static bool text_format_parse_digits(const char **ptr, const char *end_ptr, int *value); static const char *text_format_parse_format(const char *start_ptr, const char *end_ptr, int *argpos, int *widthpos, int *flags, int *width); static void text_format_string_conversion(StringInfo buf, char conversion, FmgrInfo *typOutputInfo, Datum value, bool isNull, int flags, int width); static void text_format_append_string(StringInfo buf, const char *str, int flags, int width); /***************************************************************************** * CONVERSION ROUTINES EXPORTED FOR USE BY C CODE * *****************************************************************************/ /* * cstring_to_text * * Create a text value from a null-terminated C string. * * The new text value is freshly palloc'd with a full-size VARHDR. */ text * cstring_to_text(const char *s) { return cstring_to_text_with_len(s, strlen(s)); } /* * cstring_to_text_with_len * * Same as cstring_to_text except the caller specifies the string length; * the string need not be null_terminated. */ text * cstring_to_text_with_len(const char *s, int len) { text *result = (text *) palloc(len + VARHDRSZ); SET_VARSIZE(result, len + VARHDRSZ); memcpy(VARDATA(result), s, len); return result; } /* * text_to_cstring * * Create a palloc'd, null-terminated C string from a text value. * * We support being passed a compressed or toasted text value. * This is a bit bogus since such values shouldn't really be referred to as * "text *", but it seems useful for robustness. If we didn't handle that * case here, we'd need another routine that did, anyway. */ char * text_to_cstring(const text *t) { /* must cast away the const, unfortunately */ text *tunpacked = pg_detoast_datum_packed(unconstify(text *, t)); int len = VARSIZE_ANY_EXHDR(tunpacked); char *result; result = (char *) palloc(len + 1); memcpy(result, VARDATA_ANY(tunpacked), len); result[len] = '\0'; if (tunpacked != t) pfree(tunpacked); return result; } /* * text_to_cstring_buffer * * Copy a text value into a caller-supplied buffer of size dst_len. * * The text string is truncated if necessary to fit. The result is * guaranteed null-terminated (unless dst_len == 0). * * We support being passed a compressed or toasted text value. * This is a bit bogus since such values shouldn't really be referred to as * "text *", but it seems useful for robustness. If we didn't handle that * case here, we'd need another routine that did, anyway. */ void text_to_cstring_buffer(const text *src, char *dst, size_t dst_len) { /* must cast away the const, unfortunately */ text *srcunpacked = pg_detoast_datum_packed(unconstify(text *, src)); size_t src_len = VARSIZE_ANY_EXHDR(srcunpacked); if (dst_len > 0) { dst_len--; if (dst_len >= src_len) dst_len = src_len; else /* ensure truncation is encoding-safe */ dst_len = pg_mbcliplen(VARDATA_ANY(srcunpacked), src_len, dst_len); memcpy(dst, VARDATA_ANY(srcunpacked), dst_len); dst[dst_len] = '\0'; } if (srcunpacked != src) pfree(srcunpacked); } /***************************************************************************** * USER I/O ROUTINES * *****************************************************************************/ #define VAL(CH) ((CH) - '0') #define DIG(VAL) ((VAL) + '0') /* * byteain - converts from printable representation of byte array * * Non-printable characters must be passed as '\nnn' (octal) and are * converted to internal form. '\' must be passed as '\\'. * ereport(ERROR, ...) if bad form. * * BUGS: * The input is scanned twice. * The error checking of input is minimal. */ Datum byteain(PG_FUNCTION_ARGS) { char *inputText = PG_GETARG_CSTRING(0); Node *escontext = fcinfo->context; char *tp; char *rp; int bc; bytea *result; /* Recognize hex input */ if (inputText[0] == '\\' && inputText[1] == 'x') { size_t len = strlen(inputText); bc = (len - 2) / 2 + VARHDRSZ; /* maximum possible length */ result = palloc(bc); bc = hex_decode_safe(inputText + 2, len - 2, VARDATA(result), escontext); SET_VARSIZE(result, bc + VARHDRSZ); /* actual length */ PG_RETURN_BYTEA_P(result); } /* Else, it's the traditional escaped style */ for (bc = 0, tp = inputText; *tp != '\0'; bc++) { if (tp[0] != '\\') tp++; else if ((tp[0] == '\\') && (tp[1] >= '0' && tp[1] <= '3') && (tp[2] >= '0' && tp[2] <= '7') && (tp[3] >= '0' && tp[3] <= '7')) tp += 4; else if ((tp[0] == '\\') && (tp[1] == '\\')) tp += 2; else { /* * one backslash, not followed by another or ### valid octal */ ereturn(escontext, (Datum) 0, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("invalid input syntax for type %s", "bytea"))); } } bc += VARHDRSZ; result = (bytea *) palloc(bc); SET_VARSIZE(result, bc); tp = inputText; rp = VARDATA(result); while (*tp != '\0') { if (tp[0] != '\\') *rp++ = *tp++; else if ((tp[0] == '\\') && (tp[1] >= '0' && tp[1] <= '3') && (tp[2] >= '0' && tp[2] <= '7') && (tp[3] >= '0' && tp[3] <= '7')) { bc = VAL(tp[1]); bc <<= 3; bc += VAL(tp[2]); bc <<= 3; *rp++ = bc + VAL(tp[3]); tp += 4; } else if ((tp[0] == '\\') && (tp[1] == '\\')) { *rp++ = '\\'; tp += 2; } else { /* * We should never get here. The first pass should not allow it. */ ereturn(escontext, (Datum) 0, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("invalid input syntax for type %s", "bytea"))); } } PG_RETURN_BYTEA_P(result); } /* * byteaout - converts to printable representation of byte array * * In the traditional escaped format, non-printable characters are * printed as '\nnn' (octal) and '\' as '\\'. */ Datum byteaout(PG_FUNCTION_ARGS) { bytea *vlena = PG_GETARG_BYTEA_PP(0); char *result; char *rp; if (bytea_output == BYTEA_OUTPUT_HEX) { /* Print hex format */ rp = result = palloc(VARSIZE_ANY_EXHDR(vlena) * 2 + 2 + 1); *rp++ = '\\'; *rp++ = 'x'; rp += hex_encode(VARDATA_ANY(vlena), VARSIZE_ANY_EXHDR(vlena), rp); } else if (bytea_output == BYTEA_OUTPUT_ESCAPE) { /* Print traditional escaped format */ char *vp; uint64 len; int i; len = 1; /* empty string has 1 char */ vp = VARDATA_ANY(vlena); for (i = VARSIZE_ANY_EXHDR(vlena); i != 0; i--, vp++) { if (*vp == '\\') len += 2; else if ((unsigned char) *vp < 0x20 || (unsigned char) *vp > 0x7e) len += 4; else len++; } /* * In principle len can't overflow uint32 if the input fit in 1GB, but * for safety let's check rather than relying on palloc's internal * check. */ if (len > MaxAllocSize) ereport(ERROR, (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), errmsg_internal("result of bytea output conversion is too large"))); rp = result = (char *) palloc(len); vp = VARDATA_ANY(vlena); for (i = VARSIZE_ANY_EXHDR(vlena); i != 0; i--, vp++) { if (*vp == '\\') { *rp++ = '\\'; *rp++ = '\\'; } else if ((unsigned char) *vp < 0x20 || (unsigned char) *vp > 0x7e) { int val; /* holds unprintable chars */ val = *vp; rp[0] = '\\'; rp[3] = DIG(val & 07); val >>= 3; rp[2] = DIG(val & 07); val >>= 3; rp[1] = DIG(val & 03); rp += 4; } else *rp++ = *vp; } } else { elog(ERROR, "unrecognized bytea_output setting: %d", bytea_output); rp = result = NULL; /* keep compiler quiet */ } *rp = '\0'; PG_RETURN_CSTRING(result); } /* * bytearecv - converts external binary format to bytea */ Datum bytearecv(PG_FUNCTION_ARGS) { StringInfo buf = (StringInfo) PG_GETARG_POINTER(0); bytea *result; int nbytes; nbytes = buf->len - buf->cursor; result = (bytea *) palloc(nbytes + VARHDRSZ); SET_VARSIZE(result, nbytes + VARHDRSZ); pq_copymsgbytes(buf, VARDATA(result), nbytes); PG_RETURN_BYTEA_P(result); } /* * byteasend - converts bytea to binary format * * This is a special case: just copy the input... */ Datum byteasend(PG_FUNCTION_ARGS) { bytea *vlena = PG_GETARG_BYTEA_P_COPY(0); PG_RETURN_BYTEA_P(vlena); } Datum bytea_string_agg_transfn(PG_FUNCTION_ARGS) { StringInfo state; state = PG_ARGISNULL(0) ? NULL : (StringInfo) PG_GETARG_POINTER(0); /* Append the value unless null, preceding it with the delimiter. */ if (!PG_ARGISNULL(1)) { bytea *value = PG_GETARG_BYTEA_PP(1); bool isfirst = false; /* * You might think we can just throw away the first delimiter, however * we must keep it as we may be a parallel worker doing partial * aggregation building a state to send to the main process. We need * to keep the delimiter of every aggregation so that the combine * function can properly join up the strings of two separately * partially aggregated results. The first delimiter is only stripped * off in the final function. To know how much to strip off the front * of the string, we store the length of the first delimiter in the * StringInfo's cursor field, which we don't otherwise need here. */ if (state == NULL) { state = makeStringAggState(fcinfo); isfirst = true; } if (!PG_ARGISNULL(2)) { bytea *delim = PG_GETARG_BYTEA_PP(2); appendBinaryStringInfo(state, VARDATA_ANY(delim), VARSIZE_ANY_EXHDR(delim)); if (isfirst) state->cursor = VARSIZE_ANY_EXHDR(delim); } appendBinaryStringInfo(state, VARDATA_ANY(value), VARSIZE_ANY_EXHDR(value)); } /* * The transition type for string_agg() is declared to be "internal", * which is a pass-by-value type the same size as a pointer. */ if (state) PG_RETURN_POINTER(state); PG_RETURN_NULL(); } Datum bytea_string_agg_finalfn(PG_FUNCTION_ARGS) { StringInfo state; /* cannot be called directly because of internal-type argument */ Assert(AggCheckCallContext(fcinfo, NULL)); state = PG_ARGISNULL(0) ? NULL : (StringInfo) PG_GETARG_POINTER(0); if (state != NULL) { /* As per comment in transfn, strip data before the cursor position */ bytea *result; int strippedlen = state->len - state->cursor; result = (bytea *) palloc(strippedlen + VARHDRSZ); SET_VARSIZE(result, strippedlen + VARHDRSZ); memcpy(VARDATA(result), &state->data[state->cursor], strippedlen); PG_RETURN_BYTEA_P(result); } else PG_RETURN_NULL(); } /* * textin - converts cstring to internal representation */ Datum textin(PG_FUNCTION_ARGS) { char *inputText = PG_GETARG_CSTRING(0); PG_RETURN_TEXT_P(cstring_to_text(inputText)); } /* * textout - converts internal representation to cstring */ Datum textout(PG_FUNCTION_ARGS) { Datum txt = PG_GETARG_DATUM(0); PG_RETURN_CSTRING(TextDatumGetCString(txt)); } /* * textrecv - converts external binary format to text */ Datum textrecv(PG_FUNCTION_ARGS) { StringInfo buf = (StringInfo) PG_GETARG_POINTER(0); text *result; char *str; int nbytes; str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes); result = cstring_to_text_with_len(str, nbytes); pfree(str); PG_RETURN_TEXT_P(result); } /* * textsend - converts text to binary format */ Datum textsend(PG_FUNCTION_ARGS) { text *t = PG_GETARG_TEXT_PP(0); StringInfoData buf; pq_begintypsend(&buf); pq_sendtext(&buf, VARDATA_ANY(t), VARSIZE_ANY_EXHDR(t)); PG_RETURN_BYTEA_P(pq_endtypsend(&buf)); } /* * unknownin - converts cstring to internal representation */ Datum unknownin(PG_FUNCTION_ARGS) { char *str = PG_GETARG_CSTRING(0); /* representation is same as cstring */ PG_RETURN_CSTRING(pstrdup(str)); } /* * unknownout - converts internal representation to cstring */ Datum unknownout(PG_FUNCTION_ARGS) { /* representation is same as cstring */ char *str = PG_GETARG_CSTRING(0); PG_RETURN_CSTRING(pstrdup(str)); } /* * unknownrecv - converts external binary format to unknown */ Datum unknownrecv(PG_FUNCTION_ARGS) { StringInfo buf = (StringInfo) PG_GETARG_POINTER(0); char *str; int nbytes; str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes); /* representation is same as cstring */ PG_RETURN_CSTRING(str); } /* * unknownsend - converts unknown to binary format */ Datum unknownsend(PG_FUNCTION_ARGS) { /* representation is same as cstring */ char *str = PG_GETARG_CSTRING(0); StringInfoData buf; pq_begintypsend(&buf); pq_sendtext(&buf, str, strlen(str)); PG_RETURN_BYTEA_P(pq_endtypsend(&buf)); } /* ========== PUBLIC ROUTINES ========== */ /* * textlen - * returns the logical length of a text* * (which is less than the VARSIZE of the text*) */ Datum textlen(PG_FUNCTION_ARGS) { Datum str = PG_GETARG_DATUM(0); /* try to avoid decompressing argument */ PG_RETURN_INT32(text_length(str)); } /* * text_length - * Does the real work for textlen() * * This is broken out so it can be called directly by other string processing * functions. Note that the argument is passed as a Datum, to indicate that * it may still be in compressed form. We can avoid decompressing it at all * in some cases. */ static int32 text_length(Datum str) { /* fastpath when max encoding length is one */ if (pg_database_encoding_max_length() == 1) PG_RETURN_INT32(toast_raw_datum_size(str) - VARHDRSZ); else { text *t = DatumGetTextPP(str); PG_RETURN_INT32(pg_mbstrlen_with_len(VARDATA_ANY(t), VARSIZE_ANY_EXHDR(t))); } } /* * textoctetlen - * returns the physical length of a text* * (which is less than the VARSIZE of the text*) */ Datum textoctetlen(PG_FUNCTION_ARGS) { Datum str = PG_GETARG_DATUM(0); /* We need not detoast the input at all */ PG_RETURN_INT32(toast_raw_datum_size(str) - VARHDRSZ); } /* * textcat - * takes two text* and returns a text* that is the concatenation of * the two. * * Rewritten by Sapa, sapa@hq.icb.chel.su. 8-Jul-96. * Updated by Thomas, Thomas.Lockhart@jpl.nasa.gov 1997-07-10. * Allocate space for output in all cases. * XXX - thomas 1997-07-10 */ Datum textcat(PG_FUNCTION_ARGS) { text *t1 = PG_GETARG_TEXT_PP(0); text *t2 = PG_GETARG_TEXT_PP(1); PG_RETURN_TEXT_P(text_catenate(t1, t2)); } /* * text_catenate * Guts of textcat(), broken out so it can be used by other functions * * Arguments can be in short-header form, but not compressed or out-of-line */ static text * text_catenate(text *t1, text *t2) { text *result; int len1, len2, len; char *ptr; len1 = VARSIZE_ANY_EXHDR(t1); len2 = VARSIZE_ANY_EXHDR(t2); /* paranoia ... probably should throw error instead? */ if (len1 < 0) len1 = 0; if (len2 < 0) len2 = 0; len = len1 + len2 + VARHDRSZ; result = (text *) palloc(len); /* Set size of result string... */ SET_VARSIZE(result, len); /* Fill data field of result string... */ ptr = VARDATA(result); if (len1 > 0) memcpy(ptr, VARDATA_ANY(t1), len1); if (len2 > 0) memcpy(ptr + len1, VARDATA_ANY(t2), len2); return result; } /* * charlen_to_bytelen() * Compute the number of bytes occupied by n characters starting at *p * * It is caller's responsibility that there actually are n characters; * the string need not be null-terminated. */ static int charlen_to_bytelen(const char *p, int n) { if (pg_database_encoding_max_length() == 1) { /* Optimization for single-byte encodings */ return n; } else { const char *s; for (s = p; n > 0; n--) s += pg_mblen(s); return s - p; } } /* * text_substr() * Return a substring starting at the specified position. * - thomas 1997-12-31 * * Input: * - string * - starting position (is one-based) * - string length * * If the starting position is zero or less, then return from the start of the string * adjusting the length to be consistent with the "negative start" per SQL. * If the length is less than zero, return the remaining string. * * Added multibyte support. * - Tatsuo Ishii 1998-4-21 * Changed behavior if starting position is less than one to conform to SQL behavior. * Formerly returned the entire string; now returns a portion. * - Thomas Lockhart 1998-12-10 * Now uses faster TOAST-slicing interface * - John Gray 2002-02-22 * Remove "#ifdef MULTIBYTE" and test for encoding_max_length instead. Change * behaviors conflicting with SQL to meet SQL (if E = S + L < S throw * error; if E < 1, return '', not entire string). Fixed MB related bug when * S > LC and < LC + 4 sometimes garbage characters are returned. * - Joe Conway 2002-08-10 */ Datum text_substr(PG_FUNCTION_ARGS) { PG_RETURN_TEXT_P(text_substring(PG_GETARG_DATUM(0), PG_GETARG_INT32(1), PG_GETARG_INT32(2), false)); } /* * text_substr_no_len - * Wrapper to avoid opr_sanity failure due to * one function accepting a different number of args. */ Datum text_substr_no_len(PG_FUNCTION_ARGS) { PG_RETURN_TEXT_P(text_substring(PG_GETARG_DATUM(0), PG_GETARG_INT32(1), -1, true)); } /* * text_substring - * Does the real work for text_substr() and text_substr_no_len() * * This is broken out so it can be called directly by other string processing * functions. Note that the argument is passed as a Datum, to indicate that * it may still be in compressed/toasted form. We can avoid detoasting all * of it in some cases. * * The result is always a freshly palloc'd datum. */ static text * text_substring(Datum str, int32 start, int32 length, bool length_not_specified) { int32 eml = pg_database_encoding_max_length(); int32 S = start; /* start position */ int32 S1; /* adjusted start position */ int32 L1; /* adjusted substring length */ int32 E; /* end position */ /* * SQL99 says S can be zero or negative, but we still must fetch from the * start of the string. */ S1 = Max(S, 1); /* life is easy if the encoding max length is 1 */ if (eml == 1) { if (length_not_specified) /* special case - get length to end of * string */ L1 = -1; else if (length < 0) { /* SQL99 says to throw an error for E < S, i.e., negative length */ ereport(ERROR, (errcode(ERRCODE_SUBSTRING_ERROR), errmsg("negative substring length not allowed"))); L1 = -1; /* silence stupider compilers */ } else if (pg_add_s32_overflow(S, length, &E)) { /* * L could be large enough for S + L to overflow, in which case * the substring must run to end of string. */ L1 = -1; } else { /* * A zero or negative value for the end position can happen if the * start was negative or one. SQL99 says to return a zero-length * string. */ if (E < 1) return cstring_to_text(""); L1 = E - S1; } /* * If the start position is past the end of the string, SQL99 says to * return a zero-length string -- DatumGetTextPSlice() will do that * for us. We need only convert S1 to zero-based starting position. */ return DatumGetTextPSlice(str, S1 - 1, L1); } else if (eml > 1) { /* * When encoding max length is > 1, we can't get LC without * detoasting, so we'll grab a conservatively large slice now and go * back later to do the right thing */ int32 slice_start; int32 slice_size; int32 slice_strlen; text *slice; int32 E1; int32 i; char *p; char *s; text *ret; /* * We need to start at position zero because there is no way to know * in advance which byte offset corresponds to the supplied start * position. */ slice_start = 0; if (length_not_specified) /* special case - get length to end of * string */ slice_size = L1 = -1; else if (length < 0) { /* SQL99 says to throw an error for E < S, i.e., negative length */ ereport(ERROR, (errcode(ERRCODE_SUBSTRING_ERROR), errmsg("negative substring length not allowed"))); slice_size = L1 = -1; /* silence stupider compilers */ } else if (pg_add_s32_overflow(S, length, &E)) { /* * L could be large enough for S + L to overflow, in which case * the substring must run to end of string. */ slice_size = L1 = -1; } else { /* * A zero or negative value for the end position can happen if the * start was negative or one. SQL99 says to return a zero-length * string. */ if (E < 1) return cstring_to_text(""); /* * if E is past the end of the string, the tuple toaster will * truncate the length for us */ L1 = E - S1; /* * Total slice size in bytes can't be any longer than the start * position plus substring length times the encoding max length. * If that overflows, we can just use -1. */ if (pg_mul_s32_overflow(E, eml, &slice_size)) slice_size = -1; } /* * If we're working with an untoasted source, no need to do an extra * copying step. */ if (VARATT_IS_COMPRESSED(DatumGetPointer(str)) || VARATT_IS_EXTERNAL(DatumGetPointer(str))) slice = DatumGetTextPSlice(str, slice_start, slice_size); else slice = (text *) DatumGetPointer(str); /* see if we got back an empty string */ if (VARSIZE_ANY_EXHDR(slice) == 0) { if (slice != (text *) DatumGetPointer(str)) pfree(slice); return cstring_to_text(""); } /* Now we can get the actual length of the slice in MB characters */ slice_strlen = pg_mbstrlen_with_len(VARDATA_ANY(slice), VARSIZE_ANY_EXHDR(slice)); /* * Check that the start position wasn't > slice_strlen. If so, SQL99 * says to return a zero-length string. */ if (S1 > slice_strlen) { if (slice != (text *) DatumGetPointer(str)) pfree(slice); return cstring_to_text(""); } /* * Adjust L1 and E1 now that we know the slice string length. Again * remember that S1 is one based, and slice_start is zero based. */ if (L1 > -1) E1 = Min(S1 + L1, slice_start + 1 + slice_strlen); else E1 = slice_start + 1 + slice_strlen; /* * Find the start position in the slice; remember S1 is not zero based */ p = VARDATA_ANY(slice); for (i = 0; i < S1 - 1; i++) p += pg_mblen(p); /* hang onto a pointer to our start position */ s = p; /* * Count the actual bytes used by the substring of the requested * length. */ for (i = S1; i < E1; i++) p += pg_mblen(p); ret = (text *) palloc(VARHDRSZ + (p - s)); SET_VARSIZE(ret, VARHDRSZ + (p - s)); memcpy(VARDATA(ret), s, (p - s)); if (slice != (text *) DatumGetPointer(str)) pfree(slice); return ret; } else elog(ERROR, "invalid backend encoding: encoding max length < 1"); /* not reached: suppress compiler warning */ return NULL; } /* * textoverlay * Replace specified substring of first string with second * * The SQL standard defines OVERLAY() in terms of substring and concatenation. * This code is a direct implementation of what the standard says. */ Datum textoverlay(PG_FUNCTION_ARGS) { text *t1 = PG_GETARG_TEXT_PP(0); text *t2 = PG_GETARG_TEXT_PP(1); int sp = PG_GETARG_INT32(2); /* substring start position */ int sl = PG_GETARG_INT32(3); /* substring length */ PG_RETURN_TEXT_P(text_overlay(t1, t2, sp, sl)); } Datum textoverlay_no_len(PG_FUNCTION_ARGS) { text *t1 = PG_GETARG_TEXT_PP(0); text *t2 = PG_GETARG_TEXT_PP(1); int sp = PG_GETARG_INT32(2); /* substring start position */ int sl; sl = text_length(PointerGetDatum(t2)); /* defaults to length(t2) */ PG_RETURN_TEXT_P(text_overlay(t1, t2, sp, sl)); } static text * text_overlay(text *t1, text *t2, int sp, int sl) { text *result; text *s1; text *s2; int sp_pl_sl; /* * Check for possible integer-overflow cases. For negative sp, throw a * "substring length" error because that's what should be expected * according to the spec's definition of OVERLAY(). */ if (sp <= 0) ereport(ERROR, (errcode(ERRCODE_SUBSTRING_ERROR), errmsg("negative substring length not allowed"))); if (pg_add_s32_overflow(sp, sl, &sp_pl_sl)) ereport(ERROR, (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE), errmsg("integer out of range"))); s1 = text_substring(PointerGetDatum(t1), 1, sp - 1, false); s2 = text_substring(PointerGetDatum(t1), sp_pl_sl, -1, true); result = text_catenate(s1, t2); result = text_catenate(result, s2); return result; } /* * textpos - * Return the position of the specified substring. * Implements the SQL POSITION() function. * Ref: A Guide To The SQL Standard, Date & Darwen, 1997 * - thomas 1997-07-27 */ Datum textpos(PG_FUNCTION_ARGS) { text *str = PG_GETARG_TEXT_PP(0); text *search_str = PG_GETARG_TEXT_PP(1); PG_RETURN_INT32((int32) text_position(str, search_str, PG_GET_COLLATION())); } /* * text_position - * Does the real work for textpos() * * Inputs: * t1 - string to be searched * t2 - pattern to match within t1 * Result: * Character index of the first matched char, starting from 1, * or 0 if no match. * * This is broken out so it can be called directly by other string processing * functions. */ static int text_position(text *t1, text *t2, Oid collid) { TextPositionState state; int result; /* Empty needle always matches at position 1 */ if (VARSIZE_ANY_EXHDR(t2) < 1) return 1; /* Otherwise, can't match if haystack is shorter than needle */ if (VARSIZE_ANY_EXHDR(t1) < VARSIZE_ANY_EXHDR(t2)) return 0; text_position_setup(t1, t2, collid, &state); if (!text_position_next(&state)) result = 0; else result = text_position_get_match_pos(&state); text_position_cleanup(&state); return result; } /* * text_position_setup, text_position_next, text_position_cleanup - * Component steps of text_position() * * These are broken out so that a string can be efficiently searched for * multiple occurrences of the same pattern. text_position_next may be * called multiple times, and it advances to the next match on each call. * text_position_get_match_ptr() and text_position_get_match_pos() return * a pointer or 1-based character position of the last match, respectively. * * The "state" variable is normally just a local variable in the caller. * * NOTE: text_position_next skips over the matched portion. For example, * searching for "xx" in "xxx" returns only one match, not two. */ static void text_position_setup(text *t1, text *t2, Oid collid, TextPositionState *state) { int len1 = VARSIZE_ANY_EXHDR(t1); int len2 = VARSIZE_ANY_EXHDR(t2); pg_locale_t mylocale = 0; check_collation_set(collid); if (!lc_collate_is_c(collid)) mylocale = pg_newlocale_from_collation(collid); if (!pg_locale_deterministic(mylocale)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("nondeterministic collations are not supported for substring searches"))); Assert(len1 > 0); Assert(len2 > 0); /* * Even with a multi-byte encoding, we perform the search using the raw * byte sequence, ignoring multibyte issues. For UTF-8, that works fine, * because in UTF-8 the byte sequence of one character cannot contain * another character. For other multi-byte encodings, we do the search * initially as a simple byte search, ignoring multibyte issues, but * verify afterwards that the match we found is at a character boundary, * and continue the search if it was a false match. */ if (pg_database_encoding_max_length() == 1) state->is_multibyte_char_in_char = false; else if (GetDatabaseEncoding() == PG_UTF8) state->is_multibyte_char_in_char = false; else state->is_multibyte_char_in_char = true; state->str1 = VARDATA_ANY(t1); state->str2 = VARDATA_ANY(t2); state->len1 = len1; state->len2 = len2; state->last_match = NULL; state->refpoint = state->str1; state->refpos = 0; /* * Prepare the skip table for Boyer-Moore-Horspool searching. In these * notes we use the terminology that the "haystack" is the string to be * searched (t1) and the "needle" is the pattern being sought (t2). * * If the needle is empty or bigger than the haystack then there is no * point in wasting cycles initializing the table. We also choose not to * use B-M-H for needles of length 1, since the skip table can't possibly * save anything in that case. */ if (len1 >= len2 && len2 > 1) { int searchlength = len1 - len2; int skiptablemask; int last; int i; const char *str2 = state->str2; /* * First we must determine how much of the skip table to use. The * declaration of TextPositionState allows up to 256 elements, but for * short search problems we don't really want to have to initialize so * many elements --- it would take too long in comparison to the * actual search time. So we choose a useful skip table size based on * the haystack length minus the needle length. The closer the needle * length is to the haystack length the less useful skipping becomes. * * Note: since we use bit-masking to select table elements, the skip * table size MUST be a power of 2, and so the mask must be 2^N-1. */ if (searchlength < 16) skiptablemask = 3; else if (searchlength < 64) skiptablemask = 7; else if (searchlength < 128) skiptablemask = 15; else if (searchlength < 512) skiptablemask = 31; else if (searchlength < 2048) skiptablemask = 63; else if (searchlength < 4096) skiptablemask = 127; else skiptablemask = 255; state->skiptablemask = skiptablemask; /* * Initialize the skip table. We set all elements to the needle * length, since this is the correct skip distance for any character * not found in the needle. */ for (i = 0; i <= skiptablemask; i++) state->skiptable[i] = len2; /* * Now examine the needle. For each character except the last one, * set the corresponding table element to the appropriate skip * distance. Note that when two characters share the same skip table * entry, the one later in the needle must determine the skip * distance. */ last = len2 - 1; for (i = 0; i < last; i++) state->skiptable[(unsigned char) str2[i] & skiptablemask] = last - i; } } /* * Advance to the next match, starting from the end of the previous match * (or the beginning of the string, on first call). Returns true if a match * is found. * * Note that this refuses to match an empty-string needle. Most callers * will have handled that case specially and we'll never see it here. */ static bool text_position_next(TextPositionState *state) { int needle_len = state->len2; char *start_ptr; char *matchptr; if (needle_len <= 0) return false; /* result for empty pattern */ /* Start from the point right after the previous match. */ if (state->last_match) start_ptr = state->last_match + needle_len; else start_ptr = state->str1; retry: matchptr = text_position_next_internal(start_ptr, state); if (!matchptr) return false; /* * Found a match for the byte sequence. If this is a multibyte encoding, * where one character's byte sequence can appear inside a longer * multi-byte character, we need to verify that the match was at a * character boundary, not in the middle of a multi-byte character. */ if (state->is_multibyte_char_in_char) { /* Walk one character at a time, until we reach the match. */ /* the search should never move backwards. */ Assert(state->refpoint <= matchptr); while (state->refpoint < matchptr) { /* step to next character. */ state->refpoint += pg_mblen(state->refpoint); state->refpos++; /* * If we stepped over the match's start position, then it was a * false positive, where the byte sequence appeared in the middle * of a multi-byte character. Skip it, and continue the search at * the next character boundary. */ if (state->refpoint > matchptr) { start_ptr = state->refpoint; goto retry; } } } state->last_match = matchptr; return true; } /* * Subroutine of text_position_next(). This searches for the raw byte * sequence, ignoring any multi-byte encoding issues. Returns the first * match starting at 'start_ptr', or NULL if no match is found. */ static char * text_position_next_internal(char *start_ptr, TextPositionState *state) { int haystack_len = state->len1; int needle_len = state->len2; int skiptablemask = state->skiptablemask; const char *haystack = state->str1; const char *needle = state->str2; const char *haystack_end = &haystack[haystack_len]; const char *hptr; Assert(start_ptr >= haystack && start_ptr <= haystack_end); if (needle_len == 1) { /* No point in using B-M-H for a one-character needle */ char nchar = *needle; hptr = start_ptr; while (hptr < haystack_end) { if (*hptr == nchar) return (char *) hptr; hptr++; } } else { const char *needle_last = &needle[needle_len - 1]; /* Start at startpos plus the length of the needle */ hptr = start_ptr + needle_len - 1; while (hptr < haystack_end) { /* Match the needle scanning *backward* */ const char *nptr; const char *p; nptr = needle_last; p = hptr; while (*nptr == *p) { /* Matched it all? If so, return 1-based position */ if (nptr == needle) return (char *) p; nptr--, p--; } /* * No match, so use the haystack char at hptr to decide how far to * advance. If the needle had any occurrence of that character * (or more precisely, one sharing the same skiptable entry) * before its last character, then we advance far enough to align * the last such needle character with that haystack position. * Otherwise we can advance by the whole needle length. */ hptr += state->skiptable[(unsigned char) *hptr & skiptablemask]; } } return 0; /* not found */ } /* * Return a pointer to the current match. * * The returned pointer points into the original haystack string. */ static char * text_position_get_match_ptr(TextPositionState *state) { return state->last_match; } /* * Return the offset of the current match. * * The offset is in characters, 1-based. */ static int text_position_get_match_pos(TextPositionState *state) { /* Convert the byte position to char position. */ state->refpos += pg_mbstrlen_with_len(state->refpoint, state->last_match - state->refpoint); state->refpoint = state->last_match; return state->refpos + 1; } /* * Reset search state to the initial state installed by text_position_setup. * * The next call to text_position_next will search from the beginning * of the string. */ static void text_position_reset(TextPositionState *state) { state->last_match = NULL; state->refpoint = state->str1; state->refpos = 0; } static void text_position_cleanup(TextPositionState *state) { /* no cleanup needed */ } static void check_collation_set(Oid collid) { if (!OidIsValid(collid)) { /* * This typically means that the parser could not resolve a conflict * of implicit collations, so report it that way. */ ereport(ERROR, (errcode(ERRCODE_INDETERMINATE_COLLATION), errmsg("could not determine which collation to use for string comparison"), errhint("Use the COLLATE clause to set the collation explicitly."))); } } /* varstr_cmp() * Comparison function for text strings with given lengths. * Includes locale support, but must copy strings to temporary memory * to allow null-termination for inputs to strcoll(). * Returns an integer less than, equal to, or greater than zero, indicating * whether arg1 is less than, equal to, or greater than arg2. * * Note: many functions that depend on this are marked leakproof; therefore, * avoid reporting the actual contents of the input when throwing errors. * All errors herein should be things that can't happen except on corrupt * data, anyway; otherwise we will have trouble with indexing strings that * would cause them. */ int varstr_cmp(const char *arg1, int len1, const char *arg2, int len2, Oid collid) { int result; check_collation_set(collid); /* * Unfortunately, there is no strncoll(), so in the non-C locale case we * have to do some memory copying. This turns out to be significantly * slower, so we optimize the case where LC_COLLATE is C. We also try to * optimize relatively-short strings by avoiding palloc/pfree overhead. */ if (lc_collate_is_c(collid)) { result = memcmp(arg1, arg2, Min(len1, len2)); if ((result == 0) && (len1 != len2)) result = (len1 < len2) ? -1 : 1; } else { pg_locale_t mylocale; mylocale = pg_newlocale_from_collation(collid); /* * memcmp() can't tell us which of two unequal strings sorts first, * but it's a cheap way to tell if they're equal. Testing shows that * memcmp() followed by strcoll() is only trivially slower than * strcoll() by itself, so we don't lose much if this doesn't work out * very often, and if it does - for example, because there are many * equal strings in the input - then we win big by avoiding expensive * collation-aware comparisons. */ if (len1 == len2 && memcmp(arg1, arg2, len1) == 0) return 0; result = pg_strncoll(arg1, len1, arg2, len2, mylocale); /* Break tie if necessary. */ if (result == 0 && pg_locale_deterministic(mylocale)) { result = memcmp(arg1, arg2, Min(len1, len2)); if ((result == 0) && (len1 != len2)) result = (len1 < len2) ? -1 : 1; } } return result; } /* text_cmp() * Internal comparison function for text strings. * Returns -1, 0 or 1 */ static int text_cmp(text *arg1, text *arg2, Oid collid) { char *a1p, *a2p; int len1, len2; a1p = VARDATA_ANY(arg1); a2p = VARDATA_ANY(arg2); len1 = VARSIZE_ANY_EXHDR(arg1); len2 = VARSIZE_ANY_EXHDR(arg2); return varstr_cmp(a1p, len1, a2p, len2, collid); } /* * Comparison functions for text strings. * * Note: btree indexes need these routines not to leak memory; therefore, * be careful to free working copies of toasted datums. Most places don't * need to be so careful. */ Datum texteq(PG_FUNCTION_ARGS) { Oid collid = PG_GET_COLLATION(); bool locale_is_c = false; pg_locale_t mylocale = 0; bool result; check_collation_set(collid); if (lc_collate_is_c(collid)) locale_is_c = true; else mylocale = pg_newlocale_from_collation(collid); if (locale_is_c || pg_locale_deterministic(mylocale)) { Datum arg1 = PG_GETARG_DATUM(0); Datum arg2 = PG_GETARG_DATUM(1); Size len1, len2; /* * Since we only care about equality or not-equality, we can avoid all * the expense of strcoll() here, and just do bitwise comparison. In * fact, we don't even have to do a bitwise comparison if we can show * the lengths of the strings are unequal; which might save us from * having to detoast one or both values. */ len1 = toast_raw_datum_size(arg1); len2 = toast_raw_datum_size(arg2); if (len1 != len2) result = false; else { text *targ1 = DatumGetTextPP(arg1); text *targ2 = DatumGetTextPP(arg2); result = (memcmp(VARDATA_ANY(targ1), VARDATA_ANY(targ2), len1 - VARHDRSZ) == 0); PG_FREE_IF_COPY(targ1, 0); PG_FREE_IF_COPY(targ2, 1); } } else { text *arg1 = PG_GETARG_TEXT_PP(0); text *arg2 = PG_GETARG_TEXT_PP(1); result = (text_cmp(arg1, arg2, collid) == 0); PG_FREE_IF_COPY(arg1, 0); PG_FREE_IF_COPY(arg2, 1); } PG_RETURN_BOOL(result); } Datum textne(PG_FUNCTION_ARGS) { Oid collid = PG_GET_COLLATION(); bool locale_is_c = false; pg_locale_t mylocale = 0; bool result; check_collation_set(collid); if (lc_collate_is_c(collid)) locale_is_c = true; else mylocale = pg_newlocale_from_collation(collid); if (locale_is_c || pg_locale_deterministic(mylocale)) { Datum arg1 = PG_GETARG_DATUM(0); Datum arg2 = PG_GETARG_DATUM(1); Size len1, len2; /* See comment in texteq() */ len1 = toast_raw_datum_size(arg1); len2 = toast_raw_datum_size(arg2); if (len1 != len2) result = true; else { text *targ1 = DatumGetTextPP(arg1); text *targ2 = DatumGetTextPP(arg2); result = (memcmp(VARDATA_ANY(targ1), VARDATA_ANY(targ2), len1 - VARHDRSZ) != 0); PG_FREE_IF_COPY(targ1, 0); PG_FREE_IF_COPY(targ2, 1); } } else { text *arg1 = PG_GETARG_TEXT_PP(0); text *arg2 = PG_GETARG_TEXT_PP(1); result = (text_cmp(arg1, arg2, collid) != 0); PG_FREE_IF_COPY(arg1, 0); PG_FREE_IF_COPY(arg2, 1); } PG_RETURN_BOOL(result); } Datum text_lt(PG_FUNCTION_ARGS) { text *arg1 = PG_GETARG_TEXT_PP(0); text *arg2 = PG_GETARG_TEXT_PP(1); bool result; result = (text_cmp(arg1, arg2, PG_GET_COLLATION()) < 0); PG_FREE_IF_COPY(arg1, 0); PG_FREE_IF_COPY(arg2, 1); PG_RETURN_BOOL(result); } Datum text_le(PG_FUNCTION_ARGS) { text *arg1 = PG_GETARG_TEXT_PP(0); text *arg2 = PG_GETARG_TEXT_PP(1); bool result; result = (text_cmp(arg1, arg2, PG_GET_COLLATION()) <= 0); PG_FREE_IF_COPY(arg1, 0); PG_FREE_IF_COPY(arg2, 1); PG_RETURN_BOOL(result); } Datum text_gt(PG_FUNCTION_ARGS) { text *arg1 = PG_GETARG_TEXT_PP(0); text *arg2 = PG_GETARG_TEXT_PP(1); bool result; result = (text_cmp(arg1, arg2, PG_GET_COLLATION()) > 0); PG_FREE_IF_COPY(arg1, 0); PG_FREE_IF_COPY(arg2, 1); PG_RETURN_BOOL(result); } Datum text_ge(PG_FUNCTION_ARGS) { text *arg1 = PG_GETARG_TEXT_PP(0); text *arg2 = PG_GETARG_TEXT_PP(1); bool result; result = (text_cmp(arg1, arg2, PG_GET_COLLATION()) >= 0); PG_FREE_IF_COPY(arg1, 0); PG_FREE_IF_COPY(arg2, 1); PG_RETURN_BOOL(result); } Datum text_starts_with(PG_FUNCTION_ARGS) { Datum arg1 = PG_GETARG_DATUM(0); Datum arg2 = PG_GETARG_DATUM(1); Oid collid = PG_GET_COLLATION(); pg_locale_t mylocale = 0; bool result; Size len1, len2; check_collation_set(collid); if (!lc_collate_is_c(collid)) mylocale = pg_newlocale_from_collation(collid); if (!pg_locale_deterministic(mylocale)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("nondeterministic collations are not supported for substring searches"))); len1 = toast_raw_datum_size(arg1); len2 = toast_raw_datum_size(arg2); if (len2 > len1) result = false; else { text *targ1 = text_substring(arg1, 1, len2, false); text *targ2 = DatumGetTextPP(arg2); result = (memcmp(VARDATA_ANY(targ1), VARDATA_ANY(targ2), VARSIZE_ANY_EXHDR(targ2)) == 0); PG_FREE_IF_COPY(targ1, 0); PG_FREE_IF_COPY(targ2, 1); } PG_RETURN_BOOL(result); } Datum bttextcmp(PG_FUNCTION_ARGS) { text *arg1 = PG_GETARG_TEXT_PP(0); text *arg2 = PG_GETARG_TEXT_PP(1); int32 result; result = text_cmp(arg1, arg2, PG_GET_COLLATION()); PG_FREE_IF_COPY(arg1, 0); PG_FREE_IF_COPY(arg2, 1); PG_RETURN_INT32(result); } Datum bttextsortsupport(PG_FUNCTION_ARGS) { SortSupport ssup = (SortSupport) PG_GETARG_POINTER(0); Oid collid = ssup->ssup_collation; MemoryContext oldcontext; oldcontext = MemoryContextSwitchTo(ssup->ssup_cxt); /* Use generic string SortSupport */ varstr_sortsupport(ssup, TEXTOID, collid); MemoryContextSwitchTo(oldcontext); PG_RETURN_VOID(); } /* * Generic sortsupport interface for character type's operator classes. * Includes locale support, and support for BpChar semantics (i.e. removing * trailing spaces before comparison). * * Relies on the assumption that text, VarChar, BpChar, and bytea all have the * same representation. Callers that always use the C collation (e.g. * non-collatable type callers like bytea) may have NUL bytes in their strings; * this will not work with any other collation, though. */ void varstr_sortsupport(SortSupport ssup, Oid typid, Oid collid) { bool abbreviate = ssup->abbreviate; bool collate_c = false; VarStringSortSupport *sss; pg_locale_t locale = 0; check_collation_set(collid); /* * If possible, set ssup->comparator to a function which can be used to * directly compare two datums. If we can do this, we'll avoid the * overhead of a trip through the fmgr layer for every comparison, which * can be substantial. * * Most typically, we'll set the comparator to varlenafastcmp_locale, * which uses strcoll() to perform comparisons. We use that for the * BpChar case too, but type NAME uses namefastcmp_locale. However, if * LC_COLLATE = C, we can make things quite a bit faster with * varstrfastcmp_c, bpcharfastcmp_c, or namefastcmp_c, all of which use * memcmp() rather than strcoll(). */ if (lc_collate_is_c(collid)) { if (typid == BPCHAROID) ssup->comparator = bpcharfastcmp_c; else if (typid == NAMEOID) { ssup->comparator = namefastcmp_c; /* Not supporting abbreviation with type NAME, for now */ abbreviate = false; } else ssup->comparator = varstrfastcmp_c; collate_c = true; } else { /* * We need a collation-sensitive comparison. To make things faster, * we'll figure out the collation based on the locale id and cache the * result. */ locale = pg_newlocale_from_collation(collid); /* * We use varlenafastcmp_locale except for type NAME. */ if (typid == NAMEOID) { ssup->comparator = namefastcmp_locale; /* Not supporting abbreviation with type NAME, for now */ abbreviate = false; } else ssup->comparator = varlenafastcmp_locale; } /* * Unfortunately, it seems that abbreviation for non-C collations is * broken on many common platforms; see pg_strxfrm_enabled(). * * Even apart from the risk of broken locales, it's possible that there * are platforms where the use of abbreviated keys should be disabled at * compile time. Having only 4 byte datums could make worst-case * performance drastically more likely, for example. Moreover, macOS's * strxfrm() implementation is known to not effectively concentrate a * significant amount of entropy from the original string in earlier * transformed blobs. It's possible that other supported platforms are * similarly encumbered. So, if we ever get past disabling this * categorically, we may still want or need to disable it for particular * platforms. */ if (!collate_c && !pg_strxfrm_enabled(locale)) abbreviate = false; /* * If we're using abbreviated keys, or if we're using a locale-aware * comparison, we need to initialize a VarStringSortSupport object. Both * cases will make use of the temporary buffers we initialize here for * scratch space (and to detect requirement for BpChar semantics from * caller), and the abbreviation case requires additional state. */ if (abbreviate || !collate_c) { sss = palloc(sizeof(VarStringSortSupport)); sss->buf1 = palloc(TEXTBUFLEN); sss->buflen1 = TEXTBUFLEN; sss->buf2 = palloc(TEXTBUFLEN); sss->buflen2 = TEXTBUFLEN; /* Start with invalid values */ sss->last_len1 = -1; sss->last_len2 = -1; /* Initialize */ sss->last_returned = 0; sss->locale = locale; /* * To avoid somehow confusing a strxfrm() blob and an original string, * constantly keep track of the variety of data that buf1 and buf2 * currently contain. * * Comparisons may be interleaved with conversion calls. Frequently, * conversions and comparisons are batched into two distinct phases, * but the correctness of caching cannot hinge upon this. For * comparison caching, buffer state is only trusted if cache_blob is * found set to false, whereas strxfrm() caching only trusts the state * when cache_blob is found set to true. * * Arbitrarily initialize cache_blob to true. */ sss->cache_blob = true; sss->collate_c = collate_c; sss->typid = typid; ssup->ssup_extra = sss; /* * If possible, plan to use the abbreviated keys optimization. The * core code may switch back to authoritative comparator should * abbreviation be aborted. */ if (abbreviate) { sss->prop_card = 0.20; initHyperLogLog(&sss->abbr_card, 10); initHyperLogLog(&sss->full_card, 10); ssup->abbrev_full_comparator = ssup->comparator; ssup->comparator = ssup_datum_unsigned_cmp; ssup->abbrev_converter = varstr_abbrev_convert; ssup->abbrev_abort = varstr_abbrev_abort; } } } /* * sortsupport comparison func (for C locale case) */ static int varstrfastcmp_c(Datum x, Datum y, SortSupport ssup) { VarString *arg1 = DatumGetVarStringPP(x); VarString *arg2 = DatumGetVarStringPP(y); char *a1p, *a2p; int len1, len2, result; a1p = VARDATA_ANY(arg1); a2p = VARDATA_ANY(arg2); len1 = VARSIZE_ANY_EXHDR(arg1); len2 = VARSIZE_ANY_EXHDR(arg2); result = memcmp(a1p, a2p, Min(len1, len2)); if ((result == 0) && (len1 != len2)) result = (len1 < len2) ? -1 : 1; /* We can't afford to leak memory here. */ if (PointerGetDatum(arg1) != x) pfree(arg1); if (PointerGetDatum(arg2) != y) pfree(arg2); return result; } /* * sortsupport comparison func (for BpChar C locale case) * * BpChar outsources its sortsupport to this module. Specialization for the * varstr_sortsupport BpChar case, modeled on * internal_bpchar_pattern_compare(). */ static int bpcharfastcmp_c(Datum x, Datum y, SortSupport ssup) { BpChar *arg1 = DatumGetBpCharPP(x); BpChar *arg2 = DatumGetBpCharPP(y); char *a1p, *a2p; int len1, len2, result; a1p = VARDATA_ANY(arg1); a2p = VARDATA_ANY(arg2); len1 = bpchartruelen(a1p, VARSIZE_ANY_EXHDR(arg1)); len2 = bpchartruelen(a2p, VARSIZE_ANY_EXHDR(arg2)); result = memcmp(a1p, a2p, Min(len1, len2)); if ((result == 0) && (len1 != len2)) result = (len1 < len2) ? -1 : 1; /* We can't afford to leak memory here. */ if (PointerGetDatum(arg1) != x) pfree(arg1); if (PointerGetDatum(arg2) != y) pfree(arg2); return result; } /* * sortsupport comparison func (for NAME C locale case) */ static int namefastcmp_c(Datum x, Datum y, SortSupport ssup) { Name arg1 = DatumGetName(x); Name arg2 = DatumGetName(y); return strncmp(NameStr(*arg1), NameStr(*arg2), NAMEDATALEN); } /* * sortsupport comparison func (for locale case with all varlena types) */ static int varlenafastcmp_locale(Datum x, Datum y, SortSupport ssup) { VarString *arg1 = DatumGetVarStringPP(x); VarString *arg2 = DatumGetVarStringPP(y); char *a1p, *a2p; int len1, len2, result; a1p = VARDATA_ANY(arg1); a2p = VARDATA_ANY(arg2); len1 = VARSIZE_ANY_EXHDR(arg1); len2 = VARSIZE_ANY_EXHDR(arg2); result = varstrfastcmp_locale(a1p, len1, a2p, len2, ssup); /* We can't afford to leak memory here. */ if (PointerGetDatum(arg1) != x) pfree(arg1); if (PointerGetDatum(arg2) != y) pfree(arg2); return result; } /* * sortsupport comparison func (for locale case with NAME type) */ static int namefastcmp_locale(Datum x, Datum y, SortSupport ssup) { Name arg1 = DatumGetName(x); Name arg2 = DatumGetName(y); return varstrfastcmp_locale(NameStr(*arg1), strlen(NameStr(*arg1)), NameStr(*arg2), strlen(NameStr(*arg2)), ssup); } /* * sortsupport comparison func for locale cases */ static int varstrfastcmp_locale(char *a1p, int len1, char *a2p, int len2, SortSupport ssup) { VarStringSortSupport *sss = (VarStringSortSupport *) ssup->ssup_extra; int result; bool arg1_match; /* Fast pre-check for equality, as discussed in varstr_cmp() */ if (len1 == len2 && memcmp(a1p, a2p, len1) == 0) { /* * No change in buf1 or buf2 contents, so avoid changing last_len1 or * last_len2. Existing contents of buffers might still be used by * next call. * * It's fine to allow the comparison of BpChar padding bytes here, * even though that implies that the memcmp() will usually be * performed for BpChar callers (though multibyte characters could * still prevent that from occurring). The memcmp() is still very * cheap, and BpChar's funny semantics have us remove trailing spaces * (not limited to padding), so we need make no distinction between * padding space characters and "real" space characters. */ return 0; } if (sss->typid == BPCHAROID) { /* Get true number of bytes, ignoring trailing spaces */ len1 = bpchartruelen(a1p, len1); len2 = bpchartruelen(a2p, len2); } if (len1 >= sss->buflen1) { sss->buflen1 = Max(len1 + 1, Min(sss->buflen1 * 2, MaxAllocSize)); sss->buf1 = repalloc(sss->buf1, sss->buflen1); } if (len2 >= sss->buflen2) { sss->buflen2 = Max(len2 + 1, Min(sss->buflen2 * 2, MaxAllocSize)); sss->buf2 = repalloc(sss->buf2, sss->buflen2); } /* * We're likely to be asked to compare the same strings repeatedly, and * memcmp() is so much cheaper than strcoll() that it pays to try to cache * comparisons, even though in general there is no reason to think that * that will work out (every string datum may be unique). Caching does * not slow things down measurably when it doesn't work out, and can speed * things up by rather a lot when it does. In part, this is because the * memcmp() compares data from cachelines that are needed in L1 cache even * when the last comparison's result cannot be reused. */ arg1_match = true; if (len1 != sss->last_len1 || memcmp(sss->buf1, a1p, len1) != 0) { arg1_match = false; memcpy(sss->buf1, a1p, len1); sss->buf1[len1] = '\0'; sss->last_len1 = len1; } /* * If we're comparing the same two strings as last time, we can return the * same answer without calling strcoll() again. This is more likely than * it seems (at least with moderate to low cardinality sets), because * quicksort compares the same pivot against many values. */ if (len2 != sss->last_len2 || memcmp(sss->buf2, a2p, len2) != 0) { memcpy(sss->buf2, a2p, len2); sss->buf2[len2] = '\0'; sss->last_len2 = len2; } else if (arg1_match && !sss->cache_blob) { /* Use result cached following last actual strcoll() call */ return sss->last_returned; } result = pg_strcoll(sss->buf1, sss->buf2, sss->locale); /* Break tie if necessary. */ if (result == 0 && pg_locale_deterministic(sss->locale)) result = strcmp(sss->buf1, sss->buf2); /* Cache result, perhaps saving an expensive strcoll() call next time */ sss->cache_blob = false; sss->last_returned = result; return result; } /* * Conversion routine for sortsupport. Converts original to abbreviated key * representation. Our encoding strategy is simple -- pack the first 8 bytes * of a strxfrm() blob into a Datum (on little-endian machines, the 8 bytes are * stored in reverse order), and treat it as an unsigned integer. When the "C" * locale is used, or in case of bytea, just memcpy() from original instead. */ static Datum varstr_abbrev_convert(Datum original, SortSupport ssup) { const size_t max_prefix_bytes = sizeof(Datum); VarStringSortSupport *sss = (VarStringSortSupport *) ssup->ssup_extra; VarString *authoritative = DatumGetVarStringPP(original); char *authoritative_data = VARDATA_ANY(authoritative); /* working state */ Datum res; char *pres; int len; uint32 hash; pres = (char *) &res; /* memset(), so any non-overwritten bytes are NUL */ memset(pres, 0, max_prefix_bytes); len = VARSIZE_ANY_EXHDR(authoritative); /* Get number of bytes, ignoring trailing spaces */ if (sss->typid == BPCHAROID) len = bpchartruelen(authoritative_data, len); /* * If we're using the C collation, use memcpy(), rather than strxfrm(), to * abbreviate keys. The full comparator for the C locale is always * memcmp(). It would be incorrect to allow bytea callers (callers that * always force the C collation -- bytea isn't a collatable type, but this * approach is convenient) to use strxfrm(). This is because bytea * strings may contain NUL bytes. Besides, this should be faster, too. * * More generally, it's okay that bytea callers can have NUL bytes in * strings because abbreviated cmp need not make a distinction between * terminating NUL bytes, and NUL bytes representing actual NULs in the * authoritative representation. Hopefully a comparison at or past one * abbreviated key's terminating NUL byte will resolve the comparison * without consulting the authoritative representation; specifically, some * later non-NUL byte in the longer string can resolve the comparison * against a subsequent terminating NUL in the shorter string. There will * usually be what is effectively a "length-wise" resolution there and * then. * * If that doesn't work out -- if all bytes in the longer string * positioned at or past the offset of the smaller string's (first) * terminating NUL are actually representative of NUL bytes in the * authoritative binary string (perhaps with some *terminating* NUL bytes * towards the end of the longer string iff it happens to still be small) * -- then an authoritative tie-breaker will happen, and do the right * thing: explicitly consider string length. */ if (sss->collate_c) memcpy(pres, authoritative_data, Min(len, max_prefix_bytes)); else { Size bsize; /* * We're not using the C collation, so fall back on strxfrm or ICU * analogs. */ /* By convention, we use buffer 1 to store and NUL-terminate */ if (len >= sss->buflen1) { sss->buflen1 = Max(len + 1, Min(sss->buflen1 * 2, MaxAllocSize)); sss->buf1 = repalloc(sss->buf1, sss->buflen1); } /* Might be able to reuse strxfrm() blob from last call */ if (sss->last_len1 == len && sss->cache_blob && memcmp(sss->buf1, authoritative_data, len) == 0) { memcpy(pres, sss->buf2, Min(max_prefix_bytes, sss->last_len2)); /* No change affecting cardinality, so no hashing required */ goto done; } memcpy(sss->buf1, authoritative_data, len); /* * pg_strxfrm() and pg_strxfrm_prefix expect NUL-terminated strings. */ sss->buf1[len] = '\0'; sss->last_len1 = len; if (pg_strxfrm_prefix_enabled(sss->locale)) { if (sss->buflen2 < max_prefix_bytes) { sss->buflen2 = Max(max_prefix_bytes, Min(sss->buflen2 * 2, MaxAllocSize)); sss->buf2 = repalloc(sss->buf2, sss->buflen2); } bsize = pg_strxfrm_prefix(sss->buf2, sss->buf1, max_prefix_bytes, sss->locale); sss->last_len2 = bsize; } else { /* * Loop: Call pg_strxfrm(), possibly enlarge buffer, and try * again. The pg_strxfrm() function leaves the result buffer * content undefined if the result did not fit, so we need to * retry until everything fits, even though we only need the first * few bytes in the end. */ for (;;) { bsize = pg_strxfrm(sss->buf2, sss->buf1, sss->buflen2, sss->locale); sss->last_len2 = bsize; if (bsize < sss->buflen2) break; /* * Grow buffer and retry. */ sss->buflen2 = Max(bsize + 1, Min(sss->buflen2 * 2, MaxAllocSize)); sss->buf2 = repalloc(sss->buf2, sss->buflen2); } } /* * Every Datum byte is always compared. This is safe because the * strxfrm() blob is itself NUL terminated, leaving no danger of * misinterpreting any NUL bytes not intended to be interpreted as * logically representing termination. * * (Actually, even if there were NUL bytes in the blob it would be * okay. See remarks on bytea case above.) */ memcpy(pres, sss->buf2, Min(max_prefix_bytes, bsize)); } /* * Maintain approximate cardinality of both abbreviated keys and original, * authoritative keys using HyperLogLog. Used as cheap insurance against * the worst case, where we do many string transformations for no saving * in full strcoll()-based comparisons. These statistics are used by * varstr_abbrev_abort(). * * First, Hash key proper, or a significant fraction of it. Mix in length * in order to compensate for cases where differences are past * PG_CACHE_LINE_SIZE bytes, so as to limit the overhead of hashing. */ hash = DatumGetUInt32(hash_any((unsigned char *) authoritative_data, Min(len, PG_CACHE_LINE_SIZE))); if (len > PG_CACHE_LINE_SIZE) hash ^= DatumGetUInt32(hash_uint32((uint32) len)); addHyperLogLog(&sss->full_card, hash); /* Hash abbreviated key */ #if SIZEOF_DATUM == 8 { uint32 lohalf, hihalf; lohalf = (uint32) res; hihalf = (uint32) (res >> 32); hash = DatumGetUInt32(hash_uint32(lohalf ^ hihalf)); } #else /* SIZEOF_DATUM != 8 */ hash = DatumGetUInt32(hash_uint32((uint32) res)); #endif addHyperLogLog(&sss->abbr_card, hash); /* Cache result, perhaps saving an expensive strxfrm() call next time */ sss->cache_blob = true; done: /* * Byteswap on little-endian machines. * * This is needed so that ssup_datum_unsigned_cmp() (an unsigned integer * 3-way comparator) works correctly on all platforms. If we didn't do * this, the comparator would have to call memcmp() with a pair of * pointers to the first byte of each abbreviated key, which is slower. */ res = DatumBigEndianToNative(res); /* Don't leak memory here */ if (PointerGetDatum(authoritative) != original) pfree(authoritative); return res; } /* * Callback for estimating effectiveness of abbreviated key optimization, using * heuristic rules. Returns value indicating if the abbreviation optimization * should be aborted, based on its projected effectiveness. */ static bool varstr_abbrev_abort(int memtupcount, SortSupport ssup) { VarStringSortSupport *sss = (VarStringSortSupport *) ssup->ssup_extra; double abbrev_distinct, key_distinct; Assert(ssup->abbreviate); /* Have a little patience */ if (memtupcount < 100) return false; abbrev_distinct = estimateHyperLogLog(&sss->abbr_card); key_distinct = estimateHyperLogLog(&sss->full_card); /* * Clamp cardinality estimates to at least one distinct value. While * NULLs are generally disregarded, if only NULL values were seen so far, * that might misrepresent costs if we failed to clamp. */ if (abbrev_distinct <= 1.0) abbrev_distinct = 1.0; if (key_distinct <= 1.0) key_distinct = 1.0; /* * In the worst case all abbreviated keys are identical, while at the same * time there are differences within full key strings not captured in * abbreviations. */ #ifdef TRACE_SORT if (trace_sort) { double norm_abbrev_card = abbrev_distinct / (double) memtupcount; elog(LOG, "varstr_abbrev: abbrev_distinct after %d: %f " "(key_distinct: %f, norm_abbrev_card: %f, prop_card: %f)", memtupcount, abbrev_distinct, key_distinct, norm_abbrev_card, sss->prop_card); } #endif /* * If the number of distinct abbreviated keys approximately matches the * number of distinct authoritative original keys, that's reason enough to * proceed. We can win even with a very low cardinality set if most * tie-breakers only memcmp(). This is by far the most important * consideration. * * While comparisons that are resolved at the abbreviated key level are * considerably cheaper than tie-breakers resolved with memcmp(), both of * those two outcomes are so much cheaper than a full strcoll() once * sorting is underway that it doesn't seem worth it to weigh abbreviated * cardinality against the overall size of the set in order to more * accurately model costs. Assume that an abbreviated comparison, and an * abbreviated comparison with a cheap memcmp()-based authoritative * resolution are equivalent. */ if (abbrev_distinct > key_distinct * sss->prop_card) { /* * When we have exceeded 10,000 tuples, decay required cardinality * aggressively for next call. * * This is useful because the number of comparisons required on * average increases at a linearithmic rate, and at roughly 10,000 * tuples that factor will start to dominate over the linear costs of * string transformation (this is a conservative estimate). The decay * rate is chosen to be a little less aggressive than halving -- which * (since we're called at points at which memtupcount has doubled) * would never see the cost model actually abort past the first call * following a decay. This decay rate is mostly a precaution against * a sudden, violent swing in how well abbreviated cardinality tracks * full key cardinality. The decay also serves to prevent a marginal * case from being aborted too late, when too much has already been * invested in string transformation. * * It's possible for sets of several million distinct strings with * mere tens of thousands of distinct abbreviated keys to still * benefit very significantly. This will generally occur provided * each abbreviated key is a proxy for a roughly uniform number of the * set's full keys. If it isn't so, we hope to catch that early and * abort. If it isn't caught early, by the time the problem is * apparent it's probably not worth aborting. */ if (memtupcount > 10000) sss->prop_card *= 0.65; return false; } /* * Abort abbreviation strategy. * * The worst case, where all abbreviated keys are identical while all * original strings differ will typically only see a regression of about * 10% in execution time for small to medium sized lists of strings. * Whereas on modern CPUs where cache stalls are the dominant cost, we can * often expect very large improvements, particularly with sets of strings * of moderately high to high abbreviated cardinality. There is little to * lose but much to gain, which our strategy reflects. */ #ifdef TRACE_SORT if (trace_sort) elog(LOG, "varstr_abbrev: aborted abbreviation at %d " "(abbrev_distinct: %f, key_distinct: %f, prop_card: %f)", memtupcount, abbrev_distinct, key_distinct, sss->prop_card); #endif return true; } /* * Generic equalimage support function for character type's operator classes. * Disables the use of deduplication with nondeterministic collations. */ Datum btvarstrequalimage(PG_FUNCTION_ARGS) { /* Oid opcintype = PG_GETARG_OID(0); */ Oid collid = PG_GET_COLLATION(); check_collation_set(collid); if (lc_collate_is_c(collid) || collid == DEFAULT_COLLATION_OID || get_collation_isdeterministic(collid)) PG_RETURN_BOOL(true); else PG_RETURN_BOOL(false); } Datum text_larger(PG_FUNCTION_ARGS) { text *arg1 = PG_GETARG_TEXT_PP(0); text *arg2 = PG_GETARG_TEXT_PP(1); text *result; result = ((text_cmp(arg1, arg2, PG_GET_COLLATION()) > 0) ? arg1 : arg2); PG_RETURN_TEXT_P(result); } Datum text_smaller(PG_FUNCTION_ARGS) { text *arg1 = PG_GETARG_TEXT_PP(0); text *arg2 = PG_GETARG_TEXT_PP(1); text *result; result = ((text_cmp(arg1, arg2, PG_GET_COLLATION()) < 0) ? arg1 : arg2); PG_RETURN_TEXT_P(result); } /* * Cross-type comparison functions for types text and name. */ Datum nameeqtext(PG_FUNCTION_ARGS) { Name arg1 = PG_GETARG_NAME(0); text *arg2 = PG_GETARG_TEXT_PP(1); size_t len1 = strlen(NameStr(*arg1)); size_t len2 = VARSIZE_ANY_EXHDR(arg2); Oid collid = PG_GET_COLLATION(); bool result; check_collation_set(collid); if (collid == C_COLLATION_OID) result = (len1 == len2 && memcmp(NameStr(*arg1), VARDATA_ANY(arg2), len1) == 0); else result = (varstr_cmp(NameStr(*arg1), len1, VARDATA_ANY(arg2), len2, collid) == 0); PG_FREE_IF_COPY(arg2, 1); PG_RETURN_BOOL(result); } Datum texteqname(PG_FUNCTION_ARGS) { text *arg1 = PG_GETARG_TEXT_PP(0); Name arg2 = PG_GETARG_NAME(1); size_t len1 = VARSIZE_ANY_EXHDR(arg1); size_t len2 = strlen(NameStr(*arg2)); Oid collid = PG_GET_COLLATION(); bool result; check_collation_set(collid); if (collid == C_COLLATION_OID) result = (len1 == len2 && memcmp(VARDATA_ANY(arg1), NameStr(*arg2), len1) == 0); else result = (varstr_cmp(VARDATA_ANY(arg1), len1, NameStr(*arg2), len2, collid) == 0); PG_FREE_IF_COPY(arg1, 0); PG_RETURN_BOOL(result); } Datum namenetext(PG_FUNCTION_ARGS) { Name arg1 = PG_GETARG_NAME(0); text *arg2 = PG_GETARG_TEXT_PP(1); size_t len1 = strlen(NameStr(*arg1)); size_t len2 = VARSIZE_ANY_EXHDR(arg2); Oid collid = PG_GET_COLLATION(); bool result; check_collation_set(collid); if (collid == C_COLLATION_OID) result = !(len1 == len2 && memcmp(NameStr(*arg1), VARDATA_ANY(arg2), len1) == 0); else result = !(varstr_cmp(NameStr(*arg1), len1, VARDATA_ANY(arg2), len2, collid) == 0); PG_FREE_IF_COPY(arg2, 1); PG_RETURN_BOOL(result); } Datum textnename(PG_FUNCTION_ARGS) { text *arg1 = PG_GETARG_TEXT_PP(0); Name arg2 = PG_GETARG_NAME(1); size_t len1 = VARSIZE_ANY_EXHDR(arg1); size_t len2 = strlen(NameStr(*arg2)); Oid collid = PG_GET_COLLATION(); bool result; check_collation_set(collid); if (collid == C_COLLATION_OID) result = !(len1 == len2 && memcmp(VARDATA_ANY(arg1), NameStr(*arg2), len1) == 0); else result = !(varstr_cmp(VARDATA_ANY(arg1), len1, NameStr(*arg2), len2, collid) == 0); PG_FREE_IF_COPY(arg1, 0); PG_RETURN_BOOL(result); } Datum btnametextcmp(PG_FUNCTION_ARGS) { Name arg1 = PG_GETARG_NAME(0); text *arg2 = PG_GETARG_TEXT_PP(1); int32 result; result = varstr_cmp(NameStr(*arg1), strlen(NameStr(*arg1)), VARDATA_ANY(arg2), VARSIZE_ANY_EXHDR(arg2), PG_GET_COLLATION()); PG_FREE_IF_COPY(arg2, 1); PG_RETURN_INT32(result); } Datum bttextnamecmp(PG_FUNCTION_ARGS) { text *arg1 = PG_GETARG_TEXT_PP(0); Name arg2 = PG_GETARG_NAME(1); int32 result; result = varstr_cmp(VARDATA_ANY(arg1), VARSIZE_ANY_EXHDR(arg1), NameStr(*arg2), strlen(NameStr(*arg2)), PG_GET_COLLATION()); PG_FREE_IF_COPY(arg1, 0); PG_RETURN_INT32(result); } #define CmpCall(cmpfunc) \ DatumGetInt32(DirectFunctionCall2Coll(cmpfunc, \ PG_GET_COLLATION(), \ PG_GETARG_DATUM(0), \ PG_GETARG_DATUM(1))) Datum namelttext(PG_FUNCTION_ARGS) { PG_RETURN_BOOL(CmpCall(btnametextcmp) < 0); } Datum nameletext(PG_FUNCTION_ARGS) { PG_RETURN_BOOL(CmpCall(btnametextcmp) <= 0); } Datum namegttext(PG_FUNCTION_ARGS) { PG_RETURN_BOOL(CmpCall(btnametextcmp) > 0); } Datum namegetext(PG_FUNCTION_ARGS) { PG_RETURN_BOOL(CmpCall(btnametextcmp) >= 0); } Datum textltname(PG_FUNCTION_ARGS) { PG_RETURN_BOOL(CmpCall(bttextnamecmp) < 0); } Datum textlename(PG_FUNCTION_ARGS) { PG_RETURN_BOOL(CmpCall(bttextnamecmp) <= 0); } Datum textgtname(PG_FUNCTION_ARGS) { PG_RETURN_BOOL(CmpCall(bttextnamecmp) > 0); } Datum textgename(PG_FUNCTION_ARGS) { PG_RETURN_BOOL(CmpCall(bttextnamecmp) >= 0); } #undef CmpCall /* * The following operators support character-by-character comparison * of text datums, to allow building indexes suitable for LIKE clauses. * Note that the regular texteq/textne comparison operators, and regular * support functions 1 and 2 with "C" collation are assumed to be * compatible with these! */ static int internal_text_pattern_compare(text *arg1, text *arg2) { int result; int len1, len2; len1 = VARSIZE_ANY_EXHDR(arg1); len2 = VARSIZE_ANY_EXHDR(arg2); result = memcmp(VARDATA_ANY(arg1), VARDATA_ANY(arg2), Min(len1, len2)); if (result != 0) return result; else if (len1 < len2) return -1; else if (len1 > len2) return 1; else return 0; } Datum text_pattern_lt(PG_FUNCTION_ARGS) { text *arg1 = PG_GETARG_TEXT_PP(0); text *arg2 = PG_GETARG_TEXT_PP(1); int result; result = internal_text_pattern_compare(arg1, arg2); PG_FREE_IF_COPY(arg1, 0); PG_FREE_IF_COPY(arg2, 1); PG_RETURN_BOOL(result < 0); } Datum text_pattern_le(PG_FUNCTION_ARGS) { text *arg1 = PG_GETARG_TEXT_PP(0); text *arg2 = PG_GETARG_TEXT_PP(1); int result; result = internal_text_pattern_compare(arg1, arg2); PG_FREE_IF_COPY(arg1, 0); PG_FREE_IF_COPY(arg2, 1); PG_RETURN_BOOL(result <= 0); } Datum text_pattern_ge(PG_FUNCTION_ARGS) { text *arg1 = PG_GETARG_TEXT_PP(0); text *arg2 = PG_GETARG_TEXT_PP(1); int result; result = internal_text_pattern_compare(arg1, arg2); PG_FREE_IF_COPY(arg1, 0); PG_FREE_IF_COPY(arg2, 1); PG_RETURN_BOOL(result >= 0); } Datum text_pattern_gt(PG_FUNCTION_ARGS) { text *arg1 = PG_GETARG_TEXT_PP(0); text *arg2 = PG_GETARG_TEXT_PP(1); int result; result = internal_text_pattern_compare(arg1, arg2); PG_FREE_IF_COPY(arg1, 0); PG_FREE_IF_COPY(arg2, 1); PG_RETURN_BOOL(result > 0); } Datum bttext_pattern_cmp(PG_FUNCTION_ARGS) { text *arg1 = PG_GETARG_TEXT_PP(0); text *arg2 = PG_GETARG_TEXT_PP(1); int result; result = internal_text_pattern_compare(arg1, arg2); PG_FREE_IF_COPY(arg1, 0); PG_FREE_IF_COPY(arg2, 1); PG_RETURN_INT32(result); } Datum bttext_pattern_sortsupport(PG_FUNCTION_ARGS) { SortSupport ssup = (SortSupport) PG_GETARG_POINTER(0); MemoryContext oldcontext; oldcontext = MemoryContextSwitchTo(ssup->ssup_cxt); /* Use generic string SortSupport, forcing "C" collation */ varstr_sortsupport(ssup, TEXTOID, C_COLLATION_OID); MemoryContextSwitchTo(oldcontext); PG_RETURN_VOID(); } /*------------------------------------------------------------- * byteaoctetlen * * get the number of bytes contained in an instance of type 'bytea' *------------------------------------------------------------- */ Datum byteaoctetlen(PG_FUNCTION_ARGS) { Datum str = PG_GETARG_DATUM(0); /* We need not detoast the input at all */ PG_RETURN_INT32(toast_raw_datum_size(str) - VARHDRSZ); } /* * byteacat - * takes two bytea* and returns a bytea* that is the concatenation of * the two. * * Cloned from textcat and modified as required. */ Datum byteacat(PG_FUNCTION_ARGS) { bytea *t1 = PG_GETARG_BYTEA_PP(0); bytea *t2 = PG_GETARG_BYTEA_PP(1); PG_RETURN_BYTEA_P(bytea_catenate(t1, t2)); } /* * bytea_catenate * Guts of byteacat(), broken out so it can be used by other functions * * Arguments can be in short-header form, but not compressed or out-of-line */ static bytea * bytea_catenate(bytea *t1, bytea *t2) { bytea *result; int len1, len2, len; char *ptr; len1 = VARSIZE_ANY_EXHDR(t1); len2 = VARSIZE_ANY_EXHDR(t2); /* paranoia ... probably should throw error instead? */ if (len1 < 0) len1 = 0; if (len2 < 0) len2 = 0; len = len1 + len2 + VARHDRSZ; result = (bytea *) palloc(len); /* Set size of result string... */ SET_VARSIZE(result, len); /* Fill data field of result string... */ ptr = VARDATA(result); if (len1 > 0) memcpy(ptr, VARDATA_ANY(t1), len1); if (len2 > 0) memcpy(ptr + len1, VARDATA_ANY(t2), len2); return result; } #define PG_STR_GET_BYTEA(str_) \ DatumGetByteaPP(DirectFunctionCall1(byteain, CStringGetDatum(str_))) /* * bytea_substr() * Return a substring starting at the specified position. * Cloned from text_substr and modified as required. * * Input: * - string * - starting position (is one-based) * - string length (optional) * * If the starting position is zero or less, then return from the start of the string * adjusting the length to be consistent with the "negative start" per SQL. * If the length is less than zero, an ERROR is thrown. If no third argument * (length) is provided, the length to the end of the string is assumed. */ Datum bytea_substr(PG_FUNCTION_ARGS) { PG_RETURN_BYTEA_P(bytea_substring(PG_GETARG_DATUM(0), PG_GETARG_INT32(1), PG_GETARG_INT32(2), false)); } /* * bytea_substr_no_len - * Wrapper to avoid opr_sanity failure due to * one function accepting a different number of args. */ Datum bytea_substr_no_len(PG_FUNCTION_ARGS) { PG_RETURN_BYTEA_P(bytea_substring(PG_GETARG_DATUM(0), PG_GETARG_INT32(1), -1, true)); } static bytea * bytea_substring(Datum str, int S, int L, bool length_not_specified) { int32 S1; /* adjusted start position */ int32 L1; /* adjusted substring length */ int32 E; /* end position */ /* * The logic here should generally match text_substring(). */ S1 = Max(S, 1); if (length_not_specified) { /* * Not passed a length - DatumGetByteaPSlice() grabs everything to the * end of the string if we pass it a negative value for length. */ L1 = -1; } else if (L < 0) { /* SQL99 says to throw an error for E < S, i.e., negative length */ ereport(ERROR, (errcode(ERRCODE_SUBSTRING_ERROR), errmsg("negative substring length not allowed"))); L1 = -1; /* silence stupider compilers */ } else if (pg_add_s32_overflow(S, L, &E)) { /* * L could be large enough for S + L to overflow, in which case the * substring must run to end of string. */ L1 = -1; } else { /* * A zero or negative value for the end position can happen if the * start was negative or one. SQL99 says to return a zero-length * string. */ if (E < 1) return PG_STR_GET_BYTEA(""); L1 = E - S1; } /* * If the start position is past the end of the string, SQL99 says to * return a zero-length string -- DatumGetByteaPSlice() will do that for * us. We need only convert S1 to zero-based starting position. */ return DatumGetByteaPSlice(str, S1 - 1, L1); } /* * byteaoverlay * Replace specified substring of first string with second * * The SQL standard defines OVERLAY() in terms of substring and concatenation. * This code is a direct implementation of what the standard says. */ Datum byteaoverlay(PG_FUNCTION_ARGS) { bytea *t1 = PG_GETARG_BYTEA_PP(0); bytea *t2 = PG_GETARG_BYTEA_PP(1); int sp = PG_GETARG_INT32(2); /* substring start position */ int sl = PG_GETARG_INT32(3); /* substring length */ PG_RETURN_BYTEA_P(bytea_overlay(t1, t2, sp, sl)); } Datum byteaoverlay_no_len(PG_FUNCTION_ARGS) { bytea *t1 = PG_GETARG_BYTEA_PP(0); bytea *t2 = PG_GETARG_BYTEA_PP(1); int sp = PG_GETARG_INT32(2); /* substring start position */ int sl; sl = VARSIZE_ANY_EXHDR(t2); /* defaults to length(t2) */ PG_RETURN_BYTEA_P(bytea_overlay(t1, t2, sp, sl)); } static bytea * bytea_overlay(bytea *t1, bytea *t2, int sp, int sl) { bytea *result; bytea *s1; bytea *s2; int sp_pl_sl; /* * Check for possible integer-overflow cases. For negative sp, throw a * "substring length" error because that's what should be expected * according to the spec's definition of OVERLAY(). */ if (sp <= 0) ereport(ERROR, (errcode(ERRCODE_SUBSTRING_ERROR), errmsg("negative substring length not allowed"))); if (pg_add_s32_overflow(sp, sl, &sp_pl_sl)) ereport(ERROR, (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE), errmsg("integer out of range"))); s1 = bytea_substring(PointerGetDatum(t1), 1, sp - 1, false); s2 = bytea_substring(PointerGetDatum(t1), sp_pl_sl, -1, true); result = bytea_catenate(s1, t2); result = bytea_catenate(result, s2); return result; } /* * bit_count */ Datum bytea_bit_count(PG_FUNCTION_ARGS) { bytea *t1 = PG_GETARG_BYTEA_PP(0); PG_RETURN_INT64(pg_popcount(VARDATA_ANY(t1), VARSIZE_ANY_EXHDR(t1))); } /* * byteapos - * Return the position of the specified substring. * Implements the SQL POSITION() function. * Cloned from textpos and modified as required. */ Datum byteapos(PG_FUNCTION_ARGS) { bytea *t1 = PG_GETARG_BYTEA_PP(0); bytea *t2 = PG_GETARG_BYTEA_PP(1); int pos; int px, p; int len1, len2; char *p1, *p2; len1 = VARSIZE_ANY_EXHDR(t1); len2 = VARSIZE_ANY_EXHDR(t2); if (len2 <= 0) PG_RETURN_INT32(1); /* result for empty pattern */ p1 = VARDATA_ANY(t1); p2 = VARDATA_ANY(t2); pos = 0; px = (len1 - len2); for (p = 0; p <= px; p++) { if ((*p2 == *p1) && (memcmp(p1, p2, len2) == 0)) { pos = p + 1; break; }; p1++; }; PG_RETURN_INT32(pos); } /*------------------------------------------------------------- * byteaGetByte * * this routine treats "bytea" as an array of bytes. * It returns the Nth byte (a number between 0 and 255). *------------------------------------------------------------- */ Datum byteaGetByte(PG_FUNCTION_ARGS) { bytea *v = PG_GETARG_BYTEA_PP(0); int32 n = PG_GETARG_INT32(1); int len; int byte; len = VARSIZE_ANY_EXHDR(v); if (n < 0 || n >= len) ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), errmsg("index %d out of valid range, 0..%d", n, len - 1))); byte = ((unsigned char *) VARDATA_ANY(v))[n]; PG_RETURN_INT32(byte); } /*------------------------------------------------------------- * byteaGetBit * * This routine treats a "bytea" type like an array of bits. * It returns the value of the Nth bit (0 or 1). * *------------------------------------------------------------- */ Datum byteaGetBit(PG_FUNCTION_ARGS) { bytea *v = PG_GETARG_BYTEA_PP(0); int64 n = PG_GETARG_INT64(1); int byteNo, bitNo; int len; int byte; len = VARSIZE_ANY_EXHDR(v); if (n < 0 || n >= (int64) len * 8) ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), errmsg("index %lld out of valid range, 0..%lld", (long long) n, (long long) len * 8 - 1))); /* n/8 is now known < len, so safe to cast to int */ byteNo = (int) (n / 8); bitNo = (int) (n % 8); byte = ((unsigned char *) VARDATA_ANY(v))[byteNo]; if (byte & (1 << bitNo)) PG_RETURN_INT32(1); else PG_RETURN_INT32(0); } /*------------------------------------------------------------- * byteaSetByte * * Given an instance of type 'bytea' creates a new one with * the Nth byte set to the given value. * *------------------------------------------------------------- */ Datum byteaSetByte(PG_FUNCTION_ARGS) { bytea *res = PG_GETARG_BYTEA_P_COPY(0); int32 n = PG_GETARG_INT32(1); int32 newByte = PG_GETARG_INT32(2); int len; len = VARSIZE(res) - VARHDRSZ; if (n < 0 || n >= len) ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), errmsg("index %d out of valid range, 0..%d", n, len - 1))); /* * Now set the byte. */ ((unsigned char *) VARDATA(res))[n] = newByte; PG_RETURN_BYTEA_P(res); } /*------------------------------------------------------------- * byteaSetBit * * Given an instance of type 'bytea' creates a new one with * the Nth bit set to the given value. * *------------------------------------------------------------- */ Datum byteaSetBit(PG_FUNCTION_ARGS) { bytea *res = PG_GETARG_BYTEA_P_COPY(0); int64 n = PG_GETARG_INT64(1); int32 newBit = PG_GETARG_INT32(2); int len; int oldByte, newByte; int byteNo, bitNo; len = VARSIZE(res) - VARHDRSZ; if (n < 0 || n >= (int64) len * 8) ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), errmsg("index %lld out of valid range, 0..%lld", (long long) n, (long long) len * 8 - 1))); /* n/8 is now known < len, so safe to cast to int */ byteNo = (int) (n / 8); bitNo = (int) (n % 8); /* * sanity check! */ if (newBit != 0 && newBit != 1) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("new bit must be 0 or 1"))); /* * Update the byte. */ oldByte = ((unsigned char *) VARDATA(res))[byteNo]; if (newBit == 0) newByte = oldByte & (~(1 << bitNo)); else newByte = oldByte | (1 << bitNo); ((unsigned char *) VARDATA(res))[byteNo] = newByte; PG_RETURN_BYTEA_P(res); } /* text_name() * Converts a text type to a Name type. */ Datum text_name(PG_FUNCTION_ARGS) { text *s = PG_GETARG_TEXT_PP(0); Name result; int len; len = VARSIZE_ANY_EXHDR(s); /* Truncate oversize input */ if (len >= NAMEDATALEN) len = pg_mbcliplen(VARDATA_ANY(s), len, NAMEDATALEN - 1); /* We use palloc0 here to ensure result is zero-padded */ result = (Name) palloc0(NAMEDATALEN); memcpy(NameStr(*result), VARDATA_ANY(s), len); PG_RETURN_NAME(result); } /* name_text() * Converts a Name type to a text type. */ Datum name_text(PG_FUNCTION_ARGS) { Name s = PG_GETARG_NAME(0); PG_RETURN_TEXT_P(cstring_to_text(NameStr(*s))); } /* * textToQualifiedNameList - convert a text object to list of names * * This implements the input parsing needed by nextval() and other * functions that take a text parameter representing a qualified name. * We split the name at dots, downcase if not double-quoted, and * truncate names if they're too long. */ List * textToQualifiedNameList(text *textval) { char *rawname; List *result = NIL; List *namelist; ListCell *l; /* Convert to C string (handles possible detoasting). */ /* Note we rely on being able to modify rawname below. */ rawname = text_to_cstring(textval); if (!SplitIdentifierString(rawname, '.', &namelist)) ereport(ERROR, (errcode(ERRCODE_INVALID_NAME), errmsg("invalid name syntax"))); if (namelist == NIL) ereport(ERROR, (errcode(ERRCODE_INVALID_NAME), errmsg("invalid name syntax"))); foreach(l, namelist) { char *curname = (char *) lfirst(l); result = lappend(result, makeString(pstrdup(curname))); } pfree(rawname); list_free(namelist); return result; } /* * SplitIdentifierString --- parse a string containing identifiers * * This is the guts of textToQualifiedNameList, and is exported for use in * other situations such as parsing GUC variables. In the GUC case, it's * important to avoid memory leaks, so the API is designed to minimize the * amount of stuff that needs to be allocated and freed. * * Inputs: * rawstring: the input string; must be overwritable! On return, it's * been modified to contain the separated identifiers. * separator: the separator punctuation expected between identifiers * (typically '.' or ','). Whitespace may also appear around * identifiers. * Outputs: * namelist: filled with a palloc'd list of pointers to identifiers within * rawstring. Caller should list_free() this even on error return. * * Returns true if okay, false if there is a syntax error in the string. * * Note that an empty string is considered okay here, though not in * textToQualifiedNameList. */ bool SplitIdentifierString(char *rawstring, char separator, List **namelist) { char *nextp = rawstring; bool done = false; *namelist = NIL; while (scanner_isspace(*nextp)) nextp++; /* skip leading whitespace */ if (*nextp == '\0') return true; /* allow empty string */ /* At the top of the loop, we are at start of a new identifier. */ do { char *curname; char *endp; if (*nextp == '"') { /* Quoted name --- collapse quote-quote pairs, no downcasing */ curname = nextp + 1; for (;;) { endp = strchr(nextp + 1, '"'); if (endp == NULL) return false; /* mismatched quotes */ if (endp[1] != '"') break; /* found end of quoted name */ /* Collapse adjacent quotes into one quote, and look again */ memmove(endp, endp + 1, strlen(endp)); nextp = endp; } /* endp now points at the terminating quote */ nextp = endp + 1; } else { /* Unquoted name --- extends to separator or whitespace */ char *downname; int len; curname = nextp; while (*nextp && *nextp != separator && !scanner_isspace(*nextp)) nextp++; endp = nextp; if (curname == nextp) return false; /* empty unquoted name not allowed */ /* * Downcase the identifier, using same code as main lexer does. * * XXX because we want to overwrite the input in-place, we cannot * support a downcasing transformation that increases the string * length. This is not a problem given the current implementation * of downcase_truncate_identifier, but we'll probably have to do * something about this someday. */ len = endp - curname; downname = downcase_truncate_identifier(curname, len, false); Assert(strlen(downname) <= len); strncpy(curname, downname, len); /* strncpy is required here */ pfree(downname); } while (scanner_isspace(*nextp)) nextp++; /* skip trailing whitespace */ if (*nextp == separator) { nextp++; while (scanner_isspace(*nextp)) nextp++; /* skip leading whitespace for next */ /* we expect another name, so done remains false */ } else if (*nextp == '\0') done = true; else return false; /* invalid syntax */ /* Now safe to overwrite separator with a null */ *endp = '\0'; /* Truncate name if it's overlength */ truncate_identifier(curname, strlen(curname), false); /* * Finished isolating current name --- add it to list */ *namelist = lappend(*namelist, curname); /* Loop back if we didn't reach end of string */ } while (!done); return true; } /* * SplitDirectoriesString --- parse a string containing file/directory names * * This works fine on file names too; the function name is historical. * * This is similar to SplitIdentifierString, except that the parsing * rules are meant to handle pathnames instead of identifiers: there is * no downcasing, embedded spaces are allowed, the max length is MAXPGPATH-1, * and we apply canonicalize_path() to each extracted string. Because of the * last, the returned strings are separately palloc'd rather than being * pointers into rawstring --- but we still scribble on rawstring. * * Inputs: * rawstring: the input string; must be modifiable! * separator: the separator punctuation expected between directories * (typically ',' or ';'). Whitespace may also appear around * directories. * Outputs: * namelist: filled with a palloc'd list of directory names. * Caller should list_free_deep() this even on error return. * * Returns true if okay, false if there is a syntax error in the string. * * Note that an empty string is considered okay here. */ bool SplitDirectoriesString(char *rawstring, char separator, List **namelist) { char *nextp = rawstring; bool done = false; *namelist = NIL; while (scanner_isspace(*nextp)) nextp++; /* skip leading whitespace */ if (*nextp == '\0') return true; /* allow empty string */ /* At the top of the loop, we are at start of a new directory. */ do { char *curname; char *endp; if (*nextp == '"') { /* Quoted name --- collapse quote-quote pairs */ curname = nextp + 1; for (;;) { endp = strchr(nextp + 1, '"'); if (endp == NULL) return false; /* mismatched quotes */ if (endp[1] != '"') break; /* found end of quoted name */ /* Collapse adjacent quotes into one quote, and look again */ memmove(endp, endp + 1, strlen(endp)); nextp = endp; } /* endp now points at the terminating quote */ nextp = endp + 1; } else { /* Unquoted name --- extends to separator or end of string */ curname = endp = nextp; while (*nextp && *nextp != separator) { /* trailing whitespace should not be included in name */ if (!scanner_isspace(*nextp)) endp = nextp + 1; nextp++; } if (curname == endp) return false; /* empty unquoted name not allowed */ } while (scanner_isspace(*nextp)) nextp++; /* skip trailing whitespace */ if (*nextp == separator) { nextp++; while (scanner_isspace(*nextp)) nextp++; /* skip leading whitespace for next */ /* we expect another name, so done remains false */ } else if (*nextp == '\0') done = true; else return false; /* invalid syntax */ /* Now safe to overwrite separator with a null */ *endp = '\0'; /* Truncate path if it's overlength */ if (strlen(curname) >= MAXPGPATH) curname[MAXPGPATH - 1] = '\0'; /* * Finished isolating current name --- add it to list */ curname = pstrdup(curname); canonicalize_path(curname); *namelist = lappend(*namelist, curname); /* Loop back if we didn't reach end of string */ } while (!done); return true; } /* * SplitGUCList --- parse a string containing identifiers or file names * * This is used to split the value of a GUC_LIST_QUOTE GUC variable, without * presuming whether the elements will be taken as identifiers or file names. * We assume the input has already been through flatten_set_variable_args(), * so that we need never downcase (if appropriate, that was done already). * Nor do we ever truncate, since we don't know the correct max length. * We disallow embedded whitespace for simplicity (it shouldn't matter, * because any embedded whitespace should have led to double-quoting). * Otherwise the API is identical to SplitIdentifierString. * * XXX it's annoying to have so many copies of this string-splitting logic. * However, it's not clear that having one function with a bunch of option * flags would be much better. * * XXX there is a version of this function in src/bin/pg_dump/dumputils.c. * Be sure to update that if you have to change this. * * Inputs: * rawstring: the input string; must be overwritable! On return, it's * been modified to contain the separated identifiers. * separator: the separator punctuation expected between identifiers * (typically '.' or ','). Whitespace may also appear around * identifiers. * Outputs: * namelist: filled with a palloc'd list of pointers to identifiers within * rawstring. Caller should list_free() this even on error return. * * Returns true if okay, false if there is a syntax error in the string. */ bool SplitGUCList(char *rawstring, char separator, List **namelist) { char *nextp = rawstring; bool done = false; *namelist = NIL; while (scanner_isspace(*nextp)) nextp++; /* skip leading whitespace */ if (*nextp == '\0') return true; /* allow empty string */ /* At the top of the loop, we are at start of a new identifier. */ do { char *curname; char *endp; if (*nextp == '"') { /* Quoted name --- collapse quote-quote pairs */ curname = nextp + 1; for (;;) { endp = strchr(nextp + 1, '"'); if (endp == NULL) return false; /* mismatched quotes */ if (endp[1] != '"') break; /* found end of quoted name */ /* Collapse adjacent quotes into one quote, and look again */ memmove(endp, endp + 1, strlen(endp)); nextp = endp; } /* endp now points at the terminating quote */ nextp = endp + 1; } else { /* Unquoted name --- extends to separator or whitespace */ curname = nextp; while (*nextp && *nextp != separator && !scanner_isspace(*nextp)) nextp++; endp = nextp; if (curname == nextp) return false; /* empty unquoted name not allowed */ } while (scanner_isspace(*nextp)) nextp++; /* skip trailing whitespace */ if (*nextp == separator) { nextp++; while (scanner_isspace(*nextp)) nextp++; /* skip leading whitespace for next */ /* we expect another name, so done remains false */ } else if (*nextp == '\0') done = true; else return false; /* invalid syntax */ /* Now safe to overwrite separator with a null */ *endp = '\0'; /* * Finished isolating current name --- add it to list */ *namelist = lappend(*namelist, curname); /* Loop back if we didn't reach end of string */ } while (!done); return true; } /***************************************************************************** * Comparison Functions used for bytea * * Note: btree indexes need these routines not to leak memory; therefore, * be careful to free working copies of toasted datums. Most places don't * need to be so careful. *****************************************************************************/ Datum byteaeq(PG_FUNCTION_ARGS) { Datum arg1 = PG_GETARG_DATUM(0); Datum arg2 = PG_GETARG_DATUM(1); bool result; Size len1, len2; /* * We can use a fast path for unequal lengths, which might save us from * having to detoast one or both values. */ len1 = toast_raw_datum_size(arg1); len2 = toast_raw_datum_size(arg2); if (len1 != len2) result = false; else { bytea *barg1 = DatumGetByteaPP(arg1); bytea *barg2 = DatumGetByteaPP(arg2); result = (memcmp(VARDATA_ANY(barg1), VARDATA_ANY(barg2), len1 - VARHDRSZ) == 0); PG_FREE_IF_COPY(barg1, 0); PG_FREE_IF_COPY(barg2, 1); } PG_RETURN_BOOL(result); } Datum byteane(PG_FUNCTION_ARGS) { Datum arg1 = PG_GETARG_DATUM(0); Datum arg2 = PG_GETARG_DATUM(1); bool result; Size len1, len2; /* * We can use a fast path for unequal lengths, which might save us from * having to detoast one or both values. */ len1 = toast_raw_datum_size(arg1); len2 = toast_raw_datum_size(arg2); if (len1 != len2) result = true; else { bytea *barg1 = DatumGetByteaPP(arg1); bytea *barg2 = DatumGetByteaPP(arg2); result = (memcmp(VARDATA_ANY(barg1), VARDATA_ANY(barg2), len1 - VARHDRSZ) != 0); PG_FREE_IF_COPY(barg1, 0); PG_FREE_IF_COPY(barg2, 1); } PG_RETURN_BOOL(result); } Datum bytealt(PG_FUNCTION_ARGS) { bytea *arg1 = PG_GETARG_BYTEA_PP(0); bytea *arg2 = PG_GETARG_BYTEA_PP(1); int len1, len2; int cmp; len1 = VARSIZE_ANY_EXHDR(arg1); len2 = VARSIZE_ANY_EXHDR(arg2); cmp = memcmp(VARDATA_ANY(arg1), VARDATA_ANY(arg2), Min(len1, len2)); PG_FREE_IF_COPY(arg1, 0); PG_FREE_IF_COPY(arg2, 1); PG_RETURN_BOOL((cmp < 0) || ((cmp == 0) && (len1 < len2))); } Datum byteale(PG_FUNCTION_ARGS) { bytea *arg1 = PG_GETARG_BYTEA_PP(0); bytea *arg2 = PG_GETARG_BYTEA_PP(1); int len1, len2; int cmp; len1 = VARSIZE_ANY_EXHDR(arg1); len2 = VARSIZE_ANY_EXHDR(arg2); cmp = memcmp(VARDATA_ANY(arg1), VARDATA_ANY(arg2), Min(len1, len2)); PG_FREE_IF_COPY(arg1, 0); PG_FREE_IF_COPY(arg2, 1); PG_RETURN_BOOL((cmp < 0) || ((cmp == 0) && (len1 <= len2))); } Datum byteagt(PG_FUNCTION_ARGS) { bytea *arg1 = PG_GETARG_BYTEA_PP(0); bytea *arg2 = PG_GETARG_BYTEA_PP(1); int len1, len2; int cmp; len1 = VARSIZE_ANY_EXHDR(arg1); len2 = VARSIZE_ANY_EXHDR(arg2); cmp = memcmp(VARDATA_ANY(arg1), VARDATA_ANY(arg2), Min(len1, len2)); PG_FREE_IF_COPY(arg1, 0); PG_FREE_IF_COPY(arg2, 1); PG_RETURN_BOOL((cmp > 0) || ((cmp == 0) && (len1 > len2))); } Datum byteage(PG_FUNCTION_ARGS) { bytea *arg1 = PG_GETARG_BYTEA_PP(0); bytea *arg2 = PG_GETARG_BYTEA_PP(1); int len1, len2; int cmp; len1 = VARSIZE_ANY_EXHDR(arg1); len2 = VARSIZE_ANY_EXHDR(arg2); cmp = memcmp(VARDATA_ANY(arg1), VARDATA_ANY(arg2), Min(len1, len2)); PG_FREE_IF_COPY(arg1, 0); PG_FREE_IF_COPY(arg2, 1); PG_RETURN_BOOL((cmp > 0) || ((cmp == 0) && (len1 >= len2))); } Datum byteacmp(PG_FUNCTION_ARGS) { bytea *arg1 = PG_GETARG_BYTEA_PP(0); bytea *arg2 = PG_GETARG_BYTEA_PP(1); int len1, len2; int cmp; len1 = VARSIZE_ANY_EXHDR(arg1); len2 = VARSIZE_ANY_EXHDR(arg2); cmp = memcmp(VARDATA_ANY(arg1), VARDATA_ANY(arg2), Min(len1, len2)); if ((cmp == 0) && (len1 != len2)) cmp = (len1 < len2) ? -1 : 1; PG_FREE_IF_COPY(arg1, 0); PG_FREE_IF_COPY(arg2, 1); PG_RETURN_INT32(cmp); } Datum bytea_sortsupport(PG_FUNCTION_ARGS) { SortSupport ssup = (SortSupport) PG_GETARG_POINTER(0); MemoryContext oldcontext; oldcontext = MemoryContextSwitchTo(ssup->ssup_cxt); /* Use generic string SortSupport, forcing "C" collation */ varstr_sortsupport(ssup, BYTEAOID, C_COLLATION_OID); MemoryContextSwitchTo(oldcontext); PG_RETURN_VOID(); } /* * appendStringInfoText * * Append a text to str. * Like appendStringInfoString(str, text_to_cstring(t)) but faster. */ static void appendStringInfoText(StringInfo str, const text *t) { appendBinaryStringInfo(str, VARDATA_ANY(t), VARSIZE_ANY_EXHDR(t)); } /* * replace_text * replace all occurrences of 'old_sub_str' in 'orig_str' * with 'new_sub_str' to form 'new_str' * * returns 'orig_str' if 'old_sub_str' == '' or 'orig_str' == '' * otherwise returns 'new_str' */ Datum replace_text(PG_FUNCTION_ARGS) { text *src_text = PG_GETARG_TEXT_PP(0); text *from_sub_text = PG_GETARG_TEXT_PP(1); text *to_sub_text = PG_GETARG_TEXT_PP(2); int src_text_len; int from_sub_text_len; TextPositionState state; text *ret_text; int chunk_len; char *curr_ptr; char *start_ptr; StringInfoData str; bool found; src_text_len = VARSIZE_ANY_EXHDR(src_text); from_sub_text_len = VARSIZE_ANY_EXHDR(from_sub_text); /* Return unmodified source string if empty source or pattern */ if (src_text_len < 1 || from_sub_text_len < 1) { PG_RETURN_TEXT_P(src_text); } text_position_setup(src_text, from_sub_text, PG_GET_COLLATION(), &state); found = text_position_next(&state); /* When the from_sub_text is not found, there is nothing to do. */ if (!found) { text_position_cleanup(&state); PG_RETURN_TEXT_P(src_text); } curr_ptr = text_position_get_match_ptr(&state); start_ptr = VARDATA_ANY(src_text); initStringInfo(&str); do { CHECK_FOR_INTERRUPTS(); /* copy the data skipped over by last text_position_next() */ chunk_len = curr_ptr - start_ptr; appendBinaryStringInfo(&str, start_ptr, chunk_len); appendStringInfoText(&str, to_sub_text); start_ptr = curr_ptr + from_sub_text_len; found = text_position_next(&state); if (found) curr_ptr = text_position_get_match_ptr(&state); } while (found); /* copy trailing data */ chunk_len = ((char *) src_text + VARSIZE_ANY(src_text)) - start_ptr; appendBinaryStringInfo(&str, start_ptr, chunk_len); text_position_cleanup(&state); ret_text = cstring_to_text_with_len(str.data, str.len); pfree(str.data); PG_RETURN_TEXT_P(ret_text); } /* * check_replace_text_has_escape * * Returns 0 if text contains no backslashes that need processing. * Returns 1 if text contains backslashes, but not regexp submatch specifiers. * Returns 2 if text contains regexp submatch specifiers (\1 .. \9). */ static int check_replace_text_has_escape(const text *replace_text) { int result = 0; const char *p = VARDATA_ANY(replace_text); const char *p_end = p + VARSIZE_ANY_EXHDR(replace_text); while (p < p_end) { /* Find next escape char, if any. */ p = memchr(p, '\\', p_end - p); if (p == NULL) break; p++; /* Note: a backslash at the end doesn't require extra processing. */ if (p < p_end) { if (*p >= '1' && *p <= '9') return 2; /* Found a submatch specifier, so done */ result = 1; /* Found some other sequence, keep looking */ p++; } } return result; } /* * appendStringInfoRegexpSubstr * * Append replace_text to str, substituting regexp back references for * \n escapes. start_ptr is the start of the match in the source string, * at logical character position data_pos. */ static void appendStringInfoRegexpSubstr(StringInfo str, text *replace_text, regmatch_t *pmatch, char *start_ptr, int data_pos) { const char *p = VARDATA_ANY(replace_text); const char *p_end = p + VARSIZE_ANY_EXHDR(replace_text); while (p < p_end) { const char *chunk_start = p; int so; int eo; /* Find next escape char, if any. */ p = memchr(p, '\\', p_end - p); if (p == NULL) p = p_end; /* Copy the text we just scanned over, if any. */ if (p > chunk_start) appendBinaryStringInfo(str, chunk_start, p - chunk_start); /* Done if at end of string, else advance over escape char. */ if (p >= p_end) break; p++; if (p >= p_end) { /* Escape at very end of input. Treat same as unexpected char */ appendStringInfoChar(str, '\\'); break; } if (*p >= '1' && *p <= '9') { /* Use the back reference of regexp. */ int idx = *p - '0'; so = pmatch[idx].rm_so; eo = pmatch[idx].rm_eo; p++; } else if (*p == '&') { /* Use the entire matched string. */ so = pmatch[0].rm_so; eo = pmatch[0].rm_eo; p++; } else if (*p == '\\') { /* \\ means transfer one \ to output. */ appendStringInfoChar(str, '\\'); p++; continue; } else { /* * If escape char is not followed by any expected char, just treat * it as ordinary data to copy. (XXX would it be better to throw * an error?) */ appendStringInfoChar(str, '\\'); continue; } if (so >= 0 && eo >= 0) { /* * Copy the text that is back reference of regexp. Note so and eo * are counted in characters not bytes. */ char *chunk_start; int chunk_len; Assert(so >= data_pos); chunk_start = start_ptr; chunk_start += charlen_to_bytelen(chunk_start, so - data_pos); chunk_len = charlen_to_bytelen(chunk_start, eo - so); appendBinaryStringInfo(str, chunk_start, chunk_len); } } } /* * replace_text_regexp * * replace substring(s) in src_text that match pattern with replace_text. * The replace_text can contain backslash markers to substitute * (parts of) the matched text. * * cflags: regexp compile flags. * collation: collation to use. * search_start: the character (not byte) offset in src_text at which to * begin searching. * n: if 0, replace all matches; if > 0, replace only the N'th match. */ text * replace_text_regexp(text *src_text, text *pattern_text, text *replace_text, int cflags, Oid collation, int search_start, int n) { text *ret_text; regex_t *re; int src_text_len = VARSIZE_ANY_EXHDR(src_text); int nmatches = 0; StringInfoData buf; regmatch_t pmatch[10]; /* main match, plus \1 to \9 */ int nmatch = lengthof(pmatch); pg_wchar *data; size_t data_len; int data_pos; char *start_ptr; int escape_status; initStringInfo(&buf); /* Convert data string to wide characters. */ data = (pg_wchar *) palloc((src_text_len + 1) * sizeof(pg_wchar)); data_len = pg_mb2wchar_with_len(VARDATA_ANY(src_text), data, src_text_len); /* Check whether replace_text has escapes, especially regexp submatches. */ escape_status = check_replace_text_has_escape(replace_text); /* If no regexp submatches, we can use REG_NOSUB. */ if (escape_status < 2) { cflags |= REG_NOSUB; /* Also tell pg_regexec we only want the whole-match location. */ nmatch = 1; } /* Prepare the regexp. */ re = RE_compile_and_cache(pattern_text, cflags, collation); /* start_ptr points to the data_pos'th character of src_text */ start_ptr = (char *) VARDATA_ANY(src_text); data_pos = 0; while (search_start <= data_len) { int regexec_result; CHECK_FOR_INTERRUPTS(); regexec_result = pg_regexec(re, data, data_len, search_start, NULL, /* no details */ nmatch, pmatch, 0); if (regexec_result == REG_NOMATCH) break; if (regexec_result != REG_OKAY) { char errMsg[100]; pg_regerror(regexec_result, re, errMsg, sizeof(errMsg)); ereport(ERROR, (errcode(ERRCODE_INVALID_REGULAR_EXPRESSION), errmsg("regular expression failed: %s", errMsg))); } /* * Count matches, and decide whether to replace this match. */ nmatches++; if (n > 0 && nmatches != n) { /* * No, so advance search_start, but not start_ptr/data_pos. (Thus, * we treat the matched text as if it weren't matched, and copy it * to the output later.) */ search_start = pmatch[0].rm_eo; if (pmatch[0].rm_so == pmatch[0].rm_eo) search_start++; continue; } /* * Copy the text to the left of the match position. Note we are given * character not byte indexes. */ if (pmatch[0].rm_so - data_pos > 0) { int chunk_len; chunk_len = charlen_to_bytelen(start_ptr, pmatch[0].rm_so - data_pos); appendBinaryStringInfo(&buf, start_ptr, chunk_len); /* * Advance start_ptr over that text, to avoid multiple rescans of * it if the replace_text contains multiple back-references. */ start_ptr += chunk_len; data_pos = pmatch[0].rm_so; } /* * Copy the replace_text, processing escapes if any are present. */ if (escape_status > 0) appendStringInfoRegexpSubstr(&buf, replace_text, pmatch, start_ptr, data_pos); else appendStringInfoText(&buf, replace_text); /* Advance start_ptr and data_pos over the matched text. */ start_ptr += charlen_to_bytelen(start_ptr, pmatch[0].rm_eo - data_pos); data_pos = pmatch[0].rm_eo; /* * If we only want to replace one occurrence, we're done. */ if (n > 0) break; /* * Advance search position. Normally we start the next search at the * end of the previous match; but if the match was of zero length, we * have to advance by one character, or we'd just find the same match * again. */ search_start = data_pos; if (pmatch[0].rm_so == pmatch[0].rm_eo) search_start++; } /* * Copy the text to the right of the last match. */ if (data_pos < data_len) { int chunk_len; chunk_len = ((char *) src_text + VARSIZE_ANY(src_text)) - start_ptr; appendBinaryStringInfo(&buf, start_ptr, chunk_len); } ret_text = cstring_to_text_with_len(buf.data, buf.len); pfree(buf.data); pfree(data); return ret_text; } /* * split_part * parse input string based on provided field separator * return N'th item (1 based, negative counts from end) */ Datum split_part(PG_FUNCTION_ARGS) { text *inputstring = PG_GETARG_TEXT_PP(0); text *fldsep = PG_GETARG_TEXT_PP(1); int fldnum = PG_GETARG_INT32(2); int inputstring_len; int fldsep_len; TextPositionState state; char *start_ptr; char *end_ptr; text *result_text; bool found; /* field number is 1 based */ if (fldnum == 0) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("field position must not be zero"))); inputstring_len = VARSIZE_ANY_EXHDR(inputstring); fldsep_len = VARSIZE_ANY_EXHDR(fldsep); /* return empty string for empty input string */ if (inputstring_len < 1) PG_RETURN_TEXT_P(cstring_to_text("")); /* handle empty field separator */ if (fldsep_len < 1) { /* if first or last field, return input string, else empty string */ if (fldnum == 1 || fldnum == -1) PG_RETURN_TEXT_P(inputstring); else PG_RETURN_TEXT_P(cstring_to_text("")); } /* find the first field separator */ text_position_setup(inputstring, fldsep, PG_GET_COLLATION(), &state); found = text_position_next(&state); /* special case if fldsep not found at all */ if (!found) { text_position_cleanup(&state); /* if first or last field, return input string, else empty string */ if (fldnum == 1 || fldnum == -1) PG_RETURN_TEXT_P(inputstring); else PG_RETURN_TEXT_P(cstring_to_text("")); } /* * take care of a negative field number (i.e. count from the right) by * converting to a positive field number; we need total number of fields */ if (fldnum < 0) { /* we found a fldsep, so there are at least two fields */ int numfields = 2; while (text_position_next(&state)) numfields++; /* special case of last field does not require an extra pass */ if (fldnum == -1) { start_ptr = text_position_get_match_ptr(&state) + fldsep_len; end_ptr = VARDATA_ANY(inputstring) + inputstring_len; text_position_cleanup(&state); PG_RETURN_TEXT_P(cstring_to_text_with_len(start_ptr, end_ptr - start_ptr)); } /* else, convert fldnum to positive notation */ fldnum += numfields + 1; /* if nonexistent field, return empty string */ if (fldnum <= 0) { text_position_cleanup(&state); PG_RETURN_TEXT_P(cstring_to_text("")); } /* reset to pointing at first match, but now with positive fldnum */ text_position_reset(&state); found = text_position_next(&state); Assert(found); } /* identify bounds of first field */ start_ptr = VARDATA_ANY(inputstring); end_ptr = text_position_get_match_ptr(&state); while (found && --fldnum > 0) { /* identify bounds of next field */ start_ptr = end_ptr + fldsep_len; found = text_position_next(&state); if (found) end_ptr = text_position_get_match_ptr(&state); } text_position_cleanup(&state); if (fldnum > 0) { /* N'th field separator not found */ /* if last field requested, return it, else empty string */ if (fldnum == 1) { int last_len = start_ptr - VARDATA_ANY(inputstring); result_text = cstring_to_text_with_len(start_ptr, inputstring_len - last_len); } else result_text = cstring_to_text(""); } else { /* non-last field requested */ result_text = cstring_to_text_with_len(start_ptr, end_ptr - start_ptr); } PG_RETURN_TEXT_P(result_text); } /* * Convenience function to return true when two text params are equal. */ static bool text_isequal(text *txt1, text *txt2, Oid collid) { return DatumGetBool(DirectFunctionCall2Coll(texteq, collid, PointerGetDatum(txt1), PointerGetDatum(txt2))); } /* * text_to_array * parse input string and return text array of elements, * based on provided field separator */ Datum text_to_array(PG_FUNCTION_ARGS) { SplitTextOutputData tstate; /* For array output, tstate should start as all zeroes */ memset(&tstate, 0, sizeof(tstate)); if (!split_text(fcinfo, &tstate)) PG_RETURN_NULL(); if (tstate.astate == NULL) PG_RETURN_ARRAYTYPE_P(construct_empty_array(TEXTOID)); PG_RETURN_DATUM(makeArrayResult(tstate.astate, CurrentMemoryContext)); } /* * text_to_array_null * parse input string and return text array of elements, * based on provided field separator and null string * * This is a separate entry point only to prevent the regression tests from * complaining about different argument sets for the same internal function. */ Datum text_to_array_null(PG_FUNCTION_ARGS) { return text_to_array(fcinfo); } /* * text_to_table * parse input string and return table of elements, * based on provided field separator */ Datum text_to_table(PG_FUNCTION_ARGS) { ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo; SplitTextOutputData tstate; tstate.astate = NULL; InitMaterializedSRF(fcinfo, MAT_SRF_USE_EXPECTED_DESC); tstate.tupstore = rsi->setResult; tstate.tupdesc = rsi->setDesc; (void) split_text(fcinfo, &tstate); return (Datum) 0; } /* * text_to_table_null * parse input string and return table of elements, * based on provided field separator and null string * * This is a separate entry point only to prevent the regression tests from * complaining about different argument sets for the same internal function. */ Datum text_to_table_null(PG_FUNCTION_ARGS) { return text_to_table(fcinfo); } /* * Common code for text_to_array, text_to_array_null, text_to_table * and text_to_table_null functions. * * These are not strict so we have to test for null inputs explicitly. * Returns false if result is to be null, else returns true. * * Note that if the result is valid but empty (zero elements), we return * without changing *tstate --- caller must handle that case, too. */ static bool split_text(FunctionCallInfo fcinfo, SplitTextOutputData *tstate) { text *inputstring; text *fldsep; text *null_string; Oid collation = PG_GET_COLLATION(); int inputstring_len; int fldsep_len; char *start_ptr; text *result_text; /* when input string is NULL, then result is NULL too */ if (PG_ARGISNULL(0)) return false; inputstring = PG_GETARG_TEXT_PP(0); /* fldsep can be NULL */ if (!PG_ARGISNULL(1)) fldsep = PG_GETARG_TEXT_PP(1); else fldsep = NULL; /* null_string can be NULL or omitted */ if (PG_NARGS() > 2 && !PG_ARGISNULL(2)) null_string = PG_GETARG_TEXT_PP(2); else null_string = NULL; if (fldsep != NULL) { /* * Normal case with non-null fldsep. Use the text_position machinery * to search for occurrences of fldsep. */ TextPositionState state; inputstring_len = VARSIZE_ANY_EXHDR(inputstring); fldsep_len = VARSIZE_ANY_EXHDR(fldsep); /* return empty set for empty input string */ if (inputstring_len < 1) return true; /* empty field separator: return input string as a one-element set */ if (fldsep_len < 1) { split_text_accum_result(tstate, inputstring, null_string, collation); return true; } text_position_setup(inputstring, fldsep, collation, &state); start_ptr = VARDATA_ANY(inputstring); for (;;) { bool found; char *end_ptr; int chunk_len; CHECK_FOR_INTERRUPTS(); found = text_position_next(&state); if (!found) { /* fetch last field */ chunk_len = ((char *) inputstring + VARSIZE_ANY(inputstring)) - start_ptr; end_ptr = NULL; /* not used, but some compilers complain */ } else { /* fetch non-last field */ end_ptr = text_position_get_match_ptr(&state); chunk_len = end_ptr - start_ptr; } /* build a temp text datum to pass to split_text_accum_result */ result_text = cstring_to_text_with_len(start_ptr, chunk_len); /* stash away this field */ split_text_accum_result(tstate, result_text, null_string, collation); pfree(result_text); if (!found) break; start_ptr = end_ptr + fldsep_len; } text_position_cleanup(&state); } else { /* * When fldsep is NULL, each character in the input string becomes a * separate element in the result set. The separator is effectively * the space between characters. */ inputstring_len = VARSIZE_ANY_EXHDR(inputstring); start_ptr = VARDATA_ANY(inputstring); while (inputstring_len > 0) { int chunk_len = pg_mblen(start_ptr); CHECK_FOR_INTERRUPTS(); /* build a temp text datum to pass to split_text_accum_result */ result_text = cstring_to_text_with_len(start_ptr, chunk_len); /* stash away this field */ split_text_accum_result(tstate, result_text, null_string, collation); pfree(result_text); start_ptr += chunk_len; inputstring_len -= chunk_len; } } return true; } /* * Add text item to result set (table or array). * * This is also responsible for checking to see if the item matches * the null_string, in which case we should emit NULL instead. */ static void split_text_accum_result(SplitTextOutputData *tstate, text *field_value, text *null_string, Oid collation) { bool is_null = false; if (null_string && text_isequal(field_value, null_string, collation)) is_null = true; if (tstate->tupstore) { Datum values[1]; bool nulls[1]; values[0] = PointerGetDatum(field_value); nulls[0] = is_null; tuplestore_putvalues(tstate->tupstore, tstate->tupdesc, values, nulls); } else { tstate->astate = accumArrayResult(tstate->astate, PointerGetDatum(field_value), is_null, TEXTOID, CurrentMemoryContext); } } /* * array_to_text * concatenate Cstring representation of input array elements * using provided field separator */ Datum array_to_text(PG_FUNCTION_ARGS) { ArrayType *v = PG_GETARG_ARRAYTYPE_P(0); char *fldsep = text_to_cstring(PG_GETARG_TEXT_PP(1)); PG_RETURN_TEXT_P(array_to_text_internal(fcinfo, v, fldsep, NULL)); } /* * array_to_text_null * concatenate Cstring representation of input array elements * using provided field separator and null string * * This version is not strict so we have to test for null inputs explicitly. */ Datum array_to_text_null(PG_FUNCTION_ARGS) { ArrayType *v; char *fldsep; char *null_string; /* returns NULL when first or second parameter is NULL */ if (PG_ARGISNULL(0) || PG_ARGISNULL(1)) PG_RETURN_NULL(); v = PG_GETARG_ARRAYTYPE_P(0); fldsep = text_to_cstring(PG_GETARG_TEXT_PP(1)); /* NULL null string is passed through as a null pointer */ if (!PG_ARGISNULL(2)) null_string = text_to_cstring(PG_GETARG_TEXT_PP(2)); else null_string = NULL; PG_RETURN_TEXT_P(array_to_text_internal(fcinfo, v, fldsep, null_string)); } /* * common code for array_to_text and array_to_text_null functions */ static text * array_to_text_internal(FunctionCallInfo fcinfo, ArrayType *v, const char *fldsep, const char *null_string) { text *result; int nitems, *dims, ndims; Oid element_type; int typlen; bool typbyval; char typalign; StringInfoData buf; bool printed = false; char *p; bits8 *bitmap; int bitmask; int i; ArrayMetaState *my_extra; ndims = ARR_NDIM(v); dims = ARR_DIMS(v); nitems = ArrayGetNItems(ndims, dims); /* if there are no elements, return an empty string */ if (nitems == 0) return cstring_to_text_with_len("", 0); element_type = ARR_ELEMTYPE(v); initStringInfo(&buf); /* * We arrange to look up info about element type, including its output * conversion proc, only once per series of calls, assuming the element * type doesn't change underneath us. */ my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra; if (my_extra == NULL) { fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt, sizeof(ArrayMetaState)); my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra; my_extra->element_type = ~element_type; } if (my_extra->element_type != element_type) { /* * Get info about element type, including its output conversion proc */ get_type_io_data(element_type, IOFunc_output, &my_extra->typlen, &my_extra->typbyval, &my_extra->typalign, &my_extra->typdelim, &my_extra->typioparam, &my_extra->typiofunc); fmgr_info_cxt(my_extra->typiofunc, &my_extra->proc, fcinfo->flinfo->fn_mcxt); my_extra->element_type = element_type; } typlen = my_extra->typlen; typbyval = my_extra->typbyval; typalign = my_extra->typalign; p = ARR_DATA_PTR(v); bitmap = ARR_NULLBITMAP(v); bitmask = 1; for (i = 0; i < nitems; i++) { Datum itemvalue; char *value; /* Get source element, checking for NULL */ if (bitmap && (*bitmap & bitmask) == 0) { /* if null_string is NULL, we just ignore null elements */ if (null_string != NULL) { if (printed) appendStringInfo(&buf, "%s%s", fldsep, null_string); else appendStringInfoString(&buf, null_string); printed = true; } } else { itemvalue = fetch_att(p, typbyval, typlen); value = OutputFunctionCall(&my_extra->proc, itemvalue); if (printed) appendStringInfo(&buf, "%s%s", fldsep, value); else appendStringInfoString(&buf, value); printed = true; p = att_addlength_pointer(p, typlen, p); p = (char *) att_align_nominal(p, typalign); } /* advance bitmap pointer if any */ if (bitmap) { bitmask <<= 1; if (bitmask == 0x100) { bitmap++; bitmask = 1; } } } result = cstring_to_text_with_len(buf.data, buf.len); pfree(buf.data); return result; } /* * Workhorse for to_bin, to_oct, and to_hex. Note that base must be > 1 and <= * 16. */ static inline text * convert_to_base(uint64 value, int base) { const char *digits = "0123456789abcdef"; /* We size the buffer for to_bin's longest possible return value. */ char buf[sizeof(uint64) * BITS_PER_BYTE]; char *const end = buf + sizeof(buf); char *ptr = end; Assert(base > 1); Assert(base <= 16); do { *--ptr = digits[value % base]; value /= base; } while (ptr > buf && value); return cstring_to_text_with_len(ptr, end - ptr); } /* * Convert an integer to a string containing a base-2 (binary) representation * of the number. */ Datum to_bin32(PG_FUNCTION_ARGS) { uint64 value = (uint32) PG_GETARG_INT32(0); PG_RETURN_TEXT_P(convert_to_base(value, 2)); } Datum to_bin64(PG_FUNCTION_ARGS) { uint64 value = (uint64) PG_GETARG_INT64(0); PG_RETURN_TEXT_P(convert_to_base(value, 2)); } /* * Convert an integer to a string containing a base-8 (oct) representation of * the number. */ Datum to_oct32(PG_FUNCTION_ARGS) { uint64 value = (uint32) PG_GETARG_INT32(0); PG_RETURN_TEXT_P(convert_to_base(value, 8)); } Datum to_oct64(PG_FUNCTION_ARGS) { uint64 value = (uint64) PG_GETARG_INT64(0); PG_RETURN_TEXT_P(convert_to_base(value, 8)); } /* * Convert an integer to a string containing a base-16 (hex) representation of * the number. */ Datum to_hex32(PG_FUNCTION_ARGS) { uint64 value = (uint32) PG_GETARG_INT32(0); PG_RETURN_TEXT_P(convert_to_base(value, 16)); } Datum to_hex64(PG_FUNCTION_ARGS) { uint64 value = (uint64) PG_GETARG_INT64(0); PG_RETURN_TEXT_P(convert_to_base(value, 16)); } /* * Return the size of a datum, possibly compressed * * Works on any data type */ Datum pg_column_size(PG_FUNCTION_ARGS) { Datum value = PG_GETARG_DATUM(0); int32 result; int typlen; /* On first call, get the input type's typlen, and save at *fn_extra */ if (fcinfo->flinfo->fn_extra == NULL) { /* Lookup the datatype of the supplied argument */ Oid argtypeid = get_fn_expr_argtype(fcinfo->flinfo, 0); typlen = get_typlen(argtypeid); if (typlen == 0) /* should not happen */ elog(ERROR, "cache lookup failed for type %u", argtypeid); fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt, sizeof(int)); *((int *) fcinfo->flinfo->fn_extra) = typlen; } else typlen = *((int *) fcinfo->flinfo->fn_extra); if (typlen == -1) { /* varlena type, possibly toasted */ result = toast_datum_size(value); } else if (typlen == -2) { /* cstring */ result = strlen(DatumGetCString(value)) + 1; } else { /* ordinary fixed-width type */ result = typlen; } PG_RETURN_INT32(result); } /* * Return the compression method stored in the compressed attribute. Return * NULL for non varlena type or uncompressed data. */ Datum pg_column_compression(PG_FUNCTION_ARGS) { int typlen; char *result; ToastCompressionId cmid; /* On first call, get the input type's typlen, and save at *fn_extra */ if (fcinfo->flinfo->fn_extra == NULL) { /* Lookup the datatype of the supplied argument */ Oid argtypeid = get_fn_expr_argtype(fcinfo->flinfo, 0); typlen = get_typlen(argtypeid); if (typlen == 0) /* should not happen */ elog(ERROR, "cache lookup failed for type %u", argtypeid); fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt, sizeof(int)); *((int *) fcinfo->flinfo->fn_extra) = typlen; } else typlen = *((int *) fcinfo->flinfo->fn_extra); if (typlen != -1) PG_RETURN_NULL(); /* get the compression method id stored in the compressed varlena */ cmid = toast_get_compression_id((struct varlena *) DatumGetPointer(PG_GETARG_DATUM(0))); if (cmid == TOAST_INVALID_COMPRESSION_ID) PG_RETURN_NULL(); /* convert compression method id to compression method name */ switch (cmid) { case TOAST_PGLZ_COMPRESSION_ID: result = "pglz"; break; case TOAST_LZ4_COMPRESSION_ID: result = "lz4"; break; default: elog(ERROR, "invalid compression method id %d", cmid); } PG_RETURN_TEXT_P(cstring_to_text(result)); } /* * string_agg - Concatenates values and returns string. * * Syntax: string_agg(value text, delimiter text) RETURNS text * * Note: Any NULL values are ignored. The first-call delimiter isn't * actually used at all, and on subsequent calls the delimiter precedes * the associated value. */ /* subroutine to initialize state */ static StringInfo makeStringAggState(FunctionCallInfo fcinfo) { StringInfo state; MemoryContext aggcontext; MemoryContext oldcontext; if (!AggCheckCallContext(fcinfo, &aggcontext)) { /* cannot be called directly because of internal-type argument */ elog(ERROR, "string_agg_transfn called in non-aggregate context"); } /* * Create state in aggregate context. It'll stay there across subsequent * calls. */ oldcontext = MemoryContextSwitchTo(aggcontext); state = makeStringInfo(); MemoryContextSwitchTo(oldcontext); return state; } Datum string_agg_transfn(PG_FUNCTION_ARGS) { StringInfo state; state = PG_ARGISNULL(0) ? NULL : (StringInfo) PG_GETARG_POINTER(0); /* Append the value unless null, preceding it with the delimiter. */ if (!PG_ARGISNULL(1)) { text *value = PG_GETARG_TEXT_PP(1); bool isfirst = false; /* * You might think we can just throw away the first delimiter, however * we must keep it as we may be a parallel worker doing partial * aggregation building a state to send to the main process. We need * to keep the delimiter of every aggregation so that the combine * function can properly join up the strings of two separately * partially aggregated results. The first delimiter is only stripped * off in the final function. To know how much to strip off the front * of the string, we store the length of the first delimiter in the * StringInfo's cursor field, which we don't otherwise need here. */ if (state == NULL) { state = makeStringAggState(fcinfo); isfirst = true; } if (!PG_ARGISNULL(2)) { text *delim = PG_GETARG_TEXT_PP(2); appendStringInfoText(state, delim); if (isfirst) state->cursor = VARSIZE_ANY_EXHDR(delim); } appendStringInfoText(state, value); } /* * The transition type for string_agg() is declared to be "internal", * which is a pass-by-value type the same size as a pointer. */ if (state) PG_RETURN_POINTER(state); PG_RETURN_NULL(); } /* * string_agg_combine * Aggregate combine function for string_agg(text) and string_agg(bytea) */ Datum string_agg_combine(PG_FUNCTION_ARGS) { StringInfo state1; StringInfo state2; MemoryContext agg_context; if (!AggCheckCallContext(fcinfo, &agg_context)) elog(ERROR, "aggregate function called in non-aggregate context"); state1 = PG_ARGISNULL(0) ? NULL : (StringInfo) PG_GETARG_POINTER(0); state2 = PG_ARGISNULL(1) ? NULL : (StringInfo) PG_GETARG_POINTER(1); if (state2 == NULL) { /* * NULL state2 is easy, just return state1, which we know is already * in the agg_context */ if (state1 == NULL) PG_RETURN_NULL(); PG_RETURN_POINTER(state1); } if (state1 == NULL) { /* We must copy state2's data into the agg_context */ MemoryContext old_context; old_context = MemoryContextSwitchTo(agg_context); state1 = makeStringAggState(fcinfo); appendBinaryStringInfo(state1, state2->data, state2->len); state1->cursor = state2->cursor; MemoryContextSwitchTo(old_context); } else if (state2->len > 0) { /* Combine ... state1->cursor does not change in this case */ appendBinaryStringInfo(state1, state2->data, state2->len); } PG_RETURN_POINTER(state1); } /* * string_agg_serialize * Aggregate serialize function for string_agg(text) and string_agg(bytea) * * This is strict, so we need not handle NULL input */ Datum string_agg_serialize(PG_FUNCTION_ARGS) { StringInfo state; StringInfoData buf; bytea *result; /* cannot be called directly because of internal-type argument */ Assert(AggCheckCallContext(fcinfo, NULL)); state = (StringInfo) PG_GETARG_POINTER(0); pq_begintypsend(&buf); /* cursor */ pq_sendint(&buf, state->cursor, 4); /* data */ pq_sendbytes(&buf, state->data, state->len); result = pq_endtypsend(&buf); PG_RETURN_BYTEA_P(result); } /* * string_agg_deserialize * Aggregate deserial function for string_agg(text) and string_agg(bytea) * * This is strict, so we need not handle NULL input */ Datum string_agg_deserialize(PG_FUNCTION_ARGS) { bytea *sstate; StringInfo result; StringInfoData buf; char *data; int datalen; /* cannot be called directly because of internal-type argument */ Assert(AggCheckCallContext(fcinfo, NULL)); sstate = PG_GETARG_BYTEA_PP(0); /* * Copy the bytea into a StringInfo so that we can "receive" it using the * standard recv-function infrastructure. */ initStringInfo(&buf); appendBinaryStringInfo(&buf, VARDATA_ANY(sstate), VARSIZE_ANY_EXHDR(sstate)); result = makeStringAggState(fcinfo); /* cursor */ result->cursor = pq_getmsgint(&buf, 4); /* data */ datalen = VARSIZE_ANY_EXHDR(sstate) - 4; data = (char *) pq_getmsgbytes(&buf, datalen); appendBinaryStringInfo(result, data, datalen); pq_getmsgend(&buf); pfree(buf.data); PG_RETURN_POINTER(result); } Datum string_agg_finalfn(PG_FUNCTION_ARGS) { StringInfo state; /* cannot be called directly because of internal-type argument */ Assert(AggCheckCallContext(fcinfo, NULL)); state = PG_ARGISNULL(0) ? NULL : (StringInfo) PG_GETARG_POINTER(0); if (state != NULL) { /* As per comment in transfn, strip data before the cursor position */ PG_RETURN_TEXT_P(cstring_to_text_with_len(&state->data[state->cursor], state->len - state->cursor)); } else PG_RETURN_NULL(); } /* * Prepare cache with fmgr info for the output functions of the datatypes of * the arguments of a concat-like function, beginning with argument "argidx". * (Arguments before that will have corresponding slots in the resulting * FmgrInfo array, but we don't fill those slots.) */ static FmgrInfo * build_concat_foutcache(FunctionCallInfo fcinfo, int argidx) { FmgrInfo *foutcache; int i; /* We keep the info in fn_mcxt so it survives across calls */ foutcache = (FmgrInfo *) MemoryContextAlloc(fcinfo->flinfo->fn_mcxt, PG_NARGS() * sizeof(FmgrInfo)); for (i = argidx; i < PG_NARGS(); i++) { Oid valtype; Oid typOutput; bool typIsVarlena; valtype = get_fn_expr_argtype(fcinfo->flinfo, i); if (!OidIsValid(valtype)) elog(ERROR, "could not determine data type of concat() input"); getTypeOutputInfo(valtype, &typOutput, &typIsVarlena); fmgr_info_cxt(typOutput, &foutcache[i], fcinfo->flinfo->fn_mcxt); } fcinfo->flinfo->fn_extra = foutcache; return foutcache; } /* * Implementation of both concat() and concat_ws(). * * sepstr is the separator string to place between values. * argidx identifies the first argument to concatenate (counting from zero); * note that this must be constant across any one series of calls. * * Returns NULL if result should be NULL, else text value. */ static text * concat_internal(const char *sepstr, int argidx, FunctionCallInfo fcinfo) { text *result; StringInfoData str; FmgrInfo *foutcache; bool first_arg = true; int i; /* * concat(VARIADIC some-array) is essentially equivalent to * array_to_text(), ie concat the array elements with the given separator. * So we just pass the case off to that code. */ if (get_fn_expr_variadic(fcinfo->flinfo)) { ArrayType *arr; /* Should have just the one argument */ Assert(argidx == PG_NARGS() - 1); /* concat(VARIADIC NULL) is defined as NULL */ if (PG_ARGISNULL(argidx)) return NULL; /* * Non-null argument had better be an array. We assume that any call * context that could let get_fn_expr_variadic return true will have * checked that a VARIADIC-labeled parameter actually is an array. So * it should be okay to just Assert that it's an array rather than * doing a full-fledged error check. */ Assert(OidIsValid(get_base_element_type(get_fn_expr_argtype(fcinfo->flinfo, argidx)))); /* OK, safe to fetch the array value */ arr = PG_GETARG_ARRAYTYPE_P(argidx); /* * And serialize the array. We tell array_to_text to ignore null * elements, which matches the behavior of the loop below. */ return array_to_text_internal(fcinfo, arr, sepstr, NULL); } /* Normal case without explicit VARIADIC marker */ initStringInfo(&str); /* Get output function info, building it if first time through */ foutcache = (FmgrInfo *) fcinfo->flinfo->fn_extra; if (foutcache == NULL) foutcache = build_concat_foutcache(fcinfo, argidx); for (i = argidx; i < PG_NARGS(); i++) { if (!PG_ARGISNULL(i)) { Datum value = PG_GETARG_DATUM(i); /* add separator if appropriate */ if (first_arg) first_arg = false; else appendStringInfoString(&str, sepstr); /* call the appropriate type output function, append the result */ appendStringInfoString(&str, OutputFunctionCall(&foutcache[i], value)); } } result = cstring_to_text_with_len(str.data, str.len); pfree(str.data); return result; } /* * Concatenate all arguments. NULL arguments are ignored. */ Datum text_concat(PG_FUNCTION_ARGS) { text *result; result = concat_internal("", 0, fcinfo); if (result == NULL) PG_RETURN_NULL(); PG_RETURN_TEXT_P(result); } /* * Concatenate all but first argument value with separators. The first * parameter is used as the separator. NULL arguments are ignored. */ Datum text_concat_ws(PG_FUNCTION_ARGS) { char *sep; text *result; /* return NULL when separator is NULL */ if (PG_ARGISNULL(0)) PG_RETURN_NULL(); sep = text_to_cstring(PG_GETARG_TEXT_PP(0)); result = concat_internal(sep, 1, fcinfo); if (result == NULL) PG_RETURN_NULL(); PG_RETURN_TEXT_P(result); } /* * Return first n characters in the string. When n is negative, * return all but last |n| characters. */ Datum text_left(PG_FUNCTION_ARGS) { int n = PG_GETARG_INT32(1); if (n < 0) { text *str = PG_GETARG_TEXT_PP(0); const char *p = VARDATA_ANY(str); int len = VARSIZE_ANY_EXHDR(str); int rlen; n = pg_mbstrlen_with_len(p, len) + n; rlen = pg_mbcharcliplen(p, len, n); PG_RETURN_TEXT_P(cstring_to_text_with_len(p, rlen)); } else PG_RETURN_TEXT_P(text_substring(PG_GETARG_DATUM(0), 1, n, false)); } /* * Return last n characters in the string. When n is negative, * return all but first |n| characters. */ Datum text_right(PG_FUNCTION_ARGS) { text *str = PG_GETARG_TEXT_PP(0); const char *p = VARDATA_ANY(str); int len = VARSIZE_ANY_EXHDR(str); int n = PG_GETARG_INT32(1); int off; if (n < 0) n = -n; else n = pg_mbstrlen_with_len(p, len) - n; off = pg_mbcharcliplen(p, len, n); PG_RETURN_TEXT_P(cstring_to_text_with_len(p + off, len - off)); } /* * Return reversed string */ Datum text_reverse(PG_FUNCTION_ARGS) { text *str = PG_GETARG_TEXT_PP(0); const char *p = VARDATA_ANY(str); int len = VARSIZE_ANY_EXHDR(str); const char *endp = p + len; text *result; char *dst; result = palloc(len + VARHDRSZ); dst = (char *) VARDATA(result) + len; SET_VARSIZE(result, len + VARHDRSZ); if (pg_database_encoding_max_length() > 1) { /* multibyte version */ while (p < endp) { int sz; sz = pg_mblen(p); dst -= sz; memcpy(dst, p, sz); p += sz; } } else { /* single byte version */ while (p < endp) *(--dst) = *p++; } PG_RETURN_TEXT_P(result); } /* * Support macros for text_format() */ #define TEXT_FORMAT_FLAG_MINUS 0x0001 /* is minus flag present? */ #define ADVANCE_PARSE_POINTER(ptr,end_ptr) \ do { \ if (++(ptr) >= (end_ptr)) \ ereport(ERROR, \ (errcode(ERRCODE_INVALID_PARAMETER_VALUE), \ errmsg("unterminated format() type specifier"), \ errhint("For a single \"%%\" use \"%%%%\"."))); \ } while (0) /* * Returns a formatted string */ Datum text_format(PG_FUNCTION_ARGS) { text *fmt; StringInfoData str; const char *cp; const char *start_ptr; const char *end_ptr; text *result; int arg; bool funcvariadic; int nargs; Datum *elements = NULL; bool *nulls = NULL; Oid element_type = InvalidOid; Oid prev_type = InvalidOid; Oid prev_width_type = InvalidOid; FmgrInfo typoutputfinfo; FmgrInfo typoutputinfo_width; /* When format string is null, immediately return null */ if (PG_ARGISNULL(0)) PG_RETURN_NULL(); /* If argument is marked VARIADIC, expand array into elements */ if (get_fn_expr_variadic(fcinfo->flinfo)) { ArrayType *arr; int16 elmlen; bool elmbyval; char elmalign; int nitems; /* Should have just the one argument */ Assert(PG_NARGS() == 2); /* If argument is NULL, we treat it as zero-length array */ if (PG_ARGISNULL(1)) nitems = 0; else { /* * Non-null argument had better be an array. We assume that any * call context that could let get_fn_expr_variadic return true * will have checked that a VARIADIC-labeled parameter actually is * an array. So it should be okay to just Assert that it's an * array rather than doing a full-fledged error check. */ Assert(OidIsValid(get_base_element_type(get_fn_expr_argtype(fcinfo->flinfo, 1)))); /* OK, safe to fetch the array value */ arr = PG_GETARG_ARRAYTYPE_P(1); /* Get info about array element type */ element_type = ARR_ELEMTYPE(arr); get_typlenbyvalalign(element_type, &elmlen, &elmbyval, &elmalign); /* Extract all array elements */ deconstruct_array(arr, element_type, elmlen, elmbyval, elmalign, &elements, &nulls, &nitems); } nargs = nitems + 1; funcvariadic = true; } else { /* Non-variadic case, we'll process the arguments individually */ nargs = PG_NARGS(); funcvariadic = false; } /* Setup for main loop. */ fmt = PG_GETARG_TEXT_PP(0); start_ptr = VARDATA_ANY(fmt); end_ptr = start_ptr + VARSIZE_ANY_EXHDR(fmt); initStringInfo(&str); arg = 1; /* next argument position to print */ /* Scan format string, looking for conversion specifiers. */ for (cp = start_ptr; cp < end_ptr; cp++) { int argpos; int widthpos; int flags; int width; Datum value; bool isNull; Oid typid; /* * If it's not the start of a conversion specifier, just copy it to * the output buffer. */ if (*cp != '%') { appendStringInfoCharMacro(&str, *cp); continue; } ADVANCE_PARSE_POINTER(cp, end_ptr); /* Easy case: %% outputs a single % */ if (*cp == '%') { appendStringInfoCharMacro(&str, *cp); continue; } /* Parse the optional portions of the format specifier */ cp = text_format_parse_format(cp, end_ptr, &argpos, &widthpos, &flags, &width); /* * Next we should see the main conversion specifier. Whether or not * an argument position was present, it's known that at least one * character remains in the string at this point. Experience suggests * that it's worth checking that that character is one of the expected * ones before we try to fetch arguments, so as to produce the least * confusing response to a mis-formatted specifier. */ if (strchr("sIL", *cp) == NULL) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("unrecognized format() type specifier \"%.*s\"", pg_mblen(cp), cp), errhint("For a single \"%%\" use \"%%%%\"."))); /* If indirect width was specified, get its value */ if (widthpos >= 0) { /* Collect the specified or next argument position */ if (widthpos > 0) arg = widthpos; if (arg >= nargs) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("too few arguments for format()"))); /* Get the value and type of the selected argument */ if (!funcvariadic) { value = PG_GETARG_DATUM(arg); isNull = PG_ARGISNULL(arg); typid = get_fn_expr_argtype(fcinfo->flinfo, arg); } else { value = elements[arg - 1]; isNull = nulls[arg - 1]; typid = element_type; } if (!OidIsValid(typid)) elog(ERROR, "could not determine data type of format() input"); arg++; /* We can treat NULL width the same as zero */ if (isNull) width = 0; else if (typid == INT4OID) width = DatumGetInt32(value); else if (typid == INT2OID) width = DatumGetInt16(value); else { /* For less-usual datatypes, convert to text then to int */ char *str; if (typid != prev_width_type) { Oid typoutputfunc; bool typIsVarlena; getTypeOutputInfo(typid, &typoutputfunc, &typIsVarlena); fmgr_info(typoutputfunc, &typoutputinfo_width); prev_width_type = typid; } str = OutputFunctionCall(&typoutputinfo_width, value); /* pg_strtoint32 will complain about bad data or overflow */ width = pg_strtoint32(str); pfree(str); } } /* Collect the specified or next argument position */ if (argpos > 0) arg = argpos; if (arg >= nargs) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("too few arguments for format()"))); /* Get the value and type of the selected argument */ if (!funcvariadic) { value = PG_GETARG_DATUM(arg); isNull = PG_ARGISNULL(arg); typid = get_fn_expr_argtype(fcinfo->flinfo, arg); } else { value = elements[arg - 1]; isNull = nulls[arg - 1]; typid = element_type; } if (!OidIsValid(typid)) elog(ERROR, "could not determine data type of format() input"); arg++; /* * Get the appropriate typOutput function, reusing previous one if * same type as previous argument. That's particularly useful in the * variadic-array case, but often saves work even for ordinary calls. */ if (typid != prev_type) { Oid typoutputfunc; bool typIsVarlena; getTypeOutputInfo(typid, &typoutputfunc, &typIsVarlena); fmgr_info(typoutputfunc, &typoutputfinfo); prev_type = typid; } /* * And now we can format the value. */ switch (*cp) { case 's': case 'I': case 'L': text_format_string_conversion(&str, *cp, &typoutputfinfo, value, isNull, flags, width); break; default: /* should not get here, because of previous check */ ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("unrecognized format() type specifier \"%.*s\"", pg_mblen(cp), cp), errhint("For a single \"%%\" use \"%%%%\"."))); break; } } /* Don't need deconstruct_array results anymore. */ if (elements != NULL) pfree(elements); if (nulls != NULL) pfree(nulls); /* Generate results. */ result = cstring_to_text_with_len(str.data, str.len); pfree(str.data); PG_RETURN_TEXT_P(result); } /* * Parse contiguous digits as a decimal number. * * Returns true if some digits could be parsed. * The value is returned into *value, and *ptr is advanced to the next * character to be parsed. * * Note parsing invariant: at least one character is known available before * string end (end_ptr) at entry, and this is still true at exit. */ static bool text_format_parse_digits(const char **ptr, const char *end_ptr, int *value) { bool found = false; const char *cp = *ptr; int val = 0; while (*cp >= '0' && *cp <= '9') { int8 digit = (*cp - '0'); if (unlikely(pg_mul_s32_overflow(val, 10, &val)) || unlikely(pg_add_s32_overflow(val, digit, &val))) ereport(ERROR, (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE), errmsg("number is out of range"))); ADVANCE_PARSE_POINTER(cp, end_ptr); found = true; } *ptr = cp; *value = val; return found; } /* * Parse a format specifier (generally following the SUS printf spec). * * We have already advanced over the initial '%', and we are looking for * [argpos][flags][width]type (but the type character is not consumed here). * * Inputs are start_ptr (the position after '%') and end_ptr (string end + 1). * Output parameters: * argpos: argument position for value to be printed. -1 means unspecified. * widthpos: argument position for width. Zero means the argument position * was unspecified (ie, take the next arg) and -1 means no width * argument (width was omitted or specified as a constant). * flags: bitmask of flags. * width: directly-specified width value. Zero means the width was omitted * (note it's not necessary to distinguish this case from an explicit * zero width value). * * The function result is the next character position to be parsed, ie, the * location where the type character is/should be. * * Note parsing invariant: at least one character is known available before * string end (end_ptr) at entry, and this is still true at exit. */ static const char * text_format_parse_format(const char *start_ptr, const char *end_ptr, int *argpos, int *widthpos, int *flags, int *width) { const char *cp = start_ptr; int n; /* set defaults for output parameters */ *argpos = -1; *widthpos = -1; *flags = 0; *width = 0; /* try to identify first number */ if (text_format_parse_digits(&cp, end_ptr, &n)) { if (*cp != '$') { /* Must be just a width and a type, so we're done */ *width = n; return cp; } /* The number was argument position */ *argpos = n; /* Explicit 0 for argument index is immediately refused */ if (n == 0) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("format specifies argument 0, but arguments are numbered from 1"))); ADVANCE_PARSE_POINTER(cp, end_ptr); } /* Handle flags (only minus is supported now) */ while (*cp == '-') { *flags |= TEXT_FORMAT_FLAG_MINUS; ADVANCE_PARSE_POINTER(cp, end_ptr); } if (*cp == '*') { /* Handle indirect width */ ADVANCE_PARSE_POINTER(cp, end_ptr); if (text_format_parse_digits(&cp, end_ptr, &n)) { /* number in this position must be closed by $ */ if (*cp != '$') ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("width argument position must be ended by \"$\""))); /* The number was width argument position */ *widthpos = n; /* Explicit 0 for argument index is immediately refused */ if (n == 0) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("format specifies argument 0, but arguments are numbered from 1"))); ADVANCE_PARSE_POINTER(cp, end_ptr); } else *widthpos = 0; /* width's argument position is unspecified */ } else { /* Check for direct width specification */ if (text_format_parse_digits(&cp, end_ptr, &n)) *width = n; } /* cp should now be pointing at type character */ return cp; } /* * Format a %s, %I, or %L conversion */ static void text_format_string_conversion(StringInfo buf, char conversion, FmgrInfo *typOutputInfo, Datum value, bool isNull, int flags, int width) { char *str; /* Handle NULL arguments before trying to stringify the value. */ if (isNull) { if (conversion == 's') text_format_append_string(buf, "", flags, width); else if (conversion == 'L') text_format_append_string(buf, "NULL", flags, width); else if (conversion == 'I') ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), errmsg("null values cannot be formatted as an SQL identifier"))); return; } /* Stringify. */ str = OutputFunctionCall(typOutputInfo, value); /* Escape. */ if (conversion == 'I') { /* quote_identifier may or may not allocate a new string. */ text_format_append_string(buf, quote_identifier(str), flags, width); } else if (conversion == 'L') { char *qstr = quote_literal_cstr(str); text_format_append_string(buf, qstr, flags, width); /* quote_literal_cstr() always allocates a new string */ pfree(qstr); } else text_format_append_string(buf, str, flags, width); /* Cleanup. */ pfree(str); } /* * Append str to buf, padding as directed by flags/width */ static void text_format_append_string(StringInfo buf, const char *str, int flags, int width) { bool align_to_left = false; int len; /* fast path for typical easy case */ if (width == 0) { appendStringInfoString(buf, str); return; } if (width < 0) { /* Negative width: implicit '-' flag, then take absolute value */ align_to_left = true; /* -INT_MIN is undefined */ if (width <= INT_MIN) ereport(ERROR, (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE), errmsg("number is out of range"))); width = -width; } else if (flags & TEXT_FORMAT_FLAG_MINUS) align_to_left = true; len = pg_mbstrlen(str); if (align_to_left) { /* left justify */ appendStringInfoString(buf, str); if (len < width) appendStringInfoSpaces(buf, width - len); } else { /* right justify */ if (len < width) appendStringInfoSpaces(buf, width - len); appendStringInfoString(buf, str); } } /* * text_format_nv - nonvariadic wrapper for text_format function. * * note: this wrapper is necessary to pass the sanity check in opr_sanity, * which checks that all built-in functions that share the implementing C * function take the same number of arguments. */ Datum text_format_nv(PG_FUNCTION_ARGS) { return text_format(fcinfo); } /* * Helper function for Levenshtein distance functions. Faster than memcmp(), * for this use case. */ static inline bool rest_of_char_same(const char *s1, const char *s2, int len) { while (len > 0) { len--; if (s1[len] != s2[len]) return false; } return true; } /* Expand each Levenshtein distance variant */ #include "levenshtein.c" #define LEVENSHTEIN_LESS_EQUAL #include "levenshtein.c" /* * The following *ClosestMatch() functions can be used to determine whether a * user-provided string resembles any known valid values, which is useful for * providing hints in log messages, among other things. Use these functions * like so: * * initClosestMatch(&state, source_string, max_distance); * * for (int i = 0; i < num_valid_strings; i++) * updateClosestMatch(&state, valid_strings[i]); * * closestMatch = getClosestMatch(&state); */ /* * Initialize the given state with the source string and maximum Levenshtein * distance to consider. */ void initClosestMatch(ClosestMatchState *state, const char *source, int max_d) { Assert(state); Assert(max_d >= 0); state->source = source; state->min_d = -1; state->max_d = max_d; state->match = NULL; } /* * If the candidate string is a closer match than the current one saved (or * there is no match saved), save it as the closest match. * * If the source or candidate string is NULL, empty, or too long, this function * takes no action. Likewise, if the Levenshtein distance exceeds the maximum * allowed or more than half the characters are different, no action is taken. */ void updateClosestMatch(ClosestMatchState *state, const char *candidate) { int dist; Assert(state); if (state->source == NULL || state->source[0] == '\0' || candidate == NULL || candidate[0] == '\0') return; /* * To avoid ERROR-ing, we check the lengths here instead of setting * 'trusted' to false in the call to varstr_levenshtein_less_equal(). */ if (strlen(state->source) > MAX_LEVENSHTEIN_STRLEN || strlen(candidate) > MAX_LEVENSHTEIN_STRLEN) return; dist = varstr_levenshtein_less_equal(state->source, strlen(state->source), candidate, strlen(candidate), 1, 1, 1, state->max_d, true); if (dist <= state->max_d && dist <= strlen(state->source) / 2 && (state->min_d == -1 || dist < state->min_d)) { state->min_d = dist; state->match = candidate; } } /* * Return the closest match. If no suitable candidates were provided via * updateClosestMatch(), return NULL. */ const char * getClosestMatch(ClosestMatchState *state) { Assert(state); return state->match; } /* * Unicode support */ static UnicodeNormalizationForm unicode_norm_form_from_string(const char *formstr) { UnicodeNormalizationForm form = -1; /* * Might as well check this while we're here. */ if (GetDatabaseEncoding() != PG_UTF8) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("Unicode normalization can only be performed if server encoding is UTF8"))); if (pg_strcasecmp(formstr, "NFC") == 0) form = UNICODE_NFC; else if (pg_strcasecmp(formstr, "NFD") == 0) form = UNICODE_NFD; else if (pg_strcasecmp(formstr, "NFKC") == 0) form = UNICODE_NFKC; else if (pg_strcasecmp(formstr, "NFKD") == 0) form = UNICODE_NFKD; else ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid normalization form: %s", formstr))); return form; } Datum unicode_normalize_func(PG_FUNCTION_ARGS) { text *input = PG_GETARG_TEXT_PP(0); char *formstr = text_to_cstring(PG_GETARG_TEXT_PP(1)); UnicodeNormalizationForm form; int size; pg_wchar *input_chars; pg_wchar *output_chars; unsigned char *p; text *result; int i; form = unicode_norm_form_from_string(formstr); /* convert to pg_wchar */ size = pg_mbstrlen_with_len(VARDATA_ANY(input), VARSIZE_ANY_EXHDR(input)); input_chars = palloc((size + 1) * sizeof(pg_wchar)); p = (unsigned char *) VARDATA_ANY(input); for (i = 0; i < size; i++) { input_chars[i] = utf8_to_unicode(p); p += pg_utf_mblen(p); } input_chars[i] = (pg_wchar) '\0'; Assert((char *) p == VARDATA_ANY(input) + VARSIZE_ANY_EXHDR(input)); /* action */ output_chars = unicode_normalize(form, input_chars); /* convert back to UTF-8 string */ size = 0; for (pg_wchar *wp = output_chars; *wp; wp++) { unsigned char buf[4]; unicode_to_utf8(*wp, buf); size += pg_utf_mblen(buf); } result = palloc(size + VARHDRSZ); SET_VARSIZE(result, size + VARHDRSZ); p = (unsigned char *) VARDATA_ANY(result); for (pg_wchar *wp = output_chars; *wp; wp++) { unicode_to_utf8(*wp, p); p += pg_utf_mblen(p); } Assert((char *) p == (char *) result + size + VARHDRSZ); PG_RETURN_TEXT_P(result); } /* * Check whether the string is in the specified Unicode normalization form. * * This is done by converting the string to the specified normal form and then * comparing that to the original string. To speed that up, we also apply the * "quick check" algorithm specified in UAX #15, which can give a yes or no * answer for many strings by just scanning the string once. * * This function should generally be optimized for the case where the string * is in fact normalized. In that case, we'll end up looking at the entire * string, so it's probably not worth doing any incremental conversion etc. */ Datum unicode_is_normalized(PG_FUNCTION_ARGS) { text *input = PG_GETARG_TEXT_PP(0); char *formstr = text_to_cstring(PG_GETARG_TEXT_PP(1)); UnicodeNormalizationForm form; int size; pg_wchar *input_chars; pg_wchar *output_chars; unsigned char *p; int i; UnicodeNormalizationQC quickcheck; int output_size; bool result; form = unicode_norm_form_from_string(formstr); /* convert to pg_wchar */ size = pg_mbstrlen_with_len(VARDATA_ANY(input), VARSIZE_ANY_EXHDR(input)); input_chars = palloc((size + 1) * sizeof(pg_wchar)); p = (unsigned char *) VARDATA_ANY(input); for (i = 0; i < size; i++) { input_chars[i] = utf8_to_unicode(p); p += pg_utf_mblen(p); } input_chars[i] = (pg_wchar) '\0'; Assert((char *) p == VARDATA_ANY(input) + VARSIZE_ANY_EXHDR(input)); /* quick check (see UAX #15) */ quickcheck = unicode_is_normalized_quickcheck(form, input_chars); if (quickcheck == UNICODE_NORM_QC_YES) PG_RETURN_BOOL(true); else if (quickcheck == UNICODE_NORM_QC_NO) PG_RETURN_BOOL(false); /* normalize and compare with original */ output_chars = unicode_normalize(form, input_chars); output_size = 0; for (pg_wchar *wp = output_chars; *wp; wp++) output_size++; result = (size == output_size) && (memcmp(input_chars, output_chars, size * sizeof(pg_wchar)) == 0); PG_RETURN_BOOL(result); } /* * Check if first n chars are hexadecimal digits */ static bool isxdigits_n(const char *instr, size_t n) { for (size_t i = 0; i < n; i++) if (!isxdigit((unsigned char) instr[i])) return false; return true; } static unsigned int hexval(unsigned char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 0xA; if (c >= 'A' && c <= 'F') return c - 'A' + 0xA; elog(ERROR, "invalid hexadecimal digit"); return 0; /* not reached */ } /* * Translate string with hexadecimal digits to number */ static unsigned int hexval_n(const char *instr, size_t n) { unsigned int result = 0; for (size_t i = 0; i < n; i++) result += hexval(instr[i]) << (4 * (n - i - 1)); return result; } /* * Replaces Unicode escape sequences by Unicode characters */ Datum unistr(PG_FUNCTION_ARGS) { text *input_text = PG_GETARG_TEXT_PP(0); char *instr; int len; StringInfoData str; text *result; pg_wchar pair_first = 0; char cbuf[MAX_UNICODE_EQUIVALENT_STRING + 1]; instr = VARDATA_ANY(input_text); len = VARSIZE_ANY_EXHDR(input_text); initStringInfo(&str); while (len > 0) { if (instr[0] == '\\') { if (len >= 2 && instr[1] == '\\') { if (pair_first) goto invalid_pair; appendStringInfoChar(&str, '\\'); instr += 2; len -= 2; } else if ((len >= 5 && isxdigits_n(instr + 1, 4)) || (len >= 6 && instr[1] == 'u' && isxdigits_n(instr + 2, 4))) { pg_wchar unicode; int offset = instr[1] == 'u' ? 2 : 1; unicode = hexval_n(instr + offset, 4); if (!is_valid_unicode_codepoint(unicode)) ereport(ERROR, errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid Unicode code point: %04X", unicode)); if (pair_first) { if (is_utf16_surrogate_second(unicode)) { unicode = surrogate_pair_to_codepoint(pair_first, unicode); pair_first = 0; } else goto invalid_pair; } else if (is_utf16_surrogate_second(unicode)) goto invalid_pair; if (is_utf16_surrogate_first(unicode)) pair_first = unicode; else { pg_unicode_to_server(unicode, (unsigned char *) cbuf); appendStringInfoString(&str, cbuf); } instr += 4 + offset; len -= 4 + offset; } else if (len >= 8 && instr[1] == '+' && isxdigits_n(instr + 2, 6)) { pg_wchar unicode; unicode = hexval_n(instr + 2, 6); if (!is_valid_unicode_codepoint(unicode)) ereport(ERROR, errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid Unicode code point: %04X", unicode)); if (pair_first) { if (is_utf16_surrogate_second(unicode)) { unicode = surrogate_pair_to_codepoint(pair_first, unicode); pair_first = 0; } else goto invalid_pair; } else if (is_utf16_surrogate_second(unicode)) goto invalid_pair; if (is_utf16_surrogate_first(unicode)) pair_first = unicode; else { pg_unicode_to_server(unicode, (unsigned char *) cbuf); appendStringInfoString(&str, cbuf); } instr += 8; len -= 8; } else if (len >= 10 && instr[1] == 'U' && isxdigits_n(instr + 2, 8)) { pg_wchar unicode; unicode = hexval_n(instr + 2, 8); if (!is_valid_unicode_codepoint(unicode)) ereport(ERROR, errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid Unicode code point: %04X", unicode)); if (pair_first) { if (is_utf16_surrogate_second(unicode)) { unicode = surrogate_pair_to_codepoint(pair_first, unicode); pair_first = 0; } else goto invalid_pair; } else if (is_utf16_surrogate_second(unicode)) goto invalid_pair; if (is_utf16_surrogate_first(unicode)) pair_first = unicode; else { pg_unicode_to_server(unicode, (unsigned char *) cbuf); appendStringInfoString(&str, cbuf); } instr += 10; len -= 10; } else ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid Unicode escape"), errhint("Unicode escapes must be \\XXXX, \\+XXXXXX, \\uXXXX, or \\UXXXXXXXX."))); } else { if (pair_first) goto invalid_pair; appendStringInfoChar(&str, *instr++); len--; } } /* unfinished surrogate pair? */ if (pair_first) goto invalid_pair; result = cstring_to_text_with_len(str.data, str.len); pfree(str.data); PG_RETURN_TEXT_P(result); invalid_pair: ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid Unicode surrogate pair"))); PG_RETURN_NULL(); /* keep compiler quiet */ }
d432af83f62f9d0065cce5c001d74a9f018eebf3
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
/sys/arch/hpcmips/dev/mq200subr.c
552a2ea8ccb49454c00914939d1aaafabac211dc
[]
no_license
NetBSD/src
1a9cbc22ed778be638b37869ed4fb5c8dd616166
23ee83f7c0aea0777bd89d8ebd7f0cde9880d13c
refs/heads/trunk
2023-08-31T13:24:58.105962
2023-08-27T15:50:47
2023-08-27T15:50:47
88,439,547
656
348
null
2023-07-20T20:07:24
2017-04-16T20:03:43
null
UTF-8
C
false
false
11,138
c
mq200subr.c
/* $NetBSD: mq200subr.c,v 1.7 2019/08/21 04:17:40 msaitoh Exp $ */ /*- * Copyright (c) 2001 TAKEMURA Shin * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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. * */ #ifdef _KERNEL #include <sys/cdefs.h> __KERNEL_RCSID(0, "$NetBSD: mq200subr.c,v 1.7 2019/08/21 04:17:40 msaitoh Exp $"); #include <sys/param.h> #include <sys/kernel.h> #include <sys/systm.h> #include <sys/device.h> #else #include <stdio.h> #endif #include <sys/types.h> #include <machine/platid.h> #include <machine/platid_mask.h> #include "opt_mq200.h" #include "mq200var.h" #include "mq200reg.h" #include "mq200priv.h" #define ABS(a) ((a) < 0 ? -(a) : (a)) int mq200_depth_table[] = { [MQ200_GCC_1BPP] = 1, [MQ200_GCC_2BPP] = 2, [MQ200_GCC_4BPP] = 4, [MQ200_GCC_8BPP] = 8, [MQ200_GCC_16BPP] = 16, [MQ200_GCC_24BPP] = 32, [MQ200_GCC_ARGB888] = 32, [MQ200_GCC_ABGR888] = 32, [MQ200_GCC_16BPP_DIRECT] = 16, [MQ200_GCC_24BPP_DIRECT] = 32, [MQ200_GCC_ARGB888_DIRECT] = 32, [MQ200_GCC_ABGR888_DIRECT] = 32, }; struct mq200_crt_param mq200_crt_params[] = { [MQ200_CRT_640x480_60Hz] = { 640, 480, 25175, /* width, height, dot clock */ 800, /* HD Total */ 525, /* VD Total */ 656, 752, /* HS Start, HS End */ 490, 492, /* VS Start, VS End */ (MQ200_GC1CRTC_HSYNC_ACTVLOW | MQ200_GC1CRTC_VSYNC_ACTVLOW | MQ200_GC1CRTC_BLANK_PEDESTAL_EN), }, [MQ200_CRT_800x600_60Hz] = { 800, 600, 40000, /* width, height, dot clock */ 1054, /* HD Total */ 628, /* VD Total */ 839, 967, /* HS Start, HS End */ 601, 605, /* VS Start, VS End */ MQ200_GC1CRTC_BLANK_PEDESTAL_EN, }, [MQ200_CRT_1024x768_60Hz] = { 1024, 768, 65000, /* width, height, dot clock */ 1344, /* HD Total */ 806, /* VD Total */ 1048, 1184, /* HS Start, HS End */ 771, 777, /* VS Start, VS End */ (MQ200_GC1CRTC_HSYNC_ACTVLOW | MQ200_GC1CRTC_VSYNC_ACTVLOW | MQ200_GC1CRTC_BLANK_PEDESTAL_EN), }, }; int mq200_crt_nparams = sizeof(mq200_crt_params)/sizeof(*mq200_crt_params); /* * get PLL setting register value for given frequency */ int mq200_pllparam(int reqout, u_int32_t *res) { int n, m, p, out; int ref = 12288; int bn, bm, bp, e; e = ref; bn = 0; bp = 0; bm = 0; for (p = 0; p <= 4; p++) { for (n = 0; n < (1<<5); n++) { m = (reqout * ((n + 1) << p)) / ref - 1; out = ref * (m + 1) / ((n + 1) << p); if (0xff < m) break; if (40 <= m && 1000 <= ref/(n + 1) && 170000 <= ref*(m+1)/(n+1) && ref*(m+1)/(n+1) <= 340000 && ABS(reqout - out) <= e) { e = ABS(reqout - out); bn = n; bm = m; bp = p; } } } if (ref <= e) return (-1); #if 0 out = ref * (bm + 1) / ((bn + 1) << bp); printf("PLL: %d.%03d x (%d+1) / (%d+1) / %d = %d.%03d\n", ref / 1000, ref % 1000, bm, bn, (1<<bp), out / 1000, out % 1000); #endif *res = ((bm << MQ200_PLL_M_SHIFT) | (bn << MQ200_PLL_N_SHIFT) | (bp << MQ200_PLL_P_SHIFT)); return (0); } void mq200_set_pll(struct mq200_softc *sc, int pll, int clock) { struct mq200_regctx *paramreg, *enreg; u_int32_t param, enbit; switch (pll) { case MQ200_CLOCK_PLL1: paramreg = &sc->sc_regctxs[MQ200_I_PLL(1)]; enreg = &sc->sc_regctxs[MQ200_I_DCMISC]; enbit = MQ200_DCMISC_PLL1_ENABLE; break; case MQ200_CLOCK_PLL2: paramreg = &sc->sc_regctxs[MQ200_I_PLL(2)]; enreg = &sc->sc_regctxs[MQ200_I_PMC]; enbit = MQ200_PMC_PLL2_ENABLE; break; case MQ200_CLOCK_PLL3: paramreg = &sc->sc_regctxs[MQ200_I_PLL(3)]; enreg = &sc->sc_regctxs[MQ200_I_PMC]; enbit = MQ200_PMC_PLL3_ENABLE; break; default: printf("mq200: invalid PLL: %d\n", pll); return; } if (clock != 0 && clock != -1) { /* PLL Programming */ if (mq200_pllparam(clock, &param) != 0) { printf("mq200: invalid clock rate: %s %d.%03dMHz\n", mq200_clknames[pll], clock/1000, clock%1000); return; } mq200_mod(sc, paramreg, MQ200_PLL_PARAM_MASK, param); /* enable PLL */ mq200_on(sc, enreg, enbit); } DPRINTF("%s %d.%03dMHz\n", mq200_clknames[pll], clock/1000, clock%1000); } void mq200_setup_regctx(struct mq200_softc *sc) { int i; static int offsets[MQ200_I_MAX] = { [MQ200_I_DCMISC] = MQ200_DCMISCR, [MQ200_I_PLL(2)] = MQ200_PLL2R, [MQ200_I_PLL(3)] = MQ200_PLL3R, [MQ200_I_PMC] = MQ200_PMCR, [MQ200_I_MM01] = MQ200_MMR(1), [MQ200_I_GCC(MQ200_GC1)] = MQ200_GCCR(MQ200_GC1), [MQ200_I_GCC(MQ200_GC2)] = MQ200_GCCR(MQ200_GC2), }; for (i = 0; i < sizeof(offsets)/sizeof(*offsets); i++) { if (offsets[i] == 0) #ifdef MQ200_DEBUG if (i != MQ200_I_PMC) panic("%s(%d): register context %d is empty", __FILE__, __LINE__, i); #endif sc->sc_regctxs[i].offset = offsets[i]; } } void mq200_setup(struct mq200_softc *sc) { const struct mq200_clock_setting *clock; const struct mq200_crt_param *crt; clock = &sc->sc_md->md_clock_settings[sc->sc_flags & MQ200_SC_GC_MASK]; crt = sc->sc_crt; /* disable GC1 and GC2 */ //mq200_write(sc, MQ200_GCCR(MQ200_GC1), 0); mq200_write2(sc, &sc->sc_regctxs[MQ200_I_GCC(MQ200_GC1)], 0); mq200_write(sc, MQ200_GC1CRTCR, 0); //mq200_write(sc, MQ200_GCCR(MQ200_GC2), 0); mq200_write2(sc, &sc->sc_regctxs[MQ200_I_GCC(MQ200_GC2)], 0); while (mq200_read(sc, MQ200_PMCR) & MQ200_PMC_SEQPROGRESS) /* busy wait */; /* * setup around clock */ /* setup eatch PLLs */ mq200_set_pll(sc, MQ200_CLOCK_PLL1, clock->pll1); mq200_set_pll(sc, MQ200_CLOCK_PLL2, clock->pll2); mq200_set_pll(sc, MQ200_CLOCK_PLL3, clock->pll3); if (sc->sc_flags & MQ200_SC_GC1_ENABLE) mq200_set_pll(sc, clock->gc[MQ200_GC1], crt->clock); /* setup MEMORY clock */ if (clock->mem == MQ200_CLOCK_PLL2) mq200_on(sc, &sc->sc_regctxs[MQ200_I_MM01], MQ200_MM01_CLK_PLL2); else mq200_off(sc, &sc->sc_regctxs[MQ200_I_MM01], MQ200_MM01_CLK_PLL2); DPRINTF("MEM: PLL%d\n", (clock->mem == MQ200_CLOCK_PLL2)?2:1); /* setup GE clock */ mq200_mod(sc, &sc->sc_regctxs[MQ200_I_PMC], MQ200_PMC_GE_CLK_MASK | MQ200_PMC_GE_ENABLE, (clock->ge << MQ200_PMC_GE_CLK_SHIFT) | MQ200_PMC_GE_ENABLE); DPRINTF(" GE: PLL%d\n", clock->ge); /* * setup GC1 (CRT controller) */ if (sc->sc_flags & MQ200_SC_GC1_ENABLE) { /* GC03R Horizontal Display Control */ mq200_write(sc, MQ200_GCHDCR(MQ200_GC1), (((u_int32_t)crt->hdtotal-2)<<MQ200_GC1HDC_TOTAL_SHIFT) | ((u_int32_t)crt->width << MQ200_GCHDC_END_SHIFT)); /* GC03R Vertical Display Control */ mq200_write(sc, MQ200_GCVDCR(MQ200_GC1), (((u_int32_t)crt->vdtotal-1)<<MQ200_GC1VDC_TOTAL_SHIFT) | (((u_int32_t)crt->height - 1) << MQ200_GCVDC_END_SHIFT)); /* GC04R Horizontal Sync Control */ mq200_write(sc, MQ200_GCHSCR(MQ200_GC1), ((u_int32_t)crt->hsstart << MQ200_GCHSC_START_SHIFT) | ((u_int32_t)crt->hsend << MQ200_GCHSC_END_SHIFT)); /* GC05R Vertical Sync Control */ mq200_write(sc, MQ200_GCVSCR(MQ200_GC1), ((u_int32_t)crt->vsstart << MQ200_GCVSC_START_SHIFT) | ((u_int32_t)crt->vsend << MQ200_GCVSC_END_SHIFT)); /* GC00R GC1 Control */ //mq200_write(sc, MQ200_GCCR(MQ200_GC1), mq200_write2(sc, &sc->sc_regctxs[MQ200_I_GCC(MQ200_GC1)], (MQ200_GCC_ENABLE | (clock->gc[MQ200_GC1] << MQ200_GCC_RCLK_SHIFT) | MQ200_GCC_MCLK_FD_1 | (1 << MQ200_GCC_MCLK_SD_SHIFT))); /* GC01R CRT Control */ mq200_write(sc, MQ200_GC1CRTCR, MQ200_GC1CRTC_DACEN | crt->opt); sc->sc_width[MQ200_GC1] = crt->width; sc->sc_height[MQ200_GC1] = crt->height; DPRINTF("GC1: %s\n", mq200_clknames[clock->gc[MQ200_GC1]]); } while (mq200_read(sc, MQ200_PMCR) & MQ200_PMC_SEQPROGRESS) /* busy wait */; /* * setup GC2 (FP controller) */ if (sc->sc_flags & MQ200_SC_GC2_ENABLE) { //mq200_write(sc, MQ200_GCCR(MQ200_GC2), mq200_write2(sc, &sc->sc_regctxs[MQ200_I_GCC(MQ200_GC2)], MQ200_GCC_ENABLE | (clock->gc[MQ200_GC2] << MQ200_GCC_RCLK_SHIFT) | MQ200_GCC_MCLK_FD_1 | (1 << MQ200_GCC_MCLK_SD_SHIFT)); DPRINTF("GC2: %s\n", mq200_clknames[clock->gc[MQ200_GC2]]); } while (mq200_read(sc, MQ200_PMCR) & MQ200_PMC_SEQPROGRESS) /* busy wait */; /* * disable unused PLLs */ if (clock->pll1 == 0) { DPRINTF("PLL1 disable\n"); mq200_off(sc, &sc->sc_regctxs[MQ200_I_DCMISC], MQ200_DCMISC_PLL1_ENABLE); } if (clock->pll2 == 0) { DPRINTF("PLL2 disable\n"); mq200_off(sc, &sc->sc_regctxs[MQ200_I_PMC], MQ200_PMC_PLL2_ENABLE); } if (clock->pll3 == 0) { DPRINTF("PLL3 disable\n"); mq200_off(sc, &sc->sc_regctxs[MQ200_I_PMC], MQ200_PMC_PLL3_ENABLE); } } void mq200_win_enable(struct mq200_softc *sc, int gc, u_int32_t depth, u_int32_t start, int width, int height, int stride) { DPRINTF("enable window on GC%d: %dx%d(%dx%d)\n", gc + 1, width, height, sc->sc_width[gc], sc->sc_height[gc]); if (sc->sc_width[gc] < width) { if (mq200_depth_table[depth]) start += (height - sc->sc_height[gc]) * mq200_depth_table[depth] / 8; width = sc->sc_width[gc]; } if (sc->sc_height[gc] < height) { start += (height - sc->sc_height[gc]) * stride; height = sc->sc_height[gc]; } /* GC08R Window Horizontal Control */ mq200_write(sc, MQ200_GCWHCR(gc), (((u_int32_t)width - 1) << MQ200_GCWHC_WIDTH_SHIFT) | ((sc->sc_width[gc] - width)/2)); /* GC09R Window Vertical Control */ mq200_write(sc, MQ200_GCWVCR(gc), (((u_int32_t)height - 1) << MQ200_GCWVC_HEIGHT_SHIFT) | ((sc->sc_height[gc] - height)/2)); /* GC00R GC Control */ mq200_mod(sc, &sc->sc_regctxs[MQ200_I_GCC(gc)], (MQ200_GCC_WINEN | MQ200_GCC_DEPTH_MASK), (MQ200_GCC_WINEN | (depth << MQ200_GCC_DEPTH_SHIFT))); } void mq200_win_disable(struct mq200_softc *sc, int gc) { /* GC00R GC Control */ mq200_off(sc, &sc->sc_regctxs[MQ200_I_GCC(gc)], MQ200_GCC_WINEN); }
64c3c6b14c61d38fdb3103664fd3815033aa930c
540c04254075b9fb22685a73487531f4c0b3e3ac
/lib-h3/device/emac/phy.c
16d383dc0d0ede7d1f4e1e704e804507c6256295
[ "MIT" ]
permissive
vanvught/rpidmx512
197573217fc2c0c3673d6727d199c10e528a9fac
f27ae141d14c1d1cb9e0b62a291356ae0780c99f
refs/heads/master
2023-08-08T02:06:52.200184
2023-05-19T12:44:48
2023-05-19T12:44:48
15,496,962
380
125
MIT
2023-05-19T12:47:24
2013-12-28T18:27:20
C++
UTF-8
C
false
false
3,155
c
phy.c
/** * @file phy.c * */ /* Copyright (C) 2018 by Arjan van Vught mailto:info@orangepi-dmx.nl * * 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 "h3.h" #include "h3_hs_timer.h" #include "h3_timer.h" #include "mii.h" #define CONFIG_SYS_HZ 1000 #define CONFIG_MDIO_TIMEOUT (3 * CONFIG_SYS_HZ) #define MDIO_CMD_MII_BUSY (1 << 0) #define MDIO_CMD_MII_WRITE (1 << 1) #define MDIO_CMD_MII_PHY_REG_ADDR_MASK 0x000001f0 #define MDIO_CMD_MII_PHY_REG_ADDR_SHIFT 4 #define MDIO_CMD_MII_PHY_ADDR_MASK 0x0001f000 #define MDIO_CMD_MII_PHY_ADDR_SHIFT 12 int phy_read(int addr, int reg) { uint32_t cmd = 0; cmd |= ((0x03 & 0x07) << 20); cmd |= ((addr << MDIO_CMD_MII_PHY_ADDR_SHIFT) & MDIO_CMD_MII_PHY_ADDR_MASK); cmd |= ((reg << MDIO_CMD_MII_PHY_REG_ADDR_SHIFT) & 0x000007F0); cmd |= MDIO_CMD_MII_BUSY; while ((H3_EMAC->MII_CMD & MDIO_CMD_MII_BUSY) == MDIO_CMD_MII_BUSY); H3_EMAC->MII_CMD = cmd; while ((H3_EMAC->MII_CMD & MDIO_CMD_MII_BUSY) == MDIO_CMD_MII_BUSY); return (int) H3_EMAC->MII_DATA; } int phy_write(int addr, int reg, uint16_t val) { uint32_t miiaddr = 0; uint32_t timeout = CONFIG_MDIO_TIMEOUT; miiaddr &= (uint32_t) ~MDIO_CMD_MII_PHY_REG_ADDR_MASK; miiaddr |= (reg << MDIO_CMD_MII_PHY_REG_ADDR_SHIFT) & MDIO_CMD_MII_PHY_REG_ADDR_MASK; miiaddr &= (uint32_t) ~MDIO_CMD_MII_PHY_ADDR_MASK; miiaddr |= (addr << MDIO_CMD_MII_PHY_ADDR_SHIFT) & MDIO_CMD_MII_PHY_ADDR_MASK; miiaddr |= MDIO_CMD_MII_WRITE; miiaddr |= MDIO_CMD_MII_BUSY; H3_EMAC->MII_DATA = val; H3_EMAC->MII_CMD = miiaddr; uint32_t start = h3_hs_timer_lo_us(); while (h3_hs_timer_lo_us() - start < timeout) { if (!(H3_EMAC->MII_CMD & MDIO_CMD_MII_BUSY)) { return 0; } udelay(10); }; return -1; } uint32_t phy_get_id(int addr) { int phy_reg; uint32_t phy_id; phy_reg = phy_read(addr, MII_PHYSID1); if (phy_reg < 0) { return 0; } phy_id = (uint32_t)((phy_reg & 0xffff) << 16); phy_reg = phy_read(addr, MII_PHYSID2); if (phy_reg < 0) { return 0; } phy_id |= (phy_reg & 0xffff); return phy_id; } void phy_shutdown(int addr) { phy_write(addr, MII_BMCR, BMCR_PDOWN); }
355f0be89416bdbaf70cca6fdc3ac8ccb218fcfb
f79dec3c4033ca3cbb55d8a51a748cc7b8b6fbab
/net/xipdump/patches/patch-XmgDict.c
742f3f06287025373fd5f8e680167c8f53f75c7b
[]
no_license
jsonn/pkgsrc
fb34c4a6a2d350e8e415f3c4955d4989fcd86881
c1514b5f4a3726d90e30aa16b0c209adbc276d17
refs/heads/trunk
2021-01-24T09:10:01.038867
2017-07-07T15:49:43
2017-07-07T15:49:43
2,095,004
106
47
null
2016-09-19T09:26:01
2011-07-23T23:49:04
Makefile
UTF-8
C
false
false
581
c
patch-XmgDict.c
$NetBSD: patch-XmgDict.c,v 1.1 2013/01/17 16:01:38 joerg Exp $ --- XmgDict.c.orig 2013-01-16 11:25:14.000000000 +0000 +++ XmgDict.c @@ -27,7 +27,7 @@ XFontStruct *xfs; if (he = dict_get(XmgXFSDict,name)) { - return ; + return 0; } else return (dict_add(XmgXFSDict, @@ -71,7 +71,7 @@ Pixel pixel; { if (cmap == x->cmap) { - return ; + return 0; } } VEC_ENDFOR; @@ -158,7 +158,7 @@ Pixmap pixmap; { if (depth == x->depth) { - return ; + return 0; } } VEC_ENDFOR;
9ff9a520d63d473a56a5c0ef15db83166f918f22
bdc27c22522a99b5bff2ec4cfa95fadcba65747d
/thirdparty/EVPath/EVPath/cmenet.c
eeac56f3e5aa078eacd9992b38e238ae2e899da2
[ "Apache-2.0" ]
permissive
ornladios/ADIOS2
a34e257b28adb26e6563b800502266ebb0c9088c
c8b7b66ed21b03bfb773bd972d5aeaaf10231e67
refs/heads/master
2023-08-31T18:11:22.186415
2023-08-29T20:45:03
2023-08-29T20:45:03
75,750,830
243
140
Apache-2.0
2023-09-14T11:15:00
2016-12-06T16:39:55
C++
UTF-8
C
false
false
52,272
c
cmenet.c
/***** Includes *****/ #include "config.h" #if defined (__INTEL_COMPILER) # pragma warning (disable: 1418) #endif #undef NDEBUG #ifdef HAVE_WINDOWS_H #define FD_SETSIZE 1024 #include <winsock2.h> #include <windows.h> #include <process.h> #include <time.h> #define getpid() _getpid() #else #include <time.h> #ifdef HAVE_SYS_TIME_H #include <sys/time.h> #endif #ifdef HAVE_SYS_TIMES_H #include <sys/times.h> #endif #include <sys/socket.h> #ifdef HAVE_SYS_SOCKIO_H #include <sys/sockio.h> #endif #ifdef HAVE_SYS_SELECT_H #include <sys/select.h> #endif #ifdef HAVE_SYS_UN_H #include <sys/un.h> #endif #ifdef HAVE_SYS_UIO_H #include <sys/uio.h> #endif #ifdef HAVE_HOSTLIB_H #include "hostLib.h" #endif #ifdef HAVE_STREAMS_UN_H #include <streams/un.h> #endif #include <netinet/in.h> #include <arpa/inet.h> #ifdef HAVE_NETDB_H #include <netdb.h> #endif #endif #include <stdio.h> #include <fcntl.h> #ifndef HAVE_WINDOWS_H #include <net/if.h> #include <sys/ioctl.h> #include <errno.h> #else #include <windows.h> #define drand48() (((double)rand())/((double)RAND_MAX)) #define lrand48() rand() #define srand48(x) #include <ws2tcpip.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #undef NDEBUG #include <assert.h> #include <signal.h> #include <stdlib.h> #include <string.h> #include <limits.h> #ifdef HAVE_MEMORY_H #include <memory.h> #endif #include <atl.h> #include "evpath.h" #include "cm_transport.h" #include "ev_select.h" #ifndef _MSC_VER #include <pthread.h> #define thr_mutex_t pthread_mutex_t #define thr_thread_t pthread_t #define thr_condition_t pthread_cond_t #define thr_thread_self() pthread_self() #define thr_thread_exit(status) pthread_exit(status); #define thr_thread_detach(thread) pthread_detach(thread); #define thr_thread_yield() sched_yield() #define thr_thread_join(t, s) pthread_join(t, s) #define thr_mutex_init(m) pthread_mutex_init(&m, NULL); #define thr_mutex_lock(m) pthread_mutex_lock(&m); #define thr_mutex_unlock(m) pthread_mutex_unlock(&m); #define thr_mutex_free(m) pthread_mutex_destroy(&m); #define thr_condition_init(c) pthread_cond_init(&c, NULL); #define thr_condition_wait(c, m) pthread_cond_wait(&c, &m); #define thr_condition_signal(c) pthread_cond_signal(&c); #define thr_condition_broadcast(c) pthread_cond_broadcast(&c); #define thr_condition_free(c) pthread_cond_destroy(&c); #define thr_thread_create(w,x,y,z) pthread_create(w,x,y,z); #else //#include <mutex> #include <Windows.h> #define thr_mutex_t HANDLE #define thr_thread_t DWORD #define thr_condition_t HANDLE #define thr_thread_create(w,x,y,z) 0 #define thr_thread_self() GetCurrentThreadId() #define thr_thread_exit(status) #define thr_thread_detach(thread) #define thr_thread_yield() #define thr_thread_join(t, s) (void)s #define thr_mutex_init(m) #define thr_mutex_lock(m) #define thr_mutex_unlock(m) #define thr_mutex_free(m) #define thr_condition_init(c) #define thr_condition_wait(c, m) #define thr_condition_signal(c) #define thr_condition_broadcast(c) #define thr_condition_free(c) #endif #ifdef USE_ZPL_ENET #define ENET_IMPLEMENTATION #define USE_IPV6 #define MAX_CLIENTS 4095 #include <netinet/in.h> #include <zpl-enet/include/enet.h> /* extra function to access the UDP socket FD */ ENET_API enet_uint32 enet_host_get_sock_fd(ENetHost *); enet_uint32 enet_host_get_sock_fd(ENetHost *host) { return host->socket; } extern void ZPLENETdummy() { // for warning suppression (void) enet_initialize_with_callbacks(0, NULL); (void) enet_deinitialize() ; (void) enet_linked_version() ; (void) enet_socket_listen(0, 0) ; (void) enet_socket_accept(0, NULL) ; (void) enet_socket_connect(0, NULL) ; (void) enet_socket_get_option(0, (ENetSocketOption) 1, NULL) ; (void) enet_socket_shutdown(0, (ENetSocketShutdown) 1) ; (void) enet_socketset_select(0, NULL, NULL, 0) ; (void) enet_address_get_host(NULL, NULL, 0 ) ; (void) enet_host_get_peers_count( NULL) ; (void) enet_host_get_packets_sent(NULL) ; (void) enet_host_get_packets_received(NULL) ; (void) enet_host_get_bytes_sent(NULL) ; (void) enet_host_get_bytes_received(NULL) ; (void) enet_host_get_received_data(NULL, NULL) ; (void) enet_host_get_mtu(NULL) ; (void) enet_peer_get_id(NULL) ; (void) enet_peer_get_ip(NULL, NULL, 0) ; (void) enet_peer_get_port(NULL) ; (void) enet_peer_get_rtt(NULL) ; (void) enet_peer_get_packets_sent(NULL) ; (void) enet_peer_get_packets_lost(NULL) ; (void) enet_peer_get_bytes_sent(NULL) ; (void) enet_peer_get_bytes_received(NULL) ; (void) enet_peer_get_state(NULL) ; (void) enet_peer_get_data(NULL) ; (void) enet_peer_set_data(NULL, NULL) ; (void) enet_packet_get_data(NULL) ; (void) enet_packet_get_length(NULL) ; (void) enet_packet_set_free_callback(NULL, NULL) ; (void) enet_packet_create_offset(NULL, 0, 0, 0) ; (void) enet_crc32(NULL, 0) ; (void) enet_host_check_events(NULL, NULL); (void) enet_host_send_raw(NULL, NULL, NULL, 0) ; (void) enet_host_send_raw_ex(NULL, NULL, NULL, 0, 0) ; (void) enet_host_set_intercept(NULL, NULL) ; (void) enet_host_broadcast(NULL, 0, NULL) ; (void) enet_host_compress(NULL, NULL); (void) enet_host_channel_limit(NULL, 0); (void) enet_host_bandwidth_limit(NULL, 0,0); (void) enet_peer_ping_interval(NULL, 0) ; (void) enet_peer_disconnect_now(NULL, 0) ; (void) enet_peer_disconnect_later(NULL, 0) ; (void) enet_peer_throttle_configure(NULL, 0, 0, 0) ; } #define TPORT "CMZplEnet" #define TRANSPORT_STRING "zplenet" #define INTERFACE_NAME(NAME) libcmzplenet_LTX_ ## NAME #else #define TPORT "CMEnet" #define MAX_CLIENTS 0 #define TRANSPORT_STRING "enet" #define INTERFACE_NAME(NAME) libcmenet_LTX_ ## NAME #include <enet/enet.h> #endif #ifndef _MSC_VER #include <arpa/inet.h> #endif #include <time.h> #ifdef HAVE_SYS_TIME_H #include <sys/time.h> #endif #ifdef __MACH__ #include <mach/clock.h> #include <mach/mach.h> #endif typedef struct _queued_data { struct _queued_data *next; struct enet_connection_data *econn_d; ENetPacket *packet; } *queued_data; typedef struct func_list_item { select_list_func func; void *arg1; void *arg2; } FunctionListElement; typedef struct enet_client_data { CManager cm; char *hostname; int listen_port; CMtrans_services svc; ENetHost *server; queued_data pending_data; int wake_write_fd; int wake_read_fd; enet_uint32 last_host_service_zero_return; CMTaskHandle periodic_handle; thr_mutex_t enet_lock; int enet_locked; struct enet_connection_data *pending_connections; } *enet_client_data_ptr; typedef struct enet_connection_data { char *remote_host; #ifndef USE_IPV6 int remote_IP; /* in host byte order */ #else struct in6_addr remote_IP; int remote_IPv4; /* in host byte order */ #endif int remote_contact_port; ENetPeer *peer; CMbuffer read_buffer; int read_buffer_len; ENetPacket *packet; enet_client_data_ptr ecd; CMConnection conn; attr_list conn_attr_list; int connect_condition; struct enet_connection_data *next_pending; } *enet_conn_data_ptr; static atom_t CM_PEER_IP = -1; static atom_t CM_PEER_LISTEN_PORT = -1; static atom_t CM_NETWORK_POSTFIX = -1; static atom_t CM_ENET_PORT = -1; static atom_t CM_ENET_HOSTNAME = -1; static atom_t CM_ENET_ADDR = -1; static atom_t CM_ENET_CONN_TIMEOUT = -1; static atom_t CM_ENET_CONN_REUSE = -1; static atom_t CM_TRANSPORT = -1; static enet_uint32 enet_host_service_warn_interval = 0; #ifdef __cplusplus extern "C" #else extern #endif attr_list INTERFACE_NAME(non_blocking_listen)(CManager cm, CMtrans_services svc, transport_entry trans, attr_list listen_info); #define ENETlock(lock) IntENET_lock(lock, __FILE__, __LINE__) #define ENETunlock(lock) IntENET_unlock(lock, __FILE__, __LINE__) #define gettid() pthread_self() static void IntENET_lock(enet_client_data_ptr ecd, char *file, int line) { // if (file) printf("(PID %lx, TID %lx) Trying ENET Lock at %s, line %d\n", (long) getpid(), (long)gettid(), file, line); thr_mutex_lock(ecd->enet_lock); // if (file) printf("GOT ENET Lock at %s, line %d\n", file, line); ecd->enet_locked++; } static void IntENET_unlock(enet_client_data_ptr ecd, char *file, int line) { // if (file) printf("(PID %lx, TID %lx) ENET Unlock at %s, line %d\n", (long) getpid(), (long)gettid(), file, line); ecd->enet_locked--; thr_mutex_unlock(ecd->enet_lock); } static int check_host(char *hostname, void *sin_addr) { (void)hostname; (void)sin_addr; #ifdef HAS_STRUCT_HOSTEN struct hostent *host_addr; host_addr = gethostbyname(hostname); if (host_addr == NULL) { struct in_addr addr; if (inet_aton(hostname, &addr) == 0) { /* * not translatable as a hostname or * as a dot-style string IP address */ return 0; } assert(sizeof(int) == sizeof(struct in_addr)); *((int *) sin_addr) = *((int*) &addr); } else { memcpy(sin_addr, host_addr->h_addr, host_addr->h_length); } return 1; #endif printf("Check host called, unimplemented\n"); return 0; } static enet_conn_data_ptr create_enet_conn_data(CMtrans_services svc) { enet_conn_data_ptr enet_conn_data = (enet_conn_data_ptr) svc->malloc_func(sizeof(struct enet_connection_data)); enet_conn_data->remote_host = NULL; enet_conn_data->remote_contact_port = -1; enet_conn_data->read_buffer = NULL; enet_conn_data->read_buffer_len = 1; return enet_conn_data; } static void * enet_accept_conn(enet_client_data_ptr ecd, transport_entry trans, ENetAddress *address); static void free_func(void *packet) { /* Clean up the packet now that we're done using it. */ // ENETlock(enet_data); enet_packet_destroy ((ENetPacket*)packet); // ENETunlock(enet_data); } static void handle_packet(CManager cm, CMtrans_services svc, transport_entry trans, enet_conn_data_ptr econn_d, ENetPacket *packet) { CMbuffer cb; svc->trace_out(cm, "A packet of length %u was received.\n", (unsigned int) packet->dataLength); econn_d->read_buffer_len = (int) packet->dataLength; cb = svc->create_data_and_link_buffer(cm, packet->data, econn_d->read_buffer_len); econn_d->read_buffer = cb; cb->return_callback = free_func; cb->return_callback_data = packet; econn_d->packet = packet; /* kick this upstairs */ trans->data_available(trans, econn_d->conn); svc->return_data_buffer(trans->cm, cb); } static void enet_service_network(CManager cm, void *void_trans) { transport_entry trans = (transport_entry) void_trans; enet_client_data_ptr ecd = (enet_client_data_ptr) trans->trans_data; CMtrans_services svc = ecd->svc; ENetEvent event; if (!ecd->server) return; if (!(CM_LOCKED(svc, ecd->cm))) { printf("Enet service network, CManager not locked\n"); } while (ecd->pending_data) { svc->trace_out(cm, "ENET Handling pending data\n"); queued_data entry = ecd->pending_data; ecd->pending_data = entry->next; handle_packet(cm, svc, trans, (enet_conn_data_ptr) entry->econn_d, entry->packet); free(entry); } while (ecd->server) { IntENET_lock(ecd, NULL, 0); int ret = enet_host_service (ecd->server, & event, 0); if (enet_host_service_warn_interval && (enet_time_get() > (ecd->last_host_service_zero_return + enet_host_service_warn_interval))) { fprintf(stderr, "WARNING, time between zero return for enet_host_service = %d msecs\n", enet_time_get() - ecd->last_host_service_zero_return); } IntENET_unlock(ecd, NULL, 0); if (ret <= 0) { break; } switch (event.type) { case ENET_EVENT_TYPE_NONE: break; case ENET_EVENT_TYPE_CONNECT: { enet_conn_data_ptr enet_connection_data = NULL; if (event.peer->data) { enet_conn_data_ptr last = NULL; enet_connection_data = ecd->pending_connections; while (enet_connection_data) { if (enet_connection_data->peer == event.peer) { if (last) { last->next_pending = enet_connection_data->next_pending; } else { ecd->pending_connections = enet_connection_data->next_pending; } enet_connection_data->next_pending = NULL; break; } enet_connection_data = enet_connection_data->next_pending; } } if (enet_connection_data) { svc->condition_signal(cm, enet_connection_data->connect_condition); break; } #ifndef USE_IPV6 struct in_addr addr; addr.s_addr = event.peer->address.host; svc->trace_out(cm, "A new client connected from %s:%u.\n", inet_ntoa(addr), event.peer->address.port); #else char straddr[INET6_ADDRSTRLEN]; inet_ntop(AF_INET6, &event.peer->address.host, straddr, sizeof(straddr)); svc->trace_out(cm, "A new client connected from %s:%u.\n", &straddr[0], event.peer->address.port); struct in_addr addr; if (ntohl(((enet_uint32 *)&event.peer->address.host.s6_addr)[3]) == 0xffff) {; addr.s_addr = ((enet_uint32 *)&event.peer->address.host.s6_addr)[3]; svc->trace_out(cm, "That was IPV4 address %s\n", inet_ntoa(addr)); } #endif enet_connection_data = enet_accept_conn(ecd, trans, &event.peer->address); /* Store any relevant client information here. */ svc->trace_out(cm, "ENET ======== Assigning peer %p has data %p\n", event.peer, enet_connection_data); enet_peer_timeout(event.peer, 0, 0, 200); event.peer->data = enet_connection_data; ((enet_conn_data_ptr)enet_connection_data)->peer = event.peer; break; } case ENET_EVENT_TYPE_RECEIVE: { enet_conn_data_ptr econn_d = (enet_conn_data_ptr) event.peer->data; if (econn_d) { handle_packet(cm, svc, trans, econn_d, event.packet); } else { #ifndef USE_IPV6 struct in_addr addr; addr.s_addr = event.peer->address.host; svc->trace_out(cm, "ENET ====== virgin peer, address is %s, port %u.\n", inet_ntoa(addr), event.peer->address.port); #else char straddr[INET6_ADDRSTRLEN]; inet_ntop(AF_INET6, &event.peer->address.host, straddr, sizeof(straddr)); svc->trace_out(cm, "ENET ====== virgin peer, address is %s, port %u.\n", &straddr[0], event.peer->address.port); #endif svc->trace_out(cm, "ENET ====== DISCARDING DATA\n"); } break; } #ifdef USE_ZPL_ENET case ENET_EVENT_TYPE_DISCONNECT_TIMEOUT: #endif case ENET_EVENT_TYPE_DISCONNECT: { enet_conn_data_ptr enet_conn_data = (enet_conn_data_ptr) event.peer->data; svc->trace_out(cm, "Got a disconnect on connection %p\n", event.peer->data); enet_conn_data = (enet_conn_data_ptr) event.peer->data; enet_conn_data->read_buffer_len = -1; if (enet_conn_data->conn) { svc->connection_fail(enet_conn_data->conn); } break; } default: printf("UNKNOWN EVENT TYPE! %d\n", event.type); break; } } ecd->last_host_service_zero_return = enet_time_get(); } static void enet_service_network_lock(CManager cm, void *void_trans) { transport_entry trans = (transport_entry) void_trans; enet_client_data_ptr ecd = (enet_client_data_ptr) trans->trans_data; CMtrans_services svc = ecd->svc; ACQUIRE_CM_LOCK(svc, cm); enet_service_network(cm, void_trans); DROP_CM_LOCK(svc, cm); } static void read_wake_fd_and_service(CManager cm, void *void_trans) { transport_entry trans = (transport_entry) void_trans; enet_client_data_ptr ecd = (enet_client_data_ptr) trans->trans_data; char buffer; int fd = ecd->wake_read_fd; #ifdef HAVE_WINDOWS_H recv(fd, &buffer, 1, 0); #else if (read(fd, &buffer, 1) != 1) { perror("wake read failed\n"); } #endif enet_service_network(cm, void_trans); } #ifdef NOTDEF static void dump_sockaddr(who, sa) char *who; struct sockaddr_in *sa; { unsigned char *addr; addr = (unsigned char *) &(sa->sin_addr.s_addr); printf("%s: family=%d port=%d addr=%d.%d.%d.%d\n", who, ntohs(sa->sin_family), ntohs(sa->sin_port), addr[0], addr[1], addr[2], addr[3]); } static void dump_sockinfo(msg, fd) char *msg; int fd; { int nl; struct sockaddr_in peer, me; printf("Dumping sockinfo for fd=%d: %s\n", fd, msg); nl = sizeof(me); getsockname(fd, (struct sockaddr *) &me, &nl); dump_sockaddr("Me", &me); nl = sizeof(peer); getpeername(fd, (struct sockaddr *) &peer, &nl); dump_sockaddr("Peer", &peer); } #endif static int conn_reuse = 1; /* * Accept enet connection */ static void * enet_accept_conn(enet_client_data_ptr ecd, transport_entry trans, ENetAddress *address) { CMtrans_services svc = ecd->svc; enet_conn_data_ptr enet_conn_data; CMConnection conn; attr_list conn_attr_list = NULL;; enet_conn_data = create_enet_conn_data(svc); enet_conn_data->ecd = ecd; conn_attr_list = create_attr_list(); conn = svc->connection_create(trans, enet_conn_data, conn_attr_list); enet_conn_data->conn = conn; #ifndef USE_IPV6 add_int_attr(conn_attr_list, CM_PEER_IP, ntohl(address->host)); enet_conn_data->remote_IP = ntohl(address->host); #else enet_conn_data->remote_IP = address->host; enet_conn_data->remote_IPv4 = ntohl(((enet_uint32 *)&address->host.s6_addr)[3]); add_int_attr(conn_attr_list, CM_PEER_IP, enet_conn_data->remote_IPv4); /* remote_IPv4 is in host byte order */ #endif if (!conn_reuse) { enet_conn_data->remote_contact_port = -1; } else { enet_conn_data->remote_contact_port = address->port; } if (enet_conn_data->remote_host != NULL) { svc->trace_out(trans->cm, "Accepted ENET RUDP connection from host \"%s\"", enet_conn_data->remote_host); } else { svc->trace_out(trans->cm, "Accepted ENET RUDP connection from UNKNOWN host"); } add_attr(conn_attr_list, CM_PEER_LISTEN_PORT, Attr_Int4, (attr_value) (intptr_t)enet_conn_data->remote_contact_port); #ifndef USE_IPV6 struct in_addr addr; addr.s_addr = htonl(enet_conn_data->remote_IP); svc->trace_out(trans->cm, "Remote host (IP %s) is listening at port %d\n", inet_ntoa(addr), enet_conn_data->remote_contact_port); #else char straddr[INET6_ADDRSTRLEN]; inet_ntop(AF_INET6, &enet_conn_data->remote_IP, straddr, sizeof(straddr)); svc->trace_out(trans->cm, "Remote host (IP %s) is listening at port %d\n", &straddr[0], enet_conn_data->remote_contact_port); #endif free_attr_list(conn_attr_list); return enet_conn_data; } #ifdef __cplusplus extern "C" #else extern #endif void INTERFACE_NAME(shutdown_conn)(CMtrans_services svc, enet_conn_data_ptr scd) { svc->connection_deref(scd->conn); if (scd->remote_host) free(scd->remote_host); free(scd); } static void * enet_initiate_conn(CManager cm, CMtrans_services svc, transport_entry trans, attr_list attrs, enet_conn_data_ptr enet_conn_data, attr_list conn_attr_list) { int int_port_num; enet_client_data_ptr ecd = (enet_client_data_ptr) trans->trans_data; char *host_name; int host_ip = 0; #ifdef USE_IPV6 struct in6_addr host_ipv6; #endif struct in_addr sin_addr; (void)conn_attr_list; int timeout = 200; /* connection time out default 100 milliseconds */ if (!(CM_LOCKED(svc, ecd->cm))) { printf("Enet service network, CManager not locked in enet_initiate_conn\n"); } if (!query_attr(attrs, CM_ENET_HOSTNAME, /* type pointer */ NULL, /* value pointer */ (attr_value *)(intptr_t) & host_name)) { svc->trace_out(cm, TPORT " transport found no CM_ENET_HOSTNAME attribute"); host_name = NULL; } else { svc->trace_out(cm, TPORT " transport connect to host %s", host_name); } if (!query_attr(attrs, CM_ENET_ADDR, /* type pointer */ NULL, /* value pointer */ (attr_value *)(intptr_t) & host_ip)) { svc->trace_out(cm, "CMEnet transport found no CM_ENET_ADDR attribute"); /* wasn't there */ host_ip = 0; } else { svc->trace_out(cm, "CMEnet transport connect to host_IP %lx", host_ip); } /* HOST_IP is in HOST BYTE ORDER */ if ((host_name == NULL) && (host_ip == 0)) { printf("No host no IP\n"); return 0; } if (!query_attr(attrs, CM_ENET_PORT, /* type pointer */ NULL, /* value pointer */ (attr_value *)(intptr_t) & int_port_num)) { svc->trace_out(cm, "CMEnet transport found no CM_ENET_PORT attribute"); return 0; } else { svc->trace_out(cm, "CMEnet transport connect to port %d", int_port_num); } if (!query_attr(attrs, CM_ENET_CONN_TIMEOUT, /* type pointer */ NULL, /* value pointer */ (attr_value *)(intptr_t) & timeout)) { svc->trace_out(cm, "CMEnet transport found no CM_ENET_CONN_TIMEOUT attribute"); } else { svc->trace_out(cm, "CMEnet transport connection timeout set to %d msecs", timeout); } if (!query_attr(attrs, CM_ENET_CONN_REUSE, /* type pointer */ NULL, /* value pointer */ (attr_value *)(intptr_t) & conn_reuse)) { svc->trace_out(cm, "CMEnet transport found no CM_ENET_CONN_REUSE attribute"); } else { svc->trace_out(cm, "CMEnet transport connection reuse set to %d", conn_reuse); } /* ENET connection, host_name is the machine name */ ENetAddress address; ENetPeer *peer; sin_addr.s_addr = htonl(host_ip); if (host_name) { enet_address_set_host (& address, host_name); #ifndef USE_IPV6 sin_addr.s_addr = address.host; svc->trace_out(cm, "Attempting ENET RUDP connection, USING host=\"%s\", IP = %s, port %d", host_name == 0 ? "(unknown)" : host_name, inet_ntoa(sin_addr), int_port_num); #else char straddr[INET6_ADDRSTRLEN]; inet_ntop(AF_INET6, &address.host, straddr, sizeof(straddr)); svc->trace_out(cm, "Attempting ENET RUDP connection, USING host=\"%s\", IP = %s, port %d", host_name == 0 ? "(unknown)" : host_name, &straddr[0], int_port_num); #endif } else { #ifndef USE_IPV6 address.host = ntohl(host_ip); svc->trace_out(cm, "Attempting ENET RUDP connection, USING IP = %s, port %d", inet_ntoa(sin_addr), int_port_num); #else char straddr[INET6_ADDRSTRLEN]; *((enet_uint32 *)&host_ipv6.s6_addr) = 0; *(((enet_uint32 *)&host_ipv6.s6_addr) + 1) = 0; *(((enet_uint32 *)&host_ipv6.s6_addr) + 2) = htonl(0xffff); *(((enet_uint32 *)&host_ipv6.s6_addr) + 3) = htonl(host_ip); inet_ntop(AF_INET6, &host_ipv6, straddr, sizeof(straddr)); svc->trace_out(cm, "Attempting ENET RUDP connection, USING host=\"%s\", IP = %s, port %d", host_name == 0 ? "(unknown)" : host_name, &straddr[0], int_port_num); sin_addr.s_addr = htonl(host_ip); svc->trace_out(cm, "Attempting ENET RUDP connection, USING IPv4 = %s\n", inet_ntoa(sin_addr)); memcpy(&address.host, &host_ipv6, sizeof(struct in6_addr)); #endif } address.port = (unsigned short) int_port_num; if (ecd->server == NULL) { attr_list l = INTERFACE_NAME(non_blocking_listen)(cm, svc, trans, NULL); if (l) free_attr_list(l); } /* Initiate the connection, allocating the two channels 0 and 1. */ ENETlock(ecd); peer = enet_host_connect (ecd->server, & address, 1, 0); if (peer == NULL) { fprintf (stderr, "No available peers for initiating an ENet connection, count at initiation was %d.\n", MAX_CLIENTS); exit (EXIT_FAILURE); } enet_peer_timeout(peer, 0, 0, 200); ENETunlock(ecd); peer->data = enet_conn_data; enet_conn_data->remote_host = host_name == NULL ? NULL : strdup(host_name); #ifndef USE_IPV6 enet_conn_data->remote_IP = htonl(host_ip); #else memcpy(&enet_conn_data->remote_IP, &host_ipv6, sizeof(enet_conn_data->remote_IP)); enet_conn_data->remote_IPv4 = htonl(((enet_uint32 *)&host_ipv6.s6_addr)[3]); #endif enet_conn_data->remote_contact_port = int_port_num; enet_conn_data->ecd = ecd; enet_conn_data->peer = peer; peer->data = enet_conn_data; svc->trace_out(cm, "ENET ======== On init Assigning peer %p has data %p moving to wait phase\n", peer, enet_conn_data); return enet_conn_data; } /* * Initiate a ENET RUDP connection with another CM. */ #ifdef __cplusplus extern "C" #else extern #endif void * INTERFACE_NAME(initiate_conn_nonblocking)(CManager cm, CMtrans_services svc, transport_entry trans, attr_list attrs, int connect_condition) { enet_conn_data_ptr enet_conn_data = create_enet_conn_data(svc); attr_list conn_attr_list = create_attr_list(); enet_conn_data_ptr ret; enet_conn_data->conn_attr_list = conn_attr_list; enet_conn_data->connect_condition = connect_condition; ret = enet_initiate_conn(cm, svc, trans, attrs, enet_conn_data, conn_attr_list); if (ret) { enet_client_data_ptr ecd = (enet_client_data_ptr) trans->trans_data; ret->next_pending = ecd->pending_connections; ecd->pending_connections = ret; } return (void*)ret; } /* * Initiate a ENET RUDP connection with another CM. */ #ifdef __cplusplus extern "C" #else extern #endif CMConnection INTERFACE_NAME(finalize_conn_nonblocking)(CManager cm, CMtrans_services svc, transport_entry trans, void *client_data, int result) { enet_client_data_ptr ecd = (enet_client_data_ptr) trans->trans_data; enet_conn_data_ptr final_conn_data = (enet_conn_data_ptr) client_data; enet_conn_data_ptr last = NULL, enet_conn_data = ecd->pending_connections; CMConnection conn; attr_list conn_attr_list = final_conn_data->conn_attr_list; if (!result) { while (enet_conn_data) { if (enet_conn_data == final_conn_data) { if (last) { last->next_pending = enet_conn_data->next_pending; } else { ecd->pending_connections = enet_conn_data->next_pending; } enet_conn_data->next_pending = NULL; break; } last = enet_conn_data; enet_conn_data = enet_conn_data->next_pending; } free_attr_list(conn_attr_list); free(enet_conn_data); return NULL; } add_attr(conn_attr_list, CM_PEER_LISTEN_PORT, Attr_Int4, (attr_value) (intptr_t)final_conn_data->remote_contact_port); conn = svc->connection_create(trans, final_conn_data, conn_attr_list); final_conn_data->conn = conn; free_attr_list(conn_attr_list); final_conn_data->conn_attr_list = NULL; svc->connection_addref(conn); /* one ref count went to CM, the other to the user */ return conn; } /* * Check to see that if we were to attempt to initiate a connection as * indicated by the attribute list, would we be connecting to ourselves? * For enet, this involves checking to see if the host name is the * same as ours and if the CM_ENET_PORT matches the one we are listening on. */ #ifdef __cplusplus extern "C" #else extern #endif int INTERFACE_NAME(self_check)(CManager cm, CMtrans_services svc, transport_entry trans, attr_list attrs) { enet_client_data_ptr ecd = (enet_client_data_ptr) trans->trans_data; int host_addr; int int_port_num; char *host_name; char my_host_name[256]; static int IP = 0; /* always in host byte order */ get_IP_config(my_host_name, sizeof(host_name), &IP, NULL, NULL, NULL, NULL, svc->trace_out, (void *)cm); if (IP == 0) { IP = ntohl(INADDR_LOOPBACK); } if (!query_attr(attrs, CM_ENET_HOSTNAME, /* type pointer */ NULL, /* value pointer */ (attr_value *)(intptr_t) & host_name)) { svc->trace_out(cm, "CMself check CMEnet transport found no CM_ENET_HOSTNAME attribute"); host_name = NULL; } if (!query_attr(attrs, CM_ENET_ADDR, /* type pointer */ NULL, /* value pointer */ (attr_value *)(intptr_t) & host_addr)) { svc->trace_out(cm, "CMself check CMEnet transport found no CM_ENET_ADDR attribute"); if (host_name == NULL) return 0; host_addr = 0; } if (!query_attr(attrs, CM_ENET_PORT, /* type pointer */ NULL, /* value pointer */ (attr_value *)(intptr_t) & int_port_num)) { svc->trace_out(cm, "CMself check CMEnet transport found no CM_ENET_PORT attribute"); return 0; } //get_qual_hostname(my_host_name, sizeof(my_host_name), svc, NULL, NULL); if (host_name && (strcmp(host_name, my_host_name) != 0)) { svc->trace_out(cm, "CMself check - Hostnames don't match"); return 0; } if (host_addr && (IP != host_addr)) { svc->trace_out(cm, "CMself check - Host IP addrs don't match, %lx, %lx", IP, host_addr); return 0; } if (int_port_num != ecd->listen_port) { svc->trace_out(cm, "CMself check - Ports don't match, %d, %d", int_port_num, ecd->listen_port); return 0; } svc->trace_out(cm, "CMself check returning TRUE"); return 1; } #ifdef __cplusplus extern "C" #else extern #endif int INTERFACE_NAME(connection_eq)(CManager cm, CMtrans_services svc, transport_entry trans, attr_list attrs, enet_conn_data_ptr ecd) { int int_port_num; int requested_IP = -1; char *host_name = NULL; (void) trans; if (!query_attr(attrs, CM_ENET_HOSTNAME, /* type pointer */ NULL, /* value pointer */ (attr_value *)(intptr_t) & host_name)) { svc->trace_out(cm, "CMEnet transport found no CM_ENET_HOST attribute"); } if (!query_attr(attrs, CM_ENET_PORT, /* type pointer */ NULL, /* value pointer */ (attr_value *)(intptr_t) & int_port_num)) { svc->trace_out(cm, "Conn Eq CMenet transport found no CM_ENET_PORT attribute"); return 0; } if (!query_attr(attrs, CM_ENET_ADDR, /* type pointer */ NULL, /* value pointer */ (attr_value *)(intptr_t) & requested_IP)) { svc->trace_out(cm, "CMENET transport found no CM_ENET_ADDR attribute"); } if (requested_IP == -1) { check_host(host_name, (void *) &requested_IP); requested_IP = ntohl(requested_IP); struct in_addr addr; addr.s_addr = htonl(requested_IP); svc->trace_out(cm, "IP translation for hostname %s is %s", host_name, inet_ntoa(addr)); } /* requested IP is in host byte order */ if (ecd->peer->state != ENET_PEER_STATE_CONNECTED) { svc->trace_out(cm, "ENET Conn_eq returning FALSE, peer not connected"); return 0; } struct in_addr addr1, addr2; #ifdef USE_IPV6 addr1.s_addr = htonl(ecd->remote_IPv4); #else addr1.s_addr = htonl(ecd->remote_IP); #endif addr2.s_addr = htonl(requested_IP); svc->trace_out(cm, "ENET Conn_eq comparing IP/ports %s/%d and %s/%d", inet_ntoa(addr1), ecd->remote_contact_port, inet_ntoa(addr2), int_port_num); #ifdef USE_IPV6 if ((ecd->remote_IPv4 == requested_IP) && /* both in host byte order */ #else if ((ecd->remote_IP == requested_IP) && /* both in host byte order */ #endif (ecd->remote_contact_port == int_port_num)) { svc->trace_out(cm, "ENET Conn_eq returning TRUE"); return 1; } svc->trace_out(cm, "ENET Conn_eq returning FALSE"); return 0; } static attr_list build_listen_attrs(CManager cm, CMtrans_services svc, enet_client_data_ptr ecd, attr_list listen_info, int int_port_num) { char host_name[256]; attr_list ret_list; int IP; int use_hostname = 0; svc->trace_out(cm, "CMEnet listen succeeded on port %d", int_port_num); get_IP_config(host_name, sizeof(host_name), &IP, NULL, NULL, &use_hostname, listen_info, svc->trace_out, (void *)cm); ret_list = create_attr_list(); if (ecd) { ecd->hostname = strdup(host_name); ecd->listen_port = int_port_num; } if ((IP != 0) && !use_hostname) { add_attr(ret_list, CM_ENET_ADDR, Attr_Int4, (attr_value) (intptr_t)IP); } if ((getenv("CMEnetsUseHostname") != NULL) || use_hostname) { add_attr(ret_list, CM_ENET_HOSTNAME, Attr_String, (attr_value) strdup(host_name)); } else if (IP == 0) { add_int_attr(ret_list, CM_ENET_ADDR, INADDR_LOOPBACK); } add_attr(ret_list, CM_ENET_PORT, Attr_Int4, (attr_value) (intptr_t)int_port_num); add_attr(ret_list, CM_TRANSPORT, Attr_String, (attr_value) strdup(TRANSPORT_STRING)); return ret_list; } static void wake_enet_server_thread(enet_client_data_ptr ecd) { static char buffer = 'W'; /* doesn't matter what we write */ if (ecd->wake_write_fd != -1) { #ifdef HAVE_WINDOWS_H send(ecd->wake_write_fd, &buffer, 1, 0); #else if (write(ecd->wake_write_fd, &buffer, 1) != 1) { printf("Whoops, wake write failed\n"); } #endif } } /* * Create an IP socket for connection from other CMs */ #ifdef __cplusplus extern "C" #else extern #endif attr_list INTERFACE_NAME(non_blocking_listen)(CManager cm, CMtrans_services svc, transport_entry trans, attr_list listen_info) { enet_client_data_ptr ecd = (enet_client_data_ptr) trans->trans_data; ENetAddress address; ENetHost * server; int attr_port_num = 0; u_short port_num = 0; if (!(CM_LOCKED(svc, cm))) { printf("ENET non_blocking listen, CManager not locked\n"); } /* * Check to see if a bind to a specific port was requested */ if (listen_info != NULL && !query_attr(listen_info, CM_ENET_PORT, NULL, (attr_value *)(intptr_t) & attr_port_num)) { port_num = 0; } else { if (attr_port_num > USHRT_MAX || attr_port_num < 0) { fprintf(stderr, "Requested port number %d is invalid\n", attr_port_num); return NULL; } port_num = attr_port_num; } svc->trace_out(cm, "CMEnet begin listen, requested port %d", attr_port_num); address.host = ENET_HOST_ANY; if (ecd->server != NULL) { /* we're already listening */ if (port_num == 0) { /* not requesting a specific port, return what we have */ return build_listen_attrs(cm, svc, NULL, listen_info, ecd->listen_port); } else { printf("CMlisten_specific() requesting a specific port follows other Enet operation which initiated listen at another port. Only one listen allowed, second listen fails.\n"); return NULL; } } if (port_num != 0) { /* Bind the server to the default localhost. */ /* A specific host address can be specified by */ /* enet_address_set_host (& address, "x.x.x.x"); */ address.port = port_num; svc->trace_out(cm, "CMEnet trying to bind selected port %d", port_num); ENETlock(ecd); server = enet_host_create (& address /* the address to bind the server host to */, MAX_CLIENTS, /* max 4095 connections */ 1 /* allow up to 2 channels to be used, 0 and 1 */, 0 /* assume any amount of incoming bandwidth */, 0 /* assume any amount of outgoing bandwidth */); ENETunlock(ecd); if (server == NULL) { fprintf (stderr, "An error occurred while trying to create an ENet server host.\n"); return NULL; } } else { int low_bound, high_bound; get_IP_config(NULL, 0, NULL, &low_bound, &high_bound, NULL, listen_info, svc->trace_out, (void *)cm); if (high_bound == -1) { /* unconstrained port */ address.port = 0; svc->trace_out(cm, "CMEnet trying to bind to any available port"); ENETlock(ecd); server = enet_host_create (& address /* the address to bind the server host to */, MAX_CLIENTS, /* max 4095 connections */ 1 /* allow up to 2 channels to be used, 0 and 1 */, 0 /* assume any amount of incoming bandwidth */, 0 /* assume any amount of outgoing bandwidth */); ENETunlock(ecd); if (server == NULL) { fprintf (stderr, "An error occurred while trying to create an ENet server host.\n"); return NULL; } address.port = server->address.port; svc->trace_out(cm, "CMEnet is listening on port %d\n", address.port); } else { /* specified port range */ /* port num is free. Constrain to range 26000 : 26100 */ int size; int tries; srand48(time(NULL) + getpid()); restart: size = high_bound - low_bound; tries = 10; while (tries > 0) { int target = low_bound + (int)(size * drand48()); address.port = target; svc->trace_out(cm, "CMEnet trying to bind port %d", target); ENETlock(ecd); server = enet_host_create (& address /* the address to bind the server host to */, MAX_CLIENTS /* 0 means dynamic alloc clients and/or outgoing connnections */, 1 /* allow up to 2 channels to be used, 0 and 1 */, 0 /* assume any amount of incoming bandwidth */, 0 /* assume any amount of outgoing bandwidth */); ENETunlock(ecd); tries--; if (server != NULL) tries = 0; if (tries == 5) { /* try reseeding in case we're in sync with another process */ srand48(time(NULL) + getpid()); } } if (server == NULL) { high_bound += 100; goto restart; } } } ecd->server = server; svc->fd_add_select(cm, enet_host_get_sock_fd (server), (select_list_func) enet_service_network, (void*)cm, (void*)trans); ecd->periodic_handle = svc->add_periodic_task(cm, 0, 100, (CMPollFunc) enet_service_network_lock, (void*)trans); svc->trace_out(ecd->cm, "CMENET Adding read_wake_fd as action on fd %d", ecd->wake_read_fd); svc->fd_add_select(cm, ecd->wake_read_fd, (select_list_func)read_wake_fd_and_service, (void*)cm, (void*)trans); return build_listen_attrs(cm, svc, ecd, listen_info, address.port); } #if defined(HAVE_WINDOWS_H) && !defined(NEED_IOVEC_DEFINE) #define NEED_IOVEC_DEFINE #endif #ifdef NEED_IOVEC_DEFINE struct iovec { void *iov_base; size_t iov_len; }; #endif #ifdef __cplusplus extern "C" #else extern #endif void * INTERFACE_NAME(read_block_func)(CMtrans_services svc, enet_conn_data_ptr conn_data, ssize_t *actual_len, ssize_t *offset_ptr) { CMbuffer cb; if (conn_data->read_buffer_len == -1) return NULL; *actual_len = conn_data->read_buffer_len; *offset_ptr = 0; cb = conn_data->read_buffer; conn_data->read_buffer_len = 0; conn_data->read_buffer = NULL; return cb; } #ifdef CURRENT_UTC_TIME_NEEDED static void current_utc_time(struct timespec *ts) { #ifdef __MACH__ // OS X does not have clock_gettime, use clock_get_time clock_serv_t cclock; mach_timespec_t mts; host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); clock_get_time(cclock, &mts); mach_port_deallocate(mach_task_self(), cclock); ts->tv_sec = mts.tv_sec; ts->tv_nsec = mts.tv_nsec; #else clock_gettime(CLOCK_REALTIME, ts); #endif } #endif #ifdef TIME_DIFF_USED static struct timespec time_diff(struct timespec start, struct timespec end) { struct timespec temp; if ((end.tv_nsec-start.tv_nsec)<0) { temp.tv_sec = end.tv_sec-start.tv_sec-1; temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec; } else { temp.tv_sec = end.tv_sec-start.tv_sec; temp.tv_nsec = end.tv_nsec-start.tv_nsec; } return temp; } #endif #ifdef __cplusplus extern "C" #else extern #endif int INTERFACE_NAME(writev_func)(CMtrans_services svc, enet_conn_data_ptr ecd, struct iovec *iov, size_t iovcnt, attr_list attrs) { size_t i; size_t length = 0; (void) attrs; for (i = 0; i < iovcnt; i++) { length += iov[i].iov_len; } svc->trace_out(ecd->ecd->cm, "CMENET vector write of %d bytes on peer %p", length, ecd->peer); /* Create a reliable packet of the right size */ if (!(CM_LOCKED(svc, ecd->ecd->cm))) { printf("ENET writev, CManager not locked\n"); } ENETlock(ecd->ecd); ENetPacket * packet = enet_packet_create (NULL, length, ENET_PACKET_FLAG_RELIABLE); ENETunlock(ecd->ecd); length = 0; /* copy in the data */ for (i = 0; i < iovcnt; i++) { memcpy(packet->data + length, iov[i].iov_base, iov[i].iov_len); length += iov[i].iov_len; } /* Send the packet to the peer over channel id 0. */ ENETlock(ecd->ecd); if (enet_peer_send (ecd->peer, 0, packet) == -1) { enet_packet_destroy(packet); svc->trace_out(ecd->ecd->cm, "ENET ====== failed to send a packet to peer %p, state %d\n", ecd->peer, ecd->peer->state); return -1; } ENETunlock(ecd->ecd); wake_enet_server_thread(ecd->ecd); return (int)iovcnt; } static int enet_global_init = 0; static void free_enet_data(CManager cm, void *ecdv) { enet_client_data_ptr ecd = (enet_client_data_ptr) ecdv; CMtrans_services svc = ecd->svc; (void)cm; if (ecd->hostname != NULL) svc->free_func(ecd->hostname); svc->free_func(ecd); } static void shutdown_enet_thread (CManager cm, void *ecdv) { enet_client_data_ptr ecd = (enet_client_data_ptr) ecdv; CMtrans_services svc = ecd->svc; (void)cm; if (ecd->server != NULL) { ENetHost * server = ecd->server; ENETlock(ecd); enet_host_flush(ecd->server); ENETunlock(ecd); svc->fd_remove_select(cm, enet_host_get_sock_fd (server)); svc->remove_periodic(ecd->periodic_handle); ecd->server = NULL; ENETlock(ecd); enet_host_destroy(server); ENETunlock(ecd); } } #ifdef HAVE_WINDOWS_H static char* WSAerror_str(err) int err; { switch(err) { case WSAEINTR: return "WSAEINTR"; case WSAEBADF: return "WSAEBADF"; case WSAEACCES: return "WSAEACCES"; case WSAEFAULT: return "WSAEFAULT"; case WSAEINVAL: return "WSAEINVAL"; case WSAEMFILE: return "WSAEMFILE"; case WSAEWOULDBLOCK: return "WSAEWOULDBLOCK"; case WSAEINPROGRESS: return "WSAEINPROGRESS"; case WSAEALREADY: return "WSAEALREADY"; case WSAENOTSOCK: return "WSAENOTSOCK"; case WSAEDESTADDRREQ: return "WSAEDESTADDRREQ"; case WSAEMSGSIZE: return "WSAEMSGSIZE"; case WSAEPROTOTYPE: return "WSAEPROTOTYPE"; case WSAENOPROTOOPT: return "WSAENOPROTOOPT"; case WSAEPROTONOSUPPORT: return "WSAEPROTONOSUPPORT"; case WSAESOCKTNOSUPPORT: return "WSAESOCKTNOSUPPORT"; case WSAEOPNOTSUPP: return "WSAEOPNOTSUPP"; case WSAEPFNOSUPPORT: return "WSAEPFNOSUPPORT"; case WSAEAFNOSUPPORT: return "WSAEAFNOSUPPORT"; case WSAEADDRINUSE: return "WSAEADDRINUSE"; case WSAEADDRNOTAVAIL: return "WSAEADDRNOTAVAIL"; case WSAENETDOWN: return "WSAENETDOWN"; case WSAENETUNREACH: return "WSAENETUNREACH"; case WSAENETRESET: return "WSAENETRESET"; case WSAECONNABORTED: return "WSAECONNABORTED"; case WSAECONNRESET: return "WSAECONNRESET"; case WSAENOBUFS: return "WSAENOBUFS"; case WSAEISCONN: return "WSAEISCONN"; case WSAENOTCONN: return "WSAENOTCONN"; case WSAESHUTDOWN: return "WSAESHUTDOWN"; case WSAETOOMANYREFS: return "WSAETOOMANYREFS"; case WSAETIMEDOUT: return "WSAETIMEDOUT"; case WSAECONNREFUSED: return "WSAECONNREFUSED"; case WSAELOOP: return "WSAELOOP"; case WSAENAMETOOLONG: return "WSAENAMETOOLONG"; case WSAEHOSTDOWN: return "WSAEHOSTDOWN"; case WSAEHOSTUNREACH: return "WSAEHOSTUNREACH"; case WSAENOTEMPTY: return "WSAENOTEMPTY"; case WSAEPROCLIM: return "WSAEPROCLIM"; case WSAEUSERS: return "WSAEUSERS"; case WSAEDQUOT: return "WSAEDQUOT"; case WSAESTALE: return "WSAESTALE"; case WSAEREMOTE: return "WSAEREMOTE"; case WSAEDISCON: return "WSAEDISCON"; case WSASYSNOTREADY: return "WSASYSNOTREADY"; case WSAVERNOTSUPPORTED: return "WSAVERNOTSUPPORTED"; case WSANOTINITIALISED: return "WSANOTINITIALISED"; default: return "Unknown Winsock error"; } } /* * Note. Unfortunately, the _pipe() function on WinNT * produces FDs that you can't use in select(). This ruins what we want * this pipe for, which is to wake up a thread sleeping in select(). * So, we need to introduce a pipe function that returns two socket FDs. * NT Sux. */ int pipe(filedes) SOCKET filedes[2]; { int length; struct sockaddr_in sock_addr; int sock_opt_val = 1; SOCKET sock1, sock2, conn_sock; unsigned long block = TRUE; int delay_value = 1; conn_sock = socket(AF_INET, SOCK_STREAM, 0); if (conn_sock == SOCKET_ERROR) { fprintf(stderr, "Cannot open INET socket\n"); return -1; } sock_addr.sin_family = PF_INET; sock_addr.sin_addr.s_addr = INADDR_ANY; sock_addr.sin_port = 0; if (bind(conn_sock, (struct sockaddr *) &sock_addr, sizeof sock_addr) == SOCKET_ERROR) { fprintf(stderr, "Cannot bind INET socket\n"); return -1; } length = sizeof sock_addr; if (getsockname(conn_sock, (struct sockaddr *) &sock_addr, &length) < 0) { fprintf(stderr, "Cannot get socket name\n"); return -1; } /* begin listening for conns */ if (listen(conn_sock, FD_SETSIZE)) { fprintf(stderr, "listen failed\n"); return -1; } /* send sock */ if ((sock1 = socket(AF_INET, SOCK_STREAM, 0)) == SOCKET_ERROR) { return -1; } sock_addr.sin_addr.s_addr = 0x0100007f; /* loopback */ sock_addr.sin_family = PF_INET; if (ioctlsocket(sock1, FIONBIO, &block) != 0) { printf("ioctl failed\n"); } if (connect(sock1, (struct sockaddr *) &sock_addr, sizeof sock_addr) == SOCKET_ERROR) { int err = WSAGetLastError(); if (err != WSAEWOULDBLOCK) { printf("unexpected error from connect, %s\n", WSAerror_str(err)); } } if ((sock2 = accept(conn_sock, (struct sockaddr *) 0, (int *) 0)) == SOCKET_ERROR) { int err = WSAGetLastError(); printf("err was %s\n", WSAerror_str(err)); } setsockopt(sock2, IPPROTO_TCP, TCP_NODELAY, (char *) &delay_value, sizeof(delay_value)); { fd_set stXcptFDS,stWriteFDS; struct timeval stTimeOut; /* for select() timeout (none) */ int wRet; EVPATH_FD_ZERO((fd_set FAR*)&(stXcptFDS)); EVPATH_FD_ZERO((fd_set FAR*)&(stWriteFDS)); FD_SET(sock1, (fd_set FAR*)&(stWriteFDS)); FD_SET(sock1, (fd_set FAR*)&(stXcptFDS)); stTimeOut.tv_sec = 10; stTimeOut.tv_usec = 0; wRet = select(-1, NULL, (fd_set FAR*)&(stWriteFDS), (fd_set FAR*)&(stXcptFDS), NULL); if (wRet == SOCKET_ERROR) { int err = WSAGetLastError(); printf("err was %s\n", WSAerror_str(err)); } } setsockopt(sock1, IPPROTO_TCP, TCP_NODELAY, (char *) &delay_value, sizeof(delay_value)); filedes[0] = sock1; filedes[1] = sock2; return 0; } #endif #ifdef __cplusplus extern "C" #else extern #endif void * INTERFACE_NAME(initialize)(CManager cm, CMtrans_services svc, transport_entry trans, attr_list attrs) { static int atom_init = 0; int filedes[2]; char *env = getenv("ENET_HOST_SERVICE_WARN_INTERVAL"); enet_client_data_ptr enet_data; (void)attrs; svc->trace_out(cm, "Initialize ENET reliable UDP transport built in %s", EVPATH_MODULE_BUILD_DIR); if (enet_global_init == 0) { if (enet_initialize () != 0) { fprintf (stderr, "An error occurred while initializing ENet.\n"); //return EXIT_FAILURE; } #ifndef USE_ZPL_ENET enet_time_set(0); /* rollover in 50 days, old ENET only */ #endif } if (atom_init == 0) { CM_ENET_HOSTNAME = attr_atom_from_string("CM_ENET_HOST"); CM_ENET_PORT = attr_atom_from_string("CM_ENET_PORT"); CM_ENET_ADDR = attr_atom_from_string("CM_ENET_ADDR"); CM_TRANSPORT = attr_atom_from_string("CM_TRANSPORT"); CM_PEER_IP = attr_atom_from_string("PEER_IP"); CM_PEER_LISTEN_PORT = attr_atom_from_string("PEER_LISTEN_PORT"); CM_NETWORK_POSTFIX = attr_atom_from_string("CM_NETWORK_POSTFIX"); CM_ENET_CONN_TIMEOUT = attr_atom_from_string("CM_ENET_CONN_TIMEOUT"); CM_ENET_CONN_REUSE = attr_atom_from_string("CM_ENET_CONN_REUSE"); (void)CM_NETWORK_POSTFIX; atom_init++; } if (env) { sscanf(env, "%d", &enet_host_service_warn_interval); fprintf(stderr, "DEBUG: Setting enet_host_service_warn_interval to %d\n", enet_host_service_warn_interval); } enet_data = (enet_client_data_ptr) svc->malloc_func(sizeof(struct enet_client_data)); memset(enet_data, 0, sizeof(struct enet_client_data)); thr_mutex_init(enet_data->enet_lock); enet_data->enet_locked = 0; enet_data->cm = cm; enet_data->hostname = NULL; enet_data->listen_port = -1; enet_data->svc = svc; enet_data->server = NULL; enet_data->pending_data = NULL; if (pipe(filedes) != 0) { perror("Pipe for wake not created. ENET wake mechanism inoperative."); return NULL; } enet_data->wake_read_fd = filedes[0]; enet_data->wake_write_fd = filedes[1]; svc->add_shutdown_task(cm, shutdown_enet_thread, (void *) enet_data, SHUTDOWN_TASK); svc->add_shutdown_task(cm, free_enet_data, (void *) enet_data, FREE_TASK); return (void *) enet_data; } #ifdef USE_ZPL_ENET extern transport_entry cmzplenet_add_static_transport(CManager cm, CMtrans_services svc) #else extern transport_entry cmenet_add_static_transport(CManager cm, CMtrans_services svc) #endif { transport_entry transport; transport = (transport_entry) svc->malloc_func(sizeof(struct _transport_item)); memset(transport, 0, sizeof(*transport)); #ifndef USE_ZPL_ENET transport->trans_name = strdup("enet"); #else transport->trans_name = strdup("zplenet"); #endif transport->cm = cm; transport->transport_init = (CMTransport_func)INTERFACE_NAME(initialize); transport->listen = (CMTransport_listen_func)INTERFACE_NAME(non_blocking_listen); transport->initiate_conn = NULL; transport->initiate_conn_nonblocking = (CMTransport_NBconn_func)INTERFACE_NAME(initiate_conn_nonblocking); transport->finalize_conn_nonblocking = (CMTransport_NBconn_final_func)INTERFACE_NAME(finalize_conn_nonblocking); transport->self_check = (CMTransport_self_check_func)INTERFACE_NAME(self_check); transport->connection_eq = (CMTransport_connection_eq_func)INTERFACE_NAME(connection_eq); transport->shutdown_conn = (CMTransport_shutdown_conn_func)INTERFACE_NAME(shutdown_conn); transport->read_block_func = (CMTransport_read_block_func)INTERFACE_NAME(read_block_func); transport->read_to_buffer_func = (CMTransport_read_to_buffer_func)NULL; transport->writev_func = (CMTransport_writev_func)INTERFACE_NAME(writev_func); transport->get_transport_characteristics = NULL; if (transport->transport_init) { transport->trans_data = transport->transport_init(cm, svc, transport); } return transport; }
99efd47ff25782ad1b0e51d1b3ac9f944ef7d725
7c857119fe1505b1d80d6e62969661c06dc1a2f4
/MdePkg/Include/Protocol/PciIo.h
78a845ad844fbe7d93d892434e2e6fffe0de9f1b
[ "BSD-2-Clause" ]
permissive
CloverHackyColor/CloverBootloader
7042ca7dd6b513d22be591a295e49071ae1482ee
2711170df4f60b2ae5aa20add3e00f35cf57b7e5
refs/heads/master
2023-08-30T22:14:34.590134
2023-08-27T19:14:02
2023-08-27T19:14:02
205,810,121
4,734
770
BSD-2-Clause
2023-09-03T12:41:33
2019-09-02T08:22:14
C
UTF-8
C
false
false
26,563
h
PciIo.h
/** @file EFI PCI I/O Protocol provides the basic Memory, I/O, PCI configuration, and DMA interfaces that a driver uses to access its PCI controller. Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #ifndef __PCI_IO_H__ #define __PCI_IO_H__ /// /// Global ID for the PCI I/O Protocol /// #define EFI_PCI_IO_PROTOCOL_GUID \ { \ 0x4cf5b200, 0x68b8, 0x4ca5, {0x9e, 0xec, 0xb2, 0x3e, 0x3f, 0x50, 0x2, 0x9a } \ } typedef struct _EFI_PCI_IO_PROTOCOL EFI_PCI_IO_PROTOCOL; /// /// ******************************************************* /// EFI_PCI_IO_PROTOCOL_WIDTH /// ******************************************************* /// typedef enum { EfiPciIoWidthUint8 = 0, EfiPciIoWidthUint16, EfiPciIoWidthUint32, EfiPciIoWidthUint64, EfiPciIoWidthFifoUint8, EfiPciIoWidthFifoUint16, EfiPciIoWidthFifoUint32, EfiPciIoWidthFifoUint64, EfiPciIoWidthFillUint8, EfiPciIoWidthFillUint16, EfiPciIoWidthFillUint32, EfiPciIoWidthFillUint64, EfiPciIoWidthMaximum } EFI_PCI_IO_PROTOCOL_WIDTH; // // Complete PCI address generater // #define EFI_PCI_IO_PASS_THROUGH_BAR 0xff ///< Special BAR that passes a memory or I/O cycle through unchanged #define EFI_PCI_IO_ATTRIBUTE_MASK 0x077f ///< All the following I/O and Memory cycles #define EFI_PCI_IO_ATTRIBUTE_ISA_MOTHERBOARD_IO 0x0001 ///< I/O cycles 0x0000-0x00FF (10 bit decode) #define EFI_PCI_IO_ATTRIBUTE_ISA_IO 0x0002 ///< I/O cycles 0x0100-0x03FF or greater (10 bit decode) #define EFI_PCI_IO_ATTRIBUTE_VGA_PALETTE_IO 0x0004 ///< I/O cycles 0x3C6, 0x3C8, 0x3C9 (10 bit decode) #define EFI_PCI_IO_ATTRIBUTE_VGA_MEMORY 0x0008 ///< MEM cycles 0xA0000-0xBFFFF (24 bit decode) #define EFI_PCI_IO_ATTRIBUTE_VGA_IO 0x0010 ///< I/O cycles 0x3B0-0x3BB and 0x3C0-0x3DF (10 bit decode) #define EFI_PCI_IO_ATTRIBUTE_IDE_PRIMARY_IO 0x0020 ///< I/O cycles 0x1F0-0x1F7, 0x3F6, 0x3F7 (10 bit decode) #define EFI_PCI_IO_ATTRIBUTE_IDE_SECONDARY_IO 0x0040 ///< I/O cycles 0x170-0x177, 0x376, 0x377 (10 bit decode) #define EFI_PCI_IO_ATTRIBUTE_MEMORY_WRITE_COMBINE 0x0080 ///< Map a memory range so writes are combined #define EFI_PCI_IO_ATTRIBUTE_IO 0x0100 ///< Enable the I/O decode bit in the PCI Config Header #define EFI_PCI_IO_ATTRIBUTE_MEMORY 0x0200 ///< Enable the Memory decode bit in the PCI Config Header #define EFI_PCI_IO_ATTRIBUTE_BUS_MASTER 0x0400 ///< Enable the DMA bit in the PCI Config Header #define EFI_PCI_IO_ATTRIBUTE_MEMORY_CACHED 0x0800 ///< Map a memory range so all r/w accesses are cached #define EFI_PCI_IO_ATTRIBUTE_MEMORY_DISABLE 0x1000 ///< Disable a memory range #define EFI_PCI_IO_ATTRIBUTE_EMBEDDED_DEVICE 0x2000 ///< Clear for an add-in PCI Device #define EFI_PCI_IO_ATTRIBUTE_EMBEDDED_ROM 0x4000 ///< Clear for a physical PCI Option ROM accessed through ROM BAR #define EFI_PCI_IO_ATTRIBUTE_DUAL_ADDRESS_CYCLE 0x8000 ///< Clear for PCI controllers that can not genrate a DAC #define EFI_PCI_IO_ATTRIBUTE_ISA_IO_16 0x10000 ///< I/O cycles 0x0100-0x03FF or greater (16 bit decode) #define EFI_PCI_IO_ATTRIBUTE_VGA_PALETTE_IO_16 0x20000 ///< I/O cycles 0x3C6, 0x3C8, 0x3C9 (16 bit decode) #define EFI_PCI_IO_ATTRIBUTE_VGA_IO_16 0x40000 ///< I/O cycles 0x3B0-0x3BB and 0x3C0-0x3DF (16 bit decode) #define EFI_PCI_DEVICE_ENABLE (EFI_PCI_IO_ATTRIBUTE_IO | EFI_PCI_IO_ATTRIBUTE_MEMORY | EFI_PCI_IO_ATTRIBUTE_BUS_MASTER) #define EFI_VGA_DEVICE_ENABLE (EFI_PCI_IO_ATTRIBUTE_VGA_PALETTE_IO | EFI_PCI_IO_ATTRIBUTE_VGA_MEMORY | EFI_PCI_IO_ATTRIBUTE_VGA_IO | EFI_PCI_IO_ATTRIBUTE_IO) /// /// ******************************************************* /// EFI_PCI_IO_PROTOCOL_OPERATION /// ******************************************************* /// typedef enum { /// /// A read operation from system memory by a bus master. /// EfiPciIoOperationBusMasterRead, /// /// A write operation from system memory by a bus master. /// EfiPciIoOperationBusMasterWrite, /// /// Provides both read and write access to system memory by both the processor and a /// bus master. The buffer is coherent from both the processor's and the bus master's point of view. /// EfiPciIoOperationBusMasterCommonBuffer, EfiPciIoOperationMaximum } EFI_PCI_IO_PROTOCOL_OPERATION; /// /// ******************************************************* /// EFI_PCI_IO_PROTOCOL_ATTRIBUTE_OPERATION /// ******************************************************* /// typedef enum { /// /// Retrieve the PCI controller's current attributes, and return them in Result. /// EfiPciIoAttributeOperationGet, /// /// Set the PCI controller's current attributes to Attributes. /// EfiPciIoAttributeOperationSet, /// /// Enable the attributes specified by the bits that are set in Attributes for this PCI controller. /// EfiPciIoAttributeOperationEnable, /// /// Disable the attributes specified by the bits that are set in Attributes for this PCI controller. /// EfiPciIoAttributeOperationDisable, /// /// Retrieve the PCI controller's supported attributes, and return them in Result. /// EfiPciIoAttributeOperationSupported, EfiPciIoAttributeOperationMaximum } EFI_PCI_IO_PROTOCOL_ATTRIBUTE_OPERATION; /** Reads from the memory space of a PCI controller. Returns either when the polling exit criteria is satisfied or after a defined duration. @param This A pointer to the EFI_PCI_IO_PROTOCOL instance. @param Width Signifies the width of the memory or I/O operations. @param BarIndex The BAR index of the standard PCI Configuration header to use as the base address for the memory operation to perform. @param Offset The offset within the selected BAR to start the memory operation. @param Mask Mask used for the polling criteria. @param Value The comparison value used for the polling exit criteria. @param Delay The number of 100 ns units to poll. @param Result Pointer to the last value read from the memory location. @retval EFI_SUCCESS The last data returned from the access matched the poll exit criteria. @retval EFI_UNSUPPORTED BarIndex not valid for this PCI controller. @retval EFI_UNSUPPORTED Offset is not valid for the BarIndex of this PCI controller. @retval EFI_TIMEOUT Delay expired before a match occurred. @retval EFI_OUT_OF_RESOURCES The request could not be completed due to a lack of resources. @retval EFI_INVALID_PARAMETER One or more parameters are invalid. **/ typedef EFI_STATUS (EFIAPI *EFI_PCI_IO_PROTOCOL_POLL_IO_MEM)( IN EFI_PCI_IO_PROTOCOL *This, IN EFI_PCI_IO_PROTOCOL_WIDTH Width, IN UINT8 BarIndex, IN UINT64 Offset, IN UINT64 Mask, IN UINT64 Value, IN UINT64 Delay, OUT UINT64 *Result ); /** Enable a PCI driver to access PCI controller registers in the PCI memory or I/O space. @param This A pointer to the EFI_PCI_IO_PROTOCOL instance. @param Width Signifies the width of the memory or I/O operations. @param BarIndex The BAR index of the standard PCI Configuration header to use as the base address for the memory or I/O operation to perform. @param Offset The offset within the selected BAR to start the memory or I/O operation. @param Count The number of memory or I/O operations to perform. @param Buffer For read operations, the destination buffer to store the results. For write operations, the source buffer to write data from. @retval EFI_SUCCESS The data was read from or written to the PCI controller. @retval EFI_UNSUPPORTED BarIndex not valid for this PCI controller. @retval EFI_UNSUPPORTED The address range specified by Offset, Width, and Count is not valid for the PCI BAR specified by BarIndex. @retval EFI_OUT_OF_RESOURCES The request could not be completed due to a lack of resources. @retval EFI_INVALID_PARAMETER One or more parameters are invalid. **/ typedef EFI_STATUS (EFIAPI *EFI_PCI_IO_PROTOCOL_IO_MEM)( IN EFI_PCI_IO_PROTOCOL *This, IN EFI_PCI_IO_PROTOCOL_WIDTH Width, IN UINT8 BarIndex, IN UINT64 Offset, IN UINTN Count, IN OUT VOID *Buffer ); typedef struct { /// /// Read PCI controller registers in the PCI memory or I/O space. /// EFI_PCI_IO_PROTOCOL_IO_MEM Read; /// /// Write PCI controller registers in the PCI memory or I/O space. /// EFI_PCI_IO_PROTOCOL_IO_MEM Write; } EFI_PCI_IO_PROTOCOL_ACCESS; /** Enable a PCI driver to access PCI controller registers in PCI configuration space. @param This A pointer to the EFI_PCI_IO_PROTOCOL instance. @param Width Signifies the width of the memory operations. @param Offset The offset within the PCI configuration space for the PCI controller. @param Count The number of PCI configuration operations to perform. @param Buffer For read operations, the destination buffer to store the results. For write operations, the source buffer to write data from. @retval EFI_SUCCESS The data was read from or written to the PCI controller. @retval EFI_UNSUPPORTED The address range specified by Offset, Width, and Count is not valid for the PCI configuration header of the PCI controller. @retval EFI_OUT_OF_RESOURCES The request could not be completed due to a lack of resources. @retval EFI_INVALID_PARAMETER Buffer is NULL or Width is invalid. **/ typedef EFI_STATUS (EFIAPI *EFI_PCI_IO_PROTOCOL_CONFIG)( IN EFI_PCI_IO_PROTOCOL *This, IN EFI_PCI_IO_PROTOCOL_WIDTH Width, IN UINT32 Offset, IN UINTN Count, IN OUT VOID *Buffer ); typedef struct { /// /// Read PCI controller registers in PCI configuration space. /// EFI_PCI_IO_PROTOCOL_CONFIG Read; /// /// Write PCI controller registers in PCI configuration space. /// EFI_PCI_IO_PROTOCOL_CONFIG Write; } EFI_PCI_IO_PROTOCOL_CONFIG_ACCESS; /** Enables a PCI driver to copy one region of PCI memory space to another region of PCI memory space. @param This A pointer to the EFI_PCI_IO_PROTOCOL instance. @param Width Signifies the width of the memory operations. @param DestBarIndex The BAR index in the standard PCI Configuration header to use as the base address for the memory operation to perform. @param DestOffset The destination offset within the BAR specified by DestBarIndex to start the memory writes for the copy operation. @param SrcBarIndex The BAR index in the standard PCI Configuration header to use as the base address for the memory operation to perform. @param SrcOffset The source offset within the BAR specified by SrcBarIndex to start the memory reads for the copy operation. @param Count The number of memory operations to perform. Bytes moved is Width size * Count, starting at DestOffset and SrcOffset. @retval EFI_SUCCESS The data was copied from one memory region to another memory region. @retval EFI_UNSUPPORTED DestBarIndex not valid for this PCI controller. @retval EFI_UNSUPPORTED SrcBarIndex not valid for this PCI controller. @retval EFI_UNSUPPORTED The address range specified by DestOffset, Width, and Count is not valid for the PCI BAR specified by DestBarIndex. @retval EFI_UNSUPPORTED The address range specified by SrcOffset, Width, and Count is not valid for the PCI BAR specified by SrcBarIndex. @retval EFI_INVALID_PARAMETER Width is invalid. @retval EFI_OUT_OF_RESOURCES The request could not be completed due to a lack of resources. **/ typedef EFI_STATUS (EFIAPI *EFI_PCI_IO_PROTOCOL_COPY_MEM)( IN EFI_PCI_IO_PROTOCOL *This, IN EFI_PCI_IO_PROTOCOL_WIDTH Width, IN UINT8 DestBarIndex, IN UINT64 DestOffset, IN UINT8 SrcBarIndex, IN UINT64 SrcOffset, IN UINTN Count ); /** Provides the PCI controller-specific addresses needed to access system memory. @param This A pointer to the EFI_PCI_IO_PROTOCOL instance. @param Operation Indicates if the bus master is going to read or write to system memory. @param HostAddress The system memory address to map to the PCI controller. @param NumberOfBytes On input the number of bytes to map. On output the number of bytes that were mapped. @param DeviceAddress The resulting map address for the bus master PCI controller to use to access the hosts HostAddress. @param Mapping A resulting value to pass to Unmap(). @retval EFI_SUCCESS The range was mapped for the returned NumberOfBytes. @retval EFI_UNSUPPORTED The HostAddress cannot be mapped as a common buffer. @retval EFI_INVALID_PARAMETER One or more parameters are invalid. @retval EFI_OUT_OF_RESOURCES The request could not be completed due to a lack of resources. @retval EFI_DEVICE_ERROR The system hardware could not map the requested address. **/ typedef EFI_STATUS (EFIAPI *EFI_PCI_IO_PROTOCOL_MAP)( IN EFI_PCI_IO_PROTOCOL *This, IN EFI_PCI_IO_PROTOCOL_OPERATION Operation, IN VOID *HostAddress, IN OUT UINTN *NumberOfBytes, OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, OUT VOID **Mapping ); /** Completes the Map() operation and releases any corresponding resources. @param This A pointer to the EFI_PCI_IO_PROTOCOL instance. @param Mapping The mapping value returned from Map(). @retval EFI_SUCCESS The range was unmapped. @retval EFI_DEVICE_ERROR The data was not committed to the target system memory. **/ typedef EFI_STATUS (EFIAPI *EFI_PCI_IO_PROTOCOL_UNMAP)( IN EFI_PCI_IO_PROTOCOL *This, IN VOID *Mapping ); /** Allocates pages that are suitable for an EfiPciIoOperationBusMasterCommonBuffer or EfiPciOperationBusMasterCommonBuffer64 mapping. @param This A pointer to the EFI_PCI_IO_PROTOCOL instance. @param Type This parameter is not used and must be ignored. @param MemoryType The type of memory to allocate, EfiBootServicesData or EfiRuntimeServicesData. @param Pages The number of pages to allocate. @param HostAddress A pointer to store the base system memory address of the allocated range. @param Attributes The requested bit mask of attributes for the allocated range. @retval EFI_SUCCESS The requested memory pages were allocated. @retval EFI_UNSUPPORTED Attributes is unsupported. The only legal attribute bits are MEMORY_WRITE_COMBINE, MEMORY_CACHED and DUAL_ADDRESS_CYCLE. @retval EFI_INVALID_PARAMETER One or more parameters are invalid. @retval EFI_OUT_OF_RESOURCES The memory pages could not be allocated. **/ typedef EFI_STATUS (EFIAPI *EFI_PCI_IO_PROTOCOL_ALLOCATE_BUFFER)( IN EFI_PCI_IO_PROTOCOL *This, IN EFI_ALLOCATE_TYPE Type, IN EFI_MEMORY_TYPE MemoryType, IN UINTN Pages, OUT VOID **HostAddress, IN UINT64 Attributes ); /** Frees memory that was allocated with AllocateBuffer(). @param This A pointer to the EFI_PCI_IO_PROTOCOL instance. @param Pages The number of pages to free. @param HostAddress The base system memory address of the allocated range. @retval EFI_SUCCESS The requested memory pages were freed. @retval EFI_INVALID_PARAMETER The memory range specified by HostAddress and Pages was not allocated with AllocateBuffer(). **/ typedef EFI_STATUS (EFIAPI *EFI_PCI_IO_PROTOCOL_FREE_BUFFER)( IN EFI_PCI_IO_PROTOCOL *This, IN UINTN Pages, IN VOID *HostAddress ); /** Flushes all PCI posted write transactions from a PCI host bridge to system memory. @param This A pointer to the EFI_PCI_IO_PROTOCOL instance. @retval EFI_SUCCESS The PCI posted write transactions were flushed from the PCI host bridge to system memory. @retval EFI_DEVICE_ERROR The PCI posted write transactions were not flushed from the PCI host bridge due to a hardware error. **/ typedef EFI_STATUS (EFIAPI *EFI_PCI_IO_PROTOCOL_FLUSH)( IN EFI_PCI_IO_PROTOCOL *This ); /** Retrieves this PCI controller's current PCI bus number, device number, and function number. @param This A pointer to the EFI_PCI_IO_PROTOCOL instance. @param SegmentNumber The PCI controller's current PCI segment number. @param BusNumber The PCI controller's current PCI bus number. @param DeviceNumber The PCI controller's current PCI device number. @param FunctionNumber The PCI controller's current PCI function number. @retval EFI_SUCCESS The PCI controller location was returned. @retval EFI_INVALID_PARAMETER One or more parameters are invalid. **/ typedef EFI_STATUS (EFIAPI *EFI_PCI_IO_PROTOCOL_GET_LOCATION)( IN EFI_PCI_IO_PROTOCOL *This, OUT UINTN *SegmentNumber, OUT UINTN *BusNumber, OUT UINTN *DeviceNumber, OUT UINTN *FunctionNumber ); /** Performs an operation on the attributes that this PCI controller supports. The operations include getting the set of supported attributes, retrieving the current attributes, setting the current attributes, enabling attributes, and disabling attributes. @param This A pointer to the EFI_PCI_IO_PROTOCOL instance. @param Operation The operation to perform on the attributes for this PCI controller. @param Attributes The mask of attributes that are used for Set, Enable, and Disable operations. @param Result A pointer to the result mask of attributes that are returned for the Get and Supported operations. @retval EFI_SUCCESS The operation on the PCI controller's attributes was completed. @retval EFI_INVALID_PARAMETER One or more parameters are invalid. @retval EFI_UNSUPPORTED one or more of the bits set in Attributes are not supported by this PCI controller or one of its parent bridges when Operation is Set, Enable or Disable. **/ typedef EFI_STATUS (EFIAPI *EFI_PCI_IO_PROTOCOL_ATTRIBUTES)( IN EFI_PCI_IO_PROTOCOL *This, IN EFI_PCI_IO_PROTOCOL_ATTRIBUTE_OPERATION Operation, IN UINT64 Attributes, OUT UINT64 *Result OPTIONAL ); /** Gets the attributes that this PCI controller supports setting on a BAR using SetBarAttributes(), and retrieves the list of resource descriptors for a BAR. @param This A pointer to the EFI_PCI_IO_PROTOCOL instance. @param BarIndex The BAR index of the standard PCI Configuration header to use as the base address for resource range. The legal range for this field is 0..5. @param Supports A pointer to the mask of attributes that this PCI controller supports setting for this BAR with SetBarAttributes(). @param Resources A pointer to the resource descriptors that describe the current configuration of this BAR of the PCI controller. @retval EFI_SUCCESS If Supports is not NULL, then the attributes that the PCI controller supports are returned in Supports. If Resources is not NULL, then the resource descriptors that the PCI controller is currently using are returned in Resources. @retval EFI_INVALID_PARAMETER Both Supports and Attributes are NULL. @retval EFI_UNSUPPORTED BarIndex not valid for this PCI controller. @retval EFI_OUT_OF_RESOURCES There are not enough resources available to allocate Resources. **/ typedef EFI_STATUS (EFIAPI *EFI_PCI_IO_PROTOCOL_GET_BAR_ATTRIBUTES)( IN EFI_PCI_IO_PROTOCOL *This, IN UINT8 BarIndex, OUT UINT64 *Supports, OPTIONAL OUT VOID **Resources OPTIONAL ); /** Sets the attributes for a range of a BAR on a PCI controller. @param This A pointer to the EFI_PCI_IO_PROTOCOL instance. @param Attributes The mask of attributes to set for the resource range specified by BarIndex, Offset, and Length. @param BarIndex The BAR index of the standard PCI Configuration header to use as the base address for resource range. The legal range for this field is 0..5. @param Offset A pointer to the BAR relative base address of the resource range to be modified by the attributes specified by Attributes. @param Length A pointer to the length of the resource range to be modified by the attributes specified by Attributes. @retval EFI_SUCCESS The set of attributes specified by Attributes for the resource range specified by BarIndex, Offset, and Length were set on the PCI controller, and the actual resource range is returned in Offset and Length. @retval EFI_INVALID_PARAMETER Offset or Length is NULL. @retval EFI_UNSUPPORTED BarIndex not valid for this PCI controller. @retval EFI_OUT_OF_RESOURCES There are not enough resources to set the attributes on the resource range specified by BarIndex, Offset, and Length. **/ typedef EFI_STATUS (EFIAPI *EFI_PCI_IO_PROTOCOL_SET_BAR_ATTRIBUTES)( IN EFI_PCI_IO_PROTOCOL *This, IN UINT64 Attributes, IN UINT8 BarIndex, IN OUT UINT64 *Offset, IN OUT UINT64 *Length ); /// /// The EFI_PCI_IO_PROTOCOL provides the basic Memory, I/O, PCI configuration, /// and DMA interfaces used to abstract accesses to PCI controllers. /// There is one EFI_PCI_IO_PROTOCOL instance for each PCI controller on a PCI bus. /// A device driver that wishes to manage a PCI controller in a system will have to /// retrieve the EFI_PCI_IO_PROTOCOL instance that is associated with the PCI controller. /// struct _EFI_PCI_IO_PROTOCOL { EFI_PCI_IO_PROTOCOL_POLL_IO_MEM PollMem; EFI_PCI_IO_PROTOCOL_POLL_IO_MEM PollIo; EFI_PCI_IO_PROTOCOL_ACCESS Mem; EFI_PCI_IO_PROTOCOL_ACCESS Io; EFI_PCI_IO_PROTOCOL_CONFIG_ACCESS Pci; EFI_PCI_IO_PROTOCOL_COPY_MEM CopyMem; EFI_PCI_IO_PROTOCOL_MAP Map; EFI_PCI_IO_PROTOCOL_UNMAP Unmap; EFI_PCI_IO_PROTOCOL_ALLOCATE_BUFFER AllocateBuffer; EFI_PCI_IO_PROTOCOL_FREE_BUFFER FreeBuffer; EFI_PCI_IO_PROTOCOL_FLUSH Flush; EFI_PCI_IO_PROTOCOL_GET_LOCATION GetLocation; EFI_PCI_IO_PROTOCOL_ATTRIBUTES Attributes; EFI_PCI_IO_PROTOCOL_GET_BAR_ATTRIBUTES GetBarAttributes; EFI_PCI_IO_PROTOCOL_SET_BAR_ATTRIBUTES SetBarAttributes; /// /// The size, in bytes, of the ROM image. /// UINT64 RomSize; /// /// A pointer to the in memory copy of the ROM image. The PCI Bus Driver is responsible /// for allocating memory for the ROM image, and copying the contents of the ROM to memory. /// The contents of this buffer are either from the PCI option ROM that can be accessed /// through the ROM BAR of the PCI controller, or it is from a platform-specific location. /// The Attributes() function can be used to determine from which of these two sources /// the RomImage buffer was initialized. /// VOID *RomImage; }; extern EFI_GUID gEfiPciIoProtocolGuid; #endif
e9596c26446e6634d9af8887b4b71a2bd6825a36
3cd3872acbc8b1a79a70b89b2fd58a171e7adc82
/vp8/common/arm/loopfilter_arm.c
48a19720483d8f1c29d7a91042ca790cd6e0e31b
[]
permissive
webmproject/libvpx
58ab97861063cb521ec0d00ef9cb222ca97873b1
6fd360c684736e351160b131827dfbb207841164
refs/heads/main
2023-04-09T15:32:34.688724
2023-04-07T22:19:18
2023-04-07T22:19:18
22,927,608
889
376
BSD-3-Clause
2023-03-24T13:37:34
2014-08-13T19:03:21
C
UTF-8
C
false
false
3,581
c
loopfilter_arm.c
/* * Copyright (c) 2010 The WebM project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "./vpx_config.h" #include "./vp8_rtcd.h" #include "vp8/common/arm/loopfilter_arm.h" #include "vp8/common/loopfilter.h" #include "vp8/common/onyxc_int.h" /* NEON loopfilter functions */ /* Horizontal MB filtering */ void vp8_loop_filter_mbh_neon(unsigned char *y_ptr, unsigned char *u_ptr, unsigned char *v_ptr, int y_stride, int uv_stride, loop_filter_info *lfi) { unsigned char mblim = *lfi->mblim; unsigned char lim = *lfi->lim; unsigned char hev_thr = *lfi->hev_thr; vp8_mbloop_filter_horizontal_edge_y_neon(y_ptr, y_stride, mblim, lim, hev_thr); if (u_ptr) vp8_mbloop_filter_horizontal_edge_uv_neon(u_ptr, uv_stride, mblim, lim, hev_thr, v_ptr); } /* Vertical MB Filtering */ void vp8_loop_filter_mbv_neon(unsigned char *y_ptr, unsigned char *u_ptr, unsigned char *v_ptr, int y_stride, int uv_stride, loop_filter_info *lfi) { unsigned char mblim = *lfi->mblim; unsigned char lim = *lfi->lim; unsigned char hev_thr = *lfi->hev_thr; vp8_mbloop_filter_vertical_edge_y_neon(y_ptr, y_stride, mblim, lim, hev_thr); if (u_ptr) vp8_mbloop_filter_vertical_edge_uv_neon(u_ptr, uv_stride, mblim, lim, hev_thr, v_ptr); } /* Horizontal B Filtering */ void vp8_loop_filter_bh_neon(unsigned char *y_ptr, unsigned char *u_ptr, unsigned char *v_ptr, int y_stride, int uv_stride, loop_filter_info *lfi) { unsigned char blim = *lfi->blim; unsigned char lim = *lfi->lim; unsigned char hev_thr = *lfi->hev_thr; vp8_loop_filter_horizontal_edge_y_neon(y_ptr + 4 * y_stride, y_stride, blim, lim, hev_thr); vp8_loop_filter_horizontal_edge_y_neon(y_ptr + 8 * y_stride, y_stride, blim, lim, hev_thr); vp8_loop_filter_horizontal_edge_y_neon(y_ptr + 12 * y_stride, y_stride, blim, lim, hev_thr); if (u_ptr) vp8_loop_filter_horizontal_edge_uv_neon(u_ptr + 4 * uv_stride, uv_stride, blim, lim, hev_thr, v_ptr + 4 * uv_stride); } /* Vertical B Filtering */ void vp8_loop_filter_bv_neon(unsigned char *y_ptr, unsigned char *u_ptr, unsigned char *v_ptr, int y_stride, int uv_stride, loop_filter_info *lfi) { unsigned char blim = *lfi->blim; unsigned char lim = *lfi->lim; unsigned char hev_thr = *lfi->hev_thr; vp8_loop_filter_vertical_edge_y_neon(y_ptr + 4, y_stride, blim, lim, hev_thr); vp8_loop_filter_vertical_edge_y_neon(y_ptr + 8, y_stride, blim, lim, hev_thr); vp8_loop_filter_vertical_edge_y_neon(y_ptr + 12, y_stride, blim, lim, hev_thr); if (u_ptr) vp8_loop_filter_vertical_edge_uv_neon(u_ptr + 4, uv_stride, blim, lim, hev_thr, v_ptr + 4); }
70ee1b08a587e17c20db51219814b3ecde42b9bf
e72db16e9747386afd01edd1dd36d9589a3f71ef
/src/test/tools/pmemdetect/pmemdetect.c
884c30075d577abaf203b42a6e2b58a443736319
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
pmem/pmdk
5e49feee8017574340db2a0f9b4e2eab99f8581c
ccadb16227bddea1bdcc518bd8f298d551b2baad
refs/heads/master
2023-08-31T02:28:06.884934
2023-08-30T14:52:25
2023-08-30T14:52:25
23,637,153
1,017
402
NOASSERTION
2023-09-07T11:52:42
2014-09-03T20:55:23
C
UTF-8
C
false
false
6,291
c
pmemdetect.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2016-2023, Intel Corporation */ /* * pmemdetect.c -- detect PMEM/Device DAX device or Device DAX alignment */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <getopt.h> #include <errno.h> #include "mmap.h" #include "libpmem.h" #include "file.h" #include "os.h" #include "util.h" #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <fcntl.h> #include <unistd.h> #define SIZE 4096 #define DEVDAX_DETECT (1 << 0) #define DEVDAX_ALIGN (1 << 1) #define MAP_SYNC_SUPP (1 << 2) #define DAX_REGION_DETECT (1 << 3) #define FILE_SIZE (1 << 4) #define err(fmt, ...) fprintf(stderr, "pmemdetect: " fmt, __VA_ARGS__) /* arguments */ static int Opts; static char *Path; static size_t Align; /* * print_usage -- print short description of usage */ static void print_usage(void) { printf("Usage: pmemdetect [options] <path>\n"); printf("Valid options:\n"); printf("-d, --devdax - check if <path> is Device DAX\n"); printf("-a, --align=N - check Device DAX alignment\n"); printf("-r, --dax-region - check if Dev DAX <path> has region id\n"); printf("-s, --map-sync - check if <path> supports MAP_SYNC\n"); printf("-z, --size - print file/Device DAX size\n"); printf("-h, --help - print this usage info\n"); } /* * long_options -- command line options */ static const struct option long_options[] = { {"devdax", no_argument, NULL, 'd'}, {"align", required_argument, NULL, 'a'}, {"dax-region", no_argument, NULL, 'r'}, {"map-sync", no_argument, NULL, 's'}, {"size", no_argument, NULL, 'z'}, {"help", no_argument, NULL, 'h'}, {NULL, 0, NULL, 0 }, }; /* * parse_args -- (internal) parse command line arguments */ static int parse_args(int argc, char *argv[]) { int opt; while ((opt = getopt_long(argc, argv, "a:dshrz", long_options, NULL)) != -1) { switch (opt) { case 'd': Opts |= DEVDAX_DETECT; break; case 'r': Opts |= DAX_REGION_DETECT; break; case 'a': Opts |= DEVDAX_ALIGN; char *endptr; errno = 0; size_t align = strtoull(optarg, &endptr, 0); if ((endptr && *endptr != '\0') || errno) { err("'%s' -- invalid alignment", optarg); return -1; } Align = align; break; case 's': Opts |= MAP_SYNC_SUPP; break; case 'z': Opts |= FILE_SIZE; break; case 'h': print_usage(); exit(EXIT_SUCCESS); default: print_usage(); exit(EXIT_FAILURE); } } if (optind < argc) { Path = argv[optind]; } else { print_usage(); exit(EXIT_FAILURE); } return 0; } /* * get_params -- get parameters for pmem_map_file */ static int get_params(const char *path, int *flags, size_t *size) { int ret; os_stat_t buf; ret = os_stat(path, &buf); if (ret && errno != ENOENT) { /* error other than no such file */ perror(path); return -1; } if (ret) { /* no such file */ *flags = PMEM_FILE_CREATE; *size = SIZE; } else if (S_ISDIR(buf.st_mode)) { *flags = PMEM_FILE_CREATE | PMEM_FILE_TMPFILE; *size = SIZE; } else { /* file exist */ *size = 0; *flags = 0; } return 0; } /* * is_pmem -- checks if given path points to pmem-aware filesystem */ static int is_pmem(const char *path) { int ret; int flags; size_t size; ret = get_params(path, &flags, &size); if (ret) return ret; int is_pmem; void *addr = pmem_map_file(path, size, flags, 0, &size, &is_pmem); if (addr == NULL) { perror("pmem_map_file failed"); return -1; } pmem_unmap(addr, size); return is_pmem; } /* * is_dev_dax -- checks if given path points to Device DAX */ static int is_dev_dax(const char *path) { enum file_type type = util_file_get_type(path); if (type < 0) { printf("%s -- not accessible\n", path); return -1; } if (os_access(path, W_OK|R_OK)) { printf("%s -- permission denied\n", path); return -1; } if (type == TYPE_DEVDAX) return 1; printf("%s -- not device dax\n", path); return 0; } /* * is_dev_dax_align -- checks if Device DAX alignment is as specified */ static int is_dev_dax_align(const char *path, size_t req_align) { if (is_dev_dax(path) != 1) return -1; size_t align = util_file_device_dax_alignment(path); return (req_align == align) ? 1 : 0; } /* * supports_map_sync -- checks if MAP_SYNC is supported on a filesystem * from given path */ static int supports_map_sync(const char *path) { int ret; int flags; size_t size; ret = get_params(path, &flags, &size); if (ret) return ret; int fd; if (flags & PMEM_FILE_TMPFILE) fd = util_tmpfile(path, "/pmemdetect.XXXXXX", 0); else if (flags & PMEM_FILE_CREATE) fd = os_open(path, O_CREAT|O_RDWR, S_IWUSR|S_IRUSR); else fd = os_open(path, O_RDWR); if (fd < 0) { perror(path); return -1; } if (flags & PMEM_FILE_CREATE) { ret = os_ftruncate(fd, (off_t)size); if (ret) { perror(path); os_close(fd); return -1; } } void *addr = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_SYNC|MAP_SHARED_VALIDATE, fd, 0); if (addr != MAP_FAILED) { ret = 1; } else if (addr == MAP_FAILED && (errno == EOPNOTSUPP || errno == EINVAL)) { ret = 0; } else { err("mmap: %s\n", strerror(errno)); ret = -1; } os_close(fd); if (flags & PMEM_FILE_CREATE && !(flags & PMEM_FILE_TMPFILE)) util_unlink(path); return ret; } int main(int argc, char *argv[]) { int ret; if (parse_args(argc, argv)) { ret = 2; goto out; } util_init(); util_mmap_init(); if (Opts & DEVDAX_DETECT) ret = is_dev_dax(Path); else if (Opts & DAX_REGION_DETECT) { unsigned region_id; ret = util_ddax_region_find(Path, &region_id); if (ret < 0) { printf("Sysfs id file for dax_region is not supported:" " %s\n", Path); ret = 0; } else { ret = 1; } } else if (Opts & DEVDAX_ALIGN) { ret = is_dev_dax_align(Path, Align); } else if (Opts & FILE_SIZE) { printf("%zu", (size_t)util_file_get_size(Path)); ret = 1; } else if (Opts & MAP_SYNC_SUPP) { ret = supports_map_sync(Path); } else { ret = is_pmem(Path); } /* * Return 0 on 'true'. Otherwise return 1. * If any problem occurred return 2. */ switch (ret) { case 0: ret = 1; break; case 1: ret = 0; break; default: ret = 2; break; } util_mmap_fini(); out: return ret; }
6840ff3f765dbe5afca07ae0f507bcb3d5ce5c87
ea8fc70c7dbf49059431fa45a940742736c68fb8
/ext/acl/resourceinterface.c
bb368854b0562f18b4b6a8313245340d2c87c744
[ "BSD-3-Clause" ]
permissive
dreamsxin/cphalcon7
1bd2194a251657b48857326927db69fef617ab91
1b8c6b04b4ca237a5ead87d4752df0d2e85c7a9d
refs/heads/master
2023-03-08T04:53:08.829432
2022-07-07T07:48:59
2022-07-07T07:48:59
47,245,335
298
73
null
2021-06-22T11:53:25
2015-12-02T07:44:43
C
UTF-8
C
false
false
2,099
c
resourceinterface.c
/* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2014 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to license@phalconphp.com so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: Andres Gutierrez <andres@phalconphp.com> | | Eduar Carvajal <eduar@phalconphp.com> | +------------------------------------------------------------------------+ */ #include "acl/resourceinterface.h" #include "kernel/main.h" zend_class_entry *phalcon_acl_resourceinterface_ce; static const zend_function_entry phalcon_acl_resourceinterface_method_entry[] = { PHP_ABSTRACT_ME(Phalcon_Acl_ResourceInterface, getName, arginfo_phalcon_acl_resourceinterface_getname) PHP_ABSTRACT_ME(Phalcon_Acl_ResourceInterface, getDescription, arginfo_phalcon_acl_resourceinterface_getdescription) PHP_FE_END }; /** * Phalcon\Acl\ResourceInterface initializer */ PHALCON_INIT_CLASS(Phalcon_Acl_ResourceInterface){ PHALCON_REGISTER_INTERFACE(Phalcon\\Acl, ResourceInterface, acl_resourceinterface, phalcon_acl_resourceinterface_method_entry); return SUCCESS; } /** * Returns the resource name * * @return string */ PHALCON_DOC_METHOD(Phalcon_Acl_ResourceInterface, getName); /** * Returns resource description * * @return string */ PHALCON_DOC_METHOD(Phalcon_Acl_ResourceInterface, getDescription);
b9c5f6138c34a127835c382967717b056ef338a5
d5fa3a8417ef72029ebe1a714204b4d80afa07b0
/appendixB/kernel/system/do_sigsend.c
35f38e52098cb36a0a5bc1d008b6045d9c5f3e8e
[]
no_license
wuzhouhui/misc
e9eeaa16ce21341db0e075a369edc45af4a89aae
465c679b10b9766985a510df26d3e6a549cfa421
refs/heads/master
2023-01-07T00:45:02.721093
2022-12-30T07:27:37
2022-12-30T07:27:37
48,721,582
1,287
494
null
null
null
null
UTF-8
C
false
false
3,113
c
do_sigsend.c
/* The kernel call that is implemented in this file: * m_type: SYS_SIGSEND * * The parameters for this kernel call are: * m2_i1: SIG_PROC # process to call signal handler * m2_p1: SIG_CTXT_PTR # pointer to sigcontext structure * m2_i3: SIG_FLAGS # flags for S_SIGRETURN call * */ /* * 该文件实现的系统调用: * m_type: SYS_SIGSEND * * 该系统调用的参数包括: * m2_i1: SIG_PROC 调用信号处理函数的进程号 * m2_p1: SIG_CTXT_PTR 指向 sigcontext 结构的指针 * m2_i3: SIG_FLAGS 调用 S_SIGRETURN 的标志 */ #include "../system.h" #include <signal.h> #include <string.h> #include <sys/sigcontext.h> #if USE_SIGSEND /*===========================================================================* * do_sigsend * *===========================================================================*/ PUBLIC int do_sigsend(m_ptr) message *m_ptr; /* pointer to request message */ { /* Handle sys_sigsend, POSIX-style signal handling. */ /* 处理 sys_sigsend, POSIX 风格的信号处理 */ struct sigmsg smsg; register struct proc *rp; phys_bytes src_phys, dst_phys; struct sigcontext sc, *scp; struct sigframe fr, *frp; if (! isokprocn(m_ptr->SIG_PROC)) return(EINVAL); if (iskerneln(m_ptr->SIG_PROC)) return(EPERM); rp = proc_addr(m_ptr->SIG_PROC); /* Get the sigmsg structure into our address space. */ src_phys = umap_local(proc_addr(PM_PROC_NR), D, (vir_bytes) m_ptr->SIG_CTXT_PTR, (vir_bytes) sizeof(struct sigmsg)); if (src_phys == 0) return(EFAULT); phys_copy(src_phys,vir2phys(&smsg),(phys_bytes) sizeof(struct sigmsg)); /* Compute the user stack pointer where sigcontext will be stored. */ // why minus 1 ??? scp = (struct sigcontext *) smsg.sm_stkptr - 1; /* Copy the registers to the sigcontext structure. */ memcpy(&sc.sc_regs, (char *) &rp->p_reg, sizeof(struct sigregs)); /* Finish the sigcontext initialization. */ sc.sc_flags = SC_SIGCONTEXT; sc.sc_mask = smsg.sm_mask; /* Copy the sigcontext structure to the user's stack. */ dst_phys = umap_local(rp, D, (vir_bytes) scp, (vir_bytes) sizeof(struct sigcontext)); if (dst_phys == 0) return(EFAULT); phys_copy(vir2phys(&sc), dst_phys, (phys_bytes) sizeof(struct sigcontext)); /* Initialize the sigframe structure. */ frp = (struct sigframe *) scp - 1; fr.sf_scpcopy = scp; fr.sf_retadr2= (void (*)()) rp->p_reg.pc; fr.sf_fp = rp->p_reg.fp; rp->p_reg.fp = (reg_t) &frp->sf_fp; fr.sf_scp = scp; fr.sf_code = 0; /* XXX - should be used for type of FP exception */ fr.sf_signo = smsg.sm_signo; fr.sf_retadr = (void (*)()) smsg.sm_sigreturn; /* Copy the sigframe structure to the user's stack. */ dst_phys = umap_local(rp, D, (vir_bytes) frp, (vir_bytes) sizeof(struct sigframe)); if (dst_phys == 0) return(EFAULT); phys_copy(vir2phys(&fr), dst_phys, (phys_bytes) sizeof(struct sigframe)); /* Reset user registers to execute the signal handler. */ rp->p_reg.sp = (reg_t) frp; rp->p_reg.pc = (reg_t) smsg.sm_sighandler; return(OK); } #endif /* USE_SIGSEND */
8fed0070b66b3e9d3b46329922eb229569ea1a2d
99bdb3251fecee538e0630f15f6574054dfc1468
/bsp/allwinner/libraries/sunxi-hal/hal/source/usb/manager/usb_hw_scan.c
01c68125f47e5d4c48d4194590924770906fb6f4
[ "Zlib", "LicenseRef-scancode-proprietary-license", "MIT", "BSD-3-Clause", "X11", "BSD-4-Clause-UC", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
RT-Thread/rt-thread
03a7c52c2aeb1b06a544143b0e803d72f47d1ece
3602f891211904a27dcbd51e5ba72fefce7326b2
refs/heads/master
2023-09-01T04:10:20.295801
2023-08-31T16:20:55
2023-08-31T16:20:55
7,408,108
9,599
5,805
Apache-2.0
2023-09-14T13:37:26
2013-01-02T14:49:21
C
UTF-8
C
false
false
11,927
c
usb_hw_scan.c
// #include <sunxi_drv_gpio.h> #include <stddef.h> #include <typedef.h> #include <hal_gpio.h> #include "usb_hw_scan.h" #include "usb_msg_center.h" #include "usb_manager_common.h" #undef x_set_bit #define x_set_bit(value, bit) ((value) |= (1U << (bit))) /* clear bit */ #undef x_clear_bit #define x_clear_bit(value, bit) ((value) &= ~(1U << (bit))) static int device_insmod_delay; static struct usb_scan_info g_usb_scan_info; static void (*__usb_hw_scan)(struct usb_scan_info *); extern int thread_suspend_flag; static unsigned int PIODataIn_debounce(usb_gpio_t *usb_gpio, gpio_data_t *value) { unsigned int retry = 0; unsigned int time = 10; unsigned int temp1 = 0; unsigned int cnt = 0; unsigned int change = 0; /* if have shake */ /** * try 10 times, if value is the same, * then current read is valid; otherwise invalid. */ if (usb_gpio->valid) { retry = time; while (retry--) { hal_gpio_get_data(usb_gpio->gpio_set.gpio, (gpio_data_t *)&temp1); if (temp1) { cnt++; } } /* 10 times, the value is all 0 or 1 */ if ((cnt == time) || (cnt == 0)) { change = 0; } else { change = 1; } } else { change = 1; } if (!change) { *value = temp1; } Usb_Manager_Debug("usb_gpio->valid = %x, cnt = %x, change= %d, temp1 = %x\n", usb_gpio->valid, cnt, change, temp1); return change; } static u32 get_id_state(struct usb_scan_info *info) { enum usb_id_state id_state = USB_DEVICE_MODE; gpio_data_t pin_data = 0; if (!PIODataIn_debounce((usb_gpio_t *)&info->cfg->port.id, &pin_data)) { Usb_Manager_Debug("%s pin_data:%d\n", KEY_USB_ID_GPIO, pin_data); if (pin_data) { id_state = USB_DEVICE_MODE; } else { id_state = USB_HOST_MODE; } info->id_old_state = id_state; } else { id_state = info->id_old_state; } Usb_Manager_Debug("%s id_state:%d\n", KEY_USB_ID_GPIO, id_state); Usb_Manager_Debug("%s id_old_state:%d\n", KEY_USB_ID_GPIO, info->id_old_state); return id_state; } static u32 get_detect_vbus_state(struct usb_scan_info *info) { enum usb_det_vbus_state det_vbus_state = USB_DET_VBUS_INVALID; gpio_data_t pin_data = 0; if (!PIODataIn_debounce((usb_gpio_t *)&info->cfg->port.det_vbus, &pin_data)) { Usb_Manager_Debug("%s pin_data:%d\n", KEY_USB_DETVBUS_GPIO, pin_data); if (pin_data) { det_vbus_state = USB_DET_VBUS_VALID; } else { det_vbus_state = USB_DET_VBUS_INVALID; } info->det_vbus_old_state = det_vbus_state; } else { det_vbus_state = info->det_vbus_old_state; } Usb_Manager_Debug("%s id_state:%d\n", KEY_USB_DETVBUS_GPIO, det_vbus_state); Usb_Manager_Debug("%s id_old_state:%d\n", KEY_USB_DETVBUS_GPIO, info->det_vbus_old_state); return det_vbus_state; } static u32 get_dp_dm_status(struct usb_scan_info *info) { u32 ret = 0; // u32 ret0 = 0; // u32 ret1 = 0; // u32 ret2 = 0; // ret0 = get_dp_dm_status_normal(); // ret1 = get_dp_dm_status_normal(); // ret2 = get_dp_dm_status_normal(); // /* continuous 3 times, to avoid the voltage sudden changes */ // if ((ret0 == ret1) && (ret0 == ret2)) { // ret = ret0; // } else if (ret2 == 0x11) { // if (get_usb_role() == USB_ROLE_DEVICE) { // ret = 0x11; // DMSG_PANIC("ERR: dp/dm status is continuous(0x11)\n"); // } // } else { // ret = ret2; // } return ret; } static void do_switch_to_null(struct usb_scan_info *info) { enum usb_role role = USB_ROLE_NULL; role = get_usb_role(); device_insmod_delay = 0; info->host_insmod_delay = 0; Usb_Manager_Debug("role:%d\n", role); switch (role) { case USB_ROLE_NULL: /* nothing to do */ break; case USB_ROLE_HOST: if (thread_suspend_flag) break; hw_rmmod_usb_host(); break; case USB_ROLE_DEVICE: if (thread_suspend_flag) break; hw_rmmod_usb_device(); break; default: Usb_Manager_Err("unknown usb role(%d)\n", role); } } static void do_switch_to_host(struct usb_scan_info *info) { enum usb_role role = USB_ROLE_NULL; role = get_usb_role(); device_insmod_delay = 0; Usb_Manager_Debug("role:%d\n", role); switch (role) { case USB_ROLE_NULL: if (info->cfg->port.detect_mode == USB_DETECT_MODE_THREAD) { if (thread_suspend_flag) break; /* delay for vbus is stably */ if (info->host_insmod_delay < USB_SCAN_INSMOD_HOST_DRIVER_DELAY) { info->host_insmod_delay++; break; } info->host_insmod_delay = 0; } hw_insmod_usb_host(); break; case USB_ROLE_HOST: /* nothing to do */ break; case USB_ROLE_DEVICE: if (info->cfg->port.detect_mode == USB_DETECT_MODE_THREAD) { if (thread_suspend_flag) break; } hw_rmmod_usb_device(); break; default: Usb_Manager_Err("unknown usb role(%d)\n", role); } } static void do_switch_to_device(struct usb_scan_info *info) { enum usb_role role = USB_ROLE_NULL; role = get_usb_role(); info->host_insmod_delay = 0; Usb_Manager_Debug("role:%d\n", role); switch (role) { case USB_ROLE_NULL: if (info->cfg->port.detect_mode == USB_DETECT_MODE_THREAD) { if (get_dp_dm_status(info) == 0x00) { if (thread_suspend_flag) break; /* delay for vbus is stably */ if (device_insmod_delay < USB_SCAN_INSMOD_DEVICE_DRIVER_DELAY) { device_insmod_delay++; break; } device_insmod_delay = 0; } } hw_insmod_usb_device(); break; case USB_ROLE_HOST: if (info->cfg->port.detect_mode == USB_DETECT_MODE_THREAD) { if (thread_suspend_flag) break; hw_rmmod_usb_host(); } hw_rmmod_usb_host(); break; case USB_ROLE_DEVICE: /* nothing to do */ break; default: Usb_Manager_Err("unknown usb role(%d)\n", role); } } static unsigned int get_vbus_id_state(struct usb_scan_info *info) { u32 state = 0; if (get_id_state(info) == USB_DEVICE_MODE) { x_set_bit(state, 0); } if (get_detect_vbus_state(info) == USB_DET_VBUS_VALID) { x_set_bit(state, 1); } return state; } static void vbus_id_hw_scan(struct usb_scan_info *info) { unsigned int vbus_id_state = 0; vbus_id_state = get_vbus_id_state(info); switch (vbus_id_state) { case 0x00: case 0x02: do_switch_to_host(info); break; case 0x01: // do_switch_to_null(info); // break; case 0x03: do_switch_to_device(info); break; default: Usb_Manager_Err("vbus_id_hw_scan: "); Usb_Manager_Err("unknown vbus_id_state(0x%x)\n", vbus_id_state); } } static void null_hw_scan(struct usb_scan_info *info) { Usb_Manager_Debug("null_hw_scan\n"); } void usb_hw_scan(struct usb_cfg *cfg) { __usb_hw_scan(&g_usb_scan_info); } int usb_hw_scan_init(usb_cfg_t *cfg) { int ret = 0; struct usb_port_info *port_info = NULL; struct usb_scan_info *scan_info = &g_usb_scan_info; memset(scan_info, 0, sizeof(struct usb_scan_info)); scan_info->cfg = cfg; scan_info->id_old_state = USB_DEVICE_MODE; scan_info->det_vbus_old_state = USB_DET_VBUS_INVALID; device_insmod_delay = 0; port_info = (struct usb_port_info *)&cfg->port; Usb_Manager_Debug("port_info->port.port_type:%d\n", port_info->port_type); switch (port_info->port_type) { case USB_PORT_TYPE_DEVICE: case USB_PORT_TYPE_HOST: __usb_hw_scan = null_hw_scan; break; case USB_PORT_TYPE_OTG: { if (port_info->detect_type == USB_DETECT_TYPE_VBUS_ID) { Usb_Manager_Debug("set %s mul_sel:%d\n", KEY_USB_ID_GPIO, port_info->id.gpio_set.mul_sel); Usb_Manager_Debug("set %s drv_level:%d\n", KEY_USB_ID_GPIO, port_info->id.gpio_set.drv_level); Usb_Manager_Debug("set %s pull:%d\n", KEY_USB_ID_GPIO, port_info->id.gpio_set.pull); Usb_Manager_Debug("set %s data:%d\n", KEY_USB_ID_GPIO, port_info->id.gpio_set.data); hal_gpio_pinmux_set_function(port_info->id.gpio_set.gpio, port_info->id.gpio_set.mul_sel); hal_gpio_set_driving_level(port_info->id.gpio_set.gpio, port_info->id.gpio_set.drv_level); hal_gpio_set_pull(port_info->id.gpio_set.gpio, port_info->id.gpio_set.pull); hal_gpio_set_data(port_info->id.gpio_set.gpio, port_info->id.gpio_set.data); Usb_Manager_Debug("set %s mul_sel:%d\n", KEY_USB_DETVBUS_GPIO, port_info->det_vbus.gpio_set.mul_sel); Usb_Manager_Debug("set %s drv_level:%d\n", KEY_USB_DETVBUS_GPIO, port_info->det_vbus.gpio_set.drv_level); Usb_Manager_Debug("set %s pull:%d\n", KEY_USB_DETVBUS_GPIO, port_info->det_vbus.gpio_set.pull); Usb_Manager_Debug("set %s data:%d\n", KEY_USB_DETVBUS_GPIO, port_info->det_vbus.gpio_set.data); hal_gpio_pinmux_set_function(port_info->det_vbus.gpio_set.gpio, port_info->det_vbus.gpio_set.mul_sel); hal_gpio_set_driving_level(port_info->det_vbus.gpio_set.gpio, port_info->det_vbus.gpio_set.drv_level); hal_gpio_set_pull(port_info->det_vbus.gpio_set.gpio, port_info->det_vbus.gpio_set.pull); hal_gpio_set_data(port_info->id.gpio_set.gpio, port_info->det_vbus.gpio_set.data); Usb_Manager_Debug("set %s mul_sel:%d\n", KEY_USB_DRVVBUS_GPIO, port_info->drv_vbus.gpio_set.mul_sel); Usb_Manager_Debug("set %s drv_level:%d\n", KEY_USB_DRVVBUS_GPIO, port_info->drv_vbus.gpio_set.drv_level); Usb_Manager_Debug("set %s pull:%d\n", KEY_USB_DRVVBUS_GPIO, port_info->drv_vbus.gpio_set.pull); Usb_Manager_Debug("set %s data:%d\n", KEY_USB_DRVVBUS_GPIO, port_info->drv_vbus.gpio_set.data); hal_gpio_pinmux_set_function(port_info->drv_vbus.gpio_set.gpio, port_info->drv_vbus.gpio_set.mul_sel); hal_gpio_set_driving_level(port_info->drv_vbus.gpio_set.gpio, port_info->drv_vbus.gpio_set.drv_level); hal_gpio_set_pull(port_info->drv_vbus.gpio_set.gpio, port_info->drv_vbus.gpio_set.pull); hal_gpio_set_data(port_info->drv_vbus.gpio_set.gpio, port_info->drv_vbus.gpio_set.data); } else { Usb_Manager_Err("detect_type(%d) can't support\n", port_info->port_type); } __usb_hw_scan = vbus_id_hw_scan; } break; default: Usb_Manager_Err("unknown port_type(%d)\n", port_info->port_type); ret = -1; goto failed; } return 0; failed: __usb_hw_scan = null_hw_scan; return ret; }
99e4bccb8fad9c38300c95506e127269495b2dd3
2c052c996d4267623276a681308bf87ea7388f60
/src/kernel/clock.c
f77fc563b329a6412a14c88155daaf96fae782ac
[ "Apache-2.0" ]
permissive
nanovms/nanos
17d3ce113b63c4370e40d291b8fd8fb9d943c02d
9085e091e5250fc58bf036591c8959e05fd7957f
refs/heads/master
2023-08-25T16:49:14.521701
2023-08-25T14:00:54
2023-08-25T14:14:13
115,159,616
2,055
131
Apache-2.0
2023-09-14T17:16:19
2017-12-23T00:25:34
C
UTF-8
C
false
false
2,938
c
clock.c
#include <kernel.h> //#define CLOCK_DEBUG #ifdef CLOCK_DEBUG #define clock_debug(x, ...) do {tprintf(sym(clock), 0, x, ##__VA_ARGS__);} while(0) #else #define clock_debug(x, ...) #endif extern void notify_unix_timers_of_rtc_change(void); /* These should happen in pairs such that odd indicates update in-progress */ #define vdso_update_gen() fetch_and_add((word *)&__vdso_dat->vdso_gen, 1) void kernel_delay(timestamp delta) { timestamp end = now(CLOCK_ID_MONOTONIC) + delta; while (now(CLOCK_ID_MONOTONIC) < end) kern_pause(); } timestamp kern_now(clock_id id) { return now(id); } void clock_update_last_raw(timestamp t) { /* Periodically update last_raw to avoid numerical errors from big intervals */ if (__vdso_dat->base_freq && (t - __vdso_dat->last_raw > (CLOCK_RAW_UPDATE_SECONDS<<CLOCK_FP_BITS))) { vdso_update_gen(); __vdso_dat->rtc_offset += ((s64)(t - __vdso_dat->last_raw) * __vdso_dat->base_freq) >> CLOCK_FP_BITS; __vdso_dat->last_raw = t; vdso_update_gen(); } } void clock_set_freq(s64 freq) { timestamp here = now(CLOCK_ID_MONOTONIC_RAW); vdso_update_gen(); __vdso_dat->rtc_offset += ((s64)(here - __vdso_dat->last_raw) * __vdso_dat->base_freq) >> CLOCK_FP_BITS; __vdso_dat->base_freq = freq; __vdso_dat->last_raw = here; vdso_update_gen(); timer_reorder(kernel_timers); } void clock_set_slew(s64 slewfreq, timestamp start, u64 duration) { vdso_update_gen(); __vdso_dat->slew_freq = slewfreq; __vdso_dat->slew_start = start; __vdso_dat->slew_end = start + duration; vdso_update_gen(); timer_reorder(kernel_timers); } closure_function(1, 1, boolean, timer_adjust_handler, s64, amt, void *, v) { timer t = v; if (t->absolute) return true; switch (t->id) { case CLOCK_ID_REALTIME: case CLOCK_ID_REALTIME_COARSE: case CLOCK_ID_REALTIME_ALARM: t->expiry += bound(amt); break; default: break; } return true; } void clock_step_rtc(s64 step) { timer_adjust_begin(kernel_timers); vdso_update_gen(); __vdso_dat->rtc_offset += step; vdso_update_gen(); timer_adjust_end(kernel_timers, stack_closure(timer_adjust_handler, step)); rtc_settimeofday(sec_from_timestamp(now(CLOCK_ID_REALTIME))); notify_unix_timers_of_rtc_change(); } void clock_reset_rtc(timestamp wallclock_now) { clock_debug("%s: now %T, wallclock_now %T\n", __func__, now(CLOCK_ID_REALTIME), wallclock_now); timestamp n = now(CLOCK_ID_REALTIME); rtc_settimeofday(sec_from_timestamp(wallclock_now)); notify_unix_timers_of_rtc_change(); timer_adjust_begin(kernel_timers); __vdso_dat->rtc_offset = wallclock_now - now(CLOCK_ID_MONOTONIC_RAW); reset_clock_vdso_dat(); timer_adjust_end(kernel_timers, stack_closure(timer_adjust_handler, wallclock_now - n)); }
5bacdb55daebee1b37d114d11e421cfab83e3a05
1efb2283837c9b70bc6449cec877799e4efa3268
/test/mpi/rma/transpose7.c
6af8d2d3317eceb48656ac8f6869ef11d7112ab3
[ "mpich2" ]
permissive
pmodels/mpich
d2392e8e30536cad3e500c16aa1e71211101d83f
2d265f9f5f93ebdd07ad547423bc6212868262a4
refs/heads/main
2023-09-04T05:50:15.041823
2023-09-01T23:07:33
2023-09-01T23:07:33
70,918,679
506
313
NOASSERTION
2023-09-14T14:38:36
2016-10-14T14:39:42
C
UTF-8
C
false
false
2,903
c
transpose7.c
/* * Copyright (C) by Argonne National Laboratory * See COPYRIGHT in top-level directory */ #include "mpi.h" #include <stdio.h> #include <stdlib.h> #include "mpitest.h" /* This does a transpose with a get operation, fence, and derived datatypes. Uses vector and hvector (Example 3.32 from MPI 1.1 Standard). Run on 2 processes */ #define NROWS 1000 #define NCOLS 1000 int main(int argc, char *argv[]) { int rank, nprocs, **A, *A_data, i, j; MPI_Comm CommDeuce; MPI_Win win; MPI_Datatype column, xpose; int errs = 0; MTest_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &nprocs); MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (nprocs < 2) { printf("Run this program with 2 or more processes\n"); MPI_Abort(MPI_COMM_WORLD, 1); } MPI_Comm_split(MPI_COMM_WORLD, (rank < 2), rank, &CommDeuce); if (rank < 2) { A_data = (int *) malloc(NROWS * NCOLS * sizeof(int)); A = (int **) malloc(NROWS * sizeof(int *)); A[0] = A_data; for (i = 1; i < NROWS; i++) A[i] = A[i - 1] + NCOLS; if (rank == 0) { for (i = 0; i < NROWS; i++) for (j = 0; j < NCOLS; j++) A[i][j] = -1; /* create datatype for one column */ MPI_Type_vector(NROWS, 1, NCOLS, MPI_INT, &column); /* create datatype for matrix in column-major order */ MPI_Type_create_hvector(NCOLS, 1, sizeof(int), column, &xpose); MPI_Type_commit(&xpose); MPI_Win_create(NULL, 0, 1, MPI_INFO_NULL, CommDeuce, &win); MPI_Win_fence(0, win); MPI_Get(&A[0][0], NROWS * NCOLS, MPI_INT, 1, 0, 1, xpose, win); MPI_Type_free(&column); MPI_Type_free(&xpose); MPI_Win_fence(0, win); for (j = 0; j < NCOLS; j++) { for (i = 0; i < NROWS; i++) { if (A[j][i] != i * NCOLS + j) { if (errs < 50) { printf("Error: A[%d][%d]=%d should be %d\n", j, i, A[j][i], i * NCOLS + j); } errs++; } } } if (errs >= 50) { printf("Total number of errors: %d\n", errs); } } else { for (i = 0; i < NROWS; i++) for (j = 0; j < NCOLS; j++) A[i][j] = i * NCOLS + j; MPI_Win_create(&A[0][0], NROWS * NCOLS * sizeof(int), sizeof(int), MPI_INFO_NULL, CommDeuce, &win); MPI_Win_fence(0, win); MPI_Win_fence(0, win); } MPI_Win_free(&win); free(A_data); free(A); } MPI_Comm_free(&CommDeuce); MTest_Finalize(errs); return MTestReturnValue(errs); }
f36df450c0d04ab66b19c1ee5c9624e311e6bb90
8a6b9cdf1c2e6e8b62d5c7a30f87105c9822ab22
/text.h
fbe4196e4e3797f573afe3d01d8c3d816a421ee5
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
juj/fbcp-ili9341
605c71f9a7bcb4daf4da30777ceb8b089a0bb2e5
45e77fe63cda77e9636c9f23225313a458e55377
refs/heads/master
2023-08-11T14:10:25.911373
2022-11-16T11:07:53
2022-11-16T11:07:53
111,223,550
1,388
249
MIT
2023-01-30T13:53:30
2017-11-18T17:09:15
C++
UTF-8
C
false
false
9,843
h
text.h
#pragma once #include <inttypes.h> #define MONACO_WIDTH 5 #define MONACO_HEIGHT 8 #define MONACO_BYTES_PER_CHAR (MONACO_WIDTH*MONACO_HEIGHT/8) static uint8_t monaco_font[] = { /* ..... ..... ..... ..... ..... ..... ..... ..... */ 0x00,0x00,0x00,0x00,0x00, /* #.... #.... #.... #.... #.... ..... #.... ..... !*/ 0x21,0x84,0x10,0x40,0x00, /* #.#.. #.#.. ..... ..... ..... ..... ..... ..... "*/ 0xa5,0x00,0x00,0x00,0x00, /* ..##. ..##. ##### .#.#. ##### .##.. .##.. ..... #*/ 0x8c,0x7d,0xf5,0x8d,0x01, /* ..#.. .#### #.#.. #.#.. .##.. ..### ..#.# ####. $*/ 0xc4,0x97,0x62,0x38,0x7d, /* #...# ##..# #..#. ..#.. ..##. .#.## #..#. ..... %*/ 0x71,0x26,0xc2,0x74,0x02, /* .#... #.#.. #.#.. .#... #.##. #..#. .###. ..... &*/ 0xa2,0x14,0xd1,0x92,0x03, /* #.... #.... ..... ..... ..... ..... ..... ..... '*/ 0x21,0x00,0x00,0x00,0x00, /* ..#.. .#... #.... #.... #.... #.... .#... ..#.. (*/ 0x44,0x84,0x10,0x82,0x20, /* #.... .#... ..#.. ..#.. ..#.. ..#.. .#... #.... )*/ 0x41,0x10,0x42,0x88,0x08, /* .#... ###.. ###.. .#... ..... ..... ..... ..... **/ 0xe2,0x1c,0x01,0x00,0x00, /* ..#.. ..#.. ##### ..#.. ..#.. ..... ..... ..... +*/ 0x84,0x7c,0x42,0x00,0x00, /* #.... #.... #.... ..... ..... ..... ..... ..... ,*/ 0x21,0x04,0x00,0x00,0x00, /* ###.. ..... ..... ..... ..... ..... ..... ..... -*/ 0x07,0x00,0x00,0x00,0x00, /* #.... ..... ..... ..... ..... ..... ..... ..... .*/ 0x01,0x00,0x00,0x00,0x00, /* ...#. ...#. ..#.. .#... .#... #.... ..... ..... /*/ 0x08,0x11,0x21,0x02,0x00, /* .##.. #.##. #.##. ##.#. ##.#. ##.#. .##.. ..... 0*/ 0xa6,0xb5,0xb5,0x96,0x01, /* .#... ##... .#... .#... .#... .#... ###.. ..... 1*/ 0x62,0x08,0x21,0xc4,0x01, /* ###.. ...#. ...#. ..#.. .#... #.... ####. ..... 2*/ 0x07,0x21,0x22,0xc2,0x03, /* ###.. ...#. ...#. .##.. ...#. ...#. ###.. ..... 3*/ 0x07,0x21,0x83,0xd0,0x01, /* ...#. ..##. .#.#. #..#. ##### ...#. ...#. ..... 4*/ 0x88,0xa9,0xf4,0x11,0x02, /* ####. #.... ###.. ...#. ...#. ...#. ###.. ..... 5*/ 0x2f,0x1c,0x84,0xd0,0x01, /* .##.. #.... #.#.. ##.#. ##.#. ##.#. .##.. ..... 6*/ 0x26,0x94,0xb5,0x96,0x01, /* ####. ...#. ...#. ..#.. .##.. .#... .#... ..... 7*/ 0x0f,0x21,0x62,0x84,0x00, /* .###. #..#. #..#. .##.. #..#. #..#. ###.. ..... 8*/ 0x2e,0x25,0x93,0xd2,0x01, /* .##.. #..#. #..#. #..#. .###. ...#. .##.. ..... 9*/ 0x26,0xa5,0xe4,0x90,0x01, /* #.... ..... ..... ..... #.... ..... ..... ..... :*/ 0x01,0x00,0x10,0x00,0x00, /* #.... ..... ..... ..... #.... #.... #.... ..... ;*/ 0x01,0x00,0x10,0x42,0x00, /* ....# ..##. ##... ..##. ....# ..... ..... ..... <*/ 0x90,0x0d,0x06,0x01,0x00, /* ####. ..... ####. ..... ..... ..... ..... ..... =*/ 0x0f,0x3c,0x00,0x00,0x00, /* #.... .##.. ...## .##.. #.... ..... ..... ..... >*/ 0xc1,0x60,0x13,0x00,0x00, /* ###.. ..#.. ..#.. .#... .#... ..... .#... ..... ?*/ 0x87,0x10,0x21,0x80,0x00, /* .###. #...# #.### ##.## ##.## #.##. .##.. ..... @*/ 0x2e,0xf6,0xbd,0x9b,0x01, /* .##.. .##.. .##.. .##.. ####. ####. #..#. ..... A*/ 0xc6,0x18,0xf3,0x5e,0x02, /* ##... #.#.. #.#.. ##... #.#.. #.#.. ##... ..... B*/ 0xa3,0x94,0x51,0xca,0x00, /* .###. #.... #.... #.... #.... #.... .###. ..... C*/ 0x2e,0x84,0x10,0x82,0x03, /* ###.. #..#. #..#. #..#. #..#. #..#. ###.. ..... D*/ 0x27,0xa5,0x94,0xd2,0x01, /* ####. #.... #.... ####. #.... #.... ####. ..... E*/ 0x2f,0x84,0x17,0xc2,0x03, /* ####. #.... #.... ####. #.... #.... #.... ..... F*/ 0x2f,0x84,0x17,0x42,0x00, /* .###. #.... #.... #.##. #..#. #..#. .###. ..... G*/ 0x2e,0x84,0x96,0x92,0x03, /* #..#. #..#. #..#. ####. #..#. #..#. #..#. ..... H*/ 0x29,0xa5,0x97,0x52,0x02, /* ###.. .#... .#... .#... .#... .#... ###.. ..... I*/ 0x47,0x08,0x21,0xc4,0x01, /* .###. ...#. ...#. ...#. ...#. ...#. ###.. ..... J*/ 0x0e,0x21,0x84,0xd0,0x01, /* #..#. #..#. #.#.. ##... #.#.. #.#.. #..#. ..... K*/ 0x29,0x95,0x51,0x4a,0x02, /* #.... #.... #.... #.... #.... #.... ###.. ..... L*/ 0x21,0x84,0x10,0xc2,0x01, /* ##.## ##.## ##.## ##.## ###.# #.#.# #...# ..... M*/ 0x7b,0xef,0x7d,0x6b,0x04, /* #..#. ##.#. ##.#. #.##. #.##. #.##. #..#. ..... N*/ 0x69,0xad,0xd6,0x5a,0x02, /* .##.. #..#. #..#. #..#. #..#. #..#. .##.. ..... O*/ 0x26,0xa5,0x94,0x92,0x01, /* ###.. #..#. #..#. #..#. ###.. #.... #.... ..... P*/ 0x27,0xa5,0x74,0x42,0x00, /* .##.. #..#. #..#. #..#. #..#. #..#. .##.. ..#.. Q*/ 0x26,0xa5,0x94,0x92,0x21, /* ##... #.#.. #.#.. ##... ##... #.#.. #.#.. ..... R*/ 0xa3,0x94,0x31,0x4a,0x01, /* ###.. #.... #.... .#... ..#.. ..#.. ###.. ..... S*/ 0x27,0x04,0x41,0xc8,0x01, /* ##### ..#.. ..#.. ..#.. ..#.. ..#.. ..#.. ..... T*/ 0x9f,0x10,0x42,0x08,0x01, /* #..#. #..#. #..#. #..#. #..#. #..#. .##.. ..... U*/ 0x29,0xa5,0x94,0x92,0x01, /* #.#.. #.#.. #.#.. #.#.. #.#.. .#... .#... ..... V*/ 0xa5,0x94,0x52,0x84,0x00, /* #.#.# #.#.# ###.# ##.## .#.#. .#.#. .#.#. ..... W*/ 0xb5,0xde,0xad,0x94,0x02, /* .#.#. .#.#. ..#.. ..#.. ..#.. .#.#. .#.#. ..... X*/ 0x4a,0x11,0x42,0x94,0x02, /* #.#.. #.#.. #.#.. .#... .#... .#... .#... ..... Y*/ 0xa5,0x14,0x21,0x84,0x00, /* ####. ...#. ..#.. .#... .#... #.... ####. ..... Z*/ 0x0f,0x11,0x21,0xc2,0x03, /* ###.. #.... #.... #.... #.... #.... #.... ###.. [*/ 0x27,0x84,0x10,0x42,0x38, /* #.... #.... .#... .#... ..#.. ...#. ..... ..... \*/ 0x21,0x08,0x41,0x10,0x00, /* ###.. ..#.. ..#.. ..#.. ..#.. ..#.. ..#.. ###.. ]*/ 0x87,0x10,0x42,0x08,0x39, /* .#... .##.. .##.. #..#. ..... ..... ..... ..... ^*/ 0xc2,0x98,0x04,0x00,0x00, /* ####. ..... ..... ..... ..... ..... ..... ..... _*/ 0x0f,0x00,0x00,0x00,0x00, /* .#... ..... ..... ..... ..... ..... ..... ..... `*/ 0x02,0x00,0x00,0x00,0x00, /* .#### #...# #...# #...# .#### ..... ..... ..... a*/ 0x3e,0xc6,0xe8,0x01,0x00, /* #.... #.... ####. #...# #...# #...# ####. ..... b*/ 0x21,0xbc,0x18,0xe3,0x03, /* .###. #.... #.... #.... .###. ..... ..... ..... c*/ 0x2e,0x84,0xe0,0x00,0x00, /* ...#. ...#. .###. #..#. #..#. #..#. .###. ..... d*/ 0x08,0xb9,0x94,0x92,0x03, /* .##.. #..#. ####. #.... .###. ..... ..... ..... e*/ 0x26,0xbd,0xe0,0x00,0x00, /* ..### .#... ####. .#... .#... .#... .#... ..... f*/ 0x5c,0x3c,0x21,0x84,0x00, /* .###. #..#. #..#. #..#. .###. ...#. ###.. ..... g*/ 0x2e,0xa5,0xe4,0xd0,0x01, /* #.... #.... ###.. #..#. #..#. #..#. #..#. ..... h*/ 0x21,0x9c,0x94,0x52,0x02, /* .#... ..... ##... .#... .#... .#... .##.. ..... i*/ 0x02,0x0c,0x21,0x84,0x01, /* ..#.. ..... ###.. ..#.. ..#.. ..#.. ..#.. ..#.. j*/ 0x04,0x1c,0x42,0x08,0x21, /* #.... #.... #.#.. ##... ##... #.#.. #..#. ..... k*/ 0x21,0x94,0x31,0x4a,0x02, /* ##... .#... .#... .#... .#... .#... .##.. ..... l*/ 0x43,0x08,0x21,0x84,0x01, /* ##### #.#.# #.#.# #.#.# #.#.# ..... ..... ..... m*/ 0xbf,0xd6,0x5a,0x01,0x00, /* ###.. #..#. #..#. #..#. #..#. ..... ..... ..... n*/ 0x27,0xa5,0x94,0x00,0x00, /* .##.. #..#. #..#. #..#. .##.. ..... ..... ..... o*/ 0x26,0xa5,0x64,0x00,0x00, /* ####. #...# #...# #...# ####. #.... #.... ..... p*/ 0x2f,0xc6,0xf8,0x42,0x00, /* .###. #..#. #..#. #..#. .###. ...#. ...#. ..... q*/ 0x2e,0xa5,0xe4,0x10,0x02, /* ###.. #.#.. #.... #.... #.... ..... ..... ..... r*/ 0xa7,0x84,0x10,0x00,0x00, /* .###. #..#. .###. #..#. ###.. ..... ..... ..... s*/ 0x2e,0xb9,0x74,0x00,0x00, /* .#... .#... ####. .#... .#... ..##. ..... ..... t*/ 0x42,0x3c,0x21,0x18,0x00, /* #..#. #..#. #..#. #..#. .###. ..... ..... ..... u*/ 0x29,0xa5,0xe4,0x00,0x00, /* #.#.. #.#.. #.#.. ###.. .#... ..... ..... ..... v*/ 0xa5,0x94,0x23,0x00,0x00, /* #.#.# ###.# ###.# ####. .#.#. ..... ..... ..... w*/ 0xf5,0xde,0xa7,0x00,0x00, /* .#.#. .##.. ..#.. .#.#. .#.#. ..... ..... ..... x*/ 0xca,0x10,0xa5,0x00,0x00, /* .#.#. .#.#. .#.#. ..##. ..#.. ..#.. ##... ..... y*/ 0x4a,0x29,0x46,0xc8,0x00, /* ####. ..#.. .#... #.... ####. ..... ..... ..... z*/ 0x8f,0x88,0xf0,0x00,0x00, /* .##.. .#... .#... .#... #.... .#... .#... .##.. {*/ 0x46,0x08,0x11,0x84,0x30, /* #.... #.... #.... #.... #.... #.... ..... ..... |*/ 0x21,0x84,0x10,0x02,0x00, /* ##... .#... .#... .#... ..#.. .#... .#... ##... }*/ 0x43,0x08,0x41,0x84,0x18, /* ##### ..... ..... ..... ..... ..... ..... ..... ~*/ 0x1f,0x00,0x00,0x00,0x00, }; static uint8_t monaco_font_outline[127*MONACO_BYTES_PER_CHAR] = {}; static const int8_t monaco_height_adjust[] = { 6,-1,-1,-1,-2,-1,-1,-1,-1,-1,-1,1,5,3,5,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,2,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,0,1,-1,1,-1,1,-1,1,-1,-1,-1,-1,-1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,-1,-1,-1,4, }; #define RGB565(r, g, b) (((r) << 11) | ((g) << 5) | (b)) void DrawText(uint16_t *framebuffer, int framebufferWidth, int framebufferStrideBytes, int framebufferHeight, const char *text, int x, int y, uint16_t color, uint16_t bgColor);
66ad82f65247babfd87c6a2cd5a741256322e3bf
d84c7df450292867f8c7bb58d1507735479d746d
/backends/memcheck/ceed-memcheck.h
ca451e604499577040174761f93607a1d35ab825
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
CEED/libCEED
c17e8b2f8e9ccfafc0505bb6db451e2f7cfed690
c6c10e0994b55ea1726a79024cd4c333c40de38a
refs/heads/main
2023-09-01T20:13:21.268643
2023-09-01T20:08:36
2023-09-01T20:08:36
113,349,904
167
54
BSD-2-Clause
2023-09-14T20:37:58
2017-12-06T17:57:40
C
UTF-8
C
false
false
1,188
h
ceed-memcheck.h
// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and other CEED contributors. // All Rights Reserved. See the top-level LICENSE and NOTICE files for details. // // SPDX-License-Identifier: BSD-2-Clause // // This file is part of CEED: http://github.com/ceed #ifndef CEED_MEMCHECK_H #define CEED_MEMCHECK_H #include <ceed.h> #include <ceed/backend.h> typedef struct { int mem_block_id; bool is_write_only_access; CeedScalar *array; CeedScalar *array_allocated; CeedScalar *array_owned; CeedScalar *array_borrowed; CeedScalar *array_read_only_copy; } CeedVector_Memcheck; typedef struct { const CeedScalar **inputs; CeedScalar **outputs; bool setup_done; } CeedQFunction_Memcheck; typedef struct { int mem_block_id; void *data; void *data_allocated; void *data_owned; void *data_borrowed; void *data_read_only_copy; } CeedQFunctionContext_Memcheck; CEED_INTERN int CeedVectorCreate_Memcheck(CeedSize n, CeedVector vec); CEED_INTERN int CeedQFunctionCreate_Memcheck(CeedQFunction qf); CEED_INTERN int CeedQFunctionContextCreate_Memcheck(CeedQFunctionContext ctx); #endif // CEED_MEMCHECK_H
2ff9da19540da86c2e78ef2372cddc2444a10753
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/drivers/net/wireless/ti/wl18xx/main.c
9fa692d110250bde779c627e66af87e10ba4f5f2
[ "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later", "LicenseRef-scancode-free-unknown", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
54,644
c
main.c
/* * This file is part of wl18xx * * Copyright (C) 2011 Texas Instruments * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * */ #include <linux/module.h> #include <linux/platform_device.h> #include <linux/ip.h> #include <linux/firmware.h> #include "../wlcore/wlcore.h" #include "../wlcore/debug.h" #include "../wlcore/io.h" #include "../wlcore/acx.h" #include "../wlcore/tx.h" #include "../wlcore/rx.h" #include "../wlcore/boot.h" #include "reg.h" #include "conf.h" #include "cmd.h" #include "acx.h" #include "tx.h" #include "wl18xx.h" #include "io.h" #include "scan.h" #include "event.h" #include "debugfs.h" #define WL18XX_RX_CHECKSUM_MASK 0x40 static char *ht_mode_param = NULL; static char *board_type_param = NULL; static bool checksum_param = false; static int num_rx_desc_param = -1; /* phy paramters */ static int dc2dc_param = -1; static int n_antennas_2_param = -1; static int n_antennas_5_param = -1; static int low_band_component_param = -1; static int low_band_component_type_param = -1; static int high_band_component_param = -1; static int high_band_component_type_param = -1; static int pwr_limit_reference_11_abg_param = -1; static const u8 wl18xx_rate_to_idx_2ghz[] = { /* MCS rates are used only with 11n */ 15, /* WL18XX_CONF_HW_RXTX_RATE_MCS15 */ 14, /* WL18XX_CONF_HW_RXTX_RATE_MCS14 */ 13, /* WL18XX_CONF_HW_RXTX_RATE_MCS13 */ 12, /* WL18XX_CONF_HW_RXTX_RATE_MCS12 */ 11, /* WL18XX_CONF_HW_RXTX_RATE_MCS11 */ 10, /* WL18XX_CONF_HW_RXTX_RATE_MCS10 */ 9, /* WL18XX_CONF_HW_RXTX_RATE_MCS9 */ 8, /* WL18XX_CONF_HW_RXTX_RATE_MCS8 */ 7, /* WL18XX_CONF_HW_RXTX_RATE_MCS7 */ 6, /* WL18XX_CONF_HW_RXTX_RATE_MCS6 */ 5, /* WL18XX_CONF_HW_RXTX_RATE_MCS5 */ 4, /* WL18XX_CONF_HW_RXTX_RATE_MCS4 */ 3, /* WL18XX_CONF_HW_RXTX_RATE_MCS3 */ 2, /* WL18XX_CONF_HW_RXTX_RATE_MCS2 */ 1, /* WL18XX_CONF_HW_RXTX_RATE_MCS1 */ 0, /* WL18XX_CONF_HW_RXTX_RATE_MCS0 */ 11, /* WL18XX_CONF_HW_RXTX_RATE_54 */ 10, /* WL18XX_CONF_HW_RXTX_RATE_48 */ 9, /* WL18XX_CONF_HW_RXTX_RATE_36 */ 8, /* WL18XX_CONF_HW_RXTX_RATE_24 */ /* TI-specific rate */ CONF_HW_RXTX_RATE_UNSUPPORTED, /* WL18XX_CONF_HW_RXTX_RATE_22 */ 7, /* WL18XX_CONF_HW_RXTX_RATE_18 */ 6, /* WL18XX_CONF_HW_RXTX_RATE_12 */ 3, /* WL18XX_CONF_HW_RXTX_RATE_11 */ 5, /* WL18XX_CONF_HW_RXTX_RATE_9 */ 4, /* WL18XX_CONF_HW_RXTX_RATE_6 */ 2, /* WL18XX_CONF_HW_RXTX_RATE_5_5 */ 1, /* WL18XX_CONF_HW_RXTX_RATE_2 */ 0 /* WL18XX_CONF_HW_RXTX_RATE_1 */ }; static const u8 wl18xx_rate_to_idx_5ghz[] = { /* MCS rates are used only with 11n */ 15, /* WL18XX_CONF_HW_RXTX_RATE_MCS15 */ 14, /* WL18XX_CONF_HW_RXTX_RATE_MCS14 */ 13, /* WL18XX_CONF_HW_RXTX_RATE_MCS13 */ 12, /* WL18XX_CONF_HW_RXTX_RATE_MCS12 */ 11, /* WL18XX_CONF_HW_RXTX_RATE_MCS11 */ 10, /* WL18XX_CONF_HW_RXTX_RATE_MCS10 */ 9, /* WL18XX_CONF_HW_RXTX_RATE_MCS9 */ 8, /* WL18XX_CONF_HW_RXTX_RATE_MCS8 */ 7, /* WL18XX_CONF_HW_RXTX_RATE_MCS7 */ 6, /* WL18XX_CONF_HW_RXTX_RATE_MCS6 */ 5, /* WL18XX_CONF_HW_RXTX_RATE_MCS5 */ 4, /* WL18XX_CONF_HW_RXTX_RATE_MCS4 */ 3, /* WL18XX_CONF_HW_RXTX_RATE_MCS3 */ 2, /* WL18XX_CONF_HW_RXTX_RATE_MCS2 */ 1, /* WL18XX_CONF_HW_RXTX_RATE_MCS1 */ 0, /* WL18XX_CONF_HW_RXTX_RATE_MCS0 */ 7, /* WL18XX_CONF_HW_RXTX_RATE_54 */ 6, /* WL18XX_CONF_HW_RXTX_RATE_48 */ 5, /* WL18XX_CONF_HW_RXTX_RATE_36 */ 4, /* WL18XX_CONF_HW_RXTX_RATE_24 */ /* TI-specific rate */ CONF_HW_RXTX_RATE_UNSUPPORTED, /* WL18XX_CONF_HW_RXTX_RATE_22 */ 3, /* WL18XX_CONF_HW_RXTX_RATE_18 */ 2, /* WL18XX_CONF_HW_RXTX_RATE_12 */ CONF_HW_RXTX_RATE_UNSUPPORTED, /* WL18XX_CONF_HW_RXTX_RATE_11 */ 1, /* WL18XX_CONF_HW_RXTX_RATE_9 */ 0, /* WL18XX_CONF_HW_RXTX_RATE_6 */ CONF_HW_RXTX_RATE_UNSUPPORTED, /* WL18XX_CONF_HW_RXTX_RATE_5_5 */ CONF_HW_RXTX_RATE_UNSUPPORTED, /* WL18XX_CONF_HW_RXTX_RATE_2 */ CONF_HW_RXTX_RATE_UNSUPPORTED, /* WL18XX_CONF_HW_RXTX_RATE_1 */ }; static const u8 *wl18xx_band_rate_to_idx[] = { [IEEE80211_BAND_2GHZ] = wl18xx_rate_to_idx_2ghz, [IEEE80211_BAND_5GHZ] = wl18xx_rate_to_idx_5ghz }; enum wl18xx_hw_rates { WL18XX_CONF_HW_RXTX_RATE_MCS15 = 0, WL18XX_CONF_HW_RXTX_RATE_MCS14, WL18XX_CONF_HW_RXTX_RATE_MCS13, WL18XX_CONF_HW_RXTX_RATE_MCS12, WL18XX_CONF_HW_RXTX_RATE_MCS11, WL18XX_CONF_HW_RXTX_RATE_MCS10, WL18XX_CONF_HW_RXTX_RATE_MCS9, WL18XX_CONF_HW_RXTX_RATE_MCS8, WL18XX_CONF_HW_RXTX_RATE_MCS7, WL18XX_CONF_HW_RXTX_RATE_MCS6, WL18XX_CONF_HW_RXTX_RATE_MCS5, WL18XX_CONF_HW_RXTX_RATE_MCS4, WL18XX_CONF_HW_RXTX_RATE_MCS3, WL18XX_CONF_HW_RXTX_RATE_MCS2, WL18XX_CONF_HW_RXTX_RATE_MCS1, WL18XX_CONF_HW_RXTX_RATE_MCS0, WL18XX_CONF_HW_RXTX_RATE_54, WL18XX_CONF_HW_RXTX_RATE_48, WL18XX_CONF_HW_RXTX_RATE_36, WL18XX_CONF_HW_RXTX_RATE_24, WL18XX_CONF_HW_RXTX_RATE_22, WL18XX_CONF_HW_RXTX_RATE_18, WL18XX_CONF_HW_RXTX_RATE_12, WL18XX_CONF_HW_RXTX_RATE_11, WL18XX_CONF_HW_RXTX_RATE_9, WL18XX_CONF_HW_RXTX_RATE_6, WL18XX_CONF_HW_RXTX_RATE_5_5, WL18XX_CONF_HW_RXTX_RATE_2, WL18XX_CONF_HW_RXTX_RATE_1, WL18XX_CONF_HW_RXTX_RATE_MAX, }; static struct wlcore_conf wl18xx_conf = { .sg = { .params = { [CONF_SG_ACL_BT_MASTER_MIN_BR] = 10, [CONF_SG_ACL_BT_MASTER_MAX_BR] = 180, [CONF_SG_ACL_BT_SLAVE_MIN_BR] = 10, [CONF_SG_ACL_BT_SLAVE_MAX_BR] = 180, [CONF_SG_ACL_BT_MASTER_MIN_EDR] = 10, [CONF_SG_ACL_BT_MASTER_MAX_EDR] = 80, [CONF_SG_ACL_BT_SLAVE_MIN_EDR] = 10, [CONF_SG_ACL_BT_SLAVE_MAX_EDR] = 80, [CONF_SG_ACL_WLAN_PS_MASTER_BR] = 8, [CONF_SG_ACL_WLAN_PS_SLAVE_BR] = 8, [CONF_SG_ACL_WLAN_PS_MASTER_EDR] = 20, [CONF_SG_ACL_WLAN_PS_SLAVE_EDR] = 20, [CONF_SG_ACL_WLAN_ACTIVE_MASTER_MIN_BR] = 20, [CONF_SG_ACL_WLAN_ACTIVE_MASTER_MAX_BR] = 35, [CONF_SG_ACL_WLAN_ACTIVE_SLAVE_MIN_BR] = 16, [CONF_SG_ACL_WLAN_ACTIVE_SLAVE_MAX_BR] = 35, [CONF_SG_ACL_WLAN_ACTIVE_MASTER_MIN_EDR] = 32, [CONF_SG_ACL_WLAN_ACTIVE_MASTER_MAX_EDR] = 50, [CONF_SG_ACL_WLAN_ACTIVE_SLAVE_MIN_EDR] = 28, [CONF_SG_ACL_WLAN_ACTIVE_SLAVE_MAX_EDR] = 50, [CONF_SG_ACL_ACTIVE_SCAN_WLAN_BR] = 10, [CONF_SG_ACL_ACTIVE_SCAN_WLAN_EDR] = 20, [CONF_SG_ACL_PASSIVE_SCAN_BT_BR] = 75, [CONF_SG_ACL_PASSIVE_SCAN_WLAN_BR] = 15, [CONF_SG_ACL_PASSIVE_SCAN_BT_EDR] = 27, [CONF_SG_ACL_PASSIVE_SCAN_WLAN_EDR] = 17, /* active scan params */ [CONF_SG_AUTO_SCAN_PROBE_REQ] = 170, [CONF_SG_ACTIVE_SCAN_DURATION_FACTOR_HV3] = 50, [CONF_SG_ACTIVE_SCAN_DURATION_FACTOR_A2DP] = 100, /* passive scan params */ [CONF_SG_PASSIVE_SCAN_DURATION_FACTOR_A2DP_BR] = 800, [CONF_SG_PASSIVE_SCAN_DURATION_FACTOR_A2DP_EDR] = 200, [CONF_SG_PASSIVE_SCAN_DURATION_FACTOR_HV3] = 200, /* passive scan in dual antenna params */ [CONF_SG_CONSECUTIVE_HV3_IN_PASSIVE_SCAN] = 0, [CONF_SG_BCN_HV3_COLLISION_THRESH_IN_PASSIVE_SCAN] = 0, [CONF_SG_TX_RX_PROTECTION_BWIDTH_IN_PASSIVE_SCAN] = 0, /* general params */ [CONF_SG_STA_FORCE_PS_IN_BT_SCO] = 1, [CONF_SG_ANTENNA_CONFIGURATION] = 0, [CONF_SG_BEACON_MISS_PERCENT] = 60, [CONF_SG_DHCP_TIME] = 5000, [CONF_SG_RXT] = 1200, [CONF_SG_TXT] = 1000, [CONF_SG_ADAPTIVE_RXT_TXT] = 1, [CONF_SG_GENERAL_USAGE_BIT_MAP] = 3, [CONF_SG_HV3_MAX_SERVED] = 6, [CONF_SG_PS_POLL_TIMEOUT] = 10, [CONF_SG_UPSD_TIMEOUT] = 10, [CONF_SG_CONSECUTIVE_CTS_THRESHOLD] = 2, [CONF_SG_STA_RX_WINDOW_AFTER_DTIM] = 5, [CONF_SG_STA_CONNECTION_PROTECTION_TIME] = 30, /* AP params */ [CONF_AP_BEACON_MISS_TX] = 3, [CONF_AP_RX_WINDOW_AFTER_BEACON] = 10, [CONF_AP_BEACON_WINDOW_INTERVAL] = 2, [CONF_AP_CONNECTION_PROTECTION_TIME] = 0, [CONF_AP_BT_ACL_VAL_BT_SERVE_TIME] = 25, [CONF_AP_BT_ACL_VAL_WL_SERVE_TIME] = 25, /* CTS Diluting params */ [CONF_SG_CTS_DILUTED_BAD_RX_PACKETS_TH] = 0, [CONF_SG_CTS_CHOP_IN_DUAL_ANT_SCO_MASTER] = 0, }, .state = CONF_SG_PROTECTIVE, }, .rx = { .rx_msdu_life_time = 512000, .packet_detection_threshold = 0, .ps_poll_timeout = 15, .upsd_timeout = 15, .rts_threshold = IEEE80211_MAX_RTS_THRESHOLD, .rx_cca_threshold = 0, .irq_blk_threshold = 0xFFFF, .irq_pkt_threshold = 0, .irq_timeout = 600, .queue_type = CONF_RX_QUEUE_TYPE_LOW_PRIORITY, }, .tx = { .tx_energy_detection = 0, .sta_rc_conf = { .enabled_rates = 0, .short_retry_limit = 10, .long_retry_limit = 10, .aflags = 0, }, .ac_conf_count = 4, .ac_conf = { [CONF_TX_AC_BE] = { .ac = CONF_TX_AC_BE, .cw_min = 15, .cw_max = 63, .aifsn = 3, .tx_op_limit = 0, }, [CONF_TX_AC_BK] = { .ac = CONF_TX_AC_BK, .cw_min = 15, .cw_max = 63, .aifsn = 7, .tx_op_limit = 0, }, [CONF_TX_AC_VI] = { .ac = CONF_TX_AC_VI, .cw_min = 15, .cw_max = 63, .aifsn = CONF_TX_AIFS_PIFS, .tx_op_limit = 3008, }, [CONF_TX_AC_VO] = { .ac = CONF_TX_AC_VO, .cw_min = 15, .cw_max = 63, .aifsn = CONF_TX_AIFS_PIFS, .tx_op_limit = 1504, }, }, .max_tx_retries = 100, .ap_aging_period = 300, .tid_conf_count = 4, .tid_conf = { [CONF_TX_AC_BE] = { .queue_id = CONF_TX_AC_BE, .channel_type = CONF_CHANNEL_TYPE_EDCF, .tsid = CONF_TX_AC_BE, .ps_scheme = CONF_PS_SCHEME_LEGACY, .ack_policy = CONF_ACK_POLICY_LEGACY, .apsd_conf = {0, 0}, }, [CONF_TX_AC_BK] = { .queue_id = CONF_TX_AC_BK, .channel_type = CONF_CHANNEL_TYPE_EDCF, .tsid = CONF_TX_AC_BK, .ps_scheme = CONF_PS_SCHEME_LEGACY, .ack_policy = CONF_ACK_POLICY_LEGACY, .apsd_conf = {0, 0}, }, [CONF_TX_AC_VI] = { .queue_id = CONF_TX_AC_VI, .channel_type = CONF_CHANNEL_TYPE_EDCF, .tsid = CONF_TX_AC_VI, .ps_scheme = CONF_PS_SCHEME_LEGACY, .ack_policy = CONF_ACK_POLICY_LEGACY, .apsd_conf = {0, 0}, }, [CONF_TX_AC_VO] = { .queue_id = CONF_TX_AC_VO, .channel_type = CONF_CHANNEL_TYPE_EDCF, .tsid = CONF_TX_AC_VO, .ps_scheme = CONF_PS_SCHEME_LEGACY, .ack_policy = CONF_ACK_POLICY_LEGACY, .apsd_conf = {0, 0}, }, }, .frag_threshold = IEEE80211_MAX_FRAG_THRESHOLD, .tx_compl_timeout = 350, .tx_compl_threshold = 10, .basic_rate = CONF_HW_BIT_RATE_1MBPS, .basic_rate_5 = CONF_HW_BIT_RATE_6MBPS, .tmpl_short_retry_limit = 10, .tmpl_long_retry_limit = 10, .tx_watchdog_timeout = 5000, .slow_link_thold = 3, .fast_link_thold = 30, }, .conn = { .wake_up_event = CONF_WAKE_UP_EVENT_DTIM, .listen_interval = 1, .suspend_wake_up_event = CONF_WAKE_UP_EVENT_N_DTIM, .suspend_listen_interval = 3, .bcn_filt_mode = CONF_BCN_FILT_MODE_ENABLED, .bcn_filt_ie_count = 3, .bcn_filt_ie = { [0] = { .ie = WLAN_EID_CHANNEL_SWITCH, .rule = CONF_BCN_RULE_PASS_ON_APPEARANCE, }, [1] = { .ie = WLAN_EID_HT_OPERATION, .rule = CONF_BCN_RULE_PASS_ON_CHANGE, }, [2] = { .ie = WLAN_EID_ERP_INFO, .rule = CONF_BCN_RULE_PASS_ON_CHANGE, }, }, .synch_fail_thold = 12, .bss_lose_timeout = 400, .beacon_rx_timeout = 10000, .broadcast_timeout = 20000, .rx_broadcast_in_ps = 1, .ps_poll_threshold = 10, .bet_enable = CONF_BET_MODE_ENABLE, .bet_max_consecutive = 50, .psm_entry_retries = 8, .psm_exit_retries = 16, .psm_entry_nullfunc_retries = 3, .dynamic_ps_timeout = 1500, .forced_ps = false, .keep_alive_interval = 55000, .max_listen_interval = 20, .sta_sleep_auth = WL1271_PSM_ILLEGAL, }, .itrim = { .enable = false, .timeout = 50000, }, .pm_config = { .host_clk_settling_time = 5000, .host_fast_wakeup_support = CONF_FAST_WAKEUP_DISABLE, }, .roam_trigger = { .trigger_pacing = 1, .avg_weight_rssi_beacon = 20, .avg_weight_rssi_data = 10, .avg_weight_snr_beacon = 20, .avg_weight_snr_data = 10, }, .scan = { .min_dwell_time_active = 7500, .max_dwell_time_active = 30000, .min_dwell_time_active_long = 25000, .max_dwell_time_active_long = 50000, .dwell_time_passive = 100000, .dwell_time_dfs = 150000, .num_probe_reqs = 2, .split_scan_timeout = 50000, }, .sched_scan = { /* * Values are in TU/1000 but since sched scan FW command * params are in TUs rounding up may occur. */ .base_dwell_time = 7500, .max_dwell_time_delta = 22500, /* based on 250bits per probe @1Mbps */ .dwell_time_delta_per_probe = 2000, /* based on 250bits per probe @6Mbps (plus a bit more) */ .dwell_time_delta_per_probe_5 = 350, .dwell_time_passive = 100000, .dwell_time_dfs = 150000, .num_probe_reqs = 2, .rssi_threshold = -90, .snr_threshold = 0, }, .ht = { .rx_ba_win_size = 32, .tx_ba_win_size = 64, .inactivity_timeout = 10000, .tx_ba_tid_bitmap = CONF_TX_BA_ENABLED_TID_BITMAP, }, .mem = { .num_stations = 1, .ssid_profiles = 1, .rx_block_num = 40, .tx_min_block_num = 40, .dynamic_memory = 1, .min_req_tx_blocks = 45, .min_req_rx_blocks = 22, .tx_min = 27, }, .fm_coex = { .enable = true, .swallow_period = 5, .n_divider_fref_set_1 = 0xff, /* default */ .n_divider_fref_set_2 = 12, .m_divider_fref_set_1 = 0xffff, .m_divider_fref_set_2 = 148, /* default */ .coex_pll_stabilization_time = 0xffffffff, /* default */ .ldo_stabilization_time = 0xffff, /* default */ .fm_disturbed_band_margin = 0xff, /* default */ .swallow_clk_diff = 0xff, /* default */ }, .rx_streaming = { .duration = 150, .queues = 0x1, .interval = 20, .always = 0, }, .fwlog = { .mode = WL12XX_FWLOG_ON_DEMAND, .mem_blocks = 2, .severity = 0, .timestamp = WL12XX_FWLOG_TIMESTAMP_DISABLED, .output = WL12XX_FWLOG_OUTPUT_HOST, .threshold = 0, }, .rate = { .rate_retry_score = 32000, .per_add = 8192, .per_th1 = 2048, .per_th2 = 4096, .max_per = 8100, .inverse_curiosity_factor = 5, .tx_fail_low_th = 4, .tx_fail_high_th = 10, .per_alpha_shift = 4, .per_add_shift = 13, .per_beta1_shift = 10, .per_beta2_shift = 8, .rate_check_up = 2, .rate_check_down = 12, .rate_retry_policy = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }, }, .hangover = { .recover_time = 0, .hangover_period = 20, .dynamic_mode = 1, .early_termination_mode = 1, .max_period = 20, .min_period = 1, .increase_delta = 1, .decrease_delta = 2, .quiet_time = 4, .increase_time = 1, .window_size = 16, }, .recovery = { .bug_on_recovery = 0, .no_recovery = 0, }, }; static struct wl18xx_priv_conf wl18xx_default_priv_conf = { .ht = { .mode = HT_MODE_DEFAULT, }, .phy = { .phy_standalone = 0x00, .primary_clock_setting_time = 0x05, .clock_valid_on_wake_up = 0x00, .secondary_clock_setting_time = 0x05, .board_type = BOARD_TYPE_HDK_18XX, .auto_detect = 0x00, .dedicated_fem = FEM_NONE, .low_band_component = COMPONENT_3_WAY_SWITCH, .low_band_component_type = 0x04, .high_band_component = COMPONENT_2_WAY_SWITCH, .high_band_component_type = 0x09, .tcxo_ldo_voltage = 0x00, .xtal_itrim_val = 0x04, .srf_state = 0x00, .io_configuration = 0x01, .sdio_configuration = 0x00, .settings = 0x00, .enable_clpc = 0x00, .enable_tx_low_pwr_on_siso_rdl = 0x00, .rx_profile = 0x00, .pwr_limit_reference_11_abg = 0x64, .per_chan_pwr_limit_arr_11abg = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }, .pwr_limit_reference_11p = 0x64, .per_chan_bo_mode_11_abg = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, .per_chan_bo_mode_11_p = { 0x00, 0x00, 0x00, 0x00 }, .per_chan_pwr_limit_arr_11p = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }, .psat = 0, .low_power_val = 0x08, .med_power_val = 0x12, .high_power_val = 0x18, .low_power_val_2nd = 0x05, .med_power_val_2nd = 0x0a, .high_power_val_2nd = 0x14, .external_pa_dc2dc = 0, .number_of_assembled_ant2_4 = 2, .number_of_assembled_ant5 = 1, .tx_rf_margin = 1, }, }; static const struct wlcore_partition_set wl18xx_ptable[PART_TABLE_LEN] = { [PART_TOP_PRCM_ELP_SOC] = { .mem = { .start = 0x00A02000, .size = 0x00010000 }, .reg = { .start = 0x00807000, .size = 0x00005000 }, .mem2 = { .start = 0x00800000, .size = 0x0000B000 }, .mem3 = { .start = 0x00000000, .size = 0x00000000 }, }, [PART_DOWN] = { .mem = { .start = 0x00000000, .size = 0x00014000 }, .reg = { .start = 0x00810000, .size = 0x0000BFFF }, .mem2 = { .start = 0x00000000, .size = 0x00000000 }, .mem3 = { .start = 0x00000000, .size = 0x00000000 }, }, [PART_BOOT] = { .mem = { .start = 0x00700000, .size = 0x0000030c }, .reg = { .start = 0x00802000, .size = 0x00014578 }, .mem2 = { .start = 0x00B00404, .size = 0x00001000 }, .mem3 = { .start = 0x00C00000, .size = 0x00000400 }, }, [PART_WORK] = { .mem = { .start = 0x00800000, .size = 0x000050FC }, .reg = { .start = 0x00B00404, .size = 0x00001000 }, .mem2 = { .start = 0x00C00000, .size = 0x00000400 }, .mem3 = { .start = 0x00000000, .size = 0x00000000 }, }, [PART_PHY_INIT] = { .mem = { .start = 0x80926000, .size = sizeof(struct wl18xx_mac_and_phy_params) }, .reg = { .start = 0x00000000, .size = 0x00000000 }, .mem2 = { .start = 0x00000000, .size = 0x00000000 }, .mem3 = { .start = 0x00000000, .size = 0x00000000 }, }, }; static const int wl18xx_rtable[REG_TABLE_LEN] = { [REG_ECPU_CONTROL] = WL18XX_REG_ECPU_CONTROL, [REG_INTERRUPT_NO_CLEAR] = WL18XX_REG_INTERRUPT_NO_CLEAR, [REG_INTERRUPT_ACK] = WL18XX_REG_INTERRUPT_ACK, [REG_COMMAND_MAILBOX_PTR] = WL18XX_REG_COMMAND_MAILBOX_PTR, [REG_EVENT_MAILBOX_PTR] = WL18XX_REG_EVENT_MAILBOX_PTR, [REG_INTERRUPT_TRIG] = WL18XX_REG_INTERRUPT_TRIG_H, [REG_INTERRUPT_MASK] = WL18XX_REG_INTERRUPT_MASK, [REG_PC_ON_RECOVERY] = WL18XX_SCR_PAD4, [REG_CHIP_ID_B] = WL18XX_REG_CHIP_ID_B, [REG_CMD_MBOX_ADDRESS] = WL18XX_CMD_MBOX_ADDRESS, /* data access memory addresses, used with partition translation */ [REG_SLV_MEM_DATA] = WL18XX_SLV_MEM_DATA, [REG_SLV_REG_DATA] = WL18XX_SLV_REG_DATA, /* raw data access memory addresses */ [REG_RAW_FW_STATUS_ADDR] = WL18XX_FW_STATUS_ADDR, }; static const struct wl18xx_clk_cfg wl18xx_clk_table[NUM_CLOCK_CONFIGS] = { [CLOCK_CONFIG_16_2_M] = { 7, 104, 801, 4, true }, [CLOCK_CONFIG_16_368_M] = { 9, 132, 3751, 4, true }, [CLOCK_CONFIG_16_8_M] = { 7, 100, 0, 0, false }, [CLOCK_CONFIG_19_2_M] = { 8, 100, 0, 0, false }, [CLOCK_CONFIG_26_M] = { 13, 120, 0, 0, false }, [CLOCK_CONFIG_32_736_M] = { 9, 132, 3751, 4, true }, [CLOCK_CONFIG_33_6_M] = { 7, 100, 0, 0, false }, [CLOCK_CONFIG_38_468_M] = { 8, 100, 0, 0, false }, [CLOCK_CONFIG_52_M] = { 13, 120, 0, 0, false }, }; /* TODO: maybe move to a new header file? */ #define WL18XX_FW_NAME "ti-connectivity/wl18xx-fw-2.bin" static int wl18xx_identify_chip(struct wl1271 *wl) { int ret = 0; switch (wl->chip.id) { case CHIP_ID_185x_PG20: wl1271_debug(DEBUG_BOOT, "chip id 0x%x (185x PG20)", wl->chip.id); wl->sr_fw_name = WL18XX_FW_NAME; /* wl18xx uses the same firmware for PLT */ wl->plt_fw_name = WL18XX_FW_NAME; wl->quirks |= WLCORE_QUIRK_RX_BLOCKSIZE_ALIGN | WLCORE_QUIRK_TX_BLOCKSIZE_ALIGN | WLCORE_QUIRK_NO_SCHED_SCAN_WHILE_CONN | WLCORE_QUIRK_TX_PAD_LAST_FRAME | WLCORE_QUIRK_REGDOMAIN_CONF | WLCORE_QUIRK_DUAL_PROBE_TMPL; wlcore_set_min_fw_ver(wl, WL18XX_CHIP_VER, WL18XX_IFTYPE_VER, WL18XX_MAJOR_VER, WL18XX_SUBTYPE_VER, WL18XX_MINOR_VER, /* there's no separate multi-role FW */ 0, 0, 0, 0); break; case CHIP_ID_185x_PG10: wl1271_warning("chip id 0x%x (185x PG10) is deprecated", wl->chip.id); ret = -ENODEV; goto out; default: wl1271_warning("unsupported chip id: 0x%x", wl->chip.id); ret = -ENODEV; goto out; } wl->scan_templ_id_2_4 = CMD_TEMPL_CFG_PROBE_REQ_2_4; wl->scan_templ_id_5 = CMD_TEMPL_CFG_PROBE_REQ_5; wl->sched_scan_templ_id_2_4 = CMD_TEMPL_PROBE_REQ_2_4_PERIODIC; wl->sched_scan_templ_id_5 = CMD_TEMPL_PROBE_REQ_5_PERIODIC; wl->max_channels_5 = WL18XX_MAX_CHANNELS_5GHZ; wl->ba_rx_session_count_max = WL18XX_RX_BA_MAX_SESSIONS; out: return ret; } static int wl18xx_set_clk(struct wl1271 *wl) { u16 clk_freq; int ret; ret = wlcore_set_partition(wl, &wl->ptable[PART_TOP_PRCM_ELP_SOC]); if (ret < 0) goto out; /* TODO: PG2: apparently we need to read the clk type */ ret = wl18xx_top_reg_read(wl, PRIMARY_CLK_DETECT, &clk_freq); if (ret < 0) goto out; wl1271_debug(DEBUG_BOOT, "clock freq %d (%d, %d, %d, %d, %s)", clk_freq, wl18xx_clk_table[clk_freq].n, wl18xx_clk_table[clk_freq].m, wl18xx_clk_table[clk_freq].p, wl18xx_clk_table[clk_freq].q, wl18xx_clk_table[clk_freq].swallow ? "swallow" : "spit"); ret = wl18xx_top_reg_write(wl, PLLSH_WCS_PLL_N, wl18xx_clk_table[clk_freq].n); if (ret < 0) goto out; ret = wl18xx_top_reg_write(wl, PLLSH_WCS_PLL_M, wl18xx_clk_table[clk_freq].m); if (ret < 0) goto out; if (wl18xx_clk_table[clk_freq].swallow) { /* first the 16 lower bits */ ret = wl18xx_top_reg_write(wl, PLLSH_WCS_PLL_Q_FACTOR_CFG_1, wl18xx_clk_table[clk_freq].q & PLLSH_WCS_PLL_Q_FACTOR_CFG_1_MASK); if (ret < 0) goto out; /* then the 16 higher bits, masked out */ ret = wl18xx_top_reg_write(wl, PLLSH_WCS_PLL_Q_FACTOR_CFG_2, (wl18xx_clk_table[clk_freq].q >> 16) & PLLSH_WCS_PLL_Q_FACTOR_CFG_2_MASK); if (ret < 0) goto out; /* first the 16 lower bits */ ret = wl18xx_top_reg_write(wl, PLLSH_WCS_PLL_P_FACTOR_CFG_1, wl18xx_clk_table[clk_freq].p & PLLSH_WCS_PLL_P_FACTOR_CFG_1_MASK); if (ret < 0) goto out; /* then the 16 higher bits, masked out */ ret = wl18xx_top_reg_write(wl, PLLSH_WCS_PLL_P_FACTOR_CFG_2, (wl18xx_clk_table[clk_freq].p >> 16) & PLLSH_WCS_PLL_P_FACTOR_CFG_2_MASK); } else { ret = wl18xx_top_reg_write(wl, PLLSH_WCS_PLL_SWALLOW_EN, PLLSH_WCS_PLL_SWALLOW_EN_VAL2); } out: return ret; } static int wl18xx_boot_soft_reset(struct wl1271 *wl) { int ret; /* disable Rx/Tx */ ret = wlcore_write32(wl, WL18XX_ENABLE, 0x0); if (ret < 0) goto out; /* disable auto calibration on start*/ ret = wlcore_write32(wl, WL18XX_SPARE_A2, 0xffff); out: return ret; } static int wl18xx_pre_boot(struct wl1271 *wl) { int ret; ret = wl18xx_set_clk(wl); if (ret < 0) goto out; /* Continue the ELP wake up sequence */ ret = wlcore_write32(wl, WL18XX_WELP_ARM_COMMAND, WELP_ARM_COMMAND_VAL); if (ret < 0) goto out; udelay(500); ret = wlcore_set_partition(wl, &wl->ptable[PART_BOOT]); if (ret < 0) goto out; /* Disable interrupts */ ret = wlcore_write_reg(wl, REG_INTERRUPT_MASK, WL1271_ACX_INTR_ALL); if (ret < 0) goto out; ret = wl18xx_boot_soft_reset(wl); out: return ret; } static int wl18xx_pre_upload(struct wl1271 *wl) { u32 tmp; int ret; ret = wlcore_set_partition(wl, &wl->ptable[PART_BOOT]); if (ret < 0) goto out; /* TODO: check if this is all needed */ ret = wlcore_write32(wl, WL18XX_EEPROMLESS_IND, WL18XX_EEPROMLESS_IND); if (ret < 0) goto out; ret = wlcore_read_reg(wl, REG_CHIP_ID_B, &tmp); if (ret < 0) goto out; wl1271_debug(DEBUG_BOOT, "chip id 0x%x", tmp); ret = wlcore_read32(wl, WL18XX_SCR_PAD2, &tmp); out: return ret; } static int wl18xx_set_mac_and_phy(struct wl1271 *wl) { struct wl18xx_priv *priv = wl->priv; struct wl18xx_mac_and_phy_params *params; int ret; params = kmemdup(&priv->conf.phy, sizeof(*params), GFP_KERNEL); if (!params) { ret = -ENOMEM; goto out; } ret = wlcore_set_partition(wl, &wl->ptable[PART_PHY_INIT]); if (ret < 0) goto out; ret = wlcore_write(wl, WL18XX_PHY_INIT_MEM_ADDR, params, sizeof(*params), false); out: kfree(params); return ret; } static int wl18xx_enable_interrupts(struct wl1271 *wl) { u32 event_mask, intr_mask; int ret; event_mask = WL18XX_ACX_EVENTS_VECTOR; intr_mask = WL18XX_INTR_MASK; ret = wlcore_write_reg(wl, REG_INTERRUPT_MASK, event_mask); if (ret < 0) goto out; wlcore_enable_interrupts(wl); ret = wlcore_write_reg(wl, REG_INTERRUPT_MASK, WL1271_ACX_INTR_ALL & ~intr_mask); if (ret < 0) goto disable_interrupts; return ret; disable_interrupts: wlcore_disable_interrupts(wl); out: return ret; } static int wl18xx_boot(struct wl1271 *wl) { int ret; ret = wl18xx_pre_boot(wl); if (ret < 0) goto out; ret = wl18xx_pre_upload(wl); if (ret < 0) goto out; ret = wlcore_boot_upload_firmware(wl); if (ret < 0) goto out; ret = wl18xx_set_mac_and_phy(wl); if (ret < 0) goto out; wl->event_mask = BSS_LOSS_EVENT_ID | SCAN_COMPLETE_EVENT_ID | RSSI_SNR_TRIGGER_0_EVENT_ID | PERIODIC_SCAN_COMPLETE_EVENT_ID | PERIODIC_SCAN_REPORT_EVENT_ID | DUMMY_PACKET_EVENT_ID | PEER_REMOVE_COMPLETE_EVENT_ID | BA_SESSION_RX_CONSTRAINT_EVENT_ID | REMAIN_ON_CHANNEL_COMPLETE_EVENT_ID | INACTIVE_STA_EVENT_ID | MAX_TX_FAILURE_EVENT_ID | CHANNEL_SWITCH_COMPLETE_EVENT_ID | DFS_CHANNELS_CONFIG_COMPLETE_EVENT; ret = wlcore_boot_run_firmware(wl); if (ret < 0) goto out; ret = wl18xx_enable_interrupts(wl); out: return ret; } static int wl18xx_trigger_cmd(struct wl1271 *wl, int cmd_box_addr, void *buf, size_t len) { struct wl18xx_priv *priv = wl->priv; memcpy(priv->cmd_buf, buf, len); memset(priv->cmd_buf + len, 0, WL18XX_CMD_MAX_SIZE - len); return wlcore_write(wl, cmd_box_addr, priv->cmd_buf, WL18XX_CMD_MAX_SIZE, false); } static int wl18xx_ack_event(struct wl1271 *wl) { return wlcore_write_reg(wl, REG_INTERRUPT_TRIG, WL18XX_INTR_TRIG_EVENT_ACK); } static u32 wl18xx_calc_tx_blocks(struct wl1271 *wl, u32 len, u32 spare_blks) { u32 blk_size = WL18XX_TX_HW_BLOCK_SIZE; return (len + blk_size - 1) / blk_size + spare_blks; } static void wl18xx_set_tx_desc_blocks(struct wl1271 *wl, struct wl1271_tx_hw_descr *desc, u32 blks, u32 spare_blks) { desc->wl18xx_mem.total_mem_blocks = blks; } static void wl18xx_set_tx_desc_data_len(struct wl1271 *wl, struct wl1271_tx_hw_descr *desc, struct sk_buff *skb) { desc->length = cpu_to_le16(skb->len); /* if only the last frame is to be padded, we unset this bit on Tx */ if (wl->quirks & WLCORE_QUIRK_TX_PAD_LAST_FRAME) desc->wl18xx_mem.ctrl = WL18XX_TX_CTRL_NOT_PADDED; else desc->wl18xx_mem.ctrl = 0; wl1271_debug(DEBUG_TX, "tx_fill_hdr: hlid: %d " "len: %d life: %d mem: %d", desc->hlid, le16_to_cpu(desc->length), le16_to_cpu(desc->life_time), desc->wl18xx_mem.total_mem_blocks); } static enum wl_rx_buf_align wl18xx_get_rx_buf_align(struct wl1271 *wl, u32 rx_desc) { if (rx_desc & RX_BUF_PADDED_PAYLOAD) return WLCORE_RX_BUF_PADDED; return WLCORE_RX_BUF_ALIGNED; } static u32 wl18xx_get_rx_packet_len(struct wl1271 *wl, void *rx_data, u32 data_len) { struct wl1271_rx_descriptor *desc = rx_data; /* invalid packet */ if (data_len < sizeof(*desc)) return 0; return data_len - sizeof(*desc); } static void wl18xx_tx_immediate_completion(struct wl1271 *wl) { wl18xx_tx_immediate_complete(wl); } static int wl18xx_set_host_cfg_bitmap(struct wl1271 *wl, u32 extra_mem_blk) { int ret; u32 sdio_align_size = 0; u32 host_cfg_bitmap = HOST_IF_CFG_RX_FIFO_ENABLE | HOST_IF_CFG_ADD_RX_ALIGNMENT; /* Enable Tx SDIO padding */ if (wl->quirks & WLCORE_QUIRK_TX_BLOCKSIZE_ALIGN) { host_cfg_bitmap |= HOST_IF_CFG_TX_PAD_TO_SDIO_BLK; sdio_align_size = WL12XX_BUS_BLOCK_SIZE; } /* Enable Rx SDIO padding */ if (wl->quirks & WLCORE_QUIRK_RX_BLOCKSIZE_ALIGN) { host_cfg_bitmap |= HOST_IF_CFG_RX_PAD_TO_SDIO_BLK; sdio_align_size = WL12XX_BUS_BLOCK_SIZE; } ret = wl18xx_acx_host_if_cfg_bitmap(wl, host_cfg_bitmap, sdio_align_size, extra_mem_blk, WL18XX_HOST_IF_LEN_SIZE_FIELD); if (ret < 0) return ret; return 0; } static int wl18xx_hw_init(struct wl1271 *wl) { int ret; struct wl18xx_priv *priv = wl->priv; /* (re)init private structures. Relevant on recovery as well. */ priv->last_fw_rls_idx = 0; priv->extra_spare_key_count = 0; /* set the default amount of spare blocks in the bitmap */ ret = wl18xx_set_host_cfg_bitmap(wl, WL18XX_TX_HW_BLOCK_SPARE); if (ret < 0) return ret; if (checksum_param) { ret = wl18xx_acx_set_checksum_state(wl); if (ret != 0) return ret; } return ret; } static void wl18xx_set_tx_desc_csum(struct wl1271 *wl, struct wl1271_tx_hw_descr *desc, struct sk_buff *skb) { u32 ip_hdr_offset; struct iphdr *ip_hdr; if (!checksum_param) { desc->wl18xx_checksum_data = 0; return; } if (skb->ip_summed != CHECKSUM_PARTIAL) { desc->wl18xx_checksum_data = 0; return; } ip_hdr_offset = skb_network_header(skb) - skb_mac_header(skb); if (WARN_ON(ip_hdr_offset >= (1<<7))) { desc->wl18xx_checksum_data = 0; return; } desc->wl18xx_checksum_data = ip_hdr_offset << 1; /* FW is interested only in the LSB of the protocol TCP=0 UDP=1 */ ip_hdr = (void *)skb_network_header(skb); desc->wl18xx_checksum_data |= (ip_hdr->protocol & 0x01); } static void wl18xx_set_rx_csum(struct wl1271 *wl, struct wl1271_rx_descriptor *desc, struct sk_buff *skb) { if (desc->status & WL18XX_RX_CHECKSUM_MASK) skb->ip_summed = CHECKSUM_UNNECESSARY; } static bool wl18xx_is_mimo_supported(struct wl1271 *wl) { struct wl18xx_priv *priv = wl->priv; /* only support MIMO with multiple antennas, and when SISO * is not forced through config */ return (priv->conf.phy.number_of_assembled_ant2_4 >= 2) && (priv->conf.ht.mode != HT_MODE_WIDE) && (priv->conf.ht.mode != HT_MODE_SISO20); } /* * TODO: instead of having these two functions to get the rate mask, * we should modify the wlvif->rate_set instead */ static u32 wl18xx_sta_get_ap_rate_mask(struct wl1271 *wl, struct wl12xx_vif *wlvif) { u32 hw_rate_set = wlvif->rate_set; if (wlvif->channel_type == NL80211_CHAN_HT40MINUS || wlvif->channel_type == NL80211_CHAN_HT40PLUS) { wl1271_debug(DEBUG_ACX, "using wide channel rate mask"); hw_rate_set |= CONF_TX_RATE_USE_WIDE_CHAN; /* we don't support MIMO in wide-channel mode */ hw_rate_set &= ~CONF_TX_MIMO_RATES; } else if (wl18xx_is_mimo_supported(wl)) { wl1271_debug(DEBUG_ACX, "using MIMO channel rate mask"); hw_rate_set |= CONF_TX_MIMO_RATES; } return hw_rate_set; } static u32 wl18xx_ap_get_mimo_wide_rate_mask(struct wl1271 *wl, struct wl12xx_vif *wlvif) { if (wlvif->channel_type == NL80211_CHAN_HT40MINUS || wlvif->channel_type == NL80211_CHAN_HT40PLUS) { wl1271_debug(DEBUG_ACX, "using wide channel rate mask"); /* sanity check - we don't support this */ if (WARN_ON(wlvif->band != IEEE80211_BAND_5GHZ)) return 0; return CONF_TX_RATE_USE_WIDE_CHAN; } else if (wl18xx_is_mimo_supported(wl) && wlvif->band == IEEE80211_BAND_2GHZ) { wl1271_debug(DEBUG_ACX, "using MIMO rate mask"); /* * we don't care about HT channel here - if a peer doesn't * support MIMO, we won't enable it in its rates */ return CONF_TX_MIMO_RATES; } else { return 0; } } static int wl18xx_get_pg_ver(struct wl1271 *wl, s8 *ver) { u32 fuse; s8 rom = 0, metal = 0, pg_ver = 0, rdl_ver = 0; int ret; ret = wlcore_set_partition(wl, &wl->ptable[PART_TOP_PRCM_ELP_SOC]); if (ret < 0) goto out; ret = wlcore_read32(wl, WL18XX_REG_FUSE_DATA_1_3, &fuse); if (ret < 0) goto out; pg_ver = (fuse & WL18XX_PG_VER_MASK) >> WL18XX_PG_VER_OFFSET; rom = (fuse & WL18XX_ROM_VER_MASK) >> WL18XX_ROM_VER_OFFSET; if (rom <= 0xE) metal = (fuse & WL18XX_METAL_VER_MASK) >> WL18XX_METAL_VER_OFFSET; else metal = (fuse & WL18XX_NEW_METAL_VER_MASK) >> WL18XX_NEW_METAL_VER_OFFSET; ret = wlcore_read32(wl, WL18XX_REG_FUSE_DATA_2_3, &fuse); if (ret < 0) goto out; rdl_ver = (fuse & WL18XX_RDL_VER_MASK) >> WL18XX_RDL_VER_OFFSET; if (rdl_ver > RDL_MAX) rdl_ver = RDL_NONE; wl1271_info("wl18xx HW: RDL %d, %s, PG %x.%x (ROM %x)", rdl_ver, rdl_names[rdl_ver], pg_ver, metal, rom); if (ver) *ver = pg_ver; ret = wlcore_set_partition(wl, &wl->ptable[PART_BOOT]); out: return ret; } #define WL18XX_CONF_FILE_NAME "ti-connectivity/wl18xx-conf.bin" static int wl18xx_conf_init(struct wl1271 *wl, struct device *dev) { struct wl18xx_priv *priv = wl->priv; struct wlcore_conf_file *conf_file; const struct firmware *fw; int ret; ret = request_firmware(&fw, WL18XX_CONF_FILE_NAME, dev); if (ret < 0) { wl1271_error("could not get configuration binary %s: %d", WL18XX_CONF_FILE_NAME, ret); goto out_fallback; } if (fw->size != WL18XX_CONF_SIZE) { wl1271_error("configuration binary file size is wrong, expected %zu got %zu", WL18XX_CONF_SIZE, fw->size); ret = -EINVAL; goto out; } conf_file = (struct wlcore_conf_file *) fw->data; if (conf_file->header.magic != cpu_to_le32(WL18XX_CONF_MAGIC)) { wl1271_error("configuration binary file magic number mismatch, " "expected 0x%0x got 0x%0x", WL18XX_CONF_MAGIC, conf_file->header.magic); ret = -EINVAL; goto out; } if (conf_file->header.version != cpu_to_le32(WL18XX_CONF_VERSION)) { wl1271_error("configuration binary file version not supported, " "expected 0x%08x got 0x%08x", WL18XX_CONF_VERSION, conf_file->header.version); ret = -EINVAL; goto out; } memcpy(&wl->conf, &conf_file->core, sizeof(wl18xx_conf)); memcpy(&priv->conf, &conf_file->priv, sizeof(priv->conf)); goto out; out_fallback: wl1271_warning("falling back to default config"); /* apply driver default configuration */ memcpy(&wl->conf, &wl18xx_conf, sizeof(wl18xx_conf)); /* apply default private configuration */ memcpy(&priv->conf, &wl18xx_default_priv_conf, sizeof(priv->conf)); /* For now we just fallback */ return 0; out: release_firmware(fw); return ret; } static int wl18xx_plt_init(struct wl1271 *wl) { int ret; /* calibrator based auto/fem detect not supported for 18xx */ if (wl->plt_mode == PLT_FEM_DETECT) { wl1271_error("wl18xx_plt_init: PLT FEM_DETECT not supported"); return -EINVAL; } ret = wlcore_write32(wl, WL18XX_SCR_PAD8, WL18XX_SCR_PAD8_PLT); if (ret < 0) return ret; return wl->ops->boot(wl); } static int wl18xx_get_mac(struct wl1271 *wl) { u32 mac1, mac2; int ret; ret = wlcore_set_partition(wl, &wl->ptable[PART_TOP_PRCM_ELP_SOC]); if (ret < 0) goto out; ret = wlcore_read32(wl, WL18XX_REG_FUSE_BD_ADDR_1, &mac1); if (ret < 0) goto out; ret = wlcore_read32(wl, WL18XX_REG_FUSE_BD_ADDR_2, &mac2); if (ret < 0) goto out; /* these are the two parts of the BD_ADDR */ wl->fuse_oui_addr = ((mac2 & 0xffff) << 8) + ((mac1 & 0xff000000) >> 24); wl->fuse_nic_addr = (mac1 & 0xffffff); ret = wlcore_set_partition(wl, &wl->ptable[PART_DOWN]); out: return ret; } static int wl18xx_handle_static_data(struct wl1271 *wl, struct wl1271_static_data *static_data) { struct wl18xx_static_data_priv *static_data_priv = (struct wl18xx_static_data_priv *) static_data->priv; strncpy(wl->chip.phy_fw_ver_str, static_data_priv->phy_version, sizeof(wl->chip.phy_fw_ver_str)); /* make sure the string is NULL-terminated */ wl->chip.phy_fw_ver_str[sizeof(wl->chip.phy_fw_ver_str) - 1] = '\0'; wl1271_info("PHY firmware version: %s", static_data_priv->phy_version); return 0; } static int wl18xx_get_spare_blocks(struct wl1271 *wl, bool is_gem) { struct wl18xx_priv *priv = wl->priv; /* If we have keys requiring extra spare, indulge them */ if (priv->extra_spare_key_count) return WL18XX_TX_HW_EXTRA_BLOCK_SPARE; return WL18XX_TX_HW_BLOCK_SPARE; } static int wl18xx_set_key(struct wl1271 *wl, enum set_key_cmd cmd, struct ieee80211_vif *vif, struct ieee80211_sta *sta, struct ieee80211_key_conf *key_conf) { struct wl18xx_priv *priv = wl->priv; bool change_spare = false, special_enc; int ret; wl1271_debug(DEBUG_CRYPT, "extra spare keys before: %d", priv->extra_spare_key_count); special_enc = key_conf->cipher == WL1271_CIPHER_SUITE_GEM || key_conf->cipher == WLAN_CIPHER_SUITE_TKIP; ret = wlcore_set_key(wl, cmd, vif, sta, key_conf); if (ret < 0) goto out; /* * when adding the first or removing the last GEM/TKIP key, * we have to adjust the number of spare blocks. */ if (special_enc) { if (cmd == SET_KEY) { /* first key */ change_spare = (priv->extra_spare_key_count == 0); priv->extra_spare_key_count++; } else if (cmd == DISABLE_KEY) { /* last key */ change_spare = (priv->extra_spare_key_count == 1); priv->extra_spare_key_count--; } } wl1271_debug(DEBUG_CRYPT, "extra spare keys after: %d", priv->extra_spare_key_count); if (!change_spare) goto out; /* key is now set, change the spare blocks */ if (priv->extra_spare_key_count) ret = wl18xx_set_host_cfg_bitmap(wl, WL18XX_TX_HW_EXTRA_BLOCK_SPARE); else ret = wl18xx_set_host_cfg_bitmap(wl, WL18XX_TX_HW_BLOCK_SPARE); out: return ret; } static u32 wl18xx_pre_pkt_send(struct wl1271 *wl, u32 buf_offset, u32 last_len) { if (wl->quirks & WLCORE_QUIRK_TX_PAD_LAST_FRAME) { struct wl1271_tx_hw_descr *last_desc; /* get the last TX HW descriptor written to the aggr buf */ last_desc = (struct wl1271_tx_hw_descr *)(wl->aggr_buf + buf_offset - last_len); /* the last frame is padded up to an SDIO block */ last_desc->wl18xx_mem.ctrl &= ~WL18XX_TX_CTRL_NOT_PADDED; return ALIGN(buf_offset, WL12XX_BUS_BLOCK_SIZE); } /* no modifications */ return buf_offset; } static void wl18xx_sta_rc_update(struct wl1271 *wl, struct wl12xx_vif *wlvif, struct ieee80211_sta *sta, u32 changed) { bool wide = sta->bandwidth >= IEEE80211_STA_RX_BW_40; wl1271_debug(DEBUG_MAC80211, "mac80211 sta_rc_update wide %d", wide); if (!(changed & IEEE80211_RC_BW_CHANGED)) return; mutex_lock(&wl->mutex); /* sanity */ if (WARN_ON(wlvif->bss_type != BSS_TYPE_STA_BSS)) goto out; /* ignore the change before association */ if (!test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags)) goto out; /* * If we started out as wide, we can change the operation mode. If we * thought this was a 20mhz AP, we have to reconnect */ if (wlvif->sta.role_chan_type == NL80211_CHAN_HT40MINUS || wlvif->sta.role_chan_type == NL80211_CHAN_HT40PLUS) wl18xx_acx_peer_ht_operation_mode(wl, wlvif->sta.hlid, wide); else ieee80211_connection_loss(wl12xx_wlvif_to_vif(wlvif)); out: mutex_unlock(&wl->mutex); } static int wl18xx_set_peer_cap(struct wl1271 *wl, struct ieee80211_sta_ht_cap *ht_cap, bool allow_ht_operation, u32 rate_set, u8 hlid) { return wl18xx_acx_set_peer_cap(wl, ht_cap, allow_ht_operation, rate_set, hlid); } static bool wl18xx_lnk_high_prio(struct wl1271 *wl, u8 hlid, struct wl1271_link *lnk) { u8 thold; struct wl18xx_fw_status_priv *status_priv = (struct wl18xx_fw_status_priv *)wl->fw_status_2->priv; u32 suspend_bitmap = le32_to_cpu(status_priv->link_suspend_bitmap); /* suspended links are never high priority */ if (test_bit(hlid, (unsigned long *)&suspend_bitmap)) return false; /* the priority thresholds are taken from FW */ if (test_bit(hlid, (unsigned long *)&wl->fw_fast_lnk_map) && !test_bit(hlid, (unsigned long *)&wl->ap_fw_ps_map)) thold = status_priv->tx_fast_link_prio_threshold; else thold = status_priv->tx_slow_link_prio_threshold; return lnk->allocated_pkts < thold; } static bool wl18xx_lnk_low_prio(struct wl1271 *wl, u8 hlid, struct wl1271_link *lnk) { u8 thold; struct wl18xx_fw_status_priv *status_priv = (struct wl18xx_fw_status_priv *)wl->fw_status_2->priv; u32 suspend_bitmap = le32_to_cpu(status_priv->link_suspend_bitmap); if (test_bit(hlid, (unsigned long *)&suspend_bitmap)) thold = status_priv->tx_suspend_threshold; else if (test_bit(hlid, (unsigned long *)&wl->fw_fast_lnk_map) && !test_bit(hlid, (unsigned long *)&wl->ap_fw_ps_map)) thold = status_priv->tx_fast_stop_threshold; else thold = status_priv->tx_slow_stop_threshold; return lnk->allocated_pkts < thold; } static int wl18xx_setup(struct wl1271 *wl); static struct wlcore_ops wl18xx_ops = { .setup = wl18xx_setup, .identify_chip = wl18xx_identify_chip, .boot = wl18xx_boot, .plt_init = wl18xx_plt_init, .trigger_cmd = wl18xx_trigger_cmd, .ack_event = wl18xx_ack_event, .wait_for_event = wl18xx_wait_for_event, .process_mailbox_events = wl18xx_process_mailbox_events, .calc_tx_blocks = wl18xx_calc_tx_blocks, .set_tx_desc_blocks = wl18xx_set_tx_desc_blocks, .set_tx_desc_data_len = wl18xx_set_tx_desc_data_len, .get_rx_buf_align = wl18xx_get_rx_buf_align, .get_rx_packet_len = wl18xx_get_rx_packet_len, .tx_immediate_compl = wl18xx_tx_immediate_completion, .tx_delayed_compl = NULL, .hw_init = wl18xx_hw_init, .set_tx_desc_csum = wl18xx_set_tx_desc_csum, .get_pg_ver = wl18xx_get_pg_ver, .set_rx_csum = wl18xx_set_rx_csum, .sta_get_ap_rate_mask = wl18xx_sta_get_ap_rate_mask, .ap_get_mimo_wide_rate_mask = wl18xx_ap_get_mimo_wide_rate_mask, .get_mac = wl18xx_get_mac, .debugfs_init = wl18xx_debugfs_add_files, .scan_start = wl18xx_scan_start, .scan_stop = wl18xx_scan_stop, .sched_scan_start = wl18xx_sched_scan_start, .sched_scan_stop = wl18xx_scan_sched_scan_stop, .handle_static_data = wl18xx_handle_static_data, .get_spare_blocks = wl18xx_get_spare_blocks, .set_key = wl18xx_set_key, .channel_switch = wl18xx_cmd_channel_switch, .pre_pkt_send = wl18xx_pre_pkt_send, .sta_rc_update = wl18xx_sta_rc_update, .set_peer_cap = wl18xx_set_peer_cap, .lnk_high_prio = wl18xx_lnk_high_prio, .lnk_low_prio = wl18xx_lnk_low_prio, }; /* HT cap appropriate for wide channels in 2Ghz */ static struct ieee80211_sta_ht_cap wl18xx_siso40_ht_cap_2ghz = { .cap = IEEE80211_HT_CAP_SGI_20 | IEEE80211_HT_CAP_SGI_40 | IEEE80211_HT_CAP_SUP_WIDTH_20_40 | IEEE80211_HT_CAP_DSSSCCK40 | IEEE80211_HT_CAP_GRN_FLD, .ht_supported = true, .ampdu_factor = IEEE80211_HT_MAX_AMPDU_16K, .ampdu_density = IEEE80211_HT_MPDU_DENSITY_16, .mcs = { .rx_mask = { 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, }, .rx_highest = cpu_to_le16(150), .tx_params = IEEE80211_HT_MCS_TX_DEFINED, }, }; /* HT cap appropriate for wide channels in 5Ghz */ static struct ieee80211_sta_ht_cap wl18xx_siso40_ht_cap_5ghz = { .cap = IEEE80211_HT_CAP_SGI_20 | IEEE80211_HT_CAP_SGI_40 | IEEE80211_HT_CAP_SUP_WIDTH_20_40 | IEEE80211_HT_CAP_GRN_FLD, .ht_supported = true, .ampdu_factor = IEEE80211_HT_MAX_AMPDU_16K, .ampdu_density = IEEE80211_HT_MPDU_DENSITY_16, .mcs = { .rx_mask = { 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, }, .rx_highest = cpu_to_le16(150), .tx_params = IEEE80211_HT_MCS_TX_DEFINED, }, }; /* HT cap appropriate for SISO 20 */ static struct ieee80211_sta_ht_cap wl18xx_siso20_ht_cap = { .cap = IEEE80211_HT_CAP_SGI_20 | IEEE80211_HT_CAP_GRN_FLD, .ht_supported = true, .ampdu_factor = IEEE80211_HT_MAX_AMPDU_16K, .ampdu_density = IEEE80211_HT_MPDU_DENSITY_16, .mcs = { .rx_mask = { 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, }, .rx_highest = cpu_to_le16(72), .tx_params = IEEE80211_HT_MCS_TX_DEFINED, }, }; /* HT cap appropriate for MIMO rates in 20mhz channel */ static struct ieee80211_sta_ht_cap wl18xx_mimo_ht_cap_2ghz = { .cap = IEEE80211_HT_CAP_SGI_20 | IEEE80211_HT_CAP_GRN_FLD, .ht_supported = true, .ampdu_factor = IEEE80211_HT_MAX_AMPDU_16K, .ampdu_density = IEEE80211_HT_MPDU_DENSITY_16, .mcs = { .rx_mask = { 0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, }, .rx_highest = cpu_to_le16(144), .tx_params = IEEE80211_HT_MCS_TX_DEFINED, }, }; static int wl18xx_setup(struct wl1271 *wl) { struct wl18xx_priv *priv = wl->priv; int ret; wl->rtable = wl18xx_rtable; wl->num_tx_desc = WL18XX_NUM_TX_DESCRIPTORS; wl->num_rx_desc = WL18XX_NUM_RX_DESCRIPTORS; wl->num_channels = 2; wl->num_mac_addr = WL18XX_NUM_MAC_ADDRESSES; wl->band_rate_to_idx = wl18xx_band_rate_to_idx; wl->hw_tx_rate_tbl_size = WL18XX_CONF_HW_RXTX_RATE_MAX; wl->hw_min_ht_rate = WL18XX_CONF_HW_RXTX_RATE_MCS0; wl->fw_status_priv_len = sizeof(struct wl18xx_fw_status_priv); wl->stats.fw_stats_len = sizeof(struct wl18xx_acx_statistics); wl->static_data_priv_len = sizeof(struct wl18xx_static_data_priv); if (num_rx_desc_param != -1) wl->num_rx_desc = num_rx_desc_param; ret = wl18xx_conf_init(wl, wl->dev); if (ret < 0) return ret; /* If the module param is set, update it in conf */ if (board_type_param) { if (!strcmp(board_type_param, "fpga")) { priv->conf.phy.board_type = BOARD_TYPE_FPGA_18XX; } else if (!strcmp(board_type_param, "hdk")) { priv->conf.phy.board_type = BOARD_TYPE_HDK_18XX; } else if (!strcmp(board_type_param, "dvp")) { priv->conf.phy.board_type = BOARD_TYPE_DVP_18XX; } else if (!strcmp(board_type_param, "evb")) { priv->conf.phy.board_type = BOARD_TYPE_EVB_18XX; } else if (!strcmp(board_type_param, "com8")) { priv->conf.phy.board_type = BOARD_TYPE_COM8_18XX; } else { wl1271_error("invalid board type '%s'", board_type_param); return -EINVAL; } } if (priv->conf.phy.board_type >= NUM_BOARD_TYPES) { wl1271_error("invalid board type '%d'", priv->conf.phy.board_type); return -EINVAL; } if (low_band_component_param != -1) priv->conf.phy.low_band_component = low_band_component_param; if (low_band_component_type_param != -1) priv->conf.phy.low_band_component_type = low_band_component_type_param; if (high_band_component_param != -1) priv->conf.phy.high_band_component = high_band_component_param; if (high_band_component_type_param != -1) priv->conf.phy.high_band_component_type = high_band_component_type_param; if (pwr_limit_reference_11_abg_param != -1) priv->conf.phy.pwr_limit_reference_11_abg = pwr_limit_reference_11_abg_param; if (n_antennas_2_param != -1) priv->conf.phy.number_of_assembled_ant2_4 = n_antennas_2_param; if (n_antennas_5_param != -1) priv->conf.phy.number_of_assembled_ant5 = n_antennas_5_param; if (dc2dc_param != -1) priv->conf.phy.external_pa_dc2dc = dc2dc_param; if (ht_mode_param) { if (!strcmp(ht_mode_param, "default")) priv->conf.ht.mode = HT_MODE_DEFAULT; else if (!strcmp(ht_mode_param, "wide")) priv->conf.ht.mode = HT_MODE_WIDE; else if (!strcmp(ht_mode_param, "siso20")) priv->conf.ht.mode = HT_MODE_SISO20; else { wl1271_error("invalid ht_mode '%s'", ht_mode_param); return -EINVAL; } } if (priv->conf.ht.mode == HT_MODE_DEFAULT) { /* * Only support mimo with multiple antennas. Fall back to * siso40. */ if (wl18xx_is_mimo_supported(wl)) wlcore_set_ht_cap(wl, IEEE80211_BAND_2GHZ, &wl18xx_mimo_ht_cap_2ghz); else wlcore_set_ht_cap(wl, IEEE80211_BAND_2GHZ, &wl18xx_siso40_ht_cap_2ghz); /* 5Ghz is always wide */ wlcore_set_ht_cap(wl, IEEE80211_BAND_5GHZ, &wl18xx_siso40_ht_cap_5ghz); } else if (priv->conf.ht.mode == HT_MODE_WIDE) { wlcore_set_ht_cap(wl, IEEE80211_BAND_2GHZ, &wl18xx_siso40_ht_cap_2ghz); wlcore_set_ht_cap(wl, IEEE80211_BAND_5GHZ, &wl18xx_siso40_ht_cap_5ghz); } else if (priv->conf.ht.mode == HT_MODE_SISO20) { wlcore_set_ht_cap(wl, IEEE80211_BAND_2GHZ, &wl18xx_siso20_ht_cap); wlcore_set_ht_cap(wl, IEEE80211_BAND_5GHZ, &wl18xx_siso20_ht_cap); } if (!checksum_param) { wl18xx_ops.set_rx_csum = NULL; wl18xx_ops.init_vif = NULL; } /* Enable 11a Band only if we have 5G antennas */ wl->enable_11a = (priv->conf.phy.number_of_assembled_ant5 != 0); return 0; } static int wl18xx_probe(struct platform_device *pdev) { struct wl1271 *wl; struct ieee80211_hw *hw; int ret; hw = wlcore_alloc_hw(sizeof(struct wl18xx_priv), WL18XX_AGGR_BUFFER_SIZE, sizeof(struct wl18xx_event_mailbox)); if (IS_ERR(hw)) { wl1271_error("can't allocate hw"); ret = PTR_ERR(hw); goto out; } wl = hw->priv; wl->ops = &wl18xx_ops; wl->ptable = wl18xx_ptable; ret = wlcore_probe(wl, pdev); if (ret) goto out_free; return ret; out_free: wlcore_free_hw(wl); out: return ret; } static const struct platform_device_id wl18xx_id_table[] = { { "wl18xx", 0 }, { } /* Terminating Entry */ }; MODULE_DEVICE_TABLE(platform, wl18xx_id_table); static struct platform_driver wl18xx_driver = { .probe = wl18xx_probe, .remove = wlcore_remove, .id_table = wl18xx_id_table, .driver = { .name = "wl18xx_driver", .owner = THIS_MODULE, } }; module_platform_driver(wl18xx_driver); module_param_named(ht_mode, ht_mode_param, charp, S_IRUSR); MODULE_PARM_DESC(ht_mode, "Force HT mode: wide or siso20"); module_param_named(board_type, board_type_param, charp, S_IRUSR); MODULE_PARM_DESC(board_type, "Board type: fpga, hdk (default), evb, com8 or " "dvp"); module_param_named(checksum, checksum_param, bool, S_IRUSR); MODULE_PARM_DESC(checksum, "Enable TCP checksum: boolean (defaults to false)"); module_param_named(dc2dc, dc2dc_param, int, S_IRUSR); MODULE_PARM_DESC(dc2dc, "External DC2DC: u8 (defaults to 0)"); module_param_named(n_antennas_2, n_antennas_2_param, int, S_IRUSR); MODULE_PARM_DESC(n_antennas_2, "Number of installed 2.4GHz antennas: 1 (default) or 2"); module_param_named(n_antennas_5, n_antennas_5_param, int, S_IRUSR); MODULE_PARM_DESC(n_antennas_5, "Number of installed 5GHz antennas: 1 (default) or 2"); module_param_named(low_band_component, low_band_component_param, int, S_IRUSR); MODULE_PARM_DESC(low_band_component, "Low band component: u8 " "(default is 0x01)"); module_param_named(low_band_component_type, low_band_component_type_param, int, S_IRUSR); MODULE_PARM_DESC(low_band_component_type, "Low band component type: u8 " "(default is 0x05 or 0x06 depending on the board_type)"); module_param_named(high_band_component, high_band_component_param, int, S_IRUSR); MODULE_PARM_DESC(high_band_component, "High band component: u8, " "(default is 0x01)"); module_param_named(high_band_component_type, high_band_component_type_param, int, S_IRUSR); MODULE_PARM_DESC(high_band_component_type, "High band component type: u8 " "(default is 0x09)"); module_param_named(pwr_limit_reference_11_abg, pwr_limit_reference_11_abg_param, int, S_IRUSR); MODULE_PARM_DESC(pwr_limit_reference_11_abg, "Power limit reference: u8 " "(default is 0xc8)"); module_param_named(num_rx_desc, num_rx_desc_param, int, S_IRUSR); MODULE_PARM_DESC(num_rx_desc_param, "Number of Rx descriptors: u8 (default is 32)"); MODULE_LICENSE("GPL v2"); MODULE_AUTHOR("Luciano Coelho <coelho@ti.com>"); MODULE_FIRMWARE(WL18XX_FW_NAME);
651c0804c4cd5b78fff83bf1c709b98799357492
88ae8695987ada722184307301e221e1ba3cc2fa
/third_party/ffmpeg/libavcodec/anm.c
4aabe853b43a070a3d95395642573a864743aa17
[ "LGPL-2.1-only", "LGPL-3.0-only", "LGPL-2.0-or-later", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.1-or-later", "GPL-3.0-or-later", "LGPL-3.0-or-later", "IJG", "LicenseRef-scancode-other-permissive", "MIT", "GPL-2.0-or-later", "Apache-2.0", "GPL-3.0-only", "BSD-3-Clause" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C
false
false
6,124
c
anm.c
/* * Deluxe Paint Animation decoder * Copyright (c) 2009 Peter Ross * * 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 */ /** * @file * Deluxe Paint Animation decoder */ #include "avcodec.h" #include "bytestream.h" #include "codec_internal.h" #include "decode.h" typedef struct AnmContext { AVFrame *frame; int palette[AVPALETTE_COUNT]; } AnmContext; static av_cold int decode_init(AVCodecContext *avctx) { AnmContext *s = avctx->priv_data; GetByteContext gb; int i; if (avctx->extradata_size < 16 * 8 + 4 * 256) return AVERROR_INVALIDDATA; avctx->pix_fmt = AV_PIX_FMT_PAL8; s->frame = av_frame_alloc(); if (!s->frame) return AVERROR(ENOMEM); bytestream2_init(&gb, avctx->extradata, avctx->extradata_size); bytestream2_skipu(&gb, 16 * 8); for (i = 0; i < 256; i++) s->palette[i] = (0xFFU << 24) | bytestream2_get_le32u(&gb); return 0; } /** * Perform decode operation * @param dst pointer to destination image buffer * @param dst_end pointer to end of destination image buffer * @param gb GetByteContext (optional, see below) * @param pixel Fill color (optional, see below) * @param count Pixel count * @param x Pointer to x-axis counter * @param width Image width * @param linesize Destination image buffer linesize * @return non-zero if destination buffer is exhausted * * a copy operation is achieved when 'gb' is set * a fill operation is achieved when 'gb' is null and pixel is >= 0 * a skip operation is achieved when 'gb' is null and pixel is < 0 */ static inline int op(uint8_t **dst, const uint8_t *dst_end, GetByteContext *gb, int pixel, int count, int *x, int width, int linesize) { int remaining = width - *x; while(count > 0) { int striplen = FFMIN(count, remaining); if (gb) { if (bytestream2_get_bytes_left(gb) < striplen) goto exhausted; bytestream2_get_bufferu(gb, *dst, striplen); } else if (pixel >= 0) memset(*dst, pixel, striplen); *dst += striplen; remaining -= striplen; count -= striplen; if (remaining <= 0) { *dst += linesize - width; remaining = width; } if (linesize > 0) { if (*dst >= dst_end) goto exhausted; } else { if (*dst <= dst_end) goto exhausted; } } *x = width - remaining; return 0; exhausted: *x = width - remaining; return 1; } static int decode_frame(AVCodecContext *avctx, AVFrame *rframe, int *got_frame, AVPacket *avpkt) { AnmContext *s = avctx->priv_data; const int buf_size = avpkt->size; uint8_t *dst, *dst_end; GetByteContext gb; int count, ret, x = 0; if (buf_size < 7) return AVERROR_INVALIDDATA; if ((ret = ff_reget_buffer(avctx, s->frame, 0)) < 0) return ret; dst = s->frame->data[0]; dst_end = s->frame->data[0] + s->frame->linesize[0]*avctx->height; bytestream2_init(&gb, avpkt->data, buf_size); if (bytestream2_get_byte(&gb) != 0x42) { avpriv_request_sample(avctx, "Unknown record type"); return AVERROR_INVALIDDATA; } if (bytestream2_get_byte(&gb)) { avpriv_request_sample(avctx, "Padding bytes"); return AVERROR_PATCHWELCOME; } bytestream2_skip(&gb, 2); do { /* if statements are ordered by probability */ #define OP(gb, pixel, count) \ op(&dst, dst_end, (gb), (pixel), (count), &x, avctx->width, s->frame->linesize[0]) int type = bytestream2_get_byte(&gb); count = type & 0x7F; type >>= 7; if (count) { if (OP(type ? NULL : &gb, -1, count)) break; } else if (!type) { int pixel; count = bytestream2_get_byte(&gb); /* count==0 gives nop */ pixel = bytestream2_get_byte(&gb); if (OP(NULL, pixel, count)) break; } else { int pixel; type = bytestream2_get_le16(&gb); count = type & 0x3FFF; type >>= 14; if (!count) { if (type == 0) break; // stop if (type == 2) { avpriv_request_sample(avctx, "Unknown opcode"); return AVERROR_PATCHWELCOME; } continue; } pixel = type == 3 ? bytestream2_get_byte(&gb) : -1; if (type == 1) count += 0x4000; if (OP(type == 2 ? &gb : NULL, pixel, count)) break; } } while (bytestream2_get_bytes_left(&gb) > 0); memcpy(s->frame->data[1], s->palette, AVPALETTE_SIZE); *got_frame = 1; if ((ret = av_frame_ref(rframe, s->frame)) < 0) return ret; return buf_size; } static av_cold int decode_end(AVCodecContext *avctx) { AnmContext *s = avctx->priv_data; av_frame_free(&s->frame); return 0; } const FFCodec ff_anm_decoder = { .p.name = "anm", CODEC_LONG_NAME("Deluxe Paint Animation"), .p.type = AVMEDIA_TYPE_VIDEO, .p.id = AV_CODEC_ID_ANM, .priv_data_size = sizeof(AnmContext), .init = decode_init, .close = decode_end, FF_CODEC_DECODE_CB(decode_frame), .p.capabilities = AV_CODEC_CAP_DR1, };
35b47845ccfeaaafeafc0d83d013b2963c4d738a
9907672fcd81ab73ac63b2a83422a82bf31eadde
/yukicoder/tyama_yukicoder42.c
9fa83f43e131a721deed33b49721e9629d7981e4
[ "0BSD" ]
permissive
cielavenir/procon
bbe1974b9bddb51b76d58722a0686a5b477c4456
746e1a91f574f20647e8aaaac0d9e6173f741176
refs/heads/master
2023-06-21T23:11:24.562546
2023-06-11T13:15:15
2023-06-11T13:15:15
7,557,464
137
136
null
2020-10-20T09:35:52
2013-01-11T09:40:26
C++
UTF-8
C
false
false
962
c
tyama_yukicoder42.c
#include <stdio.h> #define M 3000 #define MOD 1000000009 long long pow_binary_mod(long long x,long long y,long long mod){ long long z=1; for(;y;y>>=1){ if((y&1)!=0)z=z*x%mod; x=x*x%mod; } return z; } int Z[6]={1,5,10,50,100,500}; int A[M+1],REV[13]; int main(){ for(int i=-6;i<=6;i++)REV[6+i]=pow_binary_mod((i+MOD)%MOD,MOD-2,MOD); REV[6]=A[0]=1; for(int z=0;z<6;z++)for(int i=0;i<=M-Z[z];i++)A[i+Z[z]]+=A[i]; int T; for(scanf("%d",&T);T--;){ long long m,x,r,s=0,total=1; scanf("%lld",&m); if(m<=3000)s=A[m]; else{ x=m/500,r=m%500; for(int l=0;l<6;++l)total=( (x-l+MOD)%MOD*total%MOD*REV[l+1] )%MOD; for(int k=0;k<6;k++){ long long p=A[k*500+r]; //for(int l=0;l<6;l++)if(l!=k)p=(x-l+MOD)%MOD*p%MOD*pow_binary_mod(k-l+MOD,MOD-2,MOD)%MOD; p=p*total%MOD*pow_binary_mod((x-k+MOD)%MOD,MOD-2,MOD)%MOD; s=(s+p)%MOD; total=total*REV[k+6+1]%MOD*pow_binary_mod(REV[k+1],MOD-2,MOD)%MOD; } } printf("%lld\n",s); } }
7803846a741fbebf7233610e9fc6ff55e92f721d
6937fe134914752bde354f7588dab26cec8eba79
/tests/06_symbol_versions/v1.c
487616e3c2b602401edf45d0a13d9c7f782b180a
[ "MIT" ]
permissive
haampie/libtree
58ef4023727f723adaeab6a5c16c33c4d61c3322
eb56287c1b4eb3b267524ab1e6e31f042b713395
refs/heads/master
2023-08-06T12:35:20.172197
2023-01-15T21:49:37
2023-01-15T21:49:37
253,045,183
1,764
64
MIT
2023-02-22T08:47:20
2020-04-04T16:25:58
C
UTF-8
C
false
false
24
c
v1.c
int xyz() { return 3; }
427718cccbe5cd5ceddc7c0461b4cc5cc7903a7a
12f1e8df4b11581e75f28509bb29007b0c003f70
/src/sd_api_v2/sdk/components/serialization/common/struct_ser/s130/ble_gap_struct_serialization.h
dcca829cdc01e07778ba29afb569ac19cf574ab5
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
permissive
NordicSemiconductor/pc-ble-driver
4044f878bebe4023b96423c2a1a5c9cf60325b35
c0ffd419053e2405fffdb02ce7f1f9acceff4a66
refs/heads/master
2023-08-25T03:25:23.460137
2022-03-15T14:04:26
2022-03-15T14:04:26
36,868,122
297
159
NOASSERTION
2023-07-19T10:54:53
2015-06-04T12:12:14
C
UTF-8
C
false
false
21,853
h
ble_gap_struct_serialization.h
/* * Copyright (c) 2016 Nordic Semiconductor ASA * 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 Nordic Semiconductor ASA nor the names of other * contributors to this software may be used to endorse or promote products * derived from this software without specific prior written permission. * * 4. This software must only be used in or with a processor manufactured by Nordic * Semiconductor ASA, or in or with a processor manufactured by a third party that * is used in combination with a processor manufactured by Nordic Semiconductor. * * 5. Any software provided in binary or object form under this license must not be * reverse engineered, decompiled, modified and/or disassembled. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ble_gap.h" #ifdef __cplusplus extern "C" { #endif uint32_t ble_gap_irk_enc(void const * const p_data, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_irk_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_data); uint32_t ble_gap_addr_enc(void const * const p_data, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_addr_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_addr); uint32_t ble_gap_sec_levels_enc(void const * const p_data, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_sec_levels_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_data); uint32_t ble_gap_sec_keys_enc(void const * const p_data, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_sec_keys_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_data); uint32_t ble_gap_enc_info_enc(void const * const p_data, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_enc_info_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_enc_info); uint32_t ble_gap_sign_info_enc(void const * const p_sign_info, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_sign_info_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_sign_info); uint32_t ble_gap_evt_auth_status_t_enc(void const * const p_data, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_evt_auth_status_t_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_data); uint32_t ble_gap_conn_sec_mode_enc(void const * const p_void_sec_mode, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_conn_sec_mode_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_void_sec_mode); uint32_t ble_gap_conn_sec_t_enc(void const * const p_void_sec, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_conn_sec_t_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_void_sec); uint32_t ble_gap_evt_conn_sec_update_t_enc(void const * const p_void_conn_sec_update, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_evt_conn_sec_update_t_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_void_conn_sec_update); uint32_t ble_gap_evt_sec_info_request_t_enc(void const * const p_void_sec_info_request, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_evt_sec_info_request_t_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_void_sec_info_request); uint32_t ble_gap_evt_connected_t_enc(void const * const p_void_struct, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_evt_connected_t_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_void_connected); uint32_t ble_gap_sec_params_t_enc(void const * const p_void_struct, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_sec_params_t_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_void_struct); uint32_t ble_gap_evt_sec_params_request_t_enc(void const * const p_void_struct, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_evt_sec_params_request_t_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_void_struct); uint32_t ble_gap_conn_params_t_enc(void const * const p_void_conn_params, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_conn_params_t_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_void_conn_params); uint32_t ble_gap_evt_conn_param_update_t_enc(void const * const p_void_evt_conn_param_update, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_evt_conn_param_update_t_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_void_evt_conn_param_update); uint32_t ble_gap_evt_conn_param_update_request_t_enc(void const * const p_void_evt_conn_param_update_request, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_evt_conn_param_update_request_t_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_void_evt_conn_param_update_request); uint32_t ble_gap_evt_disconnected_t_enc(void const * const p_void_disconnected, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_evt_disconnected_t_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_void_disconnected); uint32_t ble_gap_whitelist_t_enc(void const * const p_data, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_whitelist_t_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * p_data); uint32_t ble_gap_scan_params_t_enc(void const * const p_data, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_scan_params_t_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_data); uint32_t ble_gap_master_id_t_enc(void const * const p_master_idx, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_master_id_t_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_master_idx); uint32_t ble_gap_enc_key_t_enc(void const * const p_data, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_enc_key_t_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_data); uint32_t ble_gap_id_key_t_enc(void const * const p_data, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_id_key_t_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_data); uint32_t ble_gap_sec_keyset_t_enc(void const * const p_data, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_sec_keyset_t_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_data); uint32_t ble_gap_evt_sec_request_t_enc(void const * const p_void_struct, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_evt_sec_request_t_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_data); uint32_t ble_gap_sec_kdist_t_enc(void const * const p_data, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_sec_kdist_t_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_data); uint32_t ble_gap_opt_ch_map_t_enc(void const * const p_data, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_opt_ch_map_t_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_data); uint32_t ble_gap_opt_local_conn_latency_t_enc(void const * const p_void_local_conn_latency, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_opt_local_conn_latency_t_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_void_local_conn_latency); uint32_t ble_gap_opt_passkey_t_enc(void const * const p_void_passkey, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_opt_passkey_t_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_void_passkey); uint32_t ble_gap_opt_privacy_t_enc(void const * const p_void_privacy, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_opt_privacy_t_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_void_privacy); uint32_t ble_gap_opt_scan_req_report_t_enc(void const * const p_void_scan_req_report, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_opt_scan_req_report_t_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_void_scan_req_report); uint32_t ble_gap_opt_compat_mode_t_enc(void const * const p_void_compat_mode, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_opt_compat_mode_t_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_void_compat_mode); uint32_t ble_gap_adv_ch_mask_t_enc(void const * const p_void_ch_mask, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_adv_ch_mask_t_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_void_ch_mask); uint32_t ble_gap_enable_params_t_enc(void const * const p_void_enable_params, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_enable_params_t_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_void_enable_params); uint32_t ble_gap_lesc_p256_pk_t_enc(void const * const p_pk, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_lesc_p256_pk_t_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_pk); uint32_t ble_gap_lesc_dhkey_t_enc(void const * const p_key, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_lesc_dhkey_t_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_key); uint32_t ble_gap_lesc_oob_data_t_enc(void const * const p_void_oob_data, uint8_t * const p_buf, uint32_t buf_len, uint32_t * const p_index); uint32_t ble_gap_lesc_oob_data_t_dec(uint8_t const * const p_buf, uint32_t buf_len, uint32_t * const p_index, void * const p_void_oob_data); #ifdef __cplusplus } #endif
c286da1a3dcf272dc54e11daab745742274dcfa6
52c8ed39b32ccc7c0673278c1adea3638797c9ff
/src/arch/riscv64/mach-k210/driver/spi-k210.c
ce21cb5fcfcc8e6e3abe493c59f851f2c84432d4
[ "MIT" ]
permissive
xboot/xboot
0cab7b440b612aa0a4c366025598a53a7ec3adf1
6d6b93947b7fcb8c3924fedb0715c23877eedd5e
refs/heads/master
2023-08-20T05:56:25.149388
2023-07-12T07:38:29
2023-07-12T07:38:29
471,539
765
296
MIT
2023-05-25T09:39:01
2010-01-14T08:25:12
C
UTF-8
C
false
false
11,929
c
spi-k210.c
/* * driver/spi-k210.c * * Copyright(c) 2007-2023 Jianjun Jiang <8192542@qq.com> * Official site: http://xboot.org * Mobile phone: +86-18665388956 * QQ: 8192542 * * 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 <xboot.h> #include <clk/clk.h> #include <reset/reset.h> #include <gpio/gpio.h> #include <spi/spi.h> enum { SPI_CTRL0 = 0x000, SPI_CTRL1 = 0x004, SPI_SSIENR = 0x008, SPI_MWCR = 0x00c, SPI_SER = 0x010, SPI_BAUDR = 0x014, SPI_TXFTLR = 0x018, SPI_RXFTLR = 0x01c, SPI_TXFLR = 0x020, SPI_RXFLR = 0x024, SPI_SR = 0x028, SPI_IMR = 0x02c, SPI_ISR = 0x030, SPI_RISR = 0x034, SPI_TXOICR = 0x038, SPI_RXOICR = 0x03c, SPI_RXUICR = 0x040, SPI_MSTICR = 0x044, SPI_ICR = 0x048, SPI_DMACR = 0x04c, SPI_DMATDLR = 0x050, SPI_DMARDLR = 0x054, SPI_IDR = 0x058, SPI_VERSION = 0x05c, SPI_DR = 0x060, }; struct spi_k210_pdata_t { virtual_addr_t virt; char * clk; int reset; int sclk; int sclkcfg; int io0; int io0cfg; int io1; int io1cfg; int io2; int io2cfg; int io3; int io3cfg; int io4; int io4cfg; int io5; int io5cfg; int io6; int io6cfg; int io7; int io7cfg; int cs0; int cs0cfg; int cs1; int cs1cfg; int cs2; int cs2cfg; int cs3; int cs3cfg; int fifo_len; }; static inline void spi_k210_enable_chip(struct spi_k210_pdata_t * pdat, int enable) { write32(pdat->virt + SPI_SSIENR, enable ? 1 : 0); } static inline void spi_k210_set_rate(struct spi_k210_pdata_t * pdat, u64_t rate) { u32_t div; div = clk_get_rate(pdat->clk) / rate; div = (div + 1) & 0xfffe; write32(pdat->virt + SPI_BAUDR, div); } static inline void spi_k210_set_type(struct spi_k210_pdata_t * pdat, int type) { u32_t val; val = read32(pdat->virt + SPI_CTRL0); val &= ~(0x3 << 21); switch(type) { case SPI_TYPE_SINGLE: val |= 0x0 << 21; break; case SPI_TYPE_DUAL: val |= 0x1 << 21; break; case SPI_TYPE_QUAD: val |= 0x2 << 21; break; case SPI_TYPE_OCTAL: val |= 0x3 << 21; break; default: val |= 0x0 << 21; break; } write32(pdat->virt + SPI_CTRL0, val); } static inline void spi_k210_set_mode(struct spi_k210_pdata_t * pdat, int mode) { u32_t val; val = read32(pdat->virt + SPI_CTRL0); val &= ~(0x3 << 6); val |= (mode & 0x3) << 6; write32(pdat->virt + SPI_CTRL0, val); } static inline void spi_k210_set_bits(struct spi_k210_pdata_t * pdat, int bits) { u32_t val; val = read32(pdat->virt + SPI_CTRL0); val &= ~(0xf << 16); val |= ((bits - 1) & 0xf) << 16; write32(pdat->virt + SPI_CTRL0, val); } static inline void spi_k210_set_tmode(struct spi_k210_pdata_t * pdat, int tmode) { u32_t val; val = read32(pdat->virt + SPI_CTRL0); val &= ~(0x3 << 8); val |= (tmode & 0x3) << 8; write32(pdat->virt + SPI_CTRL0, val); } static inline void spi_k210_init(struct spi_k210_pdata_t * pdat) { int i; write32(pdat->virt + SPI_IMR, 0x0); write32(pdat->virt + SPI_DMACR, 0x0); write32(pdat->virt + SPI_DMATDLR, 0x0); write32(pdat->virt + SPI_DMARDLR, 0x0); write32(pdat->virt + SPI_SER, 0x0); write32(pdat->virt + SPI_SSIENR, 0x0); write32(pdat->virt + SPI_CTRL0, (0 << 6) | (0 << 21) | ((8 - 1) << 16)); spi_k210_set_rate(pdat, 1000000); spi_k210_set_type(pdat, SPI_TYPE_SINGLE); spi_k210_set_mode(pdat, 0); spi_k210_set_bits(pdat, 8); spi_k210_set_tmode(pdat, 3); spi_k210_enable_chip(pdat, 1); if(pdat->fifo_len <= 0) { for(i = 1; i < 256; i++) { write32(pdat->virt + SPI_TXFTLR, i); if(i != read32(pdat->virt + SPI_TXFTLR)) break; } pdat->fifo_len = (i == 1) ? 0 : i; } spi_k210_enable_chip(pdat, 0); } static inline int spi_k210_xfer_8(struct spi_k210_pdata_t * pdat, struct spi_msg_t * msg) { u8_t * tx = msg->txbuf; u8_t * rx = msg->rxbuf; int txlen = msg->len; int rxlen = msg->len; int i, n, t; if(tx && rx) { spi_k210_set_tmode(pdat, 0); while((txlen > 0) || (rxlen > 0)) { if(txlen > 0) { n = pdat->fifo_len - read32(pdat->virt + SPI_TXFLR); t = pdat->fifo_len - read32(pdat->virt + SPI_RXFLR); n = n < t ? n : t; n = (n < txlen) ? n : txlen; for(i = 0; i < n; i++) write8(pdat->virt + SPI_DR, *tx++); txlen -= n; } if(rxlen > 0) { n = read32(pdat->virt + SPI_RXFLR); n = n < rxlen ? n : rxlen; for(i = 0; i < n; i++) *rx++ = (u8_t)read8(pdat->virt + SPI_DR); rxlen -= n; } } } else if(tx) { spi_k210_set_tmode(pdat, 1); while(txlen > 0) { n = pdat->fifo_len - read32(pdat->virt + SPI_TXFLR); n = (n < txlen) ? n : txlen; for(i = 0; i < n; i++) write8(pdat->virt + SPI_DR, *tx++); txlen -= n; } } else if(rx) { spi_k210_set_tmode(pdat, 2); write32(pdat->virt + SPI_CTRL1, (rxlen > 1) ? (rxlen - 1) : 0); while(rxlen > 0) { n = read32(pdat->virt + SPI_RXFLR); n = n < rxlen ? n : rxlen; for(i = 0; i < n; i++) *rx++ = (u8_t)read8(pdat->virt + SPI_DR); rxlen -= n; } } return msg->len; } static int spi_k210_transfer(struct spi_t * spi, struct spi_msg_t * msg) { struct spi_k210_pdata_t * pdat = (struct spi_k210_pdata_t *)spi->priv; int ret = 0; spi_k210_set_type(pdat, msg->type); spi_k210_set_mode(pdat, msg->mode); spi_k210_set_bits(pdat, msg->bits); spi_k210_set_rate(pdat, (msg->speed > 0) ? msg->speed : 1000000); if(msg->bits <= 8) { ret = spi_k210_xfer_8(pdat, msg); } else if(msg->bits <= 16) { } return ret; } static void spi_k210_select(struct spi_t * spi, int cs) { struct spi_k210_pdata_t * pdat = (struct spi_k210_pdata_t *)spi->priv; write32(pdat->virt + SPI_SER, read32(pdat->virt + SPI_SER) | (0x1 << cs)); write32(pdat->virt + SPI_SSIENR, 0x1); } static void spi_k210_deselect(struct spi_t * spi, int cs) { struct spi_k210_pdata_t * pdat = (struct spi_k210_pdata_t *)spi->priv; write32(pdat->virt + SPI_SSIENR, 0x0); write32(pdat->virt + SPI_SER, read32(pdat->virt + SPI_SER) & ~(0x1 << cs)); } static struct device_t * spi_k210_probe(struct driver_t * drv, struct dtnode_t * n) { struct spi_k210_pdata_t * pdat; struct spi_t * spi; struct device_t * dev; virtual_addr_t virt = phys_to_virt(dt_read_address(n)); char * clk = dt_read_string(n, "clock-name", NULL); pdat = malloc(sizeof(struct spi_k210_pdata_t)); if(!pdat) return NULL; spi = malloc(sizeof(struct spi_t)); if(!spi) { free(pdat); return NULL; } pdat->virt = virt; pdat->clk = strdup(clk); pdat->reset = dt_read_int(n, "reset", -1); pdat->sclk = dt_read_int(n, "sclk-gpio", -1); pdat->sclkcfg = dt_read_int(n, "sclk-gpio-config", -1); pdat->io0 = dt_read_int(n, "io0-gpio", -1); pdat->io0cfg = dt_read_int(n, "io0-gpio-config", -1); pdat->io1 = dt_read_int(n, "io1-gpio", -1); pdat->io1cfg = dt_read_int(n, "io1-gpio-config", -1); pdat->io2 = dt_read_int(n, "io2-gpio", -1); pdat->io2cfg = dt_read_int(n, "io2-gpio-config", -1); pdat->io3 = dt_read_int(n, "io3-gpio", -1); pdat->io3cfg = dt_read_int(n, "io3-gpio-config", -1); pdat->io4 = dt_read_int(n, "io4-gpio", -1); pdat->io4cfg = dt_read_int(n, "io4-gpio-config", -1); pdat->io5 = dt_read_int(n, "io5-gpio", -1); pdat->io5cfg = dt_read_int(n, "io5-gpio-config", -1); pdat->io6 = dt_read_int(n, "io6-gpio", -1); pdat->io6cfg = dt_read_int(n, "io6-gpio-config", -1); pdat->io7 = dt_read_int(n, "io7-gpio", -1); pdat->io7cfg = dt_read_int(n, "io7-gpio-config", -1); pdat->cs0 = dt_read_int(n, "cs0-gpio", -1); pdat->cs0cfg = dt_read_int(n, "cs0-gpio-config", -1); pdat->cs1 = dt_read_int(n, "cs1-gpio", -1); pdat->cs1cfg = dt_read_int(n, "cs1-gpio-config", -1); pdat->cs2 = dt_read_int(n, "cs2-gpio", -1); pdat->cs2cfg = dt_read_int(n, "cs2-gpio-config", -1); pdat->cs3 = dt_read_int(n, "cs3-gpio", -1); pdat->cs3cfg = dt_read_int(n, "cs3-gpio-config", -1); pdat->fifo_len = 0; spi->name = alloc_device_name(dt_read_name(n), dt_read_id(n)); spi->type = SPI_TYPE_SINGLE | SPI_TYPE_DUAL | SPI_TYPE_QUAD | SPI_TYPE_OCTAL; spi->transfer = spi_k210_transfer; spi->select = spi_k210_select; spi->deselect = spi_k210_deselect; spi->priv = pdat; if(pdat->reset >= 0) reset_deassert(pdat->reset); if(pdat->sclk >= 0) { if(pdat->sclkcfg >= 0) gpio_set_cfg(pdat->sclk, pdat->sclkcfg); gpio_set_pull(pdat->sclk, GPIO_PULL_NONE); } if(pdat->io0 >= 0) { if(pdat->io0cfg >= 0) gpio_set_cfg(pdat->io0, pdat->io0cfg); gpio_set_pull(pdat->io0, GPIO_PULL_NONE); } if(pdat->io1 >= 0) { if(pdat->io1cfg >= 0) gpio_set_cfg(pdat->io1, pdat->io1cfg); gpio_set_pull(pdat->io1, GPIO_PULL_NONE); } if(pdat->io2 >= 0) { if(pdat->io2cfg >= 0) gpio_set_cfg(pdat->io2, pdat->io2cfg); gpio_set_pull(pdat->io2, GPIO_PULL_NONE); } if(pdat->io3 >= 0) { if(pdat->io3cfg >= 0) gpio_set_cfg(pdat->io3, pdat->io3cfg); gpio_set_pull(pdat->io3, GPIO_PULL_NONE); } if(pdat->io4 >= 0) { if(pdat->io4cfg >= 0) gpio_set_cfg(pdat->io4, pdat->io4cfg); gpio_set_pull(pdat->io4, GPIO_PULL_NONE); } if(pdat->io5 >= 0) { if(pdat->io5cfg >= 0) gpio_set_cfg(pdat->io5, pdat->io5cfg); gpio_set_pull(pdat->io5, GPIO_PULL_NONE); } if(pdat->io6 >= 0) { if(pdat->io6cfg >= 0) gpio_set_cfg(pdat->io6, pdat->io6cfg); gpio_set_pull(pdat->io6, GPIO_PULL_NONE); } if(pdat->io7 >= 0) { if(pdat->io7cfg >= 0) gpio_set_cfg(pdat->io7, pdat->io7cfg); gpio_set_pull(pdat->io7, GPIO_PULL_NONE); } if(pdat->cs0 >= 0) { if(pdat->cs0cfg >= 0) gpio_set_cfg(pdat->cs0, pdat->cs0cfg); gpio_set_pull(pdat->cs0, GPIO_PULL_NONE); } if(pdat->cs1 >= 0) { if(pdat->cs1cfg >= 0) gpio_set_cfg(pdat->cs1, pdat->cs1cfg); gpio_set_pull(pdat->cs1, GPIO_PULL_NONE); } if(pdat->cs2 >= 0) { if(pdat->cs2cfg >= 0) gpio_set_cfg(pdat->cs2, pdat->cs2cfg); gpio_set_pull(pdat->cs2, GPIO_PULL_NONE); } if(pdat->cs3 >= 0) { if(pdat->cs3cfg >= 0) gpio_set_cfg(pdat->cs3, pdat->cs3cfg); gpio_set_pull(pdat->cs3, GPIO_PULL_NONE); } clk_enable(pdat->clk); spi_k210_init(pdat); if(!(dev = register_spi(spi, drv))) { clk_disable(pdat->clk); free(pdat->clk); free_device_name(spi->name); free(spi->priv); free(spi); return NULL; } return dev; } static void spi_k210_remove(struct device_t * dev) { struct spi_t * spi = (struct spi_t *)dev->priv; struct spi_k210_pdata_t * pdat = (struct spi_k210_pdata_t *)spi->priv; if(spi) { unregister_spi(spi); clk_disable(pdat->clk); free(pdat->clk); free_device_name(spi->name); free(spi->priv); free(spi); } } static void spi_k210_suspend(struct device_t * dev) { } static void spi_k210_resume(struct device_t * dev) { } static struct driver_t spi_k210 = { .name = "spi-k210", .probe = spi_k210_probe, .remove = spi_k210_remove, .suspend = spi_k210_suspend, .resume = spi_k210_resume, }; static __init void spi_k210_driver_init(void) { register_driver(&spi_k210); } static __exit void spi_k210_driver_exit(void) { unregister_driver(&spi_k210); } driver_initcall(spi_k210_driver_init); driver_exitcall(spi_k210_driver_exit);
d0c9e095bb28225c225596a0c7aa7d4007f6b04e
aa3befea459382dc5c01c925653d54f435b3fb0f
/boards/arm/cxd56xx/common/src/cxd56_audio.c
08ed9849ca993a1b6af0c121493f73546092eff3
[ "MIT-open-group", "BSD-3-Clause", "HPND-sell-variant", "BSD-4-Clause-UC", "LicenseRef-scancode-warranty-disclaimer", "MIT-0", "LicenseRef-scancode-bsd-atmel", "LicenseRef-scancode-gary-s-brown", "LicenseRef-scancode-proprietary-license", "SunPro", "MIT", "LicenseRef-scancode-public-domain-disclaimer", "LicenseRef-scancode-other-permissive", "HPND", "ISC", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "GPL-1.0-or-later", "CC-BY-2.0", "CC-BY-4.0" ]
permissive
apache/nuttx
14519a7bff4a87935d94fb8fb2b19edb501c7cec
606b6d9310fb25c7d92c6f95bf61737e3c79fa0f
refs/heads/master
2023-08-25T06:55:45.822534
2023-08-23T16:03:31
2023-08-24T21:25:47
228,103,273
407
241
Apache-2.0
2023-09-14T18:26:05
2019-12-14T23:27:55
C
UTF-8
C
false
false
12,705
c
cxd56_audio.c
/**************************************************************************** * boards/arm/cxd56xx/common/src/cxd56_audio.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. The * ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <sys/types.h> #include <stdint.h> #include <stdbool.h> #include <errno.h> #include <assert.h> #include <debug.h> #include <nuttx/arch.h> #include <nuttx/audio/audio.h> #include <nuttx/audio/cxd56.h> #include <nuttx/audio/pcm.h> #include <nuttx/signal.h> #include <arch/chip/audio.h> #include "chip.h" #include "arm_internal.h" #include <arch/board/board.h> #include "cxd56_pmic.h" #include "cxd56_gpio.h" #include "cxd56_pinconfig.h" /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ /* Check if the following are defined in the board.h */ #ifndef CXD5247_XRST # error "CXD5247_XRST must be defined in board.h !!" #endif #ifndef CXD5247_AVDD # error "CXD5247_AVDD must be defined in board.h !!" #endif #ifndef CXD5247_DVDD # error "CXD5247_DVDD must be defined in board.h !!" #endif /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Name: check_pin_i2s_mode * * Description: * Check if the pin is I2S. * ****************************************************************************/ static bool check_pin_i2s_mode(uint32_t pin) { bool res = false; cxd56_pin_status_t pstat; if (cxd56_pin_status(pin, &pstat) >= 0) { if (pstat.mode == 1) { res = true; } } return res; } /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: board_audio_power_control * * Description: * Power on/off the audio device on the board. * ****************************************************************************/ bool board_audio_power_control(bool en) { if (en) { /* Enable I2S pin. */ cxd56_audio_en_i2s_io(); /* Enable speaker output. */ cxd56_audio_set_spout(true); /* Power on Audio driver */ if (cxd56_audio_poweron() != 0) { return false; } /* Enable BaseBand driver output */ if (cxd56_audio_en_output() != 0) { return false; } /* Cancel output mute. */ board_external_amp_mute_control(false); } else { /* Set output mute. */ board_external_amp_mute_control(true); /* Disable speaker output. */ cxd56_audio_set_spout(false); /* Disable I2S pin. */ cxd56_audio_dis_i2s_io(); /* Power off Audio driver */ if (cxd56_audio_dis_output() != 0) { return false; } /* Disable BaseBand driver output */ if (cxd56_audio_poweroff() != 0) { return false; } } return true; } /**************************************************************************** * Name: board_aca_power_control * * Description: * Power on/off the Aca device on the board. * ****************************************************************************/ int board_aca_power_control(int target, bool en) { int ret = 0; static int first = 1; static bool avdd_on = false; static bool dvdd_on = false; if (first) { /* gpio configuration (output disabled yet) */ cxd56_gpio_config(CXD5247_XRST, false); first = 0; } if (en) { if (!dvdd_on && (target & CXD5247_DVDD)) { /* reset assert */ cxd56_gpio_write(CXD5247_XRST, false); } /* power on */ if (!avdd_on && (target & CXD5247_AVDD)) { board_power_control(POWER_AUDIO_AVDD, true); avdd_on = true; } if (!dvdd_on && (target & CXD5247_DVDD)) { board_power_control(POWER_AUDIO_DVDD, true); dvdd_on = true; /* reset release */ cxd56_gpio_write(CXD5247_XRST, true); } } else { if (dvdd_on && (target & CXD5247_DVDD)) { /* reset assert */ cxd56_gpio_write(CXD5247_XRST, false); } /* power off */ if (avdd_on && (target & CXD5247_AVDD)) { board_power_control(POWER_AUDIO_AVDD, false); avdd_on = false; } if (dvdd_on && (target & CXD5247_DVDD)) { board_power_control(POWER_AUDIO_DVDD, false); dvdd_on = false; } } return ret; } /**************************************************************************** * Name: board_aca_power_monitor * * Description: * Get status of Power on/off the Aca device on the board. * ****************************************************************************/ bool board_aca_power_monitor(int target) { bool avdd_stat = true; bool dvdd_stat = true; if (target & CXD5247_AVDD) { avdd_stat = board_power_monitor(POWER_AUDIO_AVDD); } if (target & CXD5247_DVDD) { dvdd_stat = board_power_monitor(POWER_AUDIO_DVDD); } return avdd_stat && dvdd_stat; } #define MUTE_OFF_DELAY (1250 * 1000) /* ms */ #define MUTE_ON_DELAY (150 * 1000) /* ms */ /**************************************************************************** * Name: board_external_amp_mute_control * * Description: * External Amp. Mute on/off. * true: Mute on * false: Mute off * ****************************************************************************/ int board_external_amp_mute_control(bool en) { int ret = 0; if (en) { /* Mute ON */ ret = board_power_control(POWER_AUDIO_MUTE, false); nxsig_usleep(MUTE_ON_DELAY); } else { /* Mute OFF */ nxsig_usleep(MUTE_OFF_DELAY); ret = board_power_control(POWER_AUDIO_MUTE, true); } return ret; } /**************************************************************************** * Name: board_external_amp_mute_monitor * * Description: * Get External Amp. Mute status. * true: Mute on * false: Mute off * ****************************************************************************/ bool board_external_amp_mute_monitor(void) { bool mute = board_power_monitor(POWER_AUDIO_MUTE); return !mute; } /**************************************************************************** * Name: board_audio_i2s_enable * * Description: * Enable I2S on the board. * ****************************************************************************/ void board_audio_i2s_enable(void) { #ifdef CONFIG_CXD56_I2S0 /* Select I2S0_BCK, I2S0_LRCK, I2S0_DATA_IN, I2S0_DATA_OUT. */ # ifdef CONFIG_CXD56_AUDIO_I2S_DEVICE_1_MASTER /* I2S0 Master. */ # ifdef CONFIG_CXD56_AUDIO_I2S_LOWEMI_2MA CXD56_PIN_CONFIGS(PINCONFS_I2S0_M_NORM); # else CXD56_PIN_CONFIGS(PINCONFS_I2S0_M_HIGH); # endif # else /* I2S0 Slave. */ # ifdef CONFIG_CXD56_AUDIO_I2S_LOWEMI_2MA CXD56_PIN_CONFIGS(PINCONFS_I2S0_S_NORM); # else CXD56_PIN_CONFIGS(PINCONFS_I2S0_S_HIGH); # endif # endif /* CONFIG_CXD56_AUDIO_I2S_DEVICE_1_MASTER */ #endif /* CONFIG_CXD56_I2S0 */ #ifdef CONFIG_CXD56_I2S1 /* Select I2S1_BCK, I2S1_LRCK, I2S1_DATA_IN, I2S1_DATA_OUT. */ # ifdef CONFIG_CXD56_AUDIO_I2S_DEVICE_2_MASTER /* I2S1 Master. */ # ifdef CONFIG_CXD56_AUDIO_I2S_LOWEMI_2MA CXD56_PIN_CONFIGS(PINCONFS_I2S1_M_NORM); # else CXD56_PIN_CONFIGS(PINCONFS_I2S1_M_HIGH); # endif # else /* I2S1 Slave. */ # ifdef CONFIG_CXD56_AUDIO_I2S_LOWEMI_2MA CXD56_PIN_CONFIGS(PINCONFS_I2S1_S_NORM); # else CXD56_PIN_CONFIGS(PINCONFS_I2S1_S_HIGH); # endif # endif /* CONFIG_CXD56_AUDIO_I2S_DEVICE_2_MASTER */ #endif /* CONFIG_CXD56_I2S1 */ } /**************************************************************************** * Name: board_audio_i2s_disable * * Description: * Disable I2S on the board. * ****************************************************************************/ void board_audio_i2s_disable(void) { #ifdef CONFIG_CXD56_I2S0 /* Select GPIO(P1v_00/01/02/03) */ if (check_pin_i2s_mode(PIN_I2S0_BCK)) { CXD56_PIN_CONFIGS(PINCONFS_I2S0_GPIO); } #endif #ifdef CONFIG_CXD56_I2S1 /* Select GPIO(P1v_00/01/02/03) */ if (check_pin_i2s_mode(PIN_I2S1_BCK)) { CXD56_PIN_CONFIGS(PINCONFS_I2S1_GPIO); } #endif } /**************************************************************************** * Name: board_audio_initialize * * Description: * Initialize audio I/O on the board. * ****************************************************************************/ void board_audio_initialize(void) { /* Select MCLK. */ #ifndef CONFIG_CXD56_AUDIO_ANALOG_NONE CXD56_PIN_CONFIGS(PINCONFS_MCLK); #endif /* Select PDM_CLK, PDM_IN, PDM_OUT. */ #ifdef CONFIG_CXD56_AUDIO_PDM_LOWEMI_2MA CXD56_PIN_CONFIGS(PINCONFS_PDM_NORM); #else CXD56_PIN_CONFIGS(PINCONFS_PDM_HIGH); #endif } /**************************************************************************** * Name: board_audio_finalize * * Description: * Finalize audio I/O on the board. * ****************************************************************************/ void board_audio_finalize(void) { /* Select GPIO(P1x_00). */ #ifndef CONFIG_CXD56_AUDIO_ANALOG_NONE CXD56_PIN_CONFIGS(PINCONFS_MCLK_GPIO); #endif /* Select GPIO(P1y_00/01/02). */ CXD56_PIN_CONFIGS(PINCONFS_PDM_GPIO); /* Disable I2S. */ board_audio_i2s_disable(); } #ifdef CONFIG_AUDIO_CXD56 /**************************************************************************** * Name: board_audio_initialize_driver * * Description: * Initialize and register the CXD56 audio driver. * ****************************************************************************/ static struct cxd56_lower_s g_cxd56_lower[2]; int board_audio_initialize_driver(int minor) { struct audio_lowerhalf_s *cxd56; struct audio_lowerhalf_s *pcm; char devname[12]; int ret; /* Initialize CXD56 output device driver */ cxd56 = cxd56_initialize(&g_cxd56_lower[0]); if (!cxd56) { auderr("ERROR: Failed to initialize the CXD56 audio\n"); return -ENODEV; } #ifndef CONFIG_AUDIO_FORMAT_PCM pcm = cxd56; #else /* Initialize a PCM decoder with the CXD56 instance. */ pcm = pcm_decode_initialize(cxd56); if (!pcm) { auderr("ERROR: Failed create the PCM decoder\n"); return -ENODEV; } #endif /* Create a device name */ snprintf(devname, 12, "pcm%d", minor); /* Finally, we can register the PCM/CXD56 audio device. */ ret = audio_register(devname, pcm); if (ret < 0) { auderr("ERROR: Failed to register /dev/%s device: %d\n", devname, ret); } /* Initialize CXD56 input device driver */ cxd56 = cxd56_initialize(&g_cxd56_lower[1]); if (!cxd56) { auderr("ERROR: Failed to initialize the CXD56 audio\n"); return -ENODEV; } /* No decoder support at the moment, only raw PCM data. */ /* Create a device name */ snprintf(devname, 12, "pcm_in%d", minor); /* Finally, we can register the CXD56 audio input device. */ ret = audio_register(devname, cxd56); if (ret < 0) { auderr("ERROR: Failed to register /dev/%s device: %d\n", devname, ret); } return ret; } #endif /* CONFIG_AUDIO_CXD56 */
78224380ea836d6f10ab7704f4826d3b105aba44
1f399edf85d995443d01f66d77eca0723886d0ff
/misc/config_tools/data/generic_board/generic_code/hybrid/pt_intx.c
e11f52060a201bb8b036b4a897314fbf434cbd1a
[ "BSD-3-Clause" ]
permissive
projectacrn/acrn-hypervisor
f9c5864d54929a5d2fa36b5e78c08f19b46b8f98
390740aa1b1e9d62c51f8e3afa0c29e07e43fa23
refs/heads/master
2023-08-18T05:07:01.310327
2023-08-11T07:49:36
2023-08-16T13:20:27
123,983,554
1,059
686
BSD-3-Clause
2023-09-14T09:51:10
2018-03-05T21:52:25
C
UTF-8
C
false
false
164
c
pt_intx.c
/* * Copyright (C) 2022 Intel Corporation. * * SPDX-License-Identifier: BSD-3-Clause */ #include <asm/vm_config.h> struct pt_intx_config vm0_pt_intx[1U] = {};
153f840ea361d79194de262c5dcc6dc2d93ca372
e30d6af49a2f03aac6585a42a5adf05721033ef0
/target/sh.c
ac52fd47ea1b638463984b379072d13ba2b2321f
[ "MIT" ]
permissive
shinh/elvm
313d295defeefdf0eab6a6fc42ff497ce2b68bd7
26a96a885965392c190061914ce386d827011371
refs/heads/master
2023-08-28T00:41:07.038666
2022-10-13T02:28:54
2022-10-13T02:28:54
68,355,989
1,017
135
MIT
2023-04-10T13:29:53
2016-09-16T05:45:46
C
UTF-8
C
false
false
3,555
c
sh.c
#include <ir/ir.h> #include <target/util.h> static void sh_init_state(Data* data) { for (int i = 0; i < 7; i++) { emit_line("%s=0", reg_names[i]); } for (int mp = 0; data; data = data->next, mp++) { if (data->v) { emit_line("m%d=%d", mp, data->v); } } } const char* sh_value_str(Value* v) { if (v->type == REG) { return format("$%s", reg_names[v->reg]); } else if (v->type == IMM) { return format("%d", v->imm); } else { error("invalid value"); } } static const char* sh_src_str(Inst* inst) { return sh_value_str(&inst->src); } static const char* sh_cmp_str(Inst* inst) { int op = normalize_cond(inst->op, 0); const char* op_str; switch (op) { case JEQ: op_str = "=="; break; case JNE: op_str = "!="; break; case JLT: op_str = "<"; break; case JGT: op_str = ">"; break; case JLE: op_str = "<="; break; case JGE: op_str = ">="; break; case JMP: return "1"; default: error("oops"); } return format("$(( $%s %s %s ))", reg_names[inst->dst.reg], op_str, sh_src_str(inst)); } static void sh_emit_inst(Inst* inst) { switch (inst->op) { case MOV: emit_line("%s=%s", reg_names[inst->dst.reg], sh_src_str(inst)); break; case ADD: emit_line("%s=$(( ($%s + %s) & " UINT_MAX_STR " ))", reg_names[inst->dst.reg], reg_names[inst->dst.reg], sh_src_str(inst)); break; case SUB: emit_line("%s=$(( ($%s - %s) & " UINT_MAX_STR "))", reg_names[inst->dst.reg], reg_names[inst->dst.reg], sh_src_str(inst)); break; case LOAD: emit_line("eval z=\\$m%s", sh_src_str(inst)); emit_line("%s=$(( $z + 0 ))", reg_names[inst->dst.reg]); break; case STORE: emit_line("eval m%s=$%s", sh_src_str(inst), reg_names[inst->dst.reg]); break; case PUTC: emit_line("t=$((%s&255))", sh_src_str(inst)); emit_line("printf \"\\\\$(printf '%%03o' $t)\""); break; case GETC: emit_line("if read -rn1 t; then"); emit_line(" if [ -z $t ]; then"); emit_line(" %s=10", reg_names[inst->dst.reg]); emit_line(" else"); emit_line(" %s=$(printf '%%d' \"'$t'\")", reg_names[inst->dst.reg]); emit_line(" fi"); emit_line("else"); emit_line(" %s=0", reg_names[inst->dst.reg]); emit_line("fi"); break; case EXIT: emit_line("exit"); break; case DUMP: break; case EQ: case NE: case LT: case GT: case LE: case GE: emit_line("%s=%s", reg_names[inst->dst.reg], sh_cmp_str(inst)); break; case JEQ: case JNE: case JLT: case JGT: case JLE: case JGE: emit_line("if [ %s = 1 ]; then", sh_cmp_str(inst)); emit_line(" pc=$(( %s - 1 ))", sh_value_str(&inst->jmp)); emit_line("fi"); break; case JMP: emit_line("pc=$(( %s - 1 ))", sh_value_str(&inst->jmp)); break; default: error("oops"); } } void target_sh(Module* module) { sh_init_state(module->data); emit_line(""); emit_line("while true; do"); emit_line("case $pc in"); int prev_pc = -1; for (Inst* inst = module->text; inst; inst = inst->next) { if (prev_pc != inst->pc) { if (prev_pc != -1) { emit_line(";;"); dec_indent(); emit_line(""); } emit_line("%d)", inst->pc); inc_indent(); } prev_pc = inst->pc; sh_emit_inst(inst); } emit_line(";;"); dec_indent(); emit_line("esac"); emit_line(""); emit_line("pc=$(( $pc + 1 ))"); emit_line("done"); }
74d65dcf45becd374651334609acf797d68ad19a
03dd31eb9723284a9cd9a3fca303d8b94972ac83
/linux.h
8e13749d055ebade84ab1b7632b8ad99783aea12
[ "LicenseRef-scancode-public-domain" ]
permissive
ibara/mg
1af38c0c87114202eb444bf4113719729932172a
caf7703318081ebb6902fe51a36e15b28615ed9b
refs/heads/master
2023-08-07T13:50:01.372285
2023-07-25T21:11:31
2023-07-25T21:11:31
36,533,845
146
29
null
2021-06-12T14:10:00
2015-05-29T23:12:41
C
UTF-8
C
false
false
179
h
linux.h
/* * Linux-specific support. (Cygwin as well.) */ #ifdef __CYGWIN__ #include <sys/socket.h> #endif #include <sys/types.h> #include <stdio.h> /* Defines */ #define TCSASOFT 0
00e5667fe92f027c8d25248a3f0a2b6e0d057882
bb7a80648bf830c2fb813cdb335032142cbee06d
/mod/mpp/3559a/inc/hisisdk/ao_exp.h
02f7e5bbcd82ed904b442009ea400c56fc97d487
[]
no_license
openhisilicon/HIVIEW
44574a29da60e3bb400c7ce97c722dfc9f2959e6
60bbfa5cb66cc82f0cdc0bba1242dbc9491b0f37
refs/heads/master
2023-09-01T01:42:19.069724
2023-08-31T09:57:39
2023-08-31T09:57:39
189,036,134
336
121
null
2023-01-07T14:10:22
2019-05-28T13:41:40
C
UTF-8
C
false
false
742
h
ao_exp.h
/* * Copyright (C) Hisilicon Technologies Co., Ltd. 2012-2019. All rights reserved. * Description: ao_ext.h * Author: Hisilicon multimedia software group * Create: 2019/03/05 * History : * 1.Date : 2019/03/05 * Modification : Created file */ #ifndef __HI_AO_EXP_H__ #define __HI_AO_EXP_H__ #include "hi_common.h" typedef struct hiAO_EXPORT_CALLBACK_S { void (*pfnAoNotify) (int aodev); } AO_EXPORT_CALLBACK_S; typedef HI_S32 FN_AO_RegisterExternCallback(AO_EXPORT_CALLBACK_S *pstExpCallback); typedef struct hiAO_EXPORT_SYMBOL_S { FN_AO_RegisterExternCallback *pfnAoRegisterExpCallback; } AO_EXPORT_SYMBOL_S; #endif /* __HI_AO_EXP_H__ */
28dafff05df0ded942638502f0dee240259fc691
e3e7da042dcef56cd654d6599898eee34e7f1a08
/network_io/os2/sendrecv_udp.c
7bd414feae96131497968a5998e826f71929735f
[ "BSD-4-Clause-UC", "LicenseRef-scancode-rsa-md4", "Zlib", "Beerware", "RSA-MD", "LicenseRef-scancode-rsa-1990", "BSD-4-Clause", "ISC", "LicenseRef-scancode-other-permissive", "Apache-2.0", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-generic-export-compliance" ]
permissive
apache/apr
1c202827c91de87043d342968be4c74d7d0ccd37
59341af138dd2c6fe9444ee9c865b769c0053bdd
refs/heads/trunk
2023-08-16T19:06:37.213299
2023-06-27T14:06:09
2023-06-27T14:06:09
160,997
419
215
Apache-2.0
2023-06-27T14:06:18
2009-03-27T15:41:55
C
UTF-8
C
false
false
3,662
c
sendrecv_udp.c
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_arch_networkio.h" #include "apr_errno.h" #include "apr_general.h" #include "apr_network_io.h" #include "apr_support.h" #include "apr_lib.h" #include <sys/time.h> static apr_status_t wait_socket_ready(apr_socket_t *sock, int readwrite) { int pollsocket = sock->socketdes; int wait_rc = select(&pollsocket, readwrite == 0, readwrite == 1, 0, sock->timeout / 1000); if (wait_rc == 0) { return APR_TIMEUP; } else if (wait_rc < 0) { return APR_FROM_OS_ERROR(sock_errno()); } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_socket_sendto(apr_socket_t *sock, apr_sockaddr_t *where, apr_int32_t flags, const char *buf, apr_size_t *len) { apr_ssize_t rv; int serrno; do { rv = sendto(sock->socketdes, buf, (*len), flags, (struct sockaddr*)&where->sa, where->salen); if (rv == -1) { serrno = sock_errno(); if (serrno == SOCEWOULDBLOCK && sock->timeout != 0) { apr_status_t wait_status = wait_socket_ready(sock, 1); if (wait_status != APR_SUCCESS) { *len = 0; return wait_status; } } else if (serrno != SOCEINTR) { *len = 0; return APR_FROM_OS_ERROR(serrno); } } else { *len = rv; return APR_SUCCESS; } } while (1); } APR_DECLARE(apr_status_t) apr_socket_recvfrom(apr_sockaddr_t *from, apr_socket_t *sock, apr_int32_t flags, char *buf, apr_size_t *len) { apr_ssize_t rv; int serrno; do { from->salen = sizeof(from->sa); rv = recvfrom(sock->socketdes, buf, (*len), flags, (struct sockaddr*)&from->sa, &from->salen); if (rv == -1) { serrno = sock_errno(); if (serrno == SOCEWOULDBLOCK && sock->timeout != 0) { apr_status_t wait_status = wait_socket_ready(sock, 0); if (wait_status != APR_SUCCESS) { *len = 0; return wait_status; } } else if (serrno != SOCEINTR) { *len = 0; return APR_FROM_OS_ERROR(serrno); } } else { *len = rv; apr_sockaddr_vars_set(from, from->sa.sin.sin_family, ntohs(from->sa.sin.sin_port)); return (rv == 0 && sock->type == SOCK_STREAM) ? APR_EOF : APR_SUCCESS; } } while (1); }
4f1fb70c123fceed8e96154c508ba8c3e8e0ae72
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/drivers/media/dvb-frontends/stb0899_cfg.h
0867906d3ff3c0153ddf41d4dcd967c858211787
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
20,457
h
stb0899_cfg.h
/* STB0899 Multistandard Frontend driver Copyright (C) Manu Abraham (abraham.manu@gmail.com) Copyright (C) ST Microelectronics 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef __STB0899_CFG_H #define __STB0899_CFG_H static const struct stb0899_s2_reg stb0899_s2_init_2[] = { { STB0899_OFF0_DMD_STATUS , STB0899_BASE_DMD_STATUS , 0x00000103 }, /* DMDSTATUS */ { STB0899_OFF0_CRL_FREQ , STB0899_BASE_CRL_FREQ , 0x3ed1da56 }, /* CRLFREQ */ { STB0899_OFF0_BTR_FREQ , STB0899_BASE_BTR_FREQ , 0x00004000 }, /* BTRFREQ */ { STB0899_OFF0_IF_AGC_GAIN , STB0899_BASE_IF_AGC_GAIN , 0x00002ade }, /* IFAGCGAIN */ { STB0899_OFF0_BB_AGC_GAIN , STB0899_BASE_BB_AGC_GAIN , 0x000001bc }, /* BBAGCGAIN */ { STB0899_OFF0_DC_OFFSET , STB0899_BASE_DC_OFFSET , 0x00000200 }, /* DCOFFSET */ { STB0899_OFF0_DMD_CNTRL , STB0899_BASE_DMD_CNTRL , 0x0000000f }, /* DMDCNTRL */ { STB0899_OFF0_IF_AGC_CNTRL , STB0899_BASE_IF_AGC_CNTRL , 0x03fb4a20 }, /* IFAGCCNTRL */ { STB0899_OFF0_BB_AGC_CNTRL , STB0899_BASE_BB_AGC_CNTRL , 0x00200c97 }, /* BBAGCCNTRL */ { STB0899_OFF0_CRL_CNTRL , STB0899_BASE_CRL_CNTRL , 0x00000016 }, /* CRLCNTRL */ { STB0899_OFF0_CRL_PHS_INIT , STB0899_BASE_CRL_PHS_INIT , 0x00000000 }, /* CRLPHSINIT */ { STB0899_OFF0_CRL_FREQ_INIT , STB0899_BASE_CRL_FREQ_INIT , 0x00000000 }, /* CRLFREQINIT */ { STB0899_OFF0_CRL_LOOP_GAIN , STB0899_BASE_CRL_LOOP_GAIN , 0x00000000 }, /* CRLLOOPGAIN */ { STB0899_OFF0_CRL_NOM_FREQ , STB0899_BASE_CRL_NOM_FREQ , 0x3ed097b6 }, /* CRLNOMFREQ */ { STB0899_OFF0_CRL_SWP_RATE , STB0899_BASE_CRL_SWP_RATE , 0x00000000 }, /* CRLSWPRATE */ { STB0899_OFF0_CRL_MAX_SWP , STB0899_BASE_CRL_MAX_SWP , 0x00000000 }, /* CRLMAXSWP */ { STB0899_OFF0_CRL_LK_CNTRL , STB0899_BASE_CRL_LK_CNTRL , 0x0f6cdc01 }, /* CRLLKCNTRL */ { STB0899_OFF0_DECIM_CNTRL , STB0899_BASE_DECIM_CNTRL , 0x00000000 }, /* DECIMCNTRL */ { STB0899_OFF0_BTR_CNTRL , STB0899_BASE_BTR_CNTRL , 0x00003993 }, /* BTRCNTRL */ { STB0899_OFF0_BTR_LOOP_GAIN , STB0899_BASE_BTR_LOOP_GAIN , 0x000d3c6f }, /* BTRLOOPGAIN */ { STB0899_OFF0_BTR_PHS_INIT , STB0899_BASE_BTR_PHS_INIT , 0x00000000 }, /* BTRPHSINIT */ { STB0899_OFF0_BTR_FREQ_INIT , STB0899_BASE_BTR_FREQ_INIT , 0x00000000 }, /* BTRFREQINIT */ { STB0899_OFF0_BTR_NOM_FREQ , STB0899_BASE_BTR_NOM_FREQ , 0x0238e38e }, /* BTRNOMFREQ */ { STB0899_OFF0_BTR_LK_CNTRL , STB0899_BASE_BTR_LK_CNTRL , 0x00000000 }, /* BTRLKCNTRL */ { STB0899_OFF0_DECN_CNTRL , STB0899_BASE_DECN_CNTRL , 0x00000000 }, /* DECNCNTRL */ { STB0899_OFF0_TP_CNTRL , STB0899_BASE_TP_CNTRL , 0x00000000 }, /* TPCNTRL */ { STB0899_OFF0_TP_BUF_STATUS , STB0899_BASE_TP_BUF_STATUS , 0x00000000 }, /* TPBUFSTATUS */ { STB0899_OFF0_DC_ESTIM , STB0899_BASE_DC_ESTIM , 0x00000000 }, /* DCESTIM */ { STB0899_OFF0_FLL_CNTRL , STB0899_BASE_FLL_CNTRL , 0x00000000 }, /* FLLCNTRL */ { STB0899_OFF0_FLL_FREQ_WD , STB0899_BASE_FLL_FREQ_WD , 0x40070000 }, /* FLLFREQWD */ { STB0899_OFF0_ANTI_ALIAS_SEL , STB0899_BASE_ANTI_ALIAS_SEL , 0x00000001 }, /* ANTIALIASSEL */ { STB0899_OFF0_RRC_ALPHA , STB0899_BASE_RRC_ALPHA , 0x00000002 }, /* RRCALPHA */ { STB0899_OFF0_DC_ADAPT_LSHFT , STB0899_BASE_DC_ADAPT_LSHFT , 0x00000000 }, /* DCADAPTISHFT */ { STB0899_OFF0_IMB_OFFSET , STB0899_BASE_IMB_OFFSET , 0x0000fe01 }, /* IMBOFFSET */ { STB0899_OFF0_IMB_ESTIMATE , STB0899_BASE_IMB_ESTIMATE , 0x00000000 }, /* IMBESTIMATE */ { STB0899_OFF0_IMB_CNTRL , STB0899_BASE_IMB_CNTRL , 0x00000001 }, /* IMBCNTRL */ { STB0899_OFF0_IF_AGC_CNTRL2 , STB0899_BASE_IF_AGC_CNTRL2 , 0x00005007 }, /* IFAGCCNTRL2 */ { STB0899_OFF0_DMD_CNTRL2 , STB0899_BASE_DMD_CNTRL2 , 0x00000002 }, /* DMDCNTRL2 */ { STB0899_OFF0_TP_BUFFER , STB0899_BASE_TP_BUFFER , 0x00000000 }, /* TPBUFFER */ { STB0899_OFF0_TP_BUFFER1 , STB0899_BASE_TP_BUFFER1 , 0x00000000 }, /* TPBUFFER1 */ { STB0899_OFF0_TP_BUFFER2 , STB0899_BASE_TP_BUFFER2 , 0x00000000 }, /* TPBUFFER2 */ { STB0899_OFF0_TP_BUFFER3 , STB0899_BASE_TP_BUFFER3 , 0x00000000 }, /* TPBUFFER3 */ { STB0899_OFF0_TP_BUFFER4 , STB0899_BASE_TP_BUFFER4 , 0x00000000 }, /* TPBUFFER4 */ { STB0899_OFF0_TP_BUFFER5 , STB0899_BASE_TP_BUFFER5 , 0x00000000 }, /* TPBUFFER5 */ { STB0899_OFF0_TP_BUFFER6 , STB0899_BASE_TP_BUFFER6 , 0x00000000 }, /* TPBUFFER6 */ { STB0899_OFF0_TP_BUFFER7 , STB0899_BASE_TP_BUFFER7 , 0x00000000 }, /* TPBUFFER7 */ { STB0899_OFF0_TP_BUFFER8 , STB0899_BASE_TP_BUFFER8 , 0x00000000 }, /* TPBUFFER8 */ { STB0899_OFF0_TP_BUFFER9 , STB0899_BASE_TP_BUFFER9 , 0x00000000 }, /* TPBUFFER9 */ { STB0899_OFF0_TP_BUFFER10 , STB0899_BASE_TP_BUFFER10 , 0x00000000 }, /* TPBUFFER10 */ { STB0899_OFF0_TP_BUFFER11 , STB0899_BASE_TP_BUFFER11 , 0x00000000 }, /* TPBUFFER11 */ { STB0899_OFF0_TP_BUFFER12 , STB0899_BASE_TP_BUFFER12 , 0x00000000 }, /* TPBUFFER12 */ { STB0899_OFF0_TP_BUFFER13 , STB0899_BASE_TP_BUFFER13 , 0x00000000 }, /* TPBUFFER13 */ { STB0899_OFF0_TP_BUFFER14 , STB0899_BASE_TP_BUFFER14 , 0x00000000 }, /* TPBUFFER14 */ { STB0899_OFF0_TP_BUFFER15 , STB0899_BASE_TP_BUFFER15 , 0x00000000 }, /* TPBUFFER15 */ { STB0899_OFF0_TP_BUFFER16 , STB0899_BASE_TP_BUFFER16 , 0x0000ff00 }, /* TPBUFFER16 */ { STB0899_OFF0_TP_BUFFER17 , STB0899_BASE_TP_BUFFER17 , 0x00000100 }, /* TPBUFFER17 */ { STB0899_OFF0_TP_BUFFER18 , STB0899_BASE_TP_BUFFER18 , 0x0000fe01 }, /* TPBUFFER18 */ { STB0899_OFF0_TP_BUFFER19 , STB0899_BASE_TP_BUFFER19 , 0x000004fe }, /* TPBUFFER19 */ { STB0899_OFF0_TP_BUFFER20 , STB0899_BASE_TP_BUFFER20 , 0x0000cfe7 }, /* TPBUFFER20 */ { STB0899_OFF0_TP_BUFFER21 , STB0899_BASE_TP_BUFFER21 , 0x0000bec6 }, /* TPBUFFER21 */ { STB0899_OFF0_TP_BUFFER22 , STB0899_BASE_TP_BUFFER22 , 0x0000c2bf }, /* TPBUFFER22 */ { STB0899_OFF0_TP_BUFFER23 , STB0899_BASE_TP_BUFFER23 , 0x0000c1c1 }, /* TPBUFFER23 */ { STB0899_OFF0_TP_BUFFER24 , STB0899_BASE_TP_BUFFER24 , 0x0000c1c1 }, /* TPBUFFER24 */ { STB0899_OFF0_TP_BUFFER25 , STB0899_BASE_TP_BUFFER25 , 0x0000c1c1 }, /* TPBUFFER25 */ { STB0899_OFF0_TP_BUFFER26 , STB0899_BASE_TP_BUFFER26 , 0x0000c1c1 }, /* TPBUFFER26 */ { STB0899_OFF0_TP_BUFFER27 , STB0899_BASE_TP_BUFFER27 , 0x0000c1c0 }, /* TPBUFFER27 */ { STB0899_OFF0_TP_BUFFER28 , STB0899_BASE_TP_BUFFER28 , 0x0000c0c0 }, /* TPBUFFER28 */ { STB0899_OFF0_TP_BUFFER29 , STB0899_BASE_TP_BUFFER29 , 0x0000c1c1 }, /* TPBUFFER29 */ { STB0899_OFF0_TP_BUFFER30 , STB0899_BASE_TP_BUFFER30 , 0x0000c1c1 }, /* TPBUFFER30 */ { STB0899_OFF0_TP_BUFFER31 , STB0899_BASE_TP_BUFFER31 , 0x0000c0c1 }, /* TPBUFFER31 */ { STB0899_OFF0_TP_BUFFER32 , STB0899_BASE_TP_BUFFER32 , 0x0000c0c1 }, /* TPBUFFER32 */ { STB0899_OFF0_TP_BUFFER33 , STB0899_BASE_TP_BUFFER33 , 0x0000c1c1 }, /* TPBUFFER33 */ { STB0899_OFF0_TP_BUFFER34 , STB0899_BASE_TP_BUFFER34 , 0x0000c1c1 }, /* TPBUFFER34 */ { STB0899_OFF0_TP_BUFFER35 , STB0899_BASE_TP_BUFFER35 , 0x0000c0c1 }, /* TPBUFFER35 */ { STB0899_OFF0_TP_BUFFER36 , STB0899_BASE_TP_BUFFER36 , 0x0000c1c1 }, /* TPBUFFER36 */ { STB0899_OFF0_TP_BUFFER37 , STB0899_BASE_TP_BUFFER37 , 0x0000c0c1 }, /* TPBUFFER37 */ { STB0899_OFF0_TP_BUFFER38 , STB0899_BASE_TP_BUFFER38 , 0x0000c1c1 }, /* TPBUFFER38 */ { STB0899_OFF0_TP_BUFFER39 , STB0899_BASE_TP_BUFFER39 , 0x0000c0c0 }, /* TPBUFFER39 */ { STB0899_OFF0_TP_BUFFER40 , STB0899_BASE_TP_BUFFER40 , 0x0000c1c0 }, /* TPBUFFER40 */ { STB0899_OFF0_TP_BUFFER41 , STB0899_BASE_TP_BUFFER41 , 0x0000c1c1 }, /* TPBUFFER41 */ { STB0899_OFF0_TP_BUFFER42 , STB0899_BASE_TP_BUFFER42 , 0x0000c0c0 }, /* TPBUFFER42 */ { STB0899_OFF0_TP_BUFFER43 , STB0899_BASE_TP_BUFFER43 , 0x0000c1c0 }, /* TPBUFFER43 */ { STB0899_OFF0_TP_BUFFER44 , STB0899_BASE_TP_BUFFER44 , 0x0000c0c1 }, /* TPBUFFER44 */ { STB0899_OFF0_TP_BUFFER45 , STB0899_BASE_TP_BUFFER45 , 0x0000c1be }, /* TPBUFFER45 */ { STB0899_OFF0_TP_BUFFER46 , STB0899_BASE_TP_BUFFER46 , 0x0000c1c9 }, /* TPBUFFER46 */ { STB0899_OFF0_TP_BUFFER47 , STB0899_BASE_TP_BUFFER47 , 0x0000c0da }, /* TPBUFFER47 */ { STB0899_OFF0_TP_BUFFER48 , STB0899_BASE_TP_BUFFER48 , 0x0000c0ba }, /* TPBUFFER48 */ { STB0899_OFF0_TP_BUFFER49 , STB0899_BASE_TP_BUFFER49 , 0x0000c1c4 }, /* TPBUFFER49 */ { STB0899_OFF0_TP_BUFFER50 , STB0899_BASE_TP_BUFFER50 , 0x0000c1bf }, /* TPBUFFER50 */ { STB0899_OFF0_TP_BUFFER51 , STB0899_BASE_TP_BUFFER51 , 0x0000c0c1 }, /* TPBUFFER51 */ { STB0899_OFF0_TP_BUFFER52 , STB0899_BASE_TP_BUFFER52 , 0x0000c1c0 }, /* TPBUFFER52 */ { STB0899_OFF0_TP_BUFFER53 , STB0899_BASE_TP_BUFFER53 , 0x0000c0c1 }, /* TPBUFFER53 */ { STB0899_OFF0_TP_BUFFER54 , STB0899_BASE_TP_BUFFER54 , 0x0000c1c1 }, /* TPBUFFER54 */ { STB0899_OFF0_TP_BUFFER55 , STB0899_BASE_TP_BUFFER55 , 0x0000c1c1 }, /* TPBUFFER55 */ { STB0899_OFF0_TP_BUFFER56 , STB0899_BASE_TP_BUFFER56 , 0x0000c1c1 }, /* TPBUFFER56 */ { STB0899_OFF0_TP_BUFFER57 , STB0899_BASE_TP_BUFFER57 , 0x0000c1c1 }, /* TPBUFFER57 */ { STB0899_OFF0_TP_BUFFER58 , STB0899_BASE_TP_BUFFER58 , 0x0000c1c1 }, /* TPBUFFER58 */ { STB0899_OFF0_TP_BUFFER59 , STB0899_BASE_TP_BUFFER59 , 0x0000c1c1 }, /* TPBUFFER59 */ { STB0899_OFF0_TP_BUFFER60 , STB0899_BASE_TP_BUFFER60 , 0x0000c1c1 }, /* TPBUFFER60 */ { STB0899_OFF0_TP_BUFFER61 , STB0899_BASE_TP_BUFFER61 , 0x0000c1c1 }, /* TPBUFFER61 */ { STB0899_OFF0_TP_BUFFER62 , STB0899_BASE_TP_BUFFER62 , 0x0000c1c1 }, /* TPBUFFER62 */ { STB0899_OFF0_TP_BUFFER63 , STB0899_BASE_TP_BUFFER63 , 0x0000c1c0 }, /* TPBUFFER63 */ { STB0899_OFF0_RESET_CNTRL , STB0899_BASE_RESET_CNTRL , 0x00000001 }, /* RESETCNTRL */ { STB0899_OFF0_ACM_ENABLE , STB0899_BASE_ACM_ENABLE , 0x00005654 }, /* ACMENABLE */ { STB0899_OFF0_DESCR_CNTRL , STB0899_BASE_DESCR_CNTRL , 0x00000000 }, /* DESCRCNTRL */ { STB0899_OFF0_CSM_CNTRL1 , STB0899_BASE_CSM_CNTRL1 , 0x00020019 }, /* CSMCNTRL1 */ { STB0899_OFF0_CSM_CNTRL2 , STB0899_BASE_CSM_CNTRL2 , 0x004b3237 }, /* CSMCNTRL2 */ { STB0899_OFF0_CSM_CNTRL3 , STB0899_BASE_CSM_CNTRL3 , 0x0003dd17 }, /* CSMCNTRL3 */ { STB0899_OFF0_CSM_CNTRL4 , STB0899_BASE_CSM_CNTRL4 , 0x00008008 }, /* CSMCNTRL4 */ { STB0899_OFF0_UWP_CNTRL1 , STB0899_BASE_UWP_CNTRL1 , 0x002a3106 }, /* UWPCNTRL1 */ { STB0899_OFF0_UWP_CNTRL2 , STB0899_BASE_UWP_CNTRL2 , 0x0006140a }, /* UWPCNTRL2 */ { STB0899_OFF0_UWP_STAT1 , STB0899_BASE_UWP_STAT1 , 0x00008000 }, /* UWPSTAT1 */ { STB0899_OFF0_UWP_STAT2 , STB0899_BASE_UWP_STAT2 , 0x00000000 }, /* UWPSTAT2 */ { STB0899_OFF0_DMD_STAT2 , STB0899_BASE_DMD_STAT2 , 0x00000000 }, /* DMDSTAT2 */ { STB0899_OFF0_FREQ_ADJ_SCALE , STB0899_BASE_FREQ_ADJ_SCALE , 0x00000471 }, /* FREQADJSCALE */ { STB0899_OFF0_UWP_CNTRL3 , STB0899_BASE_UWP_CNTRL3 , 0x017b0465 }, /* UWPCNTRL3 */ { STB0899_OFF0_SYM_CLK_SEL , STB0899_BASE_SYM_CLK_SEL , 0x00000002 }, /* SYMCLKSEL */ { STB0899_OFF0_SOF_SRCH_TO , STB0899_BASE_SOF_SRCH_TO , 0x00196464 }, /* SOFSRCHTO */ { STB0899_OFF0_ACQ_CNTRL1 , STB0899_BASE_ACQ_CNTRL1 , 0x00000603 }, /* ACQCNTRL1 */ { STB0899_OFF0_ACQ_CNTRL2 , STB0899_BASE_ACQ_CNTRL2 , 0x02046666 }, /* ACQCNTRL2 */ { STB0899_OFF0_ACQ_CNTRL3 , STB0899_BASE_ACQ_CNTRL3 , 0x10046583 }, /* ACQCNTRL3 */ { STB0899_OFF0_FE_SETTLE , STB0899_BASE_FE_SETTLE , 0x00010404 }, /* FESETTLE */ { STB0899_OFF0_AC_DWELL , STB0899_BASE_AC_DWELL , 0x0002aa8a }, /* ACDWELL */ { STB0899_OFF0_ACQUIRE_TRIG , STB0899_BASE_ACQUIRE_TRIG , 0x00000000 }, /* ACQUIRETRIG */ { STB0899_OFF0_LOCK_LOST , STB0899_BASE_LOCK_LOST , 0x00000001 }, /* LOCKLOST */ { STB0899_OFF0_ACQ_STAT1 , STB0899_BASE_ACQ_STAT1 , 0x00000500 }, /* ACQSTAT1 */ { STB0899_OFF0_ACQ_TIMEOUT , STB0899_BASE_ACQ_TIMEOUT , 0x0028a0a0 }, /* ACQTIMEOUT */ { STB0899_OFF0_ACQ_TIME , STB0899_BASE_ACQ_TIME , 0x00000000 }, /* ACQTIME */ { STB0899_OFF0_FINAL_AGC_CNTRL , STB0899_BASE_FINAL_AGC_CNTRL , 0x00800c17 }, /* FINALAGCCNTRL*/ { STB0899_OFF0_FINAL_AGC_GAIN , STB0899_BASE_FINAL_AGC_GAIN , 0x00000000 }, /* FINALAGCCGAIN*/ { STB0899_OFF0_EQUALIZER_INIT , STB0899_BASE_EQUALIZER_INIT , 0x00000000 }, /* EQUILIZERINIT*/ { STB0899_OFF0_EQ_CNTRL , STB0899_BASE_EQ_CNTRL , 0x00054802 }, /* EQCNTL */ { STB0899_OFF0_EQ_I_INIT_COEFF_0, STB0899_BASE_EQ_I_INIT_COEFF_N, 0x00000000 }, /* EQIINITCOEFF0 */ { STB0899_OFF1_EQ_I_INIT_COEFF_1, STB0899_BASE_EQ_I_INIT_COEFF_N, 0x00000000 }, /* EQIINITCOEFF1 */ { STB0899_OFF2_EQ_I_INIT_COEFF_2, STB0899_BASE_EQ_I_INIT_COEFF_N, 0x00000000 }, /* EQIINITCOEFF2 */ { STB0899_OFF3_EQ_I_INIT_COEFF_3, STB0899_BASE_EQ_I_INIT_COEFF_N, 0x00000000 }, /* EQIINITCOEFF3 */ { STB0899_OFF4_EQ_I_INIT_COEFF_4, STB0899_BASE_EQ_I_INIT_COEFF_N, 0x00000000 }, /* EQIINITCOEFF4 */ { STB0899_OFF5_EQ_I_INIT_COEFF_5, STB0899_BASE_EQ_I_INIT_COEFF_N, 0x00000400 }, /* EQIINITCOEFF5 */ { STB0899_OFF6_EQ_I_INIT_COEFF_6, STB0899_BASE_EQ_I_INIT_COEFF_N, 0x00000000 }, /* EQIINITCOEFF6 */ { STB0899_OFF7_EQ_I_INIT_COEFF_7, STB0899_BASE_EQ_I_INIT_COEFF_N, 0x00000000 }, /* EQIINITCOEFF7 */ { STB0899_OFF8_EQ_I_INIT_COEFF_8, STB0899_BASE_EQ_I_INIT_COEFF_N, 0x00000000 }, /* EQIINITCOEFF8 */ { STB0899_OFF9_EQ_I_INIT_COEFF_9, STB0899_BASE_EQ_I_INIT_COEFF_N, 0x00000000 }, /* EQIINITCOEFF9 */ { STB0899_OFFa_EQ_I_INIT_COEFF_10,STB0899_BASE_EQ_I_INIT_COEFF_N, 0x00000000 }, /* EQIINITCOEFF10*/ { STB0899_OFF0_EQ_Q_INIT_COEFF_0, STB0899_BASE_EQ_Q_INIT_COEFF_N, 0x00000000 }, /* EQQINITCOEFF0 */ { STB0899_OFF1_EQ_Q_INIT_COEFF_1, STB0899_BASE_EQ_Q_INIT_COEFF_N, 0x00000000 }, /* EQQINITCOEFF1 */ { STB0899_OFF2_EQ_Q_INIT_COEFF_2, STB0899_BASE_EQ_Q_INIT_COEFF_N, 0x00000000 }, /* EQQINITCOEFF2 */ { STB0899_OFF3_EQ_Q_INIT_COEFF_3, STB0899_BASE_EQ_Q_INIT_COEFF_N, 0x00000000 }, /* EQQINITCOEFF3 */ { STB0899_OFF4_EQ_Q_INIT_COEFF_4, STB0899_BASE_EQ_Q_INIT_COEFF_N, 0x00000000 }, /* EQQINITCOEFF4 */ { STB0899_OFF5_EQ_Q_INIT_COEFF_5, STB0899_BASE_EQ_Q_INIT_COEFF_N, 0x00000000 }, /* EQQINITCOEFF5 */ { STB0899_OFF6_EQ_Q_INIT_COEFF_6, STB0899_BASE_EQ_Q_INIT_COEFF_N, 0x00000000 }, /* EQQINITCOEFF6 */ { STB0899_OFF7_EQ_Q_INIT_COEFF_7, STB0899_BASE_EQ_Q_INIT_COEFF_N, 0x00000000 }, /* EQQINITCOEFF7 */ { STB0899_OFF8_EQ_Q_INIT_COEFF_8, STB0899_BASE_EQ_Q_INIT_COEFF_N, 0x00000000 }, /* EQQINITCOEFF8 */ { STB0899_OFF9_EQ_Q_INIT_COEFF_9, STB0899_BASE_EQ_Q_INIT_COEFF_N, 0x00000000 }, /* EQQINITCOEFF9 */ { STB0899_OFFa_EQ_Q_INIT_COEFF_10,STB0899_BASE_EQ_Q_INIT_COEFF_N, 0x00000000 }, /* EQQINITCOEFF10*/ { STB0899_OFF0_EQ_I_OUT_COEFF_0 , STB0899_BASE_EQ_I_OUT_COEFF_N , 0x00000000 }, /* EQICOEFFSOUT0 */ { STB0899_OFF1_EQ_I_OUT_COEFF_1 , STB0899_BASE_EQ_I_OUT_COEFF_N , 0x00000000 }, /* EQICOEFFSOUT1 */ { STB0899_OFF2_EQ_I_OUT_COEFF_2 , STB0899_BASE_EQ_I_OUT_COEFF_N , 0x00000000 }, /* EQICOEFFSOUT2 */ { STB0899_OFF3_EQ_I_OUT_COEFF_3 , STB0899_BASE_EQ_I_OUT_COEFF_N , 0x00000000 }, /* EQICOEFFSOUT3 */ { STB0899_OFF4_EQ_I_OUT_COEFF_4 , STB0899_BASE_EQ_I_OUT_COEFF_N , 0x00000000 }, /* EQICOEFFSOUT4 */ { STB0899_OFF5_EQ_I_OUT_COEFF_5 , STB0899_BASE_EQ_I_OUT_COEFF_N , 0x00000000 }, /* EQICOEFFSOUT5 */ { STB0899_OFF6_EQ_I_OUT_COEFF_6 , STB0899_BASE_EQ_I_OUT_COEFF_N , 0x00000000 }, /* EQICOEFFSOUT6 */ { STB0899_OFF7_EQ_I_OUT_COEFF_7 , STB0899_BASE_EQ_I_OUT_COEFF_N , 0x00000000 }, /* EQICOEFFSOUT7 */ { STB0899_OFF8_EQ_I_OUT_COEFF_8 , STB0899_BASE_EQ_I_OUT_COEFF_N , 0x00000000 }, /* EQICOEFFSOUT8 */ { STB0899_OFF9_EQ_I_OUT_COEFF_9 , STB0899_BASE_EQ_I_OUT_COEFF_N , 0x00000000 }, /* EQICOEFFSOUT9 */ { STB0899_OFFa_EQ_I_OUT_COEFF_10,STB0899_BASE_EQ_I_OUT_COEFF_N , 0x00000000 }, /* EQICOEFFSOUT10*/ { STB0899_OFF0_EQ_Q_OUT_COEFF_0 , STB0899_BASE_EQ_Q_OUT_COEFF_N , 0x00000000 }, /* EQQCOEFFSOUT0 */ { STB0899_OFF1_EQ_Q_OUT_COEFF_1 , STB0899_BASE_EQ_Q_OUT_COEFF_N , 0x00000000 }, /* EQQCOEFFSOUT1 */ { STB0899_OFF2_EQ_Q_OUT_COEFF_2 , STB0899_BASE_EQ_Q_OUT_COEFF_N , 0x00000000 }, /* EQQCOEFFSOUT2 */ { STB0899_OFF3_EQ_Q_OUT_COEFF_3 , STB0899_BASE_EQ_Q_OUT_COEFF_N , 0x00000000 }, /* EQQCOEFFSOUT3 */ { STB0899_OFF4_EQ_Q_OUT_COEFF_4 , STB0899_BASE_EQ_Q_OUT_COEFF_N , 0x00000000 }, /* EQQCOEFFSOUT4 */ { STB0899_OFF5_EQ_Q_OUT_COEFF_5 , STB0899_BASE_EQ_Q_OUT_COEFF_N , 0x00000000 }, /* EQQCOEFFSOUT5 */ { STB0899_OFF6_EQ_Q_OUT_COEFF_6 , STB0899_BASE_EQ_Q_OUT_COEFF_N , 0x00000000 }, /* EQQCOEFFSOUT6 */ { STB0899_OFF7_EQ_Q_OUT_COEFF_7 , STB0899_BASE_EQ_Q_OUT_COEFF_N , 0x00000000 }, /* EQQCOEFFSOUT7 */ { STB0899_OFF8_EQ_Q_OUT_COEFF_8 , STB0899_BASE_EQ_Q_OUT_COEFF_N , 0x00000000 }, /* EQQCOEFFSOUT8 */ { STB0899_OFF9_EQ_Q_OUT_COEFF_9 , STB0899_BASE_EQ_Q_OUT_COEFF_N , 0x00000000 }, /* EQQCOEFFSOUT9 */ { STB0899_OFFa_EQ_Q_OUT_COEFF_10, STB0899_BASE_EQ_Q_OUT_COEFF_N , 0x00000000 }, /* EQQCOEFFSOUT10*/ { 0xffff , 0xffffffff , 0xffffffff }, }; static const struct stb0899_s2_reg stb0899_s2_init_4[] = { { STB0899_OFF0_BLOCK_LNGTH , STB0899_BASE_BLOCK_LNGTH , 0x00000008 }, /* BLOCKLNGTH */ { STB0899_OFF0_ROW_STR , STB0899_BASE_ROW_STR , 0x000000b4 }, /* ROWSTR */ { STB0899_OFF0_BN_END_ADDR , STB0899_BASE_BN_END_ADDR , 0x000004b5 }, /* BNANDADDR */ { STB0899_OFF0_CN_END_ADDR , STB0899_BASE_CN_END_ADDR , 0x00000b4b }, /* CNANDADDR */ { STB0899_OFF0_INFO_LENGTH , STB0899_BASE_INFO_LENGTH , 0x00000078 }, /* INFOLENGTH */ { STB0899_OFF0_BOT_ADDR , STB0899_BASE_BOT_ADDR , 0x000001e0 }, /* BOT_ADDR */ { STB0899_OFF0_BCH_BLK_LN , STB0899_BASE_BCH_BLK_LN , 0x0000a8c0 }, /* BCHBLKLN */ { STB0899_OFF0_BCH_T , STB0899_BASE_BCH_T , 0x0000000c }, /* BCHT */ { STB0899_OFF0_CNFG_MODE , STB0899_BASE_CNFG_MODE , 0x00000001 }, /* CNFGMODE */ { STB0899_OFF0_LDPC_STAT , STB0899_BASE_LDPC_STAT , 0x0000000d }, /* LDPCSTAT */ { STB0899_OFF0_ITER_SCALE , STB0899_BASE_ITER_SCALE , 0x00000040 }, /* ITERSCALE */ { STB0899_OFF0_INPUT_MODE , STB0899_BASE_INPUT_MODE , 0x00000000 }, /* INPUTMODE */ { STB0899_OFF0_LDPCDECRST , STB0899_BASE_LDPCDECRST , 0x00000000 }, /* LDPCDECRST */ { STB0899_OFF0_CLK_PER_BYTE_RW , STB0899_BASE_CLK_PER_BYTE_RW , 0x00000008 }, /* CLKPERBYTE */ { STB0899_OFF0_BCH_ERRORS , STB0899_BASE_BCH_ERRORS , 0x00000000 }, /* BCHERRORS */ { STB0899_OFF0_LDPC_ERRORS , STB0899_BASE_LDPC_ERRORS , 0x00000000 }, /* LDPCERRORS */ { STB0899_OFF0_BCH_MODE , STB0899_BASE_BCH_MODE , 0x00000000 }, /* BCHMODE */ { STB0899_OFF0_ERR_ACC_PER , STB0899_BASE_ERR_ACC_PER , 0x00000008 }, /* ERRACCPER */ { STB0899_OFF0_BCH_ERR_ACC , STB0899_BASE_BCH_ERR_ACC , 0x00000000 }, /* BCHERRACC */ { STB0899_OFF0_FEC_TP_SEL , STB0899_BASE_FEC_TP_SEL , 0x00000000 }, /* FECTPSEL */ { 0xffff , 0xffffffff , 0xffffffff }, }; static const struct stb0899_s1_reg stb0899_s1_init_5[] = { { STB0899_TSTCK , 0x00 }, { STB0899_TSTRES , 0x00 }, { STB0899_TSTOUT , 0x00 }, { STB0899_TSTIN , 0x00 }, { STB0899_TSTSYS , 0x00 }, { STB0899_TSTCHIP , 0x00 }, { STB0899_TSTFREE , 0x00 }, { STB0899_TSTI2C , 0x00 }, { STB0899_BITSPEEDM , 0x00 }, { STB0899_BITSPEEDL , 0x00 }, { STB0899_TBUSBIT , 0x00 }, { STB0899_TSTDIS , 0x00 }, { STB0899_TSTDISRX , 0x00 }, { STB0899_TSTJETON , 0x00 }, { STB0899_TSTDCADJ , 0x00 }, { STB0899_TSTAGC1 , 0x00 }, { STB0899_TSTAGC1N , 0x00 }, { STB0899_TSTPOLYPH , 0x00 }, { STB0899_TSTR , 0x00 }, { STB0899_TSTAGC2 , 0x00 }, { STB0899_TSTCTL1 , 0x00 }, { STB0899_TSTCTL2 , 0x00 }, { STB0899_TSTCTL3 , 0x00 }, { STB0899_TSTDEMAP , 0x00 }, { STB0899_TSTDEMAP2 , 0x00 }, { STB0899_TSTDEMMON , 0x00 }, { STB0899_TSTRATE , 0x00 }, { STB0899_TSTSELOUT , 0x00 }, { STB0899_TSYNC , 0x00 }, { STB0899_TSTERR , 0x00 }, { STB0899_TSTRAM1 , 0x00 }, { STB0899_TSTVSELOUT , 0x00 }, { STB0899_TSTFORCEIN , 0x00 }, { STB0899_TSTRS1 , 0x00 }, { STB0899_TSTRS2 , 0x00 }, { STB0899_TSTRS3 , 0x00 }, { STB0899_GHOSTREG , 0x81 }, { 0xffff , 0xff }, }; #define STB0899_DVBS2_ESNO_AVE 3 #define STB0899_DVBS2_ESNO_QUANT 32 #define STB0899_DVBS2_AVFRAMES_COARSE 10 #define STB0899_DVBS2_AVFRAMES_FINE 20 #define STB0899_DVBS2_MISS_THRESHOLD 6 #define STB0899_DVBS2_UWP_THRESHOLD_ACQ 1125 #define STB0899_DVBS2_UWP_THRESHOLD_TRACK 758 #define STB0899_DVBS2_UWP_THRESHOLD_SOF 1350 #define STB0899_DVBS2_SOF_SEARCH_TIMEOUT 1664100 #define STB0899_DVBS2_BTR_NCO_BITS 28 #define STB0899_DVBS2_BTR_GAIN_SHIFT_OFFSET 15 #define STB0899_DVBS2_CRL_NCO_BITS 30 #define STB0899_DVBS2_LDPC_MAX_ITER 70 #endif //__STB0899_CFG_H
747477eb7d581835c31aaead400fdcff7421ea1b
21c92afbd7fd022a206fb31294c523aebb770104
/SuiteSparse/UMFPACK/Source/umf_analyze.h
4c7c11cc0ccc63c393688578c05cff9656b063ea
[ "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-unknown-license-reference", "GPL-2.0-or-later", "GPL-3.0-only", "LGPL-2.1-or-later", "LGPL-2.0-or-later", "GPL-1.0-or-later", "LicenseRef-scancode-other-copyleft", "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
permissive
jlblancoc/suitesparse-metis-for-windows
70e6bcab2b525afb41758d61f823efa0618f67cf
5ee2eb4bc7bfd6d27af2f7fb027b1545cfc0fa3f
refs/heads/master
2023-08-30T21:15:39.624300
2023-03-09T10:16:48
2023-03-09T10:16:48
16,236,582
423
251
BSD-3-Clause
2023-03-09T10:18:08
2014-01-25T18:06:21
C
UTF-8
C
false
false
1,049
h
umf_analyze.h
/* -------------------------------------------------------------------------- */ /* Copyright (c) 2005-2012 by Timothy A. Davis, http://www.suitesparse.com. */ /* All Rights Reserved. See ../Doc/License.txt for License. */ /* -------------------------------------------------------------------------- */ GLOBAL Int UMF_analyze ( Int n_row, /* A is n_row-by-n_col */ Int n_col, Int Ai [ ], /* Ai [Ap [0]..Ap[n_row]-1]: column indices */ Int Ap [ ], /* of size MAX (n_row, n_col) + 1 */ Int Up [ ], /* workspace of size n_col, and output column perm. */ Int fixQ, /* temporary workspaces: */ Int W [ ], /* W [0..n_col-1] */ Int Link [ ], /* Link [0..n_col-1] */ /* output: information about each frontal matrix: */ Int Front_ncols [ ], /* size n_col */ Int Front_nrows [ ], /* of size n_col */ Int Front_npivcol [ ], /* of size n_col */ Int Front_parent [ ], /* of size n_col */ Int *nfr_out, Int *p_ncompactions /* number of compactions in UMF_analyze */ ) ;
3f9eeecec1b129f4c870e8de05181da5154bd624
e73547787354afd9b717ea57fe8dd0695d161821
/src/battle/area/pra/stage/pra_04.c
af43aa3b13f2a4b3f0c73998f59c186c0cb71f32
[]
no_license
pmret/papermario
8b514b19653cef8d6145e47499b3636b8c474a37
9774b26d93f1045dd2a67e502b6efc9599fb6c31
refs/heads/main
2023-08-31T07:09:48.951514
2023-08-21T18:07:08
2023-08-21T18:07:08
287,151,133
904
139
null
2023-09-14T02:44:23
2020-08-13T01:22:57
C
UTF-8
C
false
false
75
c
pra_04.c
#include "../area.h" #include "battle/common/stage/area_pra/pra_04.inc.c"
36a2a4672ff99e870a2b5b571a1499db7399e3c0
0cc343d927d5db6693006018986715c43acab961
/examples/spouse-user.c
b3f1f76db2a9a595b1ace04ab2682f678a675ebe
[ "MIT" ]
permissive
verifast/verifast
ec0101fc4a69bd33c5f66be4444169c4e060ead8
d152da790c7ebf72ce616533a6c83082629adbdb
refs/heads/master
2023-08-25T00:13:51.464802
2023-08-13T10:00:00
2023-08-13T10:00:00
14,519,163
325
64
NOASSERTION
2023-08-10T21:16:08
2013-11-19T08:57:02
OCaml
UTF-8
C
false
false
7,087
c
spouse-user.c
#include "spouse.h" #include "stdio.h" #include "arraylist.h" //@ #include "ghostlist.gh" #include "io_helper.h" #include <stdbool.h> /*@ predicate_ctor person_ctor(int gid)(struct person* p) = p!=0 &*& person(p, ?spouse) &*& spouse == 0 ? ghost_list_member_handle(gid, p) : ghost_list_member_handle(gid, spouse); lemma void remove_diff_mem<t>(list<t> xs, t x, t y) requires mem(x, xs) == true &*& mem(y, xs) == true &*& x != y; ensures mem(y, remove(x, xs)) == true; { switch(xs) { case nil: case cons(h, t): if(h == x) { } else { if(h == y) { } else { remove_diff_mem(t, x, y); } } } } lemma void remove_diff_index_mem<t>(list<t> xs, int i, int j); requires mem(nth(i, xs), xs) == true &*& mem(nth(j, xs), xs) == true &*& i != j; ensures mem(nth(j, xs), remove(nth(i, xs), xs)) == true; lemma void foreach_remove_nth<t>(int n, list<t> xs); requires foreach(xs, ?p) &*& 0 <= n &*& n < length(xs); ensures foreach(remove_nth(n, xs), p) &*& p(nth(n, xs)); lemma void remove_nth_mem<t>(list<t> xs, int n, t x) requires 0 <= n &*& n < length(xs) &*& mem(x, xs) == true &*& nth(n, xs) != x; ensures mem(x, remove_nth(n, xs)) == true; { switch(xs) { case nil: case cons(h, t): if(h == x) { } else { if(n == 0) { } else { remove_nth_mem(t, n - 1, x); } } } } @*/ int main() //@ : main //@ requires true; //@ ensures true; { struct arraylist *persons = create_arraylist(); puts("Welcome to the Municipal Registry\n"); //@ int gid = create_ghost_list<void*>(); //@ close foreach(nil, person_ctor(gid)); while(true) /*@ invariant arraylist(persons, ?ps) &*& ghost_list(gid, ps) &*& foreach(ps, person_ctor(gid)); @*/ { int choice = 0; puts("Menu:\n"); puts(" 1. Register birth.\n"); puts(" 2. Register marriage.\n"); puts(" 3. Register divorce.\n"); puts(" 4. Register death.\n"); puts(" 5. Exit.\n"); choice = read_int(); if(choice == 1) { struct person *p = create_person(); list_add(persons, p); //@ ghost_list_add_last(gid, p); //@ close person_ctor(gid)(p); //@ close foreach(nil, person_ctor(gid)); //@ close foreach(cons(p, nil), person_ctor(gid)); //@ foreach_append(ps, cons(p, nil)); } else if (choice == 2) { int index1 = 0; int index2 = 0; int max = 0; struct person* p1 = 0; struct person* p2 = 0; struct person* spouse1 = 0; struct person* spouse2 = 0; puts("Enter the index of the first person.\n"); index1 = read_int(); puts("Enter the index of the second person.\n"); index2 = read_int(); max = list_length(persons); if(0 <= index1 && index1 < max && 0<= index2 && index2 < max && index1 != index2) { p1 = list_get(persons, index1); p2 = list_get(persons, index2); //@ foreach_remove(p1, ps); //@ open person_ctor(gid)(p1); spouse1 = person_get_spouse(p1); //@ remove_diff_index_mem(ps, index1, index2); //@ foreach_remove(p2, remove(p1, ps)); //@ open person_ctor(gid)(p2); spouse2 = person_get_spouse(p2); if(spouse1 == 0 && spouse2 == 0) { marry(p1, p2); //@ close person_ctor(gid)(p1); //@ close person_ctor(gid)(p2); //@ foreach_unremove(p2, remove(p1, ps)); //@ foreach_unremove(p1, ps); } else { //@ close person_ctor(gid)(p1); //@ close person_ctor(gid)(p2); //@ foreach_unremove(p2, remove(p1, ps)); //@ foreach_unremove(p1, ps); puts("One of the persons is already married."); } } else { puts("Index out of bounds or same index."); } } else if (choice == 3) { int index = 0; int max = 0; struct person *p = 0; struct person *spouse = 0; puts("Enter the husband's index."); index = read_int(); max = list_length(persons); if(0 <= index && index < max) { p = list_get(persons, index); //@ foreach_remove(p, ps); //@ open person_ctor(gid)(p); spouse = person_get_spouse(p); //@ spouse_diff(p); if(spouse != 0) { //@ assert ghost_list_member_handle(?id, ?d); //@ ghost_list_member_handle_lemma(id, d); //@ remove_diff_mem(ps, p, spouse); //@ foreach_remove(spouse, remove(p, ps)); //@ open person_ctor(gid)(spouse); //@ married_lemma(p); divorce(p); //@ close person_ctor(gid)(p); //@ close person_ctor(gid)(spouse); //@ foreach_unremove(spouse, remove(p, ps)); //@ foreach_unremove(p, ps); } else { puts("The person is not married."); //@ close person_ctor(gid)(p); //@ foreach_unremove(p, ps); } } else { puts("Invalid index"); } } else if (choice == 4) { int index = 0; int max = 0; struct person *p = 0; struct person *spouse = 0; puts("Enter a person's index."); index = read_int(); max = list_length(persons); if(0 <= index && index < max) { p = list_get(persons, index); list_remove_nth(persons, index); //@ foreach_remove_nth(index, ps); //@ open person_ctor(gid)(nth(index, ps)); spouse = person_get_spouse(p); //@ spouse_diff(p); if(spouse != 0) { //@ assert ghost_list_member_handle(?id, ?d); //@ ghost_list_member_handle_lemma(id, d); //@ remove_nth_mem(ps, index, spouse); //@ foreach_remove(spouse, remove_nth(index, ps)); //@ open person_ctor(gid)(spouse); //@ married_lemma(p); } //@ ghost_list_remove_nth(gid, index); die(p); if(spouse != 0) { //@ close person_ctor(gid)(spouse); //@ foreach_unremove(spouse, remove_nth(index, ps)); } } else { puts("Invalid index."); } } else if (choice == 5) { int i = list_length(persons); while(i != 0) //@ invariant arraylist(persons, ?ps0) &*& ghost_list(gid, ps0) &*& foreach(ps0, person_ctor(gid)) &*& i == length(ps0); { struct person* p = list_get(persons, 0); struct person* spouse = 0; list_remove_nth(persons, 0); //@ foreach_remove_nth(0, ps0); //@ open person_ctor(gid)(p); //@ spouse_diff(p); spouse = person_get_spouse(p); //@ assume(spouse == 0); // todo //@ ghost_list_remove_nth(gid, 0); die(p); i = list_length(persons); } //@ switch(ps0) { case nil: case cons(h0, t0): } //@ ghost_list_dispose(); //@ open foreach(nil, _); list_dispose(persons); return 0; } else { puts("Invalid Choice"); } } }
73ba33ccdea9db2340cd13ccbeb2086acd82cf1e
cfa39a4c71a733f39bf6d1f32ef540d3a49d608c
/tests/sys_epoll/epoll.c
3d89341de7e1d92e9400b912475cc28dcd4eebb4
[ "MIT" ]
permissive
redox-os/relibc
7d622ae036ccfedc31cbb19e7453f9caa1df873c
1ef79540776f2290924e5d996ef38c13e9f1d505
refs/heads/master
2023-08-31T01:42:51.820667
2023-06-13T11:34:49
2023-06-13T11:34:49
123,522,329
834
73
MIT
2023-03-08T03:47:15
2018-03-02T02:58:07
Rust
UTF-8
C
false
false
4,535
c
epoll.c
#include <fcntl.h> #include <stdio.h> #include <sys/epoll.h> #include <sys/wait.h> #include <unistd.h> int reader(int fd) { // Create an epoll file int epollfd = epoll_create1(EPOLL_CLOEXEC); if (epollfd < 0) { perror("epoll_create1"); return 1; } // Register for events from the reader file struct epoll_event ev; ev.events = EPOLLIN; ev.data.fd = fd; if (epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &ev) < 0) { perror("epoll_ctl"); return 1; } // Process exactly 1024 events struct epoll_event events[8]; for (int i = 0; i < 1024; i++) { // Wait for the next event int nfds = epoll_wait(epollfd, events, sizeof(events)/sizeof(struct epoll_event), -1); if (nfds < 0) { perror("epoll_wait"); return 1; } // For each event received for (int n = 0; n < nfds; n++) { // If the event is the reader file if (events[n].data.fd == fd) { // Read the current event count int writer_i; int count = read(fd, &writer_i, sizeof(writer_i)); if (count < 0) { perror("read"); return 1; } else if (count < sizeof(writer_i)) { fprintf(stderr, "read %d instead of %d\n", count, sizeof(writer_i)); return 1; } // Make sure the writer's event count matches our own if (i != writer_i) { fprintf(stderr, "received event count %d instead of %d\n", writer_i, i); return 1; } printf("%d == %d\n", i, writer_i); } else { // Otherwise, return an error fprintf(stderr, "unknown fd %d\n", events[n].data.fd); return 1; } } } return 0; } int writer(int fd) { // Create an epoll file int epollfd = epoll_create1(EPOLL_CLOEXEC); if (epollfd < 0) { perror("epoll_create1"); return 1; } // Register for events from the writer file struct epoll_event ev; ev.events = EPOLLOUT; ev.data.fd = fd; if (epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &ev) < 0) { perror("epoll_ctl"); return 1; } // Process exactly 1024 events struct epoll_event events[8]; for (int i = 0; i < 1024; i++) { // Wait for the next event int nfds = epoll_wait(epollfd, events, sizeof(events)/sizeof(struct epoll_event), -1); if (nfds < 0) { perror("epoll_wait"); return 1; } // For each event received for (int n = 0; n < nfds; n++) { // If the event is the writer file if (events[n].data.fd == fd) { // Write the current event count int count = write(fd, &i, sizeof(i)); if (count < 0) { perror("write"); return 1; } else if (count < sizeof(i)) { fprintf(stderr, "wrote %d instead of %d\n", count, sizeof(i)); return 1; } } else { // Otherwise, return an error fprintf(stderr, "unknown fd %d\n", events[n].data.fd); return 1; } } } return 0; } int main(int argc, char **argv) { // Create a non-blocking pipe to use for epoll testing int pipefd[2]; if (pipe2(pipefd, O_CLOEXEC | O_NONBLOCK) < 0) { perror("pipe2"); return 1; } pid_t pid = fork(); if (pid < 0) { perror("fork"); return 1; } else if (pid == 0) { // Child process will read events close(pipefd[1]); return reader(pipefd[0]); } else { // Parent process will write events close(pipefd[0]); int ret = writer(pipefd[1]); // Wait for child process int status = 0; if (waitpid(pid, &status, 0) != pid) { perror("waitpid"); return 1; } // If writer failed, return exit status if (ret != 0) { return ret; } // If child exited with exit status if (WIFEXITED(status)) { // Return the child's exit status return WEXITSTATUS(status); } else { // Otherwise, return 1 return 1; } } }
52a0d414f69f6543e89a96020fbebb377efaf442
7f98e5cf5c7856da22d01107c4ac3d73e0587a2b
/src/vendor.h
d925fa9bdf31943859e8869dcf561e513255402e
[ "MIT" ]
permissive
InfiniteRasa/Game-Server
0d2883f968137278a647360086ddd9096b5bac8a
4a9ab5f1fcdf6a18ab6911c384189cc41ddae651
refs/heads/experimental
2020-12-29T01:41:24.853909
2016-08-18T22:27:20
2016-08-18T22:27:20
2,144,264
101
80
null
2016-08-18T22:27:21
2011-08-02T18:32:06
C++
UTF-8
C
false
false
353
h
vendor.h
typedef struct { uint32 itemTemplateId; uint32 stacksize; sint32 sequence; item_t* itemInstance; // physical entity that is used to display the item }vendorItemEntry_t; typedef struct _vendorData_t { sint32 vendorPackageId; // list of sold items sint32 numberOfSoldItems; vendorItemEntry_t* soldItemList; }vendorData_t; void vendor_init();
600856460bb673b0e71d2927527c51e5490eadf3
bb7a80648bf830c2fb813cdb335032142cbee06d
/mod/mpp/3516a/inc/hisisdk/mpi_gdc.h
724de93bc63c25a61ca125d5ae0a8892c3ea0d04
[]
no_license
openhisilicon/HIVIEW
44574a29da60e3bb400c7ce97c722dfc9f2959e6
60bbfa5cb66cc82f0cdc0bba1242dbc9491b0f37
refs/heads/master
2023-09-01T01:42:19.069724
2023-08-31T09:57:39
2023-08-31T09:57:39
189,036,134
336
121
null
2023-01-07T14:10:22
2019-05-28T13:41:40
C
UTF-8
C
false
false
2,978
h
mpi_gdc.h
/* * Copyright (C) Hisilicon Technologies Co., Ltd. 2019. All rights reserved. * Description: gdc mpi declaration * Author: Hisilicon multimedia software group * Create: 2019/06/27 */ #ifndef __MPI_GDC_H__ #define __MPI_GDC_H__ #include "hi_common.h" #include "hi_comm_video.h" #include "hi_comm_gdc.h" #ifdef __cplusplus #if __cplusplus extern "C" { #endif #endif /* __cplusplus */ /* * Description : Begin a gdc job,then add task into the job,gdc will finish all the task in the job. * Input : GDC_HANDLE *phHandle * Output : None */ HI_S32 HI_MPI_GDC_BeginJob(GDC_HANDLE *phHandle); /* * Description : End a job,all tasks in the job will be submmitted to gdc * Input : GDC_HANDLE hHandle * Output : None */ HI_S32 HI_MPI_GDC_EndJob(GDC_HANDLE hHandle); /* * Description : Cancel a job ,then all tasks in the job will not be submmitted to gdc * Input : GDC_HANDLE hHandle * Output : None */ HI_S32 HI_MPI_GDC_CancelJob(GDC_HANDLE hHandle); /* * Description : Add a task to a gdc job * Input : GDC_HANDLE hHandle * const GDC_TASK_ATTR_S *pstTask * const FISHEYE_ATTR_S *pstFisheyeAttr * Output : None */ HI_S32 HI_MPI_GDC_AddCorrectionTask(GDC_HANDLE hHandle, const GDC_TASK_ATTR_S *pstTask, const FISHEYE_ATTR_S *pstFisheyeAttr); /* * Description : Add a task to a gdc job * Input : GDC_HANDLE hHandle * const GDC_TASK_ATTR_S *pstTask * const FISHEYE_ATTR_EX_S *pstFishEyeAttrEx * HI_BOOL bCheckMode * Output : None */ HI_S32 HI_MPI_GDC_AddCorrectionExTask(GDC_HANDLE hHandle, const GDC_TASK_ATTR_S *pstTask, const FISHEYE_ATTR_EX_S *pstFishEyeAttrEx, HI_BOOL bCheckMode); /* * Description : Set Config * Input : GDC_HANDLE hHandle * const FISHEYE_JOB_CONFIG_S *stJobConfig * Output : None */ HI_S32 HI_MPI_GDC_SetConfig(GDC_HANDLE hHandle, const FISHEYE_JOB_CONFIG_S *pstJobConfig); /* * Description : Set Config * Input : GDC_HANDLE hHandle * const GDC_TASK_ATTR_S* pstTask * const GDC_PMF_ATTR_S* pstGdcPmfAttr * Output : None */ HI_S32 HI_MPI_GDC_AddPMFTask(GDC_HANDLE hHandle, const GDC_TASK_ATTR_S *pstTask, const GDC_PMF_ATTR_S *pstGdcPmfAttr); /* * Description : Query source point from correction point * Input : const GDC_FISHEYE_POINT_QUERY_ATTR_S *pstFisheyePointQueryAttr * const VIDEO_FRAME_INFO_S *pstVideoInfo * const POINT_S *pstDstPoint * POINT_S *pstSrcPoint * Output : None */ HI_S32 HI_MPI_GDC_FisheyePosQueryDst2Src(const GDC_FISHEYE_POINT_QUERY_ATTR_S *pstFisheyePointQueryAttr, const VIDEO_FRAME_INFO_S *pstVideoInfo, const POINT_S *pstDstPoint, POINT_S *pstSrcPoint); #ifdef __cplusplus #if __cplusplus } #endif #endif /* __cplusplus */ #endif /* __MPI_GDC_H__ */
b3e2dbc6ed4b81219938b4b7afe5a6fa2f8fe13f
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/modules/gpu/mali400/kernel_mode/driver/src/devicedrv/mali/linux/mali_ukk_wrappers.h
ac84e446bd1239b8c180e9b061f4627e3e996dce
[ "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later", "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
5,118
h
mali_ukk_wrappers.h
/* * Copyright (C) 2010-2015 ARM Limited. All rights reserved. * * This program is free software and is provided to you under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation, and any use by you of this program is subject to the terms of such GNU licence. * * A copy of the licence is included with the program, and can also be obtained from Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file mali_ukk_wrappers.h * Defines the wrapper functions for each user-kernel function */ #ifndef __MALI_UKK_WRAPPERS_H__ #define __MALI_UKK_WRAPPERS_H__ #include "mali_uk_types.h" #include "mali_osk.h" #ifdef __cplusplus extern "C" { #endif int wait_for_notification_wrapper(struct mali_session_data *session_data, _mali_uk_wait_for_notification_s __user *uargs); int get_api_version_wrapper(struct mali_session_data *session_data, _mali_uk_get_api_version_s __user *uargs); int get_api_version_v2_wrapper(struct mali_session_data *session_data, _mali_uk_get_api_version_v2_s __user *uargs); int get_user_settings_wrapper(struct mali_session_data *session_data, _mali_uk_get_user_settings_s __user *uargs); int post_notification_wrapper(struct mali_session_data *session_data, _mali_uk_post_notification_s __user *uargs); int request_high_priority_wrapper(struct mali_session_data *session_data, _mali_uk_request_high_priority_s __user *uargs); int pending_submit_wrapper(struct mali_session_data *session_data, _mali_uk_pending_submit_s __user *uargs); int mem_alloc_wrapper(struct mali_session_data *session_data, _mali_uk_alloc_mem_s __user *uargs); int mem_free_wrapper(struct mali_session_data *session_data, _mali_uk_free_mem_s __user *uargs); int mem_bind_wrapper(struct mali_session_data *session_data, _mali_uk_bind_mem_s __user *uargs); int mem_unbind_wrapper(struct mali_session_data *session_data, _mali_uk_unbind_mem_s __user *uargs); int mem_cow_wrapper(struct mali_session_data *session_data, _mali_uk_cow_mem_s __user *uargs); int mem_cow_modify_range_wrapper(struct mali_session_data *session_data, _mali_uk_cow_modify_range_s __user *uargs); int mem_resize_mem_wrapper(struct mali_session_data *session_data, _mali_uk_mem_resize_s __user *uargs); int mem_write_safe_wrapper(struct mali_session_data *session_data, _mali_uk_mem_write_safe_s __user *uargs); int mem_query_mmu_page_table_dump_size_wrapper(struct mali_session_data *session_data, _mali_uk_query_mmu_page_table_dump_size_s __user *uargs); int mem_dump_mmu_page_table_wrapper(struct mali_session_data *session_data, _mali_uk_dump_mmu_page_table_s __user *uargs); int mem_usage_get_wrapper(struct mali_session_data *session_data, _mali_uk_profiling_memory_usage_get_s __user *uargs); int timeline_get_latest_point_wrapper(struct mali_session_data *session, _mali_uk_timeline_get_latest_point_s __user *uargs); int timeline_wait_wrapper(struct mali_session_data *session, _mali_uk_timeline_wait_s __user *uargs); int timeline_create_sync_fence_wrapper(struct mali_session_data *session, _mali_uk_timeline_create_sync_fence_s __user *uargs); int soft_job_start_wrapper(struct mali_session_data *session, _mali_uk_soft_job_start_s __user *uargs); int soft_job_signal_wrapper(struct mali_session_data *session, _mali_uk_soft_job_signal_s __user *uargs); int pp_start_job_wrapper(struct mali_session_data *session_data, _mali_uk_pp_start_job_s __user *uargs); int pp_and_gp_start_job_wrapper(struct mali_session_data *session_data, _mali_uk_pp_and_gp_start_job_s __user *uargs); int pp_get_number_of_cores_wrapper(struct mali_session_data *session_data, _mali_uk_get_pp_number_of_cores_s __user *uargs); int pp_get_core_version_wrapper(struct mali_session_data *session_data, _mali_uk_get_pp_core_version_s __user *uargs); int pp_disable_wb_wrapper(struct mali_session_data *session_data, _mali_uk_pp_disable_wb_s __user *uargs); int gp_start_job_wrapper(struct mali_session_data *session_data, _mali_uk_gp_start_job_s __user *uargs); int gp_get_number_of_cores_wrapper(struct mali_session_data *session_data, _mali_uk_get_gp_number_of_cores_s __user *uargs); int gp_get_core_version_wrapper(struct mali_session_data *session_data, _mali_uk_get_gp_core_version_s __user *uargs); int gp_suspend_response_wrapper(struct mali_session_data *session_data, _mali_uk_gp_suspend_response_s __user *uargs); int profiling_add_event_wrapper(struct mali_session_data *session_data, _mali_uk_profiling_add_event_s __user *uargs); int profiling_report_sw_counters_wrapper(struct mali_session_data *session_data, _mali_uk_sw_counters_report_s __user *uargs); int profiling_get_stream_fd_wrapper(struct mali_session_data *session_data, _mali_uk_profiling_stream_fd_get_s __user *uargs); int profiling_control_set_wrapper(struct mali_session_data *session_data, _mali_uk_profiling_control_set_s __user *uargs); int vsync_event_report_wrapper(struct mali_session_data *session_data, _mali_uk_vsync_event_report_s __user *uargs); int map_errcode(_mali_osk_errcode_t err); #ifdef __cplusplus } #endif #endif /* __MALI_UKK_WRAPPERS_H__ */
0635b5100db888284254a0e6069582568c814fe3
e73547787354afd9b717ea57fe8dd0695d161821
/src/world/area_iwa/iwa_01/iwa_01_4_npc.c
b484a2d8d1c12f4f78fb27ad269090d8d2518d75
[]
no_license
pmret/papermario
8b514b19653cef8d6145e47499b3636b8c474a37
9774b26d93f1045dd2a67e502b6efc9599fb6c31
refs/heads/main
2023-08-31T07:09:48.951514
2023-08-21T18:07:08
2023-08-21T18:07:08
287,151,133
904
139
null
2023-09-14T02:44:23
2020-08-13T01:22:57
C
UTF-8
C
false
false
5,809
c
iwa_01_4_npc.c
#include "iwa_01.h" #include "world/common/enemy/MontyMole_StoneThrower.inc.c" #include "world/common/enemy/MontyMole_GroundAmbush.inc.c" #include "world/common/enemy/MontyMole_WallAmbush.inc.c" #include "world/common/enemy/Cleft.inc.c" NpcData N(NpcData_MontyMole_WallAmbush)[] = { { .id = NPC_MontyMole_01, .pos = { 340.0f, 70.0f, 101.0f }, .yaw = 0, .territory = { .wander = { .isFlying = FALSE, .moveSpeedOverride = NO_OVERRIDE_MOVEMENT_SPEED, .wanderShape = SHAPE_CYLINDER, .centerPos = { 345, 70, 245 }, .wanderSize = { 30 }, .detectShape = SHAPE_RECT, .detectPos = { 425, 70, 245 }, .detectSize = { 145, 300 }, } }, .settings = &N(NpcSettings_MontyMole_WallAmbush), .flags = ENEMY_FLAG_IGNORE_ENTITY_COLLISION, .drops = MONTY_MOLE_DROPS, .animations = MONTY_MOLE_AMBUSH_ANIMS, .aiDetectFlags = AI_DETECT_SIGHT, }, { .id = NPC_MontyMole_01_Hole, .pos = { 340.0f, 70.0f, 101.0f }, .yaw = 0, .territory = { .wander = { .isFlying = TRUE, .moveSpeedOverride = NO_OVERRIDE_MOVEMENT_SPEED, .wanderShape = SHAPE_CYLINDER, .centerPos = { 0, 0, 0 }, .wanderSize = { 0 }, .detectShape = SHAPE_CYLINDER, .detectPos = { 0, 0, 0 }, .detectSize = { 0 }, } }, .settings = &N(NpcSettings_MontyMole_WallAmbush_Hole), .flags = ENEMY_FLAG_PASSIVE | ENEMY_FLAG_DISABLE_AI | ENEMY_FLAG_IGNORE_WORLD_COLLISION | ENEMY_FLAG_IGNORE_PLAYER_COLLISION | ENEMY_FLAG_IGNORE_ENTITY_COLLISION | ENEMY_FLAG_FLYING | ENEMY_FLAG_NO_DROPS, .drops = NO_DROPS, .animations = MONTY_MOLE_AMBUSH_ANIMS, .aiDetectFlags = AI_DETECT_SIGHT, }, }; NpcData N(NpcData_MontyMole_StoneThrower_01)[] = { { .id = NPC_MontyMole_02, .pos = { -250.0f, 10.0f, 260.0f }, .yaw = 90, .territory = { .wander = { .isFlying = TRUE, .moveSpeedOverride = NO_OVERRIDE_MOVEMENT_SPEED, .wanderShape = SHAPE_CYLINDER, .centerPos = { -250, 10, 260 }, .wanderSize = { 30 }, .detectShape = SHAPE_CYLINDER, .detectPos = { -250, 10, 260 }, .detectSize = { 180 }, } }, .settings = &N(NpcSettings_MontyMole_StoneThrower), .flags = ENEMY_FLAG_FLYING, .drops = MONTY_MOLE_DROPS, .animations = MONTY_MOLE_THROWER_ANIMS, .aiDetectFlags = AI_DETECT_SIGHT, }, MONTY_MOLE_STONE_HITBOX(NPC_MontyMole_02_Stone) }; NpcData N(NpcData_MontyMole_StoneThrower_02)[] = { { .id = NPC_MontyMole_03, .pos = { -175.0f, 10.0f, 240.0f }, .yaw = 270, .territory = { .wander = { .isFlying = TRUE, .moveSpeedOverride = NO_OVERRIDE_MOVEMENT_SPEED, .wanderShape = SHAPE_CYLINDER, .centerPos = { -175, 10, 240 }, .wanderSize = { 30 }, .detectShape = SHAPE_CYLINDER, .detectPos = { -175, 10, 240 }, .detectSize = { 180 }, } }, .settings = &N(NpcSettings_MontyMole_StoneThrower), .flags = ENEMY_FLAG_FLYING, .drops = MONTY_MOLE_DROPS, .animations = MONTY_MOLE_THROWER_ANIMS, .aiDetectFlags = AI_DETECT_SIGHT, }, MONTY_MOLE_STONE_HITBOX(NPC_MontyMole_03_Stone) }; NpcData N(NpcData_MontyMole_StoneThrower_03)[] = { { .id = NPC_MontyMole_04, .pos = { -55.0f, 10.0f, 180.0f }, .yaw = 270, .territory = { .wander = { .isFlying = TRUE, .moveSpeedOverride = NO_OVERRIDE_MOVEMENT_SPEED, .wanderShape = SHAPE_CYLINDER, .centerPos = { -55, 10, 180 }, .wanderSize = { 30 }, .detectShape = SHAPE_CYLINDER, .detectPos = { -55, 10, 180 }, .detectSize = { 180 }, } }, .settings = &N(NpcSettings_MontyMole_StoneThrower), .flags = ENEMY_FLAG_FLYING, .drops = MONTY_MOLE_DROPS, .animations = MONTY_MOLE_THROWER_ANIMS, .aiDetectFlags = AI_DETECT_SIGHT, }, MONTY_MOLE_STONE_HITBOX(NPC_MontyMole_04_Stone) }; NpcData N(NpcData_Cleft) = { .id = NPC_Cleft, .pos = { -657.0f, 163.0f, 155.0f }, .yaw = 0, .territory = { .wander = { .isFlying = TRUE, .moveSpeedOverride = NO_OVERRIDE_MOVEMENT_SPEED, .wanderShape = SHAPE_CYLINDER, .centerPos = { -639, 163, 100 }, .wanderSize = { 0 }, .detectShape = SHAPE_CYLINDER, .detectPos = { -655, 0, 125 }, .detectSize = { 125, 125 }, } }, .settings = &N(NpcSettings_Cleft), .flags = ENEMY_FLAG_IGNORE_ENTITY_COLLISION | ENEMY_FLAG_FLYING, .drops = CLEFT_DROPS, .animations = CLEFT_ANIMS, .aiDetectFlags = AI_DETECT_SIGHT, }; NpcGroupList N(DefaultNPCs) = { NPC_GROUP(N(NpcData_MontyMole_WallAmbush), BTL_IWA_FORMATION_06, BTL_IWA_STAGE_01), NPC_GROUP(N(NpcData_MontyMole_StoneThrower_01), BTL_IWA_FORMATION_07, BTL_IWA_STAGE_01), NPC_GROUP(N(NpcData_MontyMole_StoneThrower_02), BTL_IWA_FORMATION_06, BTL_IWA_STAGE_01), NPC_GROUP(N(NpcData_MontyMole_StoneThrower_03), BTL_IWA_FORMATION_07, BTL_IWA_STAGE_01), NPC_GROUP(N(NpcData_Cleft), BTL_IWA_FORMATION_04, BTL_IWA_STAGE_01), {} };
9db0762a2b349a01ee98f207e2203eec79fd9ae0
c26d7b0ed875357278e61627da2da0650da77986
/src/cmd/m4/look.c
1638bed214d9da2afd65dc1e27212e73173b9024
[ "BSD-3-Clause" ]
permissive
RetroBSD/retrobsd
5343d9e3c424637fc3ad5b03fe720b2744490025
486f81f6abff01c7dcc207235cd2979b226a95ff
refs/heads/master
2023-09-02T23:12:05.110883
2023-07-07T18:41:40
2023-07-07T18:41:40
18,598,087
282
59
BSD-3-Clause
2023-07-18T07:35:36
2014-04-09T13:25:46
C
UTF-8
C
false
false
3,513
c
look.c
/* * Copyright (c) 1989, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Ozan Yigit at York University. * * 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. */ #if !defined(lint) && defined(DOSCCS) static char sccsid[] = "@(#)look.c 8.1 (Berkeley) 6/6/93"; #endif /* * look.c * Facility: m4 macro processor * by: oz */ #include <sys/types.h> #include <stdio.h> #include <string.h> #include "mdef.h" #include "stdd.h" #include "extern.h" int hash(name) register char *name; { register unsigned long h = 0; while (*name) h = (h << 5) + h + *name++; return (h % HASHSIZE); } /* * find name in the hash table */ ndptr lookup(name) char *name; { register ndptr p; for (p = hashtab[hash(name)]; p != nil; p = p->nxtptr) if (STREQ(name, p->name)) break; return (p); } /* * hash and create an entry in the hash table. * The new entry is added in front of a hash bucket. */ ndptr addent(name) char *name; { register int h; ndptr p; h = hash(name); p = (ndptr) xalloc(sizeof(struct ndblock)); p->nxtptr = hashtab[h]; hashtab[h] = p; p->name = xstrdup(name); return p; } static void freent(p) ndptr p; { if (!(p->type & STATIC)) { free((char *) p->name); if (p->defn != null) free((char *) p->defn); } free((char *) p); } /* * remove an entry from the hashtable */ void remhash(name, all) char *name; int all; { register int h; register ndptr xp, tp, mp; h = hash(name); mp = hashtab[h]; tp = nil; while (mp != nil) { if (STREQ(mp->name, name)) { mp = mp->nxtptr; if (tp == nil) { freent(hashtab[h]); hashtab[h] = mp; } else { xp = tp->nxtptr; tp->nxtptr = mp; freent(xp); } if (!all) break; } else { tp = mp; mp = mp->nxtptr; } } }
9b038ea5172ab608f15ba80eb967a682067b8eca
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/include/uapi/linux/falloc.h
990c4ccf8b61d575a6db2a787896b027e4789698
[ "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later", "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
263
h
falloc.h
#ifndef _UAPI_FALLOC_H_ #define _UAPI_FALLOC_H_ #define FALLOC_FL_KEEP_SIZE 0x01 /* default is extend size */ #define FALLOC_FL_PUNCH_HOLE 0x02 /* de-allocates range */ #define FALLOC_FL_NO_HIDE_STALE 0x04 /* reserved codepoint */ #endif /* _UAPI_FALLOC_H_ */
dc5331010f1cd88b47a3418eadb727cc98457964
5eff7a36d9a9917dce9111f0c3074375fe6f7656
/lib/mesa/src/gallium/drivers/zink/zink_query.c
e9dc921c27eb201ca7a6ff580ff7ff2118060724
[]
no_license
openbsd/xenocara
cb392d02ebba06f6ff7d826fd8a89aa3b8401779
a012b5de33ea0b977095d77316a521195b26cc6b
refs/heads/master
2023-08-25T12:16:58.862008
2023-08-12T16:16:25
2023-08-12T16:16:25
66,967,384
177
66
null
2023-07-22T18:12:37
2016-08-30T18:36:01
C
UTF-8
C
false
false
48,707
c
zink_query.c
#include "zink_query.h" #include "zink_context.h" #include "zink_clear.h" #include "zink_program.h" #include "zink_resource.h" #include "util/u_dump.h" #include "util/u_inlines.h" #include "util/u_memory.h" #if defined(PIPE_ARCH_X86_64) || defined(PIPE_ARCH_PPC_64) || defined(PIPE_ARCH_AARCH64) || defined(PIPE_ARCH_MIPS64) #define NUM_QUERIES 5000 #else #define NUM_QUERIES 500 #endif struct zink_query_pool { struct list_head list; VkQueryType vk_query_type; VkQueryPipelineStatisticFlags pipeline_stats; VkQueryPool query_pool; unsigned last_range; }; struct zink_query_buffer { struct list_head list; unsigned num_results; struct pipe_resource *buffers[PIPE_MAX_VERTEX_STREAMS]; }; struct zink_vk_query { struct zink_query_pool *pool; unsigned query_id; bool needs_reset; bool started; uint32_t refcount; }; struct zink_query_start { struct zink_vk_query *vkq[PIPE_MAX_VERTEX_STREAMS]; bool have_gs; bool have_xfb; bool was_line_loop; }; struct zink_query { struct threaded_query base; enum pipe_query_type type; struct zink_query_pool *pool[2]; /* Everytime the gallium query needs * another vulkan query, add a new start. */ struct util_dynarray starts; unsigned last_start_idx; VkQueryType vkqtype; unsigned index; bool precise; bool active; /* query is considered active by vk */ bool needs_reset; /* query is considered active by vk and cannot be destroyed */ bool dead; /* query should be destroyed when its fence finishes */ bool needs_update; /* query needs to update its qbos */ bool needs_rast_discard_workaround; /* query needs discard disabled */ struct list_head active_list; struct list_head stats_list; /* when active, statistics queries are added to ctx->primitives_generated_queries */ bool has_draws; /* have_gs and have_xfb are valid for idx=curr_query */ struct zink_batch_usage *batch_uses; //batch that the query was started in struct list_head buffers; union { struct zink_query_buffer *curr_qbo; struct pipe_fence_handle *fence; //PIPE_QUERY_GPU_FINISHED }; struct zink_resource *predicate; bool predicate_dirty; }; static inline int get_num_starts(struct zink_query *q) { return util_dynarray_num_elements(&q->starts, struct zink_query_start); } static void update_query_id(struct zink_context *ctx, struct zink_query *q); static void begin_vk_query_indexed(struct zink_context *ctx, struct zink_vk_query *vkq, int index, VkQueryControlFlags flags) { struct zink_batch *batch = &ctx->batch; if (!vkq->started) { VKCTX(CmdBeginQueryIndexedEXT)(batch->state->cmdbuf, vkq->pool->query_pool, vkq->query_id, flags, index); vkq->started = true; } } static void end_vk_query_indexed(struct zink_context *ctx, struct zink_vk_query *vkq, int index) { struct zink_batch *batch = &ctx->batch; if (vkq->started) { VKCTX(CmdEndQueryIndexedEXT)(batch->state->cmdbuf, vkq->pool->query_pool, vkq->query_id, index); vkq->started = false; } } static void reset_vk_query_pool(struct zink_context *ctx, struct zink_vk_query *vkq) { struct zink_batch *batch = &ctx->batch; if (vkq->needs_reset) { VKCTX(CmdResetQueryPool)(batch->state->cmdbuf, vkq->pool->query_pool, vkq->query_id, 1); vkq->needs_reset = false; } } void zink_context_destroy_query_pools(struct zink_context *ctx) { struct zink_screen *screen = zink_screen(ctx->base.screen); list_for_each_entry_safe(struct zink_query_pool, pool, &ctx->query_pools, list) { VKSCR(DestroyQueryPool)(screen->dev, pool->query_pool, NULL); list_del(&pool->list); FREE(pool); } } static struct zink_query_pool * find_or_allocate_qp(struct zink_context *ctx, VkQueryType vk_query_type, VkQueryPipelineStatisticFlags pipeline_stats) { struct zink_screen *screen = zink_screen(ctx->base.screen); list_for_each_entry(struct zink_query_pool, pool, &ctx->query_pools, list) { if (pool->vk_query_type == vk_query_type) { if (vk_query_type == VK_QUERY_TYPE_PIPELINE_STATISTICS) { if (pool->pipeline_stats == pipeline_stats) return pool; } else return pool; } } struct zink_query_pool *new_pool = CALLOC_STRUCT(zink_query_pool); if (!new_pool) return NULL; new_pool->vk_query_type = vk_query_type; new_pool->pipeline_stats = pipeline_stats; VkQueryPoolCreateInfo pool_create = {0}; pool_create.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO; pool_create.queryType = vk_query_type; pool_create.queryCount = NUM_QUERIES; pool_create.pipelineStatistics = pipeline_stats; VkResult status = VKSCR(CreateQueryPool)(screen->dev, &pool_create, NULL, &new_pool->query_pool); if (status != VK_SUCCESS) { mesa_loge("ZINK: vkCreateQueryPool failed (%s)", vk_Result_to_str(status)); FREE(new_pool); return NULL; } list_addtail(&new_pool->list, &ctx->query_pools); return new_pool; } static void update_qbo(struct zink_context *ctx, struct zink_query *q); static void reset_qbos(struct zink_context *ctx, struct zink_query *q); static bool is_emulated_primgen(const struct zink_query *q) { return q->type == PIPE_QUERY_PRIMITIVES_GENERATED && q->vkqtype != VK_QUERY_TYPE_PRIMITIVES_GENERATED_EXT; } static inline unsigned get_num_query_pools(struct zink_query *q) { if (is_emulated_primgen(q)) return 2; return 1; } static inline unsigned get_num_queries(struct zink_query *q) { if (is_emulated_primgen(q)) return 2; if (q->type == PIPE_QUERY_SO_OVERFLOW_ANY_PREDICATE) return PIPE_MAX_VERTEX_STREAMS; return 1; } static inline unsigned get_num_results(struct zink_query *q) { if (q->vkqtype == VK_QUERY_TYPE_PRIMITIVES_GENERATED_EXT) return 1; switch (q->type) { case PIPE_QUERY_OCCLUSION_COUNTER: case PIPE_QUERY_OCCLUSION_PREDICATE: case PIPE_QUERY_OCCLUSION_PREDICATE_CONSERVATIVE: case PIPE_QUERY_TIME_ELAPSED: case PIPE_QUERY_TIMESTAMP: case PIPE_QUERY_PIPELINE_STATISTICS_SINGLE: return 1; case PIPE_QUERY_PRIMITIVES_GENERATED: case PIPE_QUERY_SO_OVERFLOW_ANY_PREDICATE: case PIPE_QUERY_SO_OVERFLOW_PREDICATE: case PIPE_QUERY_PRIMITIVES_EMITTED: return 2; default: debug_printf("unknown query: %s\n", util_str_query_type(q->type, true)); unreachable("zink: unknown query type"); } } static VkQueryPipelineStatisticFlags pipeline_statistic_convert(enum pipe_statistics_query_index idx) { unsigned map[] = { [PIPE_STAT_QUERY_IA_VERTICES] = VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_VERTICES_BIT, [PIPE_STAT_QUERY_IA_PRIMITIVES] = VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_PRIMITIVES_BIT, [PIPE_STAT_QUERY_VS_INVOCATIONS] = VK_QUERY_PIPELINE_STATISTIC_VERTEX_SHADER_INVOCATIONS_BIT, [PIPE_STAT_QUERY_GS_INVOCATIONS] = VK_QUERY_PIPELINE_STATISTIC_GEOMETRY_SHADER_INVOCATIONS_BIT, [PIPE_STAT_QUERY_GS_PRIMITIVES] = VK_QUERY_PIPELINE_STATISTIC_GEOMETRY_SHADER_PRIMITIVES_BIT, [PIPE_STAT_QUERY_C_INVOCATIONS] = VK_QUERY_PIPELINE_STATISTIC_CLIPPING_INVOCATIONS_BIT, [PIPE_STAT_QUERY_C_PRIMITIVES] = VK_QUERY_PIPELINE_STATISTIC_CLIPPING_PRIMITIVES_BIT, [PIPE_STAT_QUERY_PS_INVOCATIONS] = VK_QUERY_PIPELINE_STATISTIC_FRAGMENT_SHADER_INVOCATIONS_BIT, [PIPE_STAT_QUERY_HS_INVOCATIONS] = VK_QUERY_PIPELINE_STATISTIC_TESSELLATION_CONTROL_SHADER_PATCHES_BIT, [PIPE_STAT_QUERY_DS_INVOCATIONS] = VK_QUERY_PIPELINE_STATISTIC_TESSELLATION_EVALUATION_SHADER_INVOCATIONS_BIT, [PIPE_STAT_QUERY_CS_INVOCATIONS] = VK_QUERY_PIPELINE_STATISTIC_COMPUTE_SHADER_INVOCATIONS_BIT }; assert(idx < ARRAY_SIZE(map)); return map[idx]; } static void timestamp_to_nanoseconds(struct zink_screen *screen, uint64_t *timestamp) { /* The number of valid bits in a timestamp value is determined by * the VkQueueFamilyProperties::timestampValidBits property of the queue on which the timestamp is written. * - 17.5. Timestamp Queries */ if (screen->timestamp_valid_bits < 64) *timestamp &= (1ull << screen->timestamp_valid_bits) - 1; /* The number of nanoseconds it takes for a timestamp value to be incremented by 1 * can be obtained from VkPhysicalDeviceLimits::timestampPeriod * - 17.5. Timestamp Queries */ *timestamp *= (double)screen->info.props.limits.timestampPeriod; } static VkQueryType convert_query_type(struct zink_screen *screen, enum pipe_query_type query_type, bool *precise) { *precise = false; switch (query_type) { case PIPE_QUERY_OCCLUSION_COUNTER: *precise = true; FALLTHROUGH; case PIPE_QUERY_OCCLUSION_PREDICATE: case PIPE_QUERY_OCCLUSION_PREDICATE_CONSERVATIVE: return VK_QUERY_TYPE_OCCLUSION; case PIPE_QUERY_TIME_ELAPSED: case PIPE_QUERY_TIMESTAMP: return VK_QUERY_TYPE_TIMESTAMP; case PIPE_QUERY_PRIMITIVES_GENERATED: return screen->info.have_EXT_primitives_generated_query ? VK_QUERY_TYPE_PRIMITIVES_GENERATED_EXT : VK_QUERY_TYPE_PIPELINE_STATISTICS; case PIPE_QUERY_PIPELINE_STATISTICS_SINGLE: return VK_QUERY_TYPE_PIPELINE_STATISTICS; case PIPE_QUERY_SO_OVERFLOW_ANY_PREDICATE: case PIPE_QUERY_SO_OVERFLOW_PREDICATE: case PIPE_QUERY_PRIMITIVES_EMITTED: return VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT; default: debug_printf("unknown query: %s\n", util_str_query_type(query_type, true)); unreachable("zink: unknown query type"); } } static bool needs_stats_list(struct zink_query *query) { return is_emulated_primgen(query) || query->type == PIPE_QUERY_SO_OVERFLOW_ANY_PREDICATE || query->type == PIPE_QUERY_SO_OVERFLOW_PREDICATE; } static bool is_time_query(struct zink_query *query) { return query->type == PIPE_QUERY_TIMESTAMP || query->type == PIPE_QUERY_TIME_ELAPSED; } static bool is_so_overflow_query(struct zink_query *query) { return query->type == PIPE_QUERY_SO_OVERFLOW_ANY_PREDICATE || query->type == PIPE_QUERY_SO_OVERFLOW_PREDICATE; } static bool is_bool_query(struct zink_query *query) { return is_so_overflow_query(query) || query->type == PIPE_QUERY_OCCLUSION_PREDICATE || query->type == PIPE_QUERY_OCCLUSION_PREDICATE_CONSERVATIVE || query->type == PIPE_QUERY_GPU_FINISHED; } static bool qbo_append(struct pipe_screen *screen, struct zink_query *query) { if (query->curr_qbo && query->curr_qbo->list.next) return true; struct zink_query_buffer *qbo = CALLOC_STRUCT(zink_query_buffer); if (!qbo) return false; int num_buffers = get_num_queries(query); for (unsigned i = 0; i < num_buffers; i++) { qbo->buffers[i] = pipe_buffer_create(screen, PIPE_BIND_QUERY_BUFFER, PIPE_USAGE_STAGING, /* this is the maximum possible size of the results in a given buffer */ NUM_QUERIES * get_num_results(query) * sizeof(uint64_t)); if (!qbo->buffers[i]) goto fail; } list_addtail(&qbo->list, &query->buffers); return true; fail: for (unsigned i = 0; i < num_buffers; i++) pipe_resource_reference(&qbo->buffers[i], NULL); FREE(qbo); return false; } static void destroy_query(struct zink_screen *screen, struct zink_query *query) { assert(zink_screen_usage_check_completion(screen, query->batch_uses)); struct zink_query_buffer *qbo, *next; util_dynarray_foreach(&query->starts, struct zink_query_start, start) { for (unsigned i = 0; i < PIPE_MAX_VERTEX_STREAMS; i++) { if (!start->vkq[i]) continue; start->vkq[i]->refcount--; if (start->vkq[i]->refcount == 0) FREE(start->vkq[i]); } } util_dynarray_fini(&query->starts); LIST_FOR_EACH_ENTRY_SAFE(qbo, next, &query->buffers, list) { for (unsigned i = 0; i < ARRAY_SIZE(qbo->buffers); i++) pipe_resource_reference(&qbo->buffers[i], NULL); FREE(qbo); } pipe_resource_reference((struct pipe_resource**)&query->predicate, NULL); FREE(query); } static void reset_qbo(struct zink_query *q) { q->curr_qbo = list_first_entry(&q->buffers, struct zink_query_buffer, list); q->curr_qbo->num_results = 0; } static void query_pool_get_range(struct zink_context *ctx, struct zink_query *q) { bool is_timestamp = q->type == PIPE_QUERY_TIMESTAMP; struct zink_query_start *start; int num_queries = get_num_queries(q); if (!is_timestamp || get_num_starts(q) == 0) { start = util_dynarray_grow(&q->starts, struct zink_query_start, 1); memset(start, 0, sizeof(*start)); } else { start = util_dynarray_top_ptr(&q->starts, struct zink_query_start); } for (unsigned i = 0; i < num_queries; i++) { int pool_idx = q->pool[1] ? i : 0; /* try and find the active query for this */ struct zink_vk_query *vkq; int xfb_idx = num_queries == 4 ? i : q->index; if ((q->vkqtype == VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT || (pool_idx == 1)) && ctx->curr_xfb_queries[xfb_idx]) { vkq = ctx->curr_xfb_queries[xfb_idx]; vkq->refcount++; } else { struct zink_query_pool *pool = q->pool[pool_idx]; vkq = CALLOC_STRUCT(zink_vk_query); vkq->refcount = 1; vkq->needs_reset = true; vkq->pool = pool; vkq->started = false; vkq->query_id = pool->last_range; pool->last_range++; if (pool->last_range == NUM_QUERIES) pool->last_range = 0; } if (start->vkq[i]) FREE(start->vkq[i]); start->vkq[i] = vkq; } } static struct pipe_query * zink_create_query(struct pipe_context *pctx, unsigned query_type, unsigned index) { struct zink_screen *screen = zink_screen(pctx->screen); struct zink_query *query = CALLOC_STRUCT(zink_query); if (!query) return NULL; list_inithead(&query->buffers); query->index = index; query->type = query_type; if (query->type == PIPE_QUERY_GPU_FINISHED || query->type == PIPE_QUERY_TIMESTAMP_DISJOINT) return (struct pipe_query *)query; query->vkqtype = convert_query_type(screen, query_type, &query->precise); if (query->vkqtype == -1) return NULL; util_dynarray_init(&query->starts, NULL); assert(!query->precise || query->vkqtype == VK_QUERY_TYPE_OCCLUSION); /* use emulated path for drivers without full support */ if (query->vkqtype == VK_QUERY_TYPE_PRIMITIVES_GENERATED_EXT && index && !screen->info.primgen_feats.primitivesGeneratedQueryWithNonZeroStreams) query->vkqtype = VK_QUERY_TYPE_PIPELINE_STATISTICS; VkQueryPipelineStatisticFlags pipeline_stats = 0; if (query->vkqtype == VK_QUERY_TYPE_PRIMITIVES_GENERATED_EXT) { query->needs_rast_discard_workaround = !screen->info.primgen_feats.primitivesGeneratedQueryWithRasterizerDiscard; } else if (query_type == PIPE_QUERY_PRIMITIVES_GENERATED) { pipeline_stats = VK_QUERY_PIPELINE_STATISTIC_GEOMETRY_SHADER_PRIMITIVES_BIT | VK_QUERY_PIPELINE_STATISTIC_CLIPPING_INVOCATIONS_BIT; query->needs_rast_discard_workaround = true; } else if (query_type == PIPE_QUERY_PIPELINE_STATISTICS_SINGLE) pipeline_stats = pipeline_statistic_convert(index); int num_pools = get_num_query_pools(query); for (unsigned i = 0; i < num_pools; i++) { VkQueryType vkqtype = query->vkqtype; /* if xfb is active, we need to use an xfb query, otherwise we need pipeline statistics */ if (query_type == PIPE_QUERY_PRIMITIVES_GENERATED && i == 1) { vkqtype = VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT; pipeline_stats = 0; } query->pool[i] = find_or_allocate_qp(zink_context(pctx), vkqtype, pipeline_stats); if (!query->pool[i]) goto fail; } if (!qbo_append(pctx->screen, query)) goto fail; struct zink_batch *batch = &zink_context(pctx)->batch; batch->has_work = true; query->needs_reset = true; if (query->type == PIPE_QUERY_TIMESTAMP) { query->active = true; /* defer pool reset until end_query since we're guaranteed to be threadsafe then */ reset_qbo(query); } return (struct pipe_query *)query; fail: destroy_query(screen, query); return NULL; } static void zink_destroy_query(struct pipe_context *pctx, struct pipe_query *q) { struct zink_screen *screen = zink_screen(pctx->screen); struct zink_query *query = (struct zink_query *)q; /* only destroy if this query isn't active on any batches, * otherwise just mark dead and wait */ if (query->batch_uses) { p_atomic_set(&query->dead, true); return; } destroy_query(screen, query); } void zink_prune_query(struct zink_screen *screen, struct zink_batch_state *bs, struct zink_query *query) { if (!zink_batch_usage_matches(query->batch_uses, bs)) return; query->batch_uses = NULL; if (p_atomic_read(&query->dead)) destroy_query(screen, query); } static void check_query_results(struct zink_query *query, union pipe_query_result *result, int num_starts, uint64_t *results, uint64_t *xfb_results) { uint64_t last_val = 0; int result_size = get_num_results(query); int idx = 0; util_dynarray_foreach(&query->starts, struct zink_query_start, start) { unsigned i = idx * result_size; idx++; switch (query->type) { case PIPE_QUERY_OCCLUSION_PREDICATE: case PIPE_QUERY_OCCLUSION_PREDICATE_CONSERVATIVE: case PIPE_QUERY_GPU_FINISHED: result->b |= results[i] != 0; break; case PIPE_QUERY_TIME_ELAPSED: case PIPE_QUERY_TIMESTAMP: /* the application can sum the differences between all N queries to determine the total execution time. * - 17.5. Timestamp Queries */ if (query->type != PIPE_QUERY_TIME_ELAPSED || i) result->u64 += results[i] - last_val; last_val = results[i]; break; case PIPE_QUERY_OCCLUSION_COUNTER: result->u64 += results[i]; break; case PIPE_QUERY_PRIMITIVES_GENERATED: if (query->vkqtype == VK_QUERY_TYPE_PRIMITIVES_GENERATED_EXT) result->u64 += results[i]; else if (start->have_xfb || query->index) result->u64 += xfb_results[i + 1]; else /* if a given draw had a geometry shader, we need to use the first result */ result->u64 += results[i + !start->have_gs]; break; case PIPE_QUERY_PRIMITIVES_EMITTED: /* A query pool created with this type will capture 2 integers - * numPrimitivesWritten and numPrimitivesNeeded - * for the specified vertex stream output from the last vertex processing stage. * - from VK_EXT_transform_feedback spec */ result->u64 += results[i]; break; case PIPE_QUERY_SO_OVERFLOW_ANY_PREDICATE: case PIPE_QUERY_SO_OVERFLOW_PREDICATE: /* A query pool created with this type will capture 2 integers - * numPrimitivesWritten and numPrimitivesNeeded - * for the specified vertex stream output from the last vertex processing stage. * - from VK_EXT_transform_feedback spec */ if (start->have_xfb) result->b |= results[i] != results[i + 1]; break; case PIPE_QUERY_PIPELINE_STATISTICS_SINGLE: switch (query->index) { case PIPE_STAT_QUERY_IA_VERTICES: result->u64 += start->was_line_loop ? results[i] / 2 : results[i]; break; default: result->u64 += results[i]; break; } break; default: debug_printf("unhandled query type: %s\n", util_str_query_type(query->type, true)); unreachable("unexpected query type"); } } } static bool get_query_result(struct pipe_context *pctx, struct pipe_query *q, bool wait, union pipe_query_result *result) { struct zink_screen *screen = zink_screen(pctx->screen); struct zink_query *query = (struct zink_query *)q; unsigned flags = PIPE_MAP_READ; if (!wait) flags |= PIPE_MAP_DONTBLOCK; if (query->base.flushed) /* this is not a context-safe operation; ensure map doesn't use slab alloc */ flags |= PIPE_MAP_THREAD_SAFE; util_query_clear_result(result, query->type); int num_starts = get_num_starts(query); int result_size = get_num_results(query) * sizeof(uint64_t); int num_maps = get_num_queries(query); struct zink_query_buffer *qbo; struct pipe_transfer *xfer[PIPE_MAX_VERTEX_STREAMS] = { 0 }; LIST_FOR_EACH_ENTRY(qbo, &query->buffers, list) { uint64_t *results[PIPE_MAX_VERTEX_STREAMS] = { NULL, NULL }; bool is_timestamp = query->type == PIPE_QUERY_TIMESTAMP; if (!qbo->num_results) continue; for (unsigned i = 0; i < num_maps; i++) { results[i] = pipe_buffer_map_range(pctx, qbo->buffers[i], 0, (is_timestamp ? 1 : qbo->num_results) * result_size, flags, &xfer[i]); if (!results[i]) { if (wait) debug_printf("zink: qbo read failed!"); goto fail; } } if (query->type == PIPE_QUERY_SO_OVERFLOW_ANY_PREDICATE) { for (unsigned i = 0; i < PIPE_MAX_VERTEX_STREAMS && !result->b; i++) { check_query_results(query, result, num_starts, results[i], NULL); } } else check_query_results(query, result, num_starts, results[0], results[1]); for (unsigned i = 0 ; i < num_maps; i++) pipe_buffer_unmap(pctx, xfer[i]); /* if overflow is detected we can stop */ if (query->type == PIPE_QUERY_SO_OVERFLOW_ANY_PREDICATE && result->b) break; } if (is_time_query(query)) timestamp_to_nanoseconds(screen, &result->u64); return true; fail: for (unsigned i = 0 ; i < num_maps; i++) if (xfer[i]) pipe_buffer_unmap(pctx, xfer[i]); return false; } static void force_cpu_read(struct zink_context *ctx, struct pipe_query *pquery, enum pipe_query_value_type result_type, struct pipe_resource *pres, unsigned offset) { struct pipe_context *pctx = &ctx->base; unsigned result_size = result_type <= PIPE_QUERY_TYPE_U32 ? sizeof(uint32_t) : sizeof(uint64_t); struct zink_query *query = (struct zink_query*)pquery; union pipe_query_result result; if (query->needs_update) update_qbo(ctx, query); bool success = get_query_result(pctx, pquery, true, &result); if (!success) { debug_printf("zink: getting query result failed\n"); return; } if (result_type <= PIPE_QUERY_TYPE_U32) { uint32_t u32; uint32_t limit; if (result_type == PIPE_QUERY_TYPE_I32) limit = INT_MAX; else limit = UINT_MAX; if (is_bool_query(query)) u32 = result.b; else u32 = MIN2(limit, result.u64); tc_buffer_write(pctx, pres, offset, result_size, &u32); } else { uint64_t u64; if (is_bool_query(query)) u64 = result.b; else u64 = result.u64; tc_buffer_write(pctx, pres, offset, result_size, &u64); } } static void copy_pool_results_to_buffer(struct zink_context *ctx, struct zink_query *query, VkQueryPool pool, unsigned query_id, struct zink_resource *res, unsigned offset, int num_results, VkQueryResultFlags flags) { struct zink_batch *batch = &ctx->batch; unsigned type_size = (flags & VK_QUERY_RESULT_64_BIT) ? sizeof(uint64_t) : sizeof(uint32_t); unsigned base_result_size = get_num_results(query) * type_size; unsigned result_size = base_result_size * num_results; if (flags & VK_QUERY_RESULT_WITH_AVAILABILITY_BIT) result_size += type_size; zink_batch_no_rp(ctx); /* if it's a single query that doesn't need special handling, we can copy it and be done */ zink_batch_reference_resource_rw(batch, res, true); zink_screen(ctx->base.screen)->buffer_barrier(ctx, res, VK_ACCESS_TRANSFER_WRITE_BIT, 0); util_range_add(&res->base.b, &res->valid_buffer_range, offset, offset + result_size); assert(query_id < NUM_QUERIES); res->obj->unordered_read = res->obj->unordered_write = false; VKCTX(CmdCopyQueryPoolResults)(batch->state->cmdbuf, pool, query_id, num_results, res->obj->buffer, offset, base_result_size, flags); } static void copy_results_to_buffer(struct zink_context *ctx, struct zink_query *query, struct zink_resource *res, unsigned offset, int num_results, VkQueryResultFlags flags) { struct zink_query_start *start = util_dynarray_top_ptr(&query->starts, struct zink_query_start); copy_pool_results_to_buffer(ctx, query, start->vkq[0]->pool->query_pool, start->vkq[0]->query_id, res, offset, num_results, flags); } static void reset_query_range(struct zink_context *ctx, struct zink_query *q) { int num_queries = get_num_queries(q); zink_batch_no_rp(ctx); struct zink_query_start *start = util_dynarray_top_ptr(&q->starts, struct zink_query_start); for (unsigned i = 0; i < num_queries; i++) { reset_vk_query_pool(ctx, start->vkq[i]); } } static void reset_qbos(struct zink_context *ctx, struct zink_query *q) { if (q->needs_update) update_qbo(ctx, q); q->needs_reset = false; /* create new qbo for non-timestamp queries: * timestamp queries should never need more than 2 entries in the qbo */ if (q->type == PIPE_QUERY_TIMESTAMP) return; if (qbo_append(ctx->base.screen, q)) reset_qbo(q); else debug_printf("zink: qbo alloc failed on reset!"); } static inline unsigned get_buffer_offset(struct zink_query *q) { return (get_num_starts(q) - q->last_start_idx - 1) * get_num_results(q) * sizeof(uint64_t); } static void update_qbo(struct zink_context *ctx, struct zink_query *q) { struct zink_query_buffer *qbo = q->curr_qbo; struct zink_query_start *start = util_dynarray_top_ptr(&q->starts, struct zink_query_start); bool is_timestamp = q->type == PIPE_QUERY_TIMESTAMP; /* timestamp queries just write to offset 0 always */ int num_queries = get_num_queries(q); for (unsigned i = 0; i < num_queries; i++) { unsigned offset = is_timestamp ? 0 : get_buffer_offset(q); copy_pool_results_to_buffer(ctx, q, start->vkq[i]->pool->query_pool, start->vkq[i]->query_id, zink_resource(qbo->buffers[i]), offset, 1, /* there is an implicit execution dependency from each such query command to all query commands previously submitted to the same queue. There is one significant exception to this; if the flags parameter of vkCmdCopyQueryPoolResults does not include VK_QUERY_RESULT_WAIT_BIT, execution of vkCmdCopyQueryPoolResults may happen-before the results of vkCmdEndQuery are available. * - Chapter 18. Queries */ VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); } if (!is_timestamp) q->curr_qbo->num_results++; else q->curr_qbo->num_results = 1; q->needs_update = false; } static void begin_query(struct zink_context *ctx, struct zink_batch *batch, struct zink_query *q) { VkQueryControlFlags flags = 0; if (q->type == PIPE_QUERY_TIMESTAMP_DISJOINT) return; update_query_id(ctx, q); q->predicate_dirty = true; if (q->needs_reset) reset_qbos(ctx, q); reset_query_range(ctx, q); q->active = true; batch->has_work = true; struct zink_query_start *start = util_dynarray_top_ptr(&q->starts, struct zink_query_start); if (q->type == PIPE_QUERY_TIME_ELAPSED) { VKCTX(CmdWriteTimestamp)(batch->state->cmdbuf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, start->vkq[0]->pool->query_pool, start->vkq[0]->query_id); update_qbo(ctx, q); zink_batch_usage_set(&q->batch_uses, batch->state); _mesa_set_add(&batch->state->active_queries, q); } /* ignore the rest of begin_query for timestamps */ if (is_time_query(q)) return; if (q->precise) flags |= VK_QUERY_CONTROL_PRECISE_BIT; if (q->type == PIPE_QUERY_PRIMITIVES_EMITTED || is_emulated_primgen(q) || q->type == PIPE_QUERY_SO_OVERFLOW_PREDICATE) { struct zink_vk_query *vkq = start->vkq[1] ? start->vkq[1] : start->vkq[0]; assert(!ctx->curr_xfb_queries[q->index] || ctx->curr_xfb_queries[q->index] == vkq); ctx->curr_xfb_queries[q->index] = vkq; begin_vk_query_indexed(ctx, vkq, q->index, flags); } else if (q->type == PIPE_QUERY_SO_OVERFLOW_ANY_PREDICATE) { for (unsigned i = 0; i < PIPE_MAX_VERTEX_STREAMS; i++) { assert(!ctx->curr_xfb_queries[i] || ctx->curr_xfb_queries[i] == start->vkq[i]); ctx->curr_xfb_queries[i] = start->vkq[i]; begin_vk_query_indexed(ctx, start->vkq[i], i, flags); } } else if (q->vkqtype == VK_QUERY_TYPE_PRIMITIVES_GENERATED_EXT) { begin_vk_query_indexed(ctx, start->vkq[0], q->index, flags); } if (q->vkqtype != VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT && q->vkqtype != VK_QUERY_TYPE_PRIMITIVES_GENERATED_EXT) VKCTX(CmdBeginQuery)(batch->state->cmdbuf, start->vkq[0]->pool->query_pool, start->vkq[0]->query_id, flags); if (q->type == PIPE_QUERY_PIPELINE_STATISTICS_SINGLE && q->index == PIPE_STAT_QUERY_IA_VERTICES) { assert(!ctx->vertices_query); ctx->vertices_query = q; } if (needs_stats_list(q)) list_addtail(&q->stats_list, &ctx->primitives_generated_queries); zink_batch_usage_set(&q->batch_uses, batch->state); _mesa_set_add(&batch->state->active_queries, q); if (q->needs_rast_discard_workaround) { ctx->primitives_generated_active = true; if (zink_set_rasterizer_discard(ctx, true)) zink_set_color_write_enables(ctx); } } static bool zink_begin_query(struct pipe_context *pctx, struct pipe_query *q) { struct zink_query *query = (struct zink_query *)q; struct zink_context *ctx = zink_context(pctx); struct zink_batch *batch = &ctx->batch; /* drop all past results */ reset_qbo(query); util_dynarray_clear(&query->starts); query->last_start_idx = get_num_starts(query); /* A query must either begin and end inside the same subpass of a render pass instance, or must both begin and end outside of a render pass instance (i.e. contain entire render pass instances). - 18.2. Query Operation * tilers prefer out-of-renderpass queries for perf reasons, so force all queries * out of renderpasses */ zink_batch_no_rp(ctx); begin_query(ctx, batch, query); return true; } static void update_query_id(struct zink_context *ctx, struct zink_query *q) { query_pool_get_range(ctx, q); ctx->batch.has_work = true; q->has_draws = false; } static void check_update(struct zink_context *ctx, struct zink_query *q) { if (ctx->batch.in_rp) q->needs_update = true; else update_qbo(ctx, q); } static void end_query(struct zink_context *ctx, struct zink_batch *batch, struct zink_query *q) { if (q->type == PIPE_QUERY_TIMESTAMP_DISJOINT) return; ASSERTED struct zink_query_buffer *qbo = q->curr_qbo; assert(qbo); assert(!is_time_query(q)); q->active = false; struct zink_query_start *start = util_dynarray_top_ptr(&q->starts, struct zink_query_start); if (q->type == PIPE_QUERY_PRIMITIVES_EMITTED || is_emulated_primgen(q) || q->type == PIPE_QUERY_SO_OVERFLOW_PREDICATE) { struct zink_vk_query *vkq = start->vkq[1] ? start->vkq[1] : start->vkq[0]; end_vk_query_indexed(ctx, vkq, q->index); ctx->curr_xfb_queries[q->index] = NULL; } else if (q->type == PIPE_QUERY_SO_OVERFLOW_ANY_PREDICATE) { for (unsigned i = 0; i < PIPE_MAX_VERTEX_STREAMS; i++) { end_vk_query_indexed(ctx, start->vkq[i], i); ctx->curr_xfb_queries[i] = NULL; } } else if (q->vkqtype == VK_QUERY_TYPE_PRIMITIVES_GENERATED_EXT) { end_vk_query_indexed(ctx, start->vkq[0], q->index); } if (q->vkqtype != VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT && q->vkqtype != VK_QUERY_TYPE_PRIMITIVES_GENERATED_EXT && !is_time_query(q)) VKCTX(CmdEndQuery)(batch->state->cmdbuf, start->vkq[0]->pool->query_pool, start->vkq[0]->query_id); if (q->type == PIPE_QUERY_PIPELINE_STATISTICS_SINGLE && q->index == PIPE_STAT_QUERY_IA_VERTICES) ctx->vertices_query = NULL; if (needs_stats_list(q)) list_delinit(&q->stats_list); check_update(ctx, q); if (q->needs_rast_discard_workaround) { ctx->primitives_generated_active = false; if (zink_set_rasterizer_discard(ctx, false)) zink_set_color_write_enables(ctx); } } static bool zink_end_query(struct pipe_context *pctx, struct pipe_query *q) { struct zink_context *ctx = zink_context(pctx); struct zink_query *query = (struct zink_query *)q; struct zink_batch *batch = &ctx->batch; if (query->type == PIPE_QUERY_TIMESTAMP_DISJOINT) return true; if (query->type == PIPE_QUERY_GPU_FINISHED) { pctx->flush(pctx, &query->fence, PIPE_FLUSH_DEFERRED); return true; } /* FIXME: this can be called from a thread, but it needs to write to the cmdbuf */ threaded_context_unwrap_sync(pctx); zink_batch_no_rp(ctx); if (needs_stats_list(query)) list_delinit(&query->stats_list); if (is_time_query(query)) { update_query_id(ctx, query); if (query->needs_reset) reset_qbos(ctx, query); reset_query_range(ctx, query); struct zink_query_start *start = util_dynarray_top_ptr(&query->starts, struct zink_query_start); VKCTX(CmdWriteTimestamp)(batch->state->cmdbuf, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, start->vkq[0]->pool->query_pool, start->vkq[0]->query_id); zink_batch_usage_set(&query->batch_uses, batch->state); _mesa_set_add(&batch->state->active_queries, query); check_update(ctx, query); } else if (query->active) end_query(ctx, batch, query); return true; } static bool zink_get_query_result(struct pipe_context *pctx, struct pipe_query *q, bool wait, union pipe_query_result *result) { struct zink_query *query = (void*)q; struct zink_context *ctx = zink_context(pctx); if (query->type == PIPE_QUERY_TIMESTAMP_DISJOINT) { result->timestamp_disjoint.frequency = zink_screen(pctx->screen)->info.props.limits.timestampPeriod * 1000000.0; result->timestamp_disjoint.disjoint = false; return true; } if (query->type == PIPE_QUERY_GPU_FINISHED) { struct pipe_screen *screen = pctx->screen; result->b = screen->fence_finish(screen, query->base.flushed ? NULL : pctx, query->fence, wait ? PIPE_TIMEOUT_INFINITE : 0); return result->b; } if (query->needs_update) update_qbo(ctx, query); if (zink_batch_usage_is_unflushed(query->batch_uses)) { if (!threaded_query(q)->flushed) pctx->flush(pctx, NULL, 0); if (!wait) return false; } return get_query_result(pctx, q, wait, result); } static void suspend_query(struct zink_context *ctx, struct zink_query *query) { /* if a query isn't active here then we don't need to reactivate it on the next batch */ if (query->active && !is_time_query(query)) end_query(ctx, &ctx->batch, query); if (query->needs_update) update_qbo(ctx, query); } void zink_suspend_queries(struct zink_context *ctx, struct zink_batch *batch) { set_foreach(&batch->state->active_queries, entry) { struct zink_query *query = (void*)entry->key; if (query->active && !is_time_query(query)) /* the fence is going to steal the set off the batch, so we have to copy * the active queries onto a list */ list_addtail(&query->active_list, &ctx->suspended_queries); suspend_query(ctx, query); } } void zink_resume_queries(struct zink_context *ctx, struct zink_batch *batch) { struct zink_query *query, *next; LIST_FOR_EACH_ENTRY_SAFE(query, next, &ctx->suspended_queries, active_list) { list_delinit(&query->active_list); begin_query(ctx, batch, query); } } void zink_query_update_gs_states(struct zink_context *ctx, bool was_line_loop) { struct zink_query *query; bool suspendall = false; bool have_gs = !!ctx->gfx_stages[MESA_SHADER_GEOMETRY]; bool have_xfb = !!ctx->num_so_targets; LIST_FOR_EACH_ENTRY(query, &ctx->primitives_generated_queries, stats_list) { struct zink_query_start *last_start = util_dynarray_top_ptr(&query->starts, struct zink_query_start); assert(query->active); if (query->has_draws) { if (last_start->have_gs != have_gs || last_start->have_xfb != have_xfb) { suspendall = true; } } } if (ctx->vertices_query) { query = ctx->vertices_query; struct zink_query_start *last_start = util_dynarray_top_ptr(&query->starts, struct zink_query_start); assert(query->active); if (last_start->was_line_loop != was_line_loop) { suspendall = true; } } if (suspendall) { zink_suspend_queries(ctx, &ctx->batch); zink_resume_queries(ctx, &ctx->batch); } LIST_FOR_EACH_ENTRY(query, &ctx->primitives_generated_queries, stats_list) { struct zink_query_start *last_start = util_dynarray_top_ptr(&query->starts, struct zink_query_start); last_start->have_gs = have_gs; last_start->have_xfb = have_xfb; query->has_draws = true; } if (ctx->vertices_query) { query = ctx->vertices_query; struct zink_query_start *last_start = util_dynarray_top_ptr(&query->starts, struct zink_query_start); last_start->was_line_loop = was_line_loop; query->has_draws = true; } } static void zink_set_active_query_state(struct pipe_context *pctx, bool enable) { struct zink_context *ctx = zink_context(pctx); ctx->queries_disabled = !enable; struct zink_batch *batch = &ctx->batch; if (ctx->queries_disabled) zink_suspend_queries(ctx, batch); else zink_resume_queries(ctx, batch); } void zink_start_conditional_render(struct zink_context *ctx) { if (unlikely(!zink_screen(ctx->base.screen)->info.have_EXT_conditional_rendering) || ctx->render_condition.active) return; struct zink_batch *batch = &ctx->batch; VkConditionalRenderingFlagsEXT begin_flags = 0; if (ctx->render_condition.inverted) begin_flags = VK_CONDITIONAL_RENDERING_INVERTED_BIT_EXT; VkConditionalRenderingBeginInfoEXT begin_info = {0}; begin_info.sType = VK_STRUCTURE_TYPE_CONDITIONAL_RENDERING_BEGIN_INFO_EXT; begin_info.buffer = ctx->render_condition.query->predicate->obj->buffer; begin_info.flags = begin_flags; ctx->render_condition.query->predicate->obj->unordered_read = false; VKCTX(CmdBeginConditionalRenderingEXT)(batch->state->cmdbuf, &begin_info); zink_batch_reference_resource_rw(batch, ctx->render_condition.query->predicate, false); ctx->render_condition.active = true; } void zink_stop_conditional_render(struct zink_context *ctx) { struct zink_batch *batch = &ctx->batch; zink_clear_apply_conditionals(ctx); if (unlikely(!zink_screen(ctx->base.screen)->info.have_EXT_conditional_rendering) || !ctx->render_condition.active) return; VKCTX(CmdEndConditionalRenderingEXT)(batch->state->cmdbuf); ctx->render_condition.active = false; } static void zink_render_condition(struct pipe_context *pctx, struct pipe_query *pquery, bool condition, enum pipe_render_cond_flag mode) { struct zink_context *ctx = zink_context(pctx); struct zink_query *query = (struct zink_query *)pquery; zink_batch_no_rp(ctx); VkQueryResultFlagBits flags = 0; if (query == NULL) { /* force conditional clears if they exist */ if (ctx->clears_enabled && !ctx->batch.in_rp) zink_batch_rp(ctx); zink_stop_conditional_render(ctx); ctx->render_condition_active = false; ctx->render_condition.query = NULL; return; } if (!query->predicate) { struct pipe_resource *pres; /* need to create a vulkan buffer to copy the data into */ pres = pipe_buffer_create(pctx->screen, PIPE_BIND_QUERY_BUFFER, PIPE_USAGE_DEFAULT, sizeof(uint64_t)); if (!pres) return; query->predicate = zink_resource(pres); } if (query->predicate_dirty) { struct zink_resource *res = query->predicate; if (mode == PIPE_RENDER_COND_WAIT || mode == PIPE_RENDER_COND_BY_REGION_WAIT) flags |= VK_QUERY_RESULT_WAIT_BIT; flags |= VK_QUERY_RESULT_64_BIT; int num_results = get_num_starts(query); if (!is_emulated_primgen(query) && !is_so_overflow_query(query)) { copy_results_to_buffer(ctx, query, res, 0, num_results, flags); } else { /* these need special handling */ force_cpu_read(ctx, pquery, PIPE_QUERY_TYPE_U32, &res->base.b, 0); } zink_screen(ctx->base.screen)->buffer_barrier(ctx, res, VK_ACCESS_CONDITIONAL_RENDERING_READ_BIT_EXT, VK_PIPELINE_STAGE_CONDITIONAL_RENDERING_BIT_EXT); query->predicate_dirty = false; } ctx->render_condition.inverted = condition; ctx->render_condition_active = true; ctx->render_condition.query = query; if (ctx->batch.in_rp) zink_start_conditional_render(ctx); } static void zink_get_query_result_resource(struct pipe_context *pctx, struct pipe_query *pquery, enum pipe_query_flags flags, enum pipe_query_value_type result_type, int index, struct pipe_resource *pres, unsigned offset) { struct zink_context *ctx = zink_context(pctx); struct zink_screen *screen = zink_screen(pctx->screen); struct zink_query *query = (struct zink_query*)pquery; struct zink_resource *res = zink_resource(pres); unsigned result_size = result_type <= PIPE_QUERY_TYPE_U32 ? sizeof(uint32_t) : sizeof(uint64_t); VkQueryResultFlagBits size_flags = result_type <= PIPE_QUERY_TYPE_U32 ? 0 : VK_QUERY_RESULT_64_BIT; unsigned num_queries = (get_num_starts(query) - query->last_start_idx); struct zink_query_start *start = util_dynarray_top_ptr(&query->starts, struct zink_query_start); unsigned query_id = start->vkq[0]->query_id; if (index == -1) { /* VK_QUERY_RESULT_WITH_AVAILABILITY_BIT will ALWAYS write some kind of result data * in addition to the availability result, which is a problem if we're just trying to get availability data * * if we know that there's no valid buffer data in the preceding buffer range, then we can just * stomp on it with a glorious queued buffer copy instead of forcing a stall to manually write to the * buffer */ VkQueryResultFlags flag = is_time_query(query) ? 0 : VK_QUERY_RESULT_PARTIAL_BIT; unsigned src_offset = result_size * get_num_results(query); if (zink_batch_usage_check_completion(ctx, query->batch_uses)) { uint64_t u64[4] = {0}; VkResult result = VKCTX(GetQueryPoolResults)(screen->dev, start->vkq[0]->pool->query_pool, query_id, 1, sizeof(u64), u64, 0, size_flags | VK_QUERY_RESULT_WITH_AVAILABILITY_BIT | flag); if (result == VK_SUCCESS) { tc_buffer_write(pctx, pres, offset, result_size, (unsigned char*)u64 + src_offset); return; } else { mesa_loge("ZINK: vkGetQueryPoolResults failed (%s)", vk_Result_to_str(result)); } } struct pipe_resource *staging = pipe_buffer_create(pctx->screen, 0, PIPE_USAGE_STAGING, src_offset + result_size); copy_results_to_buffer(ctx, query, zink_resource(staging), 0, 1, size_flags | VK_QUERY_RESULT_WITH_AVAILABILITY_BIT | flag); zink_copy_buffer(ctx, res, zink_resource(staging), offset, result_size * get_num_results(query), result_size); pipe_resource_reference(&staging, NULL); return; } /* there is an implicit execution dependency from each such query command to all query commands previously submitted to the same queue. There is one significant exception to this; if the flags parameter of vkCmdCopyQueryPoolResults does not include VK_QUERY_RESULT_WAIT_BIT, execution of vkCmdCopyQueryPoolResults may happen-before the results of vkCmdEndQuery are available. * - Chapter 18. Queries */ size_flags |= VK_QUERY_RESULT_WAIT_BIT; if (!is_time_query(query) && !is_bool_query(query)) { if (num_queries == 1 && !is_emulated_primgen(query) && query->type != PIPE_QUERY_PRIMITIVES_EMITTED && !is_bool_query(query)) { if (size_flags == VK_QUERY_RESULT_64_BIT) { if (query->needs_update) update_qbo(ctx, query); /* internal qbo always writes 64bit value so we can just direct copy */ zink_copy_buffer(ctx, res, zink_resource(query->curr_qbo->buffers[0]), offset, get_buffer_offset(query), result_size); } else /* have to do a new copy for 32bit */ copy_results_to_buffer(ctx, query, res, offset, 1, size_flags); return; } } /* TODO: use CS to aggregate results */ /* unfortunately, there's no way to accumulate results from multiple queries on the gpu without either * clobbering all but the last result or writing the results sequentially, so we have to manually write the result */ force_cpu_read(ctx, pquery, result_type, pres, offset); } uint64_t zink_get_timestamp(struct pipe_screen *pscreen) { struct zink_screen *screen = zink_screen(pscreen); uint64_t timestamp, deviation; if (screen->info.have_EXT_calibrated_timestamps) { VkCalibratedTimestampInfoEXT cti = {0}; cti.sType = VK_STRUCTURE_TYPE_CALIBRATED_TIMESTAMP_INFO_EXT; cti.timeDomain = VK_TIME_DOMAIN_DEVICE_EXT; VkResult result = VKSCR(GetCalibratedTimestampsEXT)(screen->dev, 1, &cti, &timestamp, &deviation); if (result != VK_SUCCESS) { mesa_loge("ZINK: vkGetCalibratedTimestampsEXT failed (%s)", vk_Result_to_str(result)); } } else { struct pipe_context *pctx = &screen->copy_context->base; struct pipe_query *pquery = pctx->create_query(pctx, PIPE_QUERY_TIMESTAMP, 0); if (!pquery) return 0; union pipe_query_result result = {0}; pctx->begin_query(pctx, pquery); pctx->end_query(pctx, pquery); pctx->get_query_result(pctx, pquery, true, &result); pctx->destroy_query(pctx, pquery); timestamp = result.u64; } timestamp_to_nanoseconds(screen, &timestamp); return timestamp; } void zink_context_query_init(struct pipe_context *pctx) { struct zink_context *ctx = zink_context(pctx); list_inithead(&ctx->suspended_queries); list_inithead(&ctx->primitives_generated_queries); pctx->create_query = zink_create_query; pctx->destroy_query = zink_destroy_query; pctx->begin_query = zink_begin_query; pctx->end_query = zink_end_query; pctx->get_query_result = zink_get_query_result; pctx->get_query_result_resource = zink_get_query_result_resource; pctx->set_active_query_state = zink_set_active_query_state; pctx->render_condition = zink_render_condition; }
47f4d9ba0bf5f3f0d75d74c592b26c621b5dc526
3eb3c4046b17e265930aaf89fa93f41896f243cb
/neural_modelling/src/synapse_expander/synapse_expander.c
ecd59ab6fcb379265d387a88c7b4e7af20f15081
[ "Apache-2.0" ]
permissive
SpiNNakerManchester/sPyNNaker
b177613a114cfc7e7687ec36c1f72a2f07f66977
891cfb3046f66185fd8df52d270380fa94c32eab
refs/heads/master
2023-09-01T11:28:21.252266
2023-08-17T08:07:43
2023-08-17T08:07:43
20,801,613
101
53
Apache-2.0
2023-09-14T18:39:29
2014-06-13T11:07:19
Python
UTF-8
C
false
false
8,745
c
synapse_expander.c
/* * Copyright (c) 2017 The University of Manchester * * 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 * * https://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. */ /** * \dir * \brief Implementation of the synapse expander and delay expander * \file * \brief The synapse expander for neuron cores */ #include "matrix_generator.h" #include "connection_generator.h" #include "param_generator.h" #include "rng.h" #include <spin1_api.h> #include <data_specification.h> #include <debug.h> #include <key_atom_map.h> #include "common_mem.h" #include "bit_field_expander.h" #define INVALID_REGION_ID 0xFFFFFFFF //! The configuration of the connection builder typedef struct connection_builder_config { // the per-connector parameters uint32_t pre_lo; uint32_t pre_hi; uint32_t post_lo; uint32_t post_hi; uint32_t synapse_type; // The types of the various components uint32_t matrix_type; uint32_t connector_type; uint32_t weight_type; uint32_t delay_type; } connection_builder_config_t; //! The configuration of the synapse expander __attribute__((aligned(4))) typedef struct expander_config { uint32_t synaptic_matrix_region; uint32_t master_pop_region; uint32_t bitfield_filter_region; uint32_t structural_region; uint32_t n_in_edges; uint32_t post_slice_start; uint32_t post_slice_count; uint32_t post_index; uint32_t n_synapse_types; accum timestep_per_delay; rng_t population_rng; rng_t core_rng; unsigned long accum weight_scales[]; } expander_config_t; rng_t *population_rng; rng_t *core_rng; /** * \brief Generate the synapses for a single connector * \param[in,out] in_region: The address to read the parameters from. Should be * updated to the position just after the parameters * after calling. * \param[in] synaptic_matrix_region: The address of the synaptic matrices * \param[in] post_slice_start: The start of the slice of the post-population to * generate for * \param[in] post_slice_count: The number of neurons to generate for * \param[in] n_synapse_type_bits: The number of bits in the synapse type * \param[in] n_synapse_index_bits: The number of bits for the neuron index id * \param[in] weight_scales: An array of weight scales, one for each synapse * type * \return true on success, false on failure */ static bool read_connection_builder_region(void **region, void *synaptic_matrix, uint32_t post_slice_start, uint32_t post_slice_count, uint32_t post_index, unsigned long accum *weight_scales, accum timestep_per_delay) { connection_builder_config_t *sdram_config = *region; connection_builder_config_t config = *sdram_config; *region = &sdram_config[1]; // Get the matrix, connector, weight and delay parameter generators matrix_generator_t matrix_generator = matrix_generator_init(config.matrix_type, region, synaptic_matrix); connection_generator_t connection_generator = connection_generator_init(config.connector_type, region); param_generator_t weight_generator = param_generator_init(config.weight_type, region); param_generator_t delay_generator = param_generator_init(config.delay_type, region); // If any components couldn't be created return false if (matrix_generator == NULL || connection_generator == NULL || delay_generator == NULL || weight_generator == NULL) { return false; } if (!connection_generator_generate( connection_generator, config.pre_lo, config.pre_hi, config.post_lo, config.post_hi, post_index, post_slice_start, post_slice_count, weight_scales[config.synapse_type], timestep_per_delay, weight_generator, delay_generator, matrix_generator)) { return false; } // Free the neuron four! matrix_generator_free(matrix_generator); connection_generator_free(connection_generator); param_generator_free(weight_generator); param_generator_free(delay_generator); // Return success! return true; } /** * \brief Read the data for the expander * \param[in] ds_regions: The data specification regions * \param[in] params_address: The address of the expander parameters * \return True if the expander finished correctly, False if there was an * error */ static bool run_synapse_expander(data_specification_metadata_t *ds_regions, void *params_address) { // Read in the global parameters expander_config_t *sdram_config = params_address; uint32_t data_size = sizeof(expander_config_t) + (sizeof(long accum) * sdram_config->n_synapse_types); expander_config_t *config = spin1_malloc(data_size); fast_memcpy(config, sdram_config, data_size); log_info("Generating %u edges for %u atoms starting at %u", config->n_in_edges, config->post_slice_count, config->post_slice_start); // Get the synaptic matrix region void *synaptic_matrix = data_specification_get_region( config->synaptic_matrix_region, ds_regions); // We are changing this region, so void the checksum ds_regions->regions[config->synaptic_matrix_region].n_words = 0; ds_regions->regions[config->synaptic_matrix_region].checksum = 0; // Store the RNGs population_rng = &(config->population_rng); core_rng = &(config->core_rng); log_info("Population RNG: %u %u %u %u", population_rng->seed[0], population_rng->seed[1], population_rng->seed[2], population_rng->seed[3]); log_info("Core RNG: %u %u %u %u", core_rng->seed[0], core_rng->seed[1], core_rng->seed[2], core_rng->seed[3]); // Go through each connector and generate void *address = &(sdram_config->weight_scales[config->n_synapse_types]); for (uint32_t edge = 0; edge < config->n_in_edges; edge++) { if (!read_connection_builder_region( &address, synaptic_matrix, config->post_slice_start, config->post_slice_count, config->post_index, config->weight_scales, config->timestep_per_delay)) { return false; } } // Do bitfield generation on the whole matrix uint32_t *n_atom_data_sdram = address; void *master_pop = data_specification_get_region( config->master_pop_region, ds_regions); void *bitfield_filter = data_specification_get_region( config->bitfield_filter_region, ds_regions); void *structural_matrix = NULL; if (config->structural_region != INVALID_REGION_ID) { structural_matrix = data_specification_get_region( config->structural_region, ds_regions); } // We are changing this region, so void the checksum ds_regions->regions[config->bitfield_filter_region].n_words = 0; ds_regions->regions[config->bitfield_filter_region].checksum = 0; log_info("Region %u set to 0 at 0x%08x and 0x%08x", config->bitfield_filter_region, &(ds_regions->regions[config->bitfield_filter_region].n_words), &(ds_regions->regions[config->bitfield_filter_region].checksum)); return do_bitfield_generation(n_atom_data_sdram, master_pop, synaptic_matrix, bitfield_filter, structural_matrix); } //! Entry point void c_main(void) { sark_cpu_state(CPU_STATE_RUN); log_info("Starting To Build Connectors"); // Get pointer to 1st virtual processor info struct in SRAM and get USER1; // This is the ID of the connection builder region from which to read the // rest of the data vcpu_t *virtual_processor_table = (vcpu_t*) SV_VCPU; uint user1 = virtual_processor_table[spin1_get_core_id()].user1; // Get the addresses of the regions data_specification_metadata_t *ds_regions = data_specification_get_data_address(); void *params_address = data_specification_get_region(user1, ds_regions); log_info("\tReading SDRAM at 0x%08x", params_address); // Run the expander if (!run_synapse_expander(ds_regions, params_address)) { log_info("!!! Error reading SDRAM data !!!"); rt_error(RTE_ABORT); } log_info("Finished On Machine Connectors!"); }
2734962743715fb40ca8bf1d5d94a42440fd56e2
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/net/sched/sch_codel.c
2f9ab17db85a59524556055bc5e53c5f2cab1a67
[ "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later", "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
7,595
c
sch_codel.c
/* * Codel - The Controlled-Delay Active Queue Management algorithm * * Copyright (C) 2011-2012 Kathleen Nichols <nichols@pollere.com> * Copyright (C) 2011-2012 Van Jacobson <van@pollere.net> * * Implemented on linux by : * Copyright (C) 2012 Michael D. Taht <dave.taht@bufferbloat.net> * Copyright (C) 2012 Eric Dumazet <edumazet@google.com> * * 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, * without modification. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The names of the authors may not be used to endorse or promote products * derived from this software without specific prior written permission. * * Alternatively, provided that this notice is retained in full, this * software may be distributed under the terms of the GNU General * Public License ("GPL") version 2, in which case the provisions of the * GPL apply INSTEAD OF those given above. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * */ #include <linux/module.h> #include <linux/slab.h> #include <linux/types.h> #include <linux/kernel.h> #include <linux/errno.h> #include <linux/skbuff.h> #include <linux/prefetch.h> #include <net/pkt_sched.h> #include <net/codel.h> #define DEFAULT_CODEL_LIMIT 1000 struct codel_sched_data { struct codel_params params; struct codel_vars vars; struct codel_stats stats; u32 drop_overlimit; }; /* This is the specific function called from codel_dequeue() * to dequeue a packet from queue. Note: backlog is handled in * codel, we dont need to reduce it here. */ static struct sk_buff *dequeue(struct codel_vars *vars, struct Qdisc *sch) { struct sk_buff *skb = __skb_dequeue(&sch->q); prefetch(&skb->end); /* we'll need skb_shinfo() */ return skb; } static struct sk_buff *codel_qdisc_dequeue(struct Qdisc *sch) { struct codel_sched_data *q = qdisc_priv(sch); struct sk_buff *skb; skb = codel_dequeue(sch, &q->params, &q->vars, &q->stats, dequeue); /* We cant call qdisc_tree_decrease_qlen() if our qlen is 0, * or HTB crashes. Defer it for next round. */ if (q->stats.drop_count && sch->q.qlen) { qdisc_tree_decrease_qlen(sch, q->stats.drop_count); q->stats.drop_count = 0; } if (skb) qdisc_bstats_update(sch, skb); return skb; } static int codel_qdisc_enqueue(struct sk_buff *skb, struct Qdisc *sch) { struct codel_sched_data *q; if (likely(qdisc_qlen(sch) < sch->limit)) { codel_set_enqueue_time(skb); return qdisc_enqueue_tail(skb, sch); } q = qdisc_priv(sch); q->drop_overlimit++; return qdisc_drop(skb, sch); } static const struct nla_policy codel_policy[TCA_CODEL_MAX + 1] = { [TCA_CODEL_TARGET] = { .type = NLA_U32 }, [TCA_CODEL_LIMIT] = { .type = NLA_U32 }, [TCA_CODEL_INTERVAL] = { .type = NLA_U32 }, [TCA_CODEL_ECN] = { .type = NLA_U32 }, }; static int codel_change(struct Qdisc *sch, struct nlattr *opt) { struct codel_sched_data *q = qdisc_priv(sch); struct nlattr *tb[TCA_CODEL_MAX + 1]; unsigned int qlen; int err; if (!opt) return -EINVAL; err = nla_parse_nested(tb, TCA_CODEL_MAX, opt, codel_policy); if (err < 0) return err; sch_tree_lock(sch); if (tb[TCA_CODEL_TARGET]) { u32 target = nla_get_u32(tb[TCA_CODEL_TARGET]); q->params.target = ((u64)target * NSEC_PER_USEC) >> CODEL_SHIFT; } if (tb[TCA_CODEL_INTERVAL]) { u32 interval = nla_get_u32(tb[TCA_CODEL_INTERVAL]); q->params.interval = ((u64)interval * NSEC_PER_USEC) >> CODEL_SHIFT; } if (tb[TCA_CODEL_LIMIT]) sch->limit = nla_get_u32(tb[TCA_CODEL_LIMIT]); if (tb[TCA_CODEL_ECN]) q->params.ecn = !!nla_get_u32(tb[TCA_CODEL_ECN]); qlen = sch->q.qlen; while (sch->q.qlen > sch->limit) { struct sk_buff *skb = __skb_dequeue(&sch->q); sch->qstats.backlog -= qdisc_pkt_len(skb); qdisc_drop(skb, sch); } qdisc_tree_decrease_qlen(sch, qlen - sch->q.qlen); sch_tree_unlock(sch); return 0; } static int codel_init(struct Qdisc *sch, struct nlattr *opt) { struct codel_sched_data *q = qdisc_priv(sch); sch->limit = DEFAULT_CODEL_LIMIT; codel_params_init(&q->params); codel_vars_init(&q->vars); codel_stats_init(&q->stats); if (opt) { int err = codel_change(sch, opt); if (err) return err; } if (sch->limit >= 1) sch->flags |= TCQ_F_CAN_BYPASS; else sch->flags &= ~TCQ_F_CAN_BYPASS; return 0; } static int codel_dump(struct Qdisc *sch, struct sk_buff *skb) { struct codel_sched_data *q = qdisc_priv(sch); struct nlattr *opts; opts = nla_nest_start(skb, TCA_OPTIONS); if (opts == NULL) goto nla_put_failure; if (nla_put_u32(skb, TCA_CODEL_TARGET, codel_time_to_us(q->params.target)) || nla_put_u32(skb, TCA_CODEL_LIMIT, sch->limit) || nla_put_u32(skb, TCA_CODEL_INTERVAL, codel_time_to_us(q->params.interval)) || nla_put_u32(skb, TCA_CODEL_ECN, q->params.ecn)) goto nla_put_failure; return nla_nest_end(skb, opts); nla_put_failure: nla_nest_cancel(skb, opts); return -1; } static int codel_dump_stats(struct Qdisc *sch, struct gnet_dump *d) { const struct codel_sched_data *q = qdisc_priv(sch); struct tc_codel_xstats st = { .maxpacket = q->stats.maxpacket, .count = q->vars.count, .lastcount = q->vars.lastcount, .drop_overlimit = q->drop_overlimit, .ldelay = codel_time_to_us(q->vars.ldelay), .dropping = q->vars.dropping, .ecn_mark = q->stats.ecn_mark, }; if (q->vars.dropping) { codel_tdiff_t delta = q->vars.drop_next - codel_get_time(); if (delta >= 0) st.drop_next = codel_time_to_us(delta); else st.drop_next = -codel_time_to_us(-delta); } return gnet_stats_copy_app(d, &st, sizeof(st)); } static void codel_reset(struct Qdisc *sch) { struct codel_sched_data *q = qdisc_priv(sch); qdisc_reset_queue(sch); codel_vars_init(&q->vars); } static struct Qdisc_ops codel_qdisc_ops __read_mostly = { .id = "codel", .priv_size = sizeof(struct codel_sched_data), .enqueue = codel_qdisc_enqueue, .dequeue = codel_qdisc_dequeue, .peek = qdisc_peek_dequeued, .init = codel_init, .reset = codel_reset, .change = codel_change, .dump = codel_dump, .dump_stats = codel_dump_stats, .owner = THIS_MODULE, }; static int __init codel_module_init(void) { return register_qdisc(&codel_qdisc_ops); } static void __exit codel_module_exit(void) { unregister_qdisc(&codel_qdisc_ops); } module_init(codel_module_init) module_exit(codel_module_exit) MODULE_DESCRIPTION("Controlled Delay queue discipline"); MODULE_AUTHOR("Dave Taht"); MODULE_AUTHOR("Eric Dumazet"); MODULE_LICENSE("Dual BSD/GPL");
1f97e504b2978b72b65059c605d47a7ed9c77215
89db60818afeb3dc7c3b7abe9ceae155f074f7f2
/src/cmd/upas/smtp/rmtdns.c
54b679bb9249bdd7a34af2bafb2f53e6fd4441a3
[ "bzip2-1.0.6", "LPL-1.02", "MIT" ]
permissive
9fans/plan9port
63c3d01928c6f8a8617d3ea6ecc05bac72391132
65c090346a38a8c30cb242d345aa71060116340c
refs/heads/master
2023-08-25T17:14:26.233105
2023-08-23T13:21:37
2023-08-23T18:47:08
26,095,474
1,645
468
NOASSERTION
2023-09-05T16:55:41
2014-11-02T22:40:13
C
UTF-8
C
false
false
1,069
c
rmtdns.c
#include "common.h" #include <ndb.h> int rmtdns(char *net, char *path) { int fd, n, r; char *domain, *cp, buf[1024]; if(net == 0 || path == 0) return 0; domain = strdup(path); cp = strchr(domain, '!'); if(cp){ *cp = 0; n = cp-domain; } else n = strlen(domain); if(*domain == '[' && domain[n-1] == ']'){ /* accept [nnn.nnn.nnn.nnn] */ domain[n-1] = 0; r = strcmp(ipattr(domain+1), "ip"); domain[n-1] = ']'; } else r = strcmp(ipattr(domain), "ip"); /* accept nnn.nnn.nnn.nnn */ if(r == 0){ free(domain); return 0; } snprint(buf, sizeof(buf), "%s/dns", net); fd = open(buf, ORDWR); /* look up all others */ if(fd < 0){ /* dns screw up - can't check */ free(domain); return 0; } n = snprint(buf, sizeof(buf), "%s all", domain); free(domain); seek(fd, 0, 0); n = write(fd, buf, n); close(fd); if(n < 0){ rerrstr(buf, sizeof(buf)); if (strcmp(buf, "dns: name does not exist") == 0) return -1; } return 0; } /* void main(int, char *argv[]){ print("return = %d\n", rmtdns("/net.alt/tcp/109", argv[1]));} */
47967fb9469a96050bff311a866a2d52cbe0689c
3a4f120f3211a1482b8ba826f4922fa741c5586e
/ip/Pmods/PmodAD1_v1_0/drivers/PmodAD1_v1_0/src/PmodAD1.h
464c5e972fcf080224cc3f026e0a5ae4e3c0605f
[ "MIT" ]
permissive
Digilent/vivado-library
7135129c7e4fec84d17e1fe037598bd2124085eb
cbfde215a27053004cb41d85535c4a1bd1673e14
refs/heads/master
2023-09-05T22:04:31.189589
2023-08-22T17:23:00
2023-08-22T17:23:46
46,139,497
512
327
MIT
2023-08-22T17:23:47
2015-11-13T18:23:02
C
UTF-8
C
false
false
2,510
h
PmodAD1.h
/******************************************************************************/ /* */ /* PmodAD1.h -- PmodAD1 Driver Definitions */ /* */ /******************************************************************************/ /* Author: Arthur Brown */ /* Copyright 2017, Digilent Inc. */ /******************************************************************************/ /* Module Description: */ /* */ /* This file contains definitions for the PmodAD1 driver */ /* */ /******************************************************************************/ /* Revision History: */ /* */ /* 08/15/2017(ArtVVB): Created */ /* 02/10/2018(atangzwj): Validated for Vivado 2017.4 */ /* */ /******************************************************************************/ #ifndef PMODAD1_H #define PMODAD1_H /****************** Include Files ********************/ #include "xil_io.h" #include "xil_types.h" /* ------------------------------------------------------------ */ /* Definitions */ /* ------------------------------------------------------------ */ #define AD1_NUM_BITS 12 #define AD1_DATA_MASK 0xFFF typedef struct PmodAD1 { u32 BaseAddress; } PmodAD1; typedef u16 AD1_RawData[2]; typedef float AD1_PhysicalData[2]; /* ------------------------------------------------------------ */ /* Procedure Declarations */ /* ------------------------------------------------------------ */ void AD1_begin(PmodAD1 *InstancePtr, u32 SPI_Address); void AD1_GetSample(PmodAD1 *InstancePtr, AD1_RawData *RawDataPtr); void AD1_RawToPhysical(float ReferenceVoltage, AD1_RawData RawData, AD1_PhysicalData *PhysicalDataPtr); #endif // PMODAD1_H
bb41f638bc18e97b8dd6f8bab03fba7e3013e309
4c4deee160ee4a3056b2973f6202e5cbaafb5925
/meta2v2/meta2_filters_extract.c
46c8103b8365a399059605e294af0289f8b90d65
[ "AGPL-3.0-only", "LGPL-3.0-only" ]
permissive
open-io/oio-sds
b9bc7cec283838a59b83b5279cb181cded69034f
08abd65aac86e47cf324826487ab9b475e014938
refs/heads/master
2023-09-05T05:09:29.653325
2023-08-01T16:37:37
2023-08-31T16:05:19
32,169,193
663
121
MIT
2022-03-04T13:08:03
2015-03-13T17:06:25
Python
UTF-8
C
false
false
12,422
c
meta2_filters_extract.c
/* OpenIO SDS meta2v2 Copyright (C) 2014 Worldline, as part of Redcurrant Copyright (C) 2015-2019 OpenIO SAS, as part of OpenIO SDS Copyright (C) 2021-2023 OVH SAS This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stdlib.h> #include <string.h> #include <errno.h> #include <glib.h> #include <metautils/lib/metautils.h> #include <metautils/lib/metacomm.h> #include <server/transport_gridd.h> #include <server/gridd_dispatcher_filters.h> #include <meta2v2/meta2_macros.h> #include <meta2v2/meta2_filter_context.h> #include <meta2v2/meta2_filters.h> #include <meta2v2/meta2_backend_internals.h> #include <meta2v2/meta2_bean.h> #include <meta2v2/generic.h> #include <meta2v2/autogen.h> #define EXTRACT_STRING2(FieldName,VarName,Opt) do { \ e = metautils_message_extract_string(reply->request, FieldName, buf, sizeof(buf)); \ if(NULL != e) { \ if(!Opt) { \ meta2_filter_ctx_set_error(ctx, e); \ return FILTER_KO; \ } else { \ g_clear_error(&e); \ return FILTER_OK; \ } \ } \ meta2_filter_ctx_add_param(ctx, VarName, buf); \ } while (0) #define EXTRACT_STRING(Name, Opt) EXTRACT_STRING2(Name,Name,Opt) #define EXTRACT_OPT(Name) do { \ memset(buf, 0, sizeof(buf)); \ e = metautils_message_extract_string(reply->request, Name, buf, sizeof(buf)); \ if (NULL != e) { \ g_clear_error(&e); \ } else { \ meta2_filter_ctx_add_param(ctx, Name, buf); \ } \ } while (0) #define EXTRACT_HEADER_BEANS(FieldName,Variable) do {\ GError *err = metautils_message_extract_header_encoded(reply->request, FieldName, TRUE, &Variable, bean_sequence_decoder);\ if (err) { \ meta2_filter_ctx_set_error(ctx, err);\ return FILTER_KO;\ } \ } while(0) int meta2_filter_extract_header_url(struct gridd_filter_ctx_s *ctx, struct gridd_reply_ctx_s *reply) { TRACE_FILTER(); const gchar *err = NULL; struct oio_url_s *url = metautils_message_extract_url (reply->request); if (!oio_url_check(url, NULL, &err)) { meta2_filter_ctx_set_error(ctx, NEWERROR(CODE_BAD_REQUEST, "Invalid request: invalid %s", err)); oio_url_pclean(&url); return FILTER_KO; } meta2_filter_ctx_set_url(ctx, url); return FILTER_OK; } int meta2_filter_extract_header_storage_policy(struct gridd_filter_ctx_s *ctx, struct gridd_reply_ctx_s *reply) { GError *e = NULL; char buf[65]; TRACE_FILTER(); EXTRACT_STRING(NAME_MSGKEY_STGPOLICY, TRUE); return FILTER_OK; } int meta2_filter_extract_header_version_policy(struct gridd_filter_ctx_s *ctx, struct gridd_reply_ctx_s *reply) { GError *e = NULL; char buf[65]; TRACE_FILTER(); EXTRACT_STRING(NAME_MSGKEY_STGPOLICY, TRUE); return FILTER_OK; } static void _plist_cleaner(gpointer ptr) { GSList **lists = ptr; _bean_cleanl2(lists[0]); _bean_cleanl2(lists[1]); g_free (lists); } int meta2_filter_extract_header_chunk_beans(struct gridd_filter_ctx_s *ctx, struct gridd_reply_ctx_s *reply) { GSList **lists = g_malloc0(2 * sizeof(GSList *)); EXTRACT_HEADER_BEANS(NAME_MSGKEY_NEW, lists[0]); EXTRACT_HEADER_BEANS(NAME_MSGKEY_OLD, lists[1]); meta2_filter_ctx_set_input_udata(ctx, lists, _plist_cleaner); return FILTER_OK; } int meta2_filter_extract_body_beans(struct gridd_filter_ctx_s *ctx, struct gridd_reply_ctx_s *reply) { GSList *l = NULL; const char *opt = meta2_filter_ctx_get_param(ctx, "BODY_OPT"); TRACE_FILTER(); /* get the message body */ GError *err = metautils_message_extract_body_encoded (reply->request, (opt==NULL), &l, bean_sequence_decoder); if (err) { _bean_cleanl2 (l); meta2_filter_ctx_set_error(ctx, BADREQ("Invalid request, Empty / Invalid body: (%d) %s", err->code, err->message)); g_error_free(err); return FILTER_KO; } meta2_filter_ctx_set_input_udata(ctx, l, (GDestroyNotify)_bean_cleanl2); return FILTER_OK; } int meta2_filter_extract_header_append(struct gridd_filter_ctx_s *ctx, struct gridd_reply_ctx_s *reply) { GError *e = NULL; gchar buf[512]; TRACE_FILTER(); EXTRACT_STRING2(NAME_MSGKEY_APPEND, "APPEND", 1); return FILTER_OK; } int meta2_filter_extract_header_peers(struct gridd_filter_ctx_s *ctx, struct gridd_reply_ctx_s *reply) { GError *e = NULL; gchar buf[512]; TRACE_FILTER(); EXTRACT_OPT(SQLX_ADMIN_PEERS); return FILTER_OK; } int meta2_filter_extract_header_spare(struct gridd_filter_ctx_s *ctx, struct gridd_reply_ctx_s *reply) { GError *e = NULL; gchar buf[512]; TRACE_FILTER(); EXTRACT_OPT(NAME_MSGKEY_SPARE); const gchar *type = meta2_filter_ctx_get_param(ctx, NAME_MSGKEY_SPARE); if (type != NULL) { /* No content length in spare request */ meta2_filter_ctx_add_param(ctx, "CONTENT_LENGTH_OPT", "OK"); } // Body beans are required only when doing blacklist spare request if (type == NULL || g_ascii_strcasecmp(type, M2V2_SPARE_BY_BLACKLIST)) meta2_filter_ctx_add_param(ctx, "BODY_OPT", "OK"); return FILTER_OK; } static int _extract_header_flag(const gchar *n, struct gridd_filter_ctx_s *ctx, struct gridd_reply_ctx_s *reply) { TRACE_FILTER(); if (metautils_message_extract_flag(reply->request, n, 0)) meta2_filter_ctx_add_param(ctx, n, "1"); return FILTER_OK; } int meta2_filter_extract_header_localflag(struct gridd_filter_ctx_s *ctx, struct gridd_reply_ctx_s *reply) { TRACE_FILTER(); return _extract_header_flag(NAME_MSGKEY_LOCAL, ctx, reply); } int meta2_filter_extract_header_urgentflag(struct gridd_filter_ctx_s *ctx, struct gridd_reply_ctx_s *reply) { TRACE_FILTER(); return _extract_header_flag(NAME_MSGKEY_URGENT, ctx, reply); } int meta2_filter_extract_header_flags32(struct gridd_filter_ctx_s *ctx, struct gridd_reply_ctx_s *reply) { gchar strflags[16]; GError *e = NULL; guint32 flags = 0; TRACE_FILTER(); e = metautils_message_extract_flags32(reply->request, NAME_MSGKEY_FLAGS, FALSE, &flags); if (NULL != e) { meta2_filter_ctx_set_error(ctx, e); return FILTER_KO; } g_snprintf(strflags, sizeof(strflags), "%"G_GUINT32_FORMAT, flags); meta2_filter_ctx_add_param(ctx, NAME_MSGKEY_FLAGS, strflags); return FILTER_OK; } int meta2_filter_extract_header_string_size(struct gridd_filter_ctx_s *ctx, struct gridd_reply_ctx_s *reply) { GError *e = NULL; gchar buf[64]; const char *opt = meta2_filter_ctx_get_param(ctx, "CONTENT_LENGTH_OPT"); TRACE_FILTER(); EXTRACT_STRING(NAME_MSGKEY_CONTENTLENGTH, (opt != NULL)); return FILTER_OK; } int meta2_filter_extract_header_optional_delete_marker( struct gridd_filter_ctx_s *ctx, struct gridd_reply_ctx_s *reply) { GError *e = NULL; gchar buf[64]; TRACE_FILTER(); EXTRACT_OPT(NAME_MSGKEY_DELETE_MARKER); return FILTER_OK; } int meta2_filter_extract_header_optional_bypass_governance( struct gridd_filter_ctx_s *ctx, struct gridd_reply_ctx_s *reply) { GError *e = NULL; gchar buf[64]; TRACE_FILTER(); EXTRACT_OPT(NAME_MSGKEY_BYPASS_GOVERNANCE); return FILTER_OK; } int meta2_filter_extract_header_optional_overwrite(struct gridd_filter_ctx_s *ctx, struct gridd_reply_ctx_s *reply) { GError *e = NULL; gchar buf[64]; TRACE_FILTER(); EXTRACT_OPT(NAME_MSGKEY_OVERWRITE); EXTRACT_OPT(NAME_MSGKEY_UPDATE); EXTRACT_OPT(NAME_MSGKEY_CHANGE_POLICY); EXTRACT_OPT(NAME_MSGKEY_RESTORE_DRAINED); return FILTER_OK; } int meta2_filter_extract_header_string_maxvers(struct gridd_filter_ctx_s *ctx, struct gridd_reply_ctx_s *reply) { GError *e = NULL; gchar buf[64]; TRACE_FILTER(); EXTRACT_OPT(NAME_MSGKEY_MAXVERS); return FILTER_OK; } int meta2_filter_extract_header_optional_repli_destinations(struct gridd_filter_ctx_s *ctx, struct gridd_reply_ctx_s *reply) { GError *e = NULL; gchar buf[64*1000]; TRACE_FILTER(); EXTRACT_OPT(NAME_MSGKEY_REPLICATION_DESTS); return FILTER_OK; } int meta2_filter_extract_admin(struct gridd_filter_ctx_s *ctx, struct gridd_reply_ctx_s *reply) { GError *e = NULL; gchar buf[1024]; TRACE_FILTER(); EXTRACT_OPT(NAME_MSGKEY_ADMIN_COMMAND); const char *admin = meta2_filter_ctx_get_param(ctx, NAME_MSGKEY_ADMIN_COMMAND); oio_ext_set_admin(oio_str_parse_bool(admin, FALSE)); return FILTER_OK; } int meta2_filter_extract_force_master(struct gridd_filter_ctx_s *ctx, struct gridd_reply_ctx_s *reply) { GError *e = NULL; gchar buf[64]; TRACE_FILTER(); EXTRACT_OPT(NAME_MSGKEY_FORCE_MASTER); const char *force_master = meta2_filter_ctx_get_param( ctx, NAME_MSGKEY_FORCE_MASTER); oio_ext_set_force_master(oio_str_parse_bool(force_master, FALSE)); return FILTER_OK; } int meta2_filter_extract_user_agent(struct gridd_filter_ctx_s *ctx, struct gridd_reply_ctx_s *reply) { GError *e = NULL; gchar buf[1024]; TRACE_FILTER(); EXTRACT_OPT(NAME_MSGKEY_USER_AGENT); const char *user_agent = meta2_filter_ctx_get_param(ctx, NAME_MSGKEY_USER_AGENT); oio_ext_set_user_agent(user_agent); return FILTER_OK; } int meta2_filter_extract_list_params(struct gridd_filter_ctx_s *ctx, struct gridd_reply_ctx_s *reply) { GError *e = NULL; gchar buf[1024]; TRACE_FILTER(); EXTRACT_OPT(NAME_MSGKEY_PREFIX); EXTRACT_OPT(NAME_MSGKEY_DELIMITER); EXTRACT_OPT(NAME_MSGKEY_MARKER); EXTRACT_OPT(NAME_MSGKEY_VERSIONMARKER); EXTRACT_OPT(NAME_MSGKEY_MARKER_END); EXTRACT_OPT(NAME_MSGKEY_MAX_KEYS); return FILTER_OK; } int meta2_filter_extract_limit(struct gridd_filter_ctx_s *ctx, struct gridd_reply_ctx_s *reply) { GError *e = NULL; gchar buf[1024]; TRACE_FILTER(); EXTRACT_OPT(NAME_MSGKEY_LIMIT); return FILTER_OK; } int meta2_filter_extract_force_versioning(struct gridd_filter_ctx_s *ctx, struct gridd_reply_ctx_s *reply) { GError *e = NULL; gchar buf[1024]; TRACE_FILTER(); EXTRACT_STRING(NAME_MSGKEY_FORCE_VERSIONING, TRUE); /* TODO(mbo) we should validate value */ const char *force_versioning = meta2_filter_ctx_get_param( ctx, NAME_MSGKEY_FORCE_VERSIONING); oio_ext_set_force_versioning(force_versioning); return FILTER_OK; } int meta2_filter_extract_region(struct gridd_filter_ctx_s *ctx, struct gridd_reply_ctx_s *reply) { GError *e = NULL; gchar buf[64]; EXTRACT_OPT(NAME_MSGKEY_REGION); return FILTER_OK; } int meta2_filter_extract_simulate_versioning(struct gridd_filter_ctx_s *ctx, struct gridd_reply_ctx_s *reply) { GError *e = NULL; gchar buf[1024]; TRACE_FILTER(); EXTRACT_OPT(NAME_MSGKEY_SIM_VER); const char *simulate_versioning = meta2_filter_ctx_get_param( ctx, NAME_MSGKEY_SIM_VER); oio_ext_set_simulate_versioning( oio_str_parse_bool(simulate_versioning, FALSE)); return FILTER_OK; } int meta2_filter_extract_find_shards_params(struct gridd_filter_ctx_s *ctx, struct gridd_reply_ctx_s *reply) { GError *e = NULL; gchar buf[1024]; TRACE_FILTER(); EXTRACT_OPT(NAME_MSGKEY_SHARDING_STRATEGY); return FILTER_OK; } int meta2_filter_extract_prepare_shard_params(struct gridd_filter_ctx_s *ctx, struct gridd_reply_ctx_s *reply) { GError *e = NULL; gchar buf[1024]; TRACE_FILTER(); EXTRACT_OPT(NAME_MSGKEY_SHARDING_ACTION); return FILTER_OK; } int meta2_filter_extract_sharding_info(struct gridd_filter_ctx_s *ctx, struct gridd_reply_ctx_s *reply) { GError *e = NULL; gchar buf[1024]; TRACE_FILTER(); EXTRACT_OPT(NAME_MSGKEY_SHARD_COMMAND); const char *is_shard = meta2_filter_ctx_get_param(ctx, NAME_MSGKEY_SHARD_COMMAND); oio_ext_set_is_shard_redirection(oio_str_parse_bool(is_shard, FALSE)); if (oio_ext_is_shard_redirection()) { GPtrArray *tmp = g_ptr_array_new(); gchar **names = metautils_message_get_field_names(reply->request); for (gchar **n = names; names && *n; ++n) { if (!g_str_has_prefix(*n, NAME_MSGKEY_PREFIX_SHARED_PROPERTY)) continue; gchar *value = metautils_message_extract_string_copy( reply->request, *n); if (value && *value == ' ') { g_ptr_array_add(tmp, g_strdup( (*n) + sizeof(NAME_MSGKEY_PREFIX_SHARED_PROPERTY) - 1)); g_ptr_array_add(tmp, g_strdup(value+1)); } g_free(value); } g_strfreev(names); oio_ext_set_shared_properties( (gchar**) metautils_gpa_to_array(tmp, TRUE)); } return FILTER_OK; }
98752b1ed4929b639334a29ede85cd268c8c35e0
21c92afbd7fd022a206fb31294c523aebb770104
/SuiteSparse/UMFPACK/Source/umf_kernel_wrapup.c
cf8eec2382c8f7188f587379c855e0792e5eeb21
[ "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-unknown-license-reference", "GPL-2.0-or-later", "GPL-3.0-only", "LGPL-2.1-or-later", "LGPL-2.0-or-later", "GPL-1.0-or-later", "LicenseRef-scancode-other-copyleft", "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
permissive
jlblancoc/suitesparse-metis-for-windows
70e6bcab2b525afb41758d61f823efa0618f67cf
5ee2eb4bc7bfd6d27af2f7fb027b1545cfc0fa3f
refs/heads/master
2023-08-30T21:15:39.624300
2023-03-09T10:16:48
2023-03-09T10:16:48
16,236,582
423
251
BSD-3-Clause
2023-03-09T10:18:08
2014-01-25T18:06:21
C
UTF-8
C
false
false
12,441
c
umf_kernel_wrapup.c
/* ========================================================================== */ /* === UMF_kernel_wrapup ==================================================== */ /* ========================================================================== */ /* -------------------------------------------------------------------------- */ /* Copyright (c) 2005-2012 by Timothy A. Davis, http://www.suitesparse.com. */ /* All Rights Reserved. See ../Doc/License.txt for License. */ /* -------------------------------------------------------------------------- */ /* The matrix is factorized. Finish the LU data structure. */ #include "umf_internal.h" #include "umf_kernel_wrapup.h" GLOBAL void UMF_kernel_wrapup ( NumericType *Numeric, SymbolicType *Symbolic, WorkType *Work ) { /* ---------------------------------------------------------------------- */ /* local variables */ /* ---------------------------------------------------------------------- */ Entry pivot_value ; double d ; Entry *D ; Int i, k, col, row, llen, ulen, *ip, *Rperm, *Cperm, *Lilen, npiv, lp, *Uilen, *Lip, *Uip, *Cperm_init, up, pivrow, pivcol, *Lpos, *Upos, *Wr, *Wc, *Wp, *Frpos, *Fcpos, *Row_degree, *Col_degree, *Rperm_init, n_row, n_col, n_inner, zero_pivot, nan_pivot, n1 ; #ifndef NDEBUG UMF_dump_matrix (Numeric, Work, FALSE) ; #endif DEBUG0 (("Kernel complete, Starting Kernel wrapup\n")) ; n_row = Symbolic->n_row ; n_col = Symbolic->n_col ; n_inner = MIN (n_row, n_col) ; Rperm = Numeric->Rperm ; Cperm = Numeric->Cperm ; Lilen = Numeric->Lilen ; Uilen = Numeric->Uilen ; Upos = Numeric->Upos ; Lpos = Numeric->Lpos ; Lip = Numeric->Lip ; Uip = Numeric->Uip ; D = Numeric->D ; npiv = Work->npiv ; Numeric->npiv = npiv ; Numeric->ulen = Work->ulen ; ASSERT (n_row == Numeric->n_row) ; ASSERT (n_col == Symbolic->n_col) ; DEBUG0 (("Wrap-up: npiv "ID" ulen "ID"\n", npiv, Numeric->ulen)) ; ASSERT (npiv <= n_inner) ; /* this will be nonzero only if matrix is singular or rectangular */ ASSERT (IMPLIES (npiv == n_col, Work->ulen == 0)) ; /* ---------------------------------------------------------------------- */ /* find the smallest and largest entries in D */ /* ---------------------------------------------------------------------- */ for (k = 0 ; k < npiv ; k++) { pivot_value = D [k] ; ABS (d, pivot_value) ; zero_pivot = SCALAR_IS_ZERO (d) ; nan_pivot = SCALAR_IS_NAN (d) ; if (!zero_pivot) { /* the pivot is nonzero, but might be Inf or NaN */ Numeric->nnzpiv++ ; } if (k == 0) { Numeric->min_udiag = d ; Numeric->max_udiag = d ; } else { /* min (abs (diag (U))) behaves as follows: If any entry is zero, then the result is zero (regardless of the presence of NaN's). Otherwise, if any entry is NaN, then the result is NaN. Otherwise, the result is the smallest absolute value on the diagonal of U. */ if (SCALAR_IS_NONZERO (Numeric->min_udiag)) { if (zero_pivot || nan_pivot) { Numeric->min_udiag = d ; } else if (!SCALAR_IS_NAN (Numeric->min_udiag)) { /* d and min_udiag are both non-NaN */ Numeric->min_udiag = MIN (Numeric->min_udiag, d) ; } } /* max (abs (diag (U))) behaves as follows: If any entry is NaN then the result is NaN. Otherise, the result is the largest absolute value on the diagonal of U. */ if (nan_pivot) { Numeric->max_udiag = d ; } else if (!SCALAR_IS_NAN (Numeric->max_udiag)) { /* d and max_udiag are both non-NaN */ Numeric->max_udiag = MAX (Numeric->max_udiag, d) ; } } } /* ---------------------------------------------------------------------- */ /* check if matrix is singular or rectangular */ /* ---------------------------------------------------------------------- */ Col_degree = Cperm ; /* for NON_PIVOTAL_COL macro */ Row_degree = Rperm ; /* for NON_PIVOTAL_ROW macro */ if (npiv < n_row) { /* finalize the row permutation */ k = npiv ; DEBUGm3 (("Singular pivot rows "ID" to "ID"\n", k, n_row-1)) ; for (row = 0 ; row < n_row ; row++) { if (NON_PIVOTAL_ROW (row)) { Rperm [row] = ONES_COMPLEMENT (k) ; DEBUGm3 (("Singular row "ID" is k: "ID" pivot row\n", row, k)) ; ASSERT (!NON_PIVOTAL_ROW (row)) ; Lpos [row] = EMPTY ; Uip [row] = EMPTY ; Uilen [row] = 0 ; k++ ; } } ASSERT (k == n_row) ; } if (npiv < n_col) { /* finalize the col permutation */ k = npiv ; DEBUGm3 (("Singular pivot cols "ID" to "ID"\n", k, n_col-1)) ; for (col = 0 ; col < n_col ; col++) { if (NON_PIVOTAL_COL (col)) { Cperm [col] = ONES_COMPLEMENT (k) ; DEBUGm3 (("Singular col "ID" is k: "ID" pivot row\n", col, k)) ; ASSERT (!NON_PIVOTAL_COL (col)) ; Upos [col] = EMPTY ; Lip [col] = EMPTY ; Lilen [col] = 0 ; k++ ; } } ASSERT (k == n_col) ; } if (npiv < n_inner) { /* finalize the diagonal of U */ DEBUGm3 (("Diag of U is zero, "ID" to "ID"\n", npiv, n_inner-1)) ; for (k = npiv ; k < n_inner ; k++) { CLEAR (D [k]) ; } } /* save the pattern of the last row of U */ if (Numeric->ulen > 0) { DEBUGm3 (("Last row of U is not empty\n")) ; Numeric->Upattern = Work->Upattern ; Work->Upattern = (Int *) NULL ; } DEBUG2 (("Nnzpiv: "ID" npiv "ID"\n", Numeric->nnzpiv, npiv)) ; ASSERT (Numeric->nnzpiv <= npiv) ; if (Numeric->nnzpiv < n_inner && !SCALAR_IS_NAN (Numeric->min_udiag)) { /* the rest of the diagonal is zero, so min_udiag becomes 0, * unless it is already NaN. */ Numeric->min_udiag = 0.0 ; } /* ---------------------------------------------------------------------- */ /* size n_row, n_col workspaces that can be used here: */ /* ---------------------------------------------------------------------- */ Frpos = Work->Frpos ; /* of size n_row+1 */ Fcpos = Work->Fcpos ; /* of size n_col+1 */ Wp = Work->Wp ; /* of size MAX(n_row,n_col)+1 */ /* Work->Upattern ; cannot be used (in Numeric) */ Wr = Work->Lpattern ; /* of size n_row+1 */ Wc = Work->Wrp ; /* of size n_col+1 or bigger */ /* ---------------------------------------------------------------------- */ /* construct Rperm from inverse permutations */ /* ---------------------------------------------------------------------- */ /* use Frpos for temporary copy of inverse row permutation [ */ for (pivrow = 0 ; pivrow < n_row ; pivrow++) { k = Rperm [pivrow] ; ASSERT (k < 0) ; k = ONES_COMPLEMENT (k) ; ASSERT (k >= 0 && k < n_row) ; Wp [k] = pivrow ; Frpos [pivrow] = k ; } for (k = 0 ; k < n_row ; k++) { Rperm [k] = Wp [k] ; } /* ---------------------------------------------------------------------- */ /* construct Cperm from inverse permutation */ /* ---------------------------------------------------------------------- */ /* use Fcpos for temporary copy of inverse column permutation [ */ for (pivcol = 0 ; pivcol < n_col ; pivcol++) { k = Cperm [pivcol] ; ASSERT (k < 0) ; k = ONES_COMPLEMENT (k) ; ASSERT (k >= 0 && k < n_col) ; Wp [k] = pivcol ; /* save a copy of the inverse column permutation in Fcpos */ Fcpos [pivcol] = k ; } for (k = 0 ; k < n_col ; k++) { Cperm [k] = Wp [k] ; } #ifndef NDEBUG for (k = 0 ; k < n_col ; k++) { col = Cperm [k] ; ASSERT (col >= 0 && col < n_col) ; ASSERT (Fcpos [col] == k) ; /* col is the kth pivot */ } for (k = 0 ; k < n_row ; k++) { row = Rperm [k] ; ASSERT (row >= 0 && row < n_row) ; ASSERT (Frpos [row] == k) ; /* row is the kth pivot */ } #endif #ifndef NDEBUG UMF_dump_lu (Numeric) ; #endif /* ---------------------------------------------------------------------- */ /* permute Lpos, Upos, Lilen, Lip, Uilen, and Uip */ /* ---------------------------------------------------------------------- */ for (k = 0 ; k < npiv ; k++) { pivrow = Rperm [k] ; Wr [k] = Uilen [pivrow] ; Wp [k] = Uip [pivrow] ; } for (k = 0 ; k < npiv ; k++) { Uilen [k] = Wr [k] ; Uip [k] = Wp [k] ; } for (k = 0 ; k < npiv ; k++) { pivrow = Rperm [k] ; Wp [k] = Lpos [pivrow] ; } for (k = 0 ; k < npiv ; k++) { Lpos [k] = Wp [k] ; } for (k = 0 ; k < npiv ; k++) { pivcol = Cperm [k] ; Wc [k] = Lilen [pivcol] ; Wp [k] = Lip [pivcol] ; } for (k = 0 ; k < npiv ; k++) { Lilen [k] = Wc [k] ; Lip [k] = Wp [k] ; } for (k = 0 ; k < npiv ; k++) { pivcol = Cperm [k] ; Wp [k] = Upos [pivcol] ; } for (k = 0 ; k < npiv ; k++) { Upos [k] = Wp [k] ; } /* ---------------------------------------------------------------------- */ /* terminate the last Uchain and last Lchain */ /* ---------------------------------------------------------------------- */ Upos [npiv] = EMPTY ; Lpos [npiv] = EMPTY ; Uip [npiv] = EMPTY ; Lip [npiv] = EMPTY ; Uilen [npiv] = 0 ; Lilen [npiv] = 0 ; /* ---------------------------------------------------------------------- */ /* convert U to the new pivot order */ /* ---------------------------------------------------------------------- */ n1 = Symbolic->n1 ; for (k = 0 ; k < n1 ; k++) { /* this is a singleton row of U */ ulen = Uilen [k] ; DEBUG4 (("K "ID" New U. ulen "ID" Singleton 1\n", k, ulen)) ; if (ulen > 0) { up = Uip [k] ; ip = (Int *) (Numeric->Memory + up) ; for (i = 0 ; i < ulen ; i++) { col = *ip ; DEBUG4 ((" old col "ID" new col "ID"\n", col, Fcpos [col])); ASSERT (col >= 0 && col < n_col) ; *ip++ = Fcpos [col] ; } } } for (k = n1 ; k < npiv ; k++) { up = Uip [k] ; if (up < 0) { /* this is the start of a new Uchain (with a pattern) */ ulen = Uilen [k] ; DEBUG4 (("K "ID" New U. ulen "ID" End_Uchain 1\n", k, ulen)) ; if (ulen > 0) { up = -up ; ip = (Int *) (Numeric->Memory + up) ; for (i = 0 ; i < ulen ; i++) { col = *ip ; DEBUG4 ((" old col "ID" new col "ID"\n", col, Fcpos [col])); ASSERT (col >= 0 && col < n_col) ; *ip++ = Fcpos [col] ; } } } } ulen = Numeric->ulen ; if (ulen > 0) { /* convert last pivot row of U to the new pivot order */ DEBUG4 (("K "ID" (last)\n", k)) ; for (i = 0 ; i < ulen ; i++) { col = Numeric->Upattern [i] ; DEBUG4 ((" old col "ID" new col "ID"\n", col, Fcpos [col])) ; Numeric->Upattern [i] = Fcpos [col] ; } } /* Fcpos no longer needed ] */ /* ---------------------------------------------------------------------- */ /* convert L to the new pivot order */ /* ---------------------------------------------------------------------- */ for (k = 0 ; k < n1 ; k++) { llen = Lilen [k] ; DEBUG4 (("K "ID" New L. llen "ID" Singleton col\n", k, llen)) ; if (llen > 0) { lp = Lip [k] ; ip = (Int *) (Numeric->Memory + lp) ; for (i = 0 ; i < llen ; i++) { row = *ip ; DEBUG4 ((" old row "ID" new row "ID"\n", row, Frpos [row])) ; ASSERT (row >= 0 && row < n_row) ; *ip++ = Frpos [row] ; } } } for (k = n1 ; k < npiv ; k++) { llen = Lilen [k] ; DEBUG4 (("K "ID" New L. llen "ID" \n", k, llen)) ; if (llen > 0) { lp = Lip [k] ; if (lp < 0) { /* this starts a new Lchain */ lp = -lp ; } ip = (Int *) (Numeric->Memory + lp) ; for (i = 0 ; i < llen ; i++) { row = *ip ; DEBUG4 ((" old row "ID" new row "ID"\n", row, Frpos [row])) ; ASSERT (row >= 0 && row < n_row) ; *ip++ = Frpos [row] ; } } } /* Frpos no longer needed ] */ /* ---------------------------------------------------------------------- */ /* combine symbolic and numeric permutations */ /* ---------------------------------------------------------------------- */ Cperm_init = Symbolic->Cperm_init ; Rperm_init = Symbolic->Rperm_init ; for (k = 0 ; k < n_row ; k++) { Rperm [k] = Rperm_init [Rperm [k]] ; } for (k = 0 ; k < n_col ; k++) { Cperm [k] = Cperm_init [Cperm [k]] ; } /* Work object will be freed immediately upon return (to UMF_kernel */ /* and then to UMFPACK_numeric). */ }
47927dd8b5ff80e5afd218e46c0ef4dba465cb6a
62c8d47803da82bc6b7a276e0c54796601c66276
/util/disasm/hash.h
f2f1f66053918702efd3328703c30ec6303ec281
[ "MIT", "GPL-2.0-or-later", "GPL-1.0-or-later", "LicenseRef-scancode-unknown-license-reference" ]
permissive
autc04/executor
a01d1c5081251a331067596141422568159a7596
ada40683c14d9dfb2a660e52378e9864e0d51357
refs/heads/master
2023-07-21T14:33:48.612380
2023-05-07T21:33:31
2023-05-07T21:33:31
106,850,181
125
9
MIT
2023-07-07T14:12:07
2017-10-13T16:48:51
C++
UTF-8
C
false
false
609
h
hash.h
#ifndef _HASH_H_ #define _HASH_H_ #define LOG2_NUM_HASH_BUCKETS 11 #define NUM_HASH_BUCKETS (1UL << LOG2_NUM_HASH_BUCKETS) typedef struct _hash_elt_t { struct _hash_elt_t *next; char *key; char *value; } hash_elt_t; typedef struct { hash_elt_t *bucket[NUM_HASH_BUCKETS]; } hash_table_t; extern hash_table_t *hash_new (void); extern void hash_free (hash_table_t *h); extern const char *hash_lookup (hash_table_t *h, const char *key); extern void hash_insert (hash_table_t *h, const char *key, const char *value); extern void hash_remove (hash_table_t *h, const char *key); #endif /* !_HASH_H_ */
1b9191e5143e184286838fb5ee440fb53100e4c4
c89188712c49d11083abade8eed26e1990d72702
/common/mqtt_defconfig.h
a7a842ca3d6fcaf99a34eee119403c9af36480c0
[ "Apache-2.0", "LicenseRef-scancode-free-unknown" ]
permissive
jiejieTop/mqttclient
918d971b813563398cd2da643356c29ff03c38d9
59c8bbacad06dafee1625a9fa9f7e61764802dce
refs/heads/master
2023-05-14T06:05:23.431889
2023-04-10T01:23:36
2023-04-10T01:23:36
227,366,515
562
233
Apache-2.0
2023-04-25T14:39:37
2019-12-11T12:58:08
C
UTF-8
C
false
false
2,695
h
mqtt_defconfig.h
/* * @Author : jiejie * @GitHub : https://github.com/jiejieTop * @Date : 2021-02-26 12:00:24 * @LastEditors : jiejie * @LastEditTime : 2022-06-15 23:22:10 * @FilePath : /mqttclient/mqttclient/mqtt_defconfig.h * Copyright (c) 2022 jiejie, All Rights Reserved. Please keep the author information and source code according to the license. */ /* * @Author: jiejie * @Github: https://github.com/jiejieTop * @Date: 2020-02-25 03:36:09 * @LastEditTime: 2020-06-17 19:59:41 * @Description: the code belongs to jiejie, please keep the author information and source code according to the license. */ #ifndef _DEFCONFIG_H_ #define _DEFCONFIG_H_ #include "mqtt_config.h" #ifndef MQTT_LOG_LEVEL #define MQTT_LOG_LEVEL MQTT_LOG_DEBUG_LEVEL //MQTT_LOG_WARN_LEVEL MQTT_LOG_DEBUG_LEVEL #endif // !MQTT_LOG_LEVEL #ifndef MQTT_MAX_PACKET_ID #define MQTT_MAX_PACKET_ID (0xFFFF - 1) #endif // !MQTT_MAX_PACKET_ID #ifndef MQTT_TOPIC_LEN_MAX #define MQTT_TOPIC_LEN_MAX 64 #endif // !MQTT_TOPIC_LEN_MAX #ifndef MQTT_ACK_HANDLER_NUM_MAX #define MQTT_ACK_HANDLER_NUM_MAX 64 #endif // !MQTT_ACK_HANDLER_NUM_MAX #ifndef MQTT_DEFAULT_BUF_SIZE #define MQTT_DEFAULT_BUF_SIZE 1024 #endif // !MQTT_DEFAULT_BUF_SIZE #ifndef MQTT_DEFAULT_CMD_TIMEOUT #define MQTT_DEFAULT_CMD_TIMEOUT 4000 #endif // !MQTT_DEFAULT_CMD_TIMEOUT #ifndef MQTT_MAX_CMD_TIMEOUT #define MQTT_MAX_CMD_TIMEOUT 20000 #endif // !MQTT_MAX_CMD_TIMEOUT #ifndef MQTT_MIN_CMD_TIMEOUT #define MQTT_MIN_CMD_TIMEOUT 1000 #endif // !MQTT_MIN_CMD_TIMEOUT #ifndef MQTT_KEEP_ALIVE_INTERVAL #define MQTT_KEEP_ALIVE_INTERVAL 100 // unit: second #endif // !MQTT_KEEP_ALIVE_INTERVAL #ifndef MQTT_VERSION #define MQTT_VERSION 4 // 4 is mqtt 3.1.1 #endif // !MQTT_VERSION #ifndef MQTT_RECONNECT_DEFAULT_DURATION #define MQTT_RECONNECT_DEFAULT_DURATION 1000 #endif // !MQTT_RECONNECT_DEFAULT_DURATION #ifndef MQTT_THREAD_STACK_SIZE #define MQTT_THREAD_STACK_SIZE 4096 #endif // !MQTT_THREAD_STACK_SIZE #ifndef MQTT_THREAD_PRIO #define MQTT_THREAD_PRIO 5 #endif // !MQTT_THREAD_PRIO #ifndef MQTT_THREAD_TICK #define MQTT_THREAD_TICK 50 #endif // !MQTT_THREAD_TICK #ifndef MQTT_NETWORK_TYPE_NO_TLS #ifndef MQTT_TLS_HANDSHAKE_TIMEOUT #define MQTT_TLS_HANDSHAKE_TIMEOUT (5 * 1000) #endif // !MQTT_TLS_HANDSHAKE_TIMEOUT #endif /* MQTT_NETWORK_TYPE_NO_TLS */ #endif /* _DEFCONFIG_H_ */
21b83ffc8a9a7eafd9b096871742a663bb6d88f6
d3c83ae2d5a23fadcde502bd9fc9682f054d68c1
/src/compiler/flatcc.c
3111b4c2cb43cb8108eeb2ae7f851e6d7166a11b
[ "BSD-3-Clause", "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
dvidelabs/flatcc
44cf9b46341fd49259f8f64ce6cfc7b95fe9da83
eb5228f76d395bffe31a33398ff73e60dfba5914
refs/heads/master
2023-08-25T04:26:36.611078
2023-08-15T15:17:59
2023-08-15T15:17:59
45,867,575
643
204
Apache-2.0
2023-05-30T06:15:06
2015-11-09T21:21:58
C
UTF-8
C
false
false
16,870
c
flatcc.c
#include <assert.h> #include "config.h" #include "parser.h" #include "semantics.h" #include "fileio.h" #include "codegen.h" #include "flatcc/flatcc.h" #define checkfree(s) if (s) { free(s); s = 0; } void flatcc_init_options(flatcc_options_t *opts) { memset(opts, 0, sizeof(*opts)); opts->max_schema_size = FLATCC_MAX_SCHEMA_SIZE; opts->max_include_depth = FLATCC_MAX_INCLUDE_DEPTH; opts->max_include_count = FLATCC_MAX_INCLUDE_COUNT; opts->allow_boolean_conversion = FLATCC_ALLOW_BOOLEAN_CONVERSION; opts->allow_enum_key = FLATCC_ALLOW_ENUM_KEY; opts->allow_enum_struct_field = FLATCC_ALLOW_ENUM_STRUCT_FIELD; opts->allow_multiple_key_fields = FLATCC_ALLOW_MULTIPLE_KEY_FIELDS; opts->allow_primary_key = FLATCC_ALLOW_PRIMARY_KEY; opts->allow_scan_for_all_fields = FLATCC_ALLOW_SCAN_FOR_ALL_FIELDS; opts->allow_string_key = FLATCC_ALLOW_STRING_KEY; opts->allow_struct_field_deprecate = FLATCC_ALLOW_STRUCT_FIELD_DEPRECATE; opts->allow_struct_field_key = FLATCC_ALLOW_STRUCT_FIELD_KEY; opts->allow_struct_root = FLATCC_ALLOW_STRUCT_ROOT; opts->ascending_enum = FLATCC_ASCENDING_ENUM; opts->hide_later_enum = FLATCC_HIDE_LATER_ENUM; opts->hide_later_struct = FLATCC_HIDE_LATER_STRUCT; opts->offset_size = FLATCC_OFFSET_SIZE; opts->voffset_size = FLATCC_VOFFSET_SIZE; opts->utype_size = FLATCC_UTYPE_SIZE; opts->bool_size = FLATCC_BOOL_SIZE; opts->require_root_type = FLATCC_REQUIRE_ROOT_TYPE; opts->strict_enum_init = FLATCC_STRICT_ENUM_INIT; /* * Index 0 is table elem count, and index 1 is table size * so max count is reduced by 2, meaning field id's * must be between 0 and vt_max_count - 1. * Usually, the table is 16-bit, so FLATCC_VOFFSET_SIZE = 2. * Strange expression to avoid shift overflow on 64 bit size. */ opts->vt_max_count = ((1LL << (FLATCC_VOFFSET_SIZE * 8 - 1)) - 1) * 2; opts->default_schema_ext = FLATCC_DEFAULT_SCHEMA_EXT; opts->default_bin_schema_ext = FLATCC_DEFAULT_BIN_SCHEMA_EXT; opts->default_bin_ext = FLATCC_DEFAULT_BIN_EXT; opts->cgen_no_conflicts = FLATCC_CGEN_NO_CONFLICTS; opts->cgen_pad = FLATCC_CGEN_PAD; opts->cgen_sort = FLATCC_CGEN_SORT; opts->cgen_pragmas = FLATCC_CGEN_PRAGMAS; opts->cgen_common_reader = 0; opts->cgen_common_builder = 0; opts->cgen_reader = 0; opts->cgen_builder = 0; opts->cgen_json_parser = 0; opts->cgen_spacing = FLATCC_CGEN_SPACING; opts->bgen_bfbs = FLATCC_BGEN_BFBS; opts->bgen_qualify_names = FLATCC_BGEN_QUALIFY_NAMES; opts->bgen_length_prefix = FLATCC_BGEN_LENGTH_PREFIX; } flatcc_context_t flatcc_create_context(flatcc_options_t *opts, const char *name, flatcc_error_fun error_out, void *error_ctx) { fb_parser_t *P; if (!(P = malloc(sizeof(*P)))) { return 0; } if (fb_init_parser(P, opts, name, error_out, error_ctx, 0)) { free(P); return 0; } return P; } static flatcc_context_t __flatcc_create_child_context(flatcc_options_t *opts, const char *name, fb_parser_t *P_parent) { fb_parser_t *P; if (!(P = malloc(sizeof(*P)))) { return 0; } if (fb_init_parser(P, opts, name, P_parent->error_out, P_parent->error_ctx, P_parent->schema.root_schema)) { free(P); return 0; } return P; } /* TODO: handle include files via some sort of buffer read callback * and possible transfer file based parser to this logic. */ int flatcc_parse_buffer(flatcc_context_t ctx, const char *buf, size_t buflen) { fb_parser_t *P = ctx; /* Currently includes cannot be handled by buffers, so they should done. */ P->opts.disable_includes = 1; if ((size_t)buflen > P->opts.max_schema_size && P->opts.max_schema_size > 0) { fb_print_error(P, "input exceeds maximum allowed size\n"); return -1; } /* Add self to set of visible schema. */ ptr_set_insert_item(&P->schema.visible_schema, &P->schema, ht_keep); return fb_parse(P, buf, buflen, 0) || fb_build_schema(P) ? -1 : 0; } static void visit_dep(void *context, void *ptr) { fb_schema_t *parent = context; fb_schema_t *dep = ptr; ptr_set_insert_item(&parent->visible_schema, dep, ht_keep); } static void add_visible_schema(fb_schema_t *parent, fb_schema_t *dep) { ptr_set_visit(&dep->visible_schema, visit_dep, parent); } static int __parse_include_file(fb_parser_t *P_parent, const char *filename) { flatcc_context_t *ctx = 0; fb_parser_t *P = 0; fb_root_schema_t *rs; flatcc_options_t *opts = &P_parent->opts; fb_schema_t *dep; rs = P_parent->schema.root_schema; if (rs->include_depth >= opts->max_include_depth && opts->max_include_depth > 0) { fb_print_error(P_parent, "include nesting level too deep\n"); return -1; } if (rs->include_count >= opts->max_include_count && opts->max_include_count > 0) { fb_print_error(P_parent, "include count limit exceeded\n"); return -1; } if (!(ctx = __flatcc_create_child_context(opts, filename, P_parent))) { return -1; } P = (fb_parser_t *)ctx; /* Don't parse the same file twice, or any other file with same name. */ if ((dep = fb_schema_table_find_item(&rs->include_index, &P->schema))) { add_visible_schema(&P_parent->schema, dep); flatcc_destroy_context(ctx); return 0; } P->dependencies = P_parent->dependencies; P_parent->dependencies = P; P->referer_path = P_parent->path; /* Each parser has a root schema instance, but only the root parsers instance is used. */ rs->include_depth++; rs->include_count++; if (flatcc_parse_file(ctx, filename)) { return -1; } add_visible_schema(&P_parent->schema, &P->schema); return 0; } /* * The depends file format is a make rule: * * <outputfile> : <dep1-file> <dep2-file> ... * * like -MMD option for gcc/clang: * lib.o.d generated with content: * * lib.o : header1.h header2.h * * We use a file name <basename>.depends for schema <basename>.fbs with content: * * <basename>_reader.h : <included-schema-1> ... * * The .d extension could mean the D language and we don't have sensible * .o.d name because of multiple outputs, so .depends is better. * * (the above above is subject to the configuration of extensions). * * TODO: * perhaps we should optionally add a dependency to the common reader * and builder files when they are generated separately as they should in * concurrent builds. * * TODO: * 1. we should have a file for every output we produce (_builder.h * etc.) * 2. reader might not even be in the output, e.g. verifier only. * 3. multiple outputs doesn't work with ninja build 1.7.1, so just * use reader for now, and possible add an option for multiple * outputs later. * * http://stackoverflow.com/questions/11855386/using-g-with-mmd-in-makefile-to-automatically-generate-dependencies * https://groups.google.com/forum/#!topic/ninja-build/j-2RfBIOd_8 * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=47485 * * Spaces in gnu make: * https://www.cmcrossroads.com/article/gnu-make-meets-file-names-spaces-them * See comments on gnu make handling of spaces. * http://clang.llvm.org/doxygen/DependencyFile_8cpp_source.html */ static int __flatcc_gen_depends_file(fb_parser_t *P) { FILE *fp = 0; const char *outpath, *basename; const char *depfile, *deproot, *depext; const char *targetfile, *targetsuffix, *targetroot; char *path = 0, *deppath = 0, *tmppath = 0, *targetpath = 0; int ret = -1; /* * The dependencies list is only correct for root files as it is a * linear list. To deal with children, we would have to filter via * the visible schema hash table, but we don't really need that. */ assert(P->referer_path == 0); outpath = P->opts.outpath ? P->opts.outpath : ""; basename = P->schema.basename; targetfile = P->opts.gen_deptarget; /* The following is mostly considering build tools generating * a depfile as Ninja build would use it. It is a bit strict * on path variations and currenlty doesn't accept multiple * build products in a build rule (Ninja 1.7.1). * * Make depfile relative to cwd so the user can add output if * needed, otherwise it is not possible, or difficult, to use a path given * by a build tool, relative the cwd. If --depfile is not given, * then -d is given or we would not be here. In that case we add an * extension "<basename>.fbs.d" in the outpath. * * A general problem is that the outpath may be a build root dir or * a current subdir for a custom build rule while the dep file * content needs the same path every time, not just an equivalent * path. For dependencies, we can rely on the input schema path. * The input search paths may because confusion but we choose the * discovered path relative to cwd consistently for each schema file * encountered. * * The target file (<target>: <include1.fbs> <include2.fbs> ...) * is tricky because it is not unique - but we can chose <schema>_reader.h * or <schema>.bfbs prefixed with outpath. The user should choose an * outpath relative to cwd or an absolute path depending on what the * build system prefers. This may not be so easy in praxis, but what * can we do? * * It is important to note the default target and the default * depfile name is not just a convenience. Sometimes it is much * simpler to use this version over an explicit path, sometimes * perhaps not so much. */ if (P->opts.gen_depfile) { depfile = P->opts.gen_depfile; deproot = ""; depext = ""; } else { depfile = basename; deproot = outpath; depext = FLATCC_DEFAULT_DEP_EXT; } if (targetfile) { targetsuffix = ""; targetroot = ""; } else { targetsuffix = P->opts.bgen_bfbs ? FLATCC_DEFAULT_BIN_SCHEMA_EXT : FLATCC_DEFAULT_DEP_TARGET_SUFFIX; targetfile = basename; targetroot = outpath; } checkmem(path = fb_create_join_path(deproot, depfile, depext, 1)); checkmem(tmppath = fb_create_join_path(targetroot, targetfile, targetsuffix, 1)); /* Handle spaces in dependency file. */ checkmem((targetpath = fb_create_make_path(tmppath))); checkfree(tmppath); fp = fopen(path, "wb"); if (!fp) { fb_print_error(P, "could not open dependency file for output: %s\n", path); goto done; } fprintf(fp, "%s:", targetpath); /* Don't depend on root schema. */ P = P->dependencies; while (P) { checkmem((deppath = fb_create_make_path(P->path))); fprintf(fp, " %s", deppath); P = P->dependencies; checkfree(deppath); } fprintf(fp, "\n"); ret = 0; done: checkfree(path); checkfree(tmppath); checkfree(targetpath); checkfree(deppath); if (fp) { fclose(fp); } return ret; } int flatcc_parse_file(flatcc_context_t ctx, const char *filename) { fb_parser_t *P = ctx; size_t inpath_len, filename_len; char *buf, *path, *include_file; const char *inpath; size_t size; fb_name_t *inc; int i, ret, is_root; filename_len = strlen(filename); /* Don't parse the same file twice, or any other file with same basename. */ if (fb_schema_table_insert_item(&P->schema.root_schema->include_index, &P->schema, ht_keep)) { return 0; } buf = 0; path = 0; include_file = 0; ret = -1; is_root = !P->referer_path; /* * For root files, read file relative to working dir first. For * included files (`referer_path` set), first try include paths * in order, then path relative to including file. */ if (is_root) { if (!(buf = fb_read_file(filename, P->opts.max_schema_size, &size))) { if (size + P->schema.root_schema->total_source_size > P->opts.max_schema_size && P->opts.max_schema_size > 0) { fb_print_error(P, "input exceeds maximum allowed size\n"); goto done; } } else { checkmem((path = fb_copy_path(filename))); } } for (i = 0; !buf && i < P->opts.inpath_count; ++i) { inpath = P->opts.inpaths[i]; inpath_len = strlen(inpath); checkmem((path = fb_create_join_path_n(inpath, inpath_len, filename, filename_len, "", 1))); if (!(buf = fb_read_file(path, P->opts.max_schema_size, &size))) { free(path); path = 0; if (size > P->opts.max_schema_size && P->opts.max_schema_size > 0) { fb_print_error(P, "input exceeds maximum allowed size\n"); goto done; } } } if (!buf && !is_root) { inpath = P->referer_path; inpath_len = fb_find_basename(inpath, strlen(inpath)); checkmem((path = fb_create_join_path_n(inpath, inpath_len, filename, filename_len, "", 1))); if (!(buf = fb_read_file(path, P->opts.max_schema_size, &size))) { free(path); path = 0; if (size > P->opts.max_schema_size && P->opts.max_schema_size > 0) { fb_print_error(P, "input exceeds maximum allowed size\n"); goto done; } } } if (!buf) { fb_print_error(P, "error reading included schema file: %s\n", filename); goto done; } P->schema.root_schema->total_source_size += size; P->path = path; /* Parser owns path. */ path = 0; /* * Even if we do not have the recursive option set, we still * need to parse all include files to make sense of the current * file. */ if (!fb_parse(P, buf, size, 1)) { /* Parser owns buffer. */ buf = 0; inc = P->schema.includes; while (inc) { checkmem((include_file = fb_copy_path_n(inc->name.s.s, (size_t)inc->name.s.len))); if (__parse_include_file(P, include_file)) { goto done; } free(include_file); include_file = 0; inc = inc->link; } /* Add self to set of visible schema. */ ptr_set_insert_item(&P->schema.visible_schema, &P->schema, ht_keep); if (fb_build_schema(P)) { goto done; } /* * We choose to only generate optional .depends files for root level * files. These will contain all nested files regardless of * recursive file generation flags. */ if (P->opts.gen_dep && is_root) { if (__flatcc_gen_depends_file(P)) { goto done; } } ret = 0; } done: /* Parser owns buffer so don't free it here. */ checkfree(path); checkfree(include_file); return ret; } #if FLATCC_REFLECTION int flatcc_generate_binary_schema_to_buffer(flatcc_context_t ctx, void *buf, size_t bufsiz) { fb_parser_t *P = ctx; if (fb_codegen_bfbs_to_buffer(&P->opts, &P->schema, buf, &bufsiz)) { return (int)bufsiz; } return -1; } void *flatcc_generate_binary_schema(flatcc_context_t ctx, size_t *size) { fb_parser_t *P = ctx; return fb_codegen_bfbs_alloc_buffer(&P->opts, &P->schema, size); } #endif int flatcc_generate_files(flatcc_context_t ctx) { fb_parser_t *P = ctx, *P_leaf; fb_output_t *out, output; int ret = 0; out = &output; if (!P || P->failed) { return -1; } P_leaf = 0; while (P) { P->inverse_dependencies = P_leaf; P_leaf = P; P = P->dependencies; } P = ctx; #if FLATCC_REFLECTION if (P->opts.bgen_bfbs) { if (fb_codegen_bfbs_to_file(&P->opts, &P->schema)) { return -1; } } #endif if (fb_init_output_c(out, &P->opts)) { return -1; } /* This does not require a parse first. */ if (!P->opts.gen_append && (ret = fb_codegen_common_c(out))) { goto done; } /* If no file parsed - just common files if at all. */ if (!P->has_schema) { goto done; } if (!P->opts.cgen_recursive) { ret = fb_codegen_c(out, &P->schema); goto done; } /* Make sure stdout and outfile output is generated in the right order. */ P = P_leaf; while (!ret && P) { ret = P->failed || fb_codegen_c(out, &P->schema); P = P->inverse_dependencies; } done: fb_end_output_c(out); return ret; } void flatcc_destroy_context(flatcc_context_t ctx) { fb_parser_t *P = ctx, *dep = 0; while (P) { dep = P->dependencies; fb_clear_parser(P); free(P); P = dep; } }
5386e703abee44d4793acf44fd56ee9c85c80dcf
dae15b230f6a39e8451420b2dea61fb719f9ffdf
/include/ofpi_init.h
aa9043fae8f7604c65e0fcbfb1026ab8167bc9b0
[ "BSD-3-Clause", "GPL-1.0-or-later" ]
permissive
OpenFastPath/ofp
2b97bbd152fd877cb8b2125128d6826c0f4491dd
6b48500af9752c7d51a290390751988759a8256d
refs/heads/master
2023-05-25T15:21:17.682339
2023-05-10T07:14:01
2023-05-10T11:01:16
37,121,923
367
146
BSD-3-Clause
2023-09-13T14:19:24
2015-06-09T09:08:43
C
UTF-8
C
false
false
823
h
ofpi_init.h
/* Copyright (c) 2014, ENEA Software AB * Copyright (c) 2014, Nokia * All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #ifndef __OFPI_INIT_H__ #define __OFPI_INIT_H__ #include "api/ofp_init.h" #include <odp/helper/odph_api.h> #define SHM_NAME_GLOBAL_CONFIG "OfpGlobalConfigShMem" extern odp_pool_t ofp_packet_pool; extern odp_cpumask_t cpumask; int ofp_term_post_global(const char *pool_name); struct ofp_global_config_mem { odp_bool_t is_running ODP_ALIGNED_CACHE; #ifdef SP odph_thread_t nl_thread; odp_bool_t nl_thread_is_running; #endif /* SP */ odph_thread_t cli_thread; odp_bool_t cli_thread_is_running; ofp_global_param_t global_param; }; extern __thread ofp_global_param_t *global_param; struct ofp_global_config_mem *ofp_get_global_config(void); #endif /* __OFPI_INIT_H__ */
9156e3503a62a7e1473e3be1da5246cd2c4ae1fd
ea401c3e792a50364fe11f7cea0f35f99e8f4bde
/released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/private/tz_stack_objlabel.c
ab55734f64839540216c83fd8d5a7d2c31ee9734
[ "BSD-2-Clause", "MIT", "GPL-1.0-or-later", "LicenseRef-scancode-unknown-license-reference", "GPL-2.0-only" ]
permissive
Vaa3D/vaa3d_tools
edb696aa3b9b59acaf83d6d27c6ae0a14bf75fe9
e6974d5223ae70474efaa85e1253f5df1814fae8
refs/heads/master
2023-08-03T06:12:01.013752
2023-08-02T07:26:01
2023-08-02T07:26:01
50,527,925
107
86
MIT
2023-05-22T23:43:48
2016-01-27T18:19:17
C++
UTF-8
C
false
false
619
c
tz_stack_objlabel.c
/* private/tz_stack_objlabel.c * * 02-Jun-2008 Initial write: Ting Zhao */ #ifdef STACK_LABEL_OBJECT_RECOVER_CHORD static void stack_label_object_recover_chord(const IMatrix *chord, int seed) { int index = seed; int next = index; while (index >= 0) { next = chord->array[index]; chord->array[index] = -1; index = next; } } #endif #ifdef STACK_LABEL_OBJECT_BY_CHORD static void stack_label_object_by_chord(Stack *stack, const IMatrix *chord, int label, int seed) { int index = seed; while (index >= 0) { stack->array[index] = label; index = chord->array[index]; } } #endif
cad3e22c0f3abd7a7aaf6ba03df43301441d710d
f019a06a4aa9f88a1a091eb09861999a0d6389e4
/lib.h
bf6fffe60498c2565b4c46c15202df542a86c4cc
[ "Apache-2.0" ]
permissive
google/neper
17faefa6d171638ae6ab3b587cdda36e7b412588
8509d279655eb8770a234672ee1f064411d511e2
refs/heads/master
2023-09-05T16:28:45.786657
2023-05-18T01:42:53
2023-05-18T01:42:53
55,101,823
253
66
Apache-2.0
2023-05-18T01:42:54
2016-03-30T22:21:18
C
UTF-8
C
false
false
4,766
h
lib.h
/* * Copyright 2016 Google 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. */ #ifndef THIRD_PARTY_NEPER_LIB_H #define THIRD_PARTY_NEPER_LIB_H #include <stdbool.h> #include "countdown_cond.h" #include "percentiles.h" struct countdown_cond; struct callbacks { void *logger; /* Print in key=value format and keep track of the line number. * Not thread-safe. */ void (*print)(void *logger, const char *key, const char *value, ...) __attribute__((format(printf, 3, 4))); /* Use for undesired and unexpected events, that the program cannot * recover from. Use these whenever an event happens from which you * actually want all servers to die and dump a stack trace. */ void (*log_fatal)(void *logger, const char *file, int line, const char *function, const char *format, ...) __attribute__((format(printf, 5, 6))); /* Use for undesired and unexpected events that the program can recover * from. All ERRORs should be actionable - it should be appropriate to * file a bug whenever an ERROR occurs in production. */ void (*log_error)(void *logger, const char *file, int line, const char *function, const char *format, ...) __attribute__((format(printf, 5, 6))); /* Use for undesired but relatively expected events, which may indicate * a problem. For example, the server received a malformed query. */ void (*log_warn)(void *logger, const char *file, int line, const char *function, const char *format, ...) __attribute__((format(printf, 5, 6))); /* Use for state changes or other major events, or to aid debugging. */ void (*log_info)(void *logger, const char *file, int line, const char *function, const char *format, ...) __attribute__((format(printf, 5, 6))); /* Notify the logger to log to stderr. */ void (*logtostderr)(void *logger); }; struct options { int magic; int maxevents; int num_flows; int num_threads; int num_clients; int num_ports; int test_length; int buffer_size; int listen_backlog; int suicide_length; int recv_flags; int send_flags; int mark; int tcp_tx_delay; bool stime_use_proc; /* Enable use of /proc/stat values for stime */ bool ipv4; bool ipv6; bool client; bool debug; bool dry_run; bool pin_cpu; #ifndef NO_LIBNUMA bool pin_numa; #endif bool reuseaddr; bool logtostderr; bool nolog; bool nonblocking; bool freebind; bool tcp_fastopen; bool skip_rx_copy; bool zerocopy; bool time_wait; double interval; long long max_pacing_rate; const char *local_hosts; const char *host; const char *control_port; const char *port; int source_port; const char *all_samples; const char secret[32]; /* includes test name */ bool async_connect; /* tcp_stream */ bool enable_read; bool enable_write; bool enable_tcp_maerts; bool edge_trigger; unsigned long delay; /* ns, also used in tcp_rr */ const struct rate_conversion *throughput_opt; unsigned long long local_rate; /* updated in report */ unsigned long long remote_rate; /* updated in final msg */ /* tcp_rr */ int request_size; int response_size; struct percentiles percentiles; /* tcp_crr */ bool nostats; }; #ifdef __cplusplus extern "C" { #endif int tcp_stream(struct options *, struct callbacks *); int psp_stream(struct options *, struct callbacks *); int udp_stream(struct options *, struct callbacks *); int tcp_rr(struct options *, struct callbacks *); int udp_rr(struct options *, struct callbacks *); int psp_rr(struct options *, struct callbacks *); int tcp_crr(struct options *, struct callbacks *); int psp_crr(struct options *, struct callbacks *); #ifdef __cplusplus } #endif #endif
ddf8ce57995a122b504631b18560b91cb4561db0
2148c987c4b008453d5034ef33cbce886c241a3b
/firmware/bootloader_common/board.h
1c165328acecb3f7bc3d24654bbb50c83d4edd29
[ "Apache-2.0" ]
permissive
ytai/ioio
94cebdb9b97163be2fefb6d9a362d184b2d157c2
42f156cd676f14c6a503464bb33feb83353484f6
refs/heads/master
2023-08-30T23:36:00.823993
2023-08-24T05:00:03
2023-08-24T05:00:03
2,272,409
477
201
Apache-2.0
2023-09-11T03:26:53
2011-08-26T04:59:57
C
UTF-8
C
false
false
4,786
h
board.h
/* * Copyright 2011 Ytai Ben-Tsvi. All rights reserved. * * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED "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 ARSHAN POURSOHI 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. * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied. */ // Board implementation designators. #ifndef __BOARD_H__ #define __BOARD_H__ #define BOARD_SPRK_BASE 1000 // base number for SparkFun's boards #define BOARD_SPRK0010 BOARD_SPRK_BASE + 10 #define BOARD_SPRK0011 BOARD_SPRK_BASE + 11 #define BOARD_SPRK0012 BOARD_SPRK_BASE + 12 #define BOARD_SPRK0013 BOARD_SPRK_BASE + 13 #define BOARD_SPRK0014 BOARD_SPRK_BASE + 14 #define BOARD_SPRK0015 BOARD_SPRK_BASE + 15 #define BOARD_SPRK0016 BOARD_SPRK_BASE + 16 #define BOARD_SPRK0020 BOARD_SPRK_BASE + 20 #define BOARD_MINT_BASE 2000 // base number for IOIOMint boards #define BOARD_MINT0010 BOARD_MINT_BASE + 10 // add more boards here! #ifndef BOARD_VER #error Must define BOARD_VER #endif // sanity assert MCU #if BOARD_VER >= BOARD_SPRK0010 && BOARD_VER <= BOARD_SPRK0012 #ifndef __PIC24FJ128DA106__ #error Board and MCU mismatch - expecting PIC24FJ128DA106 #endif #elif BOARD_VER >= BOARD_SPRK0013 && BOARD_VER <= BOARD_SPRK0015 #ifndef __PIC24FJ128DA206__ #error Board and MCU mismatch - expecting PIC24FJ128DA206 #endif #elif BOARD_VER == BOARD_SPRK0016 #ifndef __PIC24FJ256DA206__ #error Board and MCU mismatch - expecting PIC24FJ256DA206 #endif #elif BOARD_VER == BOARD_SPRK0020 #ifndef __PIC24FJ256GB206__ #error Board and MCU mismatch - expecting PIC24FJ256GB206 #endif #elif BOARD_VER == BOARD_MINT0010 #ifndef __PIC24FJ256DA206__ #error Board and MCU mismatch - expecting PIC24FJ256DA206 #endif #else #error Unknown board #endif // hardware implementation versions // Each version is an 8-byte ASCII string, comprised of 4 bytes authrity // followed by 4 bytes revision. #if BOARD_VER == BOARD_SPRK0010 #define HW_IMPL_VER "SPRK0010" #elif BOARD_VER == BOARD_SPRK0011 #define HW_IMPL_VER "SPRK0011" #elif BOARD_VER == BOARD_SPRK0012 #define HW_IMPL_VER "SPRK0012" #elif BOARD_VER == BOARD_SPRK0013 #define HW_IMPL_VER "SPRK0013" #elif BOARD_VER == BOARD_SPRK0014 #define HW_IMPL_VER "SPRK0014" #elif BOARD_VER == BOARD_SPRK0015 #define HW_IMPL_VER "SPRK0015" #elif BOARD_VER == BOARD_SPRK0016 #define HW_IMPL_VER "SPRK0016" #elif BOARD_VER == BOARD_SPRK0020 #define HW_IMPL_VER "SPRK0020" #elif BOARD_VER == BOARD_MINT0010 #define HW_IMPL_VER "MINT0010" #else #error Unknown board #endif // This point to the beginning of the config word page, not writable by the app. #if defined(__PIC24FJ256DA206__) || defined(__PIC24FJ256GB206__) #define APP_PROGSPACE_END 0x2A800 #elif defined(__PIC24FJ128DA106__) || defined(__PIC24FJ128DA206__) #define APP_PROGSPACE_END 0x15400 #else #error Unknown MCU #endif // LED #if BOARD_VER >= BOARD_SPRK0010 && BOARD_VER < BOARD_SPRK0020 #define led_init() { _ODF3 = 1; _LATF3 = 1; _TRISF3 = 0;} #define led _LATF3 #define led_on() led = 0; #define led_off() led = 1; #define led_toggle() led = !led; #elif BOARD_VER >= BOARD_SPRK0020 #define led_init() { _ODC12 = 1; _LATC12 = 1; _TRISC12 = 0; } #define led_read() _RC12 #define led _LATC12 #define led_on() led = 0; #define led_off() led = 1; #define led_toggle() led = !led; #define pin1_pullup _CN17PUE #define pin1_read() _RF4 #else #error Unknown board #endif #endif // __BOARD_H__
dc54a6c43782e0412a1638dd9e4a0579b1ba650c
1c015973d4df0f85787c93c486ce7917c1f0af0d
/ext/agoo/domain.h
dc9d62f11ae28bbe5936596173afe3681719c789
[ "MIT" ]
permissive
ohler55/agoo
73d4a876d79a2cd075d88f02a9260bccb031d1dd
20b47d51c1ea4b2660031f7b4bf7b9ed88413b4f
refs/heads/develop
2023-08-31T23:12:22.615271
2023-07-10T19:21:33
2023-07-10T19:21:33
115,074,220
853
43
MIT
2023-09-04T05:38:49
2017-12-22T03:51:02
C
UTF-8
C
false
false
477
h
domain.h
// Copyright 2019 by Peter Ohler, All Rights Reserved #ifndef AGOO_DOMAIN_H #define AGOO_DOMAIN_H #include <stdbool.h> #include "err.h" extern bool agoo_domain_use(); extern int agoo_domain_add(agooErr err, const char *host, const char *path); extern int agoo_domain_add_regex(agooErr err, const char *host, const char *path); extern const char* agoo_domain_resolve(const char *host, char *buf, size_t blen); extern void agoo_domain_cleanup(); #endif // AGOO_DOMAIN_H
f5fd3573eb29a88175f168025196a218e2b7668a
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/drivers/media/usb/stkwebcam/stk-webcam.h
9bbfa3d9bfdda3a41a26ed05427f05aae3ba68c1
[ "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later", "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
3,867
h
stk-webcam.h
/* * stk-webcam.h : Driver for Syntek 1125 USB webcam controller * * Copyright (C) 2006 Nicolas VIVIEN * Copyright 2007-2008 Jaime Velasco Juan <jsagarribay@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * 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 */ #ifndef STKWEBCAM_H #define STKWEBCAM_H #include <linux/usb.h> #include <media/v4l2-device.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-common.h> #define DRIVER_VERSION "v0.0.1" #define DRIVER_VERSION_NUM 0x000001 #define MAX_ISO_BUFS 3 #define ISO_FRAMES_PER_DESC 16 #define ISO_MAX_FRAME_SIZE 3 * 1024 #define ISO_BUFFER_SIZE (ISO_FRAMES_PER_DESC * ISO_MAX_FRAME_SIZE) #define PREFIX "stkwebcam: " #define STK_INFO(str, args...) printk(KERN_INFO PREFIX str, ##args) #define STK_ERROR(str, args...) printk(KERN_ERR PREFIX str, ##args) #define STK_WARNING(str, args...) printk(KERN_WARNING PREFIX str, ##args) struct stk_iso_buf { void *data; int length; int read; struct urb *urb; }; /* Streaming IO buffers */ struct stk_sio_buffer { struct v4l2_buffer v4lbuf; char *buffer; int mapcount; struct stk_camera *dev; struct list_head list; }; enum stk_mode {MODE_VGA, MODE_SXGA, MODE_CIF, MODE_QVGA, MODE_QCIF}; struct stk_video { enum stk_mode mode; __u32 palette; int hflip; int vflip; }; enum stk_status { S_PRESENT = 1, S_INITIALISED = 2, S_MEMALLOCD = 4, S_STREAMING = 8, }; #define is_present(dev) ((dev)->status & S_PRESENT) #define is_initialised(dev) ((dev)->status & S_INITIALISED) #define is_streaming(dev) ((dev)->status & S_STREAMING) #define is_memallocd(dev) ((dev)->status & S_MEMALLOCD) #define set_present(dev) ((dev)->status = S_PRESENT) #define unset_present(dev) ((dev)->status &= \ ~(S_PRESENT|S_INITIALISED|S_STREAMING)) #define set_initialised(dev) ((dev)->status |= S_INITIALISED) #define unset_initialised(dev) ((dev)->status &= ~S_INITIALISED) #define set_memallocd(dev) ((dev)->status |= S_MEMALLOCD) #define unset_memallocd(dev) ((dev)->status &= ~S_MEMALLOCD) #define set_streaming(dev) ((dev)->status |= S_STREAMING) #define unset_streaming(dev) ((dev)->status &= ~S_STREAMING) struct regval { unsigned reg; unsigned val; }; struct stk_camera { struct v4l2_device v4l2_dev; struct v4l2_ctrl_handler hdl; struct video_device vdev; struct usb_device *udev; struct usb_interface *interface; int webcam_model; struct file *owner; struct mutex lock; int first_init; u8 isoc_ep; /* Not sure if this is right */ atomic_t urbs_used; struct stk_video vsettings; enum stk_status status; spinlock_t spinlock; wait_queue_head_t wait_frame; struct stk_iso_buf *isobufs; int frame_size; /* Streaming buffers */ int reading; unsigned int n_sbufs; struct stk_sio_buffer *sio_bufs; struct list_head sio_avail; struct list_head sio_full; unsigned sequence; }; #define vdev_to_camera(d) container_of(d, struct stk_camera, vdev) int stk_camera_write_reg(struct stk_camera *, u16, u8); int stk_camera_read_reg(struct stk_camera *, u16, int *); int stk_sensor_init(struct stk_camera *); int stk_sensor_configure(struct stk_camera *); int stk_sensor_sleep(struct stk_camera *dev); int stk_sensor_wakeup(struct stk_camera *dev); int stk_sensor_set_brightness(struct stk_camera *dev, int br); #endif
6224af7fb1674ab33336f515d02215b7224dc7ad
db229415713a206a848429321e19006b212d20d5
/test/arm/neon/hsub.c
03d6f8443f22bd6600ccf63b0a01dfd070563796
[ "MIT", "Apache-2.0", "LicenseRef-scancode-free-unknown" ]
permissive
simd-everywhere/simde
66dd029cbd0b3814b0377c72d953f223d38e7e53
4d55fc25bcfddc0e2f0c744448557a070dd310c9
refs/heads/master
2023-09-04T12:55:25.455223
2023-08-18T12:46:56
2023-08-18T14:53:06
86,497,800
1,570
173
MIT
2023-09-07T13:41:28
2017-03-28T19:14:32
C
UTF-8
C
false
false
49,098
c
hsub.c
#define SIMDE_TEST_ARM_NEON_INSN hsub #include "test-neon.h" #include "../../../simde/arm/neon/hsub.h" static int test_simde_vhsub_s8 (SIMDE_MUNIT_TEST_ARGS) { #if 1 static const struct { int8_t a[8]; int8_t b[8]; int8_t r[8]; } test_vec[] = { { { INT8_C( 82), INT8_C( 111), INT8_C( 70), -INT8_C( 31), -INT8_C( 51), -INT8_C( 22), INT8_C( 109), INT8_C( 85) }, { INT8_C( 126), INT8_C( 89), INT8_C( 38), INT8_C( 58), -INT8_C( 56), INT8_C( 28), INT8_C( 49), -INT8_C( 21) }, { -INT8_C( 22), INT8_C( 11), INT8_C( 16), -INT8_C( 45), INT8_C( 2), -INT8_C( 25), INT8_C( 30), INT8_C( 53) } }, { { -INT8_C( 63), -INT8_C( 107), -INT8_C( 109), -INT8_C( 28), INT8_C( 68), INT8_C( 51), INT8_C( 14), -INT8_C( 100) }, { INT8_C( 29), INT8_C( 41), -INT8_C( 53), -INT8_C( 109), -INT8_C( 102), INT8_C( 28), INT8_C( 36), -INT8_C( 19) }, { -INT8_C( 46), -INT8_C( 74), -INT8_C( 28), INT8_C( 40), INT8_C( 85), INT8_C( 11), -INT8_C( 11), -INT8_C( 41) } }, { { -INT8_C( 117), INT8_C( 106), -INT8_C( 50), INT8_C( 89), INT8_C( 84), INT8_C( 59), -INT8_C( 82), -INT8_C( 46) }, { -INT8_C( 107), -INT8_C( 44), INT8_C( 13), INT8_C( 93), -INT8_C( 16), INT8_C( 62), INT8_C( 72), -INT8_C( 78) }, { -INT8_C( 5), INT8_C( 75), -INT8_C( 32), -INT8_C( 2), INT8_C( 50), -INT8_C( 2), -INT8_C( 77), INT8_C( 16) } }, { { -INT8_C( 45), -INT8_C( 37), -INT8_C( 106), INT8_C( 23), INT8_C( 15), -INT8_C( 91), -INT8_C( 77), INT8_C( 44) }, { -INT8_C( 50), INT8_C( 126), -INT8_C( 64), INT8_C( 105), -INT8_C( 101), -INT8_C( 28), INT8_C( 86), INT8_C( 38) }, { INT8_C( 2), -INT8_C( 82), -INT8_C( 21), -INT8_C( 41), INT8_C( 58), -INT8_C( 32), -INT8_C( 82), INT8_C( 3) } }, { { INT8_C( 79), INT8_C( 36), INT8_MAX, -INT8_C( 93), INT8_C( 95), INT8_C( 46), INT8_C( 118), -INT8_C( 12) }, { INT8_C( 2), -INT8_C( 125), INT8_C( 81), -INT8_C( 13), -INT8_C( 63), -INT8_C( 102), -INT8_C( 91), -INT8_C( 107) }, { INT8_C( 38), INT8_C( 80), INT8_C( 23), -INT8_C( 40), INT8_C( 79), INT8_C( 74), INT8_C( 104), INT8_C( 47) } }, { { INT8_C( 117), INT8_C( 59), -INT8_C( 84), -INT8_C( 124), -INT8_C( 32), INT8_C( 96), -INT8_C( 79), -INT8_C( 81) }, { -INT8_C( 34), INT8_C( 113), INT8_C( 24), INT8_C( 121), INT8_C( 85), INT8_C( 110), -INT8_C( 96), -INT8_C( 92) }, { INT8_C( 75), -INT8_C( 27), -INT8_C( 54), -INT8_C( 123), -INT8_C( 59), -INT8_C( 7), INT8_C( 8), INT8_C( 5) } }, { { -INT8_C( 110), INT8_C( 31), INT8_C( 72), -INT8_C( 15), INT8_C( 77), -INT8_C( 66), -INT8_C( 26), INT8_C( 80) }, { INT8_C( 65), INT8_C( 55), INT8_C( 67), INT8_C( 2), -INT8_C( 47), -INT8_C( 24), -INT8_C( 105), INT8_C( 71) }, { -INT8_C( 88), -INT8_C( 12), INT8_C( 2), -INT8_C( 9), INT8_C( 62), -INT8_C( 21), INT8_C( 39), INT8_C( 4) } }, { { INT8_C( 35), INT8_C( 68), -INT8_C( 53), INT8_C( 4), -INT8_C( 92), INT8_C( 124), -INT8_C( 77), -INT8_C( 126) }, { -INT8_C( 19), -INT8_C( 53), -INT8_C( 4), INT8_C( 67), INT8_C( 57), -INT8_C( 100), -INT8_C( 25), -INT8_C( 53) }, { INT8_C( 27), INT8_C( 60), -INT8_C( 25), -INT8_C( 32), -INT8_C( 75), INT8_C( 112), -INT8_C( 26), -INT8_C( 37) } } }; for (size_t i = 0 ; i < (sizeof(test_vec) / sizeof(test_vec[0])) ; i++) { simde_int8x8_t a = simde_vld1_s8(test_vec[i].a); simde_int8x8_t b = simde_vld1_s8(test_vec[i].b); simde_int8x8_t r = simde_vhsub_s8(a, b); simde_test_arm_neon_assert_equal_i8x8(r, simde_vld1_s8(test_vec[i].r)); } return 0; #else fputc('\n', stdout); for (int i = 0 ; i < 8 ; i++) { simde_int8x8_t a = simde_test_arm_neon_random_i8x8(); simde_int8x8_t b = simde_test_arm_neon_random_i8x8(); simde_int8x8_t r = simde_vhsub_s8(a, b); simde_test_arm_neon_write_i8x8(2, a, SIMDE_TEST_VEC_POS_FIRST); simde_test_arm_neon_write_i8x8(2, b, SIMDE_TEST_VEC_POS_MIDDLE); simde_test_arm_neon_write_i8x8(2, r, SIMDE_TEST_VEC_POS_LAST); } return 1; #endif } static int test_simde_vhsub_s16 (SIMDE_MUNIT_TEST_ARGS) { #if 1 static const struct { int16_t a[4]; int16_t b[4]; int16_t r[4]; } test_vec[] = { { { INT16_C( 12219), INT16_C( 2492), -INT16_C( 23827), INT16_C( 11865) }, { -INT16_C( 25382), -INT16_C( 21711), -INT16_C( 14204), -INT16_C( 22542) }, { INT16_C( 18800), INT16_C( 12101), -INT16_C( 4812), INT16_C( 17203) } }, { { -INT16_C( 16884), -INT16_C( 20309), INT16_C( 24122), INT16_C( 10291) }, { INT16_C( 12073), INT16_C( 25195), INT16_C( 21195), -INT16_C( 31187) }, { -INT16_C( 14479), -INT16_C( 22752), INT16_C( 1463), INT16_C( 20739) } }, { { -INT16_C( 5502), INT16_C( 28559), -INT16_C( 6004), INT16_C( 26270) }, { -INT16_C( 12412), INT16_C( 2066), INT16_C( 1175), -INT16_C( 23376) }, { INT16_C( 3455), INT16_C( 13246), -INT16_C( 3590), INT16_C( 24823) } }, { { INT16_C( 23490), -INT16_C( 684), -INT16_C( 30790), -INT16_C( 7387) }, { -INT16_C( 28490), -INT16_C( 32442), INT16_C( 29666), INT16_C( 25608) }, { INT16_C( 25990), INT16_C( 15879), -INT16_C( 30228), -INT16_C( 16498) } }, { { -INT16_C( 26787), -INT16_C( 5420), INT16_C( 29312), INT16_C( 1104) }, { INT16_C( 25153), -INT16_C( 10227), -INT16_C( 17049), INT16_C( 10620) }, { -INT16_C( 25970), INT16_C( 2403), INT16_C( 23180), -INT16_C( 4758) } }, { { -INT16_C( 12008), -INT16_C( 11738), INT16_C( 19288), INT16_C( 4022) }, { -INT16_C( 805), -INT16_C( 16752), -INT16_C( 26513), -INT16_C( 13022) }, { -INT16_C( 5602), INT16_C( 2507), INT16_C( 22900), INT16_C( 8522) } }, { { -INT16_C( 2512), -INT16_C( 20297), INT16_C( 1896), -INT16_C( 22092) }, { -INT16_C( 16022), -INT16_C( 11902), -INT16_C( 386), -INT16_C( 26630) }, { INT16_C( 6755), -INT16_C( 4198), INT16_C( 1141), INT16_C( 2269) } }, { { INT16_C( 8655), INT16_C( 10345), INT16_C( 8044), INT16_C( 18487) }, { -INT16_C( 14565), -INT16_C( 29946), INT16_C( 10336), -INT16_C( 28584) }, { INT16_C( 11610), INT16_C( 20145), -INT16_C( 1146), INT16_C( 23535) } } }; for (size_t i = 0 ; i < (sizeof(test_vec) / sizeof(test_vec[0])) ; i++) { simde_int16x4_t a = simde_vld1_s16(test_vec[i].a); simde_int16x4_t b = simde_vld1_s16(test_vec[i].b); simde_int16x4_t r = simde_vhsub_s16(a, b); simde_test_arm_neon_assert_equal_i16x4(r, simde_vld1_s16(test_vec[i].r)); } return 0; #else fputc('\n', stdout); for (int i = 0 ; i < 8 ; i++) { simde_int16x4_t a = simde_test_arm_neon_random_i16x4(); simde_int16x4_t b = simde_test_arm_neon_random_i16x4(); simde_int16x4_t r = simde_vhsub_s16(a, b); simde_test_arm_neon_write_i16x4(2, a, SIMDE_TEST_VEC_POS_FIRST); simde_test_arm_neon_write_i16x4(2, b, SIMDE_TEST_VEC_POS_MIDDLE); simde_test_arm_neon_write_i16x4(2, r, SIMDE_TEST_VEC_POS_LAST); } return 1; #endif } #if !defined(TEST_SIMDE_VABD_NO_TEST_32) static int test_simde_vhsub_s32 (SIMDE_MUNIT_TEST_ARGS) { #if 1 static const struct { int32_t a[2]; int32_t b[2]; int32_t r[2]; } test_vec[] = { { { -INT32_C( 2025844961), -INT32_C( 2144209898) }, { INT32_C( 877769654), -INT32_C( 2117382991) }, { -INT32_C( 1451807308), -INT32_C( 13413454) } }, { { -INT32_C( 643222163), INT32_C( 1881268308) }, { INT32_C( 133900199), INT32_C( 1872188240) }, { -INT32_C( 388561181), INT32_C( 4540034) } }, { { INT32_C( 2029442914), -INT32_C( 2097600564) }, { -INT32_C( 1934210342), INT32_C( 51217046) }, { INT32_C( 1981826628), -INT32_C( 1074408805) } }, { { INT32_C( 199079607), INT32_C( 1031536278) }, { INT32_C( 1984263718), INT32_C( 736484553) }, { -INT32_C( 892592056), INT32_C( 147525862) } }, { { -INT32_C( 2136679500), -INT32_C( 587031293) }, { INT32_C( 2120857831), -INT32_C( 243173830) }, { -INT32_C( 2128768666), -INT32_C( 171928732) } }, { { -INT32_C( 1023582676), -INT32_C( 2097121187) }, { -INT32_C( 1191623185), -INT32_C( 706421215) }, { INT32_C( 84020254), -INT32_C( 695349986) } }, { { -INT32_C( 1135245127), INT32_C( 211441445) }, { INT32_C( 1250558736), -INT32_C( 1506014086) }, { -INT32_C( 1192901932), INT32_C( 858727765) } }, { { -INT32_C( 949405334), -INT32_C( 1605736015) }, { -INT32_C( 816233554), -INT32_C( 609927903) }, { -INT32_C( 66585890), -INT32_C( 497904056) } } }; for (size_t i = 0 ; i < (sizeof(test_vec) / sizeof(test_vec[0])) ; i++) { simde_int32x2_t a = simde_vld1_s32(test_vec[i].a); simde_int32x2_t b = simde_vld1_s32(test_vec[i].b); simde_int32x2_t r = simde_vhsub_s32(a, b); simde_test_arm_neon_assert_equal_i32x2(r, simde_vld1_s32(test_vec[i].r)); } return 0; #else fputc('\n', stdout); for (int i = 0 ; i < 8 ; i++) { simde_int32x2_t a = simde_test_arm_neon_random_i32x2(); simde_int32x2_t b = simde_test_arm_neon_random_i32x2(); simde_int32x2_t r = simde_vhsub_s32(a, b); simde_test_arm_neon_write_i32x2(2, a, SIMDE_TEST_VEC_POS_FIRST); simde_test_arm_neon_write_i32x2(2, b, SIMDE_TEST_VEC_POS_MIDDLE); simde_test_arm_neon_write_i32x2(2, r, SIMDE_TEST_VEC_POS_LAST); } return 1; #endif } #endif static int test_simde_vhsub_u8 (SIMDE_MUNIT_TEST_ARGS) { #if 1 static const struct { uint8_t a[8]; uint8_t b[8]; uint8_t r[8]; } test_vec[] = { { { UINT8_C(197), UINT8_C(250), UINT8_C(151), UINT8_C(234), UINT8_C( 82), UINT8_C( 49), UINT8_C(246), UINT8_C( 98) }, { UINT8_C( 53), UINT8_C(129), UINT8_C(172), UINT8_C(175), UINT8_C(141), UINT8_C(232), UINT8_C( 85), UINT8_C(247) }, { UINT8_C( 72), UINT8_C( 60), UINT8_C(245), UINT8_C( 29), UINT8_C(226), UINT8_C(164), UINT8_C( 80), UINT8_C(181) } }, { { UINT8_C( 33), UINT8_C(190), UINT8_C(191), UINT8_C(211), UINT8_C( 39), UINT8_C( 9), UINT8_C(115), UINT8_C(213) }, { UINT8_C( 77), UINT8_C(204), UINT8_C(165), UINT8_C(110), UINT8_C( 9), UINT8_C( 74), UINT8_C( 73), UINT8_C(206) }, { UINT8_C(234), UINT8_C(249), UINT8_C( 13), UINT8_C( 50), UINT8_C( 15), UINT8_C(223), UINT8_C( 21), UINT8_C( 3) } }, { { UINT8_C( 68), UINT8_C(225), UINT8_C(184), UINT8_C(150), UINT8_C( 18), UINT8_C(175), UINT8_C(248), UINT8_C( 71) }, { UINT8_C( 48), UINT8_C(165), UINT8_C(246), UINT8_C(189), UINT8_C(141), UINT8_C( 76), UINT8_C(180), UINT8_C(175) }, { UINT8_C( 10), UINT8_C( 30), UINT8_C(225), UINT8_C(236), UINT8_C(194), UINT8_C( 49), UINT8_C( 34), UINT8_C(204) } }, { { UINT8_C( 10), UINT8_C(115), UINT8_C(130), UINT8_C( 50), UINT8_C(125), UINT8_C(245), UINT8_C( 7), UINT8_C(202) }, { UINT8_C(194), UINT8_C(172), UINT8_C( 56), UINT8_C(203), UINT8_C(246), UINT8_C(130), UINT8_C(154), UINT8_C( 59) }, { UINT8_C(164), UINT8_C(227), UINT8_C( 37), UINT8_C(179), UINT8_C(195), UINT8_C( 57), UINT8_C(182), UINT8_C( 71) } }, { { UINT8_C( 99), UINT8_C( 82), UINT8_C(209), UINT8_C(117), UINT8_C( 1), UINT8_C(202), UINT8_C(189), UINT8_C( 49) }, { UINT8_C(111), UINT8_C(179), UINT8_C(238), UINT8_C(252), UINT8_MAX, UINT8_C(163), UINT8_C(171), UINT8_C( 10) }, { UINT8_C(250), UINT8_C(207), UINT8_C(241), UINT8_C(188), UINT8_C(129), UINT8_C( 19), UINT8_C( 9), UINT8_C( 19) } }, { { UINT8_C( 22), UINT8_C( 45), UINT8_C( 60), UINT8_C(147), UINT8_C( 35), UINT8_C( 67), UINT8_C( 93), UINT8_C(229) }, { UINT8_C(240), UINT8_C(150), UINT8_C(176), UINT8_C(230), UINT8_C( 24), UINT8_C( 74), UINT8_C( 33), UINT8_C(123) }, { UINT8_C(147), UINT8_C(203), UINT8_C(198), UINT8_C(214), UINT8_C( 5), UINT8_C(252), UINT8_C( 30), UINT8_C( 53) } }, { { UINT8_C(157), UINT8_C(243), UINT8_C(240), UINT8_C(158), UINT8_C(189), UINT8_C(173), UINT8_C(208), UINT8_C( 44) }, { UINT8_C( 97), UINT8_C(190), UINT8_C( 40), UINT8_C( 96), UINT8_C( 97), UINT8_C(212), UINT8_C(106), UINT8_C(120) }, { UINT8_C( 30), UINT8_C( 26), UINT8_C(100), UINT8_C( 31), UINT8_C( 46), UINT8_C(236), UINT8_C( 51), UINT8_C(218) } }, { { UINT8_C( 1), UINT8_C(166), UINT8_C( 11), UINT8_C( 36), UINT8_C(234), UINT8_C(105), UINT8_C( 9), UINT8_C(218) }, { UINT8_MAX, UINT8_C(186), UINT8_C(192), UINT8_C( 23), UINT8_C( 4), UINT8_C(226), UINT8_C(146), UINT8_C(161) }, { UINT8_C(129), UINT8_C(246), UINT8_C(165), UINT8_C( 6), UINT8_C(115), UINT8_C(195), UINT8_C(187), UINT8_C( 28) } } }; for (size_t i = 0 ; i < (sizeof(test_vec) / sizeof(test_vec[0])) ; i++) { simde_uint8x8_t a = simde_vld1_u8(test_vec[i].a); simde_uint8x8_t b = simde_vld1_u8(test_vec[i].b); simde_uint8x8_t r = simde_vhsub_u8(a, b); simde_test_arm_neon_assert_equal_u8x8(r, simde_vld1_u8(test_vec[i].r)); } return 0; #else fputc('\n', stdout); for (int i = 0 ; i < 8 ; i++) { simde_uint8x8_t a = simde_test_arm_neon_random_u8x8(); simde_uint8x8_t b = simde_test_arm_neon_random_u8x8(); simde_uint8x8_t r = simde_vhsub_u8(a, b); simde_test_arm_neon_write_u8x8(2, a, SIMDE_TEST_VEC_POS_FIRST); simde_test_arm_neon_write_u8x8(2, b, SIMDE_TEST_VEC_POS_MIDDLE); simde_test_arm_neon_write_u8x8(2, r, SIMDE_TEST_VEC_POS_LAST); } return 1; #endif } static int test_simde_vhsub_u16 (SIMDE_MUNIT_TEST_ARGS) { #if 1 static const struct { uint16_t a[4]; uint16_t b[4]; uint16_t r[4]; } test_vec[] = { { { UINT16_C(33493), UINT16_C(37440), UINT16_C( 4144), UINT16_C(37310) }, { UINT16_C(59086), UINT16_C(12529), UINT16_C(23738), UINT16_C(48296) }, { UINT16_C(52739), UINT16_C(12455), UINT16_C(55739), UINT16_C(60043) } }, { { UINT16_C(45826), UINT16_C(60640), UINT16_C(59932), UINT16_C( 7110) }, { UINT16_C(34724), UINT16_C(43058), UINT16_C(50281), UINT16_C(15946) }, { UINT16_C( 5551), UINT16_C( 8791), UINT16_C( 4825), UINT16_C(61118) } }, { { UINT16_C(35399), UINT16_C(30672), UINT16_C(36506), UINT16_C(26632) }, { UINT16_C(63860), UINT16_C(12184), UINT16_C(16469), UINT16_C(22763) }, { UINT16_C(51305), UINT16_C( 9244), UINT16_C(10018), UINT16_C( 1934) } }, { { UINT16_C(52212), UINT16_C( 4164), UINT16_C( 2997), UINT16_C(22828) }, { UINT16_C(24210), UINT16_C(64258), UINT16_C(19491), UINT16_C(27193) }, { UINT16_C(14001), UINT16_C(35489), UINT16_C(57289), UINT16_C(63353) } }, { { UINT16_C( 2518), UINT16_C(28897), UINT16_C(59799), UINT16_C( 3032) }, { UINT16_C(29154), UINT16_C(14394), UINT16_C( 9649), UINT16_C(42384) }, { UINT16_C(52218), UINT16_C( 7251), UINT16_C(25075), UINT16_C(45860) } }, { { UINT16_C(54513), UINT16_C(42678), UINT16_C(58079), UINT16_C(28928) }, { UINT16_C( 576), UINT16_C(25452), UINT16_C(42318), UINT16_C( 9421) }, { UINT16_C(26968), UINT16_C( 8613), UINT16_C( 7880), UINT16_C( 9753) } }, { { UINT16_C(44718), UINT16_C(17812), UINT16_C(27799), UINT16_C(31313) }, { UINT16_C(35805), UINT16_C(36786), UINT16_C(17073), UINT16_C(41524) }, { UINT16_C( 4456), UINT16_C(56049), UINT16_C( 5363), UINT16_C(60430) } }, { { UINT16_C(59926), UINT16_C(63048), UINT16_C(18636), UINT16_C( 3431) }, { UINT16_C(54346), UINT16_C(39024), UINT16_C(15993), UINT16_C(10428) }, { UINT16_C( 2790), UINT16_C(12012), UINT16_C( 1321), UINT16_C(62037) } } }; for (size_t i = 0 ; i < (sizeof(test_vec) / sizeof(test_vec[0])) ; i++) { simde_uint16x4_t a = simde_vld1_u16(test_vec[i].a); simde_uint16x4_t b = simde_vld1_u16(test_vec[i].b); simde_uint16x4_t r = simde_vhsub_u16(a, b); simde_test_arm_neon_assert_equal_u16x4(r, simde_vld1_u16(test_vec[i].r)); } return 0; #else fputc('\n', stdout); for (int i = 0 ; i < 8 ; i++) { simde_uint16x4_t a = simde_test_arm_neon_random_u16x4(); simde_uint16x4_t b = simde_test_arm_neon_random_u16x4(); simde_uint16x4_t r = simde_vhsub_u16(a, b); simde_test_arm_neon_write_u16x4(2, a, SIMDE_TEST_VEC_POS_FIRST); simde_test_arm_neon_write_u16x4(2, b, SIMDE_TEST_VEC_POS_MIDDLE); simde_test_arm_neon_write_u16x4(2, r, SIMDE_TEST_VEC_POS_LAST); } return 1; #endif } static int test_simde_vhsub_u32 (SIMDE_MUNIT_TEST_ARGS) { #if 1 static const struct { uint32_t a[2]; uint32_t b[2]; uint32_t r[2]; } test_vec[] = { { { UINT32_C(2221756652), UINT32_C(2600386237) }, { UINT32_C(4213813322), UINT32_C( 144531186) }, { UINT32_C(3298938961), UINT32_C(1227927525) } }, { { UINT32_C( 369026376), UINT32_C(2015520302) }, { UINT32_C(3004273210), UINT32_C(3185298896) }, { UINT32_C(2977343879), UINT32_C(3710077999) } }, { { UINT32_C(3678488862), UINT32_C(1366638343) }, { UINT32_C(3779895279), UINT32_C(1172957693) }, { UINT32_C(4244264087), UINT32_C( 96840325) } }, { { UINT32_C(4250593487), UINT32_C(2289400910) }, { UINT32_C(3745220111), UINT32_C(1922832212) }, { UINT32_C( 252686688), UINT32_C( 183284349) } }, { { UINT32_C(1733156192), UINT32_C( 196723228) }, { UINT32_C(1592526177), UINT32_C(3198473967) }, { UINT32_C( 70315007), UINT32_C(2794091926) } }, { { UINT32_C( 213647038), UINT32_C(2324967547) }, { UINT32_C( 191483831), UINT32_C(1182598886) }, { UINT32_C( 11081603), UINT32_C( 571184330) } }, { { UINT32_C( 11455203), UINT32_C(3993724812) }, { UINT32_C(1531770988), UINT32_C(2350510286) }, { UINT32_C(3534809403), UINT32_C( 821607263) } }, { { UINT32_C(1788400879), UINT32_C(3170118661) }, { UINT32_C(3804716539), UINT32_C(1193821283) }, { UINT32_C(3286809466), UINT32_C( 988148689) } } }; for (size_t i = 0 ; i < (sizeof(test_vec) / sizeof(test_vec[0])) ; i++) { simde_uint32x2_t a = simde_vld1_u32(test_vec[i].a); simde_uint32x2_t b = simde_vld1_u32(test_vec[i].b); simde_uint32x2_t r = simde_vhsub_u32(a, b); simde_test_arm_neon_assert_equal_u32x2(r, simde_vld1_u32(test_vec[i].r)); } return 0; #else fputc('\n', stdout); for (int i = 0 ; i < 8 ; i++) { simde_uint32x2_t a = simde_test_arm_neon_random_u32x2(); simde_uint32x2_t b = simde_test_arm_neon_random_u32x2(); simde_uint32x2_t r = simde_vhsub_u32(a, b); simde_test_arm_neon_write_u32x2(2, a, SIMDE_TEST_VEC_POS_FIRST); simde_test_arm_neon_write_u32x2(2, b, SIMDE_TEST_VEC_POS_MIDDLE); simde_test_arm_neon_write_u32x2(2, r, SIMDE_TEST_VEC_POS_LAST); } return 1; #endif } static int test_simde_vhsubq_s8 (SIMDE_MUNIT_TEST_ARGS) { #if 1 static const struct { int8_t a[16]; int8_t b[16]; int8_t r[16]; } test_vec[] = { { { INT8_C( 14), -INT8_C( 42), INT8_C( 71), -INT8_C( 102), INT8_C( 61), INT8_C( 82), -INT8_C( 120), -INT8_C( 86), INT8_C( 74), -INT8_C( 43), INT8_C( 5), INT8_C( 24), -INT8_C( 59), INT8_C( 31), -INT8_C( 92), -INT8_C( 76) }, { -INT8_C( 13), INT8_C( 60), INT8_C( 30), -INT8_C( 8), INT8_C( 104), INT8_C( 18), -INT8_C( 76), INT8_C( 100), INT8_C( 112), INT8_C( 123), INT8_C( 70), -INT8_C( 45), -INT8_C( 65), INT8_C( 110), INT8_C( 26), -INT8_C( 51) }, { INT8_C( 13), -INT8_C( 51), INT8_C( 20), -INT8_C( 47), -INT8_C( 22), INT8_C( 32), -INT8_C( 22), -INT8_C( 93), -INT8_C( 19), -INT8_C( 83), -INT8_C( 33), INT8_C( 34), INT8_C( 3), -INT8_C( 40), -INT8_C( 59), -INT8_C( 13) } }, { { INT8_C( 69), INT8_C( 97), INT8_C( 104), -INT8_C( 126), -INT8_C( 76), -INT8_C( 16), INT8_C( 44), -INT8_C( 2), -INT8_C( 59), INT8_C( 50), INT8_C( 23), -INT8_C( 117), INT8_C( 81), -INT8_C( 69), INT8_C( 63), INT8_C( 68) }, { -INT8_C( 8), INT8_C( 94), INT8_C( 61), INT8_C( 96), INT8_C( 112), -INT8_C( 15), -INT8_C( 60), -INT8_C( 32), INT8_C( 109), INT8_C( 10), -INT8_C( 76), INT8_C( 44), INT8_C( 121), -INT8_C( 50), -INT8_C( 6), -INT8_C( 66) }, { INT8_C( 38), INT8_C( 1), INT8_C( 21), -INT8_C( 111), -INT8_C( 94), -INT8_C( 1), INT8_C( 52), INT8_C( 15), -INT8_C( 84), INT8_C( 20), INT8_C( 49), -INT8_C( 81), -INT8_C( 20), -INT8_C( 10), INT8_C( 34), INT8_C( 67) } }, { { INT8_C( 48), INT8_C( 98), INT8_C( 64), -INT8_C( 28), INT8_C( 82), INT8_C( 109), -INT8_C( 30), INT8_C( 24), -INT8_C( 97), -INT8_C( 7), -INT8_C( 93), -INT8_C( 16), -INT8_C( 75), -INT8_C( 30), INT8_C( 52), -INT8_C( 83) }, { INT8_C( 64), INT8_C( 113), INT8_C( 13), -INT8_C( 79), INT8_C( 99), -INT8_C( 46), -INT8_C( 111), -INT8_C( 48), -INT8_C( 36), INT8_C( 69), -INT8_C( 4), INT8_C( 85), INT8_C( 20), -INT8_C( 10), INT8_C( 19), INT8_C( 68) }, { -INT8_C( 8), -INT8_C( 8), INT8_C( 25), INT8_C( 25), -INT8_C( 9), INT8_C( 77), INT8_C( 40), INT8_C( 36), -INT8_C( 31), -INT8_C( 38), -INT8_C( 45), -INT8_C( 51), -INT8_C( 48), -INT8_C( 10), INT8_C( 16), -INT8_C( 76) } }, { { INT8_C( 88), INT8_C( 84), INT8_C( 40), -INT8_C( 85), -INT8_C( 63), INT8_C( 10), -INT8_C( 61), INT8_C( 96), INT8_C( 4), INT8_C( 102), INT8_C( 80), -INT8_C( 71), INT8_C( 72), -INT8_C( 124), INT8_C( 102), -INT8_C( 119) }, { -INT8_C( 10), INT8_C( 115), INT8_C( 58), INT8_C( 89), INT8_C( 69), -INT8_C( 53), INT8_C( 41), INT8_C( 34), INT8_C( 17), INT8_C( 37), INT8_C( 119), INT8_C( 37), INT8_C( 28), -INT8_C( 117), INT8_C( 105), INT8_C( 116) }, { INT8_C( 49), -INT8_C( 16), -INT8_C( 9), -INT8_C( 87), -INT8_C( 66), INT8_C( 31), -INT8_C( 51), INT8_C( 31), -INT8_C( 7), INT8_C( 32), -INT8_C( 20), -INT8_C( 54), INT8_C( 22), -INT8_C( 4), -INT8_C( 2), -INT8_C( 118) } }, { { -INT8_C( 33), -INT8_C( 111), INT8_C( 31), -INT8_C( 96), -INT8_C( 101), -INT8_C( 30), INT8_C( 0), -INT8_C( 97), INT8_C( 72), INT8_C( 80), INT8_C( 88), -INT8_C( 111), -INT8_C( 44), -INT8_C( 66), INT8_C( 26), -INT8_C( 54) }, { INT8_C( 50), INT8_C( 84), INT8_C( 35), INT8_C( 119), INT8_C( 31), INT8_C( 76), -INT8_C( 103), INT8_C( 48), INT8_C( 114), INT8_C( 17), INT8_C( 85), -INT8_C( 114), -INT8_C( 100), -INT8_C( 66), INT8_C( 2), INT8_C( 123) }, { -INT8_C( 42), -INT8_C( 98), -INT8_C( 2), -INT8_C( 108), -INT8_C( 66), -INT8_C( 53), INT8_C( 51), -INT8_C( 73), -INT8_C( 21), INT8_C( 31), INT8_C( 1), INT8_C( 1), INT8_C( 28), INT8_C( 0), INT8_C( 12), -INT8_C( 89) } }, { { INT8_C( 79), INT8_C( 34), INT8_C( 27), -INT8_C( 21), INT8_C( 4), INT8_C( 27), -INT8_C( 118), INT8_C( 77), INT8_C( 107), -INT8_C( 29), -INT8_C( 34), INT8_C( 63), -INT8_C( 95), -INT8_C( 8), INT8_C( 10), -INT8_C( 45) }, { INT8_C( 76), INT8_C( 45), INT8_C( 75), INT8_C( 107), INT8_C( 122), -INT8_C( 28), -INT8_C( 100), -INT8_C( 20), -INT8_C( 11), -INT8_C( 15), INT8_C( 122), -INT8_C( 111), -INT8_C( 80), INT8_C( 124), INT8_C( 12), -INT8_C( 1) }, { INT8_C( 1), -INT8_C( 6), -INT8_C( 24), -INT8_C( 64), -INT8_C( 59), INT8_C( 27), -INT8_C( 9), INT8_C( 48), INT8_C( 59), -INT8_C( 7), -INT8_C( 78), INT8_C( 87), -INT8_C( 8), -INT8_C( 66), -INT8_C( 1), -INT8_C( 22) } }, { { -INT8_C( 98), INT8_C( 39), -INT8_C( 22), -INT8_C( 93), INT8_C( 66), INT8_C( 117), -INT8_C( 16), -INT8_C( 83), INT8_C( 88), -INT8_C( 50), -INT8_C( 19), -INT8_C( 7), -INT8_C( 58), -INT8_C( 9), -INT8_C( 51), INT8_C( 18) }, { INT8_C( 36), INT8_C( 24), INT8_C( 125), -INT8_C( 98), -INT8_C( 4), INT8_C( 25), -INT8_C( 118), -INT8_C( 14), INT8_C( 11), INT8_C( 4), -INT8_C( 125), -INT8_C( 69), -INT8_C( 127), -INT8_C( 112), -INT8_C( 70), INT8_C( 31) }, { -INT8_C( 67), INT8_C( 7), -INT8_C( 74), INT8_C( 2), INT8_C( 35), INT8_C( 46), INT8_C( 51), -INT8_C( 35), INT8_C( 38), -INT8_C( 27), INT8_C( 53), INT8_C( 31), INT8_C( 34), INT8_C( 51), INT8_C( 9), -INT8_C( 7) } }, { { -INT8_C( 73), -INT8_C( 91), -INT8_C( 62), -INT8_C( 6), INT8_C( 26), -INT8_C( 78), -INT8_C( 89), INT8_C( 114), INT8_MIN, -INT8_C( 108), INT8_C( 107), INT8_C( 70), -INT8_C( 117), INT8_C( 56), INT8_C( 88), -INT8_C( 80) }, { INT8_C( 80), -INT8_C( 42), INT8_C( 78), INT8_C( 77), -INT8_C( 17), -INT8_C( 39), INT8_C( 63), -INT8_C( 6), -INT8_C( 35), -INT8_C( 62), -INT8_C( 75), INT8_C( 94), INT8_C( 82), INT8_C( 112), INT8_C( 126), INT8_C( 10) }, { -INT8_C( 77), -INT8_C( 25), -INT8_C( 70), -INT8_C( 42), INT8_C( 21), -INT8_C( 20), -INT8_C( 76), INT8_C( 60), -INT8_C( 47), -INT8_C( 23), INT8_C( 91), -INT8_C( 12), -INT8_C( 100), -INT8_C( 28), -INT8_C( 19), -INT8_C( 45) } } }; for (size_t i = 0 ; i < (sizeof(test_vec) / sizeof(test_vec[0])) ; i++) { simde_int8x16_t a = simde_vld1q_s8(test_vec[i].a); simde_int8x16_t b = simde_vld1q_s8(test_vec[i].b); simde_int8x16_t r = simde_vhsubq_s8(a, b); simde_test_arm_neon_assert_equal_i8x16(r, simde_vld1q_s8(test_vec[i].r)); } return 0; #else fputc('\n', stdout); for (int i = 0 ; i < 8 ; i++) { simde_int8x16_t a = simde_test_arm_neon_random_i8x16(); simde_int8x16_t b = simde_test_arm_neon_random_i8x16(); simde_int8x16_t r = simde_vhsubq_s8(a, b); simde_test_arm_neon_write_i8x16(2, a, SIMDE_TEST_VEC_POS_FIRST); simde_test_arm_neon_write_i8x16(2, b, SIMDE_TEST_VEC_POS_MIDDLE); simde_test_arm_neon_write_i8x16(2, r, SIMDE_TEST_VEC_POS_LAST); } return 1; #endif } static int test_simde_vhsubq_s16 (SIMDE_MUNIT_TEST_ARGS) { #if 1 static const struct { int16_t a[8]; int16_t b[8]; int16_t r[8]; } test_vec[] = { { { INT16_C( 16405), INT16_C( 12036), -INT16_C( 21517), INT16_C( 29601), INT16_C( 3136), -INT16_C( 13382), INT16_C( 4677), -INT16_C( 27269) }, { -INT16_C( 13592), -INT16_C( 10014), INT16_C( 8611), -INT16_C( 32558), -INT16_C( 30492), INT16_C( 14047), INT16_C( 24056), INT16_C( 3392) }, { INT16_C( 14998), INT16_C( 11025), -INT16_C( 15064), INT16_C( 31079), INT16_C( 16814), -INT16_C( 13715), -INT16_C( 9690), -INT16_C( 15331) } }, { { INT16_C( 17565), -INT16_C( 28612), -INT16_C( 8720), INT16_C( 12292), -INT16_C( 16663), INT16_C( 12027), INT16_C( 30672), -INT16_C( 17980) }, { -INT16_C( 22975), -INT16_C( 7023), INT16_C( 25544), -INT16_C( 21404), INT16_C( 17387), -INT16_C( 7198), INT16_C( 9120), INT16_C( 16112) }, { INT16_C( 20270), -INT16_C( 10795), -INT16_C( 17132), INT16_C( 16848), -INT16_C( 17025), INT16_C( 9612), INT16_C( 10776), -INT16_C( 17046) } }, { { INT16_C( 11367), INT16_C( 22478), -INT16_C( 11767), -INT16_C( 3193), -INT16_C( 31856), INT16_C( 24865), -INT16_C( 6662), INT16_C( 15130) }, { -INT16_C( 21620), INT16_C( 21535), -INT16_C( 31986), -INT16_C( 1536), -INT16_C( 7481), INT16_C( 26589), -INT16_C( 12795), INT16_C( 28069) }, { INT16_C( 16493), INT16_C( 471), INT16_C( 10109), -INT16_C( 829), -INT16_C( 12188), -INT16_C( 862), INT16_C( 3066), -INT16_C( 6470) } }, { { INT16_C( 29946), INT16_C( 1220), INT16_C( 19526), -INT16_C( 10249), INT16_C( 6351), -INT16_C( 14024), INT16_C( 21246), -INT16_C( 30204) }, { INT16_C( 9213), INT16_C( 3038), -INT16_C( 8538), INT16_C( 27909), -INT16_C( 7232), -INT16_C( 14635), INT16_C( 31409), -INT16_C( 21709) }, { INT16_C( 10366), -INT16_C( 909), INT16_C( 14032), -INT16_C( 19079), INT16_C( 6791), INT16_C( 305), -INT16_C( 5082), -INT16_C( 4248) } }, { { -INT16_C( 2066), INT16_C( 13743), -INT16_C( 22973), INT16_C( 4620), INT16_C( 17599), -INT16_C( 16933), -INT16_C( 8298), -INT16_C( 27833) }, { INT16_C( 9474), -INT16_C( 22114), -INT16_C( 23549), -INT16_C( 15594), -INT16_C( 5241), INT16_C( 14473), -INT16_C( 17306), INT16_C( 21731) }, { -INT16_C( 5770), INT16_C( 17928), INT16_C( 288), INT16_C( 10107), INT16_C( 11420), -INT16_C( 15703), INT16_C( 4504), -INT16_C( 24782) } }, { { -INT16_C( 27724), -INT16_C( 2167), -INT16_C( 27335), -INT16_C( 2038), -INT16_C( 6695), INT16_C( 28597), -INT16_C( 827), -INT16_C( 14590) }, { -INT16_C( 24287), INT16_C( 9328), -INT16_C( 30907), -INT16_C( 13080), INT16_C( 29042), -INT16_C( 10236), -INT16_C( 6354), -INT16_C( 7635) }, { -INT16_C( 1719), -INT16_C( 5748), INT16_C( 1786), INT16_C( 5521), -INT16_C( 17869), INT16_C( 19416), INT16_C( 2763), -INT16_C( 3478) } }, { { -INT16_C( 18822), -INT16_C( 19239), -INT16_C( 7348), INT16_C( 9644), INT16_C( 25289), -INT16_C( 29035), -INT16_C( 26786), -INT16_C( 32683) }, { -INT16_C( 14792), INT16_C( 32164), -INT16_C( 29619), -INT16_C( 16567), INT16_C( 19966), INT16_C( 11416), -INT16_C( 15051), -INT16_C( 20722) }, { -INT16_C( 2015), -INT16_C( 25702), INT16_C( 11135), INT16_C( 13105), INT16_C( 2661), -INT16_C( 20226), -INT16_C( 5868), -INT16_C( 5981) } }, { { -INT16_C( 6277), -INT16_C( 14493), INT16_C( 4299), -INT16_C( 27411), -INT16_C( 32142), -INT16_C( 12254), INT16_C( 30489), INT16_C( 21072) }, { -INT16_C( 2755), -INT16_C( 30001), INT16_C( 6529), INT16_C( 32586), -INT16_C( 7578), -INT16_C( 25685), -INT16_C( 18009), INT16_C( 8779) }, { -INT16_C( 1761), INT16_C( 7754), -INT16_C( 1115), -INT16_C( 29999), -INT16_C( 12282), INT16_C( 6715), INT16_C( 24249), INT16_C( 6146) } } }; for (size_t i = 0 ; i < (sizeof(test_vec) / sizeof(test_vec[0])) ; i++) { simde_int16x8_t a = simde_vld1q_s16(test_vec[i].a); simde_int16x8_t b = simde_vld1q_s16(test_vec[i].b); simde_int16x8_t r = simde_vhsubq_s16(a, b); simde_test_arm_neon_assert_equal_i16x8(r, simde_vld1q_s16(test_vec[i].r)); } return 0; #else fputc('\n', stdout); for (int i = 0 ; i < 8 ; i++) { simde_int16x8_t a = simde_test_arm_neon_random_i16x8(); simde_int16x8_t b = simde_test_arm_neon_random_i16x8(); simde_int16x8_t r = simde_vhsubq_s16(a, b); simde_test_arm_neon_write_i16x8(2, a, SIMDE_TEST_VEC_POS_FIRST); simde_test_arm_neon_write_i16x8(2, b, SIMDE_TEST_VEC_POS_MIDDLE); simde_test_arm_neon_write_i16x8(2, r, SIMDE_TEST_VEC_POS_LAST); } return 1; #endif } static int test_simde_vhsubq_s32 (SIMDE_MUNIT_TEST_ARGS) { #if 1 static const struct { int32_t a[4]; int32_t b[4]; int32_t r[4]; } test_vec[] = { { { INT32_C( 1827319457), INT32_C( 805361598), INT32_C( 1912676953), -INT32_C( 674999911) }, { -INT32_C( 933129146), INT32_C( 323464109), INT32_C( 883946381), INT32_C( 1297611436) }, { INT32_C( 1380224301), INT32_C( 240948744), INT32_C( 514365286), -INT32_C( 986305674) } }, { { INT32_C( 1740194216), INT32_C( 1905768728), INT32_C( 1977850075), INT32_C( 810330346) }, { -INT32_C( 369578692), -INT32_C( 419676071), -INT32_C( 551834829), INT32_C( 1311601317) }, { INT32_C( 1054886454), INT32_C( 1162722399), INT32_C( 1264842452), -INT32_C( 250635486) } }, { { -INT32_C( 877271373), INT32_C( 2067549344), -INT32_C( 806346779), INT32_C( 67058887) }, { INT32_C( 1139603690), INT32_C( 1797908792), INT32_C( 977945748), INT32_C( 1770551222) }, { -INT32_C( 1008437532), INT32_C( 134820276), -INT32_C( 892146264), -INT32_C( 851746168) } }, { { -INT32_C( 30130850), INT32_C( 1853452425), INT32_C( 1463642768), -INT32_C( 1873068634) }, { INT32_C( 1842562869), -INT32_C( 975635152), -INT32_C( 117497279), -INT32_C( 127826022) }, { -INT32_C( 936346860), INT32_C( 1414543788), INT32_C( 790570023), -INT32_C( 872621306) } }, { { INT32_C( 1308006084), -INT32_C( 1766035706), -INT32_C( 2131822119), INT32_C( 1796229430) }, { -INT32_C( 1042750320), INT32_C( 579252449), INT32_C( 1830454739), -INT32_C( 798655476) }, { INT32_C( 1175378202), -INT32_C( 1172644078), -INT32_C( 1981138429), INT32_C( 1297442453) } }, { { INT32_C( 404577042), -INT32_C( 1531979318), INT32_C( 153394643), INT32_C( 1987392742) }, { -INT32_C( 113816296), -INT32_C( 786645506), INT32_C( 1312699970), -INT32_C( 1004624974) }, { INT32_C( 259196669), -INT32_C( 372666906), -INT32_C( 579652664), INT32_C( 1496008858) } }, { { -INT32_C( 925025026), -INT32_C( 395539435), INT32_C( 267554857), -INT32_C( 578459707) }, { -INT32_C( 1294484044), -INT32_C( 1115425926), -INT32_C( 603209431), INT32_C( 1654663780) }, { INT32_C( 184729509), INT32_C( 359943245), INT32_C( 435382144), -INT32_C( 1116561744) } }, { { INT32_C( 2066447718), INT32_C( 845453065), -INT32_C( 314485208), INT32_C( 1909114813) }, { -INT32_C( 31153788), -INT32_C( 1094998124), -INT32_C( 845494423), INT32_C( 1462778609) }, { INT32_C( 1048800753), INT32_C( 970225594), INT32_C( 265504607), INT32_C( 223168102) } } }; for (size_t i = 0 ; i < (sizeof(test_vec) / sizeof(test_vec[0])) ; i++) { simde_int32x4_t a = simde_vld1q_s32(test_vec[i].a); simde_int32x4_t b = simde_vld1q_s32(test_vec[i].b); simde_int32x4_t r = simde_vhsubq_s32(a, b); simde_test_arm_neon_assert_equal_i32x4(r, simde_vld1q_s32(test_vec[i].r)); } return 0; #else fputc('\n', stdout); for (int i = 0 ; i < 8 ; i++) { simde_int32x4_t a = simde_test_arm_neon_random_i32x4(); simde_int32x4_t b = simde_test_arm_neon_random_i32x4(); simde_int32x4_t r = simde_vhsubq_s32(a, b); simde_test_arm_neon_write_i32x4(2, a, SIMDE_TEST_VEC_POS_FIRST); simde_test_arm_neon_write_i32x4(2, b, SIMDE_TEST_VEC_POS_MIDDLE); simde_test_arm_neon_write_i32x4(2, r, SIMDE_TEST_VEC_POS_LAST); } return 1; #endif } static int test_simde_vhsubq_u8 (SIMDE_MUNIT_TEST_ARGS) { #if 1 static const struct { uint8_t a[16]; uint8_t b[16]; uint8_t r[16]; } test_vec[] = { { { UINT8_C(184), UINT8_C( 91), UINT8_C(210), UINT8_C(193), UINT8_C(242), UINT8_C( 54), UINT8_C(244), UINT8_C( 26), UINT8_C(140), UINT8_C( 53), UINT8_C( 7), UINT8_C( 73), UINT8_C(252), UINT8_C(210), UINT8_C(187), UINT8_C(128) }, { UINT8_C(115), UINT8_C(223), UINT8_C(127), UINT8_C( 8), UINT8_C(134), UINT8_C( 58), UINT8_C(198), UINT8_C(239), UINT8_C( 1), UINT8_C( 96), UINT8_C(189), UINT8_C(242), UINT8_C(154), UINT8_C(237), UINT8_C( 73), UINT8_C( 82) }, { UINT8_C( 34), UINT8_C(190), UINT8_C( 41), UINT8_C( 92), UINT8_C( 54), UINT8_C(254), UINT8_C( 23), UINT8_C(149), UINT8_C( 69), UINT8_C(234), UINT8_C(165), UINT8_C(171), UINT8_C( 49), UINT8_C(242), UINT8_C( 57), UINT8_C( 23) } }, { { UINT8_C( 72), UINT8_C( 28), UINT8_C( 20), UINT8_C( 58), UINT8_C( 82), UINT8_C( 8), UINT8_C( 85), UINT8_C(223), UINT8_C( 61), UINT8_C( 92), UINT8_C( 40), UINT8_C( 58), UINT8_C( 46), UINT8_C(227), UINT8_C(186), UINT8_C(162) }, { UINT8_C(194), UINT8_C( 57), UINT8_C(170), UINT8_C( 73), UINT8_C(116), UINT8_C(112), UINT8_C( 56), UINT8_C(117), UINT8_C(208), UINT8_C(245), UINT8_C(104), UINT8_C(106), UINT8_C(226), UINT8_C(177), UINT8_C(189), UINT8_C( 42) }, { UINT8_C(195), UINT8_C(241), UINT8_C(181), UINT8_C(248), UINT8_C(239), UINT8_C(204), UINT8_C( 14), UINT8_C( 53), UINT8_C(182), UINT8_C(179), UINT8_C(224), UINT8_C(232), UINT8_C(166), UINT8_C( 25), UINT8_C(254), UINT8_C( 60) } }, { { UINT8_C(205), UINT8_C(209), UINT8_C(101), UINT8_C( 32), UINT8_C(217), UINT8_C(186), UINT8_MAX, UINT8_C( 22), UINT8_C( 22), UINT8_C( 39), UINT8_C( 80), UINT8_C( 69), UINT8_C( 11), UINT8_C( 11), UINT8_C(231), UINT8_C(205) }, { UINT8_C( 68), UINT8_C(145), UINT8_C( 22), UINT8_C(184), UINT8_C( 1), UINT8_C( 79), UINT8_C( 46), UINT8_C(209), UINT8_C( 68), UINT8_C(150), UINT8_C( 59), UINT8_C( 39), UINT8_C( 71), UINT8_C(248), UINT8_C( 81), UINT8_C( 21) }, { UINT8_C( 68), UINT8_C( 32), UINT8_C( 39), UINT8_C(180), UINT8_C(108), UINT8_C( 53), UINT8_C(104), UINT8_C(162), UINT8_C(233), UINT8_C(200), UINT8_C( 10), UINT8_C( 15), UINT8_C(226), UINT8_C(137), UINT8_C( 75), UINT8_C( 92) } }, { { UINT8_C(201), UINT8_C(182), UINT8_C( 53), UINT8_C(162), UINT8_C(112), UINT8_C( 52), UINT8_C(185), UINT8_C(135), UINT8_C( 91), UINT8_C( 9), UINT8_C(204), UINT8_C(102), UINT8_C( 20), UINT8_C(179), UINT8_C( 52), UINT8_C( 89) }, { UINT8_C( 68), UINT8_C( 74), UINT8_C( 17), UINT8_C( 69), UINT8_C(153), UINT8_C( 63), UINT8_C( 22), UINT8_C(222), UINT8_C(213), UINT8_C( 81), UINT8_C( 5), UINT8_C( 29), UINT8_C( 74), UINT8_C( 86), UINT8_C( 50), UINT8_C( 19) }, { UINT8_C( 66), UINT8_C( 54), UINT8_C( 18), UINT8_C( 46), UINT8_C(235), UINT8_C(250), UINT8_C( 81), UINT8_C(212), UINT8_C(195), UINT8_C(220), UINT8_C( 99), UINT8_C( 36), UINT8_C(229), UINT8_C( 46), UINT8_C( 1), UINT8_C( 35) } }, { { UINT8_C( 13), UINT8_C(103), UINT8_C(182), UINT8_C(125), UINT8_C(155), UINT8_C(111), UINT8_C( 4), UINT8_C(246), UINT8_C(120), UINT8_C(208), UINT8_C( 93), UINT8_C(141), UINT8_C(131), UINT8_C(145), UINT8_C(230), UINT8_C(199) }, { UINT8_C(219), UINT8_C(247), UINT8_C( 12), UINT8_C(117), UINT8_C( 55), UINT8_C( 34), UINT8_C( 83), UINT8_C( 12), UINT8_C(116), UINT8_C( 88), UINT8_C( 41), UINT8_C(190), UINT8_C(174), UINT8_C( 91), UINT8_C(209), UINT8_C(187) }, { UINT8_C(153), UINT8_C(184), UINT8_C( 85), UINT8_C( 4), UINT8_C( 50), UINT8_C( 38), UINT8_C(216), UINT8_C(117), UINT8_C( 2), UINT8_C( 60), UINT8_C( 26), UINT8_C(231), UINT8_C(234), UINT8_C( 27), UINT8_C( 10), UINT8_C( 6) } }, { { UINT8_C(194), UINT8_C(135), UINT8_C( 57), UINT8_C( 93), UINT8_C(246), UINT8_C( 61), UINT8_C( 84), UINT8_C(111), UINT8_C( 14), UINT8_C(177), UINT8_C(252), UINT8_C(145), UINT8_C( 66), UINT8_C(226), UINT8_C( 89), UINT8_C( 29) }, { UINT8_C(217), UINT8_C(101), UINT8_C(146), UINT8_C( 16), UINT8_C(136), UINT8_C(229), UINT8_C( 29), UINT8_C(252), UINT8_C( 61), UINT8_C( 70), UINT8_C(186), UINT8_C(236), UINT8_C(162), UINT8_C(139), UINT8_C(167), UINT8_C(100) }, { UINT8_C(244), UINT8_C( 17), UINT8_C(211), UINT8_C( 38), UINT8_C( 55), UINT8_C(172), UINT8_C( 27), UINT8_C(185), UINT8_C(232), UINT8_C( 53), UINT8_C( 33), UINT8_C(210), UINT8_C(208), UINT8_C( 43), UINT8_C(217), UINT8_C(220) } }, { { UINT8_C( 19), UINT8_C(224), UINT8_C(194), UINT8_C( 9), UINT8_C( 30), UINT8_C( 22), UINT8_C(120), UINT8_C( 44), UINT8_C(199), UINT8_C(116), UINT8_C(189), UINT8_C( 9), UINT8_C( 86), UINT8_C( 22), UINT8_C( 38), UINT8_C( 48) }, { UINT8_C(124), UINT8_C(185), UINT8_C( 64), UINT8_C( 4), UINT8_C(158), UINT8_C( 93), UINT8_C( 0), UINT8_C(220), UINT8_C(164), UINT8_C(186), UINT8_C(200), UINT8_C( 70), UINT8_C( 69), UINT8_C(111), UINT8_C(170), UINT8_C( 88) }, { UINT8_C(203), UINT8_C( 19), UINT8_C( 65), UINT8_C( 2), UINT8_C(192), UINT8_C(220), UINT8_C( 60), UINT8_C(168), UINT8_C( 17), UINT8_C(221), UINT8_C(250), UINT8_C(225), UINT8_C( 8), UINT8_C(211), UINT8_C(190), UINT8_C(236) } }, { { UINT8_C( 80), UINT8_C(108), UINT8_C( 98), UINT8_C(110), UINT8_C(130), UINT8_C(218), UINT8_C(154), UINT8_C( 73), UINT8_C( 79), UINT8_C( 87), UINT8_C( 82), UINT8_C(165), UINT8_C(110), UINT8_C(121), UINT8_C(213), UINT8_C(234) }, { UINT8_C( 50), UINT8_C( 22), UINT8_C(238), UINT8_C(208), UINT8_C(115), UINT8_C(238), UINT8_C(172), UINT8_C( 23), UINT8_C(168), UINT8_C(116), UINT8_C( 93), UINT8_C(237), UINT8_C(228), UINT8_C( 8), UINT8_C( 70), UINT8_C( 52) }, { UINT8_C( 15), UINT8_C( 43), UINT8_C(186), UINT8_C(207), UINT8_C( 7), UINT8_C(246), UINT8_C(247), UINT8_C( 25), UINT8_C(211), UINT8_C(241), UINT8_C(250), UINT8_C(220), UINT8_C(197), UINT8_C( 56), UINT8_C( 71), UINT8_C( 91) } } }; for (size_t i = 0 ; i < (sizeof(test_vec) / sizeof(test_vec[0])) ; i++) { simde_uint8x16_t a = simde_vld1q_u8(test_vec[i].a); simde_uint8x16_t b = simde_vld1q_u8(test_vec[i].b); simde_uint8x16_t r = simde_vhsubq_u8(a, b); simde_test_arm_neon_assert_equal_u8x16(r, simde_vld1q_u8(test_vec[i].r)); } return 0; #else fputc('\n', stdout); for (int i = 0 ; i < 8 ; i++) { simde_uint8x16_t a = simde_test_arm_neon_random_u8x16(); simde_uint8x16_t b = simde_test_arm_neon_random_u8x16(); simde_uint8x16_t r = simde_vhsubq_u8(a, b); simde_test_arm_neon_write_u8x16(2, a, SIMDE_TEST_VEC_POS_FIRST); simde_test_arm_neon_write_u8x16(2, b, SIMDE_TEST_VEC_POS_MIDDLE); simde_test_arm_neon_write_u8x16(2, r, SIMDE_TEST_VEC_POS_LAST); } return 1; #endif } static int test_simde_vhsubq_u16 (SIMDE_MUNIT_TEST_ARGS) { #if 1 static const struct { uint16_t a[8]; uint16_t b[8]; uint16_t r[8]; } test_vec[] = { { { UINT16_C(43124), UINT16_C(63394), UINT16_C(15490), UINT16_C(53568), UINT16_C(37779), UINT16_C( 375), UINT16_C(19468), UINT16_C(16107) }, { UINT16_C(55650), UINT16_C(54798), UINT16_C(48071), UINT16_C(28653), UINT16_C(19247), UINT16_C( 4957), UINT16_C(41811), UINT16_C(51015) }, { UINT16_C(59273), UINT16_C( 4298), UINT16_C(49245), UINT16_C(12457), UINT16_C( 9266), UINT16_C(63245), UINT16_C(54364), UINT16_C(48082) } }, { { UINT16_C(59723), UINT16_C(52670), UINT16_C(65317), UINT16_C(47519), UINT16_C( 5778), UINT16_C(40634), UINT16_C(42594), UINT16_C(50652) }, { UINT16_C(60031), UINT16_C(18331), UINT16_C(34981), UINT16_C(54710), UINT16_C( 5075), UINT16_C( 9960), UINT16_C(12470), UINT16_C( 494) }, { UINT16_C(65382), UINT16_C(17169), UINT16_C(15168), UINT16_C(61940), UINT16_C( 351), UINT16_C(15337), UINT16_C(15062), UINT16_C(25079) } }, { { UINT16_C(44057), UINT16_C(16335), UINT16_C(28331), UINT16_C(15864), UINT16_C(45700), UINT16_C(59099), UINT16_C(46936), UINT16_C(55467) }, { UINT16_C(18082), UINT16_C(18207), UINT16_C(54735), UINT16_C(41500), UINT16_C( 1513), UINT16_C(40905), UINT16_C(46901), UINT16_C(20129) }, { UINT16_C(12987), UINT16_C(64600), UINT16_C(52334), UINT16_C(52718), UINT16_C(22093), UINT16_C( 9097), UINT16_C( 17), UINT16_C(17669) } }, { { UINT16_C(28771), UINT16_C( 3981), UINT16_C(34270), UINT16_C(25164), UINT16_C(10296), UINT16_C(36936), UINT16_C(62687), UINT16_C(33128) }, { UINT16_C(34618), UINT16_C( 2505), UINT16_C(58717), UINT16_C(18092), UINT16_C(30186), UINT16_C( 8165), UINT16_C(34348), UINT16_C(36718) }, { UINT16_C(62612), UINT16_C( 738), UINT16_C(53312), UINT16_C( 3536), UINT16_C(55591), UINT16_C(14385), UINT16_C(14169), UINT16_C(63741) } }, { { UINT16_C(64502), UINT16_C(54430), UINT16_C(60289), UINT16_C(47414), UINT16_C(32531), UINT16_C(62025), UINT16_C(45683), UINT16_C(44404) }, { UINT16_C(15673), UINT16_C(38583), UINT16_C(25378), UINT16_C( 3548), UINT16_C(49880), UINT16_C( 1068), UINT16_C(39496), UINT16_C(16275) }, { UINT16_C(24414), UINT16_C( 7923), UINT16_C(17455), UINT16_C(21933), UINT16_C(56861), UINT16_C(30478), UINT16_C( 3093), UINT16_C(14064) } }, { { UINT16_C(12950), UINT16_C( 5907), UINT16_C(18973), UINT16_C(12496), UINT16_C( 6601), UINT16_C(15394), UINT16_C(38603), UINT16_C( 1513) }, { UINT16_C(41171), UINT16_C(63131), UINT16_C(30723), UINT16_C(56067), UINT16_C(12090), UINT16_C(33503), UINT16_C(29642), UINT16_C(24769) }, { UINT16_C(51425), UINT16_C(36924), UINT16_C(59661), UINT16_C(43750), UINT16_C(62791), UINT16_C(56481), UINT16_C( 4480), UINT16_C(53908) } }, { { UINT16_C(54693), UINT16_C(49783), UINT16_C(18207), UINT16_C(59634), UINT16_C( 5216), UINT16_C(11300), UINT16_C( 3499), UINT16_C(32305) }, { UINT16_C(52398), UINT16_C(45428), UINT16_C(30532), UINT16_C(32397), UINT16_C(27815), UINT16_C(28929), UINT16_C(49887), UINT16_C(34001) }, { UINT16_C( 1147), UINT16_C( 2177), UINT16_C(59373), UINT16_C(13618), UINT16_C(54236), UINT16_C(56721), UINT16_C(42342), UINT16_C(64688) } }, { { UINT16_C(18583), UINT16_C(46662), UINT16_C(14479), UINT16_C(61342), UINT16_C(49741), UINT16_C(63515), UINT16_C(19664), UINT16_C(32374) }, { UINT16_C(60185), UINT16_C(23855), UINT16_C(48226), UINT16_C( 2524), UINT16_C(56617), UINT16_C( 2170), UINT16_C(19359), UINT16_C(14221) }, { UINT16_C(44735), UINT16_C(11403), UINT16_C(48662), UINT16_C(29409), UINT16_C(62098), UINT16_C(30672), UINT16_C( 152), UINT16_C( 9076) } } }; for (size_t i = 0 ; i < (sizeof(test_vec) / sizeof(test_vec[0])) ; i++) { simde_uint16x8_t a = simde_vld1q_u16(test_vec[i].a); simde_uint16x8_t b = simde_vld1q_u16(test_vec[i].b); simde_uint16x8_t r = simde_vhsubq_u16(a, b); simde_test_arm_neon_assert_equal_u16x8(r, simde_vld1q_u16(test_vec[i].r)); } return 0; #else fputc('\n', stdout); for (int i = 0 ; i < 8 ; i++) { simde_uint16x8_t a = simde_test_arm_neon_random_u16x8(); simde_uint16x8_t b = simde_test_arm_neon_random_u16x8(); simde_uint16x8_t r = simde_vhsubq_u16(a, b); simde_test_arm_neon_write_u16x8(2, a, SIMDE_TEST_VEC_POS_FIRST); simde_test_arm_neon_write_u16x8(2, b, SIMDE_TEST_VEC_POS_MIDDLE); simde_test_arm_neon_write_u16x8(2, r, SIMDE_TEST_VEC_POS_LAST); } return 1; #endif } static int test_simde_vhsubq_u32 (SIMDE_MUNIT_TEST_ARGS) { #if 1 static const struct { uint32_t a[4]; uint32_t b[4]; uint32_t r[4]; } test_vec[] = { { { UINT32_C( 586011539), UINT32_C(1494387724), UINT32_C( 508636494), UINT32_C(2476525434) }, { UINT32_C( 368102578), UINT32_C(2971585672), UINT32_C(1236965801), UINT32_C(2021672932) }, { UINT32_C( 108954480), UINT32_C(3556368322), UINT32_C(3930802642), UINT32_C( 227426251) } }, { { UINT32_C( 647654682), UINT32_C(1216326905), UINT32_C(1416024282), UINT32_C(1256653720) }, { UINT32_C(1465898959), UINT32_C(1292467876), UINT32_C(4220961559), UINT32_C( 611522058) }, { UINT32_C(3885845157), UINT32_C(4256896810), UINT32_C(2892498657), UINT32_C( 322565831) } }, { { UINT32_C(2102070916), UINT32_C(2495990458), UINT32_C( 870853787), UINT32_C(4269657903) }, { UINT32_C(1263918503), UINT32_C(1922588251), UINT32_C( 728575777), UINT32_C(3377520965) }, { UINT32_C( 419076206), UINT32_C( 286701103), UINT32_C( 71139005), UINT32_C( 446068469) } }, { { UINT32_C(2840042479), UINT32_C( 4066405), UINT32_C(1731405368), UINT32_C(2640687606) }, { UINT32_C(3924343694), UINT32_C( 995852313), UINT32_C(4117153967), UINT32_C(2562635433) }, { UINT32_C(3752816688), UINT32_C(3799074342), UINT32_C(3102092996), UINT32_C( 39026086) } }, { { UINT32_C(3074557265), UINT32_C(1253539858), UINT32_C(2628971430), UINT32_C( 708384668) }, { UINT32_C(3960676818), UINT32_C(1361538722), UINT32_C(3762720054), UINT32_C(2507670852) }, { UINT32_C(3851907519), UINT32_C(4240967864), UINT32_C(3728092984), UINT32_C(3395324204) } }, { { UINT32_C( 474790410), UINT32_C(3781624890), UINT32_C(2340231663), UINT32_C( 62240560) }, { UINT32_C(2062534872), UINT32_C(1825314358), UINT32_C(3880522403), UINT32_C( 578667799) }, { UINT32_C(3501095065), UINT32_C( 978155266), UINT32_C(3524821926), UINT32_C(4036753676) } }, { { UINT32_C(3124676991), UINT32_C(3164317133), UINT32_C(4014414014), UINT32_C(2834496719) }, { UINT32_C(4196590020), UINT32_C(2590502647), UINT32_C( 411218689), UINT32_C(4164616056) }, { UINT32_C(3759010781), UINT32_C( 286907243), UINT32_C(1801597662), UINT32_C(3629907627) } }, { { UINT32_C(2528278984), UINT32_C(3713158430), UINT32_C( 902601317), UINT32_C(1541258902) }, { UINT32_C(2522218399), UINT32_C(4012948718), UINT32_C(3892818544), UINT32_C(2061517489) }, { UINT32_C( 3030292), UINT32_C(4145072152), UINT32_C(2799858682), UINT32_C(4034838002) } } }; for (size_t i = 0 ; i < (sizeof(test_vec) / sizeof(test_vec[0])) ; i++) { simde_uint32x4_t a = simde_vld1q_u32(test_vec[i].a); simde_uint32x4_t b = simde_vld1q_u32(test_vec[i].b); simde_uint32x4_t r = simde_vhsubq_u32(a, b); simde_test_arm_neon_assert_equal_u32x4(r, simde_vld1q_u32(test_vec[i].r)); } return 0; #else fputc('\n', stdout); for (int i = 0 ; i < 8 ; i++) { simde_uint32x4_t a = simde_test_arm_neon_random_u32x4(); simde_uint32x4_t b = simde_test_arm_neon_random_u32x4(); simde_uint32x4_t r = simde_vhsubq_u32(a, b); simde_test_arm_neon_write_u32x4(2, a, SIMDE_TEST_VEC_POS_FIRST); simde_test_arm_neon_write_u32x4(2, b, SIMDE_TEST_VEC_POS_MIDDLE); simde_test_arm_neon_write_u32x4(2, r, SIMDE_TEST_VEC_POS_LAST); } return 1; #endif } SIMDE_TEST_FUNC_LIST_BEGIN SIMDE_TEST_FUNC_LIST_ENTRY(vhsub_s8) SIMDE_TEST_FUNC_LIST_ENTRY(vhsub_s16) SIMDE_TEST_FUNC_LIST_ENTRY(vhsub_s32) SIMDE_TEST_FUNC_LIST_ENTRY(vhsub_u8) SIMDE_TEST_FUNC_LIST_ENTRY(vhsub_u16) SIMDE_TEST_FUNC_LIST_ENTRY(vhsub_u32) SIMDE_TEST_FUNC_LIST_ENTRY(vhsubq_s8) SIMDE_TEST_FUNC_LIST_ENTRY(vhsubq_s16) SIMDE_TEST_FUNC_LIST_ENTRY(vhsubq_s32) SIMDE_TEST_FUNC_LIST_ENTRY(vhsubq_u8) SIMDE_TEST_FUNC_LIST_ENTRY(vhsubq_u16) SIMDE_TEST_FUNC_LIST_ENTRY(vhsubq_u32) SIMDE_TEST_FUNC_LIST_END #include "test-neon-footer.h"
e0e125811fa19a639bfb3ae4d5453c6e9e43e3c4
2308899071a849a199e3b70806b4dd1c396efc8a
/cthelper/ptyfork.h
039d4ed6ad39b780c531783b22c07a3c94520e45
[ "MIT" ]
permissive
cyd01/KiTTY
b0b06d771508668ccbd6316474382b538a65bac0
0e5d8582aad192db96ba240444a6840fa82ccf05
refs/heads/master
2023-08-10T21:25:06.926589
2023-05-23T17:23:03
2023-05-23T17:56:00
154,540,955
1,451
147
NOASSERTION
2023-05-30T17:16:10
2018-10-24T17:26:24
C
UTF-8
C
false
false
195
h
ptyfork.h
#include <sys/types.h> #include <termios.h> pid_t pty_fork(int *ptrfdm, char *slave_name, const struct termios *slave_termios, const struct winsize *slave_winsize);
5b68760b9e6b59b3259f2194df6815ba68e694a0
2b6c614334400e48912225c219905cff845d4dfa
/GluttonousSnake/2_chaos_5lines.c
7d9b9b032429663bcbcad87688b386dd157bbc07
[ "MIT" ]
permissive
RainbowRoad1/Cgame
a7926ab6fc5f64ce2581b060f6f62cc1e6367233
b873244399494e911278593e139ffb4ba4daa8e7
refs/heads/master
2022-08-09T14:45:59.311350
2022-02-09T03:02:11
2022-02-09T03:02:11
228,147,991
955
338
MIT
2022-02-09T03:02:12
2019-12-15T07:47:17
C
UTF-8
C
false
false
1,696
c
2_chaos_5lines.c
main(){int W=15,S=W*W,*m=calloc(S,4),z[2]={0},l=3,c=76,C,i,*p=m;srand(m);f:for( ++l;m[i=rand()%S];);for(m[i]--;C-80;_sleep(99)){for(i=system("cls"),*p=l;i<S;++ i%W||puts("|"))printf(m[i]>0&&m[i]--?"[]":m[i]?"00":" ");if(kbhit())C=getch()& 95,C-1>>2^18||(c^C)&3^2&&(c=C);p=z+c%2,*p+=~-c&2,*p=(--*p+W)%W;p=m+*z+z[1]*W;if (*p<0)goto f;if(*p)break;}} /* 5行贪吃蛇, 343字符(不包含换行符), 在1行80字符限制下仅可能减少代码; IJKL移动, 吃到食物成长, 可穿墙, 吃到自己身体或按下P键时游戏结束; 可自定义蛇头位置(z[0], z[1]), 蛇长(l), 初始方向(c), 地图尺寸(W); 比行数没意思, 较真还得看字符量(雾) 于2020.6.19上传, 2020.10.1补充说明并减少了一点代码量 下面是之前的说明: 2020.6.26:又压了一点...总共358字符,之前的计算忘了去换行符,应该是369个,以下为原话及旧版 使用gcc编译通过(MinGW)(gcc version 8.2.0) 没想到吧,又压缩了很多...总共374字符,修改&增加了很多细节 1.ijkl控制方向(ijkl更方便位运算...至少比wasd方便) 2.不修改窗口大小,直接用换行代替了,如果窗口不够手动拉伸下 3.增加了p键退出(实现这个就加了3个字符,可以改任意键位) 4.更方便修改地图大小,改W的值就行了(但长宽比固定1:1) */ /* main(){int W=15,S=W*W,m[S],z[2]={0},l=3,c='L',C,i=S,*p=m;while(i--)m[i]=0;srand (time(0));*p=l;f:for(++l;m[i=rand()%S];);for(m[i]--;C-80;_sleep(150)){for(*p=l, i=system("cls");i<S;++i%W||puts("|"))printf(m[i]>0&&m[i]--?"[]":m[i]?"00":" ") ;kbhit()&&(C=getch()&95,C-1>>2^18||(c^C)&3^2&&(c=C));p=z+c%2,*p-=~-c&2^2,*p=(++ *p+W)%W;p=&m[*z+z[1]*W];if(*p<0)goto f;if(*p)break;}} */
5953be20cbee98e5a77e9d91353653d7abfabc54
db229415713a206a848429321e19006b212d20d5
/simde/arm/neon/zip.h
830a8d4db1e5703f8dd58e95497c815fc82519c6
[ "MIT", "Apache-2.0", "LicenseRef-scancode-free-unknown" ]
permissive
simd-everywhere/simde
66dd029cbd0b3814b0377c72d953f223d38e7e53
4d55fc25bcfddc0e2f0c744448557a070dd310c9
refs/heads/master
2023-09-04T12:55:25.455223
2023-08-18T12:46:56
2023-08-18T14:53:06
86,497,800
1,570
173
MIT
2023-09-07T13:41:28
2017-03-28T19:14:32
C
UTF-8
C
false
false
7,435
h
zip.h
/* SPDX-License-Identifier: MIT * * 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. * * Copyright: * 2020 Evan Nemerson <evan@nemerson.com> * 2020 Sean Maher <seanptmaher@gmail.com> (Copyright owned by Google, LLC) */ #if !defined(SIMDE_ARM_NEON_ZIP_H) && !defined(SIMDE_BUG_INTEL_857088) #define SIMDE_ARM_NEON_ZIP_H #include "types.h" #include "zip1.h" #include "zip2.h" HEDLEY_DIAGNOSTIC_PUSH SIMDE_DISABLE_UNWANTED_DIAGNOSTICS SIMDE_BEGIN_DECLS_ SIMDE_FUNCTION_ATTRIBUTES simde_float32x2x2_t simde_vzip_f32(simde_float32x2_t a, simde_float32x2_t b) { #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) return vzip_f32(a, b); #else simde_float32x2x2_t r = { { simde_vzip1_f32(a, b), simde_vzip2_f32(a, b) } }; return r; #endif } #if defined(SIMDE_ARM_NEON_A32V7_ENABLE_NATIVE_ALIASES) #undef vzip_f32 #define vzip_f32(a, b) simde_vzip_f32((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde_int8x8x2_t simde_vzip_s8(simde_int8x8_t a, simde_int8x8_t b) { #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) return vzip_s8(a, b); #else simde_int8x8x2_t r = { { simde_vzip1_s8(a, b), simde_vzip2_s8(a, b) } }; return r; #endif } #if defined(SIMDE_ARM_NEON_A32V7_ENABLE_NATIVE_ALIASES) #undef vzip_s8 #define vzip_s8(a, b) simde_vzip_s8((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde_int16x4x2_t simde_vzip_s16(simde_int16x4_t a, simde_int16x4_t b) { #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) return vzip_s16(a, b); #else simde_int16x4x2_t r = { { simde_vzip1_s16(a, b), simde_vzip2_s16(a, b) } }; return r; #endif } #if defined(SIMDE_ARM_NEON_A32V7_ENABLE_NATIVE_ALIASES) #undef vzip_s16 #define vzip_s16(a, b) simde_vzip_s16((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde_int32x2x2_t simde_vzip_s32(simde_int32x2_t a, simde_int32x2_t b) { #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) return vzip_s32(a, b); #else simde_int32x2x2_t r = { { simde_vzip1_s32(a, b), simde_vzip2_s32(a, b) } }; return r; #endif } #if defined(SIMDE_ARM_NEON_A32V7_ENABLE_NATIVE_ALIASES) #undef vzip_s32 #define vzip_s32(a, b) simde_vzip_s32((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde_uint8x8x2_t simde_vzip_u8(simde_uint8x8_t a, simde_uint8x8_t b) { #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) return vzip_u8(a, b); #else simde_uint8x8x2_t r = { { simde_vzip1_u8(a, b), simde_vzip2_u8(a, b) } }; return r; #endif } #if defined(SIMDE_ARM_NEON_A32V7_ENABLE_NATIVE_ALIASES) #undef vzip_u8 #define vzip_u8(a, b) simde_vzip_u8((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde_uint16x4x2_t simde_vzip_u16(simde_uint16x4_t a, simde_uint16x4_t b) { #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) return vzip_u16(a, b); #else simde_uint16x4x2_t r = { { simde_vzip1_u16(a, b), simde_vzip2_u16(a, b) } }; return r; #endif } #if defined(SIMDE_ARM_NEON_A32V7_ENABLE_NATIVE_ALIASES) #undef vzip_u16 #define vzip_u16(a, b) simde_vzip_u16((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde_uint32x2x2_t simde_vzip_u32(simde_uint32x2_t a, simde_uint32x2_t b) { #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) return vzip_u32(a, b); #else simde_uint32x2x2_t r = { { simde_vzip1_u32(a, b), simde_vzip2_u32(a, b) } }; return r; #endif } #if defined(SIMDE_ARM_NEON_A32V7_ENABLE_NATIVE_ALIASES) #undef vzip_u32 #define vzip_u32(a, b) simde_vzip_u32((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde_float32x4x2_t simde_vzipq_f32(simde_float32x4_t a, simde_float32x4_t b) { #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) return vzipq_f32(a, b); #else simde_float32x4x2_t r = { { simde_vzip1q_f32(a, b), simde_vzip2q_f32(a, b) } }; return r; #endif } #if defined(SIMDE_ARM_NEON_A32V7_ENABLE_NATIVE_ALIASES) #undef vzipq_f32 #define vzipq_f32(a, b) simde_vzipq_f32((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde_int8x16x2_t simde_vzipq_s8(simde_int8x16_t a, simde_int8x16_t b) { #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) return vzipq_s8(a, b); #else simde_int8x16x2_t r = { { simde_vzip1q_s8(a, b), simde_vzip2q_s8(a, b) } }; return r; #endif } #if defined(SIMDE_ARM_NEON_A32V7_ENABLE_NATIVE_ALIASES) #undef vzipq_s8 #define vzipq_s8(a, b) simde_vzipq_s8((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde_int16x8x2_t simde_vzipq_s16(simde_int16x8_t a, simde_int16x8_t b) { #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) return vzipq_s16(a, b); #else simde_int16x8x2_t r = { { simde_vzip1q_s16(a, b), simde_vzip2q_s16(a, b) } }; return r; #endif } #if defined(SIMDE_ARM_NEON_A32V7_ENABLE_NATIVE_ALIASES) #undef vzipq_s16 #define vzipq_s16(a, b) simde_vzipq_s16((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde_int32x4x2_t simde_vzipq_s32(simde_int32x4_t a, simde_int32x4_t b) { #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) return vzipq_s32(a, b); #else simde_int32x4x2_t r = { { simde_vzip1q_s32(a, b), simde_vzip2q_s32(a, b) } }; return r; #endif } #if defined(SIMDE_ARM_NEON_A32V7_ENABLE_NATIVE_ALIASES) #undef vzipq_s32 #define vzipq_s32(a, b) simde_vzipq_s32((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde_uint8x16x2_t simde_vzipq_u8(simde_uint8x16_t a, simde_uint8x16_t b) { #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) return vzipq_u8(a, b); #else simde_uint8x16x2_t r = { { simde_vzip1q_u8(a, b), simde_vzip2q_u8(a, b) } }; return r; #endif } #if defined(SIMDE_ARM_NEON_A32V7_ENABLE_NATIVE_ALIASES) #undef vzipq_u8 #define vzipq_u8(a, b) simde_vzipq_u8((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde_uint16x8x2_t simde_vzipq_u16(simde_uint16x8_t a, simde_uint16x8_t b) { #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) return vzipq_u16(a, b); #else simde_uint16x8x2_t r = { { simde_vzip1q_u16(a, b), simde_vzip2q_u16(a, b) } }; return r; #endif } #if defined(SIMDE_ARM_NEON_A32V7_ENABLE_NATIVE_ALIASES) #undef vzipq_u16 #define vzipq_u16(a, b) simde_vzipq_u16((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde_uint32x4x2_t simde_vzipq_u32(simde_uint32x4_t a, simde_uint32x4_t b) { #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) return vzipq_u32(a, b); #else simde_uint32x4x2_t r = { { simde_vzip1q_u32(a, b), simde_vzip2q_u32(a, b) } }; return r; #endif } #if defined(SIMDE_ARM_NEON_A32V7_ENABLE_NATIVE_ALIASES) #undef vzipq_u32 #define vzipq_u32(a, b) simde_vzipq_u32((a), (b)) #endif SIMDE_END_DECLS_ HEDLEY_DIAGNOSTIC_POP #endif /* !defined(SIMDE_ARM_NEON_ZIP_H) */
dc6ef6792830bdf444ae27c6dbf5c14bdf65ac5b
971b2cea2d1c3001aadc8ca1a48110b7db1ed5f2
/deps/abc/src/proof/acec/acec2Mult.c
f9cbe605768037b02813a4dd67084189ff7ed544
[ "LicenseRef-scancode-warranty-disclaimer", "MIT", "MIT-Modern-Variant" ]
permissive
emsec/hal
70ad2921739967d914dd458984bd7d6d497d3b0a
e4fae37bec9168a61100eacfda37a1f291b4d0be
refs/heads/master
2023-09-02T20:27:32.909426
2023-09-01T13:03:24
2023-09-01T13:03:24
169,076,171
510
72
MIT
2023-09-01T13:03:26
2019-02-04T12:37:20
C++
UTF-8
C
false
false
52,251
c
acec2Mult.c
/**CFile**************************************************************** FileName [acec2Mult.c] SystemName [ABC: Logic synthesis and verification system.] PackageName [CEC for arithmetic circuits.] Synopsis [Core procedures.] Author [Alan Mishchenko] Affiliation [UC Berkeley] Date [Ver. 1.0. Started - June 20, 2005.] Revision [$Id: acec2Mult.c,v 1.00 2005/06/20 00:00:00 alanmi Exp $] ***********************************************************************/ #include "acecInt.h" #include "misc/vec/vecMem.h" #include "misc/util/utilTruth.h" ABC_NAMESPACE_IMPL_START static int s_nFuncTruths4a = 192; // 0xACC0 -- F(a=0) <== useful static unsigned s_FuncTruths4a[192] = { 0xACC0, 0xCAA0, 0xB8C0, 0xE288, 0xE488, 0xD8A0, 0xBC80, 0xE828, 0xE848, 0xDA80, 0xE680, 0xE860, 0x5CC0, 0x3AA0, 0x74C0, 0x2E88, 0x4E88, 0x72A0, 0x7C40, 0x28E8, 0x48E8, 0x7A20, 0x6E08, 0x60E8, 0xA330, 0xC550, 0x8B0C, 0xD144, 0xB122, 0x8D0A, 0x80BC, 0xD414, 0xB212, 0x80DA, 0x80E6, 0x8E06, 0x5330, 0x3550, 0x470C, 0x1D44, 0x1B22, 0x270A, 0x407C, 0x14D4, 0x12B2, 0x207A, 0x086E, 0x068E, 0xCA0C, 0xAC0A, 0xE230, 0xB822, 0xD844, 0xE450, 0xC0AC, 0xA0CA, 0xE320, 0xB282, 0xD484, 0xE540, 0xCB08, 0x8E82, 0xC0B8, 0x88E2, 0xD940, 0xD490, 0x8E84, 0xAD08, 0xB290, 0xB920, 0x88E4, 0xA0D8, 0xC50C, 0xA30A, 0xD130, 0x8B22, 0x8D44, 0xB150, 0xC05C, 0xA03A, 0xD310, 0x82B2, 0x84D4, 0xB510, 0xC704, 0x828E, 0xC074, 0x882E, 0x9D04, 0x90D4, 0x848E, 0xA702, 0x90B2, 0x9B02, 0x884E, 0xA072, 0xC5FC, 0xA3FA, 0xD1FC, 0x8BEE, 0x8DEE, 0xB1FA, 0xCF5C, 0xAF3A, 0xDF1C, 0x8EBE, 0x8EDE, 0xBF1A, 0xF734, 0xB2BE, 0xF374, 0xBB2E, 0xBF26, 0xB2F6, 0xD4DE, 0xF752, 0xD4F6, 0xDF46, 0xDD4E, 0xF572, 0xCAFC, 0xACFA, 0xE2FC, 0xB8EE, 0xD8EE, 0xE4FA, 0xCFAC, 0xAFCA, 0xEF2C, 0xBE8E, 0xDE8E, 0xEF4A, 0xFB38, 0xBEB2, 0xF3B8, 0xBBE2, 0xFB62, 0xF6B2, 0xDED4, 0xFD58, 0xF6D4, 0xFD64, 0xDDE4, 0xF5D8, 0x0CCA, 0x0AAC, 0x30E2, 0x22B8, 0x44D8, 0x50E4, 0x3E02, 0x2B28, 0x4D48, 0x5E04, 0x7610, 0x7160, 0xF33A, 0xF55C, 0xCF2E, 0xDD74, 0xBB72, 0xAF4E, 0xC2FE, 0xD7D4, 0xB7B2, 0xA4FE, 0x98FE, 0x9F8E, 0x033A, 0x055C, 0x032E, 0x1174, 0x1172, 0x054E, 0x023E, 0x1714, 0x1712, 0x045E, 0x1076, 0x1706, 0xFCCA, 0xFAAC, 0xFCE2, 0xEEB8, 0xEED8, 0xFAE4, 0xFEC2, 0xEBE8, 0xEDE8, 0xFEA4, 0xFE98, 0xF9E8 }; /* static int s_nFuncTruths4 = 192; // 0xF335 -- F(a=1) static unsigned s_FuncTruths4[192] = { 0x0CCA, 0x0AAC, 0x30E2, 0x22B8, 0x44D8, 0x50E4, 0x3E02, 0x2B28, 0x4D48, 0x5E04, 0x7610, 0x7160, 0xF33A, 0xF55C, 0xCF2E, 0xDD74, 0xBB72, 0xAF4E, 0xC2FE, 0xD7D4, 0xB7B2, 0xA4FE, 0x98FE, 0x9F8E, 0x033A, 0x055C, 0x032E, 0x1174, 0x1172, 0x054E, 0x023E, 0x1714, 0x1712, 0x045E, 0x1076, 0x1706, 0xFCCA, 0xFAAC, 0xFCE2, 0xEEB8, 0xEED8, 0xFAE4, 0xFEC2, 0xEBE8, 0xEDE8, 0xFEA4, 0xFE98, 0xF9E8, 0xC0AC, 0xA0CA, 0xC0B8, 0x88E2, 0x88E4, 0xA0D8, 0xCA0C, 0xAC0A, 0xCB08, 0x8E82, 0x8E84, 0xAD08, 0xE320, 0xB282, 0xE230, 0xB822, 0xB920, 0xB290, 0xD484, 0xE540, 0xD490, 0xD940, 0xD844, 0xE450, 0xC05C, 0xA03A, 0xC074, 0x882E, 0x884E, 0xA072, 0xC50C, 0xA30A, 0xC704, 0x828E, 0x848E, 0xA702, 0xD310, 0x82B2, 0xD130, 0x8B22, 0x9B02, 0x90B2, 0x84D4, 0xB510, 0x90D4, 0x9D04, 0x8D44, 0xB150, 0xCF5C, 0xAF3A, 0xF374, 0xBB2E, 0xDD4E, 0xF572, 0xC5FC, 0xA3FA, 0xF734, 0xB2BE, 0xD4DE, 0xF752, 0xDF1C, 0x8EBE, 0xD1FC, 0x8BEE, 0xDF46, 0xD4F6, 0x8EDE, 0xBF1A, 0xB2F6, 0xBF26, 0x8DEE, 0xB1FA, 0xCFAC, 0xAFCA, 0xF3B8, 0xBBE2, 0xDDE4, 0xF5D8, 0xCAFC, 0xACFA, 0xFB38, 0xBEB2, 0xDED4, 0xFD58, 0xEF2C, 0xBE8E, 0xE2FC, 0xB8EE, 0xFD64, 0xF6D4, 0xDE8E, 0xEF4A, 0xF6B2, 0xFB62, 0xD8EE, 0xE4FA, 0xACC0, 0xCAA0, 0xB8C0, 0xE288, 0xE488, 0xD8A0, 0xBC80, 0xE828, 0xE848, 0xDA80, 0xE680, 0xE860, 0x5CC0, 0x3AA0, 0x74C0, 0x2E88, 0x4E88, 0x72A0, 0x7C40, 0x28E8, 0x48E8, 0x7A20, 0x6E08, 0x60E8, 0xA330, 0xC550, 0x8B0C, 0xD144, 0xB122, 0x8D0A, 0x80BC, 0xD414, 0xB212, 0x80DA, 0x80E6, 0x8E06, 0x5330, 0x3550, 0x470C, 0x1D44, 0x1B22, 0x270A, 0x407C, 0x14D4, 0x12B2, 0x207A, 0x086E, 0x068E }; */ static int s_nFuncTruths4b = 48; // 0xF3C0 -- F(a=b) <== useful static unsigned s_FuncTruths4b[48] = { 0xF3C0, 0xF5A0, 0xCFC0, 0xDD88, 0xBB88, 0xAFA0, 0xFC30, 0xFA50, 0xCCF0, 0xD8D8, 0xB8B8, 0xAAF0, 0xF0CC, 0xE4E4, 0xFC0C, 0xEE44, 0xAACC, 0xACAC, 0xE2E2, 0xF0AA, 0xCACA, 0xCCAA, 0xEE22, 0xFA0A, 0x3F0C, 0x5F0A, 0x3F30, 0x7722, 0x7744, 0x5F50, 0x30FC, 0x50FA, 0x33F0, 0x7272, 0x7474, 0x55F0, 0x0FCC, 0x4E4E, 0x0CFC, 0x44EE, 0x55CC, 0x5C5C, 0x2E2E, 0x0FAA, 0x3A3A, 0x33AA, 0x22EE, 0x0AFA }; /* static int s_nFuncTruths4 = 12; // 0x35AC -- F(a!=b) static unsigned s_FuncTruths4[12] = { 0x35AC, 0x53CA, 0x1DB8, 0x47E2, 0x27E4, 0x1BD8, 0x3A5C, 0x5C3A, 0x4E72, 0x2E74, 0x724E, 0x742E }; */ static int s_nFuncTruths4 = 384; // 0x35C0 -- F(b=0, c=0) <== useful static unsigned s_FuncTruths4[384] = { 0x35C0, 0x53A0, 0x1DC0, 0x4788, 0x2788, 0x1BA0, 0x3C50, 0x5A30, 0x1CD0, 0x4878, 0x2878, 0x1AB0, 0x34C4, 0x606C, 0x3C44, 0x660C, 0x268C, 0x286C, 0x606A, 0x52A2, 0x486A, 0x468A, 0x660A, 0x5A22, 0x3AC0, 0x5CA0, 0x2EC0, 0x7488, 0x7288, 0x4EA0, 0x3CA0, 0x5AC0, 0x2CE0, 0x7848, 0x7828, 0x4AE0, 0x38C8, 0x6C60, 0x3C88, 0x66C0, 0x62C8, 0x6C28, 0x6A60, 0x58A8, 0x6A48, 0x64A8, 0x66A0, 0x5A88, 0xC530, 0xA350, 0xD10C, 0x8B44, 0x8D22, 0xB10A, 0xC350, 0xA530, 0xD01C, 0x84B4, 0x82D2, 0xB01A, 0xC434, 0x909C, 0xC344, 0x990C, 0x8C26, 0x82C6, 0x909A, 0xA252, 0x84A6, 0x8A46, 0x990A, 0xA522, 0xCA30, 0xAC50, 0xE20C, 0xB844, 0xD822, 0xE40A, 0xC3A0, 0xA5C0, 0xE02C, 0xB484, 0xD282, 0xE04A, 0xC838, 0x9C90, 0xC388, 0x99C0, 0xC862, 0xC682, 0x9A90, 0xA858, 0xA684, 0xA864, 0x99A0, 0xA588, 0x530C, 0x350A, 0x4730, 0x1D22, 0x1B44, 0x2750, 0x503C, 0x305A, 0x4370, 0x12D2, 0x14B4, 0x2570, 0x434C, 0x06C6, 0x443C, 0x0C66, 0x194C, 0x149C, 0x06A6, 0x252A, 0x129A, 0x192A, 0x0A66, 0x225A, 0xA30C, 0xC50A, 0x8B30, 0xD122, 0xB144, 0x8D50, 0xA03C, 0xC05A, 0x83B0, 0xD212, 0xB414, 0x85D0, 0x838C, 0xC606, 0x883C, 0xC066, 0x91C4, 0x9C14, 0xA606, 0x858A, 0x9A12, 0x91A2, 0xA066, 0x885A, 0xA3FC, 0xC5FA, 0x8BFC, 0xD1EE, 0xB1EE, 0x8DFA, 0xAF3C, 0xCF5A, 0x8FBC, 0xDE1E, 0xBE1E, 0x8FDA, 0xB3BC, 0xF636, 0xBB3C, 0xF366, 0xB3E6, 0xBE36, 0xF656, 0xD5DA, 0xDE56, 0xD5E6, 0xF566, 0xDD5A, 0x53FC, 0x35FA, 0x47FC, 0x1DEE, 0x1BEE, 0x27FA, 0x5F3C, 0x3F5A, 0x4F7C, 0x1EDE, 0x1EBE, 0x2F7A, 0x737C, 0x36F6, 0x773C, 0x3F66, 0x3B6E, 0x36BE, 0x56F6, 0x757A, 0x56DE, 0x5D6E, 0x5F66, 0x775A, 0x3FCA, 0x5FAC, 0x3FE2, 0x77B8, 0x77D8, 0x5FE4, 0x3CFA, 0x5AFC, 0x3EF2, 0x7B78, 0x7D78, 0x5EF4, 0x3ECE, 0x6F6C, 0x3CEE, 0x66FC, 0x76DC, 0x7D6C, 0x6F6A, 0x5EAE, 0x7B6A, 0x76BA, 0x66FA, 0x5AEE, 0xC03A, 0xA05C, 0xC02E, 0x8874, 0x8872, 0xA04E, 0xC30A, 0xA50C, 0xC20E, 0x8784, 0x8782, 0xA40E, 0xC232, 0x9390, 0xC322, 0x9930, 0x9832, 0x9382, 0x9590, 0xA454, 0x9584, 0x9854, 0x9950, 0xA544, 0xCF3A, 0xAF5C, 0xF32E, 0xBB74, 0xDD72, 0xF54E, 0xC3FA, 0xA5FC, 0xF23E, 0xB7B4, 0xD7D2, 0xF45E, 0xCE3E, 0x9F9C, 0xC3EE, 0x99FC, 0xDC76, 0xD7C6, 0x9F9A, 0xAE5E, 0xB7A6, 0xBA76, 0x99FA, 0xA5EE, 0x30CA, 0x50AC, 0x0CE2, 0x44B8, 0x22D8, 0x0AE4, 0x3C0A, 0x5A0C, 0x0EC2, 0x4B48, 0x2D28, 0x0EA4, 0x32C2, 0x6360, 0x3C22, 0x6630, 0x3298, 0x3928, 0x6560, 0x54A4, 0x5948, 0x5498, 0x6650, 0x5A44, 0xF3AC, 0xF5CA, 0xCFB8, 0xDDE2, 0xBBE4, 0xAFD8, 0xFA3C, 0xFC5A, 0xCBF8, 0xDED2, 0xBEB4, 0xADF8, 0xE3EC, 0xF6C6, 0xEE3C, 0xFC66, 0xB9EC, 0xBE9C, 0xF6A6, 0xE5EA, 0xDE9A, 0xD9EA, 0xFA66, 0xEE5A, 0xF35C, 0xF53A, 0xCF74, 0xDD2E, 0xBB4E, 0xAF72, 0xF53C, 0xF35A, 0xC7F4, 0xD2DE, 0xB4BE, 0xA7F2, 0xD3DC, 0xC6F6, 0xDD3C, 0xCF66, 0x9BCE, 0x9CBE, 0xA6F6, 0xB5BA, 0x9ADE, 0x9DAE, 0xAF66, 0xBB5A, 0x035C, 0x053A, 0x0374, 0x112E, 0x114E, 0x0572, 0x053C, 0x035A, 0x0734, 0x121E, 0x141E, 0x0752, 0x131C, 0x0636, 0x113C, 0x0366, 0x1346, 0x1436, 0x0656, 0x151A, 0x1256, 0x1526, 0x0566, 0x115A, 0x03AC, 0x05CA, 0x03B8, 0x11E2, 0x11E4, 0x05D8, 0x0A3C, 0x0C5A, 0x0B38, 0x1E12, 0x1E14, 0x0D58, 0x232C, 0x3606, 0x223C, 0x3066, 0x3164, 0x3614, 0x5606, 0x454A, 0x5612, 0x5162, 0x5066, 0x445A }; /* static int s_nFuncTruths4 = 96; // 0xFD80 -- F(d=0) static unsigned s_FuncTruths4[96] = { 0xFD80, 0xFB80, 0xEF80, 0xF8D0, 0xF8B0, 0xE8F0, 0xECC4, 0xE8CC, 0xEC8C, 0xE8AA, 0xEAA2, 0xEA8A, 0xFE40, 0xFE20, 0xFE08, 0xF4E0, 0xF2E0, 0xF0E8, 0xDCC8, 0xCCE8, 0xCEC8, 0xAAE8, 0xBAA8, 0xAEA8, 0xF720, 0xF740, 0xDF08, 0xDF40, 0xBF20, 0xBF08, 0xF270, 0xF470, 0xD0F8, 0xD4F0, 0xB2F0, 0xB0F8, 0xC4EC, 0xD4CC, 0xCE4C, 0xDC4C, 0x8CEC, 0x8ECC, 0xB2AA, 0xA2EA, 0x8EAA, 0x8AEA, 0xBA2A, 0xAE2A, 0xFB10, 0xFD10, 0xEF04, 0xFD04, 0xFB02, 0xEF02, 0xF1B0, 0xF1D0, 0xE0F4, 0xF0D4, 0xF0B2, 0xE0F2, 0xC8DC, 0xCCD4, 0xCD8C, 0xCDC4, 0xC8CE, 0xCC8E, 0xAAB2, 0xA8BA, 0xAA8E, 0xA8AE, 0xABA2, 0xAB8A, 0x7F02, 0x7F04, 0x7F10, 0x70F2, 0x70F4, 0x71F0, 0x4CCE, 0x4DCC, 0x4CDC, 0x2BAA, 0x2AAE, 0x2ABA, 0x40FE, 0x20FE, 0x08FE, 0x4F0E, 0x2F0E, 0x0F8E, 0x7332, 0x33B2, 0x3B32, 0x55D4, 0x7554, 0x5D54, }; */ /* static int s_nFuncTruths4 = 48; // 0xD728 -- F(e=0) static unsigned s_FuncTruths4[48] = { 0xD728, 0xB748, 0x9F60, 0xD278, 0xB478, 0x96F0, 0xC66C, 0x96CC, 0x9C6C, 0x96AA, 0xA66A, 0x9A6A, 0xEB14, 0xED12, 0xF906, 0xE1B4, 0xE1D2, 0xF096, 0xC99C, 0xCC96, 0xC9C6, 0xAA96, 0xA99A, 0xA9A6, 0x7D82, 0x7B84, 0x6F90, 0x78D2, 0x78B4, 0x69F0, 0x6CC6, 0x69CC, 0x6C9C, 0x69AA, 0x6AA6, 0x6A9A, 0x41BE, 0x21DE, 0x09F6, 0x4B1E, 0x2D1E, 0x0F96, 0x6336, 0x3396, 0x3936, 0x5596, 0x6556, 0x5956 }; */ static int s_nFuncTruths5 = 960; // 0xF335ACC0 static unsigned s_FuncTruths5[960] = { 0xF335ACC0, 0xF553CAA0, 0xCF1DB8C0, 0xDD47E288, 0xBB27E488, 0xAF1BD8A0, 0xC1FDBC80, 0xD4D7E828, 0xB2B7E848, 0xA1FBDA80, 0x89EFE680, 0x8E9FE860, 0xF3AC35C0, 0xF5CA53A0, 0xCFB81DC0, 0xDDE24788, 0xBBE42788, 0xAFD81BA0, 0xC1BCFD80, 0xD4E8D728, 0xB2E8B748, 0xA1DAFB80, 0x89E6EF80, 0x8EE89F60, 0xFA3C3C50, 0xFC5A5A30, 0xCB1CF8D0, 0xDE48D278, 0xBE28B478, 0xAD1AF8B0, 0xCBF81CD0, 0xDED24878, 0xBEB42878, 0xADF81AB0, 0x8EE896F0, 0x8E96E8F0, 0xE334ECC4, 0xF660C66C, 0xEE3C3C44, 0xFC66660C, 0xB926EC8C, 0xBE289C6C, 0xE3EC34C4, 0xF6C6606C, 0xB296E8CC, 0xB2E896CC, 0xB9EC268C, 0xBE9C286C, 0xF660A66A, 0xE552EAA2, 0xDE489A6A, 0xD946EA8A, 0xFA66660A, 0xEE5A5A22, 0xD4E896AA, 0xD496E8AA, 0xF6A6606A, 0xE5EA52A2, 0xD9EA468A, 0xDE9A486A, 0xF33A5CC0, 0xF55C3AA0, 0xCF2E74C0, 0xDD742E88, 0xBB724E88, 0xAF4E72A0, 0xC2FE7C40, 0xD7D428E8, 0xB7B248E8, 0xA4FE7A20, 0x98FE6E08, 0x9F8E60E8, 0xF35C3AC0, 0xF53A5CA0, 0xCF742EC0, 0xDD2E7488, 0xBB4E7288, 0xAF724EA0, 0xC27CFE40, 0xD728D4E8, 0xB748B2E8, 0xA47AFE20, 0x986EFE08, 0x9F608EE8, 0xF53C3CA0, 0xF35A5AC0, 0xC72CF4E0, 0xD278DE48, 0xB478BE28, 0xA74AF2E0, 0xC7F42CE0, 0xD2DE7848, 0xB4BE7828, 0xA7F24AE0, 0x96F08EE8, 0x968EF0E8, 0xD338DCC8, 0xC66CF660, 0xDD3C3C88, 0xCF6666C0, 0x9B62CEC8, 0x9C6CBE28, 0xD3DC38C8, 0xC6F66C60, 0x96B2CCE8, 0x96CCB2E8, 0x9BCE62C8, 0x9CBE6C28, 0xA66AF660, 0xB558BAA8, 0x9A6ADE48, 0x9D64AEA8, 0xAF6666A0, 0xBB5A5A88, 0x96AAD4E8, 0x96D4AAE8, 0xA6F66A60, 0xB5BA58A8, 0x9DAE64A8, 0x9ADE6A48, 0xFCC5A330, 0xFAA3C550, 0xFCD18B0C, 0xEE8BD144, 0xEE8DB122, 0xFAB18D0A, 0xFDC180BC, 0xE8EBD414, 0xE8EDB212, 0xFBA180DA, 0xEF8980E6, 0xE8F98E06, 0xFCA3C530, 0xFAC5A350, 0xFC8BD10C, 0xEED18B44, 0xEEB18D22, 0xFA8DB10A, 0xFD80C1BC, 0xE8D4EB14, 0xE8B2ED12, 0xFB80A1DA, 0xEF8089E6, 0xE88EF906, 0xFAC3C350, 0xFCA5A530, 0xF8D0CB1C, 0xED84E1B4, 0xEB82E1D2, 0xF8B0AD1A, 0xF8CBD01C, 0xEDE184B4, 0xEBE182D2, 0xF8ADB01A, 0xE88EF096, 0xE8F08E96, 0xECC4E334, 0xF990C99C, 0xEEC3C344, 0xFC99990C, 0xEC8CB926, 0xEB82C9C6, 0xECE3C434, 0xF9C9909C, 0xE8CCB296, 0xE8B2CC96, 0xECB98C26, 0xEBC982C6, 0xF990A99A, 0xEAA2E552, 0xED84A9A6, 0xEA8AD946, 0xFA99990A, 0xEEA5A522, 0xE8D4AA96, 0xE8AAD496, 0xF9A9909A, 0xEAE5A252, 0xEAD98A46, 0xEDA984A6, 0xFCCA5330, 0xFAAC3550, 0xFCE2470C, 0xEEB81D44, 0xEED81B22, 0xFAE4270A, 0xFEC2407C, 0xEBE814D4, 0xEDE812B2, 0xFEA4207A, 0xFE98086E, 0xF9E8068E, 0xFC53CA30, 0xFA35AC50, 0xFC47E20C, 0xEE1DB844, 0xEE1BD822, 0xFA27E40A, 0xFE40C27C, 0xEB14E8D4, 0xED12E8B2, 0xFE20A47A, 0xFE08986E, 0xF906E88E, 0xF5C3C3A0, 0xF3A5A5C0, 0xF4E0C72C, 0xE1B4ED84, 0xE1D2EB82, 0xF2E0A74A, 0xF4C7E02C, 0xE1EDB484, 0xE1EBD282, 0xF2A7E04A, 0xF096E88E, 0xF0E8968E, 0xDCC8D338, 0xC99CF990, 0xDDC3C388, 0xCF9999C0, 0xCEC89B62, 0xC9C6EB82, 0xDCD3C838, 0xC9F99C90, 0xCCE896B2, 0xCC96E8B2, 0xCE9BC862, 0xC9EBC682, 0xA99AF990, 0xBAA8B558, 0xA9A6ED84, 0xAEA89D64, 0xAF9999A0, 0xBBA5A588, 0xAA96E8D4, 0xAAE896D4, 0xA9F99A90, 0xBAB5A858, 0xAE9DA864, 0xA9EDA684, 0x3F53CA0C, 0x5F35AC0A, 0x3F47E230, 0x771DB822, 0x771BD844, 0x5F27E450, 0x35F3C0AC, 0x53F5A0CA, 0x34F7E320, 0x717DB282, 0x717BD484, 0x52F7E540, 0x1CDFCB08, 0x4D7D8E82, 0x1DCFC0B8, 0x47DD88E2, 0x46DFD940, 0x4D6FD490, 0x2B7B8E84, 0x1ABFAD08, 0x2B6FB290, 0x26BFB920, 0x27BB88E4, 0x1BAFA0D8, 0x3FCA530C, 0x5FAC350A, 0x3FE24730, 0x77B81D22, 0x77D81B44, 0x5FE42750, 0x35C0F3AC, 0x53A0F5CA, 0x34E3F720, 0x71B27D82, 0x71D47B84, 0x52E5F740, 0x1CCBDF08, 0x4D8E7D82, 0x1DC0CFB8, 0x4788DDE2, 0x46D9DF40, 0x4DD46F90, 0x2B8E7B84, 0x1AADBF08, 0x2BB26F90, 0x26B9BF20, 0x2788BBE4, 0x1BA0AFD8, 0x3C50FA3C, 0x5A30FC5A, 0x3E43F270, 0x7B1278D2, 0x7D1478B4, 0x5E25F470, 0x3CFA503C, 0x5AFC305A, 0x3EF24370, 0x7B7812D2, 0x7D7814B4, 0x5EF42570, 0x1CD0CBF8, 0x4878DED2, 0x1CCBD0F8, 0x48DE78D2, 0x4DD469F0, 0x4D69D4F0, 0x2878BEB4, 0x1AB0ADF8, 0x2B69B2F0, 0x2BB269F0, 0x28BE78B4, 0x1AADB0F8, 0x3E43CE4C, 0x6F066CC6, 0x3C44EE3C, 0x660CFC66, 0x7619DC4C, 0x7D146C9C, 0x34E3C4EC, 0x60F66CC6, 0x34C4E3EC, 0x606CF6C6, 0x7169D4CC, 0x71D469CC, 0x3ECE434C, 0x6F6C06C6, 0x3CEE443C, 0x66FC0C66, 0x76DC194C, 0x7D6C149C, 0x2B698ECC, 0x2B8E69CC, 0x286CBE9C, 0x268CB9EC, 0x26B98CEC, 0x28BE6C9C, 0x6F066AA6, 0x5E25AE2A, 0x7B126A9A, 0x7619BA2A, 0x660AFA66, 0x5A22EE5A, 0x60F66AA6, 0x52E5A2EA, 0x71B269AA, 0x7169B2AA, 0x606AF6A6, 0x52A2E5EA, 0x4D8E69AA, 0x4D698EAA, 0x48DE6A9A, 0x46D98AEA, 0x468AD9EA, 0x486ADE9A, 0x6F6A06A6, 0x5EAE252A, 0x7B6A129A, 0x76BA192A, 0x66FA0A66, 0x5AEE225A, 0x3FA3C50C, 0x5FC5A30A, 0x3F8BD130, 0x77D18B22, 0x77B18D44, 0x5F8DB150, 0x3AF3C05C, 0x5CF5A03A, 0x38FBD310, 0x7D7182B2, 0x7B7184D4, 0x58FDB510, 0x2CEFC704, 0x7D4D828E, 0x2ECFC074, 0x74DD882E, 0x64FD9D04, 0x6F4D90D4, 0x7B2B848E, 0x4AEFA702, 0x6F2B90B2, 0x62FB9B02, 0x72BB884E, 0x4EAFA072, 0x3FC5A30C, 0x5FA3C50A, 0x3FD18B30, 0x778BD122, 0x778DB144, 0x5FB18D50, 0x3AC0F35C, 0x5CA0F53A, 0x38D3FB10, 0x7D8271B2, 0x7B8471D4, 0x58B5FD10, 0x2CC7EF04, 0x7D824D8E, 0x2EC0CF74, 0x7488DD2E, 0x649DFD04, 0x6F904DD4, 0x7B842B8E, 0x4AA7EF02, 0x6F902BB2, 0x629BFB02, 0x7288BB4E, 0x4EA0AF72, 0x3CA0F53C, 0x5AC0F35A, 0x3D83F1B0, 0x78D27B12, 0x78B47D14, 0x5B85F1D0, 0x3CF5A03C, 0x5AF3C05A, 0x3DF183B0, 0x787BD212, 0x787DB414, 0x5BF185D0, 0x2CE0C7F4, 0x7848D2DE, 0x2CC7E0F4, 0x78D248DE, 0x69F04DD4, 0x694DF0D4, 0x7828B4BE, 0x4AE0A7F2, 0x692BF0B2, 0x69F02BB2, 0x78B428BE, 0x4AA7E0F2, 0x3D83CD8C, 0x6CC66F06, 0x3C88DD3C, 0x66C0CF66, 0x6791CDC4, 0x6C9C7D14, 0x38D3C8DC, 0x6CC660F6, 0x38C8D3DC, 0x6C60C6F6, 0x6971CCD4, 0x69CC71D4, 0x3DCD838C, 0x6C6FC606, 0x3CDD883C, 0x66CFC066, 0x67CD91C4, 0x6C7D9C14, 0x692BCC8E, 0x69CC2B8E, 0x6C289CBE, 0x62C89BCE, 0x629BC8CE, 0x6C9C28BE, 0x6AA66F06, 0x5B85AB8A, 0x6A9A7B12, 0x6791ABA2, 0x66A0AF66, 0x5A88BB5A, 0x6AA660F6, 0x58B5A8BA, 0x69AA71B2, 0x6971AAB2, 0x6A60A6F6, 0x58A8B5BA, 0x69AA4D8E, 0x694DAA8E, 0x6A9A48DE, 0x649DA8AE, 0x64A89DAE, 0x6A489ADE, 0x6A6FA606, 0x5BAB858A, 0x6A7B9A12, 0x67AB91A2, 0x66AFA066, 0x5ABB885A, 0x30A3C5FC, 0x50C5A3FA, 0x0C8BD1FC, 0x44D18BEE, 0x22B18DEE, 0x0A8DB1FA, 0x3A03CF5C, 0x5C05AF3A, 0x08CBDF1C, 0x4D418EBE, 0x2B218EDE, 0x08ADBF1A, 0x20E3F734, 0x7141B2BE, 0x2E03F374, 0x7411BB2E, 0x20B9BF26, 0x2B09B2F6, 0x7121D4DE, 0x40E5F752, 0x4D09D4F6, 0x40D9DF46, 0x7211DD4E, 0x4E05F572, 0x30C5A3FC, 0x50A3C5FA, 0x0CD18BFC, 0x448BD1EE, 0x228DB1EE, 0x0AB18DFA, 0x3ACF035C, 0x5CAF053A, 0x08DFCB1C, 0x4D8E41BE, 0x2B8E21DE, 0x08BFAD1A, 0x20F7E334, 0x71B241BE, 0x2EF30374, 0x74BB112E, 0x20BFB926, 0x2BB209F6, 0x71D421DE, 0x40F7E552, 0x4DD409F6, 0x40DFD946, 0x72DD114E, 0x4EF50572, 0x3CAF053C, 0x5ACF035A, 0x0D8FC1BC, 0x48DE4B1E, 0x28BE2D1E, 0x0B8FA1DA, 0x3C05AF3C, 0x5A03CF5A, 0x0DC18FBC, 0x484BDE1E, 0x282DBE1E, 0x0BA18FDA, 0x2FE30734, 0x7B4B121E, 0x2F07E334, 0x7B124B1E, 0x2BB20F96, 0x2B0FB296, 0x7D2D141E, 0x4FE50752, 0x4D0FD496, 0x4DD40F96, 0x7D142D1E, 0x4F07E552, 0x31B3C1BC, 0x60F66336, 0x3CBB113C, 0x66F30366, 0x23B389E6, 0x28BE3936, 0x3B13CB1C, 0x6F066336, 0x3BCB131C, 0x6F630636, 0x2B338E96, 0x2B8E3396, 0x31C1B3BC, 0x6063F636, 0x3C11BB3C, 0x6603F366, 0x2389B3E6, 0x2839BE36, 0x7133D496, 0x71D43396, 0x7D391436, 0x73D91346, 0x7313D946, 0x7D143936, 0x60F66556, 0x51D5A1DA, 0x48DE5956, 0x45D589E6, 0x66F50566, 0x5ADD115A, 0x6F066556, 0x5D15AD1A, 0x4D8E5596, 0x4D558E96, 0x6F650656, 0x5DAD151A, 0x71B25596, 0x7155B296, 0x7B125956, 0x7515B926, 0x75B91526, 0x7B591256, 0x6065F656, 0x51A1D5DA, 0x4859DE56, 0x4589D5E6, 0x6605F566, 0x5A11DD5A, 0x3053CAFC, 0x5035ACFA, 0x0C47E2FC, 0x441DB8EE, 0x221BD8EE, 0x0A27E4FA, 0x3503CFAC, 0x5305AFCA, 0x04C7EF2C, 0x414DBE8E, 0x212BDE8E, 0x02A7EF4A, 0x10D3FB38, 0x4171BEB2, 0x1D03F3B8, 0x4711BBE2, 0x029BFB62, 0x092BF6B2, 0x2171DED4, 0x10B5FD58, 0x094DF6D4, 0x049DFD64, 0x2711DDE4, 0x1B05F5D8, 0x30CA53FC, 0x50AC35FA, 0x0CE247FC, 0x44B81DEE, 0x22D81BEE, 0x0AE427FA, 0x35CF03AC, 0x53AF05CA, 0x04EFC72C, 0x41BE4D8E, 0x21DE2B8E, 0x02EFA74A, 0x10FBD338, 0x41BE71B2, 0x1DF303B8, 0x47BB11E2, 0x02FB9B62, 0x09F62BB2, 0x21DE71D4, 0x10FDB558, 0x09F64DD4, 0x04FD9D64, 0x27DD11E4, 0x1BF505D8, 0x3C5F0A3C, 0x5A3F0C5A, 0x0E4FC27C, 0x4B1E48DE, 0x2D1E28BE, 0x0E2FA47A, 0x3C0A5F3C, 0x5A0C3F5A, 0x0EC24F7C, 0x4B481EDE, 0x2D281EBE, 0x0EA42F7A, 0x1FD30B38, 0x4B7B1E12, 0x1F0BD338, 0x4B1E7B12, 0x0F962BB2, 0x0F2B96B2, 0x2D7D1E14, 0x1FB50D58, 0x0F4D96D4, 0x0F964DD4, 0x2D1E7D14, 0x1F0DB558, 0x3273C27C, 0x633660F6, 0x3C77223C, 0x663F3066, 0x323B986E, 0x393628BE, 0x3723C72C, 0x63366F06, 0x37C7232C, 0x636F3606, 0x332B968E, 0x33962B8E, 0x32C2737C, 0x636036F6, 0x3C22773C, 0x66303F66, 0x32983B6E, 0x392836BE, 0x337196D4, 0x339671D4, 0x397D3614, 0x379D3164, 0x37319D64, 0x39367D14, 0x655660F6, 0x5475A47A, 0x595648DE, 0x545D986E, 0x665F5066, 0x5A77445A, 0x65566F06, 0x5745A74A, 0x55964D8E, 0x554D968E, 0x656F5606, 0x57A7454A, 0x559671B2, 0x557196B2, 0x59567B12, 0x57519B62, 0x579B5162, 0x597B5612, 0x656056F6, 0x54A4757A, 0x594856DE, 0x54985D6E, 0x66505F66, 0x5A44775A, 0x533F0CCA, 0x355F0AAC, 0x473F30E2, 0x1D7722B8, 0x1B7744D8, 0x275F50E4, 0x437F3E02, 0x17D72B28, 0x17B74D48, 0x257F5E04, 0x197F7610, 0x179F7160, 0x530C3FCA, 0x350A5FAC, 0x47303FE2, 0x1D2277B8, 0x1B4477D8, 0x27505FE4, 0x433E7F02, 0x172BD728, 0x174DB748, 0x255E7F04, 0x19767F10, 0x17719F60, 0x503C3CFA, 0x305A5AFC, 0x433E70F2, 0x127BD278, 0x147DB478, 0x255E70F4, 0x43703EF2, 0x12D27B78, 0x14B47D78, 0x25705EF4, 0x177196F0, 0x179671F0, 0x433E4CCE, 0x066FC66C, 0x443C3CEE, 0x0C6666FC, 0x19764CDC, 0x147D9C6C, 0x434C3ECE, 0x06C66F6C, 0x17964DCC, 0x174D96CC, 0x194C76DC, 0x149C7D6C, 0x066FA66A, 0x255E2AAE, 0x127B9A6A, 0x19762ABA, 0x0A6666FA, 0x225A5AEE, 0x172B96AA, 0x17962BAA, 0x06A66F6A, 0x252A5EAE, 0x192A76BA, 0x129A7B6A, 0x5CC0F33A, 0x3AA0F55C, 0x74C0CF2E, 0x2E88DD74, 0x4E88BB72, 0x72A0AF4E, 0x7C40C2FE, 0x28E8D7D4, 0x48E8B7B2, 0x7A20A4FE, 0x6E0898FE, 0x60E89F8E, 0x5CF3C03A, 0x3AF5A05C, 0x74CFC02E, 0x2EDD8874, 0x4EBB8872, 0x72AFA04E, 0x7CC240FE, 0x28D7E8D4, 0x48B7E8B2, 0x7AA420FE, 0x6E9808FE, 0x609FE88E, 0x5FC3C30A, 0x3FA5A50C, 0x7CC24F0E, 0x2D87ED84, 0x4B87EB82, 0x7AA42F0E, 0x7C4FC20E, 0x2DED8784, 0x4BEB8782, 0x7A2FA40E, 0x690FE88E, 0x69E80F8E, 0x7CC27332, 0x3993F990, 0x77C3C322, 0x3F999930, 0x6E983B32, 0x6393EB82, 0x7C73C232, 0x39F99390, 0x69E833B2, 0x6933E8B2, 0x6E3B9832, 0x63EB9382, 0x5995F990, 0x7AA47554, 0x6595ED84, 0x6E985D54, 0x5F999950, 0x77A5A544, 0x6955E8D4, 0x69E855D4, 0x59F99590, 0x7A75A454, 0x6E5D9854, 0x65ED9584, 0x5CCF033A, 0x3AAF055C, 0x74F3032E, 0x2EBB1174, 0x4EDD1172, 0x72F5054E, 0x7F43023E, 0x2BEB1714, 0x4DED1712, 0x7F25045E, 0x7F191076, 0x71F91706, 0x5C03CF3A, 0x3A05AF5C, 0x7403F32E, 0x2E11BB74, 0x4E11DD72, 0x7205F54E, 0x7F02433E, 0x2B17EB14, 0x4D17ED12, 0x7F04255E, 0x7F101976, 0x7117F906, 0x50C3C3FA, 0x30A5A5FC, 0x70F2433E, 0x21B7E1B4, 0x41D7E1D2, 0x70F4255E, 0x7043F23E, 0x21E1B7B4, 0x41E1D7D2, 0x7025F45E, 0x7117F096, 0x71F01796, 0x4CCE433E, 0x099FC99C, 0x44C3C3EE, 0x0C9999FC, 0x4CDC1976, 0x41D7C9C6, 0x4C43CE3E, 0x09C99F9C, 0x4DCC1796, 0x4D17CC96, 0x4C19DC76, 0x41C9D7C6, 0x099FA99A, 0x2AAE255E, 0x21B7A9A6, 0x2ABA1976, 0x0A9999FA, 0x22A5A5EE, 0x2B17AA96, 0x2BAA1796, 0x09A99F9A, 0x2A25AE5E, 0x2A19BA76, 0x21A9B7A6, 0x5330FCCA, 0x3550FAAC, 0x470CFCE2, 0x1D44EEB8, 0x1B22EED8, 0x270AFAE4, 0x407CFEC2, 0x14D4EBE8, 0x12B2EDE8, 0x207AFEA4, 0x086EFE98, 0x068EF9E8, 0x53FC30CA, 0x35FA50AC, 0x47FC0CE2, 0x1DEE44B8, 0x1BEE22D8, 0x27FA0AE4, 0x40FE7CC2, 0x14EBD4E8, 0x12EDB2E8, 0x20FE7AA4, 0x08FE6E98, 0x06F98EE8, 0x5F3C3C0A, 0x3F5A5A0C, 0x4F0E7CC2, 0x1E4BDE48, 0x1E2DBE28, 0x2F0E7AA4, 0x4F7C0EC2, 0x1EDE4B48, 0x1EBE2D28, 0x2F7A0EA4, 0x0F698EE8, 0x0F8E69E8, 0x73327CC2, 0x3663F660, 0x773C3C22, 0x3F666630, 0x3B326E98, 0x3639BE28, 0x737C32C2, 0x36F66360, 0x33B269E8, 0x3369B2E8, 0x3B6E3298, 0x36BE3928, 0x5665F660, 0x75547AA4, 0x5659DE48, 0x5D546E98, 0x5F666650, 0x775A5A44, 0x5569D4E8, 0x55D469E8, 0x56F66560, 0x757A54A4, 0x5D6E5498, 0x56DE5948 }; //////////////////////////////////////////////////////////////////////// /// DECLARATIONS /// //////////////////////////////////////////////////////////////////////// #define SDB_MAX_CUTSIZE 6 #define SDB_MAX_CUTNUM 51 #define SDB_MAX_TT_WORDS ((SDB_MAX_CUTSIZE > 6) ? 1 << (SDB_MAX_CUTSIZE-6) : 1) #define SDB_CUT_NO_LEAF 0xF typedef struct Sdb_Cut_t_ Sdb_Cut_t; struct Sdb_Cut_t_ { word Sign; // signature int iFunc; // functionality int Cost; // cut cost int CostLev; // cut cost unsigned nTreeLeaves : 28; // tree leaves unsigned nLeaves : 4; // leaf count int pLeaves[SDB_MAX_CUTSIZE]; // leaves }; typedef struct Sdb_Sto_t_ Sdb_Sto_t; struct Sdb_Sto_t_ { int nCutSize; int nCutNum; int fCutMin; int fTruthMin; int fVerbose; Gia_Man_t * pGia; // user's AIG manager (will be modified by adding nodes) Vec_Int_t * vRefs; // refs for each node Vec_Wec_t * vCuts; // cuts for each node Vec_Mem_t * vTtMem; // truth tables Sdb_Cut_t pCuts[3][SDB_MAX_CUTNUM]; // temporary cuts Sdb_Cut_t * ppCuts[SDB_MAX_CUTNUM]; // temporary cut pointers int nCutsR; // the number of cuts int Pivot; // current object int iCutBest; // best-delay cut int nCutsOver; // overflow cuts double CutCount[4]; // cut counters abctime clkStart; // starting time }; static inline word * Sdb_CutTruth( Sdb_Sto_t * p, Sdb_Cut_t * pCut ) { return Vec_MemReadEntry(p->vTtMem, Abc_Lit2Var(pCut->iFunc)); } #define Sdb_ForEachCut( pList, pCut, i ) for ( i = 0, pCut = pList + 1; i < pList[0]; i++, pCut += pCut[0] + 2 ) //////////////////////////////////////////////////////////////////////// /// FUNCTION DEFINITIONS /// //////////////////////////////////////////////////////////////////////// /**Function************************************************************* Synopsis [Check correctness of cuts.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ static inline word Sdb_CutGetSign( Sdb_Cut_t * pCut ) { word Sign = 0; int i; for ( i = 0; i < (int)pCut->nLeaves; i++ ) Sign |= ((word)1) << (pCut->pLeaves[i] & 0x3F); return Sign; } static inline int Sdb_CutCheck( Sdb_Cut_t * pBase, Sdb_Cut_t * pCut ) // check if pCut is contained in pBase { int nSizeB = pBase->nLeaves; int nSizeC = pCut->nLeaves; int i, * pB = pBase->pLeaves; int k, * pC = pCut->pLeaves; for ( i = 0; i < nSizeC; i++ ) { for ( k = 0; k < nSizeB; k++ ) if ( pC[i] == pB[k] ) break; if ( k == nSizeB ) return 0; } return 1; } static inline int Sdb_CutSetCheckArray( Sdb_Cut_t ** ppCuts, int nCuts ) { Sdb_Cut_t * pCut0, * pCut1; int i, k, m, n, Value; assert( nCuts > 0 ); for ( i = 0; i < nCuts; i++ ) { pCut0 = ppCuts[i]; assert( pCut0->nLeaves <= SDB_MAX_CUTSIZE ); assert( pCut0->Sign == Sdb_CutGetSign(pCut0) ); // check duplicates for ( m = 0; m < (int)pCut0->nLeaves; m++ ) for ( n = m + 1; n < (int)pCut0->nLeaves; n++ ) assert( pCut0->pLeaves[m] < pCut0->pLeaves[n] ); // check pairs for ( k = 0; k < nCuts; k++ ) { pCut1 = ppCuts[k]; if ( pCut0 == pCut1 ) continue; // check containments Value = Sdb_CutCheck( pCut0, pCut1 ); assert( Value == 0 ); } } return 1; } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ static inline int Sdb_CutMergeOrder( Sdb_Cut_t * pCut0, Sdb_Cut_t * pCut1, Sdb_Cut_t * pCut, int nCutSize ) { int nSize0 = pCut0->nLeaves; int nSize1 = pCut1->nLeaves; int i, * pC0 = pCut0->pLeaves; int k, * pC1 = pCut1->pLeaves; int c, * pC = pCut->pLeaves; // the case of the largest cut sizes if ( nSize0 == nCutSize && nSize1 == nCutSize ) { for ( i = 0; i < nSize0; i++ ) { if ( pC0[i] != pC1[i] ) return 0; pC[i] = pC0[i]; } pCut->nLeaves = nCutSize; pCut->iFunc = -1; pCut->Sign = pCut0->Sign | pCut1->Sign; return 1; } // compare two cuts with different numbers i = k = c = 0; if ( nSize0 == 0 ) goto FlushCut1; if ( nSize1 == 0 ) goto FlushCut0; while ( 1 ) { if ( c == nCutSize ) return 0; if ( pC0[i] < pC1[k] ) { pC[c++] = pC0[i++]; if ( i >= nSize0 ) goto FlushCut1; } else if ( pC0[i] > pC1[k] ) { pC[c++] = pC1[k++]; if ( k >= nSize1 ) goto FlushCut0; } else { pC[c++] = pC0[i++]; k++; if ( i >= nSize0 ) goto FlushCut1; if ( k >= nSize1 ) goto FlushCut0; } } FlushCut0: if ( c + nSize0 > nCutSize + i ) return 0; while ( i < nSize0 ) pC[c++] = pC0[i++]; pCut->nLeaves = c; pCut->iFunc = -1; pCut->Sign = pCut0->Sign | pCut1->Sign; return 1; FlushCut1: if ( c + nSize1 > nCutSize + k ) return 0; while ( k < nSize1 ) pC[c++] = pC1[k++]; pCut->nLeaves = c; pCut->iFunc = -1; pCut->Sign = pCut0->Sign | pCut1->Sign; return 1; } static inline int Sdb_CutMergeOrder2( Sdb_Cut_t * pCut0, Sdb_Cut_t * pCut1, Sdb_Cut_t * pCut, int nCutSize ) { int x0, i0 = 0, nSize0 = pCut0->nLeaves, * pC0 = pCut0->pLeaves; int x1, i1 = 0, nSize1 = pCut1->nLeaves, * pC1 = pCut1->pLeaves; int xMin, c = 0, * pC = pCut->pLeaves; while ( 1 ) { x0 = (i0 == nSize0) ? ABC_INFINITY : pC0[i0]; x1 = (i1 == nSize1) ? ABC_INFINITY : pC1[i1]; xMin = Abc_MinInt(x0, x1); if ( xMin == ABC_INFINITY ) break; if ( c == nCutSize ) return 0; pC[c++] = xMin; if (x0 == xMin) i0++; if (x1 == xMin) i1++; } pCut->nLeaves = c; pCut->iFunc = -1; pCut->Sign = pCut0->Sign | pCut1->Sign; return 1; } static inline int Sdb_CutSetCutIsContainedOrder( Sdb_Cut_t * pBase, Sdb_Cut_t * pCut ) // check if pCut is contained in pBase { int i, nSizeB = pBase->nLeaves; int k, nSizeC = pCut->nLeaves; if ( nSizeB == nSizeC ) { for ( i = 0; i < nSizeB; i++ ) if ( pBase->pLeaves[i] != pCut->pLeaves[i] ) return 0; return 1; } assert( nSizeB > nSizeC ); if ( nSizeC == 0 ) return 1; for ( i = k = 0; i < nSizeB; i++ ) { if ( pBase->pLeaves[i] > pCut->pLeaves[k] ) return 0; if ( pBase->pLeaves[i] == pCut->pLeaves[k] ) { if ( ++k == nSizeC ) return 1; } } return 0; } static inline int Sdb_CutSetLastCutIsContained( Sdb_Cut_t ** pCuts, int nCuts ) { int i; for ( i = 0; i < nCuts; i++ ) if ( pCuts[i]->nLeaves <= pCuts[nCuts]->nLeaves && (pCuts[i]->Sign & pCuts[nCuts]->Sign) == pCuts[i]->Sign && Sdb_CutSetCutIsContainedOrder(pCuts[nCuts], pCuts[i]) ) return 1; return 0; } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ static inline int Sdb_CutCompare( Sdb_Cut_t * pCut0, Sdb_Cut_t * pCut1 ) { if ( pCut0->nTreeLeaves < pCut1->nTreeLeaves ) return -1; if ( pCut0->nTreeLeaves > pCut1->nTreeLeaves ) return 1; if ( pCut0->nLeaves < pCut1->nLeaves ) return -1; if ( pCut0->nLeaves > pCut1->nLeaves ) return 1; return 0; } static inline int Sdb_CutSetLastCutContains( Sdb_Cut_t ** pCuts, int nCuts ) { int i, k, fChanges = 0; for ( i = 0; i < nCuts; i++ ) if ( pCuts[nCuts]->nLeaves < pCuts[i]->nLeaves && (pCuts[nCuts]->Sign & pCuts[i]->Sign) == pCuts[nCuts]->Sign && Sdb_CutSetCutIsContainedOrder(pCuts[i], pCuts[nCuts]) ) pCuts[i]->nLeaves = SDB_CUT_NO_LEAF, fChanges = 1; if ( !fChanges ) return nCuts; for ( i = k = 0; i <= nCuts; i++ ) { if ( pCuts[i]->nLeaves == SDB_CUT_NO_LEAF ) continue; if ( k < i ) ABC_SWAP( Sdb_Cut_t *, pCuts[k], pCuts[i] ); k++; } return k - 1; } static inline void Sdb_CutSetSortByCost( Sdb_Cut_t ** pCuts, int nCuts ) { int i; for ( i = nCuts; i > 0; i-- ) { if ( Sdb_CutCompare(pCuts[i - 1], pCuts[i]) < 0 )//!= 1 ) return; ABC_SWAP( Sdb_Cut_t *, pCuts[i - 1], pCuts[i] ); } } static inline int Sdb_CutSetAddCut( Sdb_Cut_t ** pCuts, int nCuts, int nCutNum ) { if ( nCuts == 0 ) return 1; nCuts = Sdb_CutSetLastCutContains(pCuts, nCuts); assert( nCuts >= 0 ); Sdb_CutSetSortByCost( pCuts, nCuts ); // add new cut if there is room return Abc_MinInt( nCuts + 1, nCutNum - 1 ); } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ static inline int Sdb_CutComputeTruth6( Sdb_Sto_t * p, Sdb_Cut_t * pCut0, Sdb_Cut_t * pCut1, int fCompl0, int fCompl1, Sdb_Cut_t * pCutR, int fIsXor ) { int nOldSupp = pCutR->nLeaves, truthId, fCompl; word t; word t0 = *Sdb_CutTruth(p, pCut0); word t1 = *Sdb_CutTruth(p, pCut1); if ( Abc_LitIsCompl(pCut0->iFunc) ^ fCompl0 ) t0 = ~t0; if ( Abc_LitIsCompl(pCut1->iFunc) ^ fCompl1 ) t1 = ~t1; t0 = Abc_Tt6Expand( t0, pCut0->pLeaves, pCut0->nLeaves, pCutR->pLeaves, pCutR->nLeaves ); t1 = Abc_Tt6Expand( t1, pCut1->pLeaves, pCut1->nLeaves, pCutR->pLeaves, pCutR->nLeaves ); t = fIsXor ? t0 ^ t1 : t0 & t1; if ( (fCompl = (int)(t & 1)) ) t = ~t; if ( p->fTruthMin ) pCutR->nLeaves = Abc_Tt6MinBase( &t, pCutR->pLeaves, pCutR->nLeaves ); assert( (int)(t & 1) == 0 ); truthId = Vec_MemHashInsert(p->vTtMem, &t); pCutR->iFunc = Abc_Var2Lit( truthId, fCompl ); assert( (int)pCutR->nLeaves <= nOldSupp ); return (int)pCutR->nLeaves < nOldSupp; } static inline int Sdb_CutComputeTruth( Sdb_Sto_t * p, Sdb_Cut_t * pCut0, Sdb_Cut_t * pCut1, int fCompl0, int fCompl1, Sdb_Cut_t * pCutR, int fIsXor ) { if ( p->nCutSize <= 6 ) return Sdb_CutComputeTruth6( p, pCut0, pCut1, fCompl0, fCompl1, pCutR, fIsXor ); { word uTruth[SDB_MAX_TT_WORDS], uTruth0[SDB_MAX_TT_WORDS], uTruth1[SDB_MAX_TT_WORDS]; int nOldSupp = pCutR->nLeaves, truthId; int nCutSize = p->nCutSize, fCompl; int nWords = Abc_Truth6WordNum(nCutSize); word * pTruth0 = Sdb_CutTruth(p, pCut0); word * pTruth1 = Sdb_CutTruth(p, pCut1); Abc_TtCopy( uTruth0, pTruth0, nWords, Abc_LitIsCompl(pCut0->iFunc) ^ fCompl0 ); Abc_TtCopy( uTruth1, pTruth1, nWords, Abc_LitIsCompl(pCut1->iFunc) ^ fCompl1 ); Abc_TtExpand( uTruth0, nCutSize, pCut0->pLeaves, pCut0->nLeaves, pCutR->pLeaves, pCutR->nLeaves ); Abc_TtExpand( uTruth1, nCutSize, pCut1->pLeaves, pCut1->nLeaves, pCutR->pLeaves, pCutR->nLeaves ); if ( fIsXor ) Abc_TtXor( uTruth, uTruth0, uTruth1, nWords, (fCompl = (int)((uTruth0[0] ^ uTruth1[0]) & 1)) ); else Abc_TtAnd( uTruth, uTruth0, uTruth1, nWords, (fCompl = (int)((uTruth0[0] & uTruth1[0]) & 1)) ); if ( p->fTruthMin ) pCutR->nLeaves = Abc_TtMinBase( uTruth, pCutR->pLeaves, pCutR->nLeaves, nCutSize ); assert( (uTruth[0] & 1) == 0 ); //Kit_DsdPrintFromTruth( uTruth, pCutR->nLeaves ), printf("\n" ), printf("\n" ); truthId = Vec_MemHashInsert(p->vTtMem, uTruth); pCutR->iFunc = Abc_Var2Lit( truthId, fCompl ); assert( (int)pCutR->nLeaves <= nOldSupp ); return (int)pCutR->nLeaves < nOldSupp; } } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ static inline int Sdb_CutCountBits( word i ) { i = i - ((i >> 1) & 0x5555555555555555); i = (i & 0x3333333333333333) + ((i >> 2) & 0x3333333333333333); i = ((i + (i >> 4)) & 0x0F0F0F0F0F0F0F0F); return (i*(0x0101010101010101))>>56; } static inline void Sdb_CutAddUnit( Sdb_Sto_t * p, int iObj ) { Vec_Int_t * vThis = Vec_WecEntry( p->vCuts, iObj ); if ( Vec_IntSize(vThis) == 0 ) Vec_IntPush( vThis, 1 ); else Vec_IntAddToEntry( vThis, 0, 1 ); Vec_IntPush( vThis, 1 ); Vec_IntPush( vThis, iObj ); Vec_IntPush( vThis, 2 ); } static inline void Sdb_CutAddZero( Sdb_Sto_t * p, int iObj ) { Vec_Int_t * vThis = Vec_WecEntry( p->vCuts, iObj ); assert( Vec_IntSize(vThis) == 0 ); Vec_IntPush( vThis, 1 ); Vec_IntPush( vThis, 0 ); Vec_IntPush( vThis, 0 ); } static inline int Sdb_CutTreeLeaves( Sdb_Sto_t * p, Sdb_Cut_t * pCut ) { int i, Cost = 0; for ( i = 0; i < (int)pCut->nLeaves; i++ ) Cost += Vec_IntEntry( p->vRefs, pCut->pLeaves[i] ) == 1; return Cost; } static inline int Sdb_StoPrepareSet( Sdb_Sto_t * p, int iObj, int Index ) { Vec_Int_t * vThis = Vec_WecEntry( p->vCuts, iObj ); int i, v, * pCut, * pList = Vec_IntArray( vThis ); Sdb_ForEachCut( pList, pCut, i ) { Sdb_Cut_t * pCutTemp = &p->pCuts[Index][i]; pCutTemp->nLeaves = pCut[0]; for ( v = 1; v <= pCut[0]; v++ ) pCutTemp->pLeaves[v-1] = pCut[v]; pCutTemp->iFunc = pCut[pCut[0]+1]; pCutTemp->Sign = Sdb_CutGetSign( pCutTemp ); pCutTemp->nTreeLeaves = Sdb_CutTreeLeaves( p, pCutTemp ); } return pList[0]; } static inline void Sdb_StoInitResult( Sdb_Sto_t * p ) { int i; for ( i = 0; i < SDB_MAX_CUTNUM; i++ ) p->ppCuts[i] = &p->pCuts[2][i]; } static inline void Sdb_StoStoreResult( Sdb_Sto_t * p, int iObj, Sdb_Cut_t ** pCuts, int nCuts ) { int i, v; Vec_Int_t * vList = Vec_WecEntry( p->vCuts, iObj ); Vec_IntPush( vList, nCuts ); for ( i = 0; i < nCuts; i++ ) { Vec_IntPush( vList, pCuts[i]->nLeaves ); for ( v = 0; v < (int)pCuts[i]->nLeaves; v++ ) Vec_IntPush( vList, pCuts[i]->pLeaves[v] ); Vec_IntPush( vList, pCuts[i]->iFunc ); } } static inline void Sdb_CutPrint( Sdb_Sto_t * p, int iObj, Sdb_Cut_t * pCut ) { int i, nDigits = Abc_Base10Log(Gia_ManObjNum(p->pGia)); if ( pCut == NULL ) { printf( "No cut.\n" ); return; } printf( "%d {", pCut->nLeaves ); for ( i = 0; i < (int)pCut->nLeaves; i++ ) printf( " %*d", nDigits, pCut->pLeaves[i] ); for ( ; i < (int)p->nCutSize; i++ ) printf( " %*s", nDigits, " " ); printf( " } Cost = %3d CostL = %3d Tree = %d ", pCut->Cost, pCut->CostLev, pCut->nTreeLeaves ); printf( "\n" ); } void Sdb_StoMergeCuts( Sdb_Sto_t * p, int iObj ) { Gia_Obj_t * pObj = Gia_ManObj(p->pGia, iObj); int fIsXor = Gia_ObjIsXor(pObj); int nCutSize = p->nCutSize; int nCutNum = p->nCutNum; int fComp0 = Gia_ObjFaninC0(pObj); int fComp1 = Gia_ObjFaninC1(pObj); int Fan0 = Gia_ObjFaninId0(pObj, iObj); int Fan1 = Gia_ObjFaninId1(pObj, iObj); int nCuts0 = Sdb_StoPrepareSet( p, Fan0, 0 ); int nCuts1 = Sdb_StoPrepareSet( p, Fan1, 1 ); int i, k, nCutsR = 0; Sdb_Cut_t * pCut0, * pCut1, ** pCutsR = p->ppCuts; assert( !Gia_ObjIsBuf(pObj) ); assert( !Gia_ObjIsMux(p->pGia, pObj) ); Sdb_StoInitResult( p ); p->CutCount[0] += nCuts0 * nCuts1; for ( i = 0, pCut0 = p->pCuts[0]; i < nCuts0; i++, pCut0++ ) for ( k = 0, pCut1 = p->pCuts[1]; k < nCuts1; k++, pCut1++ ) { if ( (int)(pCut0->nLeaves + pCut1->nLeaves) > nCutSize && Sdb_CutCountBits(pCut0->Sign | pCut1->Sign) > nCutSize ) continue; p->CutCount[1]++; if ( !Sdb_CutMergeOrder(pCut0, pCut1, pCutsR[nCutsR], nCutSize) ) continue; if ( Sdb_CutSetLastCutIsContained(pCutsR, nCutsR) ) continue; p->CutCount[2]++; if ( p->fCutMin && Sdb_CutComputeTruth(p, pCut0, pCut1, fComp0, fComp1, pCutsR[nCutsR], fIsXor) ) pCutsR[nCutsR]->Sign = Sdb_CutGetSign(pCutsR[nCutsR]); pCutsR[nCutsR]->nTreeLeaves = Sdb_CutTreeLeaves( p, pCutsR[nCutsR] ); nCutsR = Sdb_CutSetAddCut( pCutsR, nCutsR, nCutNum ); } p->CutCount[3] += nCutsR; p->nCutsOver += nCutsR == nCutNum-1; p->nCutsR = nCutsR; p->Pivot = iObj; // debug printout if ( 0 ) { printf( "*** Obj = %4d NumCuts = %4d\n", iObj, nCutsR ); for ( i = 0; i < nCutsR; i++ ) Sdb_CutPrint( p, iObj, pCutsR[i] ); printf( "\n" ); } // verify assert( nCutsR > 0 && nCutsR < nCutNum ); assert( Sdb_CutSetCheckArray(pCutsR, nCutsR) ); // store the cutset Sdb_StoStoreResult( p, iObj, pCutsR, nCutsR ); if ( nCutsR > 1 || pCutsR[0]->nLeaves > 1 ) Sdb_CutAddUnit( p, iObj ); } /**Function************************************************************* Synopsis [Cut comparison.] Description [Find out if there is a cut in vCuts such that pCut has only one extra input. If so, return this input.] SideEffects [] SeeAlso [] ***********************************************************************/ int Sdb_StoDiffExactlyOne( Vec_Wec_t * vCuts, int Limit, int * pCut ) { Vec_Int_t * vCut; int i, k, iNew; // check if it is fully contained in any one Vec_WecForEachLevel( vCuts, vCut, i ) { for ( k = 1; k <= pCut[0]; k++ ) if ( Vec_IntFind(vCut, pCut[k]) == -1 ) break; if ( k == pCut[0] + 1 ) return -1; } // check if there is one different Vec_WecForEachLevel( vCuts, vCut, i ) { if ( i == Limit ) break; for ( iNew = -1, k = 1; k <= pCut[0]; k++ ) { if ( Vec_IntFind(vCut, pCut[k]) >= 0 ) continue; if ( iNew == -1 ) iNew = pCut[k]; else break; } if ( k == pCut[0] + 1 && iNew != -1 ) return iNew; } return -1; } int Sdb_StoDiffExactlyOne3( Vec_Wec_t * vCuts, int Limit, int * pCut, int * pCount ) { Vec_Int_t * vCut; int i, iNewAll = -1, Count = 0; Vec_WecForEachLevel( vCuts, vCut, i ) { int k, iNew = -1; if ( i == Limit ) break; for ( k = 1; k <= pCut[0]; k++ ) { if ( Vec_IntFind(vCut, pCut[k]) >= 0 ) continue; if ( iNew == -1 ) iNew = pCut[k]; else break; } if ( k == pCut[0] + 1 && iNew != -1 ) { if ( iNewAll == -1 ) iNewAll = iNew; if ( iNewAll == iNew ) Count++; } } *pCount = Count; return iNewAll; } Vec_Int_t * Sdb_StoFindAll( Vec_Wec_t * vCuts ) { int i, k, Entry; Vec_Int_t * vCut, * vAll = Vec_IntAlloc( 100 ); Vec_WecForEachLevel( vCuts, vCut, i ) Vec_IntForEachEntry( vCut, Entry, k ) Vec_IntPushUnique( vAll, Entry ); return vAll; } int Sdb_StoDiffExactlyOne2( Vec_Int_t * vAll, int * pCut ) { int k, iNew = -1; for ( k = 1; k <= pCut[0]; k++ ) { if ( Vec_IntFind(vAll, pCut[k]) >= 0 ) continue; if ( iNew == -1 ) iNew = pCut[k]; else break; } if ( k == pCut[0] + 1 && iNew != -1 ) return iNew; return -1; } Vec_Int_t * Sdb_StoFindInputs( Vec_Wec_t * vCuts, int Front ) { int fVerbose = 0; Vec_Int_t * vCut, * vCounts; Vec_Int_t * vRes = Vec_IntAlloc( 100 ); Vec_Int_t * vResA = Vec_IntAlloc( 100 ); Vec_Int_t * vResB = Vec_IntAlloc( 100 ); int i, k, Entry, Max = 0, Min, MinValue; // find MAX value Vec_WecForEachLevel( vCuts, vCut, i ) Vec_IntForEachEntry( vCut, Entry, k ) Max = Abc_MaxInt( Max, Entry ); // count how many times each value appears vCounts = Vec_IntStart( Max + 1 ); Vec_WecForEachLevel( vCuts, vCut, i ) Vec_IntForEachEntry( vCut, Entry, k ) Vec_IntAddToEntry( vCounts, Entry, 1 ); Vec_IntWriteEntry( vCounts, 0, 0 ); // print out if ( fVerbose ) Vec_IntForEachEntry( vCounts, Entry, k ) if ( Entry ) printf( "%5d %5d\n", k, Entry ); // collect first part MinValue = ABC_INFINITY; Vec_IntForEachEntry( vCounts, Entry, k ) if ( Entry ) MinValue = Abc_MinInt( MinValue, Entry ); if ( MinValue == ABC_INFINITY ) return vRes; Min = Vec_IntFind( vCounts, MinValue ); Vec_IntPush( vResA, Min ); Vec_IntWriteEntry( vCounts, Min, 0 ); Vec_IntForEachEntry( vCounts, Entry, k ) if ( Entry == MinValue || Entry == 2*MinValue ) { Vec_IntPush( vResA, k ); Vec_IntWriteEntry( vCounts, k, 0 ); } // collect second parts MinValue = Vec_IntEntry( vCounts, Front ); Min = Front; Vec_IntPush( vResB, Min ); Vec_IntWriteEntry( vCounts, Min, 0 ); Vec_IntForEachEntry( vCounts, Entry, k ) if ( Entry == MinValue || Entry == 2*MinValue ) { Vec_IntPush( vResB, k ); Vec_IntWriteEntry( vCounts, k, 0 ); } Vec_IntFree( vCounts ); Vec_IntPrint( vResA ); Vec_IntPrint( vResB ); // here we need to order the inputs // append Vec_IntAppend( vRes, vResA ); Vec_IntAppend( vRes, vResB ); Vec_IntFree( vResA ); Vec_IntFree( vResB ); return vRes; } /**Function************************************************************* Synopsis [Iterate through the cuts.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Sdb_StoIterCutsOne( Sdb_Sto_t * p, int iObj, int CutSize, int ** ppCut ) { int fVerbose = 0; Vec_Int_t * vThis = Vec_WecEntry( p->vCuts, iObj ); int i, k, * pCut, * pList = Vec_IntArray( vThis ); word * pTruth; Sdb_ForEachCut( pList, pCut, i ) { if ( pCut[0] != CutSize ) continue; if ( pCut[0] == 5 ) { pTruth = Vec_MemReadEntry(p->vTtMem, Abc_Lit2Var(pCut[pCut[0]+1])); for ( k = 0; k < s_nFuncTruths5; k++ ) if ( s_FuncTruths5[k] == (unsigned)*pTruth ) break; if ( k < s_nFuncTruths5 ) { if ( fVerbose ) { printf( "Object %d has %d-input cut: ", iObj, pCut[0] ); for ( k = 1; k <= pCut[0]; k++ ) printf( "%d ", pCut[k] ); printf( "\n" ); } *ppCut = pCut; return 1; // five-input } } if ( pCut[0] == 4 ) { pTruth = Vec_MemReadEntry(p->vTtMem, Abc_Lit2Var(pCut[pCut[0]+1])); for ( k = 0; k < s_nFuncTruths4; k++ ) if ( s_FuncTruths4[k] == (0xFFFF & (unsigned)*pTruth) ) break; if ( k < s_nFuncTruths4 ) { if ( fVerbose ) { printf( "Object %d has %d-input cut: ", iObj, pCut[0] ); for ( k = 1; k <= pCut[0]; k++ ) printf( "%d ", pCut[k] ); printf( "\n" ); } *ppCut = pCut; return 2; // front } } if ( pCut[0] == 4 ) { pTruth = Vec_MemReadEntry(p->vTtMem, Abc_Lit2Var(pCut[pCut[0]+1])); for ( k = 0; k < s_nFuncTruths4a; k++ ) if ( s_FuncTruths4a[k] == (0xFFFF & (unsigned)*pTruth) ) break; if ( k < s_nFuncTruths4a ) { if ( fVerbose ) { printf( "Object %d has %d-input cut: ", iObj, pCut[0] ); for ( k = 1; k <= pCut[0]; k++ ) printf( "%d ", pCut[k] ); printf( "\n" ); } *ppCut = pCut; return 3; // back unsigned } } if ( pCut[0] == 4 ) { pTruth = Vec_MemReadEntry(p->vTtMem, Abc_Lit2Var(pCut[pCut[0]+1])); for ( k = 0; k < s_nFuncTruths4b; k++ ) if ( s_FuncTruths4b[k] == (0xFFFF & (unsigned)*pTruth) ) break; if ( k < s_nFuncTruths4b ) { if ( fVerbose ) { printf( "Object %d has %d-input cut: ", iObj, pCut[0] ); for ( k = 1; k <= pCut[0]; k++ ) printf( "%d ", pCut[k] ); printf( "\n" ); } *ppCut = pCut; return 4; // back signed } } } return 0; } Vec_Int_t * Sdb_StoIterCuts( Sdb_Sto_t * p ) { Vec_Wec_t * v5Cuts = Vec_WecAlloc( 100 ); Vec_Int_t * v5Cut, * vAll, * vRes; Gia_Obj_t * pObj; int k, iObj, * pCut, Limit, iNew, iNewFront = -1, iNewBack = -1, iSigned = 0; Gia_ManForEachAnd( p->pGia, pObj, iObj ) { int RetValue = Sdb_StoIterCutsOne( p, iObj, 5, &pCut ); if ( RetValue == 0 ) continue; assert( RetValue == 1 ); assert( pCut[0] == 5 ); v5Cut = Vec_WecPushLevel( v5Cuts ); for ( k = 1; k <= pCut[0]; k++ ) Vec_IntPush( v5Cut, pCut[k] ); } Limit = Vec_WecSize( v5Cuts ); printf( "Detected %d 5-cuts.\n", Vec_WecSize(v5Cuts) ); vAll = Sdb_StoFindAll( v5Cuts ); Gia_ManForEachAnd( p->pGia, pObj, iObj ) { int RetValue = Sdb_StoIterCutsOne( p, iObj, 4, &pCut ); if ( RetValue == 0 ) continue; assert( RetValue >= 2 && RetValue <= 4 ); assert( pCut[0] == 4 ); // find cut, which differs in exactly one input iNew = Sdb_StoDiffExactlyOne( v5Cuts, Limit, pCut ); if ( iNew == -1 ) continue; if ( RetValue == 2 ) iNewFront = iNew; else iNewBack = iNew; if ( RetValue == 4 ) iSigned = 1; // save in the second cut v5Cut = Vec_WecPushLevel( v5Cuts ); Vec_IntPush( v5Cut, 0 ); for ( k = 1; k <= pCut[0]; k++ ) Vec_IntPush( v5Cut, pCut[k] ); } Vec_IntFree( vAll ); Vec_WecPrint( v5Cuts, 0 ); if ( iNewFront ) printf( "Front = %d\n", iNewFront ); if ( iNewBack ) printf( "Back = %d\n", iNewBack ); if ( iSigned ) printf( "Sign = %d\n", iSigned ); vRes = Sdb_StoFindInputs( v5Cuts, iNewFront ); Vec_WecFree( v5Cuts ); return vRes; } /**Function************************************************************* Synopsis [Incremental cut computation.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Sdb_Sto_t * Sdb_StoAlloc( Gia_Man_t * pGia, int nCutSize, int nCutNum, int fCutMin, int fTruthMin, int fVerbose ) { Sdb_Sto_t * p; assert( nCutSize < SDB_CUT_NO_LEAF ); assert( nCutSize > 1 && nCutSize <= SDB_MAX_CUTSIZE ); assert( nCutNum > 1 && nCutNum < SDB_MAX_CUTNUM ); p = ABC_CALLOC( Sdb_Sto_t, 1 ); p->clkStart = Abc_Clock(); p->nCutSize = nCutSize; p->nCutNum = nCutNum; p->fCutMin = fCutMin; p->fTruthMin = fTruthMin; p->fVerbose = fVerbose; p->pGia = pGia; p->vRefs = Vec_IntAlloc( Gia_ManObjNum(pGia) ); p->vCuts = Vec_WecStart( Gia_ManObjNum(pGia) ); p->vTtMem = fCutMin ? Vec_MemAllocForTT( nCutSize, 0 ) : NULL; return p; } void Sdb_StoFree( Sdb_Sto_t * p ) { Vec_IntFree( p->vRefs ); Vec_WecFree( p->vCuts ); if ( p->fCutMin ) Vec_MemHashFree( p->vTtMem ); if ( p->fCutMin ) Vec_MemFree( p->vTtMem ); ABC_FREE( p ); } void Sdb_StoComputeCutsConst0( Sdb_Sto_t * p, int iObj ) { Sdb_CutAddZero( p, iObj ); } void Sdb_StoComputeCutsCi( Sdb_Sto_t * p, int iObj ) { Sdb_CutAddUnit( p, iObj ); } void Sdb_StoComputeCutsNode( Sdb_Sto_t * p, int iObj ) { Sdb_StoMergeCuts( p, iObj ); } void Sdb_StoRefObj( Sdb_Sto_t * p, int iObj ) { Gia_Obj_t * pObj = Gia_ManObj(p->pGia, iObj); assert( iObj == Vec_IntSize(p->vRefs) ); Vec_IntPush( p->vRefs, 0 ); if ( Gia_ObjIsAnd(pObj) ) { Vec_IntAddToEntry( p->vRefs, Gia_ObjFaninId0(pObj, iObj), 1 ); Vec_IntAddToEntry( p->vRefs, Gia_ObjFaninId1(pObj, iObj), 1 ); } else if ( Gia_ObjIsCo(pObj) ) Vec_IntAddToEntry( p->vRefs, Gia_ObjFaninId0(pObj, iObj), 1 ); } Vec_Int_t * Sdb_StoComputeCutsDetect( Gia_Man_t * pGia ) { Vec_Int_t * vRes = NULL; Sdb_Sto_t * p = Sdb_StoAlloc( pGia, 5, 20, 1, 0, 1 ); Gia_Obj_t * pObj; int i, iObj; // prepare references Gia_ManForEachObj( p->pGia, pObj, iObj ) Sdb_StoRefObj( p, iObj ); // compute cuts Sdb_StoComputeCutsConst0( p, 0 ); Gia_ManForEachCiId( p->pGia, iObj, i ) Sdb_StoComputeCutsCi( p, iObj ); Gia_ManForEachAnd( p->pGia, pObj, iObj ) Sdb_StoComputeCutsNode( p, iObj ); if ( p->fVerbose ) { printf( "Running cut computation with CutSize = %d CutNum = %d:\n", p->nCutSize, p->nCutNum ); printf( "CutPair = %.0f ", p->CutCount[0] ); printf( "Merge = %.0f (%.2f %%) ", p->CutCount[1], 100.0*p->CutCount[1]/p->CutCount[0] ); printf( "Eval = %.0f (%.2f %%) ", p->CutCount[2], 100.0*p->CutCount[2]/p->CutCount[0] ); printf( "Cut = %.0f (%.2f %%) ", p->CutCount[3], 100.0*p->CutCount[3]/p->CutCount[0] ); printf( "Cut/Node = %.2f ", p->CutCount[3] / Gia_ManAndNum(p->pGia) ); printf( "\n" ); printf( "Over = %4d ", p->nCutsOver ); Abc_PrintTime( 0, "Time", Abc_Clock() - p->clkStart ); } vRes = Sdb_StoIterCuts( p ); Sdb_StoFree( p ); return vRes; } void Sdb_StoComputeCutsTest( Gia_Man_t * pGia ) { Vec_Int_t * vRes = Sdb_StoComputeCutsDetect( pGia ); Vec_IntFree( vRes ); } //////////////////////////////////////////////////////////////////////// /// END OF FILE /// //////////////////////////////////////////////////////////////////////// ABC_NAMESPACE_IMPL_END
85d279c040dbc64e2bef513bbeefe4a9dd994dd5
6f247f5400c6a840b6dfcb12388116dc3bb7bd49
/vstream/test/predtest.c
e409e4d022623ba9418dcb74e493d88d908fecd5
[ "MIT" ]
permissive
envytools/envytools
c062fbc3b8af90d3df9c6e0f57e9abbfc5690d01
e11d670a70ae0455261ead53cdd09c321974cc64
refs/heads/master
2023-08-26T23:44:47.131591
2022-04-30T21:15:56
2022-04-30T21:15:56
11,620,001
402
103
MIT
2022-12-07T01:35:18
2013-07-23T21:43:43
C
UTF-8
C
false
false
1,463
c
predtest.c
#include "h264.h" #include "vstream.h" #include <stdio.h> #include <stdlib.h> int main() { struct bitstream *str = vs_new_encode(VS_H264); struct h264_slice *slp = calloc (sizeof *slp, 1); slp->slice_type = 1; slp->num_ref_idx_l0_active_minus1 = 7; slp->num_ref_idx_l1_active_minus1 = 0x13; struct h264_pred_weight_table *weights = calloc (sizeof *weights, 1); weights->luma_log2_weight_denom = 3; weights->chroma_log2_weight_denom = 5; int i; for (i = 0; i <= slp->num_ref_idx_l0_active_minus1; i++) { weights->l0[i].luma_weight_flag = 1; weights->l0[i].chroma_weight_flag = 1; } for (i = 0; i <= slp->num_ref_idx_l1_active_minus1; i++) { weights->l1[i].luma_weight_flag = 1; weights->l1[i].chroma_weight_flag = 1; } weights->l0[3].luma_weight_flag = 0; weights->l0[3].luma_weight = 8; weights->l0[4].luma_weight = 0x3; weights->l0[5].luma_weight = -0x3; weights->l0[4].luma_offset = -5; weights->l0[5].luma_weight = 5; weights->l1[0x10].chroma_weight_flag = 0; weights->l1[0x10].chroma_weight[0] = 32; weights->l1[0x10].chroma_weight[1] = 32; weights->l1[0x11].chroma_weight[0] = 7; weights->l1[0x12].chroma_weight[1] = 8; weights->l1[0x13].chroma_offset[0] = 9; weights->l1[0x14].chroma_offset[1] = 10; if (h264_pred_weight_table(str, slp, weights)) { fprintf(stderr, "Failed\n"); return 1; } if (vs_end(str)) { fprintf(stderr, "Failed\n"); return 1; } fwrite(str->bytes, str->bytesnum, 1, stdout); return 0; }
4b574ef1f1bb48395ef1c14b90f78fa4a8294984
e910318d01528d82040507a49eeeb8dade45b31f
/ports/mimxrt/ticks.c
676f81b30eb26b9f6bd2d92ed5fb0e8720126291
[ "MIT" ]
permissive
pfalcon/pycopy
e844480a5e5cd463530328889daed2ba87552b8a
3ac90ae9c3c6bbebfba9cada2d37025e35c62796
refs/heads/pfalcon
2023-08-30T09:39:52.290147
2022-09-08T16:42:38
2022-09-08T16:42:38
15,507,576
753
71
MIT
2021-05-08T04:59:21
2013-12-29T11:38:47
C
UTF-8
C
false
false
4,601
c
ticks.c
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2021 Damien P. George * * 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 "py/mphal.h" #include "ticks.h" #include "fsl_gpt.h" // General purpose timer for keeping microsecond and millisecond tick values. #define GPTx GPT2 #define GPTx_IRQn GPT2_IRQn #define GPTx_IRQHandler GPT2_IRQHandler static uint32_t ticks_us64_upper; static uint32_t ticks_ms_upper; void ticks_init(void) { ticks_us64_upper = 0; ticks_ms_upper = 0; gpt_config_t config; config.clockSource = kGPT_ClockSource_Osc; config.divider = 24; // XTAL is 24MHz config.enableFreeRun = true; config.enableRunInWait = true; config.enableRunInStop = true; config.enableRunInDoze = true; config.enableRunInDbg = false; config.enableMode = true; GPT_Init(GPTx, &config); GPT_EnableInterrupts(GPTx, kGPT_RollOverFlagInterruptEnable); NVIC_SetPriority(GPTx_IRQn, 0); // highest priority NVIC_EnableIRQ(GPTx_IRQn); GPT_StartTimer(GPTx); } void GPTx_IRQHandler(void) { if (GPT_GetStatusFlags(GPTx, kGPT_OutputCompare1Flag)) { GPT_ClearStatusFlags(GPTx, kGPT_OutputCompare1Flag); GPT_DisableInterrupts(GPTx, kGPT_OutputCompare1InterruptEnable); __SEV(); } if (GPT_GetStatusFlags(GPTx, kGPT_RollOverFlag)) { GPT_ClearStatusFlags(GPTx, kGPT_RollOverFlag); ++ticks_us64_upper; if (++ticks_ms_upper >= 1000) { // Wrap upper counter at a multiple of 1000 so that when mp_hal_ticks_ms() // wraps due to overflow it wraps smoothly. ticks_ms_upper = 0; } } } static void ticks_wake_after_us32(uint32_t us) { if (us < 2) { // Delay too short to guarantee that we won't miss it when setting the OCR below. __SEV(); } else { // Disable IRQs so setting the OCR is done without any interruption. uint32_t irq_state = DisableGlobalIRQ(); GPT_EnableInterrupts(GPTx, kGPT_OutputCompare1InterruptEnable); uint32_t oc = GPT_GetCurrentTimerCount(GPTx) + us; GPT_SetOutputCompareValue(GPTx, kGPT_OutputCompare_Channel1, oc); EnableGlobalIRQ(irq_state); } } static uint64_t ticks_us64_with(uint32_t *upper_ptr) { uint32_t irq_state = DisableGlobalIRQ(); uint32_t lower = GPT_GetCurrentTimerCount(GPTx); uint32_t upper = *upper_ptr; uint32_t overflow = GPT_GetStatusFlags(GPTx, kGPT_RollOverFlag); EnableGlobalIRQ(irq_state); if (overflow && lower < 0x80000000) { // The timer counter overflowed before reading it but the IRQ handler // has not yet been called, so perform the IRQ arithmetic now. ++upper; } return (uint64_t)upper << 32 | (uint64_t)lower; } uint32_t ticks_us32(void) { return GPT_GetCurrentTimerCount(GPTx); } uint64_t ticks_us64(void) { return ticks_us64_with(&ticks_us64_upper); } uint32_t ticks_ms32(void) { // This will return a value that only has the lower 32-bits valid. return ticks_us64_with(&ticks_ms_upper) / 1000; } void ticks_delay_us64(uint64_t us) { uint64_t t0 = ticks_us64(); for (;;) { uint64_t dt = ticks_us64() - t0; if (dt >= us) { return; } dt = us - dt; if (dt > 0xffffffff) { dt = 0xffffffff; } ticks_wake_after_us32((uint32_t)dt); if (dt < 50) { __WFE(); } else { MICROPY_EVENT_POLL_HOOK } } }
984a226ecf1ac2605f4c1d4201e2f521bf3c7901
3bd385b466cb035fecd2b0c11ae054d42bf44fc2
/src/extended/regular_seqid.c
05ec76d6ae164a0e17a37683412cac36d4b9e186
[ "LicenseRef-scancode-unknown-license-reference", "ISC", "BSD-2-Clause", "LicenseRef-scancode-mit-old-style", "Zlib", "MIT", "BSD-3-Clause", "bzip2-1.0.6" ]
permissive
genometools/genometools
c366dff04f6baa887f6b3be3ec55bce824b2bae1
df1df94b8c05a9c9bf848ffc6755c87b58573da5
refs/heads/master
2023-04-13T13:57:18.748796
2023-04-09T21:29:53
2023-04-09T21:29:53
11,177,980
237
63
NOASSERTION
2023-04-09T21:29:54
2013-07-04T13:39:38
C
UTF-8
C
false
false
1,904
c
regular_seqid.c
/* Copyright (c) 2003-2010 Gordon Gremme <gordon@gremme.org> Copyright (c) 2003-2008 Center for Bioinformatics, University of Hamburg 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 "core/types_api.h" #include "extended/regular_seqid_api.h" void gt_regular_seqid_save(GtStr *seqid, GtStr *description) { GtUword i, len; unsigned char *desc, cc; gt_assert(seqid && description); len = gt_str_length(description); desc = (GtUchar*) gt_str_get(description); i = 0; if ((len >= 2) && (desc[0] == 'g') && (desc[1] == 'i') && (desc[2] == '|')) { /* skip 'gi|' */ i = 3; } else if ((len >= 2) && (desc[0] == 'S') && (desc[1] == 'Q') && (desc[2] == ';')) { /* skip 'SQ;' */ i = 3; } else if ((len >= 3) && (desc[0] == '(') && (desc[1] == 'g') && (desc[2] == 'i') && (desc[3] == '|')) { /* skip '(gi|' */ i = 4; } else if ((len >= 3) && (desc[0] == 'r') && (desc[1] == 'e') && (desc[2] == 'f') && (desc[3] == '|')) { /* skip 'ref|' */ i = 4; } for (/* init already done */ ; i < len; i++) { cc = desc[i]; if (cc == ':' || cc == '|' || cc == '\t' || cc == ' ') break; gt_str_append_char(seqid, desc[i]); } }
ad93743f92254da05f32927e3031a8b2066aa3e9
b732361d6b3405c3e79ac0a7d8361cf5b329b015
/ext/phalcon/translate/interpolator/interpolatorinterface.zep.h
605ed09489fe648cfe475119c5e891427333d716
[ "BSD-3-Clause" ]
permissive
phalcon/cphalcon
4a5b26f47b5c2a4107541d7fd73c595c0d90ed73
fc183e11e8b96c43daf7d893244846206dc2aa73
refs/heads/master
2023-03-07T22:09:48.814291
2023-02-28T16:45:15
2023-02-28T16:45:15
2,854,337
8,135
2,343
BSD-3-Clause
2023-09-12T12:41:13
2011-11-26T05:52:50
PHP
UTF-8
C
false
true
804
h
interpolatorinterface.zep.h
extern zend_class_entry *phalcon_translate_interpolator_interpolatorinterface_ce; ZEPHIR_INIT_CLASS(Phalcon_Translate_Interpolator_InterpolatorInterface); ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_phalcon_translate_interpolator_interpolatorinterface_replaceplaceholders, 0, 1, IS_STRING, 0) ZEND_ARG_TYPE_INFO(0, translation, IS_STRING, 0) #if PHP_VERSION_ID >= 80000 ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, placeholders, IS_ARRAY, 0, "[]") #else ZEND_ARG_ARRAY_INFO(0, placeholders, 0) #endif ZEND_END_ARG_INFO() ZEPHIR_INIT_FUNCS(phalcon_translate_interpolator_interpolatorinterface_method_entry) { PHP_ABSTRACT_ME(Phalcon_Translate_Interpolator_InterpolatorInterface, replacePlaceholders, arginfo_phalcon_translate_interpolator_interpolatorinterface_replaceplaceholders) PHP_FE_END };
60783f8d8a7b8e6a2b8ba931905ed87375f03e2b
fb47ab6337a71029dee71933e449cf7f6805fc0f
/lib/console/include/lib/console.h
5a6760f592b37dad45ed54542eb81a4b41b316f3
[ "MIT" ]
permissive
littlekernel/lk
7e7ba50b87b1f2e0b6e2f052c59249825c91975b
30dc320054f70910e1c1ee40a6948ee99672acec
refs/heads/master
2023-09-02T00:47:52.203963
2023-06-21T22:42:35
2023-06-21T22:42:35
3,058,456
3,077
618
MIT
2023-08-30T09:41:31
2011-12-27T19:19:36
C
UTF-8
C
false
false
1,978
h
console.h
/* * Copyright (c) 2008-2009 Travis Geiselbrecht * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT */ #pragma once #include <lk/compiler.h> __BEGIN_CDECLS /* Previously, this file was included to get access to defining a console * command. This logic has been moved into the following header, which is * what in almost every case what regular code wants to include instead of * this file. */ #include <lk/console_cmd.h> #include <lib/console/cmd.h> typedef struct console console_t; /* create an instance of the console */ /* TODO: actually implement the history option. Currently always implements history according * to the build variable CONSOLE_ENABLE_HISTORY. */ console_t *console_create(bool with_history); /* Run the main console loop. Will set the current console TLS pointer as a side effect */ void console_start(console_t *con); /* Routines to let code directly run commands in an existing console */ /* NOTE: Passing null as first argument selects the current console associated with the current thread */ int console_run_script(console_t *con, const char *string); int console_run_script_locked(console_t *con, const char *string); // special case from inside a command void console_abort_script(console_t *con); /* Get/set the current console in the thread's TLS slot reserved for it. * New threads will inherit the pointer from the parent thread. * * TODO: use a ref count to keep the console from being destroyed from underneath it. */ console_t *console_get_current(void); console_t *console_set_current(console_t *con); // returns old console pointer console_cmd_func console_get_command_handler(const char *command); /* panic shell api */ void panic_shell_start(void); /* enable the panic shell if we're being built */ #if !defined(ENABLE_PANIC_SHELL) && PLATFORM_SUPPORTS_PANIC_SHELL #define ENABLE_PANIC_SHELL 1 #endif __END_CDECLS