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
58292be32bed31de6a50bd9b727a16fa4c7b28d4
b4a3facc5fcd12a85c1ca0d33d78312eb94b61cf
/third_party/giflib-5.1.3/util/gifhisto.c
2e6bd7b5ade62f26c215e52231e809a15a746e13
[ "BSD-3-Clause", "FSFAP", "MIT", "LicenseRef-scancode-free-unknown" ]
permissive
onecoolx/picasso
2d3eecf35947be7991fea06be01986dd0d16773e
f14245e09c10467d54eaf845a874584361a46d46
refs/heads/master
2023-03-20T15:19:03.677086
2023-03-01T05:37:03
2023-03-01T05:37:03
2,441,631
333
51
BSD-3-Clause
2023-03-16T03:03:08
2011-09-23T02:54:10
C
UTF-8
C
false
false
8,077
c
gifhisto.c
/***************************************************************************** gifhisto - make a color histogram from image color frequencies *****************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <ctype.h> #include <string.h> #include <stdbool.h> #include "gif_lib.h" #include "getarg.h" #define PROGRAM_NAME "gifhisto" #define DEFAULT_HISTO_WIDTH 100 /* Histogram image diemnsions. */ #define DEFAULT_HISTO_HEIGHT 256 #define HISTO_BITS_PER_PIXEL 2 /* Size of bitmap for histogram GIF. */ static char *VersionStr = PROGRAM_NAME VERSION_COOKIE " Gershon Elber, " __DATE__ ", " __TIME__ "\n" "(C) Copyright 1989 Gershon Elber.\n"; static char *CtrlStr = PROGRAM_NAME " v%- t%- s%-Width|Height!d!d n%-ImageNumber!d b%- h%- GifFile!*s"; static int ImageWidth = DEFAULT_HISTO_WIDTH, ImageHeight = DEFAULT_HISTO_HEIGHT, ImageN = 1; static GifColorType HistoColorMap[] = { /* Constant bit map for histograms: */ { 0, 0, 0 }, { 255, 0, 0 }, { 0, 255, 0 }, { 0, 0, 255 } }; static void QuitGifError(GifFileType *GifFileIn, GifFileType *GifFileOut); /****************************************************************************** Interpret the command line and scan the given GIF file. ******************************************************************************/ int main(int argc, char **argv) { int i, j, ErrorCode, NumFiles, ExtCode, CodeSize, NumColors = 2, ImageNum = 0; bool Error, TextFlag = false, SizeFlag = false, ImageNFlag = false, BackGroundFlag = false, HelpFlag = false; long Histogram[256]; GifRecordType RecordType; GifByteType *Extension, *CodeBlock; char **FileName = NULL; GifRowType Line; GifFileType *GifFileIn = NULL, *GifFileOut = NULL; /* Same image dimension vars for both Image & ImageN as only one allowed */ if ((Error = GAGetArgs(argc, argv, CtrlStr, &GifNoisyPrint, &TextFlag, &SizeFlag, &ImageWidth, &ImageHeight, &ImageNFlag, &ImageN, &BackGroundFlag, &HelpFlag, &NumFiles, &FileName)) != false || (NumFiles > 1 && !HelpFlag)) { if (Error) GAPrintErrMsg(Error); else if (NumFiles > 1) GIF_MESSAGE("Error in command line parsing - one GIF file please."); GAPrintHowTo(CtrlStr); exit(EXIT_FAILURE); } if (HelpFlag) { (void)fprintf(stderr, VersionStr, GIFLIB_MAJOR, GIFLIB_MINOR); GAPrintHowTo(CtrlStr); exit(EXIT_SUCCESS); } if (NumFiles == 1) { if ((GifFileIn = DGifOpenFileName(*FileName, &ErrorCode)) == NULL) { PrintGifError(ErrorCode); exit(EXIT_FAILURE); } } else { /* Use stdin instead: */ if ((GifFileIn = DGifOpenFileHandle(0, &ErrorCode)) == NULL) { PrintGifError(ErrorCode); exit(EXIT_FAILURE); } } for (i = 0; i < 256; i++) Histogram[i] = 0; /* Reset counters. */ /* Scan the content of the GIF file and load the image(s) in: */ do { if (DGifGetRecordType(GifFileIn, &RecordType) == GIF_ERROR) QuitGifError(GifFileIn, GifFileOut); switch (RecordType) { case IMAGE_DESC_RECORD_TYPE: if (DGifGetImageDesc(GifFileIn) == GIF_ERROR) QuitGifError(GifFileIn, GifFileOut); if (GifFileIn->Image.ColorMap) NumColors = GifFileIn->Image.ColorMap->ColorCount; else if (GifFileIn->SColorMap) NumColors = GifFileIn->SColorMap->ColorCount; else GIF_EXIT("Neither Screen nor Image color map exists."); if ((ImageHeight / NumColors) * NumColors != ImageHeight) GIF_EXIT("Image height specified not dividable by #colors."); if (++ImageNum == ImageN) { /* This is the image we should make histogram for: */ Line = (GifRowType) malloc(GifFileIn->Image.Width * sizeof(GifPixelType)); GifQprintf("\n%s: Image %d at (%d, %d) [%dx%d]: ", PROGRAM_NAME, ImageNum, GifFileIn->Image.Left, GifFileIn->Image.Top, GifFileIn->Image.Width, GifFileIn->Image.Height); for (i = 0; i < GifFileIn->Image.Height; i++) { if (DGifGetLine(GifFileIn, Line, GifFileIn->Image.Width) == GIF_ERROR) QuitGifError(GifFileIn, GifFileOut); for (j = 0; j < GifFileIn->Image.Width; j++) Histogram[Line[j]]++; GifQprintf("\b\b\b\b%-4d", i); } free((char *) Line); } else { /* Skip the image: */ /* Now read image itself in decoded form as we dont */ /* really care what is there, and this is much faster. */ if (DGifGetCode(GifFileIn, &CodeSize, &CodeBlock) == GIF_ERROR) QuitGifError(GifFileIn, GifFileOut); while (CodeBlock != NULL) if (DGifGetCodeNext(GifFileIn, &CodeBlock) == GIF_ERROR) QuitGifError(GifFileIn, GifFileOut); } break; case EXTENSION_RECORD_TYPE: /* Skip any extension blocks in file: */ if (DGifGetExtension(GifFileIn, &ExtCode, &Extension) == GIF_ERROR) QuitGifError(GifFileIn, GifFileOut); while (Extension != NULL) { if (DGifGetExtensionNext(GifFileIn, &Extension) == GIF_ERROR) QuitGifError(GifFileIn, GifFileOut); } break; case TERMINATE_RECORD_TYPE: break; default: /* Should be trapped by DGifGetRecordType. */ break; } } while (RecordType != TERMINATE_RECORD_TYPE); /* We requested suppression of the background count: */ if (BackGroundFlag) Histogram[GifFileIn->SBackGroundColor] = 0; if (DGifCloseFile(GifFileIn, &ErrorCode) == GIF_ERROR) { PrintGifError(ErrorCode); exit(EXIT_FAILURE); } /* We may required to dump out the histogram as text file: */ if (TextFlag) { for (i = 0; i < NumColors; i++) printf("%12ld %3d\n", Histogram[i], i); } else { int Color, Count; long Scaler; /* Open stdout for the histogram output file: */ if ((GifFileOut = EGifOpenFileHandle(1, &ErrorCode)) == NULL) { PrintGifError(ErrorCode); exit(EXIT_FAILURE); } /* Dump out screen descriptor to fit histogram dimensions: */ if (EGifPutScreenDesc(GifFileOut, ImageWidth, ImageHeight, HISTO_BITS_PER_PIXEL, 0, GifMakeMapObject(4, HistoColorMap)) == GIF_ERROR) QuitGifError(GifFileIn, GifFileOut); /* Dump out image descriptor to fit histogram dimensions: */ if (EGifPutImageDesc(GifFileOut, 0, 0, ImageWidth, ImageHeight, false, NULL) == GIF_ERROR) QuitGifError(GifFileIn, GifFileOut); /* Prepare scan line for histogram file, and find scaler to scale */ /* histogram to be between 0 and ImageWidth: */ Line = (GifRowType) malloc(ImageWidth * sizeof(GifPixelType)); for (Scaler = 0, i = 0; i < NumColors; i++) if (Histogram[i] > Scaler) Scaler = Histogram[i]; Scaler /= ImageWidth; if (Scaler == 0) Scaler = 1; /* In case maximum is less than width. */ /* Dump out the image itself: */ for (Count = ImageHeight, i = 0, Color = 1; i < NumColors; i++) { int Size; if ((Size = Histogram[i] / Scaler) > ImageWidth) Size = ImageWidth; for (j = 0; j < Size; j++) Line[j] = Color; for (j = Size; j < ImageWidth; j++) Line[j] = GifFileOut->SBackGroundColor; /* Move to next color: */ if (++Color >= (1 << HISTO_BITS_PER_PIXEL)) Color = 1; /* Dump this histogram entry as many times as required: */ for (j = 0; j < ImageHeight / NumColors; j++) { if (EGifPutLine(GifFileOut, Line, ImageWidth) == GIF_ERROR) QuitGifError(GifFileIn, GifFileOut); GifQprintf("\b\b\b\b%-4d", Count--); } } if (EGifCloseFile(GifFileOut, &ErrorCode) == GIF_ERROR) { PrintGifError(ErrorCode); exit(EXIT_FAILURE); } } return 0; } /****************************************************************************** Close both input and output file (if open), and exit. ******************************************************************************/ static void QuitGifError(GifFileType *GifFileIn, GifFileType *GifFileOut) { if (GifFileIn != NULL) { PrintGifError(GifFileIn->Error); EGifCloseFile(GifFileIn, NULL); } if (GifFileOut != NULL) { PrintGifError(GifFileOut->Error); EGifCloseFile(GifFileOut, NULL); } exit(EXIT_FAILURE); } /* end */
772d31a994408599ff3bc188b742a32654639b54
5f86fc385c7dcfcb5b166cdea7c8b13057b8bb5f
/tests/crypto/read_file.c
966034070da0afc611c2532e5c0e73218cddd8c5
[ "MIT" ]
permissive
openenclave/openenclave
54a38e12d9aa73357d9f438a07cd8c07ffe5e6df
cdeb95c1ec163117de409295333b6b2702013e08
refs/heads/master
2023-08-14T16:43:32.049533
2023-07-21T15:58:54
2023-07-21T15:58:54
101,804,230
800
372
MIT
2023-09-12T20:26:02
2017-08-29T20:31:38
C
UTF-8
C
false
false
7,416
c
read_file.c
// Copyright (c) Open Enclave SDK contributors. // Licensed under the MIT License. #include <ctype.h> #ifdef OE_BUILD_ENCLAVE #include <openenclave/corelibc/string.h> #else #include "../../host/strings.h" #endif #include "readfile.h" FILE* read_file(const char* filename, const char* mode) { FILE* file; #ifdef _MSC_VER fopen_s(&file, filename, mode); #else file = fopen(filename, mode); #endif return file; } oe_result_t read_cert(char* filename, char* cert) { size_t len_cert; FILE* cfp = read_file(filename, "rb"); if (cfp != NULL) { len_cert = fread(cert, sizeof(char), max_cert_size, cfp); } else { return OE_FAILURE; } cert[len_cert] = '\0'; fclose(cfp); return OE_OK; } oe_result_t read_chain( char* filename1, char* filename2, char* chain, size_t chain_size) { size_t len_cert1 = 0, len_cert2 = 0; char chain_temp[max_cert_size]; FILE* cfp1 = read_file(filename1, "rb"); FILE* cfp2 = read_file(filename2, "rb"); if (cfp1 != NULL && cfp2 != NULL) { len_cert1 = fread(chain, sizeof(char), max_cert_size, cfp1); chain[len_cert1] = '\0'; len_cert2 = fread(chain_temp, sizeof(char), max_cert_size, cfp2); chain_temp[len_cert2] = '\0'; oe_strlcat(chain, chain_temp, chain_size); } else { return OE_FAILURE; } fclose(cfp1); fclose(cfp2); return OE_OK; } oe_result_t read_chains( char* filename1, char* filename2, char* filename3, char* chain, size_t chain_size) { size_t len_cert1 = 0, len_cert2 = 0, len_cert3 = 0; char chain_temp1[max_cert_size]; char chain_temp2[max_cert_size]; FILE* cfp1 = read_file(filename1, "rb"); FILE* cfp2 = read_file(filename2, "rb"); FILE* cfp3 = read_file(filename3, "rb"); if (cfp1 != NULL && cfp2 != NULL && cfp3 != NULL) { len_cert1 = fread(chain, sizeof(char), max_cert_size, cfp1); chain[len_cert1] = '\0'; len_cert2 = fread(chain_temp1, sizeof(char), max_cert_size, cfp2); chain_temp1[len_cert2] = '\0'; len_cert3 = fread(chain_temp2, sizeof(char), max_cert_size, cfp3); chain_temp2[len_cert3] = '\0'; oe_strlcat(chain, chain_temp1, chain_size); oe_strlcat(chain, chain_temp2, chain_size); } else { return OE_FAILURE; } fclose(cfp1); fclose(cfp2); fclose(cfp3); return OE_OK; } oe_result_t read_crl(char* filename, uint8_t* crl, size_t* crl_size) { size_t len_crl = 0; FILE* cfp = read_file(filename, "rb"); if (cfp != NULL) { len_crl = fread(crl, sizeof(char), max_cert_size, cfp); } else { return OE_FAILURE; } crl[len_crl] = '\0'; *crl_size = len_crl; fclose(cfp); return OE_OK; } oe_result_t read_dates(char* filename, oe_datetime_t* time) { size_t len_date = 0; char buffer[max_date_size]; FILE* dfp = read_file(filename, "rb"); if (dfp != NULL) { len_date = fread(buffer, sizeof(char), max_date_size, dfp); } else { return OE_FAILURE; } buffer[len_date] = '\0'; sscanf_s( buffer, "%u :%u :%u :%u :%u :%u", &(time->year), &(time->month), &(time->day), &(time->hours), &(time->minutes), &(time->seconds)); fclose(dfp); return OE_OK; } static uint8_t hexval(char c) { switch (c) { case 'A': return 10; case 'B': return 11; case 'C': return 12; case 'D': return 13; case 'E': return 14; case 'F': return 15; case 'a': return 10; case 'b': return 11; case 'c': return 12; case 'd': return 13; case 'e': return 14; case 'f': return 15; case '0': return 0; case '1': return 1; case '2': return 2; case '3': return 3; case '4': return 4; case '5': return 5; case '6': return 6; case '7': return 7; case '8': return 8; case '9': return 9; default: return 0xff; } } // Assume a series of hex digits in the file. oe_result_t read_mod(char* filename, uint8_t* mod, size_t* mod_size) { size_t len_mod; size_t numchars = 0; char buffer[(max_mod_size * 2) + 1]; char* bufp = buffer; FILE* mfp = read_file(filename, "rb"); if (mfp != NULL) { numchars = fread(buffer, sizeof(char), max_mod_size * 2, mfp); // Skip leading non-digits ("Modulus=" for example). len_mod = numchars; for (size_t i = 0; i < numchars; i++) { if ((isdigit(*bufp) || (*bufp >= 'A' && *bufp <= 'F'))) break; bufp++; len_mod--; } } else { return OE_FAILURE; } len_mod >>= 1; memset(mod, 0, len_mod + 1); for (size_t i = 0; i < len_mod; i++) { mod[i] = (uint8_t)(hexval(bufp[1]) + (hexval(bufp[0]) << 4)); bufp += 2; } *mod_size = len_mod; fclose(mfp); return OE_OK; } oe_result_t read_mixed_chain( char* chain1, char* chain2, char* chain, size_t chain_size) { oe_strlcat(chain, chain1, chain_size); oe_strlcat(chain, chain2, chain_size); return OE_OK; } oe_result_t read_sign(char* filename, uint8_t* sign, size_t* sign_size) { size_t len_sign; FILE* sfp = read_file(filename, "rb"); if (sfp != NULL) { len_sign = fread(sign, sizeof(char), max_sign_size, sfp); } else { return OE_FAILURE; } sign[len_sign] = '\0'; *sign_size = len_sign; fclose(sfp); return OE_OK; } oe_result_t read_pem_key( const char* filename, char* data, size_t data_size, size_t* data_size_out) { oe_result_t result = OE_UNEXPECTED; size_t size = 0; FILE* stream = NULL; int c; if (!filename || !data) { result = OE_INVALID_PARAMETER; goto done; } /* Open file in binary mode. */ if (!(stream = read_file(filename, "rb"))) { result = OE_FAILURE; goto done; } /* Read character-by-character, removing any <CR> characters. */ while ((c = fgetc(stream)) != EOF && size < data_size) { if (c != '\r') data[size++] = (char)c; } if (size == data_size) { result = OE_BUFFER_TOO_SMALL; goto done; } data[size] = '\0'; if (data_size_out) *data_size_out = size; result = OE_OK; done: if (stream) fclose(stream); return result; } oe_result_t read_coordinates( char* filename, uint8_t* x, uint8_t* y, size_t* x_size, size_t* y_size) { size_t len_x, len_y; FILE* cfp = read_file(filename, "rb"); if (cfp != NULL) { len_x = fread(x, sizeof(char), max_coordinates_size, cfp); len_y = fread(y, sizeof(char), max_coordinates_size, cfp); } else { return OE_FAILURE; } fclose(cfp); *x_size = len_x; *y_size = len_y; return OE_OK; }
94c7afc403c95f4a8b2dfe81ce335289600cf944
c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64
/Engine/Binaries/ThirdParty/svn/Mac/include/subversion-1/svn_xml.h
8791b143750c6f6126f873bf98826aa8c64bf5b1
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
windystrife/UnrealEngine_NVIDIAGameWorks
c3c7863083653caf1bc67d3ef104fb4b9f302e2a
b50e6338a7c5b26374d66306ebc7807541ff815e
refs/heads/4.18-GameWorks
2023-03-11T02:50:08.471040
2022-01-13T20:50:29
2022-01-13T20:50:29
124,100,479
262
179
MIT
2022-12-16T05:36:38
2018-03-06T15:44:09
C++
UTF-8
C
false
false
12,289
h
svn_xml.h
/** * @copyright * ==================================================================== * 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. * ==================================================================== * @endcopyright * * @file svn_xml.h * @brief XML code shared by various Subversion libraries. */ #ifndef SVN_XML_H #define SVN_XML_H #include <apr.h> #include <apr_pools.h> #include <apr_hash.h> #include "svn_types.h" #include "svn_string.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** The namespace all Subversion XML uses. */ #define SVN_XML_NAMESPACE "svn:" /** Used as style argument to svn_xml_make_open_tag() and friends. */ enum svn_xml_open_tag_style { /** <tag ...> */ svn_xml_normal = 1, /** <tag ...>, no cosmetic newline */ svn_xml_protect_pcdata, /** <tag .../> */ svn_xml_self_closing }; /** Determine if a string of character @a data of length @a len is a * safe bet for use with the svn_xml_escape_* functions found in this * header. * * Return @c TRUE if it is, @c FALSE otherwise. * * Essentially, this function exists to determine whether or not * simply running a string of bytes through the Subversion XML escape * routines will produce legitimate XML. It should only be necessary * for data which might contain bytes that cannot be safely encoded * into XML (certain control characters, for example). */ svn_boolean_t svn_xml_is_xml_safe(const char *data, apr_size_t len); /** Create or append in @a *outstr an xml-escaped version of @a string, * suitable for output as character data. * * If @a *outstr is @c NULL, set @a *outstr to a new stringbuf allocated * in @a pool, else append to the existing stringbuf there. */ void svn_xml_escape_cdata_stringbuf(svn_stringbuf_t **outstr, const svn_stringbuf_t *string, apr_pool_t *pool); /** Same as svn_xml_escape_cdata_stringbuf(), but @a string is an * @c svn_string_t. */ void svn_xml_escape_cdata_string(svn_stringbuf_t **outstr, const svn_string_t *string, apr_pool_t *pool); /** Same as svn_xml_escape_cdata_stringbuf(), but @a string is a * NULL-terminated C string. */ void svn_xml_escape_cdata_cstring(svn_stringbuf_t **outstr, const char *string, apr_pool_t *pool); /** Create or append in @a *outstr an xml-escaped version of @a string, * suitable for output as an attribute value. * * If @a *outstr is @c NULL, set @a *outstr to a new stringbuf allocated * in @a pool, else append to the existing stringbuf there. */ void svn_xml_escape_attr_stringbuf(svn_stringbuf_t **outstr, const svn_stringbuf_t *string, apr_pool_t *pool); /** Same as svn_xml_escape_attr_stringbuf(), but @a string is an * @c svn_string_t. */ void svn_xml_escape_attr_string(svn_stringbuf_t **outstr, const svn_string_t *string, apr_pool_t *pool); /** Same as svn_xml_escape_attr_stringbuf(), but @a string is a * NULL-terminated C string. */ void svn_xml_escape_attr_cstring(svn_stringbuf_t **outstr, const char *string, apr_pool_t *pool); /** * Return UTF-8 string @a string if it contains no characters that are * unrepresentable in XML. Else, return a copy of @a string, * allocated in @a pool, with each unrepresentable character replaced * by "?\uuu", where "uuu" is the three-digit unsigned decimal value * of that character. * * Neither the input nor the output need be valid XML; however, the * output can always be safely XML-escaped. * * @note The current implementation treats all Unicode characters as * representable, except for most ASCII control characters (the * exceptions being CR, LF, and TAB, which are valid in XML). There * may be other UTF-8 characters that are invalid in XML; see * http://subversion.tigris.org/servlets/ReadMsg?list=dev&msgNo=90591 * and its thread for details. * * @since New in 1.2. */ const char * svn_xml_fuzzy_escape(const char *string, apr_pool_t *pool); /*---------------------------------------------------------------*/ /* Generalized Subversion XML Parsing */ /** A generalized Subversion XML parser object */ typedef struct svn_xml_parser_t svn_xml_parser_t; typedef void (*svn_xml_start_elem)(void *baton, const char *name, const char **atts); typedef void (*svn_xml_end_elem)(void *baton, const char *name); /* data is not NULL-terminated. */ typedef void (*svn_xml_char_data)(void *baton, const char *data, apr_size_t len); /** Create a general Subversion XML parser */ svn_xml_parser_t * svn_xml_make_parser(void *baton, svn_xml_start_elem start_handler, svn_xml_end_elem end_handler, svn_xml_char_data data_handler, apr_pool_t *pool); /** Free a general Subversion XML parser */ void svn_xml_free_parser(svn_xml_parser_t *svn_parser); /** Push @a len bytes of xml data in @a buf at @a svn_parser. * * If this is the final push, @a is_final must be set. * * An error will be returned if there was a syntax problem in the XML, * or if any of the callbacks set an error using * svn_xml_signal_bailout(). * * If an error is returned, the @c svn_xml_parser_t will have been freed * automatically, so the caller should not call svn_xml_free_parser(). */ svn_error_t * svn_xml_parse(svn_xml_parser_t *svn_parser, const char *buf, apr_size_t len, svn_boolean_t is_final); /** The way to officially bail out of xml parsing. * * Store @a error in @a svn_parser and set all expat callbacks to @c NULL. */ void svn_xml_signal_bailout(svn_error_t *error, svn_xml_parser_t *svn_parser); /*** Helpers for dealing with the data Expat gives us. ***/ /** Return the value associated with @a name in expat attribute array @a atts, * else return @c NULL. * * (There could never be a @c NULL attribute value in the XML, * although the empty string is possible.) * * @a atts is an array of c-strings: even-numbered indexes are names, * odd-numbers hold values. If all is right, it should end on an * even-numbered index pointing to @c NULL. */ const char * svn_xml_get_attr_value(const char *name, const char *const *atts); /* Converting between Expat attribute lists and APR hash tables. */ /** Create an attribute hash from @c va_list @a ap. * * The contents of @a ap are alternating <tt>char *</tt> keys and * <tt>char *</tt> vals, terminated by a final @c NULL falling on an * even index (zero-based). */ apr_hash_t * svn_xml_ap_to_hash(va_list ap, apr_pool_t *pool); /** Create a hash that corresponds to Expat xml attribute list @a atts. * * The hash's keys and values are <tt>char *</tt>'s. * * @a atts may be NULL, in which case you just get an empty hash back * (this makes life more convenient for some callers). */ apr_hash_t * svn_xml_make_att_hash(const char **atts, apr_pool_t *pool); /** Like svn_xml_make_att_hash(), but takes a hash and preserves any * key/value pairs already in it. */ void svn_xml_hash_atts_preserving(const char **atts, apr_hash_t *ht, apr_pool_t *pool); /** Like svn_xml_make_att_hash(), but takes a hash and overwrites * key/value pairs already in it that also appear in @a atts. */ void svn_xml_hash_atts_overlaying(const char **atts, apr_hash_t *ht, apr_pool_t *pool); /* Printing XML */ /** Create an XML header and return it in @a *str. * * Fully-formed XML documents should start out with a header, * something like <pre> * \<?xml version="1.0" encoding="UTF-8"?\> * </pre> * * This function returns such a header. @a *str must either be @c NULL, in * which case a new string is created, or it must point to an existing * string to be appended to. @a encoding must either be NULL, in which case * encoding information is omitted from the header, or must be the name of * the encoding of the XML document, such as "UTF-8". * * @since New in 1.7. */ void svn_xml_make_header2(svn_stringbuf_t **str, const char *encoding, apr_pool_t *pool); /** Like svn_xml_make_header2(), but does not emit encoding information. * * @deprecated Provided for backward compatibility with the 1.6 API. */ SVN_DEPRECATED void svn_xml_make_header(svn_stringbuf_t **str, apr_pool_t *pool); /** Store a new xml tag @a tagname in @a *str. * * If @a *str is @c NULL, set @a *str to a new stringbuf allocated * in @a pool, else append to the existing stringbuf there. * * Take the tag's attributes from varargs, a SVN_VA_NULL-terminated list of * alternating <tt>char *</tt> key and <tt>char *</tt> val. Do xml-escaping * on each val. * * @a style is one of the enumerated styles in @c svn_xml_open_tag_style. */ void svn_xml_make_open_tag(svn_stringbuf_t **str, apr_pool_t *pool, enum svn_xml_open_tag_style style, const char *tagname, ...) SVN_NEEDS_SENTINEL_NULL; /** Like svn_xml_make_open_tag(), but takes a @c va_list instead of being * variadic. */ void svn_xml_make_open_tag_v(svn_stringbuf_t **str, apr_pool_t *pool, enum svn_xml_open_tag_style style, const char *tagname, va_list ap); /** Like svn_xml_make_open_tag(), but takes a hash table of attributes * (<tt>char *</tt> keys mapping to <tt>char *</tt> values). * * You might ask, why not just provide svn_xml_make_tag_atts()? * * The reason is that a hash table is the most natural interface to an * attribute list; the fact that Expat uses <tt>char **</tt> atts instead is * certainly a defensible implementation decision, but since we'd have * to have special code to support such lists throughout Subversion * anyway, we might as well write that code for the natural interface * (hashes) and then convert in the few cases where conversion is * needed. Someday it might even be nice to change expat-lite to work * with apr hashes. * * See conversion functions svn_xml_make_att_hash() and * svn_xml_make_att_hash_overlaying(). Callers should use those to * convert Expat attr lists into hashes when necessary. */ void svn_xml_make_open_tag_hash(svn_stringbuf_t **str, apr_pool_t *pool, enum svn_xml_open_tag_style style, const char *tagname, apr_hash_t *attributes); /** Store an xml close tag @a tagname in @a str. * * If @a *str is @c NULL, set @a *str to a new stringbuf allocated * in @a pool, else append to the existing stringbuf there. */ void svn_xml_make_close_tag(svn_stringbuf_t **str, apr_pool_t *pool, const char *tagname); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* SVN_XML_H */
5d0a6b62eedc80d4a6f2127c8898621e433e9213
1efd2de8bf77ec00eb2fcaf5749278495946d920
/src/pipeline/cli_mod.c
ea8b727dee545cfa3dfe397313903b789ebc1af2
[ "BSD-2-Clause", "BSD-2-Clause-Patent" ]
permissive
daos-stack/daos
6f55bf3061fd830d5b8d28506e1295e2d3a27c38
ed5eed5df43a68571afe123132a743824c02637a
refs/heads/master
2023-08-31T21:43:37.606145
2023-08-31T16:38:00
2023-08-31T16:38:00
69,390,670
631
300
NOASSERTION
2023-09-14T18:55:15
2016-09-27T19:21:29
C
UTF-8
C
false
false
627
c
cli_mod.c
/** * (C) Copyright 2016-2023 Intel Corporation. * * SPDX-License-Identifier: BSD-2-Clause-Patent */ #define D_LOGFAC DD_FAC(pipeline) #include <daos/common.h> #include "pipeline_rpc.h" int dc_pipeline_init(void) { int rc; rc = daos_rpc_register(&pipeline_proto_fmt, PIPELINE_PROTO_CLI_COUNT, NULL, DAOS_PIPELINE_MODULE); if (rc != 0) D_ERROR("failed to register DAOS pipeline RPCs: " DF_RC "\n", DP_RC(rc)); return rc; } void dc_pipeline_fini(void) { int rc; rc = daos_rpc_unregister(&pipeline_proto_fmt); if (rc != 0) D_ERROR("failed to unregister DAOS pipeline RPCs: "DF_RC"\n", DP_RC(rc)); }
2d5e6862087343c1ac9f6afb32b8f4dd24748778
aa3befea459382dc5c01c925653d54f435b3fb0f
/boards/arm/nrf52/nrf52840-dk/src/nrf52_highpri.c
f926bccf7e53e506db01c1db477ba4d95ddc7b1f
[ "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
7,912
c
nrf52_highpri.c
/**************************************************************************** * boards/arm/nrf52/nrf52840-dk/src/nrf52_highpri.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 <inttypes.h> #include <stdio.h> #include <stdlib.h> #include <strings.h> #include <unistd.h> #include <assert.h> #include <nuttx/arch.h> #include <nuttx/signal.h> #include <arch/irq.h> #include <arch/armv7-m/nvicpri.h> #include "arm_internal.h" #include "ram_vectors.h" #include "nrf52_tim.h" #include <arch/board/board.h> #ifdef CONFIG_NRF52840DK_HIGHPRI /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ /* Configuration ************************************************************/ #ifndef CONFIG_ARCH_HIPRI_INTERRUPT # error CONFIG_ARCH_HIPRI_INTERRUPT is required #endif #ifndef CONFIG_ARCH_RAMVECTORS # error CONFIG_ARCH_RAMVECTORS is required #endif #ifndef CONFIG_ARCH_IRQPRIO # error CONFIG_ARCH_IRQPRIO is required #endif #ifndef CONFIG_NRF52_TIMER0 # error CONFIG_NRF52_TIMER0 is required #endif /* Timer configuration */ #define NRF52_HIGHPRI_TIMER (0) #define NRF52_HIGHPRI_TIMER_IRQ (NRF52_IRQ_TIMER0) #define NRF52_TIMER_PRESCALER (NRF52_TIM_PRE_16000000) /**************************************************************************** * Private Types ****************************************************************************/ struct highpri_s { struct nrf52_tim_dev_s *dev; volatile uint64_t basepri[16]; volatile uint64_t handler; volatile uint64_t thread; }; /**************************************************************************** * Private Data ****************************************************************************/ static struct highpri_s g_highpri; /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Name: timer_handler * * Description: * This is the handler for the high speed TIMER0 interrupt. * ****************************************************************************/ void timer_handler(void) { uint8_t basepri; int index; int ret; /* Verify interrupt source */ ret = NRF52_TIM_CHECKINT(g_highpri.dev, NRF52_TIM_CC0); if (ret != 1) { DEBUGPANIC(); } /* Increment the count associated with the current basepri */ basepri = getbasepri(); index = ((basepri >> 4) & 15); g_highpri.basepri[index]++; /* Check if we are in an interrupt handle */ if (up_interrupt_context()) { g_highpri.handler++; } else { g_highpri.thread++; } /* Clear event */ NRF52_TIM_ACKINT(g_highpri.dev, NRF52_TIM_CC0); } /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: highpri_main * * Description: * Main entry point in into the high priority interrupt test. * ****************************************************************************/ int highpri_main(int argc, char *argv[]) { struct nrf52_tim_dev_s *tim = NULL; uint64_t basepri[16]; uint64_t handler; uint64_t thread; uint64_t total; uint32_t seconds; int ret; int i; /* Initialzie TIMER */ tim = nrf52_tim_init(NRF52_HIGHPRI_TIMER); if (tim == NULL) { printf("ERROR: failed to initialize TIMER%d instance\n", NRF52_HIGHPRI_TIMER); ret = EXIT_FAILURE; goto errout; } g_highpri.dev = tim; /* Configure TIMER mode and width */ ret = NRF52_TIM_CONFIGURE(tim, NRF52_TIM_MODE_TIMER, NRF52_TIM_WIDTH_16B); if (ret < 0) { printf("ERROR: failed to configure timer %d\n", ret); ret = EXIT_FAILURE; goto errout; } /* Configure TIMER prescaler */ ret = NRF52_TIM_SETPRE(tim, NRF52_TIMER_PRESCALER); if (ret < 0) { printf("ERROR: failed to set timer prescaler %d\n", ret); ret = EXIT_FAILURE; goto errout; } /* Set TIMER CC0 */ ret = NRF52_TIM_SETCC(tim, NRF52_TIM_CC0, 0x01); if (ret < 0) { printf("ERROR: failed to set TIMER CC %d\n", ret); ret = EXIT_FAILURE; goto errout; } /* Enable IRQ for TIMER CC0 */ ret = NRF52_TIM_ENABLEINT(tim, NRF52_TIM_INT_COMPARE0); if (ret < 0) { printf("ERROR: failed to enable TIMER0 CC IRQ %d\n", ret); ret = EXIT_FAILURE; goto errout; } /* Attach TIMER ram vector */ ret = arm_ramvec_attach(NRF52_HIGHPRI_TIMER_IRQ, timer_handler); if (ret < 0) { fprintf(stderr, "highpri_main: ERROR: arm_ramvec_attach failed: %d\n", ret); ret = EXIT_FAILURE; goto errout; } /* Set the priority of the TIM6 interrupt vector */ ret = up_prioritize_irq(NRF52_HIGHPRI_TIMER_IRQ, NVIC_SYSH_HIGH_PRIORITY); if (ret < 0) { fprintf(stderr, "highpri_main: ERROR: up_prioritize_irq failed: %d\n", ret); ret = EXIT_FAILURE; goto errout; } /* Enable the timer interrupt at the NVIC and at TIMER */ up_enable_irq(NRF52_HIGHPRI_TIMER_IRQ); NRF52_TIM_START(tim); seconds = 0; while (1) { /* Flush stdout and wait a bit */ fflush(stdout); nxsig_sleep(1); seconds++; /* Sample counts so that they are not volatile. Missing a count now * and then is a normal consequence of this design. */ for (i = 0; i < 16; i++) { basepri[i] = g_highpri.basepri[i]; } handler = g_highpri.handler; thread = g_highpri.thread; /* Then print out what is happening */ printf("Elapsed time: %" PRId32 " seconds\n\n", seconds); for (i = 0, total = 0; i < 16; i++) { total += basepri[i]; } if (total > 0) { for (i = 0; i < 16; i++) { if (basepri[i] > 0) { printf(" basepri[%02x]: %lld (%d%%)\n", i << 4, basepri[i], (int)((100 * basepri[i] + (total / 2)) / total)); } } } total = handler + thread; if (total > 0) { printf(" Handler: %lld (%d%%)\n", handler, (int)((100*handler + (total / 2)) / total)); printf(" Thread: %lld (%d%%)\n\n", thread, (int)((100*thread + (total / 2)) / total)); } } ret = EXIT_SUCCESS; errout: return ret; } #endif /* CONFIG_NRF52840DK_HIGHPRI */
fabd3a4268be5a79d60dfeafe90fd1a97b94a7c8
83b8b30ebb633eecd29ca0a7a20cc43a293c9333
/ports/espressif/common-hal/espcamera/Camera.c
574b4e846be7b134ecf5475ec824436a99ef1756
[ "GPL-1.0-or-later", "MIT" ]
permissive
adafruit/circuitpython
430ec895149d1eb814b505db39b4977a35ee88a7
506dca71b0cbb7af749bb51f86b01021db5483b3
refs/heads/main
2023-08-21T16:30:46.781068
2023-08-20T00:39:44
2023-08-20T00:39:44
66,166,069
3,806
1,560
MIT
2023-09-14T19:23:51
2016-08-20T20:10:40
C
UTF-8
C
false
false
12,448
c
Camera.c
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2022 Jeff Epler for Adafruit Industries * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "py/mperrno.h" #include "py/runtime.h" #include "bindings/espcamera/Camera.h" #include "bindings/espidf/__init__.h" #include "common-hal/espcamera/Camera.h" #include "shared-bindings/busio/I2C.h" #include "shared-bindings/microcontroller/Pin.h" #include "shared-bindings/util.h" #include "common-hal/microcontroller/Pin.h" #include "esp32-camera/driver/private_include/cam_hal.h" #if !CONFIG_SPIRAM #error espcamera only works on boards configured with spiram, disable it in mpconfigboard.mk #endif static void i2c_lock(espcamera_camera_obj_t *self) { if (common_hal_busio_i2c_deinited(self->i2c)) { raise_deinited_error(); } if (!common_hal_busio_i2c_try_lock(self->i2c)) { mp_raise_OSError(MP_EWOULDBLOCK); } } static void i2c_unlock(espcamera_camera_obj_t *self) { common_hal_busio_i2c_unlock(self->i2c); } static void maybe_claim_pin(const mcu_pin_obj_t *pin) { if (pin) { claim_pin(pin); } } void common_hal_espcamera_camera_construct( espcamera_camera_obj_t *self, uint8_t data_pins[8], const mcu_pin_obj_t *external_clock_pin, const mcu_pin_obj_t *pixel_clock_pin, const mcu_pin_obj_t *vsync_pin, const mcu_pin_obj_t *href_pin, const mcu_pin_obj_t *powerdown_pin, const mcu_pin_obj_t *reset_pin, busio_i2c_obj_t *i2c, mp_int_t external_clock_frequency, pixformat_t pixel_format, framesize_t frame_size, mp_int_t jpeg_quality, mp_int_t framebuffer_count, camera_grab_mode_t grab_mode) { if (common_hal_espidf_get_reserved_psram() == 0) { mp_raise_msg(&mp_type_MemoryError, translate( "espcamera.Camera requires reserved PSRAM to be configured. See the documentation for instructions.")); } for (int i = 0; i < 8; i++) { claim_pin_number(data_pins[i]); } maybe_claim_pin(external_clock_pin); claim_pin(pixel_clock_pin); claim_pin(vsync_pin); claim_pin(href_pin); maybe_claim_pin(powerdown_pin); maybe_claim_pin(reset_pin); if (external_clock_pin) { common_hal_pwmio_pwmout_construct(&self->pwm, external_clock_pin, 1, external_clock_frequency, true); self->camera_config.ledc_timer = self->pwm.tim_handle.timer_num; self->camera_config.ledc_channel = self->pwm.chan_handle.channel; } else { self->camera_config.ledc_channel = 0xff; // NO_CAMERA_LEDC_CHANNEL } self->i2c = i2c; self->camera_config.pin_pwdn = common_hal_mcu_pin_number(powerdown_pin); self->camera_config.pin_reset = common_hal_mcu_pin_number(reset_pin); self->camera_config.pin_xclk = common_hal_mcu_pin_number(external_clock_pin); self->camera_config.pin_sccb_sda = NO_PIN; self->camera_config.pin_sccb_scl = NO_PIN; /* sccb i2c port set below */ self->camera_config.pin_d7 = data_pins[7]; self->camera_config.pin_d6 = data_pins[6]; self->camera_config.pin_d5 = data_pins[5]; self->camera_config.pin_d4 = data_pins[4]; self->camera_config.pin_d3 = data_pins[3]; self->camera_config.pin_d2 = data_pins[2]; self->camera_config.pin_d1 = data_pins[1]; self->camera_config.pin_d0 = data_pins[0]; self->camera_config.pin_vsync = common_hal_mcu_pin_number(vsync_pin); self->camera_config.pin_href = common_hal_mcu_pin_number(href_pin); self->camera_config.pin_pclk = common_hal_mcu_pin_number(pixel_clock_pin); self->camera_config.xclk_freq_hz = external_clock_frequency; self->camera_config.pixel_format = pixel_format; self->camera_config.frame_size = frame_size; self->camera_config.jpeg_quality = jpeg_quality; self->camera_config.fb_count = framebuffer_count; self->camera_config.grab_mode = grab_mode; self->camera_config.sccb_i2c_port = i2c->i2c_num; i2c_lock(self); esp_err_t result = esp_camera_init(&self->camera_config); i2c_unlock(self); CHECK_ESP_RESULT(result); } extern void common_hal_espcamera_camera_deinit(espcamera_camera_obj_t *self) { if (common_hal_espcamera_camera_deinited(self)) { return; } common_hal_pwmio_pwmout_deinit(&self->pwm); reset_pin_number(self->camera_config.pin_pwdn); reset_pin_number(self->camera_config.pin_reset); reset_pin_number(self->camera_config.pin_xclk); reset_pin_number(self->camera_config.pin_d7); reset_pin_number(self->camera_config.pin_d6); reset_pin_number(self->camera_config.pin_d5); reset_pin_number(self->camera_config.pin_d4); reset_pin_number(self->camera_config.pin_d3); reset_pin_number(self->camera_config.pin_d2); reset_pin_number(self->camera_config.pin_d1); reset_pin_number(self->camera_config.pin_d0); esp_camera_deinit(); self->camera_config.xclk_freq_hz = 0; } bool common_hal_espcamera_camera_deinited(espcamera_camera_obj_t *self) { return !self->camera_config.xclk_freq_hz; } bool common_hal_espcamera_camera_available(espcamera_camera_obj_t *self) { return esp_camera_fb_available(); } camera_fb_t *common_hal_espcamera_camera_take(espcamera_camera_obj_t *self, int timeout_ms) { if (self->buffer_to_return) { esp_camera_fb_return(self->buffer_to_return); self->buffer_to_return = NULL; } return self->buffer_to_return = esp_camera_fb_get_timeout(timeout_ms); } #define SENSOR_GETSET(type, name, field_name, setter_function_name) \ SENSOR_GET(type, name, field_name, setter_function_name) \ SENSOR_SET(type, name, setter_function_name) #define SENSOR_STATUS_GETSET(type, name, status_field_name, setter_function_name) \ SENSOR_GETSET(type, name, status.status_field_name, setter_function_name) #define SENSOR_GET(type, name, status_field_name, setter_function_name) \ type common_hal_espcamera_camera_get_##name(espcamera_camera_obj_t * self) { \ i2c_lock(self); \ sensor_t *sensor = esp_camera_sensor_get(); \ i2c_unlock(self); \ if (!sensor->setter_function_name) { \ mp_raise_AttributeError(translate("no such attribute")); \ } \ return sensor->status_field_name; \ } #define SENSOR_SET(type, name, setter_function_name) \ void common_hal_espcamera_camera_set_##name(espcamera_camera_obj_t * self, type value) { \ i2c_lock(self); \ sensor_t *sensor = esp_camera_sensor_get(); \ i2c_unlock(self); \ if (!sensor->setter_function_name) { \ mp_raise_AttributeError(translate("no such attribute")); \ } \ if (sensor->setter_function_name(sensor, value) < 0) { \ mp_raise_ValueError(translate("invalid setting")); \ } \ } pixformat_t common_hal_espcamera_camera_get_pixel_format(espcamera_camera_obj_t *self) { return self->camera_config.pixel_format; } framesize_t common_hal_espcamera_camera_get_frame_size(espcamera_camera_obj_t *self) { return self->camera_config.frame_size; } void common_hal_espcamera_camera_reconfigure(espcamera_camera_obj_t *self, framesize_t frame_size, pixformat_t pixel_format, camera_grab_mode_t grab_mode, mp_int_t framebuffer_count) { sensor_t *sensor = esp_camera_sensor_get(); camera_sensor_info_t *sensor_info = esp_camera_sensor_get_info(&sensor->id); if (PIXFORMAT_JPEG == pixel_format && (!sensor_info->support_jpeg)) { raise_esp_error(ESP_ERR_NOT_SUPPORTED); } if (frame_size > sensor_info->max_size) { frame_size = sensor_info->max_size; } i2c_lock(self); cam_deinit(); self->camera_config.pixel_format = pixel_format; self->camera_config.frame_size = frame_size; self->camera_config.grab_mode = grab_mode; self->camera_config.fb_count = framebuffer_count; sensor->set_pixformat(sensor, self->camera_config.pixel_format); sensor->set_framesize(sensor, self->camera_config.frame_size); cam_init(&self->camera_config); cam_config(&self->camera_config, frame_size, sensor_info->pid); i2c_unlock(self); cam_start(); } SENSOR_STATUS_GETSET(int, contrast, contrast, set_contrast); SENSOR_STATUS_GETSET(int, brightness, brightness, set_brightness); SENSOR_STATUS_GETSET(int, saturation, saturation, set_saturation); SENSOR_STATUS_GETSET(int, sharpness, sharpness, set_sharpness); SENSOR_STATUS_GETSET(int, denoise, denoise, set_denoise); SENSOR_STATUS_GETSET(gainceiling_t, gainceiling, gainceiling, set_gainceiling); SENSOR_STATUS_GETSET(int, quality, quality, set_quality); SENSOR_STATUS_GETSET(bool, colorbar, colorbar, set_colorbar); SENSOR_STATUS_GETSET(bool, whitebal, awb, set_whitebal); SENSOR_STATUS_GETSET(bool, gain_ctrl, agc, set_gain_ctrl); SENSOR_STATUS_GETSET(bool, exposure_ctrl, aec, set_exposure_ctrl); SENSOR_STATUS_GETSET(bool, hmirror, hmirror, set_hmirror); SENSOR_STATUS_GETSET(bool, vflip, vflip, set_vflip); SENSOR_STATUS_GETSET(bool, aec2, aec2, set_aec2); SENSOR_STATUS_GETSET(bool, awb_gain, awb_gain, set_awb_gain); SENSOR_STATUS_GETSET(int, agc_gain, agc_gain, set_agc_gain); SENSOR_STATUS_GETSET(int, aec_value, aec_value, set_aec_value); SENSOR_STATUS_GETSET(int, special_effect, special_effect, set_special_effect); SENSOR_STATUS_GETSET(int, wb_mode, wb_mode, set_wb_mode); SENSOR_STATUS_GETSET(int, ae_level, ae_level, set_ae_level); SENSOR_STATUS_GETSET(bool, dcw, dcw, set_dcw); SENSOR_STATUS_GETSET(bool, bpc, bpc, set_bpc); SENSOR_STATUS_GETSET(bool, wpc, wpc, set_wpc); SENSOR_STATUS_GETSET(bool, raw_gma, raw_gma, set_raw_gma); SENSOR_STATUS_GETSET(bool, lenc, lenc, set_lenc); const char *common_hal_espcamera_camera_get_sensor_name(espcamera_camera_obj_t *self) { sensor_t *sensor = esp_camera_sensor_get(); camera_sensor_info_t *sensor_info = esp_camera_sensor_get_info(&sensor->id); return sensor_info->name; } const bool common_hal_espcamera_camera_get_supports_jpeg(espcamera_camera_obj_t *self) { sensor_t *sensor = esp_camera_sensor_get(); camera_sensor_info_t *sensor_info = esp_camera_sensor_get_info(&sensor->id); return sensor_info->support_jpeg; } const framesize_t common_hal_espcamera_camera_get_max_frame_size(espcamera_camera_obj_t *self) { sensor_t *sensor = esp_camera_sensor_get(); camera_sensor_info_t *sensor_info = esp_camera_sensor_get_info(&sensor->id); return sensor_info->max_size; } const int common_hal_espcamera_camera_get_address(espcamera_camera_obj_t *self) { sensor_t *sensor = esp_camera_sensor_get(); camera_sensor_info_t *sensor_info = esp_camera_sensor_get_info(&sensor->id); return sensor_info->sccb_addr; } const int common_hal_espcamera_camera_get_width(espcamera_camera_obj_t *self) { sensor_t *sensor = esp_camera_sensor_get(); framesize_t framesize = sensor->status.framesize; return resolution[framesize].width; } const int common_hal_espcamera_camera_get_height(espcamera_camera_obj_t *self) { sensor_t *sensor = esp_camera_sensor_get(); framesize_t framesize = sensor->status.framesize; return resolution[framesize].height; } const camera_grab_mode_t common_hal_espcamera_camera_get_grab_mode(espcamera_camera_obj_t *self) { return self->camera_config.grab_mode; } const int common_hal_espcamera_camera_get_framebuffer_count(espcamera_camera_obj_t *self) { return self->camera_config.fb_count; }
d3c16e03e13d188285897d6d98a020f256a4989a
aa3befea459382dc5c01c925653d54f435b3fb0f
/arch/arm/src/nrf91/nrf91_modem.c
90ebe45d8137f56c35abcc64e5c4cfaaf55258d7
[ "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
3,857
c
nrf91_modem.c
/**************************************************************************** * arch/arm/src/nrf91/nrf91_modem.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 <debug.h> #include <assert.h> #include "chip.h" #include "nrf_modem.h" #include "nrf91_modem.h" /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ #ifndef CONFIG_ARCH_TRUSTZONE_NONSECURE # error NRF91 modem works only in non-secure environment #endif #ifndef CONFIG_NRF91_LFCLK_XTAL # error NRF91 modem requires using LFXO as the LFCLK source #endif /**************************************************************************** * Private Function Prototypes ****************************************************************************/ static void nrf91_modem_fault_handler(struct nrf_modem_fault_info *info); /**************************************************************************** * Private Data ****************************************************************************/ /* Modem library parameters - must be allocated in data segment */ static const struct nrf_modem_init_params g_init_params = { .shmem = { .ctrl = { .base = NRF91_SHMEM_CTRL_BASE, .size = NRF91_SHMEM_CTRL_SIZE }, .tx = { .base = NRF91_SHMEM_TX_BASE, .size = NRF91_SHMEM_TX_SIZE }, .rx = { .base = NRF91_SHMEM_RX_BASE, .size = NRF91_SHMEM_RX_SIZE }, .trace = { .base = NRF91_SHMEM_TRACE_BASE, .size = NRF91_SHMEM_TRACE_SIZE } }, .ipc_irq_prio = NVIC_SYSH_PRIORITY_DEFAULT, .fault_handler = nrf91_modem_fault_handler }; /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Name: nrf91_modem_fault_handler ****************************************************************************/ static void nrf91_modem_fault_handler(struct nrf_modem_fault_info *info) { nerr("Modem hard fault"); ASSERT(0); } /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: nrf91_modem_initialize ****************************************************************************/ int nrf91_modem_initialize(void) { int ret = OK; /* Initialize modem */ ret = nrf_modem_init(&g_init_params); if (ret < 0) { nerr("nrf_modem_init failed %d\n", ret); } return ret; }
0035dee08c63ca2ff9cafe5433b8902cfb61162d
52c0949315583ba8898694cceacfaafaeab6f902
/third_party/libpg_query/src/postgres/include/utils/builtins.h
f5c8a8ff73dcdb343865e7629e831996d211785d
[ "BSD-3-Clause", "PostgreSQL", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
cmu-db/noisepage
97093adcc9474419e063fdd97a5aa7a7ea6f3150
79276e68fe83322f1249e8a8be96bd63c583ae56
refs/heads/master
2023-08-29T05:51:04.628704
2021-11-05T14:12:08
2021-11-05T14:12:08
140,325,970
1,245
287
MIT
2022-11-08T02:06:48
2018-07-09T18:22:34
C++
UTF-8
C
false
false
54,304
h
builtins.h
/*------------------------------------------------------------------------- * * builtins.h * Declarations for operations on built-in types. * * * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * src/include/utils/builtins.h * *------------------------------------------------------------------------- */ #ifndef BUILTINS_H #define BUILTINS_H #include "fmgr.h" #include "nodes/parsenodes.h" /* * Defined in adt/ */ /* acl.c */ extern Datum has_any_column_privilege_name_name(PG_FUNCTION_ARGS); extern Datum has_any_column_privilege_name_id(PG_FUNCTION_ARGS); extern Datum has_any_column_privilege_id_name(PG_FUNCTION_ARGS); extern Datum has_any_column_privilege_id_id(PG_FUNCTION_ARGS); extern Datum has_any_column_privilege_name(PG_FUNCTION_ARGS); extern Datum has_any_column_privilege_id(PG_FUNCTION_ARGS); extern Datum has_column_privilege_name_name_name(PG_FUNCTION_ARGS); extern Datum has_column_privilege_name_name_attnum(PG_FUNCTION_ARGS); extern Datum has_column_privilege_name_id_name(PG_FUNCTION_ARGS); extern Datum has_column_privilege_name_id_attnum(PG_FUNCTION_ARGS); extern Datum has_column_privilege_id_name_name(PG_FUNCTION_ARGS); extern Datum has_column_privilege_id_name_attnum(PG_FUNCTION_ARGS); extern Datum has_column_privilege_id_id_name(PG_FUNCTION_ARGS); extern Datum has_column_privilege_id_id_attnum(PG_FUNCTION_ARGS); extern Datum has_column_privilege_name_name(PG_FUNCTION_ARGS); extern Datum has_column_privilege_name_attnum(PG_FUNCTION_ARGS); extern Datum has_column_privilege_id_name(PG_FUNCTION_ARGS); extern Datum has_column_privilege_id_attnum(PG_FUNCTION_ARGS); extern Datum has_table_privilege_name_name(PG_FUNCTION_ARGS); extern Datum has_table_privilege_name_id(PG_FUNCTION_ARGS); extern Datum has_table_privilege_id_name(PG_FUNCTION_ARGS); extern Datum has_table_privilege_id_id(PG_FUNCTION_ARGS); extern Datum has_table_privilege_name(PG_FUNCTION_ARGS); extern Datum has_table_privilege_id(PG_FUNCTION_ARGS); extern Datum has_sequence_privilege_name_name(PG_FUNCTION_ARGS); extern Datum has_sequence_privilege_name_id(PG_FUNCTION_ARGS); extern Datum has_sequence_privilege_id_name(PG_FUNCTION_ARGS); extern Datum has_sequence_privilege_id_id(PG_FUNCTION_ARGS); extern Datum has_sequence_privilege_name(PG_FUNCTION_ARGS); extern Datum has_sequence_privilege_id(PG_FUNCTION_ARGS); extern Datum has_database_privilege_name_name(PG_FUNCTION_ARGS); extern Datum has_database_privilege_name_id(PG_FUNCTION_ARGS); extern Datum has_database_privilege_id_name(PG_FUNCTION_ARGS); extern Datum has_database_privilege_id_id(PG_FUNCTION_ARGS); extern Datum has_database_privilege_name(PG_FUNCTION_ARGS); extern Datum has_database_privilege_id(PG_FUNCTION_ARGS); extern Datum has_foreign_data_wrapper_privilege_name_name(PG_FUNCTION_ARGS); extern Datum has_foreign_data_wrapper_privilege_name_id(PG_FUNCTION_ARGS); extern Datum has_foreign_data_wrapper_privilege_id_name(PG_FUNCTION_ARGS); extern Datum has_foreign_data_wrapper_privilege_id_id(PG_FUNCTION_ARGS); extern Datum has_foreign_data_wrapper_privilege_name(PG_FUNCTION_ARGS); extern Datum has_foreign_data_wrapper_privilege_id(PG_FUNCTION_ARGS); extern Datum has_function_privilege_name_name(PG_FUNCTION_ARGS); extern Datum has_function_privilege_name_id(PG_FUNCTION_ARGS); extern Datum has_function_privilege_id_name(PG_FUNCTION_ARGS); extern Datum has_function_privilege_id_id(PG_FUNCTION_ARGS); extern Datum has_function_privilege_name(PG_FUNCTION_ARGS); extern Datum has_function_privilege_id(PG_FUNCTION_ARGS); extern Datum has_language_privilege_name_name(PG_FUNCTION_ARGS); extern Datum has_language_privilege_name_id(PG_FUNCTION_ARGS); extern Datum has_language_privilege_id_name(PG_FUNCTION_ARGS); extern Datum has_language_privilege_id_id(PG_FUNCTION_ARGS); extern Datum has_language_privilege_name(PG_FUNCTION_ARGS); extern Datum has_language_privilege_id(PG_FUNCTION_ARGS); extern Datum has_schema_privilege_name_name(PG_FUNCTION_ARGS); extern Datum has_schema_privilege_name_id(PG_FUNCTION_ARGS); extern Datum has_schema_privilege_id_name(PG_FUNCTION_ARGS); extern Datum has_schema_privilege_id_id(PG_FUNCTION_ARGS); extern Datum has_schema_privilege_name(PG_FUNCTION_ARGS); extern Datum has_schema_privilege_id(PG_FUNCTION_ARGS); extern Datum has_server_privilege_name_name(PG_FUNCTION_ARGS); extern Datum has_server_privilege_name_id(PG_FUNCTION_ARGS); extern Datum has_server_privilege_id_name(PG_FUNCTION_ARGS); extern Datum has_server_privilege_id_id(PG_FUNCTION_ARGS); extern Datum has_server_privilege_name(PG_FUNCTION_ARGS); extern Datum has_server_privilege_id(PG_FUNCTION_ARGS); extern Datum has_tablespace_privilege_name_name(PG_FUNCTION_ARGS); extern Datum has_tablespace_privilege_name_id(PG_FUNCTION_ARGS); extern Datum has_tablespace_privilege_id_name(PG_FUNCTION_ARGS); extern Datum has_tablespace_privilege_id_id(PG_FUNCTION_ARGS); extern Datum has_tablespace_privilege_name(PG_FUNCTION_ARGS); extern Datum has_tablespace_privilege_id(PG_FUNCTION_ARGS); extern Datum has_type_privilege_name_name(PG_FUNCTION_ARGS); extern Datum has_type_privilege_name_id(PG_FUNCTION_ARGS); extern Datum has_type_privilege_id_name(PG_FUNCTION_ARGS); extern Datum has_type_privilege_id_id(PG_FUNCTION_ARGS); extern Datum has_type_privilege_name(PG_FUNCTION_ARGS); extern Datum has_type_privilege_id(PG_FUNCTION_ARGS); extern Datum pg_has_role_name_name(PG_FUNCTION_ARGS); extern Datum pg_has_role_name_id(PG_FUNCTION_ARGS); extern Datum pg_has_role_id_name(PG_FUNCTION_ARGS); extern Datum pg_has_role_id_id(PG_FUNCTION_ARGS); extern Datum pg_has_role_name(PG_FUNCTION_ARGS); extern Datum pg_has_role_id(PG_FUNCTION_ARGS); /* bool.c */ extern Datum boolin(PG_FUNCTION_ARGS); extern Datum boolout(PG_FUNCTION_ARGS); extern Datum boolrecv(PG_FUNCTION_ARGS); extern Datum boolsend(PG_FUNCTION_ARGS); extern Datum booltext(PG_FUNCTION_ARGS); extern Datum booleq(PG_FUNCTION_ARGS); extern Datum boolne(PG_FUNCTION_ARGS); extern Datum boollt(PG_FUNCTION_ARGS); extern Datum boolgt(PG_FUNCTION_ARGS); extern Datum boolle(PG_FUNCTION_ARGS); extern Datum boolge(PG_FUNCTION_ARGS); extern Datum booland_statefunc(PG_FUNCTION_ARGS); extern Datum boolor_statefunc(PG_FUNCTION_ARGS); extern Datum bool_accum(PG_FUNCTION_ARGS); extern Datum bool_accum_inv(PG_FUNCTION_ARGS); extern Datum bool_alltrue(PG_FUNCTION_ARGS); extern Datum bool_anytrue(PG_FUNCTION_ARGS); extern bool parse_bool(const char *value, bool *result); extern bool parse_bool_with_len(const char *value, size_t len, bool *result); /* char.c */ extern Datum charin(PG_FUNCTION_ARGS); extern Datum charout(PG_FUNCTION_ARGS); extern Datum charrecv(PG_FUNCTION_ARGS); extern Datum charsend(PG_FUNCTION_ARGS); extern Datum chareq(PG_FUNCTION_ARGS); extern Datum charne(PG_FUNCTION_ARGS); extern Datum charlt(PG_FUNCTION_ARGS); extern Datum charle(PG_FUNCTION_ARGS); extern Datum chargt(PG_FUNCTION_ARGS); extern Datum charge(PG_FUNCTION_ARGS); extern Datum chartoi4(PG_FUNCTION_ARGS); extern Datum i4tochar(PG_FUNCTION_ARGS); extern Datum text_char(PG_FUNCTION_ARGS); extern Datum char_text(PG_FUNCTION_ARGS); /* domains.c */ extern Datum domain_in(PG_FUNCTION_ARGS); extern Datum domain_recv(PG_FUNCTION_ARGS); extern void domain_check(Datum value, bool isnull, Oid domainType, void **extra, MemoryContext mcxt); extern int errdatatype(Oid datatypeOid); extern int errdomainconstraint(Oid datatypeOid, const char *conname); /* encode.c */ extern Datum binary_encode(PG_FUNCTION_ARGS); extern Datum binary_decode(PG_FUNCTION_ARGS); extern unsigned hex_encode(const char *src, unsigned len, char *dst); extern unsigned hex_decode(const char *src, unsigned len, char *dst); /* enum.c */ extern Datum enum_in(PG_FUNCTION_ARGS); extern Datum enum_out(PG_FUNCTION_ARGS); extern Datum enum_recv(PG_FUNCTION_ARGS); extern Datum enum_send(PG_FUNCTION_ARGS); extern Datum enum_lt(PG_FUNCTION_ARGS); extern Datum enum_le(PG_FUNCTION_ARGS); extern Datum enum_eq(PG_FUNCTION_ARGS); extern Datum enum_ne(PG_FUNCTION_ARGS); extern Datum enum_ge(PG_FUNCTION_ARGS); extern Datum enum_gt(PG_FUNCTION_ARGS); extern Datum enum_cmp(PG_FUNCTION_ARGS); extern Datum enum_smaller(PG_FUNCTION_ARGS); extern Datum enum_larger(PG_FUNCTION_ARGS); extern Datum enum_first(PG_FUNCTION_ARGS); extern Datum enum_last(PG_FUNCTION_ARGS); extern Datum enum_range_bounds(PG_FUNCTION_ARGS); extern Datum enum_range_all(PG_FUNCTION_ARGS); /* int.c */ extern Datum int2in(PG_FUNCTION_ARGS); extern Datum int2out(PG_FUNCTION_ARGS); extern Datum int2recv(PG_FUNCTION_ARGS); extern Datum int2send(PG_FUNCTION_ARGS); extern Datum int2vectorin(PG_FUNCTION_ARGS); extern Datum int2vectorout(PG_FUNCTION_ARGS); extern Datum int2vectorrecv(PG_FUNCTION_ARGS); extern Datum int2vectorsend(PG_FUNCTION_ARGS); extern Datum int2vectoreq(PG_FUNCTION_ARGS); extern Datum int4in(PG_FUNCTION_ARGS); extern Datum int4out(PG_FUNCTION_ARGS); extern Datum int4recv(PG_FUNCTION_ARGS); extern Datum int4send(PG_FUNCTION_ARGS); extern Datum i2toi4(PG_FUNCTION_ARGS); extern Datum i4toi2(PG_FUNCTION_ARGS); extern Datum int4_bool(PG_FUNCTION_ARGS); extern Datum bool_int4(PG_FUNCTION_ARGS); extern Datum int4eq(PG_FUNCTION_ARGS); extern Datum int4ne(PG_FUNCTION_ARGS); extern Datum int4lt(PG_FUNCTION_ARGS); extern Datum int4le(PG_FUNCTION_ARGS); extern Datum int4gt(PG_FUNCTION_ARGS); extern Datum int4ge(PG_FUNCTION_ARGS); extern Datum int2eq(PG_FUNCTION_ARGS); extern Datum int2ne(PG_FUNCTION_ARGS); extern Datum int2lt(PG_FUNCTION_ARGS); extern Datum int2le(PG_FUNCTION_ARGS); extern Datum int2gt(PG_FUNCTION_ARGS); extern Datum int2ge(PG_FUNCTION_ARGS); extern Datum int24eq(PG_FUNCTION_ARGS); extern Datum int24ne(PG_FUNCTION_ARGS); extern Datum int24lt(PG_FUNCTION_ARGS); extern Datum int24le(PG_FUNCTION_ARGS); extern Datum int24gt(PG_FUNCTION_ARGS); extern Datum int24ge(PG_FUNCTION_ARGS); extern Datum int42eq(PG_FUNCTION_ARGS); extern Datum int42ne(PG_FUNCTION_ARGS); extern Datum int42lt(PG_FUNCTION_ARGS); extern Datum int42le(PG_FUNCTION_ARGS); extern Datum int42gt(PG_FUNCTION_ARGS); extern Datum int42ge(PG_FUNCTION_ARGS); extern Datum int4um(PG_FUNCTION_ARGS); extern Datum int4up(PG_FUNCTION_ARGS); extern Datum int4pl(PG_FUNCTION_ARGS); extern Datum int4mi(PG_FUNCTION_ARGS); extern Datum int4mul(PG_FUNCTION_ARGS); extern Datum int4div(PG_FUNCTION_ARGS); extern Datum int4abs(PG_FUNCTION_ARGS); extern Datum int4inc(PG_FUNCTION_ARGS); extern Datum int2um(PG_FUNCTION_ARGS); extern Datum int2up(PG_FUNCTION_ARGS); extern Datum int2pl(PG_FUNCTION_ARGS); extern Datum int2mi(PG_FUNCTION_ARGS); extern Datum int2mul(PG_FUNCTION_ARGS); extern Datum int2div(PG_FUNCTION_ARGS); extern Datum int2abs(PG_FUNCTION_ARGS); extern Datum int24pl(PG_FUNCTION_ARGS); extern Datum int24mi(PG_FUNCTION_ARGS); extern Datum int24mul(PG_FUNCTION_ARGS); extern Datum int24div(PG_FUNCTION_ARGS); extern Datum int42pl(PG_FUNCTION_ARGS); extern Datum int42mi(PG_FUNCTION_ARGS); extern Datum int42mul(PG_FUNCTION_ARGS); extern Datum int42div(PG_FUNCTION_ARGS); extern Datum int4mod(PG_FUNCTION_ARGS); extern Datum int2mod(PG_FUNCTION_ARGS); extern Datum int2larger(PG_FUNCTION_ARGS); extern Datum int2smaller(PG_FUNCTION_ARGS); extern Datum int4larger(PG_FUNCTION_ARGS); extern Datum int4smaller(PG_FUNCTION_ARGS); extern Datum int4and(PG_FUNCTION_ARGS); extern Datum int4or(PG_FUNCTION_ARGS); extern Datum int4xor(PG_FUNCTION_ARGS); extern Datum int4not(PG_FUNCTION_ARGS); extern Datum int4shl(PG_FUNCTION_ARGS); extern Datum int4shr(PG_FUNCTION_ARGS); extern Datum int2and(PG_FUNCTION_ARGS); extern Datum int2or(PG_FUNCTION_ARGS); extern Datum int2xor(PG_FUNCTION_ARGS); extern Datum int2not(PG_FUNCTION_ARGS); extern Datum int2shl(PG_FUNCTION_ARGS); extern Datum int2shr(PG_FUNCTION_ARGS); extern Datum generate_series_int4(PG_FUNCTION_ARGS); extern Datum generate_series_step_int4(PG_FUNCTION_ARGS); extern int2vector *buildint2vector(const int16 *int2s, int n); /* name.c */ extern Datum namein(PG_FUNCTION_ARGS); extern Datum nameout(PG_FUNCTION_ARGS); extern Datum namerecv(PG_FUNCTION_ARGS); extern Datum namesend(PG_FUNCTION_ARGS); extern Datum nameeq(PG_FUNCTION_ARGS); extern Datum namene(PG_FUNCTION_ARGS); extern Datum namelt(PG_FUNCTION_ARGS); extern Datum namele(PG_FUNCTION_ARGS); extern Datum namegt(PG_FUNCTION_ARGS); extern Datum namege(PG_FUNCTION_ARGS); extern int namecpy(Name n1, Name n2); extern int namestrcpy(Name name, const char *str); extern int namestrcmp(Name name, const char *str); extern Datum current_user(PG_FUNCTION_ARGS); extern Datum session_user(PG_FUNCTION_ARGS); extern Datum current_schema(PG_FUNCTION_ARGS); extern Datum current_schemas(PG_FUNCTION_ARGS); /* numutils.c */ extern int32 pg_atoi(const char *s, int size, int c); extern void pg_itoa(int16 i, char *a); extern void pg_ltoa(int32 l, char *a); extern void pg_lltoa(int64 ll, char *a); /* * Per-opclass comparison functions for new btrees. These are * stored in pg_amproc; most are defined in access/nbtree/nbtcompare.c */ extern Datum btboolcmp(PG_FUNCTION_ARGS); extern Datum btint2cmp(PG_FUNCTION_ARGS); extern Datum btint4cmp(PG_FUNCTION_ARGS); extern Datum btint8cmp(PG_FUNCTION_ARGS); extern Datum btfloat4cmp(PG_FUNCTION_ARGS); extern Datum btfloat8cmp(PG_FUNCTION_ARGS); extern Datum btint48cmp(PG_FUNCTION_ARGS); extern Datum btint84cmp(PG_FUNCTION_ARGS); extern Datum btint24cmp(PG_FUNCTION_ARGS); extern Datum btint42cmp(PG_FUNCTION_ARGS); extern Datum btint28cmp(PG_FUNCTION_ARGS); extern Datum btint82cmp(PG_FUNCTION_ARGS); extern Datum btfloat48cmp(PG_FUNCTION_ARGS); extern Datum btfloat84cmp(PG_FUNCTION_ARGS); extern Datum btoidcmp(PG_FUNCTION_ARGS); extern Datum btoidvectorcmp(PG_FUNCTION_ARGS); extern Datum btabstimecmp(PG_FUNCTION_ARGS); extern Datum btreltimecmp(PG_FUNCTION_ARGS); extern Datum bttintervalcmp(PG_FUNCTION_ARGS); extern Datum btcharcmp(PG_FUNCTION_ARGS); extern Datum btnamecmp(PG_FUNCTION_ARGS); extern Datum bttextcmp(PG_FUNCTION_ARGS); extern Datum bttextsortsupport(PG_FUNCTION_ARGS); /* * Per-opclass sort support functions for new btrees. Like the * functions above, these are stored in pg_amproc; most are defined in * access/nbtree/nbtcompare.c */ extern Datum btint2sortsupport(PG_FUNCTION_ARGS); extern Datum btint4sortsupport(PG_FUNCTION_ARGS); extern Datum btint8sortsupport(PG_FUNCTION_ARGS); extern Datum btfloat4sortsupport(PG_FUNCTION_ARGS); extern Datum btfloat8sortsupport(PG_FUNCTION_ARGS); extern Datum btoidsortsupport(PG_FUNCTION_ARGS); extern Datum btnamesortsupport(PG_FUNCTION_ARGS); /* float.c */ extern PGDLLIMPORT int extra_float_digits; extern double get_float8_infinity(void); extern float get_float4_infinity(void); extern double get_float8_nan(void); extern float get_float4_nan(void); extern int is_infinite(double val); extern Datum float4in(PG_FUNCTION_ARGS); extern Datum float4out(PG_FUNCTION_ARGS); extern Datum float4recv(PG_FUNCTION_ARGS); extern Datum float4send(PG_FUNCTION_ARGS); extern Datum float8in(PG_FUNCTION_ARGS); extern Datum float8out(PG_FUNCTION_ARGS); extern Datum float8recv(PG_FUNCTION_ARGS); extern Datum float8send(PG_FUNCTION_ARGS); extern Datum float4abs(PG_FUNCTION_ARGS); extern Datum float4um(PG_FUNCTION_ARGS); extern Datum float4up(PG_FUNCTION_ARGS); extern Datum float4larger(PG_FUNCTION_ARGS); extern Datum float4smaller(PG_FUNCTION_ARGS); extern Datum float8abs(PG_FUNCTION_ARGS); extern Datum float8um(PG_FUNCTION_ARGS); extern Datum float8up(PG_FUNCTION_ARGS); extern Datum float8larger(PG_FUNCTION_ARGS); extern Datum float8smaller(PG_FUNCTION_ARGS); extern Datum float4pl(PG_FUNCTION_ARGS); extern Datum float4mi(PG_FUNCTION_ARGS); extern Datum float4mul(PG_FUNCTION_ARGS); extern Datum float4div(PG_FUNCTION_ARGS); extern Datum float8pl(PG_FUNCTION_ARGS); extern Datum float8mi(PG_FUNCTION_ARGS); extern Datum float8mul(PG_FUNCTION_ARGS); extern Datum float8div(PG_FUNCTION_ARGS); extern Datum float4eq(PG_FUNCTION_ARGS); extern Datum float4ne(PG_FUNCTION_ARGS); extern Datum float4lt(PG_FUNCTION_ARGS); extern Datum float4le(PG_FUNCTION_ARGS); extern Datum float4gt(PG_FUNCTION_ARGS); extern Datum float4ge(PG_FUNCTION_ARGS); extern Datum float8eq(PG_FUNCTION_ARGS); extern Datum float8ne(PG_FUNCTION_ARGS); extern Datum float8lt(PG_FUNCTION_ARGS); extern Datum float8le(PG_FUNCTION_ARGS); extern Datum float8gt(PG_FUNCTION_ARGS); extern Datum float8ge(PG_FUNCTION_ARGS); extern Datum ftod(PG_FUNCTION_ARGS); extern Datum i4tod(PG_FUNCTION_ARGS); extern Datum i2tod(PG_FUNCTION_ARGS); extern Datum dtof(PG_FUNCTION_ARGS); extern Datum dtoi4(PG_FUNCTION_ARGS); extern Datum dtoi2(PG_FUNCTION_ARGS); extern Datum i4tof(PG_FUNCTION_ARGS); extern Datum i2tof(PG_FUNCTION_ARGS); extern Datum ftoi4(PG_FUNCTION_ARGS); extern Datum ftoi2(PG_FUNCTION_ARGS); extern Datum dround(PG_FUNCTION_ARGS); extern Datum dceil(PG_FUNCTION_ARGS); extern Datum dfloor(PG_FUNCTION_ARGS); extern Datum dsign(PG_FUNCTION_ARGS); extern Datum dtrunc(PG_FUNCTION_ARGS); extern Datum dsqrt(PG_FUNCTION_ARGS); extern Datum dcbrt(PG_FUNCTION_ARGS); extern Datum dpow(PG_FUNCTION_ARGS); extern Datum dexp(PG_FUNCTION_ARGS); extern Datum dlog1(PG_FUNCTION_ARGS); extern Datum dlog10(PG_FUNCTION_ARGS); extern Datum dacos(PG_FUNCTION_ARGS); extern Datum dasin(PG_FUNCTION_ARGS); extern Datum datan(PG_FUNCTION_ARGS); extern Datum datan2(PG_FUNCTION_ARGS); extern Datum dcos(PG_FUNCTION_ARGS); extern Datum dcot(PG_FUNCTION_ARGS); extern Datum dsin(PG_FUNCTION_ARGS); extern Datum dtan(PG_FUNCTION_ARGS); extern Datum degrees(PG_FUNCTION_ARGS); extern Datum dpi(PG_FUNCTION_ARGS); extern Datum radians(PG_FUNCTION_ARGS); extern Datum drandom(PG_FUNCTION_ARGS); extern Datum setseed(PG_FUNCTION_ARGS); extern Datum float8_accum(PG_FUNCTION_ARGS); extern Datum float4_accum(PG_FUNCTION_ARGS); extern Datum float8_avg(PG_FUNCTION_ARGS); extern Datum float8_var_pop(PG_FUNCTION_ARGS); extern Datum float8_var_samp(PG_FUNCTION_ARGS); extern Datum float8_stddev_pop(PG_FUNCTION_ARGS); extern Datum float8_stddev_samp(PG_FUNCTION_ARGS); extern Datum float8_regr_accum(PG_FUNCTION_ARGS); extern Datum float8_regr_sxx(PG_FUNCTION_ARGS); extern Datum float8_regr_syy(PG_FUNCTION_ARGS); extern Datum float8_regr_sxy(PG_FUNCTION_ARGS); extern Datum float8_regr_avgx(PG_FUNCTION_ARGS); extern Datum float8_regr_avgy(PG_FUNCTION_ARGS); extern Datum float8_covar_pop(PG_FUNCTION_ARGS); extern Datum float8_covar_samp(PG_FUNCTION_ARGS); extern Datum float8_corr(PG_FUNCTION_ARGS); extern Datum float8_regr_r2(PG_FUNCTION_ARGS); extern Datum float8_regr_slope(PG_FUNCTION_ARGS); extern Datum float8_regr_intercept(PG_FUNCTION_ARGS); extern Datum float48pl(PG_FUNCTION_ARGS); extern Datum float48mi(PG_FUNCTION_ARGS); extern Datum float48mul(PG_FUNCTION_ARGS); extern Datum float48div(PG_FUNCTION_ARGS); extern Datum float84pl(PG_FUNCTION_ARGS); extern Datum float84mi(PG_FUNCTION_ARGS); extern Datum float84mul(PG_FUNCTION_ARGS); extern Datum float84div(PG_FUNCTION_ARGS); extern Datum float48eq(PG_FUNCTION_ARGS); extern Datum float48ne(PG_FUNCTION_ARGS); extern Datum float48lt(PG_FUNCTION_ARGS); extern Datum float48le(PG_FUNCTION_ARGS); extern Datum float48gt(PG_FUNCTION_ARGS); extern Datum float48ge(PG_FUNCTION_ARGS); extern Datum float84eq(PG_FUNCTION_ARGS); extern Datum float84ne(PG_FUNCTION_ARGS); extern Datum float84lt(PG_FUNCTION_ARGS); extern Datum float84le(PG_FUNCTION_ARGS); extern Datum float84gt(PG_FUNCTION_ARGS); extern Datum float84ge(PG_FUNCTION_ARGS); extern Datum width_bucket_float8(PG_FUNCTION_ARGS); /* dbsize.c */ extern Datum pg_tablespace_size_oid(PG_FUNCTION_ARGS); extern Datum pg_tablespace_size_name(PG_FUNCTION_ARGS); extern Datum pg_database_size_oid(PG_FUNCTION_ARGS); extern Datum pg_database_size_name(PG_FUNCTION_ARGS); extern Datum pg_relation_size(PG_FUNCTION_ARGS); extern Datum pg_total_relation_size(PG_FUNCTION_ARGS); extern Datum pg_size_pretty(PG_FUNCTION_ARGS); extern Datum pg_size_pretty_numeric(PG_FUNCTION_ARGS); extern Datum pg_table_size(PG_FUNCTION_ARGS); extern Datum pg_indexes_size(PG_FUNCTION_ARGS); extern Datum pg_relation_filenode(PG_FUNCTION_ARGS); extern Datum pg_filenode_relation(PG_FUNCTION_ARGS); extern Datum pg_relation_filepath(PG_FUNCTION_ARGS); /* genfile.c */ extern Datum pg_stat_file(PG_FUNCTION_ARGS); extern Datum pg_stat_file_1arg(PG_FUNCTION_ARGS); extern Datum pg_read_file(PG_FUNCTION_ARGS); extern Datum pg_read_file_off_len(PG_FUNCTION_ARGS); extern Datum pg_read_file_all(PG_FUNCTION_ARGS); extern Datum pg_read_binary_file(PG_FUNCTION_ARGS); extern Datum pg_read_binary_file_off_len(PG_FUNCTION_ARGS); extern Datum pg_read_binary_file_all(PG_FUNCTION_ARGS); extern Datum pg_ls_dir(PG_FUNCTION_ARGS); extern Datum pg_ls_dir_1arg(PG_FUNCTION_ARGS); /* misc.c */ extern Datum current_database(PG_FUNCTION_ARGS); extern Datum current_query(PG_FUNCTION_ARGS); extern Datum pg_cancel_backend(PG_FUNCTION_ARGS); extern Datum pg_terminate_backend(PG_FUNCTION_ARGS); extern Datum pg_reload_conf(PG_FUNCTION_ARGS); extern Datum pg_tablespace_databases(PG_FUNCTION_ARGS); extern Datum pg_tablespace_location(PG_FUNCTION_ARGS); extern Datum pg_rotate_logfile(PG_FUNCTION_ARGS); extern Datum pg_sleep(PG_FUNCTION_ARGS); extern Datum pg_get_keywords(PG_FUNCTION_ARGS); extern Datum pg_typeof(PG_FUNCTION_ARGS); extern Datum pg_collation_for(PG_FUNCTION_ARGS); extern Datum pg_relation_is_updatable(PG_FUNCTION_ARGS); extern Datum pg_column_is_updatable(PG_FUNCTION_ARGS); /* oid.c */ extern Datum oidin(PG_FUNCTION_ARGS); extern Datum oidout(PG_FUNCTION_ARGS); extern Datum oidrecv(PG_FUNCTION_ARGS); extern Datum oidsend(PG_FUNCTION_ARGS); extern Datum oideq(PG_FUNCTION_ARGS); extern Datum oidne(PG_FUNCTION_ARGS); extern Datum oidlt(PG_FUNCTION_ARGS); extern Datum oidle(PG_FUNCTION_ARGS); extern Datum oidge(PG_FUNCTION_ARGS); extern Datum oidgt(PG_FUNCTION_ARGS); extern Datum oidlarger(PG_FUNCTION_ARGS); extern Datum oidsmaller(PG_FUNCTION_ARGS); extern Datum oidvectorin(PG_FUNCTION_ARGS); extern Datum oidvectorout(PG_FUNCTION_ARGS); extern Datum oidvectorrecv(PG_FUNCTION_ARGS); extern Datum oidvectorsend(PG_FUNCTION_ARGS); extern Datum oidvectoreq(PG_FUNCTION_ARGS); extern Datum oidvectorne(PG_FUNCTION_ARGS); extern Datum oidvectorlt(PG_FUNCTION_ARGS); extern Datum oidvectorle(PG_FUNCTION_ARGS); extern Datum oidvectorge(PG_FUNCTION_ARGS); extern Datum oidvectorgt(PG_FUNCTION_ARGS); extern oidvector *buildoidvector(const Oid *oids, int n); extern Oid oidparse(Node *node); /* orderedsetaggs.c */ extern Datum ordered_set_transition(PG_FUNCTION_ARGS); extern Datum ordered_set_transition_multi(PG_FUNCTION_ARGS); extern Datum percentile_disc_final(PG_FUNCTION_ARGS); extern Datum percentile_cont_float8_final(PG_FUNCTION_ARGS); extern Datum percentile_cont_interval_final(PG_FUNCTION_ARGS); extern Datum percentile_disc_multi_final(PG_FUNCTION_ARGS); extern Datum percentile_cont_float8_multi_final(PG_FUNCTION_ARGS); extern Datum percentile_cont_interval_multi_final(PG_FUNCTION_ARGS); extern Datum mode_final(PG_FUNCTION_ARGS); extern Datum hypothetical_rank_final(PG_FUNCTION_ARGS); extern Datum hypothetical_percent_rank_final(PG_FUNCTION_ARGS); extern Datum hypothetical_cume_dist_final(PG_FUNCTION_ARGS); extern Datum hypothetical_dense_rank_final(PG_FUNCTION_ARGS); /* pseudotypes.c */ extern Datum cstring_in(PG_FUNCTION_ARGS); extern Datum cstring_out(PG_FUNCTION_ARGS); extern Datum cstring_recv(PG_FUNCTION_ARGS); extern Datum cstring_send(PG_FUNCTION_ARGS); extern Datum any_in(PG_FUNCTION_ARGS); extern Datum any_out(PG_FUNCTION_ARGS); extern Datum anyarray_in(PG_FUNCTION_ARGS); extern Datum anyarray_out(PG_FUNCTION_ARGS); extern Datum anyarray_recv(PG_FUNCTION_ARGS); extern Datum anyarray_send(PG_FUNCTION_ARGS); extern Datum anynonarray_in(PG_FUNCTION_ARGS); extern Datum anynonarray_out(PG_FUNCTION_ARGS); extern Datum anyenum_in(PG_FUNCTION_ARGS); extern Datum anyenum_out(PG_FUNCTION_ARGS); extern Datum anyrange_in(PG_FUNCTION_ARGS); extern Datum anyrange_out(PG_FUNCTION_ARGS); extern Datum void_in(PG_FUNCTION_ARGS); extern Datum void_out(PG_FUNCTION_ARGS); extern Datum void_recv(PG_FUNCTION_ARGS); extern Datum void_send(PG_FUNCTION_ARGS); extern Datum trigger_in(PG_FUNCTION_ARGS); extern Datum trigger_out(PG_FUNCTION_ARGS); extern Datum event_trigger_in(PG_FUNCTION_ARGS); extern Datum event_trigger_out(PG_FUNCTION_ARGS); extern Datum language_handler_in(PG_FUNCTION_ARGS); extern Datum language_handler_out(PG_FUNCTION_ARGS); extern Datum fdw_handler_in(PG_FUNCTION_ARGS); extern Datum fdw_handler_out(PG_FUNCTION_ARGS); extern Datum tsm_handler_in(PG_FUNCTION_ARGS); extern Datum tsm_handler_out(PG_FUNCTION_ARGS); extern Datum internal_in(PG_FUNCTION_ARGS); extern Datum internal_out(PG_FUNCTION_ARGS); extern Datum opaque_in(PG_FUNCTION_ARGS); extern Datum opaque_out(PG_FUNCTION_ARGS); extern Datum anyelement_in(PG_FUNCTION_ARGS); extern Datum anyelement_out(PG_FUNCTION_ARGS); extern Datum shell_in(PG_FUNCTION_ARGS); extern Datum shell_out(PG_FUNCTION_ARGS); extern Datum pg_node_tree_in(PG_FUNCTION_ARGS); extern Datum pg_node_tree_out(PG_FUNCTION_ARGS); extern Datum pg_node_tree_recv(PG_FUNCTION_ARGS); extern Datum pg_node_tree_send(PG_FUNCTION_ARGS); extern Datum pg_ddl_command_in(PG_FUNCTION_ARGS); extern Datum pg_ddl_command_out(PG_FUNCTION_ARGS); extern Datum pg_ddl_command_recv(PG_FUNCTION_ARGS); extern Datum pg_ddl_command_send(PG_FUNCTION_ARGS); /* regexp.c */ extern Datum nameregexeq(PG_FUNCTION_ARGS); extern Datum nameregexne(PG_FUNCTION_ARGS); extern Datum textregexeq(PG_FUNCTION_ARGS); extern Datum textregexne(PG_FUNCTION_ARGS); extern Datum nameicregexeq(PG_FUNCTION_ARGS); extern Datum nameicregexne(PG_FUNCTION_ARGS); extern Datum texticregexeq(PG_FUNCTION_ARGS); extern Datum texticregexne(PG_FUNCTION_ARGS); extern Datum textregexsubstr(PG_FUNCTION_ARGS); extern Datum textregexreplace_noopt(PG_FUNCTION_ARGS); extern Datum textregexreplace(PG_FUNCTION_ARGS); extern Datum similar_escape(PG_FUNCTION_ARGS); extern Datum regexp_matches(PG_FUNCTION_ARGS); extern Datum regexp_matches_no_flags(PG_FUNCTION_ARGS); extern Datum regexp_split_to_table(PG_FUNCTION_ARGS); extern Datum regexp_split_to_table_no_flags(PG_FUNCTION_ARGS); extern Datum regexp_split_to_array(PG_FUNCTION_ARGS); extern Datum regexp_split_to_array_no_flags(PG_FUNCTION_ARGS); extern char *regexp_fixed_prefix(text *text_re, bool case_insensitive, Oid collation, bool *exact); /* regproc.c */ extern Datum regprocin(PG_FUNCTION_ARGS); extern Datum regprocout(PG_FUNCTION_ARGS); extern Datum to_regproc(PG_FUNCTION_ARGS); extern Datum to_regprocedure(PG_FUNCTION_ARGS); extern Datum regprocrecv(PG_FUNCTION_ARGS); extern Datum regprocsend(PG_FUNCTION_ARGS); extern Datum regprocedurein(PG_FUNCTION_ARGS); extern Datum regprocedureout(PG_FUNCTION_ARGS); extern Datum regprocedurerecv(PG_FUNCTION_ARGS); extern Datum regproceduresend(PG_FUNCTION_ARGS); extern Datum regoperin(PG_FUNCTION_ARGS); extern Datum regoperout(PG_FUNCTION_ARGS); extern Datum regoperrecv(PG_FUNCTION_ARGS); extern Datum regopersend(PG_FUNCTION_ARGS); extern Datum to_regoper(PG_FUNCTION_ARGS); extern Datum to_regoperator(PG_FUNCTION_ARGS); extern Datum regoperatorin(PG_FUNCTION_ARGS); extern Datum regoperatorout(PG_FUNCTION_ARGS); extern Datum regoperatorrecv(PG_FUNCTION_ARGS); extern Datum regoperatorsend(PG_FUNCTION_ARGS); extern Datum regclassin(PG_FUNCTION_ARGS); extern Datum regclassout(PG_FUNCTION_ARGS); extern Datum regclassrecv(PG_FUNCTION_ARGS); extern Datum regclasssend(PG_FUNCTION_ARGS); extern Datum to_regclass(PG_FUNCTION_ARGS); extern Datum regtypein(PG_FUNCTION_ARGS); extern Datum regtypeout(PG_FUNCTION_ARGS); extern Datum regtyperecv(PG_FUNCTION_ARGS); extern Datum regtypesend(PG_FUNCTION_ARGS); extern Datum to_regtype(PG_FUNCTION_ARGS); extern Datum regrolein(PG_FUNCTION_ARGS); extern Datum regroleout(PG_FUNCTION_ARGS); extern Datum regrolerecv(PG_FUNCTION_ARGS); extern Datum regrolesend(PG_FUNCTION_ARGS); extern Datum to_regrole(PG_FUNCTION_ARGS); extern Datum regnamespacein(PG_FUNCTION_ARGS); extern Datum regnamespaceout(PG_FUNCTION_ARGS); extern Datum regnamespacerecv(PG_FUNCTION_ARGS); extern Datum regnamespacesend(PG_FUNCTION_ARGS); extern Datum to_regnamespace(PG_FUNCTION_ARGS); extern Datum regconfigin(PG_FUNCTION_ARGS); extern Datum regconfigout(PG_FUNCTION_ARGS); extern Datum regconfigrecv(PG_FUNCTION_ARGS); extern Datum regconfigsend(PG_FUNCTION_ARGS); extern Datum regdictionaryin(PG_FUNCTION_ARGS); extern Datum regdictionaryout(PG_FUNCTION_ARGS); extern Datum regdictionaryrecv(PG_FUNCTION_ARGS); extern Datum regdictionarysend(PG_FUNCTION_ARGS); extern Datum text_regclass(PG_FUNCTION_ARGS); extern List *stringToQualifiedNameList(const char *string); extern char *format_procedure(Oid procedure_oid); extern char *format_procedure_qualified(Oid procedure_oid); extern void format_procedure_parts(Oid operator_oid, List **objnames, List **objargs); extern char *format_operator(Oid operator_oid); extern char *format_operator_qualified(Oid operator_oid); extern void format_operator_parts(Oid operator_oid, List **objnames, List **objargs); /* rowtypes.c */ extern Datum record_in(PG_FUNCTION_ARGS); extern Datum record_out(PG_FUNCTION_ARGS); extern Datum record_recv(PG_FUNCTION_ARGS); extern Datum record_send(PG_FUNCTION_ARGS); extern Datum record_eq(PG_FUNCTION_ARGS); extern Datum record_ne(PG_FUNCTION_ARGS); extern Datum record_lt(PG_FUNCTION_ARGS); extern Datum record_gt(PG_FUNCTION_ARGS); extern Datum record_le(PG_FUNCTION_ARGS); extern Datum record_ge(PG_FUNCTION_ARGS); extern Datum btrecordcmp(PG_FUNCTION_ARGS); extern Datum record_image_eq(PG_FUNCTION_ARGS); extern Datum record_image_ne(PG_FUNCTION_ARGS); extern Datum record_image_lt(PG_FUNCTION_ARGS); extern Datum record_image_gt(PG_FUNCTION_ARGS); extern Datum record_image_le(PG_FUNCTION_ARGS); extern Datum record_image_ge(PG_FUNCTION_ARGS); extern Datum btrecordimagecmp(PG_FUNCTION_ARGS); /* ruleutils.c */ extern __thread bool quote_all_identifiers; extern Datum pg_get_ruledef(PG_FUNCTION_ARGS); extern Datum pg_get_ruledef_ext(PG_FUNCTION_ARGS); extern Datum pg_get_viewdef(PG_FUNCTION_ARGS); extern Datum pg_get_viewdef_ext(PG_FUNCTION_ARGS); extern Datum pg_get_viewdef_wrap(PG_FUNCTION_ARGS); extern Datum pg_get_viewdef_name(PG_FUNCTION_ARGS); extern Datum pg_get_viewdef_name_ext(PG_FUNCTION_ARGS); extern Datum pg_get_indexdef(PG_FUNCTION_ARGS); extern Datum pg_get_indexdef_ext(PG_FUNCTION_ARGS); extern Datum pg_get_triggerdef(PG_FUNCTION_ARGS); extern Datum pg_get_triggerdef_ext(PG_FUNCTION_ARGS); extern Datum pg_get_constraintdef(PG_FUNCTION_ARGS); extern Datum pg_get_constraintdef_ext(PG_FUNCTION_ARGS); extern Datum pg_get_expr(PG_FUNCTION_ARGS); extern Datum pg_get_expr_ext(PG_FUNCTION_ARGS); extern Datum pg_get_userbyid(PG_FUNCTION_ARGS); extern Datum pg_get_serial_sequence(PG_FUNCTION_ARGS); extern Datum pg_get_functiondef(PG_FUNCTION_ARGS); extern Datum pg_get_function_arguments(PG_FUNCTION_ARGS); extern Datum pg_get_function_identity_arguments(PG_FUNCTION_ARGS); extern Datum pg_get_function_result(PG_FUNCTION_ARGS); extern Datum pg_get_function_arg_default(PG_FUNCTION_ARGS); extern const char *quote_identifier(const char *ident); extern char *quote_qualified_identifier(const char *qualifier, const char *ident); /* tid.c */ extern Datum tidin(PG_FUNCTION_ARGS); extern Datum tidout(PG_FUNCTION_ARGS); extern Datum tidrecv(PG_FUNCTION_ARGS); extern Datum tidsend(PG_FUNCTION_ARGS); extern Datum tideq(PG_FUNCTION_ARGS); extern Datum tidne(PG_FUNCTION_ARGS); extern Datum tidlt(PG_FUNCTION_ARGS); extern Datum tidle(PG_FUNCTION_ARGS); extern Datum tidgt(PG_FUNCTION_ARGS); extern Datum tidge(PG_FUNCTION_ARGS); extern Datum bttidcmp(PG_FUNCTION_ARGS); extern Datum tidlarger(PG_FUNCTION_ARGS); extern Datum tidsmaller(PG_FUNCTION_ARGS); extern Datum currtid_byreloid(PG_FUNCTION_ARGS); extern Datum currtid_byrelname(PG_FUNCTION_ARGS); /* varchar.c */ extern Datum bpcharin(PG_FUNCTION_ARGS); extern Datum bpcharout(PG_FUNCTION_ARGS); extern Datum bpcharrecv(PG_FUNCTION_ARGS); extern Datum bpcharsend(PG_FUNCTION_ARGS); extern Datum bpchartypmodin(PG_FUNCTION_ARGS); extern Datum bpchartypmodout(PG_FUNCTION_ARGS); extern Datum bpchar(PG_FUNCTION_ARGS); extern Datum char_bpchar(PG_FUNCTION_ARGS); extern Datum name_bpchar(PG_FUNCTION_ARGS); extern Datum bpchar_name(PG_FUNCTION_ARGS); extern Datum bpchareq(PG_FUNCTION_ARGS); extern Datum bpcharne(PG_FUNCTION_ARGS); extern Datum bpcharlt(PG_FUNCTION_ARGS); extern Datum bpcharle(PG_FUNCTION_ARGS); extern Datum bpchargt(PG_FUNCTION_ARGS); extern Datum bpcharge(PG_FUNCTION_ARGS); extern Datum bpcharcmp(PG_FUNCTION_ARGS); extern Datum bpchar_larger(PG_FUNCTION_ARGS); extern Datum bpchar_smaller(PG_FUNCTION_ARGS); extern Datum bpcharlen(PG_FUNCTION_ARGS); extern Datum bpcharoctetlen(PG_FUNCTION_ARGS); extern Datum hashbpchar(PG_FUNCTION_ARGS); extern Datum bpchar_pattern_lt(PG_FUNCTION_ARGS); extern Datum bpchar_pattern_le(PG_FUNCTION_ARGS); extern Datum bpchar_pattern_gt(PG_FUNCTION_ARGS); extern Datum bpchar_pattern_ge(PG_FUNCTION_ARGS); extern Datum btbpchar_pattern_cmp(PG_FUNCTION_ARGS); extern Datum varcharin(PG_FUNCTION_ARGS); extern Datum varcharout(PG_FUNCTION_ARGS); extern Datum varcharrecv(PG_FUNCTION_ARGS); extern Datum varcharsend(PG_FUNCTION_ARGS); extern Datum varchartypmodin(PG_FUNCTION_ARGS); extern Datum varchartypmodout(PG_FUNCTION_ARGS); extern Datum varchar_transform(PG_FUNCTION_ARGS); extern Datum varchar(PG_FUNCTION_ARGS); /* varlena.c */ extern text *cstring_to_text(const char *s); extern text *cstring_to_text_with_len(const char *s, int len); extern char *text_to_cstring(const text *t); extern void text_to_cstring_buffer(const text *src, char *dst, size_t dst_len); #define CStringGetTextDatum(s) PointerGetDatum(cstring_to_text(s)) #define TextDatumGetCString(d) text_to_cstring((text *) DatumGetPointer(d)) extern Datum textin(PG_FUNCTION_ARGS); extern Datum textout(PG_FUNCTION_ARGS); extern Datum textrecv(PG_FUNCTION_ARGS); extern Datum textsend(PG_FUNCTION_ARGS); extern Datum textcat(PG_FUNCTION_ARGS); extern Datum texteq(PG_FUNCTION_ARGS); extern Datum textne(PG_FUNCTION_ARGS); extern Datum text_lt(PG_FUNCTION_ARGS); extern Datum text_le(PG_FUNCTION_ARGS); extern Datum text_gt(PG_FUNCTION_ARGS); extern Datum text_ge(PG_FUNCTION_ARGS); extern Datum text_larger(PG_FUNCTION_ARGS); extern Datum text_smaller(PG_FUNCTION_ARGS); extern Datum text_pattern_lt(PG_FUNCTION_ARGS); extern Datum text_pattern_le(PG_FUNCTION_ARGS); extern Datum text_pattern_gt(PG_FUNCTION_ARGS); extern Datum text_pattern_ge(PG_FUNCTION_ARGS); extern Datum bttext_pattern_cmp(PG_FUNCTION_ARGS); extern Datum textlen(PG_FUNCTION_ARGS); extern Datum textoctetlen(PG_FUNCTION_ARGS); extern Datum textpos(PG_FUNCTION_ARGS); extern Datum text_substr(PG_FUNCTION_ARGS); extern Datum text_substr_no_len(PG_FUNCTION_ARGS); extern Datum textoverlay(PG_FUNCTION_ARGS); extern Datum textoverlay_no_len(PG_FUNCTION_ARGS); extern Datum name_text(PG_FUNCTION_ARGS); extern Datum text_name(PG_FUNCTION_ARGS); extern int varstr_cmp(char *arg1, int len1, char *arg2, int len2, Oid collid); extern int varstr_levenshtein(const char *source, int slen, const char *target, int tlen, int ins_c, int del_c, int sub_c, bool trusted); extern int varstr_levenshtein_less_equal(const char *source, int slen, const char *target, int tlen, int ins_c, int del_c, int sub_c, int max_d, bool trusted); extern List *textToQualifiedNameList(text *textval); extern bool SplitIdentifierString(char *rawstring, char separator, List **namelist); extern bool SplitDirectoriesString(char *rawstring, char separator, List **namelist); extern Datum replace_text(PG_FUNCTION_ARGS); extern text *replace_text_regexp(text *src_text, void *regexp, text *replace_text, bool glob); extern Datum split_text(PG_FUNCTION_ARGS); extern Datum text_to_array(PG_FUNCTION_ARGS); extern Datum array_to_text(PG_FUNCTION_ARGS); extern Datum text_to_array_null(PG_FUNCTION_ARGS); extern Datum array_to_text_null(PG_FUNCTION_ARGS); extern Datum to_hex32(PG_FUNCTION_ARGS); extern Datum to_hex64(PG_FUNCTION_ARGS); extern Datum md5_text(PG_FUNCTION_ARGS); extern Datum md5_bytea(PG_FUNCTION_ARGS); extern Datum unknownin(PG_FUNCTION_ARGS); extern Datum unknownout(PG_FUNCTION_ARGS); extern Datum unknownrecv(PG_FUNCTION_ARGS); extern Datum unknownsend(PG_FUNCTION_ARGS); extern Datum pg_column_size(PG_FUNCTION_ARGS); extern Datum bytea_string_agg_transfn(PG_FUNCTION_ARGS); extern Datum bytea_string_agg_finalfn(PG_FUNCTION_ARGS); extern Datum string_agg_transfn(PG_FUNCTION_ARGS); extern Datum string_agg_finalfn(PG_FUNCTION_ARGS); extern Datum text_concat(PG_FUNCTION_ARGS); extern Datum text_concat_ws(PG_FUNCTION_ARGS); extern Datum text_left(PG_FUNCTION_ARGS); extern Datum text_right(PG_FUNCTION_ARGS); extern Datum text_reverse(PG_FUNCTION_ARGS); extern Datum text_format(PG_FUNCTION_ARGS); extern Datum text_format_nv(PG_FUNCTION_ARGS); /* version.c */ extern Datum pgsql_version(PG_FUNCTION_ARGS); /* xid.c */ extern Datum xidin(PG_FUNCTION_ARGS); extern Datum xidout(PG_FUNCTION_ARGS); extern Datum xidrecv(PG_FUNCTION_ARGS); extern Datum xidsend(PG_FUNCTION_ARGS); extern Datum xideq(PG_FUNCTION_ARGS); extern Datum xid_age(PG_FUNCTION_ARGS); extern Datum mxid_age(PG_FUNCTION_ARGS); extern int xidComparator(const void *arg1, const void *arg2); extern Datum cidin(PG_FUNCTION_ARGS); extern Datum cidout(PG_FUNCTION_ARGS); extern Datum cidrecv(PG_FUNCTION_ARGS); extern Datum cidsend(PG_FUNCTION_ARGS); extern Datum cideq(PG_FUNCTION_ARGS); /* like.c */ extern Datum namelike(PG_FUNCTION_ARGS); extern Datum namenlike(PG_FUNCTION_ARGS); extern Datum nameiclike(PG_FUNCTION_ARGS); extern Datum nameicnlike(PG_FUNCTION_ARGS); extern Datum textlike(PG_FUNCTION_ARGS); extern Datum textnlike(PG_FUNCTION_ARGS); extern Datum texticlike(PG_FUNCTION_ARGS); extern Datum texticnlike(PG_FUNCTION_ARGS); extern Datum bytealike(PG_FUNCTION_ARGS); extern Datum byteanlike(PG_FUNCTION_ARGS); extern Datum like_escape(PG_FUNCTION_ARGS); extern Datum like_escape_bytea(PG_FUNCTION_ARGS); /* oracle_compat.c */ extern Datum lower(PG_FUNCTION_ARGS); extern Datum upper(PG_FUNCTION_ARGS); extern Datum initcap(PG_FUNCTION_ARGS); extern Datum lpad(PG_FUNCTION_ARGS); extern Datum rpad(PG_FUNCTION_ARGS); extern Datum btrim(PG_FUNCTION_ARGS); extern Datum btrim1(PG_FUNCTION_ARGS); extern Datum byteatrim(PG_FUNCTION_ARGS); extern Datum ltrim(PG_FUNCTION_ARGS); extern Datum ltrim1(PG_FUNCTION_ARGS); extern Datum rtrim(PG_FUNCTION_ARGS); extern Datum rtrim1(PG_FUNCTION_ARGS); extern Datum translate(PG_FUNCTION_ARGS); extern Datum chr (PG_FUNCTION_ARGS); extern Datum repeat(PG_FUNCTION_ARGS); extern Datum ascii(PG_FUNCTION_ARGS); /* inet_cidr_ntop.c */ extern char *inet_cidr_ntop(int af, const void *src, int bits, char *dst, size_t size); /* inet_net_pton.c */ extern int inet_net_pton(int af, const char *src, void *dst, size_t size); /* network.c */ extern Datum inet_in(PG_FUNCTION_ARGS); extern Datum inet_out(PG_FUNCTION_ARGS); extern Datum inet_recv(PG_FUNCTION_ARGS); extern Datum inet_send(PG_FUNCTION_ARGS); extern Datum cidr_in(PG_FUNCTION_ARGS); extern Datum cidr_out(PG_FUNCTION_ARGS); extern Datum cidr_recv(PG_FUNCTION_ARGS); extern Datum cidr_send(PG_FUNCTION_ARGS); extern Datum network_cmp(PG_FUNCTION_ARGS); extern Datum network_lt(PG_FUNCTION_ARGS); extern Datum network_le(PG_FUNCTION_ARGS); extern Datum network_eq(PG_FUNCTION_ARGS); extern Datum network_ge(PG_FUNCTION_ARGS); extern Datum network_gt(PG_FUNCTION_ARGS); extern Datum network_ne(PG_FUNCTION_ARGS); extern Datum network_smaller(PG_FUNCTION_ARGS); extern Datum network_larger(PG_FUNCTION_ARGS); extern Datum hashinet(PG_FUNCTION_ARGS); extern Datum network_sub(PG_FUNCTION_ARGS); extern Datum network_subeq(PG_FUNCTION_ARGS); extern Datum network_sup(PG_FUNCTION_ARGS); extern Datum network_supeq(PG_FUNCTION_ARGS); extern Datum network_overlap(PG_FUNCTION_ARGS); extern Datum network_network(PG_FUNCTION_ARGS); extern Datum network_netmask(PG_FUNCTION_ARGS); extern Datum network_hostmask(PG_FUNCTION_ARGS); extern Datum network_masklen(PG_FUNCTION_ARGS); extern Datum network_family(PG_FUNCTION_ARGS); extern Datum network_broadcast(PG_FUNCTION_ARGS); extern Datum network_host(PG_FUNCTION_ARGS); extern Datum network_show(PG_FUNCTION_ARGS); extern Datum inet_abbrev(PG_FUNCTION_ARGS); extern Datum cidr_abbrev(PG_FUNCTION_ARGS); extern double convert_network_to_scalar(Datum value, Oid typid); extern Datum inet_to_cidr(PG_FUNCTION_ARGS); extern Datum inet_set_masklen(PG_FUNCTION_ARGS); extern Datum cidr_set_masklen(PG_FUNCTION_ARGS); extern Datum network_scan_first(Datum in); extern Datum network_scan_last(Datum in); extern Datum inet_client_addr(PG_FUNCTION_ARGS); extern Datum inet_client_port(PG_FUNCTION_ARGS); extern Datum inet_server_addr(PG_FUNCTION_ARGS); extern Datum inet_server_port(PG_FUNCTION_ARGS); extern Datum inetnot(PG_FUNCTION_ARGS); extern Datum inetand(PG_FUNCTION_ARGS); extern Datum inetor(PG_FUNCTION_ARGS); extern Datum inetpl(PG_FUNCTION_ARGS); extern Datum inetmi_int8(PG_FUNCTION_ARGS); extern Datum inetmi(PG_FUNCTION_ARGS); extern void clean_ipv6_addr(int addr_family, char *addr); extern Datum inet_same_family(PG_FUNCTION_ARGS); extern Datum inet_merge(PG_FUNCTION_ARGS); /* mac.c */ extern Datum macaddr_in(PG_FUNCTION_ARGS); extern Datum macaddr_out(PG_FUNCTION_ARGS); extern Datum macaddr_recv(PG_FUNCTION_ARGS); extern Datum macaddr_send(PG_FUNCTION_ARGS); extern Datum macaddr_cmp(PG_FUNCTION_ARGS); extern Datum macaddr_lt(PG_FUNCTION_ARGS); extern Datum macaddr_le(PG_FUNCTION_ARGS); extern Datum macaddr_eq(PG_FUNCTION_ARGS); extern Datum macaddr_ge(PG_FUNCTION_ARGS); extern Datum macaddr_gt(PG_FUNCTION_ARGS); extern Datum macaddr_ne(PG_FUNCTION_ARGS); extern Datum macaddr_not(PG_FUNCTION_ARGS); extern Datum macaddr_and(PG_FUNCTION_ARGS); extern Datum macaddr_or(PG_FUNCTION_ARGS); extern Datum macaddr_trunc(PG_FUNCTION_ARGS); extern Datum hashmacaddr(PG_FUNCTION_ARGS); /* numeric.c */ extern Datum numeric_in(PG_FUNCTION_ARGS); extern Datum numeric_out(PG_FUNCTION_ARGS); extern Datum numeric_recv(PG_FUNCTION_ARGS); extern Datum numeric_send(PG_FUNCTION_ARGS); extern Datum numerictypmodin(PG_FUNCTION_ARGS); extern Datum numerictypmodout(PG_FUNCTION_ARGS); extern Datum numeric_transform(PG_FUNCTION_ARGS); extern Datum numeric (PG_FUNCTION_ARGS); extern Datum numeric_abs(PG_FUNCTION_ARGS); extern Datum numeric_uminus(PG_FUNCTION_ARGS); extern Datum numeric_uplus(PG_FUNCTION_ARGS); extern Datum numeric_sign(PG_FUNCTION_ARGS); extern Datum numeric_round(PG_FUNCTION_ARGS); extern Datum numeric_trunc(PG_FUNCTION_ARGS); extern Datum numeric_ceil(PG_FUNCTION_ARGS); extern Datum numeric_floor(PG_FUNCTION_ARGS); extern Datum numeric_sortsupport(PG_FUNCTION_ARGS); extern Datum numeric_cmp(PG_FUNCTION_ARGS); extern Datum numeric_eq(PG_FUNCTION_ARGS); extern Datum numeric_ne(PG_FUNCTION_ARGS); extern Datum numeric_gt(PG_FUNCTION_ARGS); extern Datum numeric_ge(PG_FUNCTION_ARGS); extern Datum numeric_lt(PG_FUNCTION_ARGS); extern Datum numeric_le(PG_FUNCTION_ARGS); extern Datum numeric_add(PG_FUNCTION_ARGS); extern Datum numeric_sub(PG_FUNCTION_ARGS); extern Datum numeric_mul(PG_FUNCTION_ARGS); extern Datum numeric_div(PG_FUNCTION_ARGS); extern Datum numeric_div_trunc(PG_FUNCTION_ARGS); extern Datum numeric_mod(PG_FUNCTION_ARGS); extern Datum numeric_inc(PG_FUNCTION_ARGS); extern Datum numeric_smaller(PG_FUNCTION_ARGS); extern Datum numeric_larger(PG_FUNCTION_ARGS); extern Datum numeric_fac(PG_FUNCTION_ARGS); extern Datum numeric_sqrt(PG_FUNCTION_ARGS); extern Datum numeric_exp(PG_FUNCTION_ARGS); extern Datum numeric_ln(PG_FUNCTION_ARGS); extern Datum numeric_log(PG_FUNCTION_ARGS); extern Datum numeric_power(PG_FUNCTION_ARGS); extern Datum int4_numeric(PG_FUNCTION_ARGS); extern Datum numeric_int4(PG_FUNCTION_ARGS); extern Datum int8_numeric(PG_FUNCTION_ARGS); extern Datum numeric_int8(PG_FUNCTION_ARGS); extern Datum int2_numeric(PG_FUNCTION_ARGS); extern Datum numeric_int2(PG_FUNCTION_ARGS); extern Datum float8_numeric(PG_FUNCTION_ARGS); extern Datum numeric_float8(PG_FUNCTION_ARGS); extern Datum numeric_float8_no_overflow(PG_FUNCTION_ARGS); extern Datum float4_numeric(PG_FUNCTION_ARGS); extern Datum numeric_float4(PG_FUNCTION_ARGS); extern Datum numeric_accum(PG_FUNCTION_ARGS); extern Datum numeric_avg_accum(PG_FUNCTION_ARGS); extern Datum numeric_accum_inv(PG_FUNCTION_ARGS); extern Datum int2_accum(PG_FUNCTION_ARGS); extern Datum int4_accum(PG_FUNCTION_ARGS); extern Datum int8_accum(PG_FUNCTION_ARGS); extern Datum int2_accum_inv(PG_FUNCTION_ARGS); extern Datum int4_accum_inv(PG_FUNCTION_ARGS); extern Datum int8_accum_inv(PG_FUNCTION_ARGS); extern Datum int8_avg_accum(PG_FUNCTION_ARGS); extern Datum numeric_avg(PG_FUNCTION_ARGS); extern Datum numeric_sum(PG_FUNCTION_ARGS); extern Datum numeric_var_pop(PG_FUNCTION_ARGS); extern Datum numeric_var_samp(PG_FUNCTION_ARGS); extern Datum numeric_stddev_pop(PG_FUNCTION_ARGS); extern Datum numeric_stddev_samp(PG_FUNCTION_ARGS); extern Datum numeric_poly_sum(PG_FUNCTION_ARGS); extern Datum numeric_poly_avg(PG_FUNCTION_ARGS); extern Datum numeric_poly_var_pop(PG_FUNCTION_ARGS); extern Datum numeric_poly_var_samp(PG_FUNCTION_ARGS); extern Datum numeric_poly_stddev_pop(PG_FUNCTION_ARGS); extern Datum numeric_poly_stddev_samp(PG_FUNCTION_ARGS); extern Datum int2_sum(PG_FUNCTION_ARGS); extern Datum int4_sum(PG_FUNCTION_ARGS); extern Datum int8_sum(PG_FUNCTION_ARGS); extern Datum int2_avg_accum(PG_FUNCTION_ARGS); extern Datum int4_avg_accum(PG_FUNCTION_ARGS); extern Datum int2_avg_accum_inv(PG_FUNCTION_ARGS); extern Datum int4_avg_accum_inv(PG_FUNCTION_ARGS); extern Datum int8_avg_accum_inv(PG_FUNCTION_ARGS); extern Datum int8_avg(PG_FUNCTION_ARGS); extern Datum int2int4_sum(PG_FUNCTION_ARGS); extern Datum width_bucket_numeric(PG_FUNCTION_ARGS); extern Datum hash_numeric(PG_FUNCTION_ARGS); extern Datum generate_series_numeric(PG_FUNCTION_ARGS); extern Datum generate_series_step_numeric(PG_FUNCTION_ARGS); /* ri_triggers.c */ extern Datum RI_FKey_check_ins(PG_FUNCTION_ARGS); extern Datum RI_FKey_check_upd(PG_FUNCTION_ARGS); extern Datum RI_FKey_noaction_del(PG_FUNCTION_ARGS); extern Datum RI_FKey_noaction_upd(PG_FUNCTION_ARGS); extern Datum RI_FKey_cascade_del(PG_FUNCTION_ARGS); extern Datum RI_FKey_cascade_upd(PG_FUNCTION_ARGS); extern Datum RI_FKey_restrict_del(PG_FUNCTION_ARGS); extern Datum RI_FKey_restrict_upd(PG_FUNCTION_ARGS); extern Datum RI_FKey_setnull_del(PG_FUNCTION_ARGS); extern Datum RI_FKey_setnull_upd(PG_FUNCTION_ARGS); extern Datum RI_FKey_setdefault_del(PG_FUNCTION_ARGS); extern Datum RI_FKey_setdefault_upd(PG_FUNCTION_ARGS); /* trigfuncs.c */ extern Datum suppress_redundant_updates_trigger(PG_FUNCTION_ARGS); /* encoding support functions */ extern Datum getdatabaseencoding(PG_FUNCTION_ARGS); extern Datum database_character_set(PG_FUNCTION_ARGS); extern Datum pg_client_encoding(PG_FUNCTION_ARGS); extern Datum PG_encoding_to_char(PG_FUNCTION_ARGS); extern Datum PG_char_to_encoding(PG_FUNCTION_ARGS); extern Datum PG_character_set_name(PG_FUNCTION_ARGS); extern Datum PG_character_set_id(PG_FUNCTION_ARGS); extern Datum pg_convert(PG_FUNCTION_ARGS); extern Datum pg_convert_to(PG_FUNCTION_ARGS); extern Datum pg_convert_from(PG_FUNCTION_ARGS); extern Datum length_in_encoding(PG_FUNCTION_ARGS); extern Datum pg_encoding_max_length_sql(PG_FUNCTION_ARGS); /* format_type.c */ extern Datum format_type(PG_FUNCTION_ARGS); extern char *format_type_be(Oid type_oid); extern char *format_type_be_qualified(Oid type_oid); extern char *format_type_with_typemod(Oid type_oid, int32 typemod); extern Datum oidvectortypes(PG_FUNCTION_ARGS); extern int32 type_maximum_size(Oid type_oid, int32 typemod); /* quote.c */ extern Datum quote_ident(PG_FUNCTION_ARGS); extern Datum quote_literal(PG_FUNCTION_ARGS); extern char *quote_literal_cstr(const char *rawstr); extern Datum quote_nullable(PG_FUNCTION_ARGS); /* guc.c */ extern Datum show_config_by_name(PG_FUNCTION_ARGS); extern Datum set_config_by_name(PG_FUNCTION_ARGS); extern Datum show_all_settings(PG_FUNCTION_ARGS); extern Datum show_all_file_settings(PG_FUNCTION_ARGS); /* rls.c */ extern Datum row_security_active(PG_FUNCTION_ARGS); extern Datum row_security_active_name(PG_FUNCTION_ARGS); /* lockfuncs.c */ extern Datum pg_lock_status(PG_FUNCTION_ARGS); extern Datum pg_advisory_lock_int8(PG_FUNCTION_ARGS); extern Datum pg_advisory_xact_lock_int8(PG_FUNCTION_ARGS); extern Datum pg_advisory_lock_shared_int8(PG_FUNCTION_ARGS); extern Datum pg_advisory_xact_lock_shared_int8(PG_FUNCTION_ARGS); extern Datum pg_try_advisory_lock_int8(PG_FUNCTION_ARGS); extern Datum pg_try_advisory_xact_lock_int8(PG_FUNCTION_ARGS); extern Datum pg_try_advisory_lock_shared_int8(PG_FUNCTION_ARGS); extern Datum pg_try_advisory_xact_lock_shared_int8(PG_FUNCTION_ARGS); extern Datum pg_advisory_unlock_int8(PG_FUNCTION_ARGS); extern Datum pg_advisory_unlock_shared_int8(PG_FUNCTION_ARGS); extern Datum pg_advisory_lock_int4(PG_FUNCTION_ARGS); extern Datum pg_advisory_xact_lock_int4(PG_FUNCTION_ARGS); extern Datum pg_advisory_lock_shared_int4(PG_FUNCTION_ARGS); extern Datum pg_advisory_xact_lock_shared_int4(PG_FUNCTION_ARGS); extern Datum pg_try_advisory_lock_int4(PG_FUNCTION_ARGS); extern Datum pg_try_advisory_xact_lock_int4(PG_FUNCTION_ARGS); extern Datum pg_try_advisory_lock_shared_int4(PG_FUNCTION_ARGS); extern Datum pg_try_advisory_xact_lock_shared_int4(PG_FUNCTION_ARGS); extern Datum pg_advisory_unlock_int4(PG_FUNCTION_ARGS); extern Datum pg_advisory_unlock_shared_int4(PG_FUNCTION_ARGS); extern Datum pg_advisory_unlock_all(PG_FUNCTION_ARGS); /* txid.c */ extern Datum txid_snapshot_in(PG_FUNCTION_ARGS); extern Datum txid_snapshot_out(PG_FUNCTION_ARGS); extern Datum txid_snapshot_recv(PG_FUNCTION_ARGS); extern Datum txid_snapshot_send(PG_FUNCTION_ARGS); extern Datum txid_current(PG_FUNCTION_ARGS); extern Datum txid_current_snapshot(PG_FUNCTION_ARGS); extern Datum txid_snapshot_xmin(PG_FUNCTION_ARGS); extern Datum txid_snapshot_xmax(PG_FUNCTION_ARGS); extern Datum txid_snapshot_xip(PG_FUNCTION_ARGS); extern Datum txid_visible_in_snapshot(PG_FUNCTION_ARGS); /* uuid.c */ extern Datum uuid_in(PG_FUNCTION_ARGS); extern Datum uuid_out(PG_FUNCTION_ARGS); extern Datum uuid_send(PG_FUNCTION_ARGS); extern Datum uuid_recv(PG_FUNCTION_ARGS); extern Datum uuid_lt(PG_FUNCTION_ARGS); extern Datum uuid_le(PG_FUNCTION_ARGS); extern Datum uuid_eq(PG_FUNCTION_ARGS); extern Datum uuid_ge(PG_FUNCTION_ARGS); extern Datum uuid_gt(PG_FUNCTION_ARGS); extern Datum uuid_ne(PG_FUNCTION_ARGS); extern Datum uuid_cmp(PG_FUNCTION_ARGS); extern Datum uuid_hash(PG_FUNCTION_ARGS); /* windowfuncs.c */ extern Datum window_row_number(PG_FUNCTION_ARGS); extern Datum window_rank(PG_FUNCTION_ARGS); extern Datum window_dense_rank(PG_FUNCTION_ARGS); extern Datum window_percent_rank(PG_FUNCTION_ARGS); extern Datum window_cume_dist(PG_FUNCTION_ARGS); extern Datum window_ntile(PG_FUNCTION_ARGS); extern Datum window_lag(PG_FUNCTION_ARGS); extern Datum window_lag_with_offset(PG_FUNCTION_ARGS); extern Datum window_lag_with_offset_and_default(PG_FUNCTION_ARGS); extern Datum window_lead(PG_FUNCTION_ARGS); extern Datum window_lead_with_offset(PG_FUNCTION_ARGS); extern Datum window_lead_with_offset_and_default(PG_FUNCTION_ARGS); extern Datum window_first_value(PG_FUNCTION_ARGS); extern Datum window_last_value(PG_FUNCTION_ARGS); extern Datum window_nth_value(PG_FUNCTION_ARGS); /* access/spgist/spgquadtreeproc.c */ extern Datum spg_quad_config(PG_FUNCTION_ARGS); extern Datum spg_quad_choose(PG_FUNCTION_ARGS); extern Datum spg_quad_picksplit(PG_FUNCTION_ARGS); extern Datum spg_quad_inner_consistent(PG_FUNCTION_ARGS); extern Datum spg_quad_leaf_consistent(PG_FUNCTION_ARGS); /* access/spgist/spgkdtreeproc.c */ extern Datum spg_kd_config(PG_FUNCTION_ARGS); extern Datum spg_kd_choose(PG_FUNCTION_ARGS); extern Datum spg_kd_picksplit(PG_FUNCTION_ARGS); extern Datum spg_kd_inner_consistent(PG_FUNCTION_ARGS); /* access/spgist/spgtextproc.c */ extern Datum spg_text_config(PG_FUNCTION_ARGS); extern Datum spg_text_choose(PG_FUNCTION_ARGS); extern Datum spg_text_picksplit(PG_FUNCTION_ARGS); extern Datum spg_text_inner_consistent(PG_FUNCTION_ARGS); extern Datum spg_text_leaf_consistent(PG_FUNCTION_ARGS); /* access/gin/ginarrayproc.c */ extern Datum ginarrayextract(PG_FUNCTION_ARGS); extern Datum ginarrayextract_2args(PG_FUNCTION_ARGS); extern Datum ginqueryarrayextract(PG_FUNCTION_ARGS); extern Datum ginarrayconsistent(PG_FUNCTION_ARGS); extern Datum ginarraytriconsistent(PG_FUNCTION_ARGS); /* access/tablesample/bernoulli.c */ extern Datum tsm_bernoulli_handler(PG_FUNCTION_ARGS); /* access/tablesample/system.c */ extern Datum tsm_system_handler(PG_FUNCTION_ARGS); /* access/transam/twophase.c */ extern Datum pg_prepared_xact(PG_FUNCTION_ARGS); /* access/transam/multixact.c */ extern Datum pg_get_multixact_members(PG_FUNCTION_ARGS); /* access/transam/committs.c */ extern Datum pg_xact_commit_timestamp(PG_FUNCTION_ARGS); extern Datum pg_last_committed_xact(PG_FUNCTION_ARGS); /* catalogs/dependency.c */ extern Datum pg_describe_object(PG_FUNCTION_ARGS); extern Datum pg_identify_object(PG_FUNCTION_ARGS); extern Datum pg_identify_object_as_address(PG_FUNCTION_ARGS); /* catalog/objectaddress.c */ extern Datum pg_get_object_address(PG_FUNCTION_ARGS); /* commands/constraint.c */ extern Datum unique_key_recheck(PG_FUNCTION_ARGS); /* commands/event_trigger.c */ extern Datum pg_event_trigger_dropped_objects(PG_FUNCTION_ARGS); extern Datum pg_event_trigger_table_rewrite_oid(PG_FUNCTION_ARGS); extern Datum pg_event_trigger_table_rewrite_reason(PG_FUNCTION_ARGS); extern Datum pg_event_trigger_ddl_commands(PG_FUNCTION_ARGS); /* commands/extension.c */ extern Datum pg_available_extensions(PG_FUNCTION_ARGS); extern Datum pg_available_extension_versions(PG_FUNCTION_ARGS); extern Datum pg_extension_update_paths(PG_FUNCTION_ARGS); extern Datum pg_extension_config_dump(PG_FUNCTION_ARGS); /* commands/prepare.c */ extern Datum pg_prepared_statement(PG_FUNCTION_ARGS); /* utils/mmgr/portalmem.c */ extern Datum pg_cursor(PG_FUNCTION_ARGS); #endif /* BUILTINS_H */
78f3f2ac107bcc5c05f1893f79a2acbad9fc0d5f
72d652464a9d1528aede99c2d416d6f0e0bf3a04
/Sources/CCryptoBoringSSL/include/CCryptoBoringSSL_asm_base.h
836d127a41d962a07c050e5cc944b3399b126d82
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
apple/swift-crypto
288985439732eea85a2aa5a9975147ed98da6152
953b34a60168bb44ffc5e0c3fc345189cdbca128
refs/heads/main
2023-09-06T00:35:42.620284
2023-08-17T13:53:44
2023-08-17T13:53:44
198,488,246
1,412
165
Apache-2.0
2023-09-13T11:03:23
2019-07-23T18:36:09
C
UTF-8
C
false
false
8,003
h
CCryptoBoringSSL_asm_base.h
/* Copyright (c) 2023, Google Inc. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef OPENSSL_HEADER_ASM_BASE_H #define OPENSSL_HEADER_ASM_BASE_H #include "CCryptoBoringSSL_target.h" // This header contains symbols and common sections used by assembly files. It // is included as a public header to simplify the build, but is not intended for // external use. // // Every assembly file must include this header. Some linker features require // all object files to be tagged with some section metadata. This header file, // when included in assembly, adds that metadata. It also makes defines like // |OPENSSL_X86_64| available and includes the prefixing macros. // // Including this header in an assembly file imples: // // - The file does not require an executable stack. // // - The file, on aarch64, uses the macros defined below to be compatible with // BTI and PAC. // // - The file, on x86_64, requires the program to be compatible with Intel IBT // and SHSTK #if defined(__ASSEMBLER__) #if defined(BORINGSSL_PREFIX) #include "CCryptoBoringSSL_boringssl_prefix_symbols_asm.h" #endif #if defined(__ELF__) // Every ELF object file, even empty ones, should disable executable stacks. See // https://www.airs.com/blog/archives/518. .pushsection .note.GNU-stack, "", %progbits .popsection #endif #if defined(__CET__) && defined(OPENSSL_X86_64) // Clang and GCC define __CET__ and provide <cet.h> when they support Intel's // Indirect Branch Tracking. // https://lpc.events/event/7/contributions/729/attachments/496/903/CET-LPC-2020.pdf // // cet.h defines _CET_ENDBR which is used to mark function entry points for IBT. // and adds the assembly marker. The value of _CET_ENDBR is made dependant on if // '-fcf-protection' is passed to the compiler. _CET_ENDBR is only required when // the function is the target of an indirect jump, but BoringSSL chooses to mark // all assembly entry points because it is easier, and allows BoringSSL's ABI // tester to call the assembly entry points via an indirect jump. #include <cet.h> #else #define _CET_ENDBR #endif #if defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64) // We require the ARM assembler provide |__ARM_ARCH| from Arm C Language // Extensions (ACLE). This is supported in GCC 4.8+ and Clang 3.2+. MSVC does // not implement ACLE, but we require Clang's assembler on Windows. #if !defined(__ARM_ARCH) #error "ARM assembler must define __ARM_ARCH" #endif // __ARM_ARCH__ is used by OpenSSL assembly to determine the minimum target ARM // version. // // TODO(davidben): Switch the assembly to use |__ARM_ARCH| directly. #define __ARM_ARCH__ __ARM_ARCH // Even when building for 32-bit ARM, support for aarch64 crypto instructions // will be included. #define __ARM_MAX_ARCH__ 8 // Support macros for // - Armv8.3-A Pointer Authentication and // - Armv8.5-A Branch Target Identification // features which require emitting a .note.gnu.property section with the // appropriate architecture-dependent feature bits set. // // |AARCH64_SIGN_LINK_REGISTER| and |AARCH64_VALIDATE_LINK_REGISTER| expand to // PACIxSP and AUTIxSP, respectively. |AARCH64_SIGN_LINK_REGISTER| should be // used immediately before saving the LR register (x30) to the stack. // |AARCH64_VALIDATE_LINK_REGISTER| should be used immediately after restoring // it. Note |AARCH64_SIGN_LINK_REGISTER|'s modifications to LR must be undone // with |AARCH64_VALIDATE_LINK_REGISTER| before RET. The SP register must also // have the same value at the two points. For example: // // .global f // f: // AARCH64_SIGN_LINK_REGISTER // stp x29, x30, [sp, #-96]! // mov x29, sp // ... // ldp x29, x30, [sp], #96 // AARCH64_VALIDATE_LINK_REGISTER // ret // // |AARCH64_VALID_CALL_TARGET| expands to BTI 'c'. Either it, or // |AARCH64_SIGN_LINK_REGISTER|, must be used at every point that may be an // indirect call target. In particular, all symbols exported from a file must // begin with one of these macros. For example, a leaf function that does not // save LR can instead use |AARCH64_VALID_CALL_TARGET|: // // .globl return_zero // return_zero: // AARCH64_VALID_CALL_TARGET // mov x0, #0 // ret // // A non-leaf function which does not immediately save LR may need both macros // because |AARCH64_SIGN_LINK_REGISTER| appears late. For example, the function // may jump to an alternate implementation before setting up the stack: // // .globl with_early_jump // with_early_jump: // AARCH64_VALID_CALL_TARGET // cmp x0, #128 // b.lt .Lwith_early_jump_128 // AARCH64_SIGN_LINK_REGISTER // stp x29, x30, [sp, #-96]! // mov x29, sp // ... // ldp x29, x30, [sp], #96 // AARCH64_VALIDATE_LINK_REGISTER // ret // // .Lwith_early_jump_128: // ... // ret // // These annotations are only required with indirect calls. Private symbols that // are only the target of direct calls do not require annotations. Also note // that |AARCH64_VALID_CALL_TARGET| is only valid for indirect calls (BLR), not // indirect jumps (BR). Indirect jumps in assembly are currently not supported // and would require a macro for BTI 'j'. // // Although not necessary, it is safe to use these macros in 32-bit ARM // assembly. This may be used to simplify dual 32-bit and 64-bit files. // // References: // - "ELF for the Arm® 64-bit Architecture" // https://github.com/ARM-software/abi-aa/blob/master/aaelf64/aaelf64.rst // - "Providing protection for complex software" // https://developer.arm.com/architectures/learn-the-architecture/providing-protection-for-complex-software #if defined(__ARM_FEATURE_BTI_DEFAULT) && __ARM_FEATURE_BTI_DEFAULT == 1 #define GNU_PROPERTY_AARCH64_BTI (1 << 0) // Has Branch Target Identification #define AARCH64_VALID_CALL_TARGET hint #34 // BTI 'c' #else #define GNU_PROPERTY_AARCH64_BTI 0 // No Branch Target Identification #define AARCH64_VALID_CALL_TARGET #endif #if defined(__ARM_FEATURE_PAC_DEFAULT) && \ (__ARM_FEATURE_PAC_DEFAULT & 1) == 1 // Signed with A-key #define GNU_PROPERTY_AARCH64_POINTER_AUTH \ (1 << 1) // Has Pointer Authentication #define AARCH64_SIGN_LINK_REGISTER hint #25 // PACIASP #define AARCH64_VALIDATE_LINK_REGISTER hint #29 // AUTIASP #elif defined(__ARM_FEATURE_PAC_DEFAULT) && \ (__ARM_FEATURE_PAC_DEFAULT & 2) == 2 // Signed with B-key #define GNU_PROPERTY_AARCH64_POINTER_AUTH \ (1 << 1) // Has Pointer Authentication #define AARCH64_SIGN_LINK_REGISTER hint #27 // PACIBSP #define AARCH64_VALIDATE_LINK_REGISTER hint #31 // AUTIBSP #else #define GNU_PROPERTY_AARCH64_POINTER_AUTH 0 // No Pointer Authentication #if GNU_PROPERTY_AARCH64_BTI != 0 #define AARCH64_SIGN_LINK_REGISTER AARCH64_VALID_CALL_TARGET #else #define AARCH64_SIGN_LINK_REGISTER #endif #define AARCH64_VALIDATE_LINK_REGISTER #endif #if GNU_PROPERTY_AARCH64_POINTER_AUTH != 0 || GNU_PROPERTY_AARCH64_BTI != 0 .pushsection .note.gnu.property, "a"; .balign 8; .long 4; .long 0x10; .long 0x5; .asciz "GNU"; .long 0xc0000000; /* GNU_PROPERTY_AARCH64_FEATURE_1_AND */ .long 4; .long (GNU_PROPERTY_AARCH64_POINTER_AUTH | GNU_PROPERTY_AARCH64_BTI); .long 0; .popsection; #endif #endif // ARM || AARCH64 #endif // __ASSEMBLER__ #endif // OPENSSL_HEADER_ASM_BASE_H
0ebf64109a8bbd238036daa99c9ecacd031e54f7
b71097386a6da0e3ca65f19a1906f0ebe11eac18
/lib/dt-core.h
2094fcc4c721347b96700f834a70e3555ed301a2
[ "BSD-3-Clause" ]
permissive
hroptatyr/dateutils
0584063e4a35c511ad3600c27efb2f4214af24c6
c57828809a018061147bc806a058aa4c4b9c449a
refs/heads/master
2023-09-05T20:26:30.356886
2023-07-05T12:19:20
2023-07-05T12:19:20
2,341,061
517
44
NOASSERTION
2023-06-26T12:04:46
2011-09-07T11:19:46
C
UTF-8
C
false
false
10,657
h
dt-core.h
/*** dt-core.h -- our universe of datetimes * * Copyright (C) 2011-2022 Sebastian Freundt * * Author: Sebastian Freundt <freundt@ga-group.nl> * * This file is part of dateutils. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the author nor the names of any contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE 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 INCLUDED_dt_core_h_ #define INCLUDED_dt_core_h_ #include <stdlib.h> #include <stdint.h> #include <unistd.h> #include <stdbool.h> #include "boops.h" #include "date-core.h" #include "time-core.h" typedef enum { /* this one's our own version of UNK */ DT_UNK = 0, /* the lower date types come from date-core.h */ DT_PACK = DT_NDTYP, DT_YMDHMS = DT_PACK, DT_SEXY, DT_SEXYTAI, DT_NDTTYP, } dt_dttyp_t; typedef enum { DT_DURH = DT_NDURTYP + 0U, DT_DURM = DT_NDURTYP + 1U, DT_DURS = DT_NDURTYP + 2U, DT_DURNANO = DT_NDURTYP + 3U, } dt_dtdurtyp_t; /* this will be 16 and hence must be #defined as we're using * a bitfield of size 4 to store the dtdurtyp. */ #define DT_NDTDURTYP (DT_NDURTYP + 4U) /** packs * packs are just packs of dates and times */ typedef union { uint64_t u:53; struct { #if BYTE_ORDER == BIG_ENDIAN #define DT_YEAR_OFFS (1900) /* offset by the year 1900 */ unsigned int y:12; unsigned int m:4; unsigned int d:6; /* round up to 32 bits, remaining bits are seconds east */ unsigned int offs:10; /* time part */ unsigned int H:5; unsigned int M:8; unsigned int S:8; #elif BYTE_ORDER == LITTLE_ENDIAN unsigned int d:6; unsigned int m:4; /* offset by the year 1900 */ #define DT_YEAR_OFFS (1900) unsigned int y:12; /* round up to 32 bits, remaining bits are seconds east */ unsigned int offs:10; /* time part */ unsigned int S:8; unsigned int M:8; unsigned int H:5; #else # warning unknown byte order #endif /* BYTE_ORDER */ }; } dt_ymdhms_t; /** sexy * sexy is really, secsi, seconds since X, 1970-01-01T00:00:00 here */ typedef int64_t dt_sexy_t; typedef int64_t dt_ssexy_t; #define DT_SEXY_BASE_YEAR (1917) struct dt_dt_s { union { /* packs */ struct { /* dt type, or date type */ dt_dttyp_t typ:4; /* sandwich indicator (use d and t slots below) */ uint16_t sandwich:1; /* whether we had zone info already but fixed it */ uint16_t znfxd:1; /* whether to be aware of leap-seconds */ uint16_t tai:1; /* error indicator to denote date has been fixed up */ uint16_t fix:1; /* was duration indicator */ uint16_t xxx:1; /* negation indicator */ uint16_t neg:1; /* we've got 6 bits left here to coincide with dt_d_s * use that and the neg flag for zdiffs * zdiff itself has 15-minute resolution, * range [0, 63] aka [00:00 16:00] * The policy is to store the time always in UTC * but keep the difference in this slot. */ uint16_t zdiff:6; #define ZDIFF_RES (15U * 60U) union { uint64_t u:48; dt_ymdhms_t ymdhms; dt_sexy_t sexy:48; dt_ssexy_t sxepoch:48; struct { #if BYTE_ORDER == BIG_ENDIAN int32_t corr:16; int32_t soft:32; #elif BYTE_ORDER == LITTLE_ENDIAN int32_t soft:32; int32_t corr:16; #else # warning unknown byte order #endif /* BYTE_ORDER */ }; }; } __attribute__((packed)); /* sandwich types */ struct { struct dt_d_s d; struct dt_t_s t; }; }; }; struct dt_dtdur_s { union { /* packs */ struct { /* dt type, or date type */ dt_dtdurtyp_t durtyp:4; /* was sandwich indicator */ uint16_t:1; /* whether we had zone info already but fixed it */ uint16_t znfxd:1; /* whether to be aware of leap-seconds */ uint16_t tai:1; /* error indicator to denote date has been fixed up */ uint16_t fix:1; /* co-class indicator */ uint16_t cocl:1; /* negation indicator */ uint16_t neg:1; /* we've got 6 bits left here to coincide with dt_d_s * use that and the neg flag for zdiffs * zdiff itself has 15-minute resolution, * range [0, 63] aka [00:00 16:00] * The policy is to store the time always in UTC * but keep the difference in this slot. */ uint16_t zdiff:6; #define ZDIFF_RES (15U * 60U) union { uint64_t u:48; dt_ymdhms_t ymdhms; /* for value+unit durations */ dt_ssexy_t dv:48; struct { #if BYTE_ORDER == BIG_ENDIAN int32_t corr:16; int32_t soft:32; #elif BYTE_ORDER == LITTLE_ENDIAN int32_t soft:32; int32_t corr:16; #else # warning unknown byte order #endif /* BYTE_ORDER */ }; }; } __attribute__((packed)); /* sandwich types */ struct { struct dt_ddur_s d; struct dt_t_s t; }; }; }; /* decls */ /** * Like strptime() for our dates. * The format characters are _NOT_ compatible with strptime(). * If FMT is NULL the standard format for each calendric system is used, * see format.texi or dateutils info page. * * FMT can also be the name of a calendar: * - ymd for YMD dates * - ymcw for YMCW dates * - bizda for bizda/YMDU dates * * If optional EP is non-NULL it will point to the end of the parsed * date string. */ extern struct dt_dt_s dt_strpdt(const char *str, const char *fmt, char **ep); /** * Like strftime() for our dates */ extern size_t dt_strfdt(char *restrict buf, size_t bsz, const char *fmt, struct dt_dt_s); /** * Parse durations as in 1w5d, etc. */ extern struct dt_dtdur_s dt_strpdtdur(const char *str, char **ep); /** * Print a duration. */ extern size_t dt_strfdtdur(char *restrict buf, size_t bsz, const char *fmt, struct dt_dtdur_s); /** * Negate the duration. */ extern struct dt_dtdur_s dt_neg_dtdur(struct dt_dtdur_s); /** * Is duration DUR negative? */ extern int dt_dtdur_neg_p(struct dt_dtdur_s dur); /** * Like time() but return the current date in the desired format. */ extern struct dt_dt_s dt_datetime(dt_dttyp_t dttyp); /** * Convert D to another calendric system, specified by TGTTYP. */ extern struct dt_dt_s dt_dtconv(dt_dttyp_t tgttyp, struct dt_dt_s); /** * Add duration DUR to date/time D. * The result will be in the calendar as specified by TGTTYP, or if * DT_UNK is given, the calendar of D will be used. */ extern struct dt_dt_s dt_dtadd(struct dt_dt_s d, struct dt_dtdur_s dur); /** * Get duration between D1 and D2. * The result will be of type TGTTYP, * the calendar of D1 will be used, e.g. its month-per-year, days-per-week, * etc. conventions count. * If instead D2 should count, swap D1 and D2 and negate the duration * by setting/clearing the neg bit. */ extern struct dt_dtdur_s dt_dtdiff(dt_dtdurtyp_t tgttyp, struct dt_dt_s d1, struct dt_dt_s d2); /** * Compare two dates, yielding 0 if they are equal, -1 if D1 is older, * 1 if D1 is younger than the D2. */ extern int dt_dtcmp(struct dt_dt_s d1, struct dt_dt_s d2); /** * Check if D is in the interval spanned by D1 and D2, * 1 if D1 is younger than the D2. */ extern int dt_dt_in_range_p(struct dt_dt_s d, struct dt_dt_s d1, struct dt_dt_s d2); /* more specific but still useful functions */ /** * Convert a dt_dt_s to an epoch difference, based on the Unix epoch. */ extern dt_ssexy_t dt_to_unix_epoch(struct dt_dt_s); /** * Convert a dt_dt_s to an epoch difference, based on the GPS epoch. */ extern dt_ssexy_t dt_to_gps_epoch(struct dt_dt_s); /** * Set specific fallback date/time to use when input is underspecified. * Internally, when no default is set and input is underspecified the * value of `dt_datetime()' (i.e. now) is used to fill fields up. * This is also used for ambiguous format specifiers (like %y or %_y) * to position their range on the absolute time scale. */ extern void dt_set_base(struct dt_dt_s); #define HAVE_DT_SET_BASE 1 /** * Return the base date/time as struct dt_dt_s. */ extern struct dt_dt_s dt_get_base(void); #define HAVE_DT_GET_BASE 1 /** * Crop datetimess with days beyond ultimo. */ extern __attribute__((const)) struct dt_dt_s dt_fixup(struct dt_dt_s); /** * Decay military midnigths to the following day 00:00:00 */ extern __attribute__((const)) struct dt_dt_s dt_milfup(struct dt_dt_s); /* some useful gimmicks, sort of */ static inline __attribute__((const)) bool dt_unk_p(struct dt_dt_s d) { return !(d.sandwich || d.typ > DT_UNK); } static inline __attribute__((const)) bool dt_durunk_p(struct dt_dtdur_s d) { return !d.durtyp; } static inline __attribute__((const)) bool dt_sandwich_p(struct dt_dt_s d) { return d.sandwich && d.d.typ > DT_DUNK; } static inline __attribute__((const)) bool dt_sandwich_only_d_p(struct dt_dt_s d) { return !d.sandwich && d.d.typ > DT_DUNK && d.d.typ < DT_NDTYP; } static inline __attribute__((const)) bool dt_sandwich_only_t_p(struct dt_dt_s d) { return d.sandwich && d.typ == DT_UNK; } static inline __attribute__((const)) bool dt_separable_p(struct dt_dt_s d) { /* return true if D is a d+t sandwich or D is d-only or D is t-only */ return d.typ < DT_PACK; } #define DT_SANDWICH_UNK (DT_UNK) static inline void dt_make_sandwich(struct dt_dt_s *d, dt_dtyp_t dty, dt_ttyp_t tty) { d->d.typ = dty; d->t.typ = tty; d->sandwich = 1; return; } static inline void dt_make_d_only(struct dt_dt_s *d, dt_dtyp_t dty) { d->d.typ = dty; d->t.typ = DT_TUNK; d->sandwich = 0; return; } static inline void dt_make_t_only(struct dt_dt_s *d, dt_ttyp_t tty) { d->d.typ = DT_DUNK; d->t.typ = tty; d->sandwich = 1; return; } #endif /* INCLUDED_dt_core_h_ */
3f610854488688498e45e4a433c1634aae08010f
50dd46b8ece33f3cdd174284b15d1d51f89669d4
/2021/quals/hw-pcivault/challenge/solution/protocol.c
5ff0f00c95412fbe753461409d44c2d3911fd571
[ "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
permissive
google/google-ctf
f99da1ee07729bbccb869fff1cbaed6a80e43bcc
df02323eaf945d15e124801c74abaadca2749dc7
refs/heads/master
2023-08-31T14:30:27.548081
2023-08-29T13:04:20
2023-08-29T13:04:20
131,317,137
4,136
607
Apache-2.0
2023-08-30T22:17:02
2018-04-27T15:56:03
Go
UTF-8
C
false
false
7,193
c
protocol.c
// Copyright 2021 Google LLC // // 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. #include "protocol.h" #include <linux/wait.h> #define EXEC_SYNC(priv, cmd) \ do { \ iowrite8((cmd) | CMD_EXECUTE, (priv)->hwmem); \ wait_event(device_wait_queue, \ ((ioread8((priv)->hwmem) & CMD_EXECUTE) == 0)); \ } while (0) int device_status_to_error_code(u8 status_code) { switch (status_code) { case STATUS_OK: return 0; case STATUS_IN_PROGRESS: return -EINPROGRESS; case STATUS_REQ_INIT: // Next call should init the device anyway. return -EAGAIN; case STATUS_ERROR: return -EIO; case STATUS_OOM: return -ENOMEM; default: return -EIO; } } int device_reset(struct private_data *priv) { // force device in the uninitialized state. printk(KERN_INFO "Resetting device\n"); EXEC_SYNC(priv, 66 | CMD_EXECUTE); return 0; } int device_init(struct private_data *priv) { struct DeviceConfigDescriptor device_descriptor = {}; struct HostConfigDescriptor host_descriptor = { .host_config_descriptor_length = sizeof(struct HostConfigDescriptor), .config_version = CONFIG_VERSION, .max_packet_size = /*MAX_PACKET_SIZE*/ 0x100}; u16 len; u8 status; int i; volatile int vi; printk(KERN_INFO "Initializing device\n"); status = ioread8(priv->hwmem + 1); if (status != STATUS_REQ_INIT) { printk(KERN_INFO "Device already initialized, skipping\n"); return 0; } // 1) Get device descriptor. EXEC_SYNC(priv, CMD_GET_DEVICE_CONFIG); status = ioread8(priv->hwmem + 1); len = ioread16(priv->hwmem + 2); if (status != STATUS_OK) { printk(KERN_INFO "Device did not accept GetDeviceConfig request: %d\n", status); return device_status_to_error_code(status); } if (len != sizeof(struct DeviceConfigDescriptor)) { printk(KERN_INFO "Device sent response of invalid length (%d vs expected %ld)\n", len, sizeof(struct DeviceConfigDescriptor)); return -EPROTO; } for (i = 0; i < sizeof(struct DeviceConfigDescriptor); i++) { ((u8 *)&device_descriptor)[i] = ioread8(priv->hwmem + 4 + i); } if (device_descriptor.device_config_descriptor_length != sizeof(struct DeviceConfigDescriptor) || device_descriptor.config_version != CONFIG_VERSION || device_descriptor.device_version != 1) { printk(KERN_INFO "Unknown version details in the device descriptor\n"); return -EPROTO; } priv->device_max_packet_size = device_descriptor.max_packet_size; // 2) Send host descriptor. for (i = 0; i < device_descriptor.host_config_descriptor_length; i++) { iowrite8(((u8 *)&host_descriptor)[i], priv->hwmem + 4 + i); } iowrite8(device_descriptor.host_config_descriptor_length, priv->hwmem + 2); iowrite8(CMD_SET_HOST_CONFIG | CMD_EXECUTE, priv->hwmem); wait_event(device_wait_queue, ((ioread8((priv)->hwmem) & CMD_EXECUTE) == 0)); status = ioread8(priv->hwmem + 1); if (status != STATUS_OK) { printk(KERN_INFO "Sending host config failed: %d\n", status); return device_status_to_error_code(status); } printk(KERN_INFO "Device initialized\n"); return 0; } int device_select_entry(struct private_data *priv, const char *entry_name) { u16 len = 0; int rc; // Assure device is initialized. if (ioread8(priv->hwmem + 1) == STATUS_REQ_INIT) { rc = device_init(priv); if (rc < 0) return rc; } // Write payload. for (len = 0; entry_name[len] && len < priv->device_max_packet_size - 4; len++) { iowrite8(entry_name[len], priv->hwmem + 4 + len); } // Write entry length. iowrite16(len, priv->hwmem + 2); EXEC_SYNC(priv, CMD_SET_KEY); return device_status_to_error_code(ioread8(priv->hwmem + 1)); } int device_read_entry(struct private_data *priv, char *buffer) { size_t i; u8 status; u16 len; int rc; // Assure device is initialized. if (ioread8(priv->hwmem + 1) == STATUS_REQ_INIT) { return -EBUSY; rc = device_init(priv); if (rc < 0) return rc; } EXEC_SYNC(priv, CMD_GET_VAL); status = ioread8(priv->hwmem + 1); len = ioread16(priv->hwmem + 2); for (i = 0; i < len; i++) { buffer[i] = ioread8(priv->hwmem + 4 + i); } if (status != STATUS_OK) return device_status_to_error_code(status); return len; } int device_write_entry(struct private_data *priv, const char *buffer, size_t buffer_sz) { size_t i; int rc; // Assure device is initialized. if (ioread8(priv->hwmem + 1) == STATUS_REQ_INIT) { rc = device_init(priv); if (rc < 0) return rc; } if (buffer == NULL) { return -EINVAL; } /* if (buffer_sz > priv->device_max_packet_size - 4) { return -EOVERFLOW; } */ for (i = 0; i < buffer_sz; i++) { iowrite8(buffer[i], priv->hwmem + 4 + i); } // Write length iowrite16(buffer_sz, priv->hwmem + 2); EXEC_SYNC(priv, CMD_SET_VAL); return device_status_to_error_code(ioread8(priv->hwmem + 1)); } int device_delete_entry(struct private_data *priv) { int rc; // Assure device is initialized. if (ioread8(priv->hwmem + 1) == STATUS_REQ_INIT) { rc = device_init(priv); if (rc < 0) return rc; } EXEC_SYNC(priv, CMD_DELETE); return device_status_to_error_code(ioread8(priv->hwmem + 1)); } int pwn_device(struct private_data *priv, long arg) { int i; volatile long j; struct HostConfigDescriptor host_descriptor = { .host_config_descriptor_length = sizeof(struct HostConfigDescriptor), .config_version = CONFIG_VERSION, .max_packet_size = 0x100}; // 1) Make sure we're in the uninitialized state. while (ioread8(priv->hwmem + 1) != STATUS_REQ_INIT) { printk(KERN_INFO "Resetting device"); EXEC_SYNC(priv, 66); } // Send over our valid config, then change it midway. // data for (i = 0; i < sizeof(struct HostConfigDescriptor); i++) { iowrite8(((u8 *)&host_descriptor)[i], priv->hwmem + 4 + i); } // len iowrite8(sizeof(struct HostConfigDescriptor), priv->hwmem + 2); // trigger iowrite8(CMD_SET_HOST_CONFIG | CMD_EXECUTE, (priv)->hwmem); // delay for (j = 0; j < arg; j++) { } // HACKHACKHACK host_descriptor.max_packet_size = MAX_PACKET_SIZE; for (i = offsetof(struct HostConfigDescriptor, max_packet_size); i < sizeof(struct HostConfigDescriptor); i++) { iowrite8(((u8 *)&host_descriptor)[i], priv->hwmem + 4 + i); } wait_event(device_wait_queue, ((ioread8((priv)->hwmem) & CMD_EXECUTE) == 0)); return ioread8(priv->hwmem + 1); }
5548650f2c5fec64e61442803f95c6bd4a3f98e5
99bdb3251fecee538e0630f15f6574054dfc1468
/bsp/phytium/libraries/standalone/drivers/mmc/fsdmmc/fsdmmc.h
7805a17679dd351ff952fa896de9649733b93db4
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "Zlib", "LicenseRef-scancode-proprietary-license", "MIT", "BSD-3-Clause", "X11", "BSD-4-Clause-UC" ]
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
5,417
h
fsdmmc.h
/* * Copyright : (C) 2022 Phytium Information Technology, Inc. * All Rights Reserved. * * This program is OPEN SOURCE software: you can redistribute it and/or modify it * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, * either version 1.0 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 Phytium Public License for more details. * * * FilePath: fsdmmc.h * Date: 2022-02-10 14:53:42 * LastEditTime: 2022-02-18 08:55:57 * Description:  This file is for functions in this file are the minimum required functions * for this driver. * * Modify History: * Ver   Who        Date         Changes * ----- ------     --------    -------------------------------------- * 1.0 zhugengyu 2021/12/2 init */ #ifndef FSDMMC_H #define FSDMMC_H /***************************** Include Files *********************************/ #include "ftypes.h" #include "ferror_code.h" #include "fkernel.h" #ifdef __cplusplus extern "C" { #endif /************************** Constant Definitions *****************************/ #define FSDMMC_SUCCESS FT_SUCCESS #define FSDMMC_ERR_NOT_READY FT_MAKE_ERRCODE(ErrModBsp, ErrBspMmc, 1) #define FSDMMC_ERR_TIMEOUT FT_MAKE_ERRCODE(ErrModBsp, ErrBspMmc, 2) #define FSDMMC_ERR_CMD_FAILED FT_MAKE_ERRCODE(ErrModBsp, ErrBspMmc, 3) #define FSDMMC_ERR_DATA_FAILED FT_MAKE_ERRCODE(ErrModBsp, ErrBspMmc, 4) #define FSDMMC_ERR_CARD_NO_FOUND FT_MAKE_ERRCODE(ErrModBsp, ErrBspMmc, 5) #define FSDMMC_ERR_INVALID_BUF FT_MAKE_ERRCODE(ErrModBsp, ErrBspMmc, 6) /**************************** Type Definitions *******************************/ enum { FSDMMC_DMA_BD_INTR = 0, FSDMMC_CMD_INTR, FSDMMC_ERROR_INTR, FSDMMC_INTR_NUM }; /* 中断类型 */ enum { FSDMMC_EVT_CARD_REMOVED = 0, FSDMMC_EVT_CMD_DONE, FSDMMC_EVT_CMD_ERROR, FSDMMC_EVT_CMD_RESP_ERROR, FSDMMC_EVT_DATA_ERROR, FSDMMC_EVT_DATA_READ_DONE, FSDMMC_EVT_DATA_WRITE_DONE, FSDMMC_EVT_NUM }; /* 事件类型 */ /** * This typedef contains data information for the device. */ typedef struct { u8 *buf; u32 blksz; u32 blkcnt; u32 datalen; } FSdmmcData; /** * This typedef contains command information for the device. */ typedef struct { u32 cmdidx; u32 cmdarg; u32 resptype; u32 response[4]; u32 flag; #define FSDMMC_CMD_FLAG_NEED_STOP BIT(0) #define FSDMMC_CMD_FLAG_NEED_INIT BIT(1) #define FSDMMC_CMD_FLAG_EXP_RESP BIT(2) #define FSDMMC_CMD_FLAG_EXP_LONG_RESP BIT(3) #define FSDMMC_CMD_FLAG_NEED_RESP_CRC BIT(4) #define FSDMMC_CMD_FLAG_EXP_DATA BIT(5) #define FSDMMC_CMD_FLAG_WRITE_DATA BIT(6) #define FSDMMC_CMD_FLAG_READ_DATA BIT(7) #define FSDMMC_CMD_FLAG_NEED_AUTO_STOP BIT(8) #define FSDMMC_CMD_FLAG_ADTC BIT(9) FSdmmcData *data_p; } FSdmmcCmd; /** * This typedef contains configuration information for the device. */ typedef struct { u32 instance_id; /* Device instance id */ uintptr base_addr; /* Device base address */ u32 irq_num[FSDMMC_INTR_NUM]; } FSdmmcConfig; typedef void (*FSdmmcEventHandler)(void *args); /** * This typedef contains driver instance data. The user is required to allocate a * variable of this type for every device in the system. A pointer * to a variable of this type is then passed to the driver API functions. */ typedef struct { FSdmmcConfig config; /* Current active configs */ u32 is_ready; /* Device is initialized and ready */ FSdmmcEventHandler evt_handler[FSDMMC_EVT_NUM]; void *evt_args[FSDMMC_EVT_NUM]; } FSdmmc; /* Device instance */ /************************** Variable Definitions *****************************/ /***************** Macros (Inline Functions) Definitions *********************/ /************************** Function Prototypes ******************************/ /* 获取FSDMMC控制器默认配置 */ const FSdmmcConfig *FSdmmcLookupConfig(u32 instance_id); /* 初始化FSDMMC控制器, 使之可以使用 */ FError FSdmmcCfgInitialize(FSdmmc *instance_p, const FSdmmcConfig *cofig_p); /* 去使能FSDMMC控制器, 清零实例数据 */ void FSdmmcDeInitialize(FSdmmc *instance_p); /* 通过FSDMMC轮询方式发送/接收数据和命令 */ FError FSdmmcPollTransfer(FSdmmc *instance_p, FSdmmcCmd *cmd_data_p); /* 通过FSDMMC中断方式发送/接收数据和命令 */ FError FSdmmcInterruptTransfer(FSdmmc *instance_p, FSdmmcCmd *cmd_data_p); /* 获取FSDMMC的中断掩码 */ u32 FSdmmcGetInterruptMask(uintptr base_addr, u32 intr_type); /* 设置FSDMMC的中断掩码 */ void FSdmmcSetInterruptMask(uintptr base_addr, u32 intr_type, u32 mask, boolean enable); /* 命令中断响应函数 */ void FSdmmcCmdInterrupHandler(s32 vector, void *param); /* 错误中断响应函数 */ void FSdmmcErrInterrupHandler(s32 vector, void *param); /* DMA中断响应函数 */ void FSdmmcDmaInterrupHandler(s32 vector, void *param); /* 注册中断事件响应函数 */ void FSdmmcRegisterInterruptHandler(FSdmmc *instance_p, u32 event, FSdmmcEventHandler handler, void *args); #ifdef __cplusplus } #endif #endif
730a4611bf9d3cda4312927927ef51ad5f2bb6ae
5fdaec353b93b273d117c5ef1ca7d2352f4bad4b
/orio-0.1.0/testsuite/lu/pluto/lu.base.c
353913094b9e41614f7c75a33adadde3d757b874
[ "MIT", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-other-permissive" ]
permissive
bondhugula/pluto
1ddf0bf53dc8a9c50f895018b2810558441e85f3
eddc38537d61cd49d55e454831086848d51473d7
refs/heads/master
2023-07-21T19:53:05.377621
2023-06-21T09:22:57
2023-07-15T03:50:17
76,021,818
242
68
MIT
2023-07-15T03:50:18
2016-12-09T09:35:40
C
UTF-8
C
false
false
1,897
c
lu.base.c
#include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) double L[N][N]; double U[N][N]; double A[N][N+13]; void print_array() { int i, j; for (i=0; i<N; i++) { for (j=0; j<N; j++) { fprintf(stderr, "%lf ", round(A[i][j])); if (j%80 == 79) fprintf(stderr, "\n"); } fprintf(stderr, "\n"); } fprintf(stderr, "\n"); } void init_arrays() { int i, j, k; /* have to initialize this matrix properly to prevent * division by zero */ for (i=0; i<N; i++) { for (j=0; j<N; j++) { L[i][j] = 0.0; U[i][j] = 0.0; } } for (i=0; i<N; i++) { for (j=0; j<=i; j++) { L[i][j] = i+j+1; U[j][i] = i+j+1; } } for (i=0; i<N; i++) { for (j=0; j<N; j++) { for (k=0; k<N; k++) { A[i][j] += L[i][k]*U[k][j]; } } } } double rtclock() { struct timezone tzp; struct timeval tp; int stat; gettimeofday (&tp, &tzp); return (tp.tv_sec + tp.tv_usec*1.0e-6); } int main() { init_arrays(); double annot_t_start=0, annot_t_end=0, annot_t_total=0; int annot_i; for (annot_i=0; annot_i<REPS; annot_i++) { annot_t_start = rtclock(); register int i,j,k; for (k=0; k<=N-1; k++) { for (j=k+1; j<=N-1; j++) A[k][j] = A[k][j]/A[k][k]; for(i=k+1; i<=N-1; i++) for (j=k+1; j<=N-1; j++) A[i][j] = A[i][j] - A[i][k]*A[k][j]; } annot_t_end = rtclock(); annot_t_total += annot_t_end - annot_t_start; } //print_array(); annot_t_total = annot_t_total / REPS; printf("%f\n", annot_t_total); return ((int) A[0][0]); }
0b8d8c417b9f0348ae8cd7801a0ce955dde1498b
774b8fcea7c8b57b7494cc7f48c6593f5e3e0517
/src/wolfssl/wolfcrypt/blake2-int.h
0a01a2154bee3a0f91aa72a02333d5cf4982d774
[ "MIT" ]
permissive
Mixiaoxiao/Arduino-HomeKit-ESP8266
a180603fe20db0374d00ce2266827249151e76af
8a8e1a065005e9252d728b24f96f6d0b29993f67
refs/heads/master
2023-08-03T12:49:47.785503
2022-07-21T18:02:27
2022-07-21T18:02:27
240,946,290
1,385
274
MIT
2023-07-19T12:21:00
2020-02-16T18:50:03
C
UTF-8
C
false
false
5,808
h
blake2-int.h
/* BLAKE2 reference source code package - reference C implementations Written in 2012 by Samuel Neves <sneves@dei.uc.pt> To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty. You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. */ /* blake2-int.h * * Copyright (C) 2006-2017 wolfSSL Inc. * * This file is part of wolfSSL. * * wolfSSL 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. * * wolfSSL is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ #ifndef WOLFCRYPT_BLAKE2_INT_H #define WOLFCRYPT_BLAKE2_INT_H #include <wolfssl/wolfcrypt/types.h> #if defined(_MSC_VER) #define ALIGN(x) __declspec(align(x)) #elif defined(__GNUC__) #define ALIGN(x) __attribute__((aligned(x))) #else #define ALIGN(x) #endif #if defined(__cplusplus) extern "C" { #endif enum blake2s_constant { BLAKE2S_BLOCKBYTES = 64, BLAKE2S_OUTBYTES = 32, BLAKE2S_KEYBYTES = 32, BLAKE2S_SALTBYTES = 8, BLAKE2S_PERSONALBYTES = 8 }; enum blake2b_constant { BLAKE2B_BLOCKBYTES = 128, BLAKE2B_OUTBYTES = 64, BLAKE2B_KEYBYTES = 64, BLAKE2B_SALTBYTES = 16, BLAKE2B_PERSONALBYTES = 16 }; #pragma pack(push, 1) typedef struct __blake2s_param { byte digest_length; /* 1 */ byte key_length; /* 2 */ byte fanout; /* 3 */ byte depth; /* 4 */ word32 leaf_length; /* 8 */ byte node_offset[6];/* 14 */ byte node_depth; /* 15 */ byte inner_length; /* 16 */ /* byte reserved[0]; */ byte salt[BLAKE2B_SALTBYTES]; /* 24 */ byte personal[BLAKE2S_PERSONALBYTES]; /* 32 */ } blake2s_param; ALIGN( 64 ) typedef struct __blake2s_state { word32 h[8]; word32 t[2]; word32 f[2]; byte buf[2 * BLAKE2S_BLOCKBYTES]; word64 buflen; byte last_node; } blake2s_state ; typedef struct __blake2b_param { byte digest_length; /* 1 */ byte key_length; /* 2 */ byte fanout; /* 3 */ byte depth; /* 4 */ word32 leaf_length; /* 8 */ word64 node_offset; /* 16 */ byte node_depth; /* 17 */ byte inner_length; /* 18 */ byte reserved[14]; /* 32 */ byte salt[BLAKE2B_SALTBYTES]; /* 48 */ byte personal[BLAKE2B_PERSONALBYTES]; /* 64 */ } blake2b_param; ALIGN( 64 ) typedef struct __blake2b_state { word64 h[8]; word64 t[2]; word64 f[2]; byte buf[2 * BLAKE2B_BLOCKBYTES]; word64 buflen; byte last_node; } blake2b_state; typedef struct __blake2sp_state { blake2s_state S[8][1]; blake2s_state R[1]; byte buf[8 * BLAKE2S_BLOCKBYTES]; word64 buflen; } blake2sp_state; typedef struct __blake2bp_state { blake2b_state S[4][1]; blake2b_state R[1]; byte buf[4 * BLAKE2B_BLOCKBYTES]; word64 buflen; } blake2bp_state; #pragma pack(pop) /* Streaming API */ int blake2s_init( blake2s_state *S, const byte outlen ); int blake2s_init_key( blake2s_state *S, const byte outlen, const void *key, const byte keylen ); int blake2s_init_param( blake2s_state *S, const blake2s_param *P ); int blake2s_update( blake2s_state *S, const byte *in, word64 inlen ); int blake2s_final( blake2s_state *S, byte *out, byte outlen ); int blake2b_init( blake2b_state *S, const byte outlen ); int blake2b_init_key( blake2b_state *S, const byte outlen, const void *key, const byte keylen ); int blake2b_init_param( blake2b_state *S, const blake2b_param *P ); int blake2b_update( blake2b_state *S, const byte *in, word64 inlen ); int blake2b_final( blake2b_state *S, byte *out, byte outlen ); int blake2sp_init( blake2sp_state *S, const byte outlen ); int blake2sp_init_key( blake2sp_state *S, const byte outlen, const void *key, const byte keylen ); int blake2sp_update( blake2sp_state *S, const byte *in, word64 inlen ); int blake2sp_final( blake2sp_state *S, byte *out, byte outlen ); int blake2bp_init( blake2bp_state *S, const byte outlen ); int blake2bp_init_key( blake2bp_state *S, const byte outlen, const void *key, const byte keylen ); int blake2bp_update( blake2bp_state *S, const byte *in, word64 inlen ); int blake2bp_final( blake2bp_state *S, byte *out, byte outlen ); /* Simple API */ int blake2s( byte *out, const void *in, const void *key, const byte outlen, const word64 inlen, byte keylen ); int blake2b( byte *out, const void *in, const void *key, const byte outlen, const word64 inlen, byte keylen ); int blake2sp( byte *out, const void *in, const void *key, const byte outlen, const word64 inlen, byte keylen ); int blake2bp( byte *out, const void *in, const void *key, const byte outlen, const word64 inlen, byte keylen ); static INLINE int blake2( byte *out, const void *in, const void *key, const byte outlen, const word64 inlen, byte keylen ) { return blake2b( out, in, key, outlen, inlen, keylen ); } #if defined(__cplusplus) } #endif #endif /* WOLFCRYPT_BLAKE2_INT_H */
ddbe8327f4c4da0efa46239595149b9f03b25b40
99bdb3251fecee538e0630f15f6574054dfc1468
/bsp/Infineon/libraries/IFX_PSOC6_HAL/mtb-pdl-cat1/drivers/source/cy_ipc_pipe.c
b97de3fd5e9836288938c220d84753bef4658fbb
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-warranty-disclaimer", "GPL-1.0-or-later", "LicenseRef-scancode-proprietary-license", "Zlib", "MIT", "BSD-3-Clause", "X11", "BSD-4-Clause-UC" ]
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
26,005
c
cy_ipc_pipe.c
/***************************************************************************//** * \file cy_ipc_pipe.c * \version 1.80 * * Description: * IPC Pipe Driver - This source file includes code for the Pipe layer on top * of the IPC driver. * ******************************************************************************** * Copyright 2016-2020 Cypress Semiconductor Corporation * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "cy_device.h" #if defined (CY_IP_M4CPUSS) || defined (CY_IP_M7CPUSS) #include "cy_ipc_pipe.h" /* Define a pointer to array of endPoints. */ static cy_stc_ipc_pipe_ep_t * cy_ipc_pipe_epArray = NULL; /******************************************************************************* * Function Name: Cy_IPC_Pipe_Config ****************************************************************************//** * * This function stores a copy of a pointer to the array of endpoints. All * access to endpoints will be via the index of the endpoint in this array. * * \note In general case, this function is called in the default startup code, * so user doesn't need to call it anywhere. * However, it may be useful in case of some pipe customizations. * * \param theEpArray * This is the pointer to an array of endpoint structures that the designer * created and will be used to reference all endpoints. * * \funcusage * \snippet ipc/snippet/main.c snippet_myIpcPipeEpArray * \snippet ipc/snippet/main.c snippet_Cy_IPC_Pipe_Config * *******************************************************************************/ void Cy_IPC_Pipe_Config(cy_stc_ipc_pipe_ep_t * theEpArray) { /* Keep copy of this endpoint */ if (cy_ipc_pipe_epArray == NULL) { cy_ipc_pipe_epArray = theEpArray; } } /******************************************************************************* * Function Name: Cy_IPC_Pipe_Init ****************************************************************************//** * * Initializes the system pipes. The system pipes are used by BLE. * \note The function should be called on all CPUs. * * \note In general case, this function is called in the default startup code, * so user doesn't need to call it anywhere. * However, it may be useful in case of some pipe customizations. * * \param config * This is the pointer to the pipe configuration structure * * \funcusage * \snippet ipc/snippet/main.c snippet_myIpcPipeCbArray * \snippet ipc/snippet/main.c snippet_myIpcPipeEpConfig * \snippet ipc/snippet/main.c snippet_Cy_IPC_Pipe_Init * *******************************************************************************/ void Cy_IPC_Pipe_Init(cy_stc_ipc_pipe_config_t const *config) { /* Create the interrupt structures and arrays needed */ cy_stc_sysint_t ipc_intr_cypipeConfig; cy_stc_ipc_pipe_ep_config_t epConfigDataA; cy_stc_ipc_pipe_ep_config_t epConfigDataB; /* Parameters checking begin */ CY_ASSERT_L1(NULL != config); #if (CY_CPU_CORTEX_M0P) CY_ASSERT_L2((uint32_t)(1UL << __NVIC_PRIO_BITS) > config->ep0ConfigData.ipcNotifierPriority); #else CY_ASSERT_L2((uint32_t)(1UL << __NVIC_PRIO_BITS) > config->ep1ConfigData.ipcNotifierPriority); #endif CY_ASSERT_L1(NULL != config->endpointsCallbacksArray); CY_ASSERT_L1(NULL != config->userPipeIsrHandler); /* Parameters checking end */ #if defined(CY_IP_M4CPUSS) /* Only for CAT1A devices. This Part of code is soon going to deprecated */ #if (CY_CPU_CORTEX_M0P) /* Receiver endpoint = EP0, Sender endpoint = EP1 */ epConfigDataA = config->ep0ConfigData; epConfigDataB = config->ep1ConfigData; /* Configure CM0 interrupts */ ipc_intr_cypipeConfig.intrSrc = (IRQn_Type)epConfigDataA.ipcNotifierMuxNumber; CY_MISRA_DEVIATE_LINE('MISRA C-2012 Rule 10.8','Intentional typecast to IRQn_Type enum'); ipc_intr_cypipeConfig.cm0pSrc = (cy_en_intr_t)((int32_t)cpuss_interrupts_ipc_0_IRQn + (int32_t)epConfigDataA.ipcNotifierNumber); ipc_intr_cypipeConfig.intrPriority = epConfigDataA.ipcNotifierPriority; #else /* Receiver endpoint = EP1, Sender endpoint = EP0 */ epConfigDataA = config->ep1ConfigData; epConfigDataB = config->ep0ConfigData; /* Configure interrupts */ CY_MISRA_DEVIATE_LINE('MISRA C-2012 Rule 10.8','Intentional typecast to IRQn_Type enum'); ipc_intr_cypipeConfig.intrSrc = (IRQn_Type)((int32_t)cpuss_interrupts_ipc_0_IRQn + (int32_t)epConfigDataA.ipcNotifierNumber); ipc_intr_cypipeConfig.intrPriority = epConfigDataA.ipcNotifierPriority; #endif /* (CY_CPU_CORTEX_M0P) */ /* Initialize the pipe endpoints */ Cy_IPC_Pipe_EndpointInit(epConfigDataA.epAddress, config->endpointsCallbacksArray, config->endpointClientsCount, epConfigDataA.epConfig, &ipc_intr_cypipeConfig); /* Create the endpoints for the CM4 just for reference */ Cy_IPC_Pipe_EndpointInit(epConfigDataB.epAddress, NULL, 0UL, epConfigDataB.epConfig, NULL); (void)Cy_SysInt_Init(&ipc_intr_cypipeConfig, config->userPipeIsrHandler); /* Enable the interrupts */ NVIC_EnableIRQ(ipc_intr_cypipeConfig.intrSrc); #else /* Receiver endpoint = EP0, Sender endpoint = EP1 */ epConfigDataA = config->ep0ConfigData; epConfigDataB = config->ep1ConfigData; /* New Implementation which supports all devices */ #if defined(CY_IP_M4CPUSS) && (CY_CPU_CORTEX_M0P) /* Configure CM0 interrupts */ ipc_intr_cypipeConfig.intrSrc = (IRQn_Type)epConfigDataA.ipcNotifierMuxNumber; CY_MISRA_DEVIATE_LINE('MISRA C-2012 Rule 10.8','Intentional typecast to IRQn_Type enum'); ipc_intr_cypipeConfig.cm0pSrc = (cy_en_intr_t)((int32_t)cpuss_interrupts_ipc_0_IRQn + (int32_t)epConfigDataA.ipcNotifierNumber); ipc_intr_cypipeConfig.intrPriority = epConfigDataA.ipcNotifierPriority; #elif defined (CY_IP_M7CPUSS) /* CM7 */ /* Configure CM0 interrupts */ CY_MISRA_DEVIATE_LINE('MISRA C-2012 Rule 10.8','Intentional typecast to uint32_t'); ipc_intr_cypipeConfig.intrSrc = ((epConfigDataA.ipcNotifierMuxNumber << 16) | (uint32_t)((int32_t)cpuss_interrupts_ipc_0_IRQn + (int32_t)epConfigDataA.ipcNotifierNumber)); ipc_intr_cypipeConfig.intrPriority = epConfigDataA.ipcNotifierPriority; #else /* Configure interrupts */ CY_MISRA_DEVIATE_LINE('MISRA C-2012 Rule 10.8','Intentional typecast to IRQn_Type enum'); ipc_intr_cypipeConfig.intrSrc = (IRQn_Type)((int32_t)cpuss_interrupts_ipc_0_IRQn + (int32_t)epConfigDataA.ipcNotifierNumber); ipc_intr_cypipeConfig.intrPriority = epConfigDataA.ipcNotifierPriority; #endif /* (CY_CPU_CORTEX_M0P && CY_IP_M4CPUSS) */ /* Initialize the pipe endpoints */ Cy_IPC_Pipe_EndpointInit(epConfigDataA.epAddress, config->endpointsCallbacksArray, config->endpointClientsCount, epConfigDataA.epConfig, &ipc_intr_cypipeConfig); /* Create the endpoints for the CM4 just for reference */ Cy_IPC_Pipe_EndpointInit(epConfigDataB.epAddress, NULL, 0UL, epConfigDataB.epConfig, NULL); (void)Cy_SysInt_Init(&ipc_intr_cypipeConfig, config->userPipeIsrHandler); /* Enable the interrupts */ #if defined (CY_IP_M7CPUSS) CY_MISRA_DEVIATE_LINE('MISRA C-2012 Rule 10.8','Intentional typecast to IRQn_Type enum'); NVIC_EnableIRQ((IRQn_Type)((ipc_intr_cypipeConfig.intrSrc >> 16) & 0x00FFU)); #else NVIC_EnableIRQ(ipc_intr_cypipeConfig.intrSrc); #endif /* defined (CY_IP_M7CPUSS) */ #endif /* CY_IP_M4CPUSS */ } /******************************************************************************* * Function Name: Cy_IPC_Pipe_EndpointInit ****************************************************************************//** * * This function initializes the endpoint of a pipe for the current CPU. The * current CPU is the CPU that is executing the code. An endpoint of a pipe * is for the IPC channel that receives a message for the current CPU. * * After this function is called, the callbackArray needs to be populated * with the callback functions for that endpoint using the * Cy_IPC_Pipe_RegisterCallback() function. * * \note In general case, this function is called within \ref Cy_IPC_Pipe_Init, * so user doesn't need to call it anywhere. * However, it may be useful in case of some pipe/endpoint customizations. * * \param epAddr * This parameter is the address (or index in the array of endpoint structures) * that designates the endpoint you want to initialize. * * \param cbArray * This is a pointer to the callback function array. Based on the client ID, one * of the functions in this array is called to process the message. * * \param cbCnt * This is the size of the callback array, or the number of defined clients. * * \param epConfig * This value defines the IPC channel, IPC interrupt number, and the interrupt * mask for the entire pipe. * The format of the endpoint configuration * Bits[31:16] Interrupt Mask * Bits[15:8 ] IPC interrupt * Bits[ 7:0 ] IPC channel * * \param epInterrupt * This is a pointer to the endpoint interrupt description structure. * * \funcusage * \snippet ipc/snippet/main.c snippet_myIpcPipeCbArray * \snippet ipc/snippet/main.c snippet_myIpcPipeEpConfig * \snippet ipc/snippet/main.c snippet_Cy_IPC_Pipe_EndpointInit * *******************************************************************************/ void Cy_IPC_Pipe_EndpointInit(uint32_t epAddr, cy_ipc_pipe_callback_array_ptr_t cbArray, uint32_t cbCnt, uint32_t epConfig, cy_stc_sysint_t const *epInterrupt) { cy_stc_ipc_pipe_ep_t * endpoint; CY_ASSERT_L1(NULL != cy_ipc_pipe_epArray); endpoint = &cy_ipc_pipe_epArray[epAddr]; /* Extract the channel, interrupt and interrupt mask */ endpoint->ipcChan = _FLD2VAL(CY_IPC_PIPE_CFG_CHAN, epConfig); endpoint->intrChan = _FLD2VAL(CY_IPC_PIPE_CFG_INTR, epConfig); endpoint->pipeIntMask = _FLD2VAL(CY_IPC_PIPE_CFG_IMASK, epConfig); /* Assign IPC channel to this endpoint */ endpoint->ipcPtr = Cy_IPC_Drv_GetIpcBaseAddress (endpoint->ipcChan); /* Assign interrupt structure to endpoint and Initialize the interrupt mask for this endpoint */ endpoint->ipcIntrPtr = Cy_IPC_Drv_GetIntrBaseAddr(endpoint->intrChan); /* Only allow notify and release interrupts from endpoints in this pipe. */ Cy_IPC_Drv_SetInterruptMask(endpoint->ipcIntrPtr, endpoint->pipeIntMask, endpoint->pipeIntMask); /* Save the Client count and the callback array pointer */ endpoint->clientCount = cbCnt; endpoint->callbackArray = cbArray; endpoint->busy = CY_IPC_PIPE_ENDPOINT_NOTBUSY; if (NULL != epInterrupt) { #if defined (CY_IP_M7CPUSS) CY_MISRA_DEVIATE_LINE('MISRA C-2012 Rule 10.8','Intentional typecast to IRQn_Type enum.'); endpoint->pipeIntrSrc = (IRQn_Type)((epInterrupt->intrSrc >> 16) & 0x00FFU); #else endpoint->pipeIntrSrc = epInterrupt->intrSrc; #endif /* CY_IP_M7CPUSS */ } } /******************************************************************************* * Function Name: Cy_IPC_Pipe_SendMessage ****************************************************************************//** * * This function is used to send a message from one endpoint to another. It * generates an interrupt on the endpoint that receives the message and a * release interrupt to the sender to acknowledge the message has been processed. * * \param toAddr * This parameter is the address (or index in the array of endpoint structures) * of the endpoint to which you are sending the message. * * \param fromAddr * This parameter is the address (or index in the array of endpoint structures) * of the endpoint from which the message is being sent. * * \param msgPtr * Pointer to the message structure to be sent. * * \param callBackPtr * Pointer to the Release callback function. * * \return * CY_IPC_PIPE_SUCCESS: Message was sent to the other end of the pipe * CY_IPC_PIPE_ERROR_BAD_HANDLE: The handle provided for the pipe was not valid * CY_IPC_PIPE_ERROR_SEND_BUSY: The pipe is already busy sending a message * * \funcusage * \snippet ipc/snippet/main.c snippet_myReleaseCallback * \snippet ipc/snippet/main.c snippet_Cy_IPC_Pipe_SendMessage * *******************************************************************************/ cy_en_ipc_pipe_status_t Cy_IPC_Pipe_SendMessage(uint32_t toAddr, uint32_t fromAddr, void * msgPtr, cy_ipc_pipe_relcallback_ptr_t callBackPtr) { cy_en_ipc_pipe_status_t returnStatus; uint32_t releaseMask; uint32_t notifyMask; cy_stc_ipc_pipe_ep_t * fromEp; cy_stc_ipc_pipe_ep_t * toEp; CY_ASSERT_L1(NULL != msgPtr); CY_ASSERT_L1(NULL != cy_ipc_pipe_epArray); toEp = &(cy_ipc_pipe_epArray[toAddr]); fromEp = &cy_ipc_pipe_epArray[fromAddr]; /* Create the release mask for the "fromAddr" channel's interrupt channel */ releaseMask = (uint32_t)(1UL << (fromEp->intrChan)); /* Shift into position */ releaseMask = _VAL2FLD(CY_IPC_PIPE_MSG_RELEASE, releaseMask); /* Create the notify mask for the "toAddr" channel's interrupt channel */ notifyMask = (uint32_t)(1UL << (toEp->intrChan)); /* Check if IPC channel valid */ if( toEp->ipcPtr != NULL) { if(fromEp->busy == CY_IPC_PIPE_ENDPOINT_NOTBUSY) { /* Attempt to acquire the channel */ if( CY_IPC_DRV_SUCCESS == Cy_IPC_Drv_LockAcquire(toEp->ipcPtr) ) { /* Mask out the release mask area */ * (uint32_t *) msgPtr &= ~(CY_IPC_PIPE_MSG_RELEASE_Msk); * (uint32_t *) msgPtr |= releaseMask; #if (defined (CY_CPU_CORTEX_M7) && (CY_CPU_CORTEX_M7)) && (defined (CY_IP_M7CPUSS)) /* Flush the cache */ CY_MISRA_DEVIATE_LINE('SIZEOF_MISMATCH','SizeOf void pointer is passed.'); SCB_CleanDCache_by_Addr((uint32_t *)msgPtr,(int32_t)sizeof(msgPtr)); #endif /* If the channel was acquired, write the message. */ Cy_IPC_Drv_WriteDataValue(toEp->ipcPtr, (uint32_t) msgPtr); /* Set the busy flag. The ISR clears this after the release */ fromEp->busy = CY_IPC_PIPE_ENDPOINT_BUSY; /* Setup release callback function */ fromEp->releaseCallbackPtr = callBackPtr; /* Cause notify event/interrupt */ Cy_IPC_Drv_AcquireNotify(toEp->ipcPtr, notifyMask); returnStatus = CY_IPC_PIPE_SUCCESS; } else { /* Channel was already acquired, return Error */ returnStatus = CY_IPC_PIPE_ERROR_SEND_BUSY; } } else { /* Channel may not be acquired, but the release interrupt has not executed yet */ returnStatus = CY_IPC_PIPE_ERROR_SEND_BUSY; } } else { /* Null pipe handle. */ returnStatus = CY_IPC_PIPE_ERROR_BAD_HANDLE; } return (returnStatus); } /******************************************************************************* * Function Name: Cy_IPC_Pipe_RegisterCallback ****************************************************************************//** * * This function registers a callback that is called when a message is received * on a pipe. * The client_ID is the same as the index of the callback function array. * The callback may be a real function pointer or NULL if no callback is required. * * \param epAddr * This parameter is the address (or index in the array of endpoint structures) * that designates the endpoint to which you want to add callback functions. * * \param callBackPtr * Pointer to the callback function called when the endpoint has received a message. * If this parameters is NULL current callback will be unregistered. * * \param clientId * The index in the callback array (Client ID) where the function pointer is saved. * * \return * CY_IPC_PIPE_SUCCESS: Callback registered successfully * CY_IPC_PIPE_ERROR_BAD_CLIENT: Client ID out of range, callback not registered. * * \funcusage * \snippet ipc/snippet/main.c snippet_myAcquireCallback * \snippet ipc/snippet/main.c snippet_Cy_IPC_Pipe_RegisterCallback * *******************************************************************************/ cy_en_ipc_pipe_status_t Cy_IPC_Pipe_RegisterCallback(uint32_t epAddr, cy_ipc_pipe_callback_ptr_t callBackPtr, uint32_t clientId) { cy_en_ipc_pipe_status_t returnStatus; cy_stc_ipc_pipe_ep_t * thisEp; CY_ASSERT_L1(NULL != cy_ipc_pipe_epArray); thisEp = &cy_ipc_pipe_epArray[epAddr]; CY_ASSERT_L1(NULL != thisEp->callbackArray); /* Check if clientId is between 0 and less than client count */ if (clientId < thisEp->clientCount) { /* Copy callback function into callback function pointer array */ thisEp->callbackArray[clientId] = callBackPtr; returnStatus = CY_IPC_PIPE_SUCCESS; } else { returnStatus = CY_IPC_PIPE_ERROR_BAD_CLIENT; } return (returnStatus); } /******************************************************************************* * Function Name: Cy_IPC_Pipe_RegisterCallbackRel ****************************************************************************//** * * This function registers a default callback if a release interrupt * is generated but the current release callback function is null. * * * \param epAddr * This parameter is the address (or index in the array of endpoint structures) * that designates the endpoint to which you want to add a release callback function. * * \param callBackPtr * Pointer to the callback executed when the endpoint has received a message. * If this parameters is NULL current callback will be unregistered. * * \return * None * * \funcusage * \snippet ipc/snippet/main.c snippet_myDefaultReleaseCallback * \snippet ipc/snippet/main.c snippet_Cy_IPC_Pipe_RegisterCallbackRel * *******************************************************************************/ void Cy_IPC_Pipe_RegisterCallbackRel(uint32_t epAddr, cy_ipc_pipe_relcallback_ptr_t callBackPtr) { cy_stc_ipc_pipe_ep_t * endpoint; CY_ASSERT_L1(NULL != cy_ipc_pipe_epArray); endpoint = &cy_ipc_pipe_epArray[epAddr]; /* Copy callback function into callback function pointer array */ endpoint->defaultReleaseCallbackPtr = callBackPtr; } /******************************************************************************* * Function Name: Cy_IPC_Pipe_ExecuteCallback ****************************************************************************//** * * This function is called by the ISR for a given pipe endpoint to dispatch * the appropriate callback function based on the client ID for that endpoint. * * \param epAddr * This parameter is the address (or index in the array of endpoint structures) * that designates the endpoint to process. * * \note This function should be used instead of obsolete * Cy_IPC_Pipe_ExecCallback() function because it will be removed in the * next releases. * * \funcusage * \snippet ipc/snippet/main.c snippet_myIpcPipeEpArray * \snippet ipc/snippet/main.c snippet_Cy_IPC_Pipe_ExecuteCallback * *******************************************************************************/ void Cy_IPC_Pipe_ExecuteCallback(uint32_t epAddr) { cy_stc_ipc_pipe_ep_t * endpoint; CY_ASSERT_L1(NULL != cy_ipc_pipe_epArray); endpoint = &cy_ipc_pipe_epArray[epAddr]; Cy_IPC_Pipe_ExecCallback(endpoint); } /******************************************************************************* * Function Name: Cy_IPC_Pipe_ExecCallback ****************************************************************************//** * * This function is called by the ISR for a given pipe endpoint to dispatch * the appropriate callback function based on the client ID for that endpoint. * * \param endpoint * Pointer to endpoint structure. * * \note This function is obsolete and will be removed in the next releases. * Please use Cy_IPC_Pipe_ExecuteCallback() instead. * *******************************************************************************/ void Cy_IPC_Pipe_ExecCallback(cy_stc_ipc_pipe_ep_t * endpoint) { uint32_t *msgPtr = NULL; uint32_t clientID; uint32_t shadowIntr; uint32_t releaseMask = (uint32_t)0; cy_ipc_pipe_callback_ptr_t callbackPtr; /* Parameters checking begin */ CY_ASSERT_L1(NULL != endpoint); CY_ASSERT_L1(NULL != endpoint->ipcPtr); CY_ASSERT_L1(NULL != endpoint->ipcIntrPtr); CY_ASSERT_L1(NULL != endpoint->callbackArray); /* Parameters checking end */ shadowIntr = Cy_IPC_Drv_GetInterruptStatusMasked(endpoint->ipcIntrPtr); /* Check to make sure the interrupt was a notify interrupt */ if (0UL != Cy_IPC_Drv_ExtractAcquireMask(shadowIntr)) { /* Clear the notify interrupt. */ Cy_IPC_Drv_ClearInterrupt(endpoint->ipcIntrPtr, CY_IPC_NO_NOTIFICATION, Cy_IPC_Drv_ExtractAcquireMask(shadowIntr)); if ( Cy_IPC_Drv_IsLockAcquired (endpoint->ipcPtr) ) { /* Extract Client ID */ if( CY_IPC_DRV_SUCCESS == Cy_IPC_Drv_ReadMsgPtr (endpoint->ipcPtr, (void **)&msgPtr)) { #if (defined (CY_CPU_CORTEX_M7) && CY_CPU_CORTEX_M7) && (defined (CY_IP_M7CPUSS)) SCB_InvalidateDCache_by_Addr(msgPtr, (int32_t)sizeof(*msgPtr)); #endif /* Get release mask */ releaseMask = _FLD2VAL(CY_IPC_PIPE_MSG_RELEASE, *msgPtr); clientID = _FLD2VAL(CY_IPC_PIPE_MSG_CLIENT, *msgPtr); /* Make sure client ID is within valid range */ if (endpoint->clientCount > clientID) { callbackPtr = endpoint->callbackArray[clientID]; /* Get the callback function */ if (callbackPtr != NULL) { callbackPtr(msgPtr); /* Call the function pointer for "clientID" */ } } } /* Must always release the IPC channel */ (void)Cy_IPC_Drv_LockRelease (endpoint->ipcPtr, releaseMask); } } /* Check to make sure the interrupt was a release interrupt */ if (0UL != Cy_IPC_Drv_ExtractReleaseMask(shadowIntr)) /* Check for a Release interrupt */ { /* Clear the release interrupt */ Cy_IPC_Drv_ClearInterrupt(endpoint->ipcIntrPtr, Cy_IPC_Drv_ExtractReleaseMask(shadowIntr), CY_IPC_NO_NOTIFICATION); if (endpoint->releaseCallbackPtr != NULL) { endpoint->releaseCallbackPtr(); /* Clear the pointer after it was called */ endpoint->releaseCallbackPtr = NULL; } else { if (endpoint->defaultReleaseCallbackPtr != NULL) { endpoint->defaultReleaseCallbackPtr(); } } /* Clear the busy flag when release is detected */ endpoint->busy = CY_IPC_PIPE_ENDPOINT_NOTBUSY; } (void)Cy_IPC_Drv_GetInterruptStatus(endpoint->ipcIntrPtr); } /******************************************************************************* * Function Name: Cy_IPC_Pipe_EndpointPause ****************************************************************************//** * * This function sets the receiver endpoint to paused state. * * \param epAddr * This parameter is the address (or index in the array of endpoint structures) * that designates the endpoint to pause. * * \return * CY_IPC_PIPE_SUCCESS: Callback registered successfully * * \funcusage * \snippet ipc/snippet/main.c snippet_Cy_IPC_Pipe_EndpointPauseResume * *******************************************************************************/ cy_en_ipc_pipe_status_t Cy_IPC_Pipe_EndpointPause(uint32_t epAddr) { cy_stc_ipc_pipe_ep_t * endpoint; CY_ASSERT_L1(NULL != cy_ipc_pipe_epArray); endpoint = &cy_ipc_pipe_epArray[epAddr]; /* Disable the interrupts */ NVIC_DisableIRQ(endpoint->pipeIntrSrc); return (CY_IPC_PIPE_SUCCESS); } /******************************************************************************* * Function Name: Cy_IPC_Pipe_EndpointResume ****************************************************************************//** * * This function sets the receiver endpoint to active state. * * \param epAddr * This parameter is the address (or index in the array of endpoint structures) * that designates the endpoint to resume. * * \return * CY_IPC_PIPE_SUCCESS: Callback registered successfully * * \funcusage * \snippet ipc/snippet/main.c snippet_Cy_IPC_Pipe_EndpointPauseResume * *******************************************************************************/ cy_en_ipc_pipe_status_t Cy_IPC_Pipe_EndpointResume(uint32_t epAddr) { cy_stc_ipc_pipe_ep_t * endpoint; CY_ASSERT_L1(NULL != cy_ipc_pipe_epArray); endpoint = &cy_ipc_pipe_epArray[epAddr]; /* Enable the interrupts */ NVIC_EnableIRQ(endpoint->pipeIntrSrc); return (CY_IPC_PIPE_SUCCESS); } #endif /* [] END OF FILE */
f73c0702b807c1c1a4eb97301a8da3480f2d2520
13e2a9bf3ebb4d2c6cdcc5b3cadaa9d87d94933e
/src/game/gui/dialog.h
be7f1205a391e9e80c80a5774a42f48c8cb232b1
[ "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
1,069
h
dialog.h
#ifndef DIALOG_H #define DIALOG_H #include "game/gui/component.h" #include "utils/vector.h" #include "video/surface.h" typedef enum dialog_style_t { DIALOG_STYLE_YES_NO, DIALOG_STYLE_OK } dialog_style; typedef enum dialog_result_t { DIALOG_RESULT_CANCEL, DIALOG_RESULT_YES_OK, DIALOG_RESULT_NO } dialog_result; typedef struct component_t component; typedef struct dialog_t dialog; typedef void (*dialog_clicked_cb)(dialog *, dialog_result result); typedef struct dialog_t { int x; int y; char text[256]; surface background; component *yes; component *no; component *ok; int visible; dialog_result result; // events void *userdata; dialog_clicked_cb clicked; } dialog; void dialog_create(dialog *dlg, dialog_style style, const char *text, int x, int y); void dialog_free(dialog *dlg); void dialog_show(dialog *dlg, int visible); int dialog_is_visible(dialog *dlg); void dialog_tick(dialog *dlg); void dialog_render(dialog *dlg); void dialog_event(dialog *dlg, int action); #endif // DIALOG_H
dfbae56eb195fd2eb2c4aad2578db9858c64a726
cb6d0a660cfcb28ee9e8a1c0266925f8f541edfb
/libbpf-tools/sigsnoop.bpf.c
e03981fc1d6a5829a58b9a50f9ff35b5dc5f6093
[ "Apache-2.0" ]
permissive
iovisor/bcc
0e002769364523caeb731216021b0a3c881a723f
ec49363e2e9daec026ee6cae4c5fc316f8fab0ff
refs/heads/master
2023-09-03T22:37:47.238198
2023-08-31T14:44:55
2023-09-01T11:21:30
34,921,116
18,467
3,907
Apache-2.0
2023-09-13T21:22:53
2015-05-01T19:52:32
C
UTF-8
C
false
false
3,253
c
sigsnoop.bpf.c
// SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) /* Copyright (c) 2021~2022 Hengqi Chen */ #include <vmlinux.h> #include <bpf/bpf_helpers.h> #include "sigsnoop.h" #define MAX_ENTRIES 10240 const volatile pid_t filtered_pid = 0; const volatile int target_signal = 0; const volatile bool failed_only = false; struct { __uint(type, BPF_MAP_TYPE_HASH); __uint(max_entries, MAX_ENTRIES); __type(key, __u32); __type(value, struct event); } values SEC(".maps"); struct { __uint(type, BPF_MAP_TYPE_PERF_EVENT_ARRAY); __uint(key_size, sizeof(__u32)); __uint(value_size, sizeof(__u32)); } events SEC(".maps"); static int probe_entry(pid_t tpid, int sig) { struct event event = {}; __u64 pid_tgid; __u32 pid, tid; if (target_signal && sig != target_signal) return 0; pid_tgid = bpf_get_current_pid_tgid(); pid = pid_tgid >> 32; tid = (__u32)pid_tgid; if (filtered_pid && pid != filtered_pid) return 0; event.pid = pid; event.tpid = tpid; event.sig = sig; bpf_get_current_comm(event.comm, sizeof(event.comm)); bpf_map_update_elem(&values, &tid, &event, BPF_ANY); return 0; } static int probe_exit(void *ctx, int ret) { __u64 pid_tgid = bpf_get_current_pid_tgid(); __u32 tid = (__u32)pid_tgid; struct event *eventp; eventp = bpf_map_lookup_elem(&values, &tid); if (!eventp) return 0; if (failed_only && ret >= 0) goto cleanup; eventp->ret = ret; bpf_perf_event_output(ctx, &events, BPF_F_CURRENT_CPU, eventp, sizeof(*eventp)); cleanup: bpf_map_delete_elem(&values, &tid); return 0; } SEC("tracepoint/syscalls/sys_enter_kill") int kill_entry(struct trace_event_raw_sys_enter *ctx) { pid_t tpid = (pid_t)ctx->args[0]; int sig = (int)ctx->args[1]; return probe_entry(tpid, sig); } SEC("tracepoint/syscalls/sys_exit_kill") int kill_exit(struct trace_event_raw_sys_exit *ctx) { return probe_exit(ctx, ctx->ret); } SEC("tracepoint/syscalls/sys_enter_tkill") int tkill_entry(struct trace_event_raw_sys_enter *ctx) { pid_t tpid = (pid_t)ctx->args[0]; int sig = (int)ctx->args[1]; return probe_entry(tpid, sig); } SEC("tracepoint/syscalls/sys_exit_tkill") int tkill_exit(struct trace_event_raw_sys_exit *ctx) { return probe_exit(ctx, ctx->ret); } SEC("tracepoint/syscalls/sys_enter_tgkill") int tgkill_entry(struct trace_event_raw_sys_enter *ctx) { pid_t tpid = (pid_t)ctx->args[1]; int sig = (int)ctx->args[2]; return probe_entry(tpid, sig); } SEC("tracepoint/syscalls/sys_exit_tgkill") int tgkill_exit(struct trace_event_raw_sys_exit *ctx) { return probe_exit(ctx, ctx->ret); } SEC("tracepoint/signal/signal_generate") int sig_trace(struct trace_event_raw_signal_generate *ctx) { struct event event = {}; pid_t tpid = ctx->pid; int ret = ctx->errno; int sig = ctx->sig; __u64 pid_tgid; __u32 pid; if (failed_only && ret == 0) return 0; if (target_signal && sig != target_signal) return 0; pid_tgid = bpf_get_current_pid_tgid(); pid = pid_tgid >> 32; if (filtered_pid && pid != filtered_pid) return 0; event.pid = pid; event.tpid = tpid; event.sig = sig; event.ret = ret; bpf_get_current_comm(event.comm, sizeof(event.comm)); bpf_perf_event_output(ctx, &events, BPF_F_CURRENT_CPU, &event, sizeof(event)); return 0; } char LICENSE[] SEC("license") = "Dual BSD/GPL";
af9c09504127c73867afaa9f92ade5f34c8f4f77
802f0c1dd855693f709da4024b50d6d4938c13ff
/examples/c/wind_turbine_nmpc.c
d1b9c8434a2c2907a396948eedc9df72a03b3b3a
[ "BSD-2-Clause" ]
permissive
acados/acados
9cd480da3462725506f06199838e3cdae007d0c8
64166a37859108ab74ce6bf7408501f9bd4a89da
refs/heads/master
2023-08-16T13:03:44.298740
2023-08-15T13:07:48
2023-08-15T13:07:48
55,497,573
558
213
NOASSERTION
2023-09-01T09:01:33
2016-04-05T10:06:48
C
UTF-8
C
false
false
39,520
c
wind_turbine_nmpc.c
/* * Copyright (c) The acados authors. * * This file is part of acados. * * The 2-Clause BSD License * * 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.; */ // std #include <assert.h> #include <math.h> #include <stdio.h> #include <stdlib.h> // blasfeo #include "blasfeo/include/blasfeo_d_aux_ext_dep.h" #include "blasfeo/include/blasfeo_i_aux_ext_dep.h" // acados #include "acados_c/external_function_interface.h" #include "acados_c/ocp_nlp_interface.h" #include "acados/utils/mem.h" #include "acados/utils/print.h" #include "acados/utils/timing.h" #include "acados/utils/types.h" // example specific #include "examples/c/wt_model_nx6/nx6p2/wt_model.h" #include "examples/c/wt_model_nx6/setup.c" #define NN 40 #define MAX_SQP_ITERS 10 #define NREP 1 static void shift_states(ocp_nlp_dims *dims, ocp_nlp_out *out, double *x_end) { int N = dims->N; for (int i = 0; i < N; i++) blasfeo_dveccp(dims->nx[i], &out->ux[i], dims->nu[i], &out->ux[i+1], dims->nu[i+1]); blasfeo_pack_dvec(dims->nx[N], x_end, 1, &out->ux[N], dims->nu[N]); } static void shift_controls(ocp_nlp_dims *dims, ocp_nlp_out *out, double *u_end) { int N = dims->N; for (int i = 0; i < N-1; i++) blasfeo_dveccp(dims->nu[i], &out->ux[i], 0, &out->ux[i+1], 0); blasfeo_pack_dvec(dims->nu[N-1], u_end, 1, &out->ux[N-1], 0); } static void select_dynamics_wt_casadi(int N, external_function_param_casadi *expl_vde_for, external_function_param_casadi *impl_ode_fun, external_function_param_casadi *impl_ode_fun_jac_x_xdot, external_function_param_casadi *impl_ode_jac_x_xdot_u, external_function_param_casadi *impl_ode_fun_jac_x_xdot_u, external_function_param_casadi *phi_fun, external_function_param_casadi *phi_fun_jac_y, external_function_param_casadi *phi_jac_y_uhat, external_function_param_casadi *f_lo_jac_x1_x1dot_u_z) { for (int ii = 0; ii < N; ii++) { expl_vde_for[ii].casadi_fun = &wt_nx6p2_expl_vde_for; expl_vde_for[ii].casadi_work = &wt_nx6p2_expl_vde_for_work; expl_vde_for[ii].casadi_sparsity_in = &wt_nx6p2_expl_vde_for_sparsity_in; expl_vde_for[ii].casadi_sparsity_out = &wt_nx6p2_expl_vde_for_sparsity_out; expl_vde_for[ii].casadi_n_in = &wt_nx6p2_expl_vde_for_n_in; expl_vde_for[ii].casadi_n_out = &wt_nx6p2_expl_vde_for_n_out; impl_ode_fun[ii].casadi_fun = &wt_nx6p2_impl_ode_fun; impl_ode_fun[ii].casadi_work = &wt_nx6p2_impl_ode_fun_work; impl_ode_fun[ii].casadi_sparsity_in = &wt_nx6p2_impl_ode_fun_sparsity_in; impl_ode_fun[ii].casadi_sparsity_out = &wt_nx6p2_impl_ode_fun_sparsity_out; impl_ode_fun[ii].casadi_n_in = &wt_nx6p2_impl_ode_fun_n_in; impl_ode_fun[ii].casadi_n_out = &wt_nx6p2_impl_ode_fun_n_out; impl_ode_fun_jac_x_xdot[ii].casadi_fun = &wt_nx6p2_impl_ode_fun_jac_x_xdot; impl_ode_fun_jac_x_xdot[ii].casadi_work = &wt_nx6p2_impl_ode_fun_jac_x_xdot_work; impl_ode_fun_jac_x_xdot[ii].casadi_sparsity_in = &wt_nx6p2_impl_ode_fun_jac_x_xdot_sparsity_in; impl_ode_fun_jac_x_xdot[ii].casadi_sparsity_out = &wt_nx6p2_impl_ode_fun_jac_x_xdot_sparsity_out; impl_ode_fun_jac_x_xdot[ii].casadi_n_in = &wt_nx6p2_impl_ode_fun_jac_x_xdot_n_in; impl_ode_fun_jac_x_xdot[ii].casadi_n_out = &wt_nx6p2_impl_ode_fun_jac_x_xdot_n_out; impl_ode_jac_x_xdot_u[ii].casadi_fun = &wt_nx6p2_impl_ode_jac_x_xdot_u; impl_ode_jac_x_xdot_u[ii].casadi_work = &wt_nx6p2_impl_ode_jac_x_xdot_u_work; impl_ode_jac_x_xdot_u[ii].casadi_sparsity_in = &wt_nx6p2_impl_ode_jac_x_xdot_u_sparsity_in; impl_ode_jac_x_xdot_u[ii].casadi_sparsity_out = &wt_nx6p2_impl_ode_jac_x_xdot_u_sparsity_out; impl_ode_jac_x_xdot_u[ii].casadi_n_in = &wt_nx6p2_impl_ode_jac_x_xdot_u_n_in; impl_ode_jac_x_xdot_u[ii].casadi_n_out = &wt_nx6p2_impl_ode_jac_x_xdot_u_n_out; impl_ode_fun_jac_x_xdot_u[ii].casadi_fun = &wt_nx6p2_impl_ode_fun_jac_x_xdot_u; impl_ode_fun_jac_x_xdot_u[ii].casadi_work = &wt_nx6p2_impl_ode_fun_jac_x_xdot_u_work; impl_ode_fun_jac_x_xdot_u[ii].casadi_sparsity_in = &wt_nx6p2_impl_ode_fun_jac_x_xdot_u_sparsity_in; impl_ode_fun_jac_x_xdot_u[ii].casadi_sparsity_out = &wt_nx6p2_impl_ode_fun_jac_x_xdot_u_sparsity_out; impl_ode_fun_jac_x_xdot_u[ii].casadi_n_in = &wt_nx6p2_impl_ode_fun_jac_x_xdot_u_n_in; impl_ode_fun_jac_x_xdot_u[ii].casadi_n_out = &wt_nx6p2_impl_ode_fun_jac_x_xdot_u_n_out; // GNSF functions // phi_fun phi_fun[ii].casadi_fun = &wt_nx6p2_phi_fun; phi_fun[ii].casadi_work = &wt_nx6p2_phi_fun_work; phi_fun[ii].casadi_sparsity_in = &wt_nx6p2_phi_fun_sparsity_in; phi_fun[ii].casadi_sparsity_out = &wt_nx6p2_phi_fun_sparsity_out; phi_fun[ii].casadi_n_in = &wt_nx6p2_phi_fun_n_in; phi_fun[ii].casadi_n_out = &wt_nx6p2_phi_fun_n_out; phi_fun_jac_y[ii].casadi_fun = &wt_nx6p2_phi_fun_jac_y; phi_fun_jac_y[ii].casadi_work = &wt_nx6p2_phi_fun_jac_y_work; phi_fun_jac_y[ii].casadi_sparsity_in = &wt_nx6p2_phi_fun_jac_y_sparsity_in; phi_fun_jac_y[ii].casadi_sparsity_out = &wt_nx6p2_phi_fun_jac_y_sparsity_out; phi_fun_jac_y[ii].casadi_n_in = &wt_nx6p2_phi_fun_jac_y_n_in; phi_fun_jac_y[ii].casadi_n_out = &wt_nx6p2_phi_fun_jac_y_n_out; phi_jac_y_uhat[ii].casadi_fun = &wt_nx6p2_phi_jac_y_uhat; phi_jac_y_uhat[ii].casadi_work = &wt_nx6p2_phi_jac_y_uhat_work; phi_jac_y_uhat[ii].casadi_sparsity_in = &wt_nx6p2_phi_jac_y_uhat_sparsity_in; phi_jac_y_uhat[ii].casadi_sparsity_out = &wt_nx6p2_phi_jac_y_uhat_sparsity_out; phi_jac_y_uhat[ii].casadi_n_in = &wt_nx6p2_phi_jac_y_uhat_n_in; phi_jac_y_uhat[ii].casadi_n_out = &wt_nx6p2_phi_jac_y_uhat_n_out; // f_lo - linear output function f_lo_jac_x1_x1dot_u_z[ii].casadi_fun = &wt_nx6p2_f_lo_fun_jac_x1k1uz; f_lo_jac_x1_x1dot_u_z[ii].casadi_work = &wt_nx6p2_f_lo_fun_jac_x1k1uz_work; f_lo_jac_x1_x1dot_u_z[ii].casadi_sparsity_in = &wt_nx6p2_f_lo_fun_jac_x1k1uz_sparsity_in; f_lo_jac_x1_x1dot_u_z[ii].casadi_sparsity_out = &wt_nx6p2_f_lo_fun_jac_x1k1uz_sparsity_out; f_lo_jac_x1_x1dot_u_z[ii].casadi_n_in = &wt_nx6p2_f_lo_fun_jac_x1k1uz_n_in; f_lo_jac_x1_x1dot_u_z[ii].casadi_n_out = &wt_nx6p2_f_lo_fun_jac_x1k1uz_n_out; } } /************************************************ * nonlinear constraint ************************************************/ void ext_fun_h1(void *fun, ext_fun_arg_t *type_in, void **in, ext_fun_arg_t *type_out, void **out) { int nu = 2; int nx = 8; int nh = 1; // scaling double alpha = 0.944*97/100; // ux // struct blasfeo_dvec *ux = in[0]; struct blasfeo_dvec_args *x_args = in[0]; // struct blasfeo_dvec_args *u_args = in[1]; struct blasfeo_dvec *x = x_args->x; // struct blasfeo_dvec *u = u_args->x; int x_offset = x_args->xi; // int u_offset = u_args->xi; // h struct blasfeo_dvec_args *h_args = out[0]; struct blasfeo_dvec *h = h_args->x; int xi = h_args->xi; BLASFEO_DVECEL(h, xi) = alpha * BLASFEO_DVECEL(x, x_offset) * BLASFEO_DVECEL(x, x_offset+5); // jac struct blasfeo_dmat_args *jac_args = out[1]; struct blasfeo_dmat *jac = jac_args->A; int ai = jac_args->ai; int aj = jac_args->aj; blasfeo_dgese(nu+nx, nh, 0.0, jac, ai, aj); BLASFEO_DMATEL(jac, ai+nu+0, aj) = alpha * BLASFEO_DVECEL(x, x_offset+5); BLASFEO_DMATEL(jac, ai+nu+5, aj) = alpha * BLASFEO_DVECEL(x, x_offset+0); return; } /************************************************ * main ************************************************/ int main() { // _MM_SET_EXCEPTION_MASK(_MM_GET_EXCEPTION_MASK() & ~_MM_MASK_INVALID); int nx_ = 8; int nu_ = 2; int ny_ = 4; int np = 1; // number of local parametrs for each dynamics model function /************************************************ * problem dimensions ************************************************/ // optimization variables int nx[NN+1] = {}; // states int nu[NN+1] = {}; // inputs int nz[NN+1] = {}; // algebraic variables int ns[NN+1] = {}; // slacks // cost int ny[NN+1] = {}; // measurements // constraints int nbx[NN+1] = {}; // state bounds int nbu[NN+1] = {}; // input bounds int ng[NN+1] = {}; // general linear constraints int nh[NN+1] = {}; // nonlinear constraints int nsh[NN+1] = {}; // softed nonlinear constraints // TODO(dimitris): setup bounds on states and controls based on ACADO controller nx[0] = nx_; nu[0] = nu_; nbx[0] = nx_; nbu[0] = nu_; ng[0] = 0; // TODO(dimitris): add bilinear constraints later nh[0] = 0; nsh[0] = 0; ns[0] = nsh[0]; ny[0] = 4; nz[0] = 0; for (int i = 1; i < NN; i++) { nx[i] = nx_; nu[i] = nu_; nbx[i] = 3; nbu[i] = nu_; ng[i] = 0; nh[i] = 1; nsh[i] = 1; ns[i] = nsh[i]; ny[i] = 4; nz[i] = 0; } nx[NN] = nx_; nu[NN] = 0; nbx[NN] = 3; nbu[NN] = 0; ng[NN] = 0; nh[NN] = 0; nsh[NN] = 0; ns[NN] = nsh[NN]; ny[NN] = 2; nz[NN] = 0; /************************************************ * problem data ************************************************/ double *x_end = malloc(sizeof(double)*nx_); double *u_end = malloc(sizeof(double)*nu_); // value of last stage when shifting states and controls for (int i = 0; i < nx_; i++) x_end[i] = 0.0; for (int i = 0; i < nu_; i++) u_end[i] = 0.0; /* constraints */ // pitch angle rate double dbeta_min = - 8.0; double dbeta_max = 8.0; // generator torque double dM_gen_min = - 1.0; double dM_gen_max = 1.0; // generator angular velocity double OmegaR_min = 6.0/60*2*3.14159265359; double OmegaR_max = 13.0/60*2*3.14159265359; // pitch angle double beta_min = 0.0; double beta_max = 35.0; // generator torque double M_gen_min = 0.0; double M_gen_max = 5.0; // electric power double Pel_min = 0.0; double Pel_max = 5.0; /* soft constraints */ // middle stage int *idxsh1 = malloc(nsh[1]*sizeof(int)); double *lsh1 = malloc((nsh[1])*sizeof(double)); double *ush1 = malloc((nsh[1])*sizeof(double)); /* box constraints */ // acados inf double acados_inf = 1e8; // first stage // input bounds int *idxbu0 = malloc(nbu[0]*sizeof(int)); double *lbu0 = malloc((nbu[0])*sizeof(double)); double *ubu0 = malloc((nbu[0])*sizeof(double)); // pitch angle rate idxbu0[0] = 0; lbu0[0] = dbeta_min; ubu0[0] = dbeta_max; // generator torque idxbu0[1] = 1; lbu0[1] = dM_gen_min; ubu0[1] = dM_gen_max; // state bounds int *idxbx0 = malloc(nbx[0]*sizeof(int)); double *lbx0 = malloc((nbx[0])*sizeof(double)); double *ubx0 = malloc((nbx[0])*sizeof(double)); // dummy for (int ii=0; ii<nbx[0]; ii++) { idxbx0[ii] = ii; lbx0[ii] = - acados_inf; ubx0[ii] = acados_inf; } // middle stages // input bounds int *idxbu1 = malloc(nbu[1]*sizeof(int)); double *lbu1 = malloc((nbu[1])*sizeof(double)); double *ubu1 = malloc((nbu[1])*sizeof(double)); // pitch angle rate idxbu1[0] = 0; lbu1[0] = dbeta_min; ubu1[0] = dbeta_max; // generator torque rate idxbu1[1] = 1; lbu1[1] = dM_gen_min; ubu1[1] = dM_gen_max; // state bounds int *idxbx1 = malloc(nbx[1]*sizeof(int)); double *lbx1 = malloc((nbx[1])*sizeof(double)); double *ubx1 = malloc((nbx[1])*sizeof(double)); // generator angular velocity idxbx1[0] = 0; lbx1[0] = OmegaR_min; ubx1[0] = OmegaR_max; // pitch angle idxbx1[1] = 6; lbx1[1] = beta_min; ubx1[1] = beta_max; // generator torque idxbx1[2] = 7; lbx1[2] = M_gen_min; ubx1[2] = M_gen_max; // last stage // state bounds int *idxbxN = malloc(nbx[NN]*sizeof(int)); double *lbxN = malloc((nbx[NN])*sizeof(double)); double *ubxN = malloc((nbx[NN])*sizeof(double)); // generator angular velocity idxbxN[0] = 0; lbxN[0] = OmegaR_min; ubxN[0] = OmegaR_max; // pitch angle idxbxN[1] = 6; lbxN[1] = beta_min; ubxN[1] = beta_max; // generator torque idxbxN[2] = 7; lbxN[2] = M_gen_min; ubxN[2] = M_gen_max; // to shift double *specific_u = malloc(nu_*sizeof(double)); double *specific_x = malloc(nx_*sizeof(double)); #if 0 int_print_mat(1, nb[0], idxb0, 1); d_print_mat(1, nb[0], lb0, 1); d_print_mat(1, nb[0], ub0, 1); int_print_mat(1, nb[1], idxb1, 1); d_print_mat(1, nb[1], lb1, 1); d_print_mat(1, nb[1], ub1, 1); int_print_mat(1, nb[NN], idxbN, 1); d_print_mat(1, nb[NN], lbN, 1); d_print_mat(1, nb[NN], ubN, 1); exit(1); #endif /* nonlinear constraints */ // middle stages external_function_generic h1; double *lh1; double *uh1; lh1 = malloc((nh[1])*sizeof(double)); uh1 = malloc((nh[1])*sizeof(double)); if (nh[1]>0) { h1.evaluate = &ext_fun_h1; // electric power lh1[0] = Pel_min; uh1[0] = Pel_max; } // softed if (nsh[1]>0) { idxsh1[0] = 0; lsh1[0] = 0.0; ush1[0] = 0.0; } /* linear least squares */ // output definition // y = {x[0], x[4]; u[0]; u[1]; u[2]}; // = Vx * x + Vu * u double *Vx = malloc((ny_*nx_)*sizeof(double)); for (int ii=0; ii<ny_*nx_; ii++) Vx[ii] = 0.0; Vx[0+ny_*0] = 1.0; Vx[1+ny_*4] = 1.0; double *Vu = malloc((ny_*nu_)*sizeof(double)); for (int ii=0; ii<ny_*nu_; ii++) Vu[ii] = 0.0; Vu[2+ny_*0] = 1.0; Vu[3+ny_*1] = 1.0; double *VxN = malloc((ny[NN]*nx[NN])*sizeof(double)); for (int ii=0; ii<ny[NN]*nx[NN]; ii++) VxN[ii] = 0.0; VxN[0+ny[NN]*0] = 1.0; VxN[1+ny[NN]*4] = 1.0; double *W = malloc((ny_*ny_)*sizeof(double)); for (int ii=0; ii<ny_*ny_; ii++) W[ii] = 0.0; W[0+ny_*0] = 1.5114; W[1+ny_*0] = -0.0649; W[0+ny_*1] = -0.0649; W[1+ny_*1] = 0.0180; W[2+ny_*2] = 0.01; W[3+ny_*3] = 0.001; double *W_N = malloc((ny[NN]*ny[NN])*sizeof(double)); W_N[0+ny[NN]*0] = 1.5114; W_N[1+ny[NN]*0] = -0.0649; W_N[0+ny[NN]*1] = -0.0649; W_N[1+ny[NN]*1] = 0.0180; /* slacks */ // first stage double *lZ0 = malloc(ns[0]*sizeof(double)); double *uZ0 = malloc(ns[0]*sizeof(double)); double *lz0 = malloc(ns[0]*sizeof(double)); double *uz0 = malloc(ns[0]*sizeof(double)); // middle stages double *lZ1 = malloc(ns[1]*sizeof(double)); double *uZ1 = malloc(ns[1]*sizeof(double)); double *lz1 = malloc(ns[1]*sizeof(double)); double *uz1 = malloc(ns[1]*sizeof(double)); lZ1[0] = 1e2; uZ1[0] = 1e2; lz1[0] = 0e1; uz1[0] = 0e1; // final stage double *lZN = malloc(ns[NN]*sizeof(double)); double *uZN = malloc(ns[NN]*sizeof(double)); double *lzN = malloc(ns[NN]*sizeof(double)); double *uzN = malloc(ns[NN]*sizeof(double)); #if 0 d_print_mat(ny_, nx_, Vx, ny_); d_print_mat(ny_, nu_, Vu, ny_); d_print_mat(ny_, ny_, W, ny_); // exit(1); #endif /************************************************ * plan + config ************************************************/ ocp_nlp_plan_t *plan = ocp_nlp_plan_create(NN); plan->nlp_solver = SQP; // plan->nlp_solver = SQP_RTI; for (int i = 0; i <= NN; i++) plan->nlp_cost[i] = LINEAR_LS; plan->ocp_qp_solver_plan.qp_solver = PARTIAL_CONDENSING_HPIPM; // plan->ocp_qp_solver_plan.qp_solver = FULL_CONDENSING_HPIPM; // plan->ocp_qp_solver_plan.qp_solver = FULL_CONDENSING_QPOASES; // plan->ocp_qp_solver_plan.qp_solver = FULL_CONDENSING_QORE; for (int i = 0; i < NN; i++) { plan->nlp_dynamics[i] = CONTINUOUS_MODEL; // plan->sim_solver_plan[i].sim_solver = ERK; // plan->sim_solver_plan[i].sim_solver = IRK; // plan->sim_solver_plan[i].sim_solver = LIFTED_IRK; plan->sim_solver_plan[i].sim_solver = GNSF; } for (int i = 0; i <= NN; i++) plan->nlp_constraints[i] = BGH; ocp_nlp_config *config = ocp_nlp_config_create(*plan); /************************************************ * ocp_nlp_dims ************************************************/ ocp_nlp_dims *dims = ocp_nlp_dims_create(config); ocp_nlp_dims_set_opt_vars(config, dims, "nx", nx); ocp_nlp_dims_set_opt_vars(config, dims, "nu", nu); ocp_nlp_dims_set_opt_vars(config, dims, "nz", nz); ocp_nlp_dims_set_opt_vars(config, dims, "ns", ns); for (int i = 0; i <= NN; i++) { ocp_nlp_dims_set_cost(config, dims, i, "ny", &ny[i]); ocp_nlp_dims_set_constraints(config, dims, i, "nbx", &nbx[i]); ocp_nlp_dims_set_constraints(config, dims, i, "nbu", &nbu[i]); ocp_nlp_dims_set_constraints(config, dims, i, "ng", &ng[i]); ocp_nlp_dims_set_constraints(config, dims, i, "nh", &nh[i]); ocp_nlp_dims_set_constraints(config, dims, i, "nsh", &nsh[i]); } /************************************************ * dynamics ************************************************/ // explicit model external_function_param_casadi *expl_vde_for = malloc(NN*sizeof(external_function_param_casadi)); // implicit model external_function_param_casadi *impl_ode_fun = malloc(NN*sizeof(external_function_param_casadi)); external_function_param_casadi *impl_ode_fun_jac_x_xdot = malloc(NN*sizeof(external_function_param_casadi)); external_function_param_casadi *impl_ode_jac_x_xdot_u = malloc(NN*sizeof(external_function_param_casadi)); external_function_param_casadi *impl_ode_fun_jac_x_xdot_u = malloc(NN*sizeof(external_function_param_casadi)); // gnsf model external_function_param_casadi *phi_fun = malloc(NN*sizeof(external_function_param_casadi)); external_function_param_casadi *phi_fun_jac_y = malloc(NN*sizeof(external_function_param_casadi)); external_function_param_casadi *phi_jac_y_uhat = malloc(NN*sizeof(external_function_param_casadi)); external_function_param_casadi *f_lo_jac_x1_x1dot_u_z = malloc(NN*sizeof(external_function_param_casadi)); select_dynamics_wt_casadi(NN, expl_vde_for, impl_ode_fun, impl_ode_fun_jac_x_xdot, impl_ode_jac_x_xdot_u, impl_ode_fun_jac_x_xdot_u, phi_fun, phi_fun_jac_y, phi_jac_y_uhat, f_lo_jac_x1_x1dot_u_z); // explicit model external_function_param_casadi_create_array(NN, expl_vde_for, np); // implicit model external_function_param_casadi_create_array(NN, impl_ode_fun, np); external_function_param_casadi_create_array(NN, impl_ode_fun_jac_x_xdot, np); external_function_param_casadi_create_array(NN, impl_ode_jac_x_xdot_u, np); external_function_param_casadi_create_array(NN, impl_ode_fun_jac_x_xdot_u, np); // gnsf model external_function_param_casadi_create_array(NN, phi_fun, np); external_function_param_casadi_create_array(NN, phi_fun_jac_y, np); external_function_param_casadi_create_array(NN, phi_jac_y_uhat, np); external_function_param_casadi_create_array(NN, f_lo_jac_x1_x1dot_u_z, np); // GNSF import matrices function external_function_casadi get_matrices_fun; get_matrices_fun.casadi_fun = &wt_nx6p2_get_matrices_fun; get_matrices_fun.casadi_work = &wt_nx6p2_get_matrices_fun_work; get_matrices_fun.casadi_sparsity_in = &wt_nx6p2_get_matrices_fun_sparsity_in; get_matrices_fun.casadi_sparsity_out = &wt_nx6p2_get_matrices_fun_sparsity_out; get_matrices_fun.casadi_n_in = &wt_nx6p2_get_matrices_fun_n_in; get_matrices_fun.casadi_n_out = &wt_nx6p2_get_matrices_fun_n_out; external_function_casadi_create(&get_matrices_fun); // external_function_generic *get_model_matrices = (external_function_generic *) &get_matrices_fun; /* initialize additional gnsf dimensions */ int gnsf_nx1 = 8; int gnsf_nz1 = 0; int gnsf_nout = 1; int gnsf_ny = 5; int gnsf_nuhat = 0; for (int i = 0; i < NN; i++) { if (plan->sim_solver_plan[i].sim_solver == GNSF) { ocp_nlp_dims_set_dynamics(config, dims, i, "gnsf_nx1", &gnsf_nx1); ocp_nlp_dims_set_dynamics(config, dims, i, "gnsf_nz1", &gnsf_nz1); ocp_nlp_dims_set_dynamics(config, dims, i, "gnsf_nout", &gnsf_nout); ocp_nlp_dims_set_dynamics(config, dims, i, "gnsf_ny", &gnsf_ny); ocp_nlp_dims_set_dynamics(config, dims, i, "gnsf_nuhat", &gnsf_nuhat); } } /************************************************ * nlp_in ************************************************/ ocp_nlp_in *nlp_in = ocp_nlp_in_create(config, dims); // sampling times for (int ii=0; ii<NN; ii++) { nlp_in->Ts[ii] = 0.2; } // output definition: y = [x; u] /* cost */ // linear ls int status = ACADOS_SUCCESS; for (int i = 0; i <= NN; i++) { // Cyt ocp_nlp_cost_model_set(config, dims, nlp_in, i, "Vu", Vu); if (i < NN) ocp_nlp_cost_model_set(config, dims, nlp_in, i, "Vx", Vx); else ocp_nlp_cost_model_set(config, dims, nlp_in, i, "Vx", VxN); // printf("setted Cyt x=\n"); // blasfeo_print_dmat(nx[i]+ nu[i], ny[i], &cost[i]->Cyt,0, 0); // W ocp_nlp_cost_model_set(config, dims, nlp_in, i, "W", W); } status = ocp_nlp_cost_model_set(config, dims, nlp_in, NN, "W", W_N); // slacks (middle stages) for (int ii=1; ii<NN; ii++) { ocp_nlp_cost_model_set(config, dims, nlp_in, ii, "Zl", lZ1); ocp_nlp_cost_model_set(config, dims, nlp_in, ii, "Zu", uZ1); ocp_nlp_cost_model_set(config, dims, nlp_in, ii, "zl", lz1); ocp_nlp_cost_model_set(config, dims, nlp_in, ii, "zu", uz1); } /* dynamics */ int set_fun_status; for (int i=0; i<NN; i++) { if (plan->sim_solver_plan[i].sim_solver == ERK) { set_fun_status = ocp_nlp_dynamics_model_set(config, dims, nlp_in, i, "expl_vde_for", &expl_vde_for[i]); if (set_fun_status != 0) exit(1); } else if (plan->sim_solver_plan[i].sim_solver == IRK) { set_fun_status = ocp_nlp_dynamics_model_set(config, dims, nlp_in, i, "impl_ode_fun", &impl_ode_fun[i]); if (set_fun_status != 0) exit(1); set_fun_status = ocp_nlp_dynamics_model_set(config, dims, nlp_in, i, "impl_ode_fun_jac_x_xdot", &impl_ode_fun_jac_x_xdot[i]); if (set_fun_status != 0) exit(1); set_fun_status = ocp_nlp_dynamics_model_set(config, dims, nlp_in, i, "impl_ode_jac_x_xdot_u", &impl_ode_jac_x_xdot_u[i]); if (set_fun_status != 0) exit(1); } else if (plan->sim_solver_plan[i].sim_solver == GNSF) { set_fun_status = ocp_nlp_dynamics_model_set(config, dims, nlp_in, i, "phi_fun", &phi_fun[i]); if (set_fun_status != 0) exit(1); set_fun_status = ocp_nlp_dynamics_model_set(config, dims, nlp_in, i, "phi_fun_jac_y", &phi_fun_jac_y[i]); if (set_fun_status != 0) exit(1); set_fun_status = ocp_nlp_dynamics_model_set(config, dims, nlp_in, i, "phi_jac_y_uhat", &phi_jac_y_uhat[i]); if (set_fun_status != 0) exit(1); set_fun_status = ocp_nlp_dynamics_model_set(config, dims, nlp_in, i, "f_lo_jac_x1_x1dot_u_z", &f_lo_jac_x1_x1dot_u_z[i]); if (set_fun_status != 0) exit(1); set_fun_status = ocp_nlp_dynamics_model_set(config, dims, nlp_in, i, "get_gnsf_matrices", &get_matrices_fun); if (set_fun_status != 0) exit(1); } else if (plan->sim_solver_plan[i].sim_solver == LIFTED_IRK) { set_fun_status = ocp_nlp_dynamics_model_set(config, dims, nlp_in, i, "impl_ode_fun", &impl_ode_fun[i]); if (set_fun_status != 0) exit(1); set_fun_status = ocp_nlp_dynamics_model_set(config, dims, nlp_in, i, "impl_ode_fun_jac_x_xdot_u", &impl_ode_fun_jac_x_xdot_u[i]); if (set_fun_status != 0) exit(1); } else { printf("\nWrong sim name\n\n"); exit(1); } } /* constraints */ /* box constraints */ // fist stage ocp_nlp_constraints_model_set(config, dims, nlp_in, 0, "idxbu", idxbu0); ocp_nlp_constraints_model_set(config, dims, nlp_in, 0, "lbu", lbu0); ocp_nlp_constraints_model_set(config, dims, nlp_in, 0, "ubu", ubu0); ocp_nlp_constraints_model_set(config, dims, nlp_in, 0, "idxbx", idxbx0); ocp_nlp_constraints_model_set(config, dims, nlp_in, 0, "lbx", lbx0); ocp_nlp_constraints_model_set(config, dims, nlp_in, 0, "ubx", ubx0); // middle stages for (int i = 1; i < NN; i++) { ocp_nlp_constraints_model_set(config, dims, nlp_in, i, "idxbu", idxbu1); ocp_nlp_constraints_model_set(config, dims, nlp_in, i, "lbu", lbu1); ocp_nlp_constraints_model_set(config, dims, nlp_in, i, "ubu", ubu1); ocp_nlp_constraints_model_set(config, dims, nlp_in, i, "idxbx", idxbx1); ocp_nlp_constraints_model_set(config, dims, nlp_in, i, "lbx", lbx1); ocp_nlp_constraints_model_set(config, dims, nlp_in, i, "ubx", ubx1); } // last stage ocp_nlp_constraints_model_set(config, dims, nlp_in, NN, "idxbx", idxbxN); ocp_nlp_constraints_model_set(config, dims, nlp_in, NN, "lbx", lbxN); ocp_nlp_constraints_model_set(config, dims, nlp_in, NN, "ubx", ubxN); /* nonlinear constraints */ // middle stages for (int i = 1; i < NN; i++) { if(nh[i]>0) { ocp_nlp_constraints_model_set(config, dims, nlp_in, i, "lh", lh1); ocp_nlp_constraints_model_set(config, dims, nlp_in, i, "uh", uh1); ocp_nlp_constraints_model_set(config, dims, nlp_in, i, "nl_constr_h_fun_jac", &h1); } } /* soft constraints */ // middle stages for (int i = 1; i < NN; i++) { if (ns[i]>0) { ocp_nlp_constraints_model_set(config, dims, nlp_in, i, "lsh", lsh1); ocp_nlp_constraints_model_set(config, dims, nlp_in, i, "ush", ush1); ocp_nlp_constraints_model_set(config, dims, nlp_in, i, "idxsh", idxsh1); } } /************************************************ * sqp opts ************************************************/ // create opts void *nlp_opts = ocp_nlp_solver_opts_create(config, dims); // nlp opts if (plan->nlp_solver == SQP) { int max_iter = MAX_SQP_ITERS; double tol_stat = 1e-6; double tol_eq = 1e-8; double tol_ineq = 1e-8; double tol_comp = 1e-8; ocp_nlp_solver_opts_set(config, nlp_opts, "max_iter", &max_iter); ocp_nlp_solver_opts_set(config, nlp_opts, "tol_stat", &tol_stat); ocp_nlp_solver_opts_set(config, nlp_opts, "tol_eq", &tol_eq); ocp_nlp_solver_opts_set(config, nlp_opts, "tol_ineq", &tol_ineq); ocp_nlp_solver_opts_set(config, nlp_opts, "tol_comp", &tol_comp); } else if (plan->nlp_solver == SQP_RTI) { // ocp_nlp_sqp_rti_opts *sqp_rti_opts = nlp_opts; // for (int i = 0; i < NN; ++i) // { // ocp_nlp_dynamics_cont_opts *dynamics_stage_opts = sqp_rti_opts->dynamics[i]; // dynamics_stage_opts->compute_adj = 0; // } // for (int i = 0; i < NN; ++i) // { // if (plan->nlp_constraints[i] == BGH) // { // ocp_nlp_constraints_bgh_opts *constr_stage_opts = sqp_rti_opts->constraints[i]; // constr_stage_opts->compute_adj = 0; // } // } } // sim opts for (int i = 0; i < NN; ++i) { if (plan->sim_solver_plan[i].sim_solver == ERK) { int ns = 4; int num_steps = 10; ocp_nlp_solver_opts_set_at_stage(config, nlp_opts, i, "dynamics_num_steps", &num_steps); ocp_nlp_solver_opts_set_at_stage(config, nlp_opts, i, "dynamics_ns", &ns); } else if (plan->sim_solver_plan[i].sim_solver == IRK) { int num_steps = 1; int ns = 4; bool jac_reuse = true; ocp_nlp_solver_opts_set_at_stage(config, nlp_opts, i, "dynamics_num_steps", &num_steps); ocp_nlp_solver_opts_set_at_stage(config, nlp_opts, i, "dynamics_ns", &ns); ocp_nlp_solver_opts_set_at_stage(config, nlp_opts, i, "dynamics_jac_reuse", &jac_reuse); } else if (plan->sim_solver_plan[i].sim_solver == LIFTED_IRK) { int num_steps = 1; int ns = 4; ocp_nlp_solver_opts_set_at_stage(config, nlp_opts, i, "dynamics_num_steps", &num_steps); ocp_nlp_solver_opts_set_at_stage(config, nlp_opts, i, "dynamics_ns", &ns); } else if (plan->sim_solver_plan[i].sim_solver == GNSF) { int num_steps = 1; int ns = 4; int newton_iter = 1; bool jac_reuse = true; ocp_nlp_solver_opts_set_at_stage(config, nlp_opts, i, "dynamics_num_steps", &num_steps); ocp_nlp_solver_opts_set_at_stage(config, nlp_opts, i, "dynamics_ns", &ns); ocp_nlp_solver_opts_set_at_stage(config, nlp_opts, i, "dynamics_jac_reuse", &jac_reuse); ocp_nlp_solver_opts_set_at_stage(config, nlp_opts, i, "dynamics_newton_iter", &newton_iter); } } // partial condensing opts if (plan->ocp_qp_solver_plan.qp_solver == PARTIAL_CONDENSING_HPIPM) { int cond_N = 5; ocp_nlp_solver_opts_set(config, nlp_opts, "qp_cond_N", &cond_N); } // update opts after manual changes ocp_nlp_solver_opts_update(config, dims, nlp_opts); /************************************************ * ocp_nlp_out & solver ************************************************/ ocp_nlp_out *nlp_out = ocp_nlp_out_create(config, dims); ocp_nlp_out *sens_nlp_out = ocp_nlp_out_create(config, dims); ocp_nlp_solver *solver = ocp_nlp_solver_create(config, dims, nlp_opts); /************************************************ * precomputation (after all options are set) ************************************************/ status = ocp_nlp_precompute(solver, nlp_in, nlp_out); /************************************************ * sqp solve ************************************************/ int n_sim = 40; double *x_sim = malloc(nx_*(n_sim+1)*sizeof(double)); double *u_sim = malloc(nu_*(n_sim+0)*sizeof(double)); acados_timer timer; acados_tic(&timer); for (int rep = 0; rep < NREP; rep++) { // warm start output initial guess of solution for (int i=0; i<=NN; i++) { blasfeo_pack_dvec(2, u0_ref, 1, nlp_out->ux+i, 0); // blasfeo_pack_dvec(1, wind0_ref+i, 1, nlp_out->ux+i, 2); blasfeo_pack_dvec(nx[i], x0_ref, 1, nlp_out->ux+i, nu[i]); } // set x0 as box constraint ocp_nlp_constraints_model_set(config, dims, nlp_in, 0, "lbx", x0_ref); ocp_nlp_constraints_model_set(config, dims, nlp_in, 0, "ubx", x0_ref); // store x0 for(int ii=0; ii<nx_; ii++) x_sim[ii] = x0_ref[ii]; for (int idx = 0; idx < n_sim; idx++) { // update wind distrurbance as external function parameter for (int ii=0; ii<NN; ii++) { if (plan->sim_solver_plan[ii].sim_solver == ERK) { expl_vde_for[ii].set_param(expl_vde_for+ii, wind0_ref+idx+ii); } else if (plan->sim_solver_plan[ii].sim_solver == IRK || plan->sim_solver_plan[ii].sim_solver == LIFTED_IRK) { impl_ode_fun[ii].set_param(impl_ode_fun+ii, wind0_ref+idx+ii); impl_ode_fun_jac_x_xdot[ii].set_param(impl_ode_fun_jac_x_xdot+ii, wind0_ref+idx+ii); impl_ode_jac_x_xdot_u[ii].set_param(impl_ode_jac_x_xdot_u+ii, wind0_ref+idx+ii); impl_ode_fun_jac_x_xdot_u[ii].set_param(impl_ode_fun_jac_x_xdot_u+ii, wind0_ref+idx+ii); } else if (plan->sim_solver_plan[ii].sim_solver == GNSF) { phi_fun[ii].set_param(phi_fun+ii, wind0_ref+idx+ii); phi_fun_jac_y[ii].set_param(phi_fun_jac_y+ii, wind0_ref+idx+ii); phi_jac_y_uhat[ii].set_param(phi_jac_y_uhat+ii, wind0_ref+idx+ii); f_lo_jac_x1_x1dot_u_z[ii].set_param(f_lo_jac_x1_x1dot_u_z+ii, wind0_ref+idx+ii); } else { printf("\nWrong sim name\n\n"); exit(1); } } // update reference for (int i = 0; i <= NN; i++) { ocp_nlp_cost_model_set(config, dims, nlp_in, i, "yref", &y_ref[(idx + i)*4]); } // solve NLP status = ocp_nlp_solve(solver, nlp_in, nlp_out); // evaluate parametric sensitivity of solution // ocp_nlp_out_print(dims, nlp_out); ocp_nlp_eval_param_sens(solver, "ex", 0, 0, sens_nlp_out); // ocp_nlp_out_print(dims, nlp_out); // update initial condition // TODO(dimitris): maybe simulate system instead of passing x[1] as next state ocp_nlp_out_get(config, dims, nlp_out, 1, "x", specific_x); ocp_nlp_constraints_model_set(config, dims, nlp_in, 0, "lbx", specific_x); ocp_nlp_constraints_model_set(config, dims, nlp_in, 0, "ubx", specific_x); // store trajectory ocp_nlp_out_get(config, dims, nlp_out, 1, "x", x_sim+(idx+1)*nx_); ocp_nlp_out_get(config, dims, nlp_out, 0, "u", u_sim+idx*nu_); // print info if (true) { int sqp_iter; double time_lin, time_qp_sol, time_tot; ocp_nlp_get(config, solver, "sqp_iter", &sqp_iter); ocp_nlp_get(config, solver, "time_tot", &time_tot); ocp_nlp_get(config, solver, "time_qp_sol", &time_qp_sol); ocp_nlp_get(config, solver, "time_lin", &time_lin); printf("\nproblem #%d, status %d, iters %d, time (total %f, lin %f, qp_sol %f) ms\n", idx, status, sqp_iter, time_tot*1e3, time_lin*1e3, time_qp_sol*1e3); printf("xsim = \n"); ocp_nlp_out_get(config, dims, nlp_out, 0, "x", x_end); d_print_mat(1, nx[0], x_end, 1); printf("electrical power = %f\n", 0.944*97/100* x_end[0] * x_end[5]); } if (status!=0) { if (plan->nlp_solver == SQP) // RTI has no residual { ocp_nlp_res *residual; ocp_nlp_get(config, solver, "nlp_res", &residual); printf("\nresiduals\n"); ocp_nlp_res_print(dims, residual); exit(1); } } // shift trajectories if (true) { ocp_nlp_out_get(config, dims, nlp_out, NN-1, "u", u_end); ocp_nlp_out_get(config, dims, nlp_out, NN-1, "x", x_end); shift_states(dims, nlp_out, x_end); shift_controls(dims, nlp_out, u_end); } } } double time = acados_toc(&timer)/NREP; printf("\n\ntotal time (including printing) = %f ms (time per SQP = %f)\n\n", time*1e3, time*1e3/n_sim); #if 0 d_print_mat(nx_, n_sim+1, x_sim, nx_); d_print_mat(nu_, n_sim, u_sim, nu_); #endif /************************************************ * free memory ************************************************/ external_function_casadi_free(&get_matrices_fun); external_function_param_casadi_free(expl_vde_for); external_function_param_casadi_free(impl_ode_fun); external_function_param_casadi_free(impl_ode_fun_jac_x_xdot); external_function_param_casadi_free(impl_ode_jac_x_xdot_u); external_function_param_casadi_free(impl_ode_fun_jac_x_xdot_u); external_function_param_casadi_free(phi_fun); external_function_param_casadi_free(phi_fun_jac_y); external_function_param_casadi_free(phi_jac_y_uhat); external_function_param_casadi_free(f_lo_jac_x1_x1dot_u_z); free(expl_vde_for); free(impl_ode_fun); free(impl_ode_fun_jac_x_xdot); free(impl_ode_jac_x_xdot_u); free(impl_ode_fun_jac_x_xdot_u); free(phi_fun); free(phi_fun_jac_y); free(phi_jac_y_uhat); free(f_lo_jac_x1_x1dot_u_z); ocp_nlp_solver_opts_destroy(nlp_opts); ocp_nlp_in_destroy(nlp_in); ocp_nlp_out_destroy(nlp_out); ocp_nlp_out_destroy(sens_nlp_out); ocp_nlp_solver_destroy(solver); ocp_nlp_dims_destroy(dims); ocp_nlp_config_destroy(config); ocp_nlp_plan_destroy(plan); free(specific_x); free(specific_u); free(x_sim); free(u_sim); free(lZ0); free(uZ0); free(lz0); free(uz0); free(lZ1); free(uZ1); free(lz1); free(uz1); free(lZN); free(uZN); free(lzN); free(uzN); free(W_N); free(W); free(VxN); free(Vx); free(Vu); free(lh1); free(uh1); free(idxbu0); free(lbu0); free(ubu0); free(idxbx0); free(lbx0); free(ubx0); free(idxbx1); free(lbu1); free(ubu1); free(idxbu1); free(lbx1); free(ubx1); free(idxbxN); free(lbxN); free(ubxN); free(idxsh1); free(lsh1); free(ush1); free(x_end); free(u_end); /************************************************ * return ************************************************/ if (status == 0 || (status == 1 && MAX_SQP_ITERS == 1)) printf("\nsuccess!\n\n"); else printf("\nfailure!\n\n"); return 0; }
128fcc372dec392ca2c5b6fd6399a697896e8b2a
4cd1ef1ad1f6c0b4200554459d24ee2ce43467f6
/src/rt/bigint/bigint.h
b4c48f0376c9fbfd99228ee53a91b96767ab38c2
[ "LicenseRef-scancode-unknown-license-reference", "bzip2-1.0.6", "BSD-1-Clause", "LicenseRef-scancode-other-permissive", "MIT", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
graydon/rust-prehistory
1407321c4f71465abade332d9cab2abcc7ba25f2
637a7740bc89abb228cc4a28b18de86facac1177
refs/heads/master
2023-07-28T22:38:00.311903
2023-05-10T06:17:53
2023-05-10T06:17:53
71,227,065
551
44
NOASSERTION
2023-05-10T06:17:54
2016-10-18T08:40:25
C
WINDOWS-1252
C
false
false
10,368
h
bigint.h
/* bigint.h - include file for bigint package ** ** This library lets you do math on arbitrarily large integers. It's ** pretty fast - compared with the multi-precision routines in the "bc" ** calculator program, these routines are between two and twelve times faster, ** except for division which is maybe half as fast. ** ** The calling convention is a little unusual. There's a basic problem ** with writing a math library in a language that doesn't do automatic ** garbage collection - what do you do about intermediate results? ** You'd like to be able to write code like this: ** ** d = bi_sqrt( bi_add( bi_multiply( x, x ), bi_multiply( y, y ) ) ); ** ** That works fine when the numbers being passed back and forth are ** actual values - ints, floats, or even fixed-size structs. However, ** when the numbers can be any size, as in this package, then you have ** to pass them around as pointers to dynamically-allocated objects. ** Those objects have to get de-allocated after you are done with them. ** But how do you de-allocate the intermediate results in a complicated ** multiple-call expression like the above? ** ** There are two common solutions to this problem. One, switch all your ** code to a language that provides automatic garbage collection, for ** example Java. This is a fine idea and I recommend you do it wherever ** it's feasible. Two, change your routines to use a calling convention ** that prevents people from writing multiple-call expressions like that. ** The resulting code will be somewhat clumsy-looking, but it will work ** just fine. ** ** This package uses a third method, which I haven't seen used anywhere ** before. It's simple: each number can be used precisely once, after ** which it is automatically de-allocated. This handles the anonymous ** intermediate values perfectly. Named values still need to be copied ** and freed explicitly. Here's the above example using this convention: ** ** d = bi_sqrt( bi_add( ** bi_multiply( bi_copy( x ), bi_copy( x ) ), ** bi_multiply( bi_copy( y ), bi_copy( y ) ) ) ); ** bi_free( x ); ** bi_free( y ); ** ** Or, since the package contains a square routine, you could just write: ** ** d = bi_sqrt( bi_add( bi_square( x ), bi_square( y ) ) ); ** ** This time the named values are only being used once, so you don't ** have to copy and free them. ** ** This really works, however you do have to be very careful when writing ** your code. If you leave out a bi_copy() and use a value more than once, ** you'll get a runtime error about "zero refs" and a SIGFPE. Run your ** code in a debugger, get a backtrace to see where the call was, and then ** eyeball the code there to see where you need to add the bi_copy(). ** ** ** Copyright © 2000 by Jef Poskanzer <jef@mail.acme.com>. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions ** are met: ** 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 AUTHOR AND CONTRIBUTORS ``AS IS'' AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ** ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE ** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS ** OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ** HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT ** LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY ** OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF ** SUCH DAMAGE. */ /* Type definition for bigints - it's an opaque type, the real definition ** is in bigint.c. */ typedef void* bigint; /* Some convenient pre-initialized numbers. These are all permanent, ** so you can use them as many times as you want without calling bi_copy(). */ extern bigint bi_0, bi_1, bi_2, bi_10, bi_m1, bi_maxint, bi_minint; /* Initialize the bigint package. You must call this when your program ** starts up. */ void bi_initialize( void ); /* Shut down the bigint package. You should call this when your program ** exits. It's not actually required, but it does do some consistency ** checks which help keep your program bug-free, so you really ought ** to call it. */ void bi_terminate( void ); /* Run in unsafe mode, skipping most runtime checks. Slightly faster. ** Once your code is debugged you can add this call after bi_initialize(). */ void bi_no_check( void ); /* Make a copy of a bigint. You must call this if you want to use a ** bigint more than once. (Or you can make the bigint permanent.) ** Note that this routine is very cheap - all it actually does is ** increment a reference counter. */ bigint bi_copy( bigint bi ); /* Make a bigint permanent, so it doesn't get automatically freed when ** used as an operand. */ void bi_permanent( bigint bi ); /* Undo bi_permanent(). The next use will free the bigint. */ void bi_depermanent( bigint bi ); /* Explicitly free a bigint. Normally bigints get freed automatically ** when they are used as an operand. This routine lets you free one ** without using it. If the bigint is permanent, this doesn't do ** anything, you have to depermanent it first. */ void bi_free( bigint bi ); /* Compare two bigints. Returns -1, 0, or 1. */ int bi_compare( bigint bia, bigint bib ); /* Convert an int to a bigint. */ bigint int_to_bi( int i ); /* Convert a string to a bigint. */ bigint str_to_bi( char* str ); /* Convert a bigint to an int. SIGFPE on overflow. */ int bi_to_int( bigint bi ); /* Write a bigint to a file. */ void bi_print( FILE* f, bigint bi ); /* Read a bigint from a file. */ bigint bi_scan( FILE* f ); /* Operations on a bigint and a regular int. */ /* Add an int to a bigint. */ bigint bi_int_add( bigint bi, int i ); /* Subtract an int from a bigint. */ bigint bi_int_subtract( bigint bi, int i ); /* Multiply a bigint by an int. */ bigint bi_int_multiply( bigint bi, int i ); /* Divide a bigint by an int. SIGFPE on divide-by-zero. */ bigint bi_int_divide( bigint binumer, int denom ); /* Take the remainder of a bigint by an int, with an int result. ** SIGFPE if m is zero. */ int bi_int_rem( bigint bi, int m ); /* Take the modulus of a bigint by an int, with an int result. ** Note that mod is not rem: mod is always within [0..m), while ** rem can be negative. SIGFPE if m is zero or negative. */ int bi_int_mod( bigint bi, int m ); /* Basic operations on two bigints. */ /* Add two bigints. */ bigint bi_add( bigint bia, bigint bib ); /* Subtract bib from bia. */ bigint bi_subtract( bigint bia, bigint bib ); /* Multiply two bigints. */ bigint bi_multiply( bigint bia, bigint bib ); /* Divide one bigint by another. SIGFPE on divide-by-zero. */ bigint bi_divide( bigint binumer, bigint bidenom ); /* Binary division of one bigint by another. SIGFPE on divide-by-zero. ** This is here just for testing. It's about five times slower than ** regular division. */ bigint bi_binary_divide( bigint binumer, bigint bidenom ); /* Take the remainder of one bigint by another. SIGFPE if bim is zero. */ bigint bi_rem( bigint bia, bigint bim ); /* Take the modulus of one bigint by another. Note that mod is not rem: ** mod is always within [0..bim), while rem can be negative. SIGFPE if ** bim is zero or negative. */ bigint bi_mod( bigint bia, bigint bim ); /* Some less common operations. */ /* Negate a bigint. */ bigint bi_negate( bigint bi ); /* Absolute value of a bigint. */ bigint bi_abs( bigint bi ); /* Divide a bigint in half. */ bigint bi_half( bigint bi ); /* Multiply a bigint by two. */ bigint bi_double( bigint bi ); /* Square a bigint. */ bigint bi_square( bigint bi ); /* Raise bi to the power of biexp. SIGFPE if biexp is negative. */ bigint bi_power( bigint bi, bigint biexp ); /* Integer square root. */ bigint bi_sqrt( bigint bi ); /* Factorial. */ bigint bi_factorial( bigint bi ); /* Some predicates. */ /* 1 if the bigint is odd, 0 if it's even. */ int bi_is_odd( bigint bi ); /* 1 if the bigint is even, 0 if it's odd. */ int bi_is_even( bigint bi ); /* 1 if the bigint equals zero, 0 if it's nonzero. */ int bi_is_zero( bigint bi ); /* 1 if the bigint equals one, 0 otherwise. */ int bi_is_one( bigint bi ); /* 1 if the bigint is less than zero, 0 if it's zero or greater. */ int bi_is_negative( bigint bi ); /* Now we get into the esoteric number-theory stuff used for cryptography. */ /* Modular exponentiation. Much faster than bi_mod(bi_power(bi,biexp),bim). ** Also, biexp can be negative. */ bigint bi_mod_power( bigint bi, bigint biexp, bigint bim ); /* Modular inverse. mod( bi * modinv(bi), bim ) == 1. SIGFPE if bi is not ** relatively prime to bim. */ bigint bi_mod_inverse( bigint bi, bigint bim ); /* Produce a random number in the half-open interval [0..bi). You need ** to have called srandom() before using this. */ bigint bi_random( bigint bi ); /* Greatest common divisor of two bigints. Euclid's algorithm. */ bigint bi_gcd( bigint bim, bigint bin ); /* Greatest common divisor of two bigints, plus the corresponding multipliers. ** Extended Euclid's algorithm. */ bigint bi_egcd( bigint bim, bigint bin, bigint* bim_mul, bigint* bin_mul ); /* Least common multiple of two bigints. */ bigint bi_lcm( bigint bia, bigint bib ); /* The Jacobi symbol. SIGFPE if bib is even. */ bigint bi_jacobi( bigint bia, bigint bib ); /* Probabalistic prime checking. A non-zero return means the probability ** that bi is prime is at least 1 - 1/2 ^ certainty. */ int bi_is_probable_prime( bigint bi, int certainty ); /* Random probabilistic prime with the specified number of bits. */ bigint bi_generate_prime( int bits, int certainty ); /* Number of bits in the number. The log base 2, approximately. */ int bi_bits( bigint bi );
c841465098b41e1d41c471deb6f45dde4c08fd2e
f79dec3c4033ca3cbb55d8a51a748cc7b8b6fbab
/multimedia/transcode/patches/patch-encode_encode_lavc.c
dd63790571e679a06296fa1ce93df4f820e147c1
[]
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
9,892
c
patch-encode_encode_lavc.c
$NetBSD: patch-encode_encode_lavc.c,v 1.2 2015/11/21 17:14:26 adam Exp $ Fixes building against FFmpeg version >= 2.0.0 (gentoo patch). --- encode/encode_lavc.c.orig 2011-11-19 16:50:27.000000000 +0000 +++ encode/encode_lavc.c @@ -74,6 +74,9 @@ struct tclavcconfigdata_ { int lmin; int lmax; int me_method; + int luma_elim_threshold; + int chroma_elim_threshold; + int quantizer_noise_shaping; /* same as above for flags */ struct { @@ -114,6 +117,7 @@ struct tclavcprivatedata_ { AVFrame ff_venc_frame; AVCodecContext ff_vcontext; + AVDictionary * ff_opts; AVCodec *ff_vcodec; @@ -164,6 +168,7 @@ static const TCCodecID tc_lavc_codecs_ou TC_CODEC_ERROR }; +#if LIBAVCODEC_VERSION_MAJOR < 55 static const enum CodecID tc_lavc_internal_codecs[] = { CODEC_ID_MPEG1VIDEO, CODEC_ID_MPEG2VIDEO, CODEC_ID_MPEG4, CODEC_ID_H263I, CODEC_ID_H263P, @@ -176,6 +181,20 @@ static const enum CodecID tc_lavc_intern CODEC_ID_MSMPEG4V2, CODEC_ID_MSMPEG4V3, CODEC_ID_NONE }; +#else +static const enum AVCodecID tc_lavc_internal_codecs[] = { + AV_CODEC_ID_MPEG1VIDEO, AV_CODEC_ID_MPEG2VIDEO, AV_CODEC_ID_MPEG4, + AV_CODEC_ID_H263I, AV_CODEC_ID_H263P, + AV_CODEC_ID_H264, + AV_CODEC_ID_WMV1, AV_CODEC_ID_WMV2, + AV_CODEC_ID_RV10, + AV_CODEC_ID_HUFFYUV, AV_CODEC_ID_FFV1, + AV_CODEC_ID_DVVIDEO, + AV_CODEC_ID_MJPEG, AV_CODEC_ID_LJPEG, + AV_CODEC_ID_MSMPEG4V2, AV_CODEC_ID_MSMPEG4V3, + AV_CODEC_ID_NONE +}; +#endif static const TCFormatID tc_lavc_formats[] = { TC_FORMAT_ERROR }; @@ -937,7 +956,11 @@ static int tc_lavc_settings_from_vob(TCL static void tc_lavc_config_defaults(TCLavcPrivateData *pd) { /* first of all reinitialize lavc data */ +#if LIBAVCODEC_VERSION_MAJOR < 55 avcodec_get_context_defaults(&pd->ff_vcontext); +#else + avcodec_get_context_defaults3(&pd->ff_vcontext, NULL); +#endif pd->confdata.thread_count = 1; @@ -955,8 +978,6 @@ static void tc_lavc_config_defaults(TCLa /* * context *transcode* (not libavcodec) defaults */ - pd->ff_vcontext.mb_qmin = 2; - pd->ff_vcontext.mb_qmax = 31; pd->ff_vcontext.max_qdiff = 3; pd->ff_vcontext.max_b_frames = 0; pd->ff_vcontext.me_range = 0; @@ -977,8 +998,8 @@ static void tc_lavc_config_defaults(TCLa pd->ff_vcontext.mpeg_quant = 0; pd->ff_vcontext.rc_initial_cplx = 0.0; pd->ff_vcontext.rc_qsquish = 1.0; - pd->ff_vcontext.luma_elim_threshold = 0; - pd->ff_vcontext.chroma_elim_threshold = 0; + pd->confdata.luma_elim_threshold = 0; + pd->confdata.chroma_elim_threshold = 0; pd->ff_vcontext.strict_std_compliance = 0; pd->ff_vcontext.dct_algo = FF_DCT_AUTO; pd->ff_vcontext.idct_algo = FF_IDCT_AUTO; @@ -1002,7 +1023,7 @@ static void tc_lavc_config_defaults(TCLa pd->ff_vcontext.intra_quant_bias = FF_DEFAULT_QUANT_BIAS; pd->ff_vcontext.inter_quant_bias = FF_DEFAULT_QUANT_BIAS; pd->ff_vcontext.noise_reduction = 0; - pd->ff_vcontext.quantizer_noise_shaping = 0; + pd->confdata.quantizer_noise_shaping = 0; pd->ff_vcontext.flags = 0; } @@ -1034,16 +1055,11 @@ static void tc_lavc_dispatch_settings(TC pd->ff_vcontext.flags = 0; SET_FLAG(pd, mv0); - SET_FLAG(pd, cbp); SET_FLAG(pd, qpel); - SET_FLAG(pd, alt); - SET_FLAG(pd, vdpart); SET_FLAG(pd, naq); SET_FLAG(pd, ilme); SET_FLAG(pd, ildct); SET_FLAG(pd, aic); - SET_FLAG(pd, aiv); - SET_FLAG(pd, umv); SET_FLAG(pd, psnr); SET_FLAG(pd, trell); SET_FLAG(pd, gray); @@ -1064,6 +1080,30 @@ static void tc_lavc_dispatch_settings(TC pd->ff_vcontext.flags |= CODEC_FLAG_INTERLACED_DCT; pd->ff_vcontext.flags |= CODEC_FLAG_INTERLACED_ME; } + if (pd->confdata.flags.alt) { + av_dict_set(&(pd->ff_opts), "alternate_scan", "1", 0); + } + if (pd->confdata.flags.vdpart) { + av_dict_set(&(pd->ff_opts), "data_partitioning", "1", 0); + } + if (pd->confdata.flags.umv) { + av_dict_set(&(pd->ff_opts), "umv", "1", 0); + } + if (pd->confdata.flags.aiv) { + av_dict_set(&(pd->ff_opts), "aiv", "1", 0); + } + if (pd->confdata.flags.cbp) { + av_dict_set(&(pd->ff_opts), "mpv_flags", "+cbp_rd", 0); + } + + char buf[1024]; +#define set_dict_opt(val, opt) \ + snprintf(buf, sizeof(buf), "%i", pd->confdata.val);\ + av_dict_set(&(pd->ff_opts), opt, buf, 0) + + set_dict_opt(luma_elim_threshold, "luma_elim_threshold"); + set_dict_opt(chroma_elim_threshold, "chroma_elim_threshold"); + set_dict_opt(quantizer_noise_shaping, "quantizer_noise_shaping"); } #undef SET_FLAG @@ -1116,8 +1156,6 @@ static int tc_lavc_read_config(TCLavcPri // handled by transcode core // { "vqmax", PCTX(qmax), TCCONF_TYPE_INT, TCCONF_FLAG_RANGE, 1, 60 }, // handled by transcode core - { "mbqmin", PCTX(mb_qmin), TCCONF_TYPE_INT, TCCONF_FLAG_RANGE, 1, 60 }, - { "mbqmax", PCTX(mb_qmax), TCCONF_TYPE_INT, TCCONF_FLAG_RANGE, 1, 60 }, { "lmin", PAUX(lmin), TCCONF_TYPE_FLOAT, TCCONF_FLAG_RANGE, 0.01, 255.0 }, { "lmax", PAUX(lmax), TCCONF_TYPE_FLOAT, TCCONF_FLAG_RANGE, 0.01, 255.0 }, { "vqdiff", PCTX(max_qdiff), TCCONF_TYPE_INT, TCCONF_FLAG_RANGE, 1, 31 }, @@ -1150,8 +1188,8 @@ static int tc_lavc_read_config(TCLavcPri { "vrc_init_cplx", PCTX(rc_initial_cplx), TCCONF_TYPE_FLOAT, TCCONF_FLAG_RANGE, 0.0, 9999999.0 }, // { "vrc_init_occupancy", }, // not yet supported { "vqsquish", PCTX(rc_qsquish), TCCONF_TYPE_FLOAT, TCCONF_FLAG_RANGE, 0.0, 99.0 }, - { "vlelim", PCTX(luma_elim_threshold), TCCONF_TYPE_INT, TCCONF_FLAG_RANGE, -99, 99 }, - { "vcelim", PCTX(chroma_elim_threshold), TCCONF_TYPE_INT, TCCONF_FLAG_RANGE, -99, 99 }, + { "vlelim", PAUX(luma_elim_threshold), TCCONF_TYPE_INT, TCCONF_FLAG_RANGE, -99, 99 }, + { "vcelim", PAUX(chroma_elim_threshold), TCCONF_TYPE_INT, TCCONF_FLAG_RANGE, -99, 99 }, { "vstrict", PCTX(strict_std_compliance), TCCONF_TYPE_INT, TCCONF_FLAG_RANGE, -99, 99 }, { "vpsize", PCTX(rtp_payload_size), TCCONF_TYPE_INT, TCCONF_FLAG_RANGE, 0, 100000000 }, { "dct", PCTX(dct_algo), TCCONF_TYPE_INT, TCCONF_FLAG_RANGE, 0, 10 }, @@ -1177,25 +1215,25 @@ static int tc_lavc_read_config(TCLavcPri { "ibias", PCTX(intra_quant_bias), TCCONF_TYPE_INT, TCCONF_FLAG_RANGE, -512, 512 }, { "pbias", PCTX(inter_quant_bias), TCCONF_TYPE_INT, TCCONF_FLAG_RANGE, -512, 512 }, { "nr", PCTX(noise_reduction), TCCONF_TYPE_INT, TCCONF_FLAG_RANGE, 0, 1000000}, - { "qns", PCTX(quantizer_noise_shaping), TCCONF_TYPE_INT, TCCONF_FLAG_RANGE, 0, 3 }, + { "qns", PAUX(quantizer_noise_shaping), TCCONF_TYPE_INT, TCCONF_FLAG_RANGE, 0, 3 }, { "inter_matrix_file", inter_matrix_file, TCCONF_TYPE_STRING, 0, 0, 0 }, { "intra_matrix_file", intra_matrix_file, TCCONF_TYPE_STRING, 0, 0, 0 }, { "mv0", PAUX(flags.mv0), TCCONF_TYPE_FLAG, 0, 0, CODEC_FLAG_MV0 }, - { "cbp", PAUX(flags.cbp), TCCONF_TYPE_FLAG, 0, 0, CODEC_FLAG_CBP_RD }, + { "cbp", PAUX(flags.cbp), TCCONF_TYPE_FLAG, 0, 0, 1 }, { "qpel", PAUX(flags.qpel), TCCONF_TYPE_FLAG, 0, 0, CODEC_FLAG_QPEL }, - { "alt", PAUX(flags.alt), TCCONF_TYPE_FLAG, 0, 0, CODEC_FLAG_ALT_SCAN }, + { "alt", PAUX(flags.alt), TCCONF_TYPE_FLAG, 0, 0, 1 }, { "ilme", PAUX(flags.ilme), TCCONF_TYPE_FLAG, 0, 0, CODEC_FLAG_INTERLACED_ME }, { "ildct", PAUX(flags.ildct), TCCONF_TYPE_FLAG, 0, 0, CODEC_FLAG_INTERLACED_DCT }, { "naq", PAUX(flags.naq), TCCONF_TYPE_FLAG, 0, 0, CODEC_FLAG_NORMALIZE_AQP }, - { "vdpart", PAUX(flags.vdpart), TCCONF_TYPE_FLAG, 0, 0, CODEC_FLAG_PART }, + { "vdpart", PAUX(flags.vdpart), TCCONF_TYPE_FLAG, 0, 0, 1 }, #if LIBAVCODEC_VERSION_INT < ((52<<16)+(0<<8)+0) { "aic", PAUX(flags.aic), TCCONF_TYPE_FLAG, 0, 0, CODEC_FLAG_H263P_AIC }, #else { "aic", PAUX(flags.aic), TCCONF_TYPE_FLAG, 0, 0, CODEC_FLAG_AC_PRED }, #endif - { "aiv", PAUX(flags.aiv), TCCONF_TYPE_FLAG, 0, 0, CODEC_FLAG_H263P_AIV }, - { "umv", PAUX(flags.umv), TCCONF_TYPE_FLAG, 0, 0, CODEC_FLAG_H263P_UMV }, + { "aiv", PAUX(flags.aiv), TCCONF_TYPE_FLAG, 0, 0, 1 }, + { "umv", PAUX(flags.umv), TCCONF_TYPE_FLAG, 0, 0, 1 }, { "psnr", PAUX(flags.psnr), TCCONF_TYPE_FLAG, 0, 0, CODEC_FLAG_PSNR }, #if LIBAVCODEC_VERSION_INT < ((52<<16)+(0<<8)+0) { "trell", PAUX(flags.trell), TCCONF_TYPE_FLAG, 0, 0, CODEC_FLAG_TRELLIS_QUANT }, @@ -1345,6 +1383,8 @@ static int tc_lavc_configure(TCModuleIns pd = self->userdata; + pd->ff_opts = NULL; + pd->flush_flag = vob->encoder_flush; /* FIXME: move into core? */ @@ -1387,7 +1427,7 @@ static int tc_lavc_configure(TCModuleIns pd->confdata.thread_count, (pd->confdata.thread_count > 1) ?"s" :""); } - avcodec_thread_init(&pd->ff_vcontext, pd->confdata.thread_count); + pd->ff_vcontext.thread_count = pd->confdata.thread_count; pd->ff_vcodec = avcodec_find_encoder(FF_VCODEC_ID(pd)); if (pd->ff_vcodec == NULL) { @@ -1397,11 +1437,11 @@ static int tc_lavc_configure(TCModuleIns } TC_LOCK_LIBAVCODEC; - ret = avcodec_open(&pd->ff_vcontext, pd->ff_vcodec); + ret = avcodec_open2(&pd->ff_vcontext, pd->ff_vcodec, &(pd->ff_opts)); TC_UNLOCK_LIBAVCODEC; if (ret < 0) { - tc_log_error(MOD_NAME, "avcodec_open() failed"); + tc_log_error(MOD_NAME, "avcodec_open2() failed"); goto failed; } /* finally, pass up the extradata, if any */
6d1d0db3f2f9171d962bc50cae0554c747c12cce
35266a567d1f4e389bb234e72e2d8e4af06bb707
/external/dyncall/dyncall_callvm_sparc64.c
954a501349d7f76bf1ed14915f4b842a7cee1d68
[ "MIT", "ISC" ]
permissive
WheretIB/nullc
6c6ec4a0f53a28c1ede2c0e3e4a9d0af5437d96d
bac1a2b2c35676a61392c094b142b50b92952fc8
refs/heads/master
2022-11-11T03:38:03.706686
2022-11-06T01:55:45
2022-11-06T01:55:45
32,209,998
161
13
MIT
2022-11-06T01:55:46
2015-03-14T12:15:38
C++
UTF-8
C
false
false
5,366
c
dyncall_callvm_sparc64.c
/* Package: dyncall Library: dyncall File: dyncall/dyncall_callvm_sparc64.c Description: Call VM for sparc64 (v9) ABI. License: Copyright (c) 2011-2018 Daniel Adler <dadler@uni-goettingen.de> 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 "dyncall_callvm_sparc64.h" #include "dyncall_call_sparc64.h" #include "dyncall_alloc.h" /* Reset argument buffer. */ static void dc_callvm_reset_v9(DCCallVM* in_self) { DCCallVM_v9* self = (DCCallVM_v9*)in_self; dcVecResize(&self->mVecHead, 0); } /* Destructor. */ static void dc_callvm_free_v9(DCCallVM* in_self) { dcFreeMem(in_self); } static void dc_callvm_argLongLong_v9(DCCallVM* in_self, DClonglong x) { DCCallVM_v9* self = (DCCallVM_v9*)in_self; dcVecAppend(&self->mVecHead, &x, sizeof(DClonglong)); } /* all integers are promoted to 64-bit. */ static void dc_callvm_argLong_v9 (DCCallVM* in_self, DClong x) { dc_callvm_argLongLong_v9(in_self, (DClonglong) x ); } static void dc_callvm_argInt_v9 (DCCallVM* in_self, DCint x) { dc_callvm_argLongLong_v9(in_self, (DClonglong) x ); } static void dc_callvm_argBool_v9 (DCCallVM* in_self, DCbool x) { dc_callvm_argLongLong_v9(in_self, (DClonglong) x ); } static void dc_callvm_argChar_v9 (DCCallVM* in_self, DCchar x) { dc_callvm_argLongLong_v9(in_self, (DClonglong) x ); } static void dc_callvm_argShort_v9 (DCCallVM* in_self, DCshort x) { dc_callvm_argLongLong_v9(in_self, (DClonglong) x ); } static void dc_callvm_argPointer_v9(DCCallVM* in_self, DCpointer x) { dc_callvm_argLongLong_v9(in_self, (DClonglong) x ); } static void dc_callvm_argDouble_v9(DCCallVM* in_self, DCdouble x) { DCCallVM_v9* self = (DCCallVM_v9*)in_self; dcVecAppend(&self->mVecHead, &x, sizeof(DCdouble)); } static void dc_callvm_argDouble_v9_ellipsis(DCCallVM* in_self, DCdouble x) { union { long long l; double d; } u; u.d = x; dc_callvm_argLongLong_v9(in_self, u.l); } static void dc_callvm_argFloat_v9_ellipsis(DCCallVM* in_self, DCfloat x) { dc_callvm_argDouble_v9_ellipsis(in_self, (DCdouble) x); } static void dc_callvm_argFloat_v9(DCCallVM* in_self, DCfloat x) { union { double d; float f[2]; } u; u.f[1] = x; dc_callvm_argDouble_v9(in_self, u.d); } static void dc_callvm_mode_v9(DCCallVM* in_self, DCint mode); DCCallVM_vt gVT_v9_ellipsis = { &dc_callvm_free_v9, &dc_callvm_reset_v9, &dc_callvm_mode_v9, &dc_callvm_argBool_v9, &dc_callvm_argChar_v9, &dc_callvm_argShort_v9, &dc_callvm_argInt_v9, &dc_callvm_argLong_v9, &dc_callvm_argLongLong_v9, &dc_callvm_argFloat_v9_ellipsis, &dc_callvm_argDouble_v9_ellipsis, &dc_callvm_argPointer_v9, NULL /* argStruct */, (DCvoidvmfunc*) &dcCall_v9, (DCboolvmfunc*) &dcCall_v9, (DCcharvmfunc*) &dcCall_v9, (DCshortvmfunc*) &dcCall_v9, (DCintvmfunc*) &dcCall_v9, (DClongvmfunc*) &dcCall_v9, (DClonglongvmfunc*) &dcCall_v9, (DCfloatvmfunc*) &dcCall_v9, (DCdoublevmfunc*) &dcCall_v9, (DCpointervmfunc*) &dcCall_v9, NULL /* callStruct */ }; /* CallVM virtual table. */ DCCallVM_vt gVT_v9 = { &dc_callvm_free_v9, &dc_callvm_reset_v9, &dc_callvm_mode_v9, &dc_callvm_argBool_v9, &dc_callvm_argChar_v9, &dc_callvm_argShort_v9, &dc_callvm_argInt_v9, &dc_callvm_argLong_v9, &dc_callvm_argLongLong_v9, &dc_callvm_argFloat_v9, &dc_callvm_argDouble_v9, &dc_callvm_argPointer_v9, NULL /* argStruct */, (DCvoidvmfunc*) &dcCall_v9, (DCboolvmfunc*) &dcCall_v9, (DCcharvmfunc*) &dcCall_v9, (DCshortvmfunc*) &dcCall_v9, (DCintvmfunc*) &dcCall_v9, (DClongvmfunc*) &dcCall_v9, (DClonglongvmfunc*) &dcCall_v9, (DCfloatvmfunc*) &dcCall_v9, (DCdoublevmfunc*) &dcCall_v9, (DCpointervmfunc*) &dcCall_v9, NULL /* callStruct */ }; /* mode: only a single mode available currently. */ static void dc_callvm_mode_v9(DCCallVM* in_self, DCint mode) { DCCallVM_v9* self = (DCCallVM_v9*)in_self; DCCallVM_vt* vt; switch(mode) { case DC_CALL_C_DEFAULT: case DC_CALL_C_SPARC64: case DC_CALL_C_ELLIPSIS: vt = &gVT_v9; break; case DC_CALL_C_ELLIPSIS_VARARGS: vt = &gVT_v9_ellipsis; break; default: self->mInterface.mError = DC_ERROR_UNSUPPORTED_MODE; return; } dc_callvm_base_init(&self->mInterface, vt); } /* Public API. */ DCCallVM* dcNewCallVM(DCsize size) { DCCallVM_v9* p = (DCCallVM_v9*)dcAllocMem(sizeof(DCCallVM_v9)+size); dc_callvm_mode_v9((DCCallVM*)p, DC_CALL_C_DEFAULT); dcVecInit(&p->mVecHead,size); dc_callvm_reset_v9(&p->mInterface); return (DCCallVM*)p; }
e47e3f1b431dee0471124160fed9effbc2746edb
eb4d06c58aa902fe06055327b90b99a6dacb2ebc
/OHMySQL/lib/MySQL.xcframework/tvos-arm64_x86_64-simulator/MySQL.framework/Headers/mysql_runtime_error.h
5c9f2535110e1f1ea80c3814dd13e89c9279a400
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "GPL-2.0-only", "GPL-1.0-or-later", "LicenseRef-scancode-mysql-linking-exception-2018", "Universal-FOSS-exception-1.0" ]
permissive
oleghnidets/OHMySQL
5c3741afdd866910b473cc267749e017af1900ed
c6afc83187d9527933de016438024f8472aff768
refs/heads/master
2023-07-24T12:03:42.077178
2023-07-07T20:46:40
2023-07-07T20:46:40
41,176,216
250
53
MIT
2023-02-21T20:34:01
2015-08-21T20:31:41
C
UTF-8
C
false
false
1,912
h
mysql_runtime_error.h
/* Copyright (c) 2018, 2022, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. 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, version 2.0, 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 */ #ifndef MYSQL_RUNTIME_ERROR_H #define MYSQL_RUNTIME_ERROR_H #include <mysql/components/service.h> //! @cond Doxygen_Suppress #include <stdarg.h> //! @endcond /** This service defines the error report function api. */ BEGIN_SERVICE_DEFINITION(mysql_runtime_error) /** It calls the server SQL error generation function and adds the error into the THD's error context. @param error_id mysql server error number, used to get the error description. @param flags this will tell, whether the error is a fatal statement error or write the error to error log file. @param args variable argument list which has the error message details. */ DECLARE_METHOD(void, emit, (int error_id, int flags, va_list args)); END_SERVICE_DEFINITION(mysql_runtime_error) #endif /* MYSQL_RUNTIME_ERROR_H */
568aeaf387b23770d474d32fde7e5319ab3f9796
ef413c27f91521703cfa21f65a8b6aa1c50347d2
/src/windows/WinMiniFB.c
69fac7727339bd4b177132d710cfd475bc38fc4f
[ "MIT" ]
permissive
emoon/minifb
7a9204948e7afaf966448198c552d464690db6ad
37776c0e947f55345c7777ab1925b1a751abb9ee
refs/heads/master
2023-08-23T05:49:24.258963
2023-06-04T15:31:20
2023-06-04T15:31:20
20,552,735
907
87
MIT
2023-06-04T15:31:21
2014-06-06T05:41:52
C
UTF-8
C
false
false
34,104
c
WinMiniFB.c
#include <MiniFB.h> #include <MiniFB_internal.h> #include <WindowData.h> #include "WindowData_Win.h" #if defined(USE_OPENGL_API) #include "gl/MiniFB_GL.h" #endif #include <stdio.h> #include <stdlib.h> /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copied (and modified) from Windows Kit 10 to avoid setting _WIN32_WINNT to a higher version typedef enum mfb_PROCESS_DPI_AWARENESS { mfb_PROCESS_DPI_UNAWARE = 0, mfb_PROCESS_SYSTEM_DPI_AWARE = 1, mfb_PROCESS_PER_MONITOR_DPI_AWARE = 2 } mfb_PROCESS_DPI_AWARENESS; typedef enum mfb_MONITOR_DPI_TYPE { mfb_MDT_EFFECTIVE_DPI = 0, mfb_MDT_ANGULAR_DPI = 1, mfb_MDT_RAW_DPI = 2, mfb_MDT_DEFAULT = mfb_MDT_EFFECTIVE_DPI } mfb_MONITOR_DPI_TYPE; #define mfb_DPI_AWARENESS_CONTEXT_UNAWARE ((HANDLE) -1) #define mfb_DPI_AWARENESS_CONTEXT_SYSTEM_AWARE ((HANDLE) -2) #define mfb_DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE ((HANDLE) -3) #define mfb_DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 ((HANDLE) -4) #define mfb_DPI_AWARENESS_CONTEXT_UNAWARE_GDISCALED ((HANDLE) -5) // user32.dll typedef BOOL(WINAPI *PFN_SetProcessDPIAware)(void); typedef BOOL(WINAPI *PFN_SetProcessDpiAwarenessContext)(HANDLE); typedef UINT(WINAPI *PFN_GetDpiForWindow)(HWND); typedef BOOL(WINAPI *PFN_EnableNonClientDpiScaling)(HWND); HMODULE mfb_user32_dll = 0x0; PFN_SetProcessDPIAware mfb_SetProcessDPIAware = 0x0; PFN_SetProcessDpiAwarenessContext mfb_SetProcessDpiAwarenessContext = 0x0; PFN_GetDpiForWindow mfb_GetDpiForWindow = 0x0; PFN_EnableNonClientDpiScaling mfb_EnableNonClientDpiScaling = 0x0; // shcore.dll typedef HRESULT(WINAPI *PFN_SetProcessDpiAwareness)(mfb_PROCESS_DPI_AWARENESS); typedef HRESULT(WINAPI *PFN_GetDpiForMonitor)(HMONITOR, mfb_MONITOR_DPI_TYPE, UINT *, UINT *); HMODULE mfb_shcore_dll = 0x0; PFN_SetProcessDpiAwareness mfb_SetProcessDpiAwareness = 0x0; PFN_GetDpiForMonitor mfb_GetDpiForMonitor = 0x0; //-- void load_functions() { if(mfb_user32_dll == 0x0) { mfb_user32_dll = LoadLibraryA("user32.dll"); if (mfb_user32_dll != 0x0) { mfb_SetProcessDPIAware = (PFN_SetProcessDPIAware) GetProcAddress(mfb_user32_dll, "SetProcessDPIAware"); mfb_SetProcessDpiAwarenessContext = (PFN_SetProcessDpiAwarenessContext) GetProcAddress(mfb_user32_dll, "SetProcessDpiAwarenessContext"); mfb_GetDpiForWindow = (PFN_GetDpiForWindow) GetProcAddress(mfb_user32_dll, "GetDpiForWindow"); mfb_EnableNonClientDpiScaling = (PFN_EnableNonClientDpiScaling) GetProcAddress(mfb_user32_dll, "EnableNonClientDpiScaling"); } } if(mfb_shcore_dll == 0x0) { mfb_shcore_dll = LoadLibraryA("shcore.dll"); if (mfb_shcore_dll != 0x0) { mfb_SetProcessDpiAwareness = (PFN_SetProcessDpiAwareness) GetProcAddress(mfb_shcore_dll, "SetProcessDpiAwareness"); mfb_GetDpiForMonitor = (PFN_GetDpiForMonitor) GetProcAddress(mfb_shcore_dll, "GetDpiForMonitor"); } } } //-- // NOT Thread safe. Just convenient (Don't do this at home guys) char * GetErrorMessage() { static char buffer[256]; buffer[0] = 0; FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, // Not used with FORMAT_MESSAGE_FROM_SYSTEM GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buffer, sizeof(buffer), NULL); return buffer; } //-- void dpi_aware() { if (mfb_SetProcessDpiAwarenessContext != 0x0) { if(mfb_SetProcessDpiAwarenessContext(mfb_DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2) == false) { uint32_t error = GetLastError(); if(error == ERROR_INVALID_PARAMETER) { error = NO_ERROR; if(mfb_SetProcessDpiAwarenessContext(mfb_DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE) == false) { error = GetLastError(); } } if(error != NO_ERROR) { fprintf(stderr, "Error (SetProcessDpiAwarenessContext): %s\n", GetErrorMessage()); } } } else if (mfb_SetProcessDpiAwareness != 0x0) { if(mfb_SetProcessDpiAwareness(mfb_PROCESS_PER_MONITOR_DPI_AWARE) != S_OK) { fprintf(stderr, "Error (SetProcessDpiAwareness): %s\n", GetErrorMessage()); } } else if (mfb_SetProcessDPIAware != 0x0) { if(mfb_SetProcessDPIAware() == false) { fprintf(stderr, "Error (SetProcessDPIAware): %s\n", GetErrorMessage()); } } } //-- void get_monitor_scale(HWND hWnd, float *scale_x, float *scale_y) { UINT x, y; if(mfb_GetDpiForMonitor != 0x0) { HMONITOR monitor = MonitorFromWindow(hWnd, MONITOR_DEFAULTTONEAREST); mfb_GetDpiForMonitor(monitor, mfb_MDT_EFFECTIVE_DPI, &x, &y); } else { const HDC dc = GetDC(hWnd); x = GetDeviceCaps(dc, LOGPIXELSX); y = GetDeviceCaps(dc, LOGPIXELSY); ReleaseDC(NULL, dc); } if (scale_x) { *scale_x = x / (float) USER_DEFAULT_SCREEN_DPI; if(*scale_x == 0) { *scale_x = 1; } } if (scale_y) { *scale_y = y / (float) USER_DEFAULT_SCREEN_DPI; if (*scale_y == 0) { *scale_y = 1; } } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void mfb_get_monitor_scale(struct mfb_window *window, float *scale_x, float *scale_y) { HWND hWnd = 0x0; if(window != 0x0) { SWindowData *window_data = (SWindowData *) window; SWindowData_Win *window_data_win = (SWindowData_Win *) window_data->specific; hWnd = window_data_win->window; } get_monitor_scale(hWnd, scale_x, scale_y); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// long s_window_style = WS_POPUP | WS_SYSMENU | WS_CAPTION; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void init_keycodes(); uint32_t translate_mod(); mfb_key translate_key(unsigned int wParam, unsigned long lParam); void destroy_window_data(SWindowData *window_data); LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { LRESULT res = 0; SWindowData *window_data = (SWindowData *) GetWindowLongPtr(hWnd, GWLP_USERDATA); SWindowData_Win *window_data_win = 0x0; if (window_data != 0x0) { window_data_win = (SWindowData_Win *) window_data->specific; } switch (message) { case WM_NCCREATE: { if(mfb_EnableNonClientDpiScaling) mfb_EnableNonClientDpiScaling(hWnd); return DefWindowProc(hWnd, message, wParam, lParam); } // TODO //case 0x02E4://WM_GETDPISCALEDSIZE: //{ // SIZE* size = (SIZE*) lParam; // WORD dpi = LOWORD(wParam); // return true; // break; //} // TODO //case WM_DPICHANGED: //{ // const float xscale = HIWORD(wParam); // const float yscale = LOWORD(wParam); // break; //} #if !defined(USE_OPENGL_API) case WM_PAINT: { if (window_data && window_data->draw_buffer && window_data_win) { StretchDIBits(window_data_win->hdc, window_data->dst_offset_x, window_data->dst_offset_y, window_data->dst_width, window_data->dst_height, 0, 0, window_data->buffer_width, window_data->buffer_height, window_data->draw_buffer, window_data_win->bitmapInfo, DIB_RGB_COLORS, SRCCOPY); } ValidateRect(hWnd, 0x0); break; } #endif case WM_CLOSE: { if (window_data) { bool destroy = false; // Obtain a confirmation of close if (!window_data->close_func || window_data->close_func((struct mfb_window*)window_data)) { destroy = true; } if (destroy) { window_data->close = true; if (window_data_win) { DestroyWindow(window_data_win->window); } } } break; } case WM_DESTROY: if (window_data) { window_data->close = true; } break; case WM_KEYDOWN: case WM_SYSKEYDOWN: case WM_KEYUP: case WM_SYSKEYUP: { if (window_data) { mfb_key key_code = translate_key((unsigned int)wParam, (unsigned long)lParam); int is_pressed = !((lParam >> 31) & 1); window_data->mod_keys = translate_mod(); if (key_code == KB_KEY_UNKNOWN) return FALSE; window_data->key_status[key_code] = (uint8_t) is_pressed; kCall(keyboard_func, key_code, window_data->mod_keys, is_pressed); } break; } case WM_CHAR: case WM_SYSCHAR: { static WCHAR highSurrogate = 0; if (window_data) { if (wParam >= 0xd800 && wParam <= 0xdbff) { highSurrogate = (WCHAR) wParam; } else { unsigned int codepoint = 0; if (wParam >= 0xdc00 && wParam <= 0xdfff) { if (highSurrogate != 0) { codepoint += (highSurrogate - 0xd800) << 10; codepoint += (WCHAR) wParam - 0xdc00; codepoint += 0x10000; } } else { codepoint = (WCHAR) wParam; } highSurrogate = 0; kCall(char_input_func, codepoint); } } } break; case WM_UNICHAR: { if (window_data) { if (wParam == UNICODE_NOCHAR) { // WM_UNICHAR is not sent by Windows, but is sent by some third-party input method engine // Returning TRUE here announces support for this message return TRUE; } kCall(char_input_func, (unsigned int) wParam); } break; } case WM_LBUTTONUP: case WM_RBUTTONUP: case WM_MBUTTONUP: case WM_XBUTTONUP: case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK: case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK: case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK: case WM_XBUTTONDOWN: case WM_XBUTTONDBLCLK: { if (window_data) { mfb_mouse_button button = MOUSE_BTN_0; window_data->mod_keys = translate_mod(); int is_pressed = 0; switch(message) { case WM_LBUTTONDOWN: is_pressed = 1; case WM_LBUTTONUP: button = MOUSE_BTN_1; break; case WM_RBUTTONDOWN: is_pressed = 1; case WM_RBUTTONUP: button = MOUSE_BTN_2; break; case WM_MBUTTONDOWN: is_pressed = 1; case WM_MBUTTONUP: button = MOUSE_BTN_3; break; default: button = (GET_XBUTTON_WPARAM(wParam) == XBUTTON1 ? MOUSE_BTN_5 : MOUSE_BTN_6); if (message == WM_XBUTTONDOWN) { is_pressed = 1; } } window_data->mouse_button_status[button & 0x07] = is_pressed; kCall(mouse_btn_func, button, window_data->mod_keys, is_pressed); } break; } case WM_MOUSEWHEEL: if (window_data) { window_data->mouse_wheel_y = (SHORT)HIWORD(wParam) / (float)WHEEL_DELTA; kCall(mouse_wheel_func, translate_mod(), 0.0f, window_data->mouse_wheel_y); } break; case WM_MOUSEHWHEEL: // This message is only sent on Windows Vista and later // NOTE: The X-axis is inverted for consistency with macOS and X11 if (window_data) { window_data->mouse_wheel_x = -((SHORT)HIWORD(wParam) / (float)WHEEL_DELTA); kCall(mouse_wheel_func, translate_mod(), window_data->mouse_wheel_x, 0.0f); } break; case WM_MOUSEMOVE: if (window_data) { if (window_data_win->mouse_inside == false) { window_data_win->mouse_inside = true; TRACKMOUSEEVENT tme; ZeroMemory(&tme, sizeof(tme)); tme.cbSize = sizeof(tme); tme.dwFlags = TME_LEAVE; tme.hwndTrack = hWnd; TrackMouseEvent(&tme); } window_data->mouse_pos_x = (int)(short) LOWORD(lParam); window_data->mouse_pos_y = (int)(short) HIWORD(lParam); kCall(mouse_move_func, window_data->mouse_pos_x, window_data->mouse_pos_y); } break; case WM_MOUSELEAVE: if (window_data) { window_data_win->mouse_inside = false; } break; case WM_SIZE: if (window_data) { float scale_x, scale_y; uint32_t width, height; if(wParam == SIZE_MINIMIZED) { return res; } get_monitor_scale(hWnd, &scale_x, &scale_y); window_data->window_width = LOWORD(lParam); window_data->window_height = HIWORD(lParam); resize_dst(window_data, window_data->window_width, window_data->window_height); #if !defined(USE_OPENGL_API) BitBlt(window_data_win->hdc, 0, 0, window_data->window_width, window_data->window_height, 0, 0, 0, BLACKNESS); #else resize_GL(window_data); #endif if(window_data->window_width != 0 && window_data->window_height != 0) { width = (uint32_t) (window_data->window_width / scale_x); height = (uint32_t) (window_data->window_height / scale_y); kCall(resize_func, width, height); } } break; case WM_SETFOCUS: if (window_data) { window_data->is_active = true; kCall(active_func, true); } break; case WM_KILLFOCUS: if (window_data) { window_data->is_active = false; kCall(active_func, false); } break; default: { res = DefWindowProc(hWnd, message, wParam, lParam); } } return res; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct mfb_window * mfb_open_ex(const char *title, unsigned width, unsigned height, unsigned flags) { RECT rect = { 0 }; int x = 0, y = 0; load_functions(); dpi_aware(); init_keycodes(); SWindowData *window_data = malloc(sizeof(SWindowData)); if (window_data == 0x0) { return 0x0; } memset(window_data, 0, sizeof(SWindowData)); SWindowData_Win *window_data_win = malloc(sizeof(SWindowData_Win)); if(window_data_win == 0x0) { free(window_data); return 0x0; } memset(window_data_win, 0, sizeof(SWindowData_Win)); window_data->specific = window_data_win; window_data->buffer_width = width; window_data->buffer_height = height; window_data->buffer_stride = width * 4; s_window_style = WS_OVERLAPPEDWINDOW & ~WS_MAXIMIZEBOX & ~WS_THICKFRAME; if (flags & WF_FULLSCREEN) { flags = WF_FULLSCREEN; // Remove all other flags rect.right = GetSystemMetrics(SM_CXSCREEN); rect.bottom = GetSystemMetrics(SM_CYSCREEN); s_window_style = WS_POPUP & ~(WS_CAPTION | WS_THICKFRAME | WS_MINIMIZE | WS_MAXIMIZE | WS_SYSMENU); DEVMODE settings = { 0 }; EnumDisplaySettings(0, 0, &settings); settings.dmPelsWidth = GetSystemMetrics(SM_CXSCREEN); settings.dmPelsHeight = GetSystemMetrics(SM_CYSCREEN); settings.dmBitsPerPel = 32; settings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; if (ChangeDisplaySettings(&settings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) { flags = WF_FULLSCREEN_DESKTOP; } } if (flags & WF_BORDERLESS) { s_window_style = WS_POPUP; } if (flags & WF_RESIZABLE) { s_window_style |= WS_MAXIMIZEBOX | WS_SIZEBOX; } if (flags & WF_FULLSCREEN_DESKTOP) { s_window_style = WS_OVERLAPPEDWINDOW; width = GetSystemMetrics(SM_CXFULLSCREEN); height = GetSystemMetrics(SM_CYFULLSCREEN); rect.right = width; rect.bottom = height; AdjustWindowRect(&rect, s_window_style, 0); if (rect.left < 0) { width += rect.left * 2; rect.right += rect.left; rect.left = 0; } if (rect.bottom > (LONG) height) { height -= (rect.bottom - height); rect.bottom += (rect.bottom - height); rect.top = 0; } } else if (!(flags & WF_FULLSCREEN)) { float scale_x, scale_y; get_monitor_scale(0, &scale_x, &scale_y); rect.right = (LONG) (width * scale_x); rect.bottom = (LONG) (height * scale_y); AdjustWindowRect(&rect, s_window_style, 0); rect.right -= rect.left; rect.bottom -= rect.top; x = (GetSystemMetrics(SM_CXSCREEN) - rect.right) / 2; y = (GetSystemMetrics(SM_CYSCREEN) - rect.bottom + rect.top) / 2; } window_data_win->wc.style = CS_OWNDC | CS_VREDRAW | CS_HREDRAW; window_data_win->wc.lpfnWndProc = WndProc; window_data_win->wc.hCursor = LoadCursor(0, IDC_ARROW); window_data_win->wc.lpszClassName = title; RegisterClass(&window_data_win->wc); calc_dst_factor(window_data, width, height); window_data->window_width = rect.right; window_data->window_height = rect.bottom; window_data_win->window = CreateWindowEx( 0, title, title, s_window_style, x, y, window_data->window_width, window_data->window_height, 0, 0, 0, 0); if (!window_data_win->window) { free(window_data); free(window_data_win); return 0x0; } SetWindowLongPtr(window_data_win->window, GWLP_USERDATA, (LONG_PTR) window_data); if (flags & WF_ALWAYS_ON_TOP) SetWindowPos(window_data_win->window, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); ShowWindow(window_data_win->window, SW_NORMAL); window_data_win->hdc = GetDC(window_data_win->window); #if !defined(USE_OPENGL_API) window_data_win->bitmapInfo = (BITMAPINFO *) calloc(1, sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * 3); if(window_data_win->bitmapInfo == 0x0) { free(window_data); free(window_data_win); return 0x0; } window_data_win->bitmapInfo->bmiHeader.biSize = sizeof(BITMAPINFOHEADER); window_data_win->bitmapInfo->bmiHeader.biPlanes = 1; window_data_win->bitmapInfo->bmiHeader.biBitCount = 32; window_data_win->bitmapInfo->bmiHeader.biCompression = BI_BITFIELDS; window_data_win->bitmapInfo->bmiHeader.biWidth = window_data->buffer_width; window_data_win->bitmapInfo->bmiHeader.biHeight = -(LONG)window_data->buffer_height; window_data_win->bitmapInfo->bmiColors[0].rgbRed = 0xff; window_data_win->bitmapInfo->bmiColors[1].rgbGreen = 0xff; window_data_win->bitmapInfo->bmiColors[2].rgbBlue = 0xff; #else create_GL_context(window_data); #endif window_data_win->timer = mfb_timer_create(); mfb_set_keyboard_callback((struct mfb_window *) window_data, keyboard_default); #if defined(_DEBUG) || defined(DEBUG) #if defined(USE_OPENGL_API) printf("Window created using OpenGL API\n"); #else printf("Window created using GDI API\n"); #endif #endif window_data->is_initialized = true; return (struct mfb_window *) window_data; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// mfb_update_state mfb_update_ex(struct mfb_window *window, void *buffer, unsigned width, unsigned height) { MSG msg; if (window == 0x0) { return STATE_INVALID_WINDOW; } SWindowData *window_data = (SWindowData *) window; if (window_data->close) { destroy_window_data(window_data); return STATE_EXIT; } if (buffer == 0x0) { return STATE_INVALID_BUFFER; } window_data->draw_buffer = buffer; window_data->buffer_width = width; window_data->buffer_stride = width * 4; window_data->buffer_height = height; SWindowData_Win *window_data_win = (SWindowData_Win *) window_data->specific; #if !defined(USE_OPENGL_API) window_data_win->bitmapInfo->bmiHeader.biWidth = window_data->buffer_width; window_data_win->bitmapInfo->bmiHeader.biHeight = -(LONG) window_data->buffer_height; InvalidateRect(window_data_win->window, 0x0, TRUE); SendMessage(window_data_win->window, WM_PAINT, 0, 0); #else redraw_GL(window_data, buffer); #endif while (window_data->close == false && PeekMessage(&msg, window_data_win->window, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } return STATE_OK; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// mfb_update_state mfb_update_events(struct mfb_window *window) { MSG msg; if (window == 0x0) { return STATE_INVALID_WINDOW; } SWindowData *window_data = (SWindowData *)window; if (window_data->close) { destroy_window_data(window_data); return STATE_EXIT; } SWindowData_Win *window_data_win = (SWindowData_Win *) window_data->specific; while (window_data->close == false && PeekMessage(&msg, window_data_win->window, 0, 0, PM_REMOVE)) { //if(msg.message == WM_PAINT) // return STATE_OK; TranslateMessage(&msg); DispatchMessage(&msg); } return STATE_OK; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// extern double g_time_for_frame; extern bool g_use_hardware_sync; bool mfb_wait_sync(struct mfb_window *window) { if (window == 0x0) { return false; } SWindowData *window_data = (SWindowData *)window; if (window_data->close) { destroy_window_data(window_data); return false; } if(g_use_hardware_sync) { return true; } MSG msg; SWindowData_Win *window_data_win = (SWindowData_Win *) window_data->specific; double current; while (1) { current = mfb_timer_now(window_data_win->timer); if (current >= g_time_for_frame) { mfb_timer_reset(window_data_win->timer); return true; } else if (g_time_for_frame - current > 2.0/1000.0) { timeBeginPeriod(1); Sleep(1); timeEndPeriod(1); if(PeekMessage(&msg, window_data_win->window, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); if (window_data->close) { destroy_window_data(window_data); return false; } } } } return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void destroy_window_data(SWindowData *window_data) { if (window_data == 0x0) return; SWindowData_Win *window_data_win = (SWindowData_Win *) window_data->specific; #if !defined(USE_OPENGL_API) if (window_data_win->bitmapInfo != 0x0) { free(window_data_win->bitmapInfo); window_data_win->bitmapInfo = 0x0; } #else destroy_GL_context(window_data); #endif if (window_data_win->window != 0 && window_data_win->hdc != 0) { ReleaseDC(window_data_win->window, window_data_win->hdc); DestroyWindow(window_data_win->window); } window_data_win->window = 0; window_data_win->hdc = 0; mfb_timer_destroy(window_data_win->timer); window_data_win->timer = 0x0; window_data->draw_buffer = 0x0; window_data->close = true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// uint32_t translate_mod() { uint32_t mods = 0; if (GetKeyState(VK_SHIFT) & 0x8000) mods |= KB_MOD_SHIFT; if (GetKeyState(VK_CONTROL) & 0x8000) mods |= KB_MOD_CONTROL; if (GetKeyState(VK_MENU) & 0x8000) mods |= KB_MOD_ALT; if ((GetKeyState(VK_LWIN) | GetKeyState(VK_RWIN)) & 0x8000) mods |= KB_MOD_SUPER; if (GetKeyState(VK_CAPITAL) & 1) mods |= KB_MOD_CAPS_LOCK; if (GetKeyState(VK_NUMLOCK) & 1) mods |= KB_MOD_NUM_LOCK; return mods; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// extern short int g_keycodes[512]; void init_keycodes() { if(g_keycodes[0x00B] != KB_KEY_0) { g_keycodes[0x00B] = KB_KEY_0; g_keycodes[0x002] = KB_KEY_1; g_keycodes[0x003] = KB_KEY_2; g_keycodes[0x004] = KB_KEY_3; g_keycodes[0x005] = KB_KEY_4; g_keycodes[0x006] = KB_KEY_5; g_keycodes[0x007] = KB_KEY_6; g_keycodes[0x008] = KB_KEY_7; g_keycodes[0x009] = KB_KEY_8; g_keycodes[0x00A] = KB_KEY_9; g_keycodes[0x01E] = KB_KEY_A; g_keycodes[0x030] = KB_KEY_B; g_keycodes[0x02E] = KB_KEY_C; g_keycodes[0x020] = KB_KEY_D; g_keycodes[0x012] = KB_KEY_E; g_keycodes[0x021] = KB_KEY_F; g_keycodes[0x022] = KB_KEY_G; g_keycodes[0x023] = KB_KEY_H; g_keycodes[0x017] = KB_KEY_I; g_keycodes[0x024] = KB_KEY_J; g_keycodes[0x025] = KB_KEY_K; g_keycodes[0x026] = KB_KEY_L; g_keycodes[0x032] = KB_KEY_M; g_keycodes[0x031] = KB_KEY_N; g_keycodes[0x018] = KB_KEY_O; g_keycodes[0x019] = KB_KEY_P; g_keycodes[0x010] = KB_KEY_Q; g_keycodes[0x013] = KB_KEY_R; g_keycodes[0x01F] = KB_KEY_S; g_keycodes[0x014] = KB_KEY_T; g_keycodes[0x016] = KB_KEY_U; g_keycodes[0x02F] = KB_KEY_V; g_keycodes[0x011] = KB_KEY_W; g_keycodes[0x02D] = KB_KEY_X; g_keycodes[0x015] = KB_KEY_Y; g_keycodes[0x02C] = KB_KEY_Z; g_keycodes[0x028] = KB_KEY_APOSTROPHE; g_keycodes[0x02B] = KB_KEY_BACKSLASH; g_keycodes[0x033] = KB_KEY_COMMA; g_keycodes[0x00D] = KB_KEY_EQUAL; g_keycodes[0x029] = KB_KEY_GRAVE_ACCENT; g_keycodes[0x01A] = KB_KEY_LEFT_BRACKET; g_keycodes[0x00C] = KB_KEY_MINUS; g_keycodes[0x034] = KB_KEY_PERIOD; g_keycodes[0x01B] = KB_KEY_RIGHT_BRACKET; g_keycodes[0x027] = KB_KEY_SEMICOLON; g_keycodes[0x035] = KB_KEY_SLASH; g_keycodes[0x056] = KB_KEY_WORLD_2; g_keycodes[0x00E] = KB_KEY_BACKSPACE; g_keycodes[0x153] = KB_KEY_DELETE; g_keycodes[0x14F] = KB_KEY_END; g_keycodes[0x01C] = KB_KEY_ENTER; g_keycodes[0x001] = KB_KEY_ESCAPE; g_keycodes[0x147] = KB_KEY_HOME; g_keycodes[0x152] = KB_KEY_INSERT; g_keycodes[0x15D] = KB_KEY_MENU; g_keycodes[0x151] = KB_KEY_PAGE_DOWN; g_keycodes[0x149] = KB_KEY_PAGE_UP; g_keycodes[0x045] = KB_KEY_PAUSE; g_keycodes[0x146] = KB_KEY_PAUSE; g_keycodes[0x039] = KB_KEY_SPACE; g_keycodes[0x00F] = KB_KEY_TAB; g_keycodes[0x03A] = KB_KEY_CAPS_LOCK; g_keycodes[0x145] = KB_KEY_NUM_LOCK; g_keycodes[0x046] = KB_KEY_SCROLL_LOCK; g_keycodes[0x03B] = KB_KEY_F1; g_keycodes[0x03C] = KB_KEY_F2; g_keycodes[0x03D] = KB_KEY_F3; g_keycodes[0x03E] = KB_KEY_F4; g_keycodes[0x03F] = KB_KEY_F5; g_keycodes[0x040] = KB_KEY_F6; g_keycodes[0x041] = KB_KEY_F7; g_keycodes[0x042] = KB_KEY_F8; g_keycodes[0x043] = KB_KEY_F9; g_keycodes[0x044] = KB_KEY_F10; g_keycodes[0x057] = KB_KEY_F11; g_keycodes[0x058] = KB_KEY_F12; g_keycodes[0x064] = KB_KEY_F13; g_keycodes[0x065] = KB_KEY_F14; g_keycodes[0x066] = KB_KEY_F15; g_keycodes[0x067] = KB_KEY_F16; g_keycodes[0x068] = KB_KEY_F17; g_keycodes[0x069] = KB_KEY_F18; g_keycodes[0x06A] = KB_KEY_F19; g_keycodes[0x06B] = KB_KEY_F20; g_keycodes[0x06C] = KB_KEY_F21; g_keycodes[0x06D] = KB_KEY_F22; g_keycodes[0x06E] = KB_KEY_F23; g_keycodes[0x076] = KB_KEY_F24; g_keycodes[0x038] = KB_KEY_LEFT_ALT; g_keycodes[0x01D] = KB_KEY_LEFT_CONTROL; g_keycodes[0x02A] = KB_KEY_LEFT_SHIFT; g_keycodes[0x15B] = KB_KEY_LEFT_SUPER; g_keycodes[0x137] = KB_KEY_PRINT_SCREEN; g_keycodes[0x138] = KB_KEY_RIGHT_ALT; g_keycodes[0x11D] = KB_KEY_RIGHT_CONTROL; g_keycodes[0x036] = KB_KEY_RIGHT_SHIFT; g_keycodes[0x15C] = KB_KEY_RIGHT_SUPER; g_keycodes[0x150] = KB_KEY_DOWN; g_keycodes[0x14B] = KB_KEY_LEFT; g_keycodes[0x14D] = KB_KEY_RIGHT; g_keycodes[0x148] = KB_KEY_UP; g_keycodes[0x052] = KB_KEY_KP_0; g_keycodes[0x04F] = KB_KEY_KP_1; g_keycodes[0x050] = KB_KEY_KP_2; g_keycodes[0x051] = KB_KEY_KP_3; g_keycodes[0x04B] = KB_KEY_KP_4; g_keycodes[0x04C] = KB_KEY_KP_5; g_keycodes[0x04D] = KB_KEY_KP_6; g_keycodes[0x047] = KB_KEY_KP_7; g_keycodes[0x048] = KB_KEY_KP_8; g_keycodes[0x049] = KB_KEY_KP_9; g_keycodes[0x04E] = KB_KEY_KP_ADD; g_keycodes[0x053] = KB_KEY_KP_DECIMAL; g_keycodes[0x135] = KB_KEY_KP_DIVIDE; g_keycodes[0x11C] = KB_KEY_KP_ENTER; g_keycodes[0x037] = KB_KEY_KP_MULTIPLY; g_keycodes[0x04A] = KB_KEY_KP_SUBTRACT; } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// mfb_key translate_key(unsigned int wParam, unsigned long lParam) { if (wParam == VK_CONTROL) { MSG next; DWORD time; if (lParam & 0x01000000) return KB_KEY_RIGHT_CONTROL; time = GetMessageTime(); if (PeekMessageW(&next, 0x0, 0, 0, PM_NOREMOVE)) if (next.message == WM_KEYDOWN || next.message == WM_SYSKEYDOWN || next.message == WM_KEYUP || next.message == WM_SYSKEYUP) if (next.wParam == VK_MENU && (next.lParam & 0x01000000) && next.time == time) return KB_KEY_UNKNOWN; return KB_KEY_LEFT_CONTROL; } if (wParam == VK_PROCESSKEY) return KB_KEY_UNKNOWN; return (mfb_key) g_keycodes[HIWORD(lParam) & 0x1FF]; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool mfb_set_viewport(struct mfb_window *window, unsigned offset_x, unsigned offset_y, unsigned width, unsigned height) { SWindowData *window_data = (SWindowData *) window; SWindowData_Win *window_data_win = 0x0; float scale_x, scale_y; if(window_data == 0x0) { return false; } if (offset_x + width > window_data->window_width) { return false; } if (offset_y + height > window_data->window_height) { return false; } window_data_win = (SWindowData_Win *) window_data->specific; get_monitor_scale(window_data_win->window, &scale_x, &scale_y); window_data->dst_offset_x = (uint32_t) (offset_x * scale_x); window_data->dst_offset_y = (uint32_t) (offset_y * scale_y); window_data->dst_width = (uint32_t) (width * scale_x); window_data->dst_height = (uint32_t) (height * scale_y); calc_dst_factor(window_data, window_data->window_width, window_data->window_height); #if !defined(USE_OPENGL_API) window_data_win = (SWindowData_Win *) window_data->specific; BitBlt(window_data_win->hdc, 0, 0, window_data->window_width, window_data->window_height, 0, 0, 0, BLACKNESS); #endif return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// extern double g_timer_frequency; extern double g_timer_resolution; uint64_t mfb_timer_tick() { int64_t counter; QueryPerformanceCounter((LARGE_INTEGER *) &counter); return counter; } void mfb_timer_init() { uint64_t frequency; QueryPerformanceFrequency((LARGE_INTEGER *) &frequency); g_timer_frequency = (double) ((int64_t) frequency); g_timer_resolution = 1.0 / g_timer_frequency; }
03402edba951a9ed6aa5e8c77c740069bfbbdd9f
988e8b511c965f2be69b1cbc56983772e587af60
/ext/ruby_fann/fann_data.h
f5768319ad5ff77a43ad2bddba550f33ee3e8fd7
[ "MIT" ]
permissive
tangledpath/ruby-fann
7145dc56c13a2c8395e54b926991725f0c1fbaa5
ccfada03ed7c64075b0c535f3a537367b6e9f788
refs/heads/master
2023-09-06T01:07:09.958039
2023-08-15T01:43:34
2023-08-15T01:43:34
9,036,378
370
44
MIT
2023-08-14T21:59:45
2013-03-26T17:44:46
C
UTF-8
C
false
false
26,039
h
fann_data.h
/* Fast Artificial Neural Network Library (fann) Copyright (C) 2003-2012 Steffen Nissen (sn@leenissen.dk) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __fann_data_h__ #define __fann_data_h__ #include <stdio.h> /* Section: FANN Datatypes The two main datatypes used in the fann library is <struct fann>, which represents an artificial neural network, and <struct fann_train_data>, which represent training data. */ /* Type: fann_type fann_type is the type used for the weights, inputs and outputs of the neural network. fann_type is defined as a: float - if you include fann.h or floatfann.h double - if you include doublefann.h int - if you include fixedfann.h (please be aware that fixed point usage is only to be used during execution, and not during training). */ /* Enum: fann_train_enum The Training algorithms used when training on <struct fann_train_data> with functions like <fann_train_on_data> or <fann_train_on_file>. The incremental training looks alters the weights after each time it is presented an input pattern, while batch only alters the weights once after it has been presented to all the patterns. FANN_TRAIN_INCREMENTAL - Standard backpropagation algorithm, where the weights are updated after each training pattern. This means that the weights are updated many times during a single epoch. For this reason some problems, will train very fast with this algorithm, while other more advanced problems will not train very well. FANN_TRAIN_BATCH - Standard backpropagation algorithm, where the weights are updated after calculating the mean square error for the whole training set. This means that the weights are only updated once during a epoch. For this reason some problems, will train slower with this algorithm. But since the mean square error is calculated more correctly than in incremental training, some problems will reach a better solutions with this algorithm. FANN_TRAIN_RPROP - A more advanced batch training algorithm which achieves good results for many problems. The RPROP training algorithm is adaptive, and does therefore not use the learning_rate. Some other parameters can however be set to change the way the RPROP algorithm works, but it is only recommended for users with insight in how the RPROP training algorithm works. The RPROP training algorithm is described by [Riedmiller and Braun, 1993], but the actual learning algorithm used here is the iRPROP- training algorithm which is described by [Igel and Husken, 2000] which is an variety of the standard RPROP training algorithm. FANN_TRAIN_QUICKPROP - A more advanced batch training algorithm which achieves good results for many problems. The quickprop training algorithm uses the learning_rate parameter along with other more advanced parameters, but it is only recommended to change these advanced parameters, for users with insight in how the quickprop training algorithm works. The quickprop training algorithm is described by [Fahlman, 1988]. See also: <fann_set_training_algorithm>, <fann_get_training_algorithm> */ enum fann_train_enum { FANN_TRAIN_INCREMENTAL = 0, FANN_TRAIN_BATCH, FANN_TRAIN_RPROP, FANN_TRAIN_QUICKPROP, FANN_TRAIN_SARPROP }; /* Constant: FANN_TRAIN_NAMES Constant array consisting of the names for the training algorithms, so that the name of an training function can be received by: (code) char *name = FANN_TRAIN_NAMES[train_function]; (end) See Also: <fann_train_enum> */ static char const *const FANN_TRAIN_NAMES[] = { "FANN_TRAIN_INCREMENTAL", "FANN_TRAIN_BATCH", "FANN_TRAIN_RPROP", "FANN_TRAIN_QUICKPROP", "FANN_TRAIN_SARPROP" }; /* Enums: fann_activationfunc_enum The activation functions used for the neurons during training. The activation functions can either be defined for a group of neurons by <fann_set_activation_function_hidden> and <fann_set_activation_function_output> or it can be defined for a single neuron by <fann_set_activation_function>. The steepness of an activation function is defined in the same way by <fann_set_activation_steepness_hidden>, <fann_set_activation_steepness_output> and <fann_set_activation_steepness>. The functions are described with functions where: * x is the input to the activation function, * y is the output, * s is the steepness and * d is the derivation. FANN_LINEAR - Linear activation function. * span: -inf < y < inf * y = x*s, d = 1*s * Can NOT be used in fixed point. FANN_THRESHOLD - Threshold activation function. * x < 0 -> y = 0, x >= 0 -> y = 1 * Can NOT be used during training. FANN_THRESHOLD_SYMMETRIC - Threshold activation function. * x < 0 -> y = 0, x >= 0 -> y = 1 * Can NOT be used during training. FANN_SIGMOID - Sigmoid activation function. * One of the most used activation functions. * span: 0 < y < 1 * y = 1/(1 + exp(-2*s*x)) * d = 2*s*y*(1 - y) FANN_SIGMOID_STEPWISE - Stepwise linear approximation to sigmoid. * Faster than sigmoid but a bit less precise. FANN_SIGMOID_SYMMETRIC - Symmetric sigmoid activation function, aka. tanh. * One of the most used activation functions. * span: -1 < y < 1 * y = tanh(s*x) = 2/(1 + exp(-2*s*x)) - 1 * d = s*(1-(y*y)) FANN_SIGMOID_SYMMETRIC - Stepwise linear approximation to symmetric sigmoid. * Faster than symmetric sigmoid but a bit less precise. FANN_GAUSSIAN - Gaussian activation function. * 0 when x = -inf, 1 when x = 0 and 0 when x = inf * span: 0 < y < 1 * y = exp(-x*s*x*s) * d = -2*x*s*y*s FANN_GAUSSIAN_SYMMETRIC - Symmetric gaussian activation function. * -1 when x = -inf, 1 when x = 0 and 0 when x = inf * span: -1 < y < 1 * y = exp(-x*s*x*s)*2-1 * d = -2*x*s*(y+1)*s FANN_ELLIOT - Fast (sigmoid like) activation function defined by David Elliott * span: 0 < y < 1 * y = ((x*s) / 2) / (1 + |x*s|) + 0.5 * d = s*1/(2*(1+|x*s|)*(1+|x*s|)) FANN_ELLIOT_SYMMETRIC - Fast (symmetric sigmoid like) activation function defined by David Elliott * span: -1 < y < 1 * y = (x*s) / (1 + |x*s|) * d = s*1/((1+|x*s|)*(1+|x*s|)) FANN_LINEAR_PIECE - Bounded linear activation function. * span: 0 <= y <= 1 * y = x*s, d = 1*s FANN_LINEAR_PIECE_SYMMETRIC - Bounded linear activation function. * span: -1 <= y <= 1 * y = x*s, d = 1*s FANN_SIN_SYMMETRIC - Periodical sinus activation function. * span: -1 <= y <= 1 * y = sin(x*s) * d = s*cos(x*s) FANN_COS_SYMMETRIC - Periodical cosinus activation function. * span: -1 <= y <= 1 * y = cos(x*s) * d = s*-sin(x*s) FANN_SIN - Periodical sinus activation function. * span: 0 <= y <= 1 * y = sin(x*s)/2+0.5 * d = s*cos(x*s)/2 FANN_COS - Periodical cosinus activation function. * span: 0 <= y <= 1 * y = cos(x*s)/2+0.5 * d = s*-sin(x*s)/2 See also: <fann_set_activation_function_layer>, <fann_set_activation_function_hidden>, <fann_set_activation_function_output>, <fann_set_activation_steepness>, <fann_set_activation_function> */ enum fann_activationfunc_enum { FANN_LINEAR = 0, FANN_THRESHOLD, FANN_THRESHOLD_SYMMETRIC, FANN_SIGMOID, FANN_SIGMOID_STEPWISE, FANN_SIGMOID_SYMMETRIC, FANN_SIGMOID_SYMMETRIC_STEPWISE, FANN_GAUSSIAN, FANN_GAUSSIAN_SYMMETRIC, /* Stepwise linear approximation to gaussian. * Faster than gaussian but a bit less precise. * NOT implemented yet. */ FANN_GAUSSIAN_STEPWISE, FANN_ELLIOT, FANN_ELLIOT_SYMMETRIC, FANN_LINEAR_PIECE, FANN_LINEAR_PIECE_SYMMETRIC, FANN_SIN_SYMMETRIC, FANN_COS_SYMMETRIC, FANN_SIN, FANN_COS }; /* Constant: FANN_ACTIVATIONFUNC_NAMES Constant array consisting of the names for the activation function, so that the name of an activation function can be received by: (code) char *name = FANN_ACTIVATIONFUNC_NAMES[activation_function]; (end) See Also: <fann_activationfunc_enum> */ static char const *const FANN_ACTIVATIONFUNC_NAMES[] = { "FANN_LINEAR", "FANN_THRESHOLD", "FANN_THRESHOLD_SYMMETRIC", "FANN_SIGMOID", "FANN_SIGMOID_STEPWISE", "FANN_SIGMOID_SYMMETRIC", "FANN_SIGMOID_SYMMETRIC_STEPWISE", "FANN_GAUSSIAN", "FANN_GAUSSIAN_SYMMETRIC", "FANN_GAUSSIAN_STEPWISE", "FANN_ELLIOT", "FANN_ELLIOT_SYMMETRIC", "FANN_LINEAR_PIECE", "FANN_LINEAR_PIECE_SYMMETRIC", "FANN_SIN_SYMMETRIC", "FANN_COS_SYMMETRIC", "FANN_SIN", "FANN_COS" }; /* Enum: fann_errorfunc_enum Error function used during training. FANN_ERRORFUNC_LINEAR - Standard linear error function. FANN_ERRORFUNC_TANH - Tanh error function, usually better but can require a lower learning rate. This error function agressively targets outputs that differ much from the desired, while not targetting outputs that only differ a little that much. This activation function is not recommended for cascade training and incremental training. See also: <fann_set_train_error_function>, <fann_get_train_error_function> */ enum fann_errorfunc_enum { FANN_ERRORFUNC_LINEAR = 0, FANN_ERRORFUNC_TANH }; /* Constant: FANN_ERRORFUNC_NAMES Constant array consisting of the names for the training error functions, so that the name of an error function can be received by: (code) char *name = FANN_ERRORFUNC_NAMES[error_function]; (end) See Also: <fann_errorfunc_enum> */ static char const *const FANN_ERRORFUNC_NAMES[] = { "FANN_ERRORFUNC_LINEAR", "FANN_ERRORFUNC_TANH" }; /* Enum: fann_stopfunc_enum Stop criteria used during training. FANN_STOPFUNC_MSE - Stop criteria is Mean Square Error (MSE) value. FANN_STOPFUNC_BIT - Stop criteria is number of bits that fail. The number of bits; means the number of output neurons which differ more than the bit fail limit (see <fann_get_bit_fail_limit>, <fann_set_bit_fail_limit>). The bits are counted in all of the training data, so this number can be higher than the number of training data. See also: <fann_set_train_stop_function>, <fann_get_train_stop_function> */ enum fann_stopfunc_enum { FANN_STOPFUNC_MSE = 0, FANN_STOPFUNC_BIT }; /* Constant: FANN_STOPFUNC_NAMES Constant array consisting of the names for the training stop functions, so that the name of a stop function can be received by: (code) char *name = FANN_STOPFUNC_NAMES[stop_function]; (end) See Also: <fann_stopfunc_enum> */ static char const *const FANN_STOPFUNC_NAMES[] = { "FANN_STOPFUNC_MSE", "FANN_STOPFUNC_BIT" }; /* Enum: fann_network_type_enum Definition of network types used by <fann_get_network_type> FANN_NETTYPE_LAYER - Each layer only has connections to the next layer FANN_NETTYPE_SHORTCUT - Each layer has connections to all following layers See Also: <fann_get_network_type> This enumeration appears in FANN >= 2.1.0 */ enum fann_nettype_enum { FANN_NETTYPE_LAYER = 0, /* Each layer only has connections to the next layer */ FANN_NETTYPE_SHORTCUT /* Each layer has connections to all following layers */ }; /* Constant: FANN_NETWORK_TYPE_NAMES Constant array consisting of the names for the network types, so that the name of an network type can be received by: (code) char *network_type_name = FANN_NETWORK_TYPE_NAMES[fann_get_network_type(ann)]; (end) See Also: <fann_get_network_type> This constant appears in FANN >= 2.1.0 */ static char const *const FANN_NETTYPE_NAMES[] = { "FANN_NETTYPE_LAYER", "FANN_NETTYPE_SHORTCUT" }; /* forward declarations for use with the callback */ struct fann; struct fann_train_data; /* Type: fann_callback_type This callback function can be called during training when using <fann_train_on_data>, <fann_train_on_file> or <fann_cascadetrain_on_data>. >typedef int (FANN_API * fann_callback_type) (struct fann *ann, struct fann_train_data *train, > unsigned int max_epochs, > unsigned int epochs_between_reports, > float desired_error, unsigned int epochs); The callback can be set by using <fann_set_callback> and is very usefull for doing custom things during training. It is recommended to use this function when implementing custom training procedures, or when visualizing the training in a GUI etc. The parameters which the callback function takes is the parameters given to the <fann_train_on_data>, plus an epochs parameter which tells how many epochs the training have taken so far. The callback function should return an integer, if the callback function returns -1, the training will terminate. Example of a callback function: >int FANN_API test_callback(struct fann *ann, struct fann_train_data *train, > unsigned int max_epochs, unsigned int epochs_between_reports, > float desired_error, unsigned int epochs) >{ > printf("Epochs %8d. MSE: %.5f. Desired-MSE: %.5f\n", epochs, fann_get_MSE(ann), desired_error); > return 0; >} See also: <fann_set_callback>, <fann_train_on_data> */ FANN_EXTERNAL typedef int (FANN_API * fann_callback_type) (struct fann *ann, struct fann_train_data *train, unsigned int max_epochs, unsigned int epochs_between_reports, float desired_error, unsigned int epochs); /* ----- Data structures ----- * No data within these structures should be altered directly by the user. */ struct fann_neuron { /* Index to the first and last connection * (actually the last is a past end index) */ long first_con; long last_con; /* The sum of the inputs multiplied with the weights */ fann_type sum; /* The value of the activation function applied to the sum */ fann_type value; /* The steepness of the activation function */ fann_type activation_steepness; /* Used to choose which activation function to use */ enum fann_activationfunc_enum activation_function; #ifdef __GNUC__ } __attribute__ ((packed)); #else }; #endif /* A single layer in the neural network. */ struct fann_layer { /* A pointer to the first neuron in the layer * When allocated, all the neurons in all the layers are actually * in one long array, this is because we wan't to easily clear all * the neurons at once. */ struct fann_neuron *first_neuron; /* A pointer to the neuron past the last neuron in the layer */ /* the number of neurons is last_neuron - first_neuron */ struct fann_neuron *last_neuron; }; /* Struct: struct fann_error Structure used to store error-related information, both <struct fann> and <struct fann_train_data> can be casted to this type. See also: <fann_set_error_log>, <fann_get_errno> */ struct fann_error { enum fann_errno_enum errno_f; FILE *error_log; char *errstr; }; /* Struct: struct fann The fast artificial neural network(fann) structure. Data within this structure should never be accessed directly, but only by using the *fann_get_...* and *fann_set_...* functions. The fann structure is created using one of the *fann_create_...* functions and each of the functions which operates on the structure takes *struct fann * ann* as the first parameter. See also: <fann_create_standard>, <fann_destroy> */ struct fann { /* The type of error that last occured. */ enum fann_errno_enum errno_f; /* Where to log error messages. */ FILE *error_log; /* A string representation of the last error. */ char *errstr; /* the learning rate of the network */ float learning_rate; /* The learning momentum used for backpropagation algorithm. */ float learning_momentum; /* the connection rate of the network * between 0 and 1, 1 meaning fully connected */ float connection_rate; /* is 1 if shortcut connections are used in the ann otherwise 0 * Shortcut connections are connections that skip layers. * A fully connected ann with shortcut connections are a ann where * neurons have connections to all neurons in all later layers. */ enum fann_nettype_enum network_type; /* pointer to the first layer (input layer) in an array af all the layers, * including the input and outputlayers */ struct fann_layer *first_layer; /* pointer to the layer past the last layer in an array af all the layers, * including the input and outputlayers */ struct fann_layer *last_layer; /* Total number of neurons. * very usefull, because the actual neurons are allocated in one long array */ unsigned int total_neurons; /* Number of input neurons (not calculating bias) */ unsigned int num_input; /* Number of output neurons (not calculating bias) */ unsigned int num_output; /* The weight array */ fann_type *weights; /* The connection array */ struct fann_neuron **connections; /* Used to contain the errors used during training * Is allocated during first training session, * which means that if we do not train, it is never allocated. */ fann_type *train_errors; /* Training algorithm used when calling fann_train_on_.. */ enum fann_train_enum training_algorithm; #ifdef FIXEDFANN /* the decimal_point, used for shifting the fix point * in fixed point integer operatons. */ unsigned int decimal_point; /* the multiplier, used for multiplying the fix point * in fixed point integer operatons. * Only used in special cases, since the decimal_point is much faster. */ unsigned int multiplier; /* When in choosen (or in fixed point), the sigmoid function is * calculated as a stepwise linear function. In the * activation_results array, the result is saved, and in the * two values arrays, the values that gives the results are saved. */ fann_type sigmoid_results[6]; fann_type sigmoid_values[6]; fann_type sigmoid_symmetric_results[6]; fann_type sigmoid_symmetric_values[6]; #endif /* Total number of connections. * very usefull, because the actual connections * are allocated in one long array */ unsigned int total_connections; /* used to store outputs in */ fann_type *output; /* the number of data used to calculate the mean square error. */ unsigned int num_MSE; /* the total error value. * the real mean square error is MSE_value/num_MSE */ float MSE_value; /* The number of outputs which would fail (only valid for classification problems) */ unsigned int num_bit_fail; /* The maximum difference between the actual output and the expected output * which is accepted when counting the bit fails. * This difference is multiplied by two when dealing with symmetric activation functions, * so that symmetric and not symmetric activation functions can use the same limit. */ fann_type bit_fail_limit; /* The error function used during training. (default FANN_ERRORFUNC_TANH) */ enum fann_errorfunc_enum train_error_function; /* The stop function used during training. (default FANN_STOPFUNC_MSE) */ enum fann_stopfunc_enum train_stop_function; /* The callback function used during training. (default NULL) */ fann_callback_type callback; /* A pointer to user defined data. (default NULL) */ void *user_data; /* Variables for use with Cascade Correlation */ /* The error must change by at least this * fraction of its old value to count as a * significant change. */ float cascade_output_change_fraction; /* No change in this number of epochs will cause * stagnation. */ unsigned int cascade_output_stagnation_epochs; /* The error must change by at least this * fraction of its old value to count as a * significant change. */ float cascade_candidate_change_fraction; /* No change in this number of epochs will cause * stagnation. */ unsigned int cascade_candidate_stagnation_epochs; /* The current best candidate, which will be installed. */ unsigned int cascade_best_candidate; /* The upper limit for a candidate score */ fann_type cascade_candidate_limit; /* Scale of copied candidate output weights */ fann_type cascade_weight_multiplier; /* Maximum epochs to train the output neurons during cascade training */ unsigned int cascade_max_out_epochs; /* Maximum epochs to train the candidate neurons during cascade training */ unsigned int cascade_max_cand_epochs; /* Minimum epochs to train the output neurons during cascade training */ unsigned int cascade_min_out_epochs; /* Minimum epochs to train the candidate neurons during cascade training */ unsigned int cascade_min_cand_epochs; /* An array consisting of the activation functions used when doing * cascade training. */ enum fann_activationfunc_enum *cascade_activation_functions; /* The number of elements in the cascade_activation_functions array. */ unsigned int cascade_activation_functions_count; /* An array consisting of the steepnesses used during cascade training. */ fann_type *cascade_activation_steepnesses; /* The number of elements in the cascade_activation_steepnesses array. */ unsigned int cascade_activation_steepnesses_count; /* The number of candidates of each type that will be present. * The actual number of candidates is then * cascade_activation_functions_count * * cascade_activation_steepnesses_count * * cascade_num_candidate_groups */ unsigned int cascade_num_candidate_groups; /* An array consisting of the score of the individual candidates, * which is used to decide which candidate is the best */ fann_type *cascade_candidate_scores; /* The number of allocated neurons during cascade correlation algorithms. * This number might be higher than the actual number of neurons to avoid * allocating new space too often. */ unsigned int total_neurons_allocated; /* The number of allocated connections during cascade correlation algorithms. * This number might be higher than the actual number of neurons to avoid * allocating new space too often. */ unsigned int total_connections_allocated; /* Variables for use with Quickprop training */ /* Decay is used to make the weights not go so high */ float quickprop_decay; /* Mu is a factor used to increase and decrease the stepsize */ float quickprop_mu; /* Variables for use with with RPROP training */ /* Tells how much the stepsize should increase during learning */ float rprop_increase_factor; /* Tells how much the stepsize should decrease during learning */ float rprop_decrease_factor; /* The minimum stepsize */ float rprop_delta_min; /* The maximum stepsize */ float rprop_delta_max; /* The initial stepsize */ float rprop_delta_zero; /* Defines how much the weights are constrained to smaller values at the beginning */ float sarprop_weight_decay_shift; /* Decides if the stepsize is too big with regard to the error */ float sarprop_step_error_threshold_factor; /* Defines how much the stepsize is influenced by the error */ float sarprop_step_error_shift; /* Defines how much the epoch influences weight decay and noise */ float sarprop_temperature; /* Current training epoch */ unsigned int sarprop_epoch; /* Used to contain the slope errors used during batch training * Is allocated during first training session, * which means that if we do not train, it is never allocated. */ fann_type *train_slopes; /* The previous step taken by the quickprop/rprop procedures. * Not allocated if not used. */ fann_type *prev_steps; /* The slope values used by the quickprop/rprop procedures. * Not allocated if not used. */ fann_type *prev_train_slopes; /* The last delta applied to a connection weight. * This is used for the momentum term in the backpropagation algorithm. * Not allocated if not used. */ fann_type *prev_weights_deltas; #ifndef FIXEDFANN /* Arithmetic mean used to remove steady component in input data. */ float *scale_mean_in; /* Standart deviation used to normalize input data (mostly to [-1;1]). */ float *scale_deviation_in; /* User-defined new minimum for input data. * Resulting data values may be less than user-defined minimum. */ float *scale_new_min_in; /* Used to scale data to user-defined new maximum for input data. * Resulting data values may be greater than user-defined maximum. */ float *scale_factor_in; /* Arithmetic mean used to remove steady component in output data. */ float *scale_mean_out; /* Standart deviation used to normalize output data (mostly to [-1;1]). */ float *scale_deviation_out; /* User-defined new minimum for output data. * Resulting data values may be less than user-defined minimum. */ float *scale_new_min_out; /* Used to scale data to user-defined new maximum for output data. * Resulting data values may be greater than user-defined maximum. */ float *scale_factor_out; #endif }; /* Type: fann_connection Describes a connection between two neurons and its weight from_neuron - Unique number used to identify source neuron to_neuron - Unique number used to identify destination neuron weight - The numerical value of the weight See Also: <fann_get_connection_array>, <fann_set_weight_array> This structure appears in FANN >= 2.1.0 */ struct fann_connection { /* Unique number used to identify source neuron */ unsigned int from_neuron; /* Unique number used to identify destination neuron */ unsigned int to_neuron; /* The numerical value of the weight */ fann_type weight; }; #endif
71b7a80ba35a895b4fb8797b61d5cd30e4a4d315
03666e5f961946fc1a0ac67781ac1425562ef0d7
/src/operators/MultiresControl/QvisMultiresControlWindow.C
f9dd84f811d84efe51de367ac8a72aa0880b32cd
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
visit-dav/visit
e9f81b4d4b9b9930a0db9d5282cd1bcabf465e2e
601ae46e0bef2e18425b482a755d03490ade0493
refs/heads/develop
2023-09-06T08:19:38.397058
2023-09-05T21:29:32
2023-09-05T21:29:32
165,565,988
335
120
BSD-3-Clause
2023-09-14T00:53:37
2019-01-13T23:27:26
C
UTF-8
C
false
false
7,289
c
QvisMultiresControlWindow.C
// Copyright (c) Lawrence Livermore National Security, LLC and other VisIt // Project developers. See the top-level LICENSE file for dates and other // details. No copyright assignment is required to contribute to VisIt. #include <algorithm> #include <QApplication> #include <QLabel> #include <QGridLayout> #include <QSlider> #include "QvisMultiresControlWindow.h" #include <DebugStream.h> #include <FileServerList.h> #include <MultiresControlAttributes.h> // **************************************************************************** // Method: QvisMultiresControlWindow::QvisMultiresControlWindow // // Purpose: // Constructor // // Note: Autogenerated by xml2window. // // Programmer: xml2window // Creation: omitted // // Modifications: // // **************************************************************************** QvisMultiresControlWindow::QvisMultiresControlWindow(const int type, MultiresControlAttributes *subj, const QString &caption, const QString &shortName, QvisNotepadArea *notepad) : QvisOperatorWindow(type,subj, caption, shortName, notepad), resolution(NULL), resolutionLevelLabel(NULL) { atts = subj; fileServer->Attach(this); } // **************************************************************************** // Method: QvisMultiresControlWindow::~QvisMultiresControlWindow // // Purpose: // Destructor // // Note: Autogenerated by xml2window. // // Programmer: xml2window // Creation: omitted // // Modifications: // // **************************************************************************** QvisMultiresControlWindow::~QvisMultiresControlWindow() { if(fileServer) { fileServer->Detach(this); } } // **************************************************************************** // Method: QvisMultiresControlWindow::CreateWindowContents // // Purpose: // Creates the widgets for the window. // // Note: Autogenerated by xml2window. // // Programmer: xml2window // Creation: omitted // // Modifications: // // Tom Fogal, Mon Aug 30 12:30:54 MDT 2010 // Add resolution # to label. // // Brad Whitlock, Wed Sep 2 17:54:16 PDT 2020 // Use valueChanged to set the label text. Use sliderReleased to update the // multires value. This makes autoupdate work better. // // **************************************************************************** void QvisMultiresControlWindow::CreateWindowContents() { QGridLayout *mainLayout = new QGridLayout(NULL); topLayout->addLayout(mainLayout); resolutionLevelLabel = new QLabel(this); mainLayout->addWidget(resolutionLevelLabel,0,0); UpdateLabelText(0); this->resolution = new QSlider(Qt::Horizontal, this); this->resolution->setMaximum(32); // HACK, we don't know yet. this->resolution->setValue(0); mainLayout->addWidget(this->resolution, 0, 1); connect(this->resolution, SIGNAL(valueChanged(int)), this, SLOT(updateResolutionLevelLabel(int))); connect(this->resolution, SIGNAL(sliderReleased()), this, SLOT(resolutionLevelChanged())); } // **************************************************************************** // Method: QvisMultiresControlWindow::UpdateWindow // // Purpose: // Updates the widgets in the window when the subject changes. // // Note: Autogenerated by xml2window. // // Programmer: xml2window // Creation: omitted // // Modifications: // // Tom Fogal, Mon Aug 30 12:30:28 MDT 2010 // Include resolution # in label. // // **************************************************************************** void QvisMultiresControlWindow::UpdateWindow(bool doAll) { QString temp; if(fileServer) { const avtDatabaseMetaData *md = fileServer->GetMetaData( fileServer->GetOpenFile(), GetStateForSource(fileServer->GetOpenFile()), true, true ); if(md && md->GetNumMeshes() != 0) { const avtMeshMetaData* mmd = md->GetMesh(0); debug3 << "Mesh says there are " << mmd->LODs << " levels of detail.\n"; atts->SetMaxResolution(mmd->LODs); } } else { debug1 << "No file server, bailing...\n"; } debug1 << atts->GetMaxResolution() << " levels of detail available.\n"; this->resolution->blockSignals(true); this->resolution->setValue(atts->GetResolution()); this->resolution->setMaximum(std::max(0, atts->GetMaxResolution())); this->resolution->blockSignals(false); this->resolution->update(); UpdateLabelText(atts->GetResolution()); // set it back to its default background color. QPalette p = QApplication::palette(); this->resolutionLevelLabel->setPalette(p); } // **************************************************************************** // Method: QvisMultiresControlWindow::GetCurrentValues // // Purpose: // Gets values from certain widgets and stores them in the subject. // // Note: Autogenerated by xml2window. // // Programmer: xml2window // Creation: omitted // // Modifications: // // **************************************************************************** void QvisMultiresControlWindow::GetCurrentValues(int which_widget) { bool doAll = (which_widget == -1); QString msg, temp; // Do resolution if(which_widget == MultiresControlAttributes::ID_resolution || doAll) { atts->SetResolution(this->resolution->value()); } } // **************************************************************************** // Method: QvisMultiresControlWindow::UpdateLabelText // // Purpose: // Update the resolution label text. // // Arguments: // value : The value we want to put into the text. // // Returns: // // Note: // // Programmer: Brad Whitlock // Creation: Wed Sep 2 18:28:45 PDT 2020 // // Modifications: // // **************************************************************************** void QvisMultiresControlWindow::UpdateLabelText(int value) { // Adjust padding so the width does not change so much that the slider moves // because the label changed sizes. QString res, space(" "); res.setNum(value); if(value < 100) res = space + res; if(value < 10) res = space + res; resolutionLevelLabel->setText(tr("Resolution: %1").arg(res)); } // // Qt Slot functions // // Modificatons: // // Tom Fogal, Mon Aug 30 12:52:36 MDT 2010 // Change resolution label as well. // // Brad Whitlock, Wed Sep 2 18:07:03 PDT 2020 // Only set the label values here. void QvisMultiresControlWindow::updateResolutionLevelLabel(int val) { if(val != atts->GetResolution()) { UpdateLabelText(val); resolutionLevelLabel->setAutoFillBackground(true); // Change the text color to indicate there would be unapplied changes. QPalette p; p.setColor(QPalette::WindowText, QColor(0,228,0)); resolutionLevelLabel->setPalette(p); } } void QvisMultiresControlWindow::resolutionLevelChanged() { int val = resolution->value(); if(val != atts->GetResolution()) { UpdateLabelText(val); atts->SetResolution(val); SetUpdate(false); Apply(); } }
33ea81575863d9bef5feddaa143aba820f68e7ce
cff4428975e403e4ef02d75498b78cd1a610a01a
/src/box/func_cache.h
fc34832b489a7f39dc08842fcf3d4622f9e1d371
[ "BSD-2-Clause" ]
permissive
tarantool/tarantool
c1f252b642d223af62485dc21165c7f7c3354e7e
f58cc96f2798ddc5f492223897d0b77e4f902128
refs/heads/master
2023-09-03T15:16:29.144171
2023-08-31T11:39:28
2023-09-01T12:39:29
911,980
3,205
490
NOASSERTION
2023-09-14T17:58:17
2010-09-15T07:59:26
Lua
UTF-8
C
false
false
3,085
h
func_cache.h
/* * SPDX-License-Identifier: BSD-2-Clause * * Copyright 2010-2021, Tarantool AUTHORS, please see AUTHORS file. */ #pragma once #include <stdint.h> #include "func.h" #if defined(__cplusplus) extern "C" { #endif /* defined(__cplusplus) */ struct func; /** * Type of a holder that can pin a func. @sa struct func_cache_holder. */ enum func_holder_type { FUNC_HOLDER_CONSTRAINT, FUNC_HOLDER_SPACE_UPGRADE, FUNC_HOLDER_FIELD_DEFAULT, FUNC_HOLDER_MAX, }; /** * Lowercase name of each type. */ extern const char *func_cache_holder_type_strs[FUNC_HOLDER_MAX]; /** * Definition of a holder that pinned some func. Pinning of a func is * a mechanism that is designed for preventing of deletion of some func from * func cache by storing links to holders that prevented that. */ struct func_cache_holder { /** Holders of the same func are linked into ring list by this link. */ struct rlist link; /** Actual pointer to func. */ struct func *func; /** * Type of holder, mostly for better error generation, but also can be * used for proper container_of application. */ enum func_holder_type type; }; /** * Initialize function cache storage. */ void func_cache_init(void); /** * Cleanup function cache storage. */ void func_cache_destroy(void); /** * Insert a new function object in the function cache. * @param func Function object to insert. */ void func_cache_insert(struct func *func); /** * Delete a function object from the function cache. * The function must not have any keepers (assert, @sa func_cache_is_kept), * so if there is no assurance that there are no pins, @sa func_cache_is_pinned * must be called before. * If the function is not found by five ID - do nothing. * @param fid ID of function object. */ void func_cache_delete(uint32_t fid); /** * Find function by ID or return NULL if not found. * @param fid ID of function object. */ struct func * func_by_id(uint32_t fid); /** * Find function by name or return NULL if not found. * @param name Name of function object. * @param name_len Length of the name of function object. */ struct func * func_by_name(const char *name, uint32_t name_len); /** * Register that there is a @a holder of type @a type that is dependent * on function @a func. * The function must be in cache (asserted). * If a function has holders, it must not be deleted (asserted). */ void func_pin(struct func *func, struct func_cache_holder *holder, enum func_holder_type type); /** * Notify that a @a holder does not depend anymore on function. * The function must be in cache (asserted). * If a function has no holders, it can be deleted. */ void func_unpin(struct func_cache_holder *holder); /** * Check whether the function @a func has holders or not. * If it has, @a type argument is set to the first holder's type. * The function must be in cache (asserted). * If a function has holders, it must not be deleted (asserted). */ bool func_is_pinned(struct func *func, enum func_holder_type *type); #if defined(__cplusplus) } /* extern "C" */ #endif /* defined(__cplusplus) */
81c99f455c88f7f07f500a08e4fb0c88903e3868
f9e7d65cb784c01a0200145ba8d289afe41d4a56
/board/casta/board.c
e1d7630e3f076fb5deb5d37996d7688b12bc31ab
[ "BSD-3-Clause" ]
permissive
FrameworkComputer/EmbeddedController
ad7086769e87d0a4179eae96a7c9ff5e383ff54e
f6d6b927eed71550d3475411cfc3e59abe5cef2a
refs/heads/hx20-hx30
2023-08-08T20:45:10.621169
2023-05-26T07:03:59
2023-05-26T07:03:59
447,021,040
846
48
BSD-3-Clause
2023-05-26T07:04:59
2022-01-12T00:11:14
C
UTF-8
C
false
false
4,545
c
board.c
/* Copyright 2018 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /* Casta board-specific configuration */ #include "adc.h" #include "adc_chip.h" #include "battery.h" #include "charge_manager.h" #include "charge_state.h" #include "common.h" #include "cros_board_info.h" #include "driver/charger/bd9995x.h" #include "driver/ppc/nx20p348x.h" #include "driver/tcpm/anx7447.h" #include "driver/tcpm/ps8xxx.h" #include "driver/tcpm/tcpci.h" #include "driver/tcpm/tcpm.h" #include "extpower.h" #include "gpio.h" #include "hooks.h" #include "i2c.h" #include "keyboard_scan.h" #include "lid_switch.h" #include "power.h" #include "power_button.h" #include "switch.h" #include "system.h" #include "tcpci.h" #include "temp_sensor.h" #include "thermistor.h" #include "usb_mux.h" #include "usbc_ppc.h" #include "util.h" #define CPRINTSUSB(format, args...) cprints(CC_USBCHARGE, format, ## args) #define CPRINTFUSB(format, args...) cprintf(CC_USBCHARGE, format, ## args) #define CPRINTS(format, args...) cprints(CC_SYSTEM, format, ## args) static uint8_t sku_id; static void ppc_interrupt(enum gpio_signal signal) { switch (signal) { case GPIO_USB_PD_C0_INT_ODL: nx20p348x_interrupt(0); break; case GPIO_USB_PD_C1_INT_ODL: nx20p348x_interrupt(1); break; default: break; } } /* Must come after other header files and GPIO interrupts*/ #include "gpio_list.h" /* ADC channels */ const struct adc_t adc_channels[] = { [ADC_TEMP_SENSOR_AMB] = { "TEMP_AMB", NPCX_ADC_CH0, ADC_MAX_VOLT, ADC_READ_MAX+1, 0}, [ADC_TEMP_SENSOR_CHARGER] = { "TEMP_CHARGER", NPCX_ADC_CH1, ADC_MAX_VOLT, ADC_READ_MAX+1, 0}, }; BUILD_ASSERT(ARRAY_SIZE(adc_channels) == ADC_CH_COUNT); /* TODO(b/119872005): Casta: confirm thermistor parts */ const struct temp_sensor_t temp_sensors[] = { [TEMP_SENSOR_BATTERY] = {.name = "Battery", .type = TEMP_SENSOR_TYPE_BATTERY, .read = charge_get_battery_temp, .idx = 0}, [TEMP_SENSOR_AMBIENT] = {.name = "Ambient", .type = TEMP_SENSOR_TYPE_BOARD, .read = get_temp_3v3_51k1_47k_4050b, .idx = ADC_TEMP_SENSOR_AMB}, [TEMP_SENSOR_CHARGER] = {.name = "Charger", .type = TEMP_SENSOR_TYPE_BOARD, .read = get_temp_3v3_13k7_47k_4050b, .idx = ADC_TEMP_SENSOR_CHARGER}, }; BUILD_ASSERT(ARRAY_SIZE(temp_sensors) == TEMP_SENSOR_COUNT); /* * I2C callbacks to ensure bus free time for battery I2C transactions is at * least 5ms. */ #define BATTERY_FREE_MIN_DELTA_US (5 * MSEC) static timestamp_t battery_last_i2c_time; static int is_battery_i2c(const int port, const uint16_t slave_addr_flags) { return (port == I2C_PORT_BATTERY) && (slave_addr_flags == BATTERY_ADDR_FLAGS); } static int is_battery_port(int port) { return (port == I2C_PORT_BATTERY); } void i2c_start_xfer_notify(const int port, const uint16_t slave_addr_flags) { unsigned int time_delta_us; if (!is_battery_i2c(port, slave_addr_flags)) return; time_delta_us = time_since32(battery_last_i2c_time); if (time_delta_us >= BATTERY_FREE_MIN_DELTA_US) return; usleep(BATTERY_FREE_MIN_DELTA_US - time_delta_us); } void i2c_end_xfer_notify(const int port, const uint16_t slave_addr_flags) { /* * The bus free time needs to be maintained from last transaction * on I2C bus to any device on it to the next transaction to battery. */ if (!is_battery_port(port)) return; battery_last_i2c_time = get_time(); } /* Read CBI from i2c eeprom and initialize variables for board variants */ static void cbi_init(void) { uint32_t val; if (cbi_get_sku_id(&val) != EC_SUCCESS || val > UINT8_MAX) return; sku_id = val; CPRINTS("SKU: %d", sku_id); } DECLARE_HOOK(HOOK_INIT, cbi_init, HOOK_PRIO_INIT_I2C + 1); /* TODO: Casta: remove this routine after rev0 is not supported */ static void board_init(void) { uint32_t val; if (cbi_get_board_version(&val) == EC_SUCCESS && val > 0) return; gpio_set_flags(GPIO_USB_C0_MUX_INT_ODL, GPIO_INT_FALLING | GPIO_PULL_UP); } DECLARE_HOOK(HOOK_INIT, board_init, HOOK_PRIO_DEFAULT); void board_overcurrent_event(int port, int is_overcurrented) { /* Check that port number is valid. */ if ((port < 0) || (port >= CONFIG_USB_PD_PORT_MAX_COUNT)) return; /* Note that the level is inverted because the pin is active low. */ gpio_set_level(GPIO_USB_C_OC, !is_overcurrented); } __override uint8_t board_get_usb_pd_port_count(void) { if (sku_id == 2) return CONFIG_USB_PD_PORT_MAX_COUNT - 1; return CONFIG_USB_PD_PORT_MAX_COUNT; }
0fad4125e77471e39d7b694f04a000d7f56ee058
fbe68d84e97262d6d26dd65c704a7b50af2b3943
/third_party/virtualbox/src/VBox/Additions/x11/x11include/xorg-server-1.7.7/resource.h
8ed4e569ef538c19ee260599f8fa359e1d463e5c
[ "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
8,243
h
resource.h
/*********************************************************** Copyright 1987, 1989, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. 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 OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. Copyright 1987, 1989 by Digital Equipment Corporation, Maynard, Massachusetts. All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Digital not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ #ifndef RESOURCE_H #define RESOURCE_H 1 #include "misc.h" #include "dixaccess.h" /***************************************************************** * STUFF FOR RESOURCES *****************************************************************/ /* classes for Resource routines */ typedef unsigned long RESTYPE; #define RC_VANILLA ((RESTYPE)0) #define RC_CACHED ((RESTYPE)1<<31) #define RC_DRAWABLE ((RESTYPE)1<<30) /* Use class RC_NEVERRETAIN for resources that should not be retained * regardless of the close down mode when the client dies. (A client's * event selections on objects that it doesn't own are good candidates.) * Extensions can use this too! */ #define RC_NEVERRETAIN ((RESTYPE)1<<29) #define RC_LASTPREDEF RC_NEVERRETAIN #define RC_ANY (~(RESTYPE)0) /* types for Resource routines */ #define RT_WINDOW ((RESTYPE)1|RC_DRAWABLE) #define RT_PIXMAP ((RESTYPE)2|RC_DRAWABLE) #define RT_GC ((RESTYPE)3) #undef RT_FONT #undef RT_CURSOR #define RT_FONT ((RESTYPE)4) #define RT_CURSOR ((RESTYPE)5) #define RT_COLORMAP ((RESTYPE)6) #define RT_CMAPENTRY ((RESTYPE)7) #define RT_OTHERCLIENT ((RESTYPE)8|RC_NEVERRETAIN) #define RT_PASSIVEGRAB ((RESTYPE)9|RC_NEVERRETAIN) #define RT_LASTPREDEF ((RESTYPE)9) #define RT_NONE ((RESTYPE)0) /* bits and fields within a resource id */ #define RESOURCE_AND_CLIENT_COUNT 29 /* 29 bits for XIDs */ #if MAXCLIENTS == 64 #define RESOURCE_CLIENT_BITS 6 #endif #if MAXCLIENTS == 128 #define RESOURCE_CLIENT_BITS 7 #endif #if MAXCLIENTS == 256 #define RESOURCE_CLIENT_BITS 8 #endif #if MAXCLIENTS == 512 #define RESOURCE_CLIENT_BITS 9 #endif /* client field offset */ #define CLIENTOFFSET (RESOURCE_AND_CLIENT_COUNT - RESOURCE_CLIENT_BITS) /* resource field */ #define RESOURCE_ID_MASK ((1 << CLIENTOFFSET) - 1) /* client field */ #define RESOURCE_CLIENT_MASK (((1 << RESOURCE_CLIENT_BITS) - 1) << CLIENTOFFSET) /* extract the client mask from an XID */ #define CLIENT_BITS(id) ((id) & RESOURCE_CLIENT_MASK) /* extract the client id from an XID */ #define CLIENT_ID(id) ((int)(CLIENT_BITS(id) >> CLIENTOFFSET)) #define SERVER_BIT (Mask)0x40000000 /* use illegal bit */ #ifdef INVALID #undef INVALID /* needed on HP/UX */ #endif /* Invalid resource id */ #define INVALID (0) #define BAD_RESOURCE 0xe0000000 /* Resource state callback */ extern _X_EXPORT CallbackListPtr ResourceStateCallback; typedef enum {ResourceStateAdding, ResourceStateFreeing} ResourceState; typedef struct { ResourceState state; XID id; RESTYPE type; pointer value; } ResourceStateInfoRec; typedef int (*DeleteType)( pointer /*value*/, XID /*id*/); typedef void (*FindResType)( pointer /*value*/, XID /*id*/, pointer /*cdata*/); typedef void (*FindAllRes)( pointer /*value*/, XID /*id*/, RESTYPE /*type*/, pointer /*cdata*/); typedef Bool (*FindComplexResType)( pointer /*value*/, XID /*id*/, pointer /*cdata*/); extern _X_EXPORT RESTYPE CreateNewResourceType( DeleteType /*deleteFunc*/); extern _X_EXPORT RESTYPE CreateNewResourceClass(void); extern _X_EXPORT Bool InitClientResources( ClientPtr /*client*/); extern _X_EXPORT XID FakeClientID( int /*client*/); /* Quartz support on Mac OS X uses the CarbonCore framework whose AddResource function conflicts here. */ #ifdef __APPLE__ #define AddResource Darwin_X_AddResource #endif extern _X_EXPORT Bool AddResource( XID /*id*/, RESTYPE /*type*/, pointer /*value*/); extern _X_EXPORT void FreeResource( XID /*id*/, RESTYPE /*skipDeleteFuncType*/); extern _X_EXPORT void FreeResourceByType( XID /*id*/, RESTYPE /*type*/, Bool /*skipFree*/); extern _X_EXPORT Bool ChangeResourceValue( XID /*id*/, RESTYPE /*rtype*/, pointer /*value*/); extern _X_EXPORT void FindClientResourcesByType( ClientPtr /*client*/, RESTYPE /*type*/, FindResType /*func*/, pointer /*cdata*/); extern _X_EXPORT void FindAllClientResources( ClientPtr /*client*/, FindAllRes /*func*/, pointer /*cdata*/); extern _X_EXPORT void FreeClientNeverRetainResources( ClientPtr /*client*/); extern _X_EXPORT void FreeClientResources( ClientPtr /*client*/); extern _X_EXPORT void FreeAllResources(void); extern _X_EXPORT Bool LegalNewID( XID /*id*/, ClientPtr /*client*/); extern _X_EXPORT pointer LookupClientResourceComplex( ClientPtr client, RESTYPE type, FindComplexResType func, pointer cdata); extern _X_EXPORT int dixLookupResourceByType( pointer *result, XID id, RESTYPE rtype, ClientPtr client, Mask access_mode); extern _X_EXPORT int dixLookupResourceByClass( pointer *result, XID id, RESTYPE rclass, ClientPtr client, Mask access_mode); extern _X_EXPORT void GetXIDRange( int /*client*/, Bool /*server*/, XID * /*minp*/, XID * /*maxp*/); extern _X_EXPORT unsigned int GetXIDList( ClientPtr /*client*/, unsigned int /*count*/, XID * /*pids*/); extern _X_EXPORT RESTYPE lastResourceType; extern _X_EXPORT RESTYPE TypeMask; /* * These are deprecated compatibility functions and will be removed soon! * Please use the noted replacements instead. */ #ifdef __GNUC__ #define X_DEPRECATED __attribute__((deprecated)) #else #define X_DEPRECATED #endif /* replaced by dixLookupResourceByType */ extern _X_EXPORT pointer SecurityLookupIDByType( ClientPtr client, XID id, RESTYPE rtype, Mask access_mode) X_DEPRECATED; /* replaced by dixLookupResourceByClass */ extern _X_EXPORT pointer SecurityLookupIDByClass( ClientPtr client, XID id, RESTYPE classes, Mask access_mode) X_DEPRECATED; /* replaced by dixLookupResourceByType */ extern _X_EXPORT pointer LookupIDByType( XID id, RESTYPE rtype) X_DEPRECATED; /* replaced by dixLookupResourceByClass */ extern _X_EXPORT pointer LookupIDByClass( XID id, RESTYPE classes) X_DEPRECATED; #endif /* RESOURCE_H */
f0d43e44027824ac418896fbc89cab97139db562
799f8b6ff03e950162954b20d88b78880f3d07fc
/src/lib/XDither.c
18f2d837b4cbe2eea4e6ea206f487b9888fcf1dd
[]
no_license
fricas/fricas
7cd701887db04fa63da2e867a1fa6a147028fa74
8c99d3286abe4b583c9118d8461bc592724e43b6
refs/heads/master
2023-08-16T17:22:59.241544
2023-08-12T13:03:39
2023-08-12T13:03:39
19,549,841
266
51
null
2023-09-01T20:19:29
2014-05-07T20:47:48
null
UTF-8
C
false
false
6,241
c
XDither.c
/* Copyright (c) 1991-2002, The Numerical ALgorithms Group Ltd. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of The Numerical ALgorithms Group Ltd. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "fricas_c_macros.h" #include <stdio.h> #include <stdlib.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xos.h> #include <X11/cursorfont.h> #define XDitherWidth 3 #define XDitherMax 10 char XDitherBits[] = { 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x02, 0x00, 0x07, 0x02, 0x04, 0x07, 0x02, 0x04, 0x07, 0x03, 0x05, 0x07, 0x03, 0x05, 0x07, 0x07, 0x07, 0x07, 0x07 }; #include "XDither.H1" Pixmap XDither[XDitherMax]; unsigned int DITHERINIT = 0; /* * This routine has the function of returning the number of characters needed * to store a bitmap. It first calculates the number of bits needed per line. * Then it finds the closest multiple of 8 which is bigger than the number of * bits. Once that is done, it multiplies this number by the number of bits * high the bitmap is. */ int dither_char_bitmap(void) { int bits_line; int total_chars; for (bits_line = 8, total_chars = 1; bits_line < XDitherWidth; total_chars++) bits_line += 8; total_chars = total_chars * XDitherWidth; return total_chars; } int XInitDither(Display *display, int screen, GC gc, unsigned long fg, unsigned long bg) { char *bits; int count; int chars_bitmap = dither_char_bitmap(); int bit; XGCValues xgcv; DITHERINIT = 1; /* * First thing I should do is load in the Pixmaps */ bits = (char *) malloc(chars_bitmap * sizeof(char)); for (count = 0; count < XDitherMax; count++) { /* * Load in the next bitmap */ for (bit = 0; bit < chars_bitmap; bit++) bits[bit] = XDitherBits[count * chars_bitmap + bit]; /* * Create it and put it into the Pixmap array */ XDither[count] = XCreatePixmapFromBitmapData(display, RootWindow(display, screen), bits, XDitherWidth, XDitherWidth, BlackPixel(display, screen), WhitePixel(display, screen), 1); } /* * Now reset the gc values to be as I need them */ xgcv.background = bg; xgcv.foreground = fg; xgcv.fill_style = FillOpaqueStippled; xgcv.stipple = XDither[4]; XChangeGC(display, gc, GCForeground | GCBackground | GCFillStyle | GCStipple, &xgcv); return (XDitherMax); } int XChangeDither(Display *display, GC gc, int dither) { if (!DITHERINIT) { fprintf(stderr, "XChange Error: Init Not Called\n"); exit(-1); } if (dither >= XDitherMax || dither < 0) { fprintf(stderr, "Dither %d, out of range\n",dither); return (-1); } XSetStipple(display, gc, XDither[dither]); return (1); } void XDitherRectangle(Display *display, Drawable drawable, GC gc, int x, int y, unsigned int width, unsigned int height) { if (!DITHERINIT) { fprintf(stderr, "XDither Error: Tried to fill before INIT called\n"); exit(-1); } XFillRectangle(display, drawable, gc, x, y, width, height); } void XDitherRectangles(Display *display, Drawable drawable, GC gc, XRectangle *rectangles, int nrectangles) { if (!DITHERINIT) { fprintf(stderr, "XDither Error: Tried to fill before INIT called\n"); exit(-1); } XFillRectangles(display, drawable, gc, rectangles, nrectangles); } void XDitherPolygon(Display * display, Drawable drawable, GC gc, XPoint *points, int npoints, int shape, int mode) { if (!DITHERINIT) { fprintf(stderr, "XDither Error: Tried to fill before INIT called\n"); exit(-1); } XFillPolygon(display, drawable, gc, points, npoints, shape, mode); } void XDitherArc(Display *display, Drawable drawable, GC gc, int x,int y, unsigned int width, unsigned int height, int angle1, int angle2) { if (!DITHERINIT) { fprintf(stderr, "XDither Error: Tried to fill before INIT called\n"); exit(-1); } XFillArc(display, drawable, gc, x, y, width, height, angle1, angle2); } void XDitherArcs(Display *display,Drawable drawable, GC gc, XArc *arcs,int narcs) { if (!DITHERINIT) { fprintf(stderr, "XDither Error: Tried to fill before INIT called\n"); exit(-1); } XFillArcs(display, drawable, gc, arcs, narcs); }
f2a50b26d2968255764c1a73f2213fc443d74fad
7f6c235b0598353549959c18f69eefd20b766907
/examples/sms/3dcity/tile/splash_tile.c
d5d64fa9c3330dcbd20e97178aa5141f2b1358ac
[ "ClArtistic" ]
permissive
z88dk/z88dk
46dfd4905f36d99333173cadd0a660839befc9f0
8b07f37cc43c5d9ffe69b563c80763491d8faff7
refs/heads/master
2023-09-04T19:29:49.254958
2023-09-03T20:51:24
2023-09-03T20:51:24
54,035,569
820
263
NOASSERTION
2023-09-05T11:09:04
2016-03-16T13:48:16
Assembly
UTF-8
C
false
false
28,805
c
splash_tile.c
#include "splash_tile.h" #include <sms.h> const unsigned char engine_tile_splash_data_tiles[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x07, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xFC, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0x3F, 0x3F, 0x00, 0x40, 0x40, 0x40, 0x3F, 0x7F, 0x7F, 0x7F, 0x3F, 0x3F, 0x3F, 0x3F, 0x7F, 0x3F, 0x3F, 0x3F, 0x7F, 0x3F, 0x3F, 0x3F, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xC0, 0xC0, 0x00, 0x20, 0x20, 0x20, 0xC0, 0xE0, 0xE0, 0xE0, 0xC0, 0xE0, 0xE0, 0xE0, 0xC0, 0xA0, 0xA0, 0xA0, 0xC0, 0x7F, 0x5F, 0x7F, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x80, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x81, 0x81, 0x81, 0x7E, 0x7E, 0x7E, 0x7E, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x80, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0x1F, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xF0, 0xF0, 0x00, 0x0F, 0x0F, 0x0F, 0x07, 0x37, 0x37, 0x37, 0x0F, 0x7F, 0x7F, 0x7F, 0x1F, 0x5F, 0x5F, 0x5F, 0x3F, 0x7F, 0x7F, 0x7F, 0x3F, 0x3E, 0x3E, 0x3E, 0x7F, 0x3E, 0x3E, 0x3E, 0x7F, 0x3E, 0x3E, 0x3E, 0x7F, 0xFA, 0xFA, 0xFA, 0xFC, 0xFC, 0xFC, 0xFC, 0xFF, 0xFD, 0xFD, 0xFD, 0xFF, 0xFA, 0xFA, 0xFA, 0xFD, 0x3E, 0x3E, 0x3E, 0xC1, 0xFE, 0xC2, 0xC2, 0x01, 0xE6, 0xC2, 0xC2, 0x01, 0xF3, 0xF3, 0xF3, 0x00, 0xBF, 0xBF, 0xBF, 0x7F, 0x7F, 0x7F, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFE, 0xFE, 0xFF, 0xFE, 0xFE, 0xFE, 0xFF, 0x9E, 0x9E, 0x9E, 0xFF, 0xDE, 0xDE, 0xDE, 0x3F, 0x6E, 0x6E, 0x6E, 0x9F, 0x1D, 0x1D, 0x1D, 0xFE, 0x83, 0x83, 0x83, 0xFC, 0x7F, 0x41, 0x47, 0x80, 0xFE, 0x9E, 0x9E, 0x01, 0xF1, 0x91, 0x91, 0x0F, 0xFB, 0x0B, 0x0B, 0x07, 0xD8, 0x18, 0x18, 0x07, 0x40, 0x40, 0x40, 0x80, 0xC0, 0xC0, 0xC0, 0x3F, 0xBF, 0xBF, 0xBF, 0x7F, 0xBF, 0xBF, 0xBF, 0x7F, 0x7E, 0x7E, 0x7E, 0xFD, 0xFB, 0xF9, 0xF9, 0xFC, 0xFF, 0xF9, 0xF9, 0xF0, 0xF6, 0xF6, 0xF6, 0xF9, 0x01, 0x01, 0x01, 0x00, 0x09, 0x09, 0x09, 0xF0, 0xF7, 0xF7, 0xF7, 0xF8, 0xFC, 0xFC, 0xFC, 0xFF, 0x7F, 0x7F, 0x7F, 0xFF, 0x7F, 0x7F, 0x7F, 0xFF, 0xFE, 0xFE, 0xFE, 0xFF, 0xFE, 0xFE, 0xFE, 0xFF, 0x7F, 0x7F, 0x7F, 0xFF, 0x7F, 0x7F, 0x7F, 0xFF, 0x7F, 0x7F, 0x7F, 0xFF, 0x7F, 0x7F, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF, 0xBF, 0xBF, 0xBF, 0x7F, 0x60, 0x60, 0x40, 0x80, 0x1F, 0x1F, 0x1F, 0xE0, 0x00, 0x00, 0x00, 0xFF, 0x9A, 0x9A, 0x9A, 0xFF, 0x6D, 0x6D, 0x6D, 0x9E, 0x6F, 0x6F, 0x6F, 0x9C, 0x6B, 0x6B, 0x6B, 0x9C, 0x5B, 0x59, 0x59, 0xBC, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xB0, 0xB0, 0x0F, 0x5F, 0x5F, 0x5F, 0xBF, 0xBF, 0xBF, 0xBF, 0x7F, 0xBE, 0xBE, 0xBE, 0x7F, 0xBD, 0xBD, 0xBD, 0x7E, 0x7B, 0x7A, 0x7A, 0xFC, 0x7B, 0x7B, 0x7B, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04, 0xF8, 0xFB, 0xFB, 0xFB, 0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0xBF, 0xBF, 0xBF, 0x7F, 0xFF, 0x7F, 0x7F, 0x3F, 0xBF, 0x3F, 0x3F, 0x7F, 0xBF, 0xBF, 0xBF, 0x7F, 0x07, 0x07, 0x07, 0x1F, 0x2F, 0x2F, 0x2F, 0x1F, 0xAF, 0xAF, 0xAF, 0x1F, 0x6F, 0x6F, 0x6F, 0x9F, 0x9F, 0x9F, 0x9F, 0xFF, 0xCF, 0xCF, 0xCF, 0xFF, 0xB7, 0xB7, 0xB7, 0xCF, 0x6F, 0x4F, 0x4F, 0x87, 0xE8, 0xE8, 0xE8, 0xF0, 0xF0, 0xF0, 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF9, 0xF9, 0xF9, 0xFF, 0xF4, 0xF4, 0xF4, 0xFB, 0x00, 0x00, 0x00, 0x00, 0xCC, 0xCC, 0xCC, 0x03, 0xAB, 0xAB, 0xAB, 0xC7, 0xDF, 0xDF, 0xDF, 0xE7, 0xD3, 0xD3, 0xD3, 0xEF, 0x83, 0x83, 0x83, 0xFF, 0x97, 0x97, 0x97, 0xEF, 0x9B, 0x9B, 0x9B, 0xE7, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x0C, 0xF0, 0xFB, 0xFB, 0xFB, 0xFC, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFE, 0xFE, 0xFF, 0xF9, 0xF9, 0xF9, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x02, 0x02, 0x02, 0x01, 0xFF, 0xFF, 0xFF, 0x03, 0x07, 0x07, 0x07, 0xFF, 0xEF, 0xEF, 0xEF, 0xFF, 0x97, 0x97, 0x97, 0xEF, 0xF7, 0xC7, 0xC7, 0x0F, 0xF7, 0x17, 0x97, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x0C, 0xF0, 0xFA, 0xFA, 0xF8, 0xFC, 0xFA, 0xFA, 0xFA, 0xFC, 0xF3, 0xF3, 0xF3, 0xFC, 0xE0, 0xE0, 0xE0, 0xFF, 0xDB, 0xDB, 0xDB, 0xE7, 0xDF, 0xCF, 0xCF, 0xE7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xC0, 0x80, 0x00, 0xE0, 0xC0, 0xC0, 0x80, 0xF0, 0xF0, 0xF0, 0xC0, 0xD0, 0xD0, 0xD0, 0xE0, 0x3F, 0x3F, 0x3F, 0x7F, 0x7F, 0x7F, 0x7F, 0x3F, 0x5C, 0x5C, 0x5C, 0x3F, 0x2B, 0x2B, 0x2B, 0x1C, 0x62, 0x62, 0x62, 0x1D, 0x43, 0x43, 0x43, 0x3F, 0x3F, 0x3F, 0x3F, 0x7F, 0x7F, 0x7F, 0x7F, 0x3F, 0x78, 0x78, 0x78, 0xF0, 0xF4, 0xF4, 0xF4, 0xF8, 0xFE, 0xFF, 0xFF, 0xFC, 0xFD, 0xFD, 0xFD, 0xFE, 0x9F, 0x9F, 0x9F, 0xFE, 0x9D, 0x9D, 0x9D, 0xFE, 0xFB, 0xFA, 0xFA, 0xFC, 0xFA, 0xF8, 0xFA, 0xFC, 0x3E, 0x3E, 0x3E, 0x7F, 0x3E, 0x3E, 0x3E, 0x7F, 0x3E, 0x3E, 0x3E, 0x7F, 0x3E, 0x3E, 0x3E, 0x7F, 0x3E, 0x3E, 0x3E, 0x7F, 0x3E, 0x3E, 0x3E, 0x7F, 0x3E, 0x3E, 0x3E, 0x7F, 0x3E, 0x3E, 0x3E, 0x7F, 0xA6, 0x06, 0x06, 0x19, 0x9C, 0x1C, 0x0C, 0x03, 0x81, 0x01, 0x01, 0x03, 0x81, 0x01, 0x01, 0x03, 0x82, 0x02, 0x02, 0x01, 0x81, 0x01, 0x01, 0x00, 0x81, 0x01, 0x01, 0x00, 0xC0, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0xF0, 0xF0, 0xFF, 0xFF, 0xF8, 0xF8, 0xF0, 0xF7, 0xF7, 0xF7, 0xF8, 0xF3, 0xF3, 0xF3, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0xF9, 0xF9, 0xF9, 0xFE, 0xEF, 0xEE, 0xEF, 0xF0, 0x1F, 0x10, 0x10, 0xE0, 0xFC, 0x00, 0x00, 0x00, 0xF0, 0x80, 0x80, 0x00, 0x78, 0x60, 0x40, 0x80, 0xC2, 0xC2, 0xC2, 0xFC, 0xF6, 0xF6, 0xF4, 0xF8, 0xDF, 0x5F, 0x5F, 0x3F, 0xFF, 0x7F, 0x7F, 0x1F, 0xFF, 0x3F, 0x3F, 0x1F, 0x2F, 0x2F, 0x2F, 0x1F, 0x2F, 0x2F, 0x2F, 0x1F, 0x2F, 0x2F, 0x2F, 0x1F, 0x0F, 0x2F, 0x2F, 0x1F, 0x17, 0x17, 0x17, 0x0F, 0x97, 0x95, 0x95, 0xF8, 0xFF, 0xF9, 0xF9, 0xF0, 0xFF, 0xF9, 0xF9, 0xF0, 0xED, 0xE9, 0xE9, 0xF0, 0xED, 0xE8, 0xE8, 0xF0, 0xDC, 0xD0, 0xD0, 0xE0, 0xDC, 0xC0, 0xD0, 0xE0, 0xD8, 0xC0, 0xC0, 0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC, 0xFC, 0xFC, 0xFF, 0xFB, 0xFA, 0xFA, 0xFC, 0xBF, 0xBF, 0xBF, 0x7C, 0xBC, 0xBC, 0xBC, 0x7F, 0x3F, 0x3F, 0x3F, 0x7F, 0x5F, 0x5F, 0x5F, 0x3F, 0xFE, 0xFE, 0xFE, 0xFF, 0xF3, 0xF3, 0xF3, 0xFC, 0x0F, 0x08, 0x08, 0xF0, 0xFF, 0x00, 0x00, 0x00, 0xFC, 0xE0, 0xE0, 0x00, 0xD8, 0xD0, 0xD0, 0xE0, 0xE1, 0xE1, 0xE1, 0xFE, 0xFD, 0xFD, 0xFD, 0xFE, 0x7F, 0x4F, 0x4F, 0x87, 0xF7, 0xF7, 0xF7, 0x0F, 0xEF, 0x2F, 0x2F, 0x1F, 0x2F, 0x2F, 0x2F, 0x1F, 0x63, 0x63, 0x63, 0x1F, 0x5F, 0x5F, 0x5F, 0x23, 0xB7, 0x97, 0x97, 0x0F, 0x17, 0x07, 0x07, 0x0F, 0xFC, 0xF8, 0xF8, 0xF3, 0xED, 0xE9, 0xE9, 0xF3, 0xDD, 0xDD, 0xDD, 0xE3, 0xDF, 0xCF, 0xDF, 0xE3, 0xDB, 0xCB, 0xCB, 0xE7, 0xD7, 0xD7, 0xD7, 0xEF, 0xEE, 0xEE, 0xEE, 0xFF, 0x81, 0x81, 0x81, 0xFE, 0x9D, 0x9D, 0x95, 0xE3, 0xDD, 0xD1, 0xD1, 0xE3, 0xDD, 0xD1, 0xD1, 0xE3, 0xD5, 0xD1, 0xD1, 0xE3, 0xB5, 0xA1, 0xA1, 0xC3, 0x71, 0x61, 0x61, 0x83, 0xF1, 0xC1, 0xC1, 0x03, 0xE1, 0x81, 0x81, 0x03, 0xF3, 0xF0, 0xF0, 0xFC, 0xF7, 0xF4, 0xF4, 0xF8, 0xF7, 0xF0, 0xF0, 0xF8, 0xFF, 0xF8, 0xF8, 0xF0, 0xFE, 0xF8, 0xF8, 0xF0, 0xFE, 0xF8, 0xF8, 0xF0, 0xFE, 0xF8, 0xF8, 0xF0, 0xFE, 0xF8, 0xF8, 0xF0, 0xEF, 0x2F, 0x2F, 0x1F, 0xBF, 0x3F, 0x3F, 0x1F, 0x2F, 0x2F, 0x2F, 0x1F, 0x2F, 0x2F, 0x2F, 0x1F, 0x2F, 0x2F, 0x2F, 0x1F, 0x2F, 0x2F, 0x2F, 0x1F, 0x2F, 0x2F, 0x2F, 0x1F, 0x17, 0x17, 0x17, 0x0F, 0xB7, 0xA7, 0xA7, 0xCF, 0xF5, 0xC5, 0xC5, 0x8F, 0xF9, 0xC9, 0xC9, 0x87, 0xFD, 0xC5, 0xC5, 0x83, 0xFB, 0xFB, 0xFB, 0x87, 0x8F, 0x8F, 0x8F, 0xFF, 0xCF, 0xCF, 0xCF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x88, 0x88, 0x88, 0xF0, 0x88, 0x88, 0x88, 0xF0, 0xC8, 0xC8, 0xC8, 0xF0, 0xD8, 0xD0, 0xD0, 0xE0, 0xD8, 0xD0, 0xD0, 0xE0, 0xB8, 0xA0, 0xA0, 0xC0, 0xB8, 0xA0, 0xA0, 0xC0, 0x70, 0x40, 0x40, 0x80, 0x5D, 0x5D, 0x5D, 0x3F, 0x7F, 0x7F, 0x7F, 0x3F, 0x5C, 0x5C, 0x5C, 0x3F, 0x2B, 0x2A, 0x2A, 0x1C, 0x1F, 0x1C, 0x1C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF3, 0xF0, 0xF0, 0xFC, 0xE7, 0xE4, 0xE4, 0xF8, 0x0E, 0x00, 0x08, 0xF0, 0xFE, 0x00, 0xE0, 0x00, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x3E, 0x3E, 0x7F, 0x5E, 0x5E, 0x5E, 0x3F, 0x5E, 0x5E, 0x5E, 0x3F, 0x5F, 0x5F, 0x5F, 0x3F, 0x2C, 0x2C, 0x2C, 0x1F, 0x13, 0x13, 0x12, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0x60, 0x60, 0x00, 0xD8, 0xD8, 0xD8, 0x20, 0x18, 0x10, 0x10, 0xE0, 0x30, 0x20, 0x20, 0xC0, 0xF0, 0xE0, 0xE0, 0x00, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x73, 0x73, 0x73, 0x3F, 0x29, 0x29, 0x29, 0x1E, 0x1F, 0x1E, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xAC, 0xA8, 0xA8, 0xF0, 0xFE, 0xF8, 0xF8, 0x00, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x17, 0x17, 0x0F, 0x0F, 0x0F, 0x0F, 0x07, 0x0F, 0x0F, 0x0F, 0x07, 0x0A, 0x0A, 0x0A, 0x07, 0x07, 0x07, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD8, 0xC0, 0xD0, 0xE0, 0xD8, 0xC0, 0xC0, 0xE0, 0x38, 0x20, 0x20, 0xC0, 0xF0, 0xC0, 0xC0, 0x00, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2C, 0x2C, 0x2C, 0x1F, 0x12, 0x12, 0x12, 0x0F, 0x0F, 0x0F, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFB, 0xFA, 0xFA, 0xFC, 0x7F, 0x7E, 0x7C, 0x80, 0xFE, 0x80, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x17, 0x17, 0x17, 0x0F, 0x17, 0x17, 0x17, 0x0F, 0x17, 0x17, 0x17, 0x0F, 0x17, 0x17, 0x17, 0x0F, 0x67, 0x67, 0x67, 0x1F, 0x5F, 0x5F, 0x5F, 0x3F, 0x3F, 0x3F, 0x3F, 0x1F, 0x3E, 0x3E, 0x3E, 0x1F, 0xBF, 0x80, 0xA0, 0xC0, 0xBF, 0x80, 0x80, 0xC0, 0xB8, 0x80, 0x80, 0xC0, 0xF8, 0xC0, 0xC0, 0x80, 0x70, 0x40, 0x40, 0x80, 0x70, 0x40, 0x40, 0x80, 0x60, 0x40, 0x40, 0x80, 0x60, 0x40, 0x40, 0x80, 0xC1, 0x01, 0x01, 0x03, 0xC1, 0x01, 0x01, 0x03, 0x01, 0x01, 0x01, 0x03, 0x02, 0x02, 0x02, 0x01, 0x03, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xEE, 0xE8, 0xE8, 0xF0, 0xEC, 0xE8, 0xE8, 0xF0, 0x8C, 0x88, 0x88, 0xF0, 0x7C, 0x60, 0x70, 0x80, 0xF8, 0x80, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0B, 0x0B, 0x0B, 0x07, 0x07, 0x07, 0x07, 0x03, 0x02, 0x02, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xDC, 0xDC, 0xDC, 0xFF, 0xBF, 0xBF, 0xBF, 0xC0, 0xFF, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x80, 0xC0, 0x00, 0xE0, 0x00, 0x80, 0x00, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5E, 0x5E, 0x5E, 0x3F, 0x3E, 0x3E, 0x3E, 0x1F, 0x2E, 0x2E, 0x2E, 0x1F, 0x2E, 0x2E, 0x2E, 0x1F, 0x2D, 0x2D, 0x2D, 0x1E, 0x2D, 0x2D, 0x2D, 0x1E, 0x23, 0x22, 0x22, 0x1C, 0x1F, 0x1C, 0x1C, 0x00, 0xE0, 0x80, 0x80, 0x00, 0xC0, 0x00, 0x00, 0x00, 0xC0, 0x00, 0x00, 0x00, 0xC0, 0x00, 0x00, 0x00, 0xC0, 0x00, 0x00, 0x00, 0xC0, 0x00, 0x00, 0x00, 0xC0, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x02, 0x02, 0x02, 0x01, 0x05, 0x05, 0x05, 0x03, 0x0B, 0x0B, 0x0B, 0x07, 0x0F, 0x0F, 0x0F, 0x07, 0x0F, 0x0F, 0x0F, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xF0, 0xF0, 0x00, 0x0C, 0x08, 0x08, 0xF0, 0xF4, 0xF4, 0xF4, 0xF8, 0xFA, 0xF8, 0xF8, 0xFC, 0xFB, 0xF9, 0xFB, 0xFC, 0xFB, 0xFB, 0xFB, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x20, 0x20, 0xC0, 0xD8, 0xD8, 0xD8, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x7F, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x02, 0x02, 0x02, 0x01, 0x01, 0x01, 0x01, 0x03, 0x01, 0x01, 0x01, 0x03, 0x01, 0x01, 0x01, 0x03, 0xE1, 0xE1, 0xE1, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFE, 0xFE, 0x00, 0x01, 0x01, 0x01, 0xFE, 0xFF, 0xFF, 0xFF, 0xFE, 0xFD, 0xFD, 0xFD, 0xFE, 0xFF, 0xFE, 0xFE, 0xFC, 0xFB, 0xFA, 0xFB, 0xFC, 0x0B, 0x0B, 0x0B, 0x07, 0x05, 0x05, 0x05, 0x03, 0x01, 0x01, 0x01, 0x03, 0x01, 0x01, 0x01, 0x03, 0x01, 0x01, 0x01, 0x03, 0x02, 0x02, 0x02, 0x01, 0x01, 0x01, 0x01, 0x03, 0xC1, 0xC1, 0xC1, 0x03, 0xF2, 0xF2, 0xF2, 0xFD, 0xF4, 0xF4, 0xF4, 0xFB, 0xF5, 0xF5, 0xF5, 0xFB, 0xF5, 0xF5, 0xF5, 0xFB, 0xFD, 0xFD, 0xFD, 0xF3, 0xFD, 0xF9, 0xF9, 0xF3, 0xFD, 0xF9, 0xF9, 0xF3, 0xFD, 0xF9, 0xF9, 0xF3, 0xFC, 0xF8, 0xF8, 0xF0, 0xF4, 0xF4, 0xF4, 0xF8, 0xFC, 0xF8, 0xF8, 0xF0, 0xFC, 0xF8, 0xF8, 0xF0, 0xEC, 0xE8, 0xE8, 0xF0, 0x8C, 0x88, 0x88, 0xF0, 0x7C, 0x40, 0x40, 0x80, 0x7C, 0x60, 0x60, 0x80, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x02, 0x02, 0x02, 0x01, 0x02, 0x02, 0x02, 0x01, 0x01, 0x01, 0x01, 0x03, 0x01, 0x01, 0x01, 0x03, 0x01, 0x01, 0x01, 0x03, 0x01, 0x01, 0x01, 0x03, 0x3F, 0x3F, 0x3F, 0x7F, 0x7F, 0x7F, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFB, 0xFB, 0xFB, 0xFC, 0xF7, 0xF4, 0xF4, 0xF8, 0xFF, 0xFA, 0xFE, 0xF0, 0xF7, 0xF7, 0xF7, 0xF8, 0xD5, 0xD5, 0xD5, 0xE3, 0xE3, 0xE3, 0xE3, 0xFF, 0xEF, 0xEF, 0xEF, 0xFF, 0x97, 0x97, 0x97, 0xEF, 0xF7, 0xF7, 0xF7, 0x0F, 0xF7, 0x17, 0x17, 0x0F, 0x2A, 0x0A, 0x0A, 0x1D, 0x9E, 0x9E, 0x9E, 0x01, 0xFB, 0xFB, 0xFB, 0xFC, 0xFC, 0xFC, 0xFC, 0xFF, 0xFC, 0xFC, 0xFC, 0xFF, 0xFB, 0xFA, 0xFA, 0xFC, 0xF7, 0xF4, 0xF4, 0xF8, 0xF7, 0xF4, 0xF0, 0xF8, 0xFE, 0xF8, 0xF8, 0xF0, 0xFC, 0xF8, 0xF8, 0xF0, 0xF4, 0xF4, 0xF4, 0xF8, 0xEC, 0xEC, 0xEC, 0xF0, 0x18, 0x10, 0x10, 0xE0, 0xF8, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x9F, 0x9F, 0x9F, 0x7F, 0xDF, 0x5F, 0x5F, 0x3F, 0x87, 0x87, 0x87, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04, 0x00, 0x08, 0x08, 0x08, 0x07, 0xF7, 0xF7, 0xF7, 0x0F, 0xD7, 0xD7, 0xD7, 0xEF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x01, 0x01, 0x00, 0x02, 0x02, 0x02, 0x01, 0x41, 0x41, 0x41, 0x03, 0x21, 0x21, 0x21, 0xC3, 0xC1, 0xC1, 0xC1, 0xE3, 0xE1, 0xE1, 0xE1, 0xC3, 0xA1, 0xA1, 0xA1, 0xC0, 0x62, 0x42, 0x42, 0x81, 0x21, 0x21, 0x21, 0xC3, 0xD1, 0xC1, 0xC1, 0xE3, 0xD1, 0xC1, 0xD1, 0xE3, 0xD5, 0xC1, 0xC1, 0xE3, 0xFD, 0xF1, 0xF1, 0x83, 0xFD, 0xFD, 0xFD, 0x83, 0x93, 0x93, 0x93, 0xFF, 0xFC, 0xFC, 0xFC, 0xFF, 0xFD, 0xF9, 0xF9, 0xF3, 0xFD, 0xF9, 0xF9, 0xF3, 0xFD, 0xF9, 0xF9, 0xF3, 0xFD, 0xF9, 0xF9, 0xF3, 0xFD, 0xF9, 0xF9, 0xF3, 0xFD, 0xF9, 0xF9, 0xF3, 0xFD, 0xF9, 0xF9, 0xF3, 0xFD, 0xF9, 0xF9, 0xF3, 0xD8, 0xD0, 0xD0, 0xE0, 0xE4, 0xE4, 0xE4, 0xF8, 0xF8, 0xF8, 0xF8, 0xFC, 0xF7, 0xF5, 0xF5, 0xF8, 0xF7, 0xF5, 0xF5, 0xF8, 0xFE, 0xFA, 0xFA, 0xF1, 0xFE, 0xFA, 0xFA, 0xF1, 0xFD, 0xF9, 0xF9, 0xF3, 0x00, 0x00, 0x00, 0x00, 0x41, 0x41, 0x41, 0x3E, 0xBF, 0xBF, 0xBF, 0x7F, 0x7F, 0x7F, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x80, 0x80, 0x80, 0x00, 0x40, 0x40, 0x40, 0x80, 0xC1, 0xC1, 0xC1, 0x80, 0xB9, 0xB9, 0xB9, 0xC0, 0x15, 0x15, 0x15, 0xF8, 0xDB, 0xDB, 0xDB, 0x3C, 0xFF, 0x7F, 0x7F, 0x3C, 0x2F, 0x2F, 0x2F, 0x1F, 0x5F, 0x5F, 0x5F, 0x3F, 0xBF, 0xBF, 0xBF, 0x7F, 0x7F, 0x7F, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFE, 0xFE, 0xFF, 0x7E, 0x7E, 0x7E, 0xFF, 0xBE, 0xBE, 0xBE, 0x7F, 0xFC, 0xFC, 0xFC, 0xF0, 0xF4, 0xF4, 0xF4, 0xF8, 0xFA, 0xF8, 0xF8, 0xFC, 0xFA, 0xF8, 0xF8, 0xFC, 0x3E, 0x3C, 0x3C, 0xC0, 0x7E, 0x00, 0x00, 0x80, 0xE0, 0x00, 0x00, 0x00, 0xE0, 0xE0, 0xE0, 0x00, 0x01, 0x01, 0x01, 0x03, 0x01, 0x01, 0x01, 0x03, 0x02, 0x02, 0x02, 0x01, 0x01, 0x01, 0x01, 0x00, 0x03, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x03, 0x01, 0x01, 0x01, 0x03, 0x01, 0x01, 0x01, 0x03, 0xF3, 0xF3, 0xF3, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC7, 0xC7, 0xC7, 0xFF, 0xD7, 0xD7, 0xD7, 0xEF, 0x14, 0x14, 0x14, 0xEF, 0x1E, 0x1E, 0x1E, 0xFD, 0xFD, 0xFD, 0xFD, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x45, 0x41, 0x45, 0x83, 0xA1, 0xA1, 0xA1, 0xC3, 0xD1, 0xD1, 0xD1, 0xE3, 0xE9, 0xE9, 0xE9, 0xF3, 0xF9, 0xF9, 0xF9, 0xF3, 0xE9, 0xE9, 0xE9, 0xF3, 0xD1, 0xD1, 0xD1, 0xE3, 0xD1, 0xC1, 0xC1, 0xE3, 0xFD, 0xF9, 0xF9, 0xF0, 0xFC, 0xF8, 0xF8, 0xF0, 0xFC, 0xF8, 0xF8, 0xF0, 0xFC, 0xF8, 0xF8, 0xF0, 0xFC, 0xF8, 0xF8, 0xF0, 0xFC, 0xF8, 0xF8, 0xF0, 0xFC, 0xF8, 0xF8, 0xF0, 0xFC, 0xF8, 0xF8, 0xF0, 0x37, 0x37, 0x37, 0xCF, 0xEF, 0xEF, 0xEF, 0x1F, 0x2F, 0x2F, 0x2F, 0x1F, 0x2F, 0x2F, 0x2F, 0x1F, 0x2F, 0x2F, 0x2F, 0x1F, 0x1F, 0x1F, 0x1F, 0x0F, 0x17, 0x17, 0x17, 0x0F, 0x07, 0x07, 0x07, 0x0F, 0xE7, 0xE7, 0xE7, 0xFF, 0xEF, 0xEF, 0xEF, 0xFF, 0xE3, 0xE3, 0xE3, 0xFF, 0x8F, 0x8F, 0x8F, 0xF3, 0xFB, 0xFB, 0xFB, 0x87, 0xF3, 0xF3, 0xF3, 0x8F, 0x8F, 0x8F, 0x8F, 0xFF, 0xFC, 0xFC, 0xFC, 0xFF, 0x65, 0x45, 0x41, 0x83, 0x2F, 0x07, 0x07, 0xC3, 0xBB, 0x8B, 0x8B, 0xC7, 0xF7, 0xC7, 0xC7, 0x8F, 0xF7, 0xF7, 0xF7, 0x8F, 0xAF, 0xAF, 0xAF, 0xDF, 0xCF, 0xCF, 0xCF, 0xFF, 0x73, 0x73, 0x73, 0xFF, 0xF2, 0xF2, 0xF2, 0xFD, 0xEE, 0xEE, 0xEE, 0xF1, 0xDE, 0xD2, 0xD2, 0xE1, 0xDD, 0xC1, 0xC1, 0xE3, 0xDD, 0xC1, 0xC1, 0xE3, 0xD5, 0xD1, 0xD1, 0xE3, 0xE9, 0xE9, 0xE9, 0xF3, 0xF5, 0xF5, 0xF5, 0xFB, 0xFD, 0xF9, 0xF9, 0xF3, 0xFD, 0xF9, 0xF9, 0xF3, 0xFD, 0xF9, 0xFD, 0xF3, 0xFD, 0xF9, 0xF9, 0xF3, 0xFD, 0xF9, 0xFD, 0xF3, 0xFD, 0xF9, 0xFD, 0xF3, 0xED, 0xE9, 0xE9, 0xF3, 0xED, 0xE9, 0xE9, 0xF3, 0xFD, 0xF9, 0xF9, 0xF3, 0xFD, 0xF9, 0xFD, 0xF3, 0xFD, 0xF9, 0xF9, 0xF3, 0xFC, 0xF8, 0xF8, 0xF3, 0xFF, 0xFB, 0xFB, 0xF0, 0xFD, 0xF9, 0xF9, 0xF0, 0xFD, 0xF9, 0xF9, 0xF0, 0xFC, 0xF8, 0xF8, 0xF0, 0xFD, 0xFD, 0xFD, 0xFE, 0xFB, 0xFA, 0xFA, 0xFC, 0xFB, 0xF8, 0xFA, 0xFC, 0xFB, 0xFA, 0xFA, 0xFC, 0xFB, 0xFB, 0xFB, 0xFC, 0xFE, 0xFE, 0xFE, 0xFD, 0x7E, 0x7E, 0x7E, 0xFF, 0xBF, 0xBF, 0xBF, 0x7F, 0xBD, 0x3D, 0x3D, 0x7E, 0xAD, 0xAD, 0x2D, 0x7E, 0xAF, 0x2F, 0x2F, 0x7E, 0xBF, 0x3F, 0x3F, 0x7E, 0xBD, 0xBD, 0xBD, 0x7E, 0xFD, 0xFD, 0xFD, 0xFE, 0x7D, 0x7D, 0x7D, 0xFE, 0xFB, 0xFA, 0xFA, 0xFC, 0xBF, 0x3F, 0x3F, 0x7F, 0x7F, 0x7F, 0x7F, 0x3F, 0xDC, 0x5C, 0x5C, 0x3F, 0xAB, 0x2B, 0x2B, 0x1C, 0xE2, 0x62, 0x62, 0x1D, 0xC3, 0x43, 0xC3, 0x3F, 0xBF, 0xBF, 0xBF, 0x7F, 0xBF, 0xBF, 0xBF, 0x7F, 0x40, 0x40, 0x50, 0xE0, 0xE8, 0xE8, 0xE8, 0xF0, 0xF4, 0xF4, 0xF4, 0xF8, 0xF8, 0xF8, 0xF8, 0xFC, 0x9A, 0x98, 0x98, 0xFC, 0xFA, 0xF8, 0xF8, 0x9C, 0xBB, 0xBA, 0xB8, 0xFC, 0xFB, 0xFA, 0xFA, 0xFC, 0x02, 0x02, 0x02, 0x01, 0x01, 0x01, 0x01, 0x03, 0x02, 0x02, 0x02, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xEF, 0xEF, 0xEF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE0, 0xE0, 0xE0, 0xFF, 0xDF, 0xD1, 0xD7, 0xE0, 0xFF, 0xE0, 0xE0, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xB5, 0xA1, 0xA1, 0xC3, 0x79, 0x41, 0x41, 0x83, 0xF2, 0x82, 0x82, 0x01, 0xE2, 0x02, 0x02, 0x01, 0xC3, 0x03, 0x03, 0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFB, 0xFA, 0xF0, 0xFC, 0xFC, 0xFC, 0xF3, 0xF0, 0xF0, 0xF0, 0xFF, 0xF9, 0xF9, 0xF9, 0xFE, 0x47, 0x47, 0x47, 0xF8, 0x9F, 0x90, 0x90, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0B, 0x0B, 0x0B, 0x07, 0x85, 0x85, 0x85, 0x03, 0x82, 0x82, 0x82, 0x01, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xCB, 0xC9, 0xC9, 0xFC, 0xBF, 0xBD, 0xBD, 0xC0, 0xFF, 0xC1, 0xC1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6C, 0x6C, 0x6C, 0xF3, 0x5E, 0x52, 0x5A, 0xE1, 0xFD, 0xE1, 0xE1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, 0x70, 0x70, 0xFF, 0xDF, 0xDF, 0xDF, 0xE0, 0xBF, 0xA1, 0xA1, 0x40, 0x03, 0x01, 0x01, 0x00, 0x01, 0x01, 0x01, 0x00, 0x01, 0x01, 0x01, 0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xED, 0xE9, 0xE9, 0xF3, 0xBD, 0xB9, 0xB9, 0x73, 0xBE, 0xBA, 0xBA, 0x71, 0x7F, 0x79, 0x79, 0xF0, 0xFD, 0xF9, 0xF9, 0xF0, 0xED, 0xE9, 0xE9, 0xF0, 0x5C, 0x58, 0x5C, 0xE0, 0xE4, 0xE0, 0xE0, 0x00, 0xFC, 0xF8, 0xF8, 0xF0, 0xFC, 0xF8, 0xF8, 0xF0, 0xFC, 0xF8, 0xF8, 0xF0, 0xFC, 0xF8, 0xF8, 0xF0, 0x5C, 0x58, 0x58, 0xE0, 0x3C, 0x20, 0x20, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0x7E, 0x7E, 0x3F, 0x3B, 0x3B, 0x3B, 0x1C, 0x16, 0x14, 0x14, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x04, 0x04, 0xF8, 0xFF, 0xF8, 0xF8, 0x00, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x3F, 0x3F, 0x7F, 0xBF, 0x3F, 0x3F, 0x7F, 0x5C, 0x5C, 0x5C, 0x3F, 0x2B, 0x2A, 0x2B, 0x1C, 0x1C, 0x1C, 0x1C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF3, 0xF2, 0xF2, 0xFC, 0xEF, 0xEC, 0xEC, 0xF0, 0x0E, 0x08, 0x00, 0xF0, 0xFC, 0x90, 0x80, 0x00, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; const unsigned int engine_tile_splash_data_tilemap[] = { 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0101, 0x0102, 0x0103, 0x0104, 0x0105, 0x0106, 0x0107, 0x0108, 0x0100, 0x0100, 0x0109, 0x010A, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x010B, 0x010C, 0x010D, 0x010E, 0x010F, 0x0110, 0x0111, 0x0112, 0x0113, 0x0114, 0x0115, 0x0116, 0x0117, 0x0118, 0x0119, 0x011A, 0x011B, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x011C, 0x011D, 0x011E, 0x011F, 0x0120, 0x0121, 0x0122, 0x0123, 0x0124, 0x0125, 0x0126, 0x0127, 0x0128, 0x0129, 0x012A, 0x012B, 0x012C, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x012D, 0x012E, 0x012F, 0x0130, 0x0131, 0x0132, 0x0133, 0x0134, 0x0135, 0x0136, 0x0137, 0x0138, 0x0139, 0x013A, 0x013B, 0x013C, 0x013D, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x013E, 0x013F, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0140, 0x0141, 0x0142, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0143, 0x0144, 0x0145, 0x0102, 0x0100, 0x0100, 0x0146, 0x0147, 0x0148, 0x0100, 0x0100, 0x0109, 0x010A, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0149, 0x014A, 0x014B, 0x014C, 0x014D, 0x014E, 0x014F, 0x0150, 0x0151, 0x0152, 0x0153, 0x0154, 0x0155, 0x0156, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0157, 0x0158, 0x0159, 0x015A, 0x015B, 0x015C, 0x015D, 0x015E, 0x015F, 0x0160, 0x0161, 0x0162, 0x0163, 0x0164, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0165, 0x0166, 0x0167, 0x0168, 0x0169, 0x016A, 0x016B, 0x016C, 0x016D, 0x016E, 0x016F, 0x0170, 0x0171, 0x0172, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, }; void engine_tile_splash_load_tiles(int start, int count) { // start 80 0x0050 // count xx how many lines in tiles array (above) // bpp 4 bits per pixel load_tiles(engine_tile_splash_data_tiles, start, count, 4); // SMS. } void engine_tile_splash_show_tiles(unsigned char x, unsigned char y, unsigned char width, unsigned char height) { set_bkg_map(engine_tile_splash_data_tilemap, x, y, width, height); }
6a153e15f9316bd9ca0e87ce29eb32caf3bc159b
99bdb3251fecee538e0630f15f6574054dfc1468
/bsp/raspberry-pico/libraries/pico-sdk/src/rp2_common/hardware_flash/include/hardware/flash.h
7ea96b44d6719621085aaaeab1ea031757287364
[ "BSD-3-Clause", "Apache-2.0", "Zlib", "LicenseRef-scancode-proprietary-license", "MIT", "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
1,992
h
flash.h
/* * Copyright (c) 2020 Raspberry Pi (Trading) Ltd. * * SPDX-License-Identifier: BSD-3-Clause */ #ifndef _HARDWARE_FLASH_H #define _HARDWARE_FLASH_H #include "pico.h" // PICO_CONFIG: PARAM_ASSERTIONS_ENABLED_FLASH, Enable/disable assertions in the flash module, type=bool, default=0, group=hardware_flash #ifndef PARAM_ASSERTIONS_ENABLED_FLASH #define PARAM_ASSERTIONS_ENABLED_FLASH 0 #endif #define FLASH_PAGE_SIZE (1u << 8) #define FLASH_SECTOR_SIZE (1u << 12) #define FLASH_BLOCK_SIZE (1u << 16) /** \file flash.h * \defgroup hardware_flash hardware_flash * * Low level flash programming and erase API * * Note these functions are *unsafe* if you have two cores concurrently * executing from flash. In this case you must perform your own * synchronisation to make sure no XIP accesses take place during flash * programming. * * If PICO_NO_FLASH=1 is not defined (i.e. if the program is built to run from * flash) then these functions will make a static copy of the second stage * bootloader in SRAM, and use this to reenter execute-in-place mode after * programming or erasing flash, so that they can safely be called from * flash-resident code. * * \subsection flash_example Example * \include flash_program.c */ /*! \brief Erase areas of flash * \ingroup hardware_flash * * \param flash_offs Offset into flash, in bytes, to start the erase. Must be aligned to a 4096-byte flash sector. * \param count Number of bytes to be erased. Must be a multiple of 4096 bytes (one sector). */ void flash_range_erase(uint32_t flash_offs, size_t count); /*! \brief Program flash * \ingroup hardware_flash * * \param flash_offs Flash address of the first byte to be programmed. Must be aligned to a 256-byte flash page. * \param data Pointer to the data to program into flash * \param count Number of bytes to program. Must be a multiple of 256 bytes (one page). */ void flash_range_program(uint32_t flash_offs, const uint8_t *data, size_t count); #endif
adce5c8153b8609e4c9ec0b3ec9d469b6fc24c38
ca4c4631f3d47a90b8415bbe70dbc7cae18c071e
/unit_tests/actuator/UnitTestActuatorNGP.C
5ed43b65ef59b680770d82ed49b4b188f1b73bf4
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
Exawind/nalu-wind
5765078c445d379ea952d2b25a01f5ff490837a6
722cd7757a412c9306645963808047824c312a17
refs/heads/master
2023-08-16T17:44:54.744168
2023-08-15T18:05:23
2023-08-15T18:05:23
132,016,365
111
87
NOASSERTION
2023-09-14T04:02:07
2018-05-03T15:39:32
C
UTF-8
C
false
false
2,071
c
UnitTestActuatorNGP.C
// Copyright 2017 National Technology & Engineering Solutions of Sandia, LLC // (NTESS), National Renewable Energy Laboratory, University of Texas Austin, // Northwest Research Associates. Under the terms of Contract DE-NA0003525 // with NTESS, the U.S. Government retains certain rights in this software. // // This software is released under the BSD 3-clause license. See LICENSE file // for more details. // #include <actuator/UnitTestActuatorNGP.h> #include <NaluEnv.h> #include <gtest/gtest.h> namespace sierra { namespace nalu { namespace { TEST(ActuatorNGP, NGP_testExecuteOnHostOnly) { ActuatorMeta actMeta(1); ActuatorInfoNGP infoTurb0; infoTurb0.turbineName_ = "Turbine0"; infoTurb0.numPoints_ = 20; actMeta.add_turbine(infoTurb0); ActuatorBulk actBulk(actMeta); ASSERT_NO_THROW(TestActuatorHostOnly(actBulk)); EXPECT_DOUBLE_EQ(3.0, actBulk.epsilon_.h_view(1, 0)); EXPECT_DOUBLE_EQ(6.0, actBulk.epsilon_.h_view(1, 1)); EXPECT_DOUBLE_EQ(9.0, actBulk.epsilon_.h_view(1, 2)); EXPECT_DOUBLE_EQ(1.0, actBulk.pointCentroid_.h_view(1, 0)); EXPECT_DOUBLE_EQ(0.5, actBulk.pointCentroid_.h_view(1, 1)); EXPECT_DOUBLE_EQ(0.25, actBulk.pointCentroid_.h_view(1, 2)); EXPECT_DOUBLE_EQ(2.5, actBulk.velocity_.h_view(1, 0)); EXPECT_DOUBLE_EQ(5.0, actBulk.velocity_.h_view(1, 1)); EXPECT_DOUBLE_EQ(7.5, actBulk.velocity_.h_view(1, 2)); EXPECT_DOUBLE_EQ(3.1, actBulk.actuatorForce_.h_view(1, 0)); EXPECT_DOUBLE_EQ(6.2, actBulk.actuatorForce_.h_view(1, 1)); EXPECT_DOUBLE_EQ(9.3, actBulk.actuatorForce_.h_view(1, 2)); } TEST(ActuatorNGP, NGP_testExecuteOnHostAndDevice) { ActuatorMeta actMeta(1); ActuatorInfoNGP infoTurb0; infoTurb0.turbineName_ = "Turbine0"; infoTurb0.numPoints_ = 20; actMeta.add_turbine(infoTurb0); ActuatorBulkMod actBulk(actMeta); ASSERT_NO_THROW(TestActuatorHostDev(actBulk)); const double expectVal = actBulk.velocity_.h_view(1, 1) * actBulk.pointCentroid_.h_view(1, 0); EXPECT_DOUBLE_EQ(expectVal, actBulk.scalar_.h_view(1)); } } // namespace } // namespace nalu } // namespace sierra
9489f223967883f92ba640e9d0a92d175fe596fa
9de0cec678bc4a3bec2b4adabef9f39ff5b4afac
/PWGLF/ThermalFits/PlotRatiosForQM14.C
afa4ebc791117a22e74a662c3e7b402038a3dbd1
[]
permissive
alisw/AliPhysics
91bf1bd01ab2af656a25ff10b25e618a63667d3e
5df28b2b415e78e81273b0d9bf5c1b99feda3348
refs/heads/master
2023-08-31T20:41:44.927176
2023-08-31T14:51:12
2023-08-31T14:51:12
61,661,378
129
1,150
BSD-3-Clause
2023-09-14T18:48:45
2016-06-21T19:31:29
C++
UTF-8
C
false
false
89,318
c
PlotRatiosForQM14.C
#if !defined (__CINT__) || (defined(__MAKECINT__)) #include <iostream> #include "TClonesArray.h" #include "AliParticleYield.h" #include "TH1F.h" #include "TCanvas.h" #include "TStyle.h" #include <fstream> #include "TLatex.h" #include "TLegend.h" #include "TList.h" #include "TF1.h" #include "AliPWGHistoTools.h" #include "TGraphErrors.h" #include "TMath.h" #include "TDatabasePDG.h" #include "TH2F.h" #include "TSystem.h" #include "TPaveText.h" #include <map> #include <fstream> #include <istream> #include "TMarker.h" #include "TObjString.h" #include "TLegendEntry.h" #endif // Plots ratios for QM and saves input files for thermal models #if 1 // DUMMY IFDEF USED TO HIDE PREAMBLE in EMACS enum MyParticles { kPDGPi = 211, kPDGK = 321, kPDGProton = 2212, kPDGKS0 = 310, kPDGLambda=3122, kPDGXi=3312,kPDGOmega=3334,kPDGPhi=333,kPDGKStar=313,kPDGDeuteron=1000010020,kPDGHE3 = 1000020030, kPDGHyperTriton = 1010010030, kPDGSigmaStarPlus=3224,kPDGSigmaStarMinus=3114,kPDGXiStar=3324}; typedef enum {kStatError, kSystError, kTotalError} myerror_t; TH1F * GetHistoRatios(TClonesArray * arr, Int_t system, Float_t energy, TString centrality, const char * histotitle, Int_t icolor, Int_t imarker = kOpenSquare, Int_t errorsType = kTotalError, Float_t shift = 0) ; TH1F * GetHistoYields(TClonesArray * arr, Int_t system, Float_t energy, TString centrality, const char * histotitle, Int_t icolor, Int_t imarker = kOpenSquare, Int_t errorsType = kTotalError, Float_t shift = 0) ; void PrepareThermalModelsInputFiles(TClonesArray * arr, Int_t system, Float_t energy, TString centrality, Bool_t separateCharges=0) ; void SetStyle(Bool_t graypalette=0) ; TLegend * NewLegendQM(Double_t x1, Double_t y1, Double_t x2, Double_t y2, Bool_t isYield = 0) ; void DrawRatio(TString what, Bool_t isYield = kFALSE, Double_t shiftloc=0.); void DrawFrame(Bool_t yields = 0) ; void DrawExtrapolatedSymbolsAndLegendPbPb0010() ; void DrawExtrapolatedSymbolsAndLegendpPb0005() ; void DrawMarkerKStarNoFit(Bool_t plotLegend = 0) ; void DrawMarkerNucleiNoFit() ; void DrawExtrapNotInFitpPb0005(Bool_t drawExtrap = 1) ; void DrawExtrapolatedSymbolsYieldsPbPb0010(Double_t x1=0.144578, Double_t y1=0.408249, Double_t x2=0.351406, Double_t y2=0.542403, Bool_t plotExtraploatedLegend=1); Float_t shiftRatioDataModel = 0; Double_t GetGraphRatioAndStdDev(TGraphErrors * gModel, TGraphErrors * &gRatio, TGraphErrors *&gStdDev) ; TString particlesToExcludeFromChi2 = "";// The above method recomputes the chi2. This string is used to store values to be excluded from this calculation. Each PDG cocde has to be enclosed in [..]. This is obviously not efficient as it involves many string conversions. But efficiency is not an issue here. void LoadArrays() ; //void AddLabel(Float_t x, Float_t y, TString text); void myLatexDraw(TLatex *currentLatex, Float_t currentSize=0.5, Int_t currentColor=1); void myPaveSetup(float rRatio=0, float rRange3=0, float rRange5=0, int rFillColor=0); void myPadSetUp(TPad *currentPad); TGraphErrors* PlotThermusYields(const char * filename, Int_t color, Int_t lineStyle, const char * tag); TGraphErrors * PlotGSIYields(const char * fileName, Int_t color=kBlack, Int_t lineStyle = kSolid, const char * tag ="", Bool_t isPbPb = 1); TGraphErrors* PlotFlorenceYields(const char * filename, Int_t color, Int_t lineStyle, const char * tag) ; void AddLineToThermalLegend(TObject * obj, TString line, const char * optFirst = "L"); void SaveCanvas(const char * name) ; // Ratios to be draw. Remember to change the labels in DrawFrame if you change this const Int_t nratio = 10; Int_t num [nratio] = {kPDGK , kPDGProton , kPDGLambda , kPDGXi , kPDGOmega , kPDGDeuteron , kPDGHE3 , kPDGHyperTriton , kPDGPhi , kPDGKStar}; Int_t denum[nratio] = {kPDGPi , kPDGPi , kPDGKS0 , kPDGPi , kPDGPi , kPDGProton , kPDGDeuteron , kPDGPi , kPDGK , kPDGK}; Int_t isSum[nratio] = {1 , 1 , 1 , 1 , 1 , 1 , 0 , 1 , 1 , 1 }; // const Int_t nratio = 10; // Int_t num [nratio] = {kPDGK , kPDGProton , kPDGLambda , kPDGXi , kPDGOmega , kPDGDeuteron , kPDGHE3 , kPDGHyperTriton , kPDGPhi , kPDGKStar}; // Int_t denum[nratio] = {kPDGPi , kPDGPi , kPDGKS0 , kPDGPi , kPDGPi , kPDGProton , kPDGDeuteron , kPDGPi , kPDGK , kPDGK}; // Int_t isSum[nratio] = {1 , 1 , 1 , 1 , 1 , 1 , 0 , 1 , 1 , 1 }; const char * ratiosLabels[] = {"#frac{K^{+}+K^{-}}{#pi^{+}+#pi^{-}}", "#frac{p+#bar{p}}{#pi^{+}+#pi^{-}}", "#frac{2#Lambda}{K_{S}^{0}}", "#frac{#Xi^{-}+#Xi^{+}}{#pi^{+}+#pi^{-}}", "#frac{#Omega^{-}+#Omega^{+}}{#pi^{+}+#pi^{-}}", "#frac{d}{p+#bar{p}}", "#frac{{}^{3}He }{d}", "#frac{{}^{3}_{#Lambda}H+{}^{3}_{#Lambda}#bar{H} }{#pi^{+}+#pi^{-}}", "#frac{#phi}{K^{+}+K^{-}}", "#frac{K*+#bar{K}*}{K^{+}+K^{-}}",}; //static const Double_t scale[] = {1 , 3 , 0.5 , 30 , 250 , 50 , 100 , 4e5 , 2 , 1 }; static const Double_t scale[] = {1 , 3 , 0.5 , 80 , 1000 , 50 , 100 , 4e5 , 2 , 1 }; //static const Double_t scale[] = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,}; const Int_t npart = 12; Int_t particleYields [npart] = {kPDGPi ,kPDGK ,kPDGKS0, kPDGKStar, kPDGPhi, kPDGProton , kPDGLambda , kPDGXi , kPDGOmega , kPDGDeuteron, kPDGHyperTriton, kPDGHE3 }; Int_t isSumYields[npart] = {1 ,1 ,0 , 1 , 0 , 1 ,1 ,1 ,1 ,0 , 1 , 0 }; //Int_t isSumInputFiles[npart] = {1 ,1 ,0 , 1 , 0 , 1 ,1 ,1 ,1 ,0 , 1 , 0 }; const char * yieldsLabels[] = {"#frac{#pi^{+}+#pi^{-}}{2}", "#frac{K^{+}+K^{-}}{2}", "K_{S}^{0}", "#frac{K*+K*}{2}", "#phi", "#frac{p+#bar{p}}{2}", "#Lambda", "#frac{#Xi^{-}+#Xi^{+}}{2}", "#frac{#Omega^{-}+#Omega^{+}}{2}", "d", "#frac{{}^{3}_{#Lambda}H+{}^{3}_{#Lambda}#bar{H}}{2}", "{}^{3}He", }; // Int_t markerNoFit = 28; Int_t markerExtrap = 27; Double_t maxy = 0.5; // Data arrays; TClonesArray *arrPbPb=0, *arrpp7=0, *arrpPb=0, * arrpp276=0, * arrpp900=0, * arrThermus=0; TClonesArray *arrSTARPbPb=0, *arrPHENIXPbPb=0, *arrBRAHMSPbPb=0; TClonesArray *arrSTARpp =0, *arrPHENIXpp=0; //const Double_t *scaleRatios = 0; Double_t *correlatedUnc = 0; //Double_t correlatedUncLocalPbPb[14] = {0.0424 , 0.0424 , 0.041 , 0 , 0 , 0.0424 , 0.0424 , 0 , 0.05 , 0.05 }; Double_t correlatedUncLocalPbPbOnlyKStarPhi[14] = {0. , 0. , 0. , 0 , 0 , 0. , 0. , 0 , 0.05 , 0.05 }; Double_t correlatedUncLocalPP [14] = {0.0424 , 0.0424 , 0.041 , 0 , 0 , 0.0424 , 0.0424 , 0 , 0.0424 , 0.0424 }; Double_t correlatedUncZero[14] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0}; TCanvas *myCan = 0; TPad *myPadStdDev =0; TPad *myPadRatio =0; TPad *myPadHisto =0; TPad *myPadLabel =0; TLegend * legThermal = 0; #endif Bool_t saveCanvas = 1; // if true, the canvas is saved and copied to the analysis note folder TClonesArray * PlotRatiosForQM14() { #if !(!defined (__CINT__) || (defined(__MAKECINT__))) LoadLibs(); #endif // LoadArrays(); // Uncomment stuff in this section to save the inputs for thermal models //#define SAVE_INPUT_THERMAL_MODEL #ifdef SAVE_INPUT_THERMAL_MODEL PrepareThermalModelsInputFiles(arrPbPb, AliParticleYield::kCSPbPb, 2760, "V0M0010", /*separateCharges*/1); // PrepareThermalModelsInputFiles(arrpp7, AliParticleYield::kCSpp, 7000, "", /*separateCharges*/1); // PrepareThermalModelsInputFiles(arrpPb, AliParticleYield::kCSpPb, 5020, "V0A0005", /*separateCharges*/1); // PrepareThermalModelsInputFiles(arrpPb, AliParticleYield::kCSpPb, 5020, "V0A2040", /*separateCharges*/1); // PrepareThermalModelsInputFiles(arrpPb, AliParticleYield::kCSpPb, 5020, "V0A6080", /*separateCharges*/1); // PrepareThermalModelsInputFiles(arrPbPb, AliParticleYield::kCSPbPb, 2760, "V0M6080", /* separateCharges*/1); // PrepareThermalModelsInputFiles(arrPbPb, AliParticleYield::kCSPbPb, 2760, "V0M2040", /*separateCharges*/1); PrepareThermalModelsInputFiles(arrPbPb, AliParticleYield::kCSPbPb, 2760, "V0M0010", /*separateCharges*/0); // PrepareThermalModelsInputFiles(arrpp7, AliParticleYield::kCSpp, 7000, "", /*separateCharges*/0); // PrepareThermalModelsInputFiles(arrpPb, AliParticleYield::kCSpPb, 5020, "V0A0005", /*separateCharges*/0); // PrepareThermalModelsInputFiles(arrpPb, AliParticleYield::kCSpPb, 5020, "V0A2040", /*separateCharges*/0); // PrepareThermalModelsInputFiles(arrpPb, AliParticleYield::kCSpPb, 5020, "V0A6080", /*separateCharges*/0); // PrepareThermalModelsInputFiles(arrPbPb, AliParticleYield::kCSPbPb, 2760, "V0M6080", /*separateCharges*/0); // PrepareThermalModelsInputFiles(arrPbPb, AliParticleYield::kCSPbPb, 2760, "V0M2040", /*separateCharges*/0); return 0; #endif SetStyle(); DrawRatio("allpp"); // DrawRatio("allppWithRHIC"); // DrawRatio("PbPbWithPP7TeV"); //DrawRatio("allsyst"); //DrawRatio("PbPb6080andpPb0005"); // DrawRatio("pp_vsRHIC"); // DrawRatio("PbPb_vsRHIC"); //DrawRatio("aliceall"); // Yields and FITS // maxy=2000; // DrawRatio("fit_ReferenceFit_PbPb0010", 1); // DrawRatio("fit_ReferenceFit_GSIONLY_PbPb0010", 1); // DrawRatio("fit_ReferenceFit_GSITHERMUS_PbPb0010",1); // DrawRatio("fitSHARE_NoPionsNoProtons_PbPb0010",1); // DrawRatio("fitGSI_NoPionsNoProtons_PbPb0010", 1); // DrawRatio("fitShare_All_PbPb0010", 1); // DrawRatio("fitShareWithWithoutNuclei_PbPb0010", 1); // maxy=200; // DrawRatio("fitGSI_PbPb6080", 1); // maxy=150; // DrawRatio("fitGSI_PbPb2040", 1); // maxy = 60; // DrawRatio("fitThermus_GammaSFree_pPb0005"); // DrawRatio("fitShare_pPb0005"); // DrawRatio("fitShare_pPb0005_NoOmega", 1); // maxy=20; // DrawRatio("fitThermus_GammaSFree_pPb2040"); // maxy=9; // DrawRatio("fitThermus_GammaSFree_pPb6080"); // maxy=9; // DrawRatio("fitGSI_pp"); // DrawRatio("fitFlorence_pp"); // NewLegendQM(); return arrPbPb; } TH1F * GetHistoRatios(TClonesArray * arr, Int_t system, Float_t energy, TString centrality, const char * histotitle, Int_t icolor, Int_t imarker, Int_t errorType, Float_t shift) { // FIXME: THIS SHOULD BE REVIEWED TO MAKE SURE THE PLOTS ARE LABELLED CORRECTLY // scaleRatios = scale; TH1F * h = new TH1F(Form("hRatio_%d_%0.0f_%s_%d",system,energy,centrality.Data(),errorType), histotitle, nratio, 1+shift, nratio+1+shift); TClonesArray * arrRatios = new TClonesArray ("AliParticleYield");// We save to disk the precomputed ratios Int_t iratioArr = 0;// Index used only to add particles to the array above // Double_t isSum = -1; // if this is -1, then the sum criterion is ignored for(Int_t iratio = 1; iratio <= nratio; iratio++){ std::cout << "******** " << num[iratio-1] << "/" << denum[iratio-1]<< " ("<<isSum[iratio-1]<<")*******" << std::endl ; AliParticleYield * ratio = AliParticleYield::FindRatio(arr, num[iratio-1], denum[iratio-1], system, energy, centrality,isSum[iratio-1]); if(ratio) { ratio = new AliParticleYield(*ratio); // We need to clone it to avoid a mess if we need to use this particle again later (e.g. double scalings) std::cout << " " ; ratio->Print("short"); } if(!ratio) { // If the ratio is not found, try to build it! std::cout << " Looking for " << num[iratio-1] << " ("<<isSum[iratio-1]<<")"<<std::endl; AliParticleYield * part1 = AliParticleYield::FindParticle(arr, num[iratio-1], system, energy, centrality, isSum[iratio-1]); if(part1) { part1 = new AliParticleYield(*part1); // We need to clone it to avoid a mess if we need to use this particle again later if(isSum[iratio-1] && part1->IsTypeAverage()) { std::cout << "Sum requested, found average, scaling x2" << std::endl; part1->Scale(2.); } } // Try with the !sum, if part 1 is not found if(!part1) { std::cout << " Looking for " << num[iratio-1] << " ("<<!isSum[iratio-1]<<")"<<std::endl; part1 = AliParticleYield::FindParticle(arr, num[iratio-1], system, energy, centrality,!isSum[iratio-1]); if(part1) { part1 = new AliParticleYield(*part1); // We need to clone it to avoid a mess if we need to use this particle again later // If the sum was requested, try to recover it! if(isSum[iratio-1]) { std::cout << " Looking for " << -num[iratio-1] <<std::endl; // If it's lambda and ALICE, use 2L instead of L + Lbar // FIXME: do the same for deuterons? if((num[iratio-1] == kPDGLambda || num[iratio-1] == kPDGDeuteron) && energy > 300) { std::cout << " It's Lambda or deuteron ALICE: Scaling x2 " << std::endl; part1->Print(); part1->Scale(2.); } else { AliParticleYield * part1_bar = AliParticleYield::FindParticle(arr, -num[iratio-1], system, energy, centrality,0); if(part1 && part1_bar) { std::cout << "Adding " << part1_bar->GetPartName() << " " << part1->GetPartName() << std::endl; part1 = AliParticleYield::Add(part1, part1_bar); } else if (TDatabasePDG::Instance()->GetParticle(-num[iratio-1])){ // Before scaling x2 check it it makes sense (antiparticle exists) std::cout << "WARNING: Sum requested but not found, scaling x2 " << part1->GetName() << std::endl; part1->Scale(2); } } } else if(part1) { // if we are here, it means the sum was *not* requested (isSum=0), but we found something with (!isSum) = 1 // if the not sum was requested, but the sum is found, divide by 2 so that it is comparable std::cout << "WARNING: Using sum/2 for " << part1->GetName() << std::endl; part1->Scale(0.5); } } } std::cout << " Looking for " << denum[iratio-1] << " ("<<isSum[iratio-1]<<")"<<std::endl; AliParticleYield * part2 = AliParticleYield::FindParticle(arr, denum[iratio-1], system, energy, centrality,isSum[iratio-1]); if(part2) { part2 = new AliParticleYield(*part2); // We need to clone it to avoid a mess if we need to use this particle again later if(isSum[iratio-1] && part2->IsTypeAverage()) { std::cout << "Sum requested, found average, scaling x2" << std::endl; part2->Scale(2.); } } if(!part2) {// Try with the !sum, if part 2 is not found std::cout << " Looking for " << denum[iratio-1] << " ("<<!isSum[iratio-1]<<")"<<std::endl; part2 = AliParticleYield::FindParticle(arr, denum[iratio-1], system, energy, centrality,!isSum[iratio-1]); if(part2) { part2 = new AliParticleYield(*part2); // We need to clone it to avoid a mess if we need to use this particle again later if(isSum[iratio-1]) { std::cout << " Looking for " << -denum[iratio-1] << std::endl; AliParticleYield * part2_bar = AliParticleYield::FindParticle(arr, -denum[iratio-1], system, energy, centrality,0); if(part2 && part2_bar){ std::cout << "Adding " << part2_bar->GetPartName() << " " << part2->GetPartName() << std::endl; part2 = AliParticleYield::Add(part2, part2_bar); } else if (TDatabasePDG::Instance()->GetParticle(-denum[iratio-1])){ // Before scaling x2 check it it makes sense (antiparticle exists) std::cout << "WARNING: Sum requested but not found, scaling x2 " << part2->GetName() << std::endl; part2->Scale(2); } } else if(part2){ // if the not sum was requested, but the sum is found, divide by 2 so that it is comparable std::cout << "WARNING: Using sum/2 for " << part2->GetName() << std::endl; part2->Scale(0.5); } } } ratio = AliParticleYield::Divide(part1, part2, correlatedUnc[iratio-1], "YQ"); // Assume by that the systematics of part1 and part2 are uncorrelated. if(ratio) { std::cout << "" << std::endl; std::cout << "WARNING: building ratio " << num[iratio-1] <<"/"<<denum[iratio-1]<<": Check uncertainties!!" << std::endl; ratio->Print(""); std::cout << "" << std::endl; } } if(ratio){ ratio->Scale(scale[iratio-1]); h->SetBinContent(iratio, ratio->GetYield()); if(errorType == kTotalError) { h->SetBinError (iratio, ratio->GetTotalError(0/* 0 = no normalization error */)); } else if (errorType == kStatError) { h->SetBinError (iratio, ratio->GetStatError()); } else if (errorType == kSystError) { h->SetBinError (iratio, ratio->GetSystError()); } else { std::cout << "ERROR: Unknown Error Type " << errorType << std::endl; } // h->GetXaxis()->SetBinLabel(iratio, Form("#splitline{%s}{%s}",Form("#times%2.2f", scale[iratio-1]), ratio->GetLatexName())); h->GetXaxis()->SetBinLabel(iratio, ratio->GetLatexName()); new ((*arrRatios)[iratioArr++]) AliParticleYield(*ratio); } else { h->GetXaxis()->SetBinLabel(iratio, Form("#frac{%d}{%d}",num[iratio-1], denum[iratio-1])); } std::cout << "*** END OF " << num[iratio-1] << "/" << denum[iratio-1]<< " *******" << std::endl ; } h->GetYaxis()->SetRangeUser(0, maxy); h->SetLineColor(icolor); h->SetMarkerColor(icolor); h->SetMarkerStyle(imarker); // the "if" avoids saving twice the same ratios if(errorType == kSystError) AliParticleYield::SaveAsASCIIFile(arrRatios, TString("ratios_")+h->GetName()); return h; } void PrepareThermalModelsInputFiles(TClonesArray * arr, Int_t system, Float_t energy, TString centrality, Bool_t separateCharges) { // If "Separate charges" is true, tries to dump both charges are dumped TClonesArray * arrOut = new TClonesArray("AliParticleYield"); TClonesArray * arrOutGSI = new TClonesArray("AliParticleYield"); // We add dummy lines to the GSI output file if needed! ; Int_t ipartOut = 0; // Index for the array Int_t ipartOutGSI = 0; // Index for the array for(Int_t ipart = 0; ipart < npart; ipart++){ if(!separateCharges) { AliParticleYield * part = AliParticleYield::FindParticle(arr, particleYields[ipart], system, energy, centrality, isSumYields[ipart]); if(!part && isSumYields[ipart]) { //Could not find the particle, but the sum was requested: build the sum! part = AliParticleYield::FindParticle(arr, particleYields[ipart], system, energy, centrality, 0); AliParticleYield * part2 = AliParticleYield::FindParticle(arr, -particleYields[ipart], system, energy, centrality, 0); if(part2 && part) part = AliParticleYield::Add(part, part2); else if(part) part->Scale(2.); // If we only found a particle, we can scale it by a factor 2. else part = 0; } // We want to save the average of particle and antiparticle in this case if(part) { if(isSumYields[ipart] && !part->IsTypeAverage()) part->Scale(0.5); // If it's not already an average, but just a sum, divide by 2 new((*arrOut )[ipartOut++]) AliParticleYield(*part); new((*arrOutGSI)[ipartOutGSI++]) AliParticleYield(*part); } else { // Add dummy particle to the GSI list new((*arrOutGSI)[ipartOutGSI++]) AliParticleYield(particleYields[ipart], system, energy, -10, -10, -10, -10, -10, -10, 5, 256, "DUMMY", 1, "ALICE"); } } else { // ignore isSumYields and try to find both particleYields Bool_t notFound = 0; AliParticleYield * part = AliParticleYield::FindParticle(arr, particleYields[ipart], system, energy, centrality, 0); if(part) { new((*arrOut)[ipartOut++]) AliParticleYield(*part); new((*arrOutGSI)[ipartOutGSI++]) AliParticleYield(*part); } else { // std::cout << "ADDING DUMMY part " << particleYields[ipart] << std::endl; // new((*arrOutGSI)[ipartOutGSI++]) AliParticleYield(particleYields[ipart], system, energy, -10, -10, -10, -10, -10, -10, 5, 256, "DUMMY", 1, "ALICE"); notFound=1; } // Try to find antiparticle (-pdg code) part = AliParticleYield::FindParticle(arr, -particleYields[ipart], system, energy, centrality, 0); if(part) { new((*arrOut)[ipartOut++]) AliParticleYield(*part); new((*arrOutGSI)[ipartOutGSI++]) AliParticleYield(*part); } else if (notFound) { // If neither charge was found, check if we at least have the sum part = AliParticleYield::FindParticle(arr, abs(particleYields[ipart]), system, energy, centrality, 1); if (part) { if(!part->IsTypeAverage()) part->Scale(0.5); // If it's a sum (not an average) divide by 2 new((*arrOut)[ipartOut++]) AliParticleYield(*part); new((*arrOutGSI)[ipartOutGSI++]) AliParticleYield(*part); if(TDatabasePDG::Instance()->GetParticle(-particleYields[ipart]) && (particleYields[ipart] != kPDGLambda) && (particleYields[ipart] != kPDGKStar) ){// if only the sum was found, add a dummy entry to the // GSI file, so that anton always has the same # of // lines. However, we don't do this for the Lambda and // KStar (always one of the charges or the average) new((*arrOutGSI)[ipartOutGSI++]) AliParticleYield(-particleYields[ipart], system, energy, -10, -10, -10, -10, -10, -10, 5, 256, "DUMMY", 1, "ALICE"); } } else { std::cout << "ADDING DUMMY sum " << particleYields[ipart] << std::endl; new((*arrOutGSI)[ipartOutGSI++]) AliParticleYield(particleYields[ipart], system, energy, -10, -10, -10, -10, -10, -10, 5, 256, "DUMMY", 1, "ALICE"); if (particleYields[ipart]==kPDGHyperTriton) { // If is the 3LH, add another one for the antiparticle AliParticleYield(-particleYields[ipart], system, energy, -10, -10, -10, -10, -10, -10, 5, 256, "DUMMY", 1, "ALICE"); } } } } } std::cout << "Particles for thermal model fits:" << std::endl; arrOut->Print("short"); // arrOut->Print(""); std::cout << "" << std::endl; // Write GSI input file TIter it(arrOutGSI); AliParticleYield * part = 0; ofstream fout(Form("gsi_System_%d_Energy_%0.0f_Centr_%s_BothCharges_%d", system, energy, centrality.Data(), separateCharges)); while ((part = (AliParticleYield*) it.Next())){ fout << part->GetYield() << " " << part->GetTotalError() << std::endl; } fout.close(); // Write thermus file AliParticleYield::WriteThermusFile(arrOut, Form("thermus_System_%d_Energy_%0.0f_Centr_%s_BothCharges_%d", system, energy, centrality.Data(), separateCharges)); } TH1F * GetHistoYields(TClonesArray * arr, Int_t system, Float_t energy, TString centrality, const char * histotitle, Int_t icolor, Int_t imarker, Int_t errorsType, Float_t shift) { TH1F * h = new TH1F(Form("hPart_%d_%0.0f_%s",system,energy,centrality.Data()), histotitle, npart, 1+shift, npart+1+shift); for(Int_t ipart = 1; ipart <= npart; ipart++){ std::cout << "----- Searching " << particleYields[ipart-1] << " -------" << std::endl; AliParticleYield * part = AliParticleYield::FindParticle(arr, particleYields[ipart-1], system, energy, centrality,isSumYields[ipart-1]); if(part) { std::cout << "found" << std::endl; part->Print(); } if(!part && isSumYields[ipart-1]) { //Could not find the particle, but the sum was requested: build the sum! part = AliParticleYield::FindParticle(arr, particleYields[ipart-1], system, energy, centrality, 0); AliParticleYield * part2 = AliParticleYield::FindParticle(arr, -particleYields[ipart-1], system, energy, centrality, 0); if(part2 && part) { std::cout << " Building sum" << std::endl; part->Print(); part2->Print(); part = AliParticleYield::Add(part, part2); } else if(part) { std::cout << "Scaling part" << std::endl; part->Print(); part = new AliParticleYield(*part); // Always clone before scaling part->Scale(2.); // If we only found a particle, we can scale it by a factor 2. } else part = 0; } if(!part){ std::cout << "Cannot find " << particleYields[ipart-1] << std::endl; continue; } if(isSumYields[ipart-1] && !part->IsTypeAverage()) { std::cout << " scaling /2" << std::endl; part = new AliParticleYield(*part); // Always clone before scaling part->Scale(0.5); // take average } std::cout << " Plotting " << particleYields[ipart-1] << std::endl; part->Print(); // part->Scale(scale[ipart-1]); h->SetBinContent(ipart, part->GetYield()); if(errorsType == kTotalError) { h->SetBinError (ipart, part->GetTotalError(0/* 0 = no normalization error */)); } else if (errorsType == kSystError) { h->SetBinError (ipart, part->GetSystError()); } else if (errorsType == kStatError) { h->SetBinError (ipart, part->GetStatError()); } h->GetXaxis()->SetBinLabel(ipart, part->GetLatexName()); } h->SetMarkerStyle(imarker); h->SetMarkerColor(icolor); h->SetLineColor(icolor); h->SetMarkerSize(1.4); return h; } void LoadArrays() { arrPbPb = AliParticleYield::ReadFromASCIIFile("PbPb_2760_Cascades.txt"); arrPbPb->AbsorbObjects( AliParticleYield::ReadFromASCIIFile("PbPb_2760_DeuHelium3.txt")); arrPbPb->AbsorbObjects( AliParticleYield::ReadFromASCIIFile("PbPb_2760_Hypertriton.txt")); arrPbPb->AbsorbObjects( AliParticleYield::ReadFromASCIIFile("PbPb_2760_Kstar892.txt")); arrPbPb->AbsorbObjects( AliParticleYield::ReadFromASCIIFile("PbPb_2760_LambdaK0.txt")); arrPbPb->AbsorbObjects( AliParticleYield::ReadFromASCIIFile("PbPb_2760_PiKaPr.txt")); arrPbPb->AbsorbObjects( AliParticleYield::ReadFromASCIIFile("PbPb_2760_phi1020.txt")); arrPbPb->AbsorbObjects( AliParticleYield::ReadFromASCIIFile("PbPb_2760_AveragedNumbers.txt")); arrpp7 = AliParticleYield::ReadFromASCIIFile("pp_7000.txt"); arrpp276 = AliParticleYield::ReadFromASCIIFile("pp_2760.txt"); arrpp900 = AliParticleYield::ReadFromASCIIFile("pp_900.txt"); arrpPb = AliParticleYield::ReadFromASCIIFile("pPb_5020_MultiStrange.txt"); arrpPb->AbsorbObjects(AliParticleYield::ReadFromASCIIFile("pPb_5020_PiKaPrLamndaK0.txt")); arrpPb->AbsorbObjects(AliParticleYield::ReadFromASCIIFile("pPb_5020_deuteron.txt")); arrpPb->AbsorbObjects(AliParticleYield::ReadFromASCIIFile("pPb_5020_AveragedNumbers.txt")); arrpPb->AbsorbObjects(AliParticleYield::ReadFromASCIIFile("pPb_5020_phi.txt")); arrpPb->AbsorbObjects(AliParticleYield::ReadFromASCIIFile("pPb_5020_Kstar.txt")); arrThermus = AliParticleYield::ReadFromASCIIFile("PbPb_2760_Thermus_Boris_20140407.txt"); // RHIC data arrSTARPbPb = AliParticleYield::ReadFromASCIIFile("PbPb_200_STAR-AntonQM12.txt"); arrPHENIXPbPb = AliParticleYield::ReadFromASCIIFile("PbPb_200_PHENIX-AntonQM12.txt"); arrBRAHMSPbPb = AliParticleYield::ReadFromASCIIFile("PbPb_200_BRAHMS-AntonQM12.txt"); arrSTARpp = AliParticleYield::ReadFromASCIIFile("pp_200_STAR.txt"); arrPHENIXpp = AliParticleYield::ReadFromASCIIFile("pp_200_PHENIX.txt"); } void SetStyle(Bool_t graypalette) { std::cout << "Setting style!" << std::endl; gStyle->Reset("Plain"); gStyle->SetOptTitle(0); gStyle->SetOptStat(0); if(graypalette) gStyle->SetPalette(8,0); else gStyle->SetPalette(1); gStyle->SetDrawBorder(0); gStyle->SetCanvasColor(10); gStyle->SetCanvasBorderMode(0); gStyle->SetPadBorderMode(0); gStyle->SetFrameLineWidth(1); gStyle->SetFrameFillColor(kWhite); gStyle->SetPadColor(10); gStyle->SetPadTickX(1); gStyle->SetPadTickY(1); gStyle->SetPadBottomMargin(0.15); gStyle->SetPadLeftMargin(0.15); gStyle->SetHistLineWidth(1); gStyle->SetHistLineColor(kRed); gStyle->SetFuncWidth(2); gStyle->SetFuncColor(kGreen); gStyle->SetLineWidth(1); gStyle->SetLabelSize(0.045,"yz"); gStyle->SetLabelSize(0.06,"x"); gStyle->SetLabelOffset(0.01,"y"); gStyle->SetLabelOffset(0.01,"x"); gStyle->SetLabelColor(kBlack,"xyz"); gStyle->SetTitleSize(0.05,"xyz"); gStyle->SetTitleOffset(1.25,"y"); gStyle->SetTitleOffset(1.2,"x"); gStyle->SetTitleFillColor(kWhite); gStyle->SetTextSizePixels(26); gStyle->SetTextFont(42); gStyle->SetTickLength(0.012,"X"); gStyle->SetTickLength(0.012,"Y"); gStyle->SetLegendBorderSize(0); gStyle->SetLegendFillColor(kWhite); // gStyle->SetFillColor(kWhite); gStyle->SetLegendFont(42); gStyle->SetErrorX(0); gStyle->SetEndErrorSize(5); } TLegend * NewLegendQM(Double_t x1, Double_t y1, Double_t x2, Double_t y2, Bool_t isYield) { const char * style = "p"; const char ** labels=0; // Bool_t beautify=kFALSE; Bool_t useTitle=kTRUE; TLegend * l = new TLegend(x1, y1, x2, y2); l->SetFillColor(kWhite); l->SetTextFont(43); l->SetTextSize(25); l->SetBorderSize(1); l->SetLineWidth(1); l->SetMargin(0.1); // const Int_t markers[] = {20,24,21,25,23,28,33,20,24,21,25,23,28,33}; // const Int_t colors[] = {1,2,3,4,6,7,8,9,10,11,1,2,3,4,6,7,8,9,10}; TList * list = gPad->GetListOfPrimitives(); TIterator * iter = list->MakeIterator(); TObject * obj = 0; Int_t ilabel = -1; while ((obj = (TObject*) iter->Next())){ if (obj->InheritsFrom("TH1") || obj->InheritsFrom("TGraph") || obj->InheritsFrom("TF1")) { if( (TString(obj->GetName()) == "hframe" ) ) continue; ilabel++; if (labels != 0) l->AddEntry(obj, labels[ilabel], style); else{ if (useTitle) { if(TString(obj->GetTitle()).Contains("NoLegend")) continue; TString title = obj->GetTitle(); if(title.Contains("p-Pb")) { TObjArray * tokens = title.Tokenize(","); if(tokens) { TString system = ((TObjString*) tokens->At(0))->String().Strip(TString::kBoth, ' '); TString centr = ((TObjString*) tokens->At(1))->String().Strip(TString::kBoth, ' '); l->AddEntry(obj, system, style); l->AddEntry(obj, centr, "0"); delete tokens; } } else { l->AddEntry(obj, obj->GetTitle(), style); } } else l->AddEntry(obj, obj->GetName(), style); } // if(beautify) { // if(!obj->InheritsFrom("TF1")){ // ((TH1*)obj)->SetLineColor(colors[ilabel]); // ((TH1*)obj)->SetMarkerColor(colors[ilabel]); // ((TH1*)obj)->SetMarkerStyle(markers[ilabel]); // } else { // ((TF1*)obj)->SetLineColor(colors[ilabel]); // } } } if(isYield) { // Add some details on excluded stuff l->SetTextSize(22); l->SetBorderSize(0); l->GetEntry()->SetOption("0"); l->SetMargin(0.01); } l->Draw(); return l; } void DrawRatio(TString what, Bool_t isYield, Double_t shift) { // This is used to simplify the code above // In order to draw syst error bars, we need to convert to graphs the syst errors histos // if isYield == true plots yields rather than ratios // Sample colors // const Int_t colors[] = {kBlack, kRed+1 , kBlue+1, kGreen+3, kMagenta+1, kOrange-1,kCyan+2,kYellow+2 , kWhite}; TClonesArray * array = 0; Int_t system, color, marker; Float_t energy = 0, shiftloc = shift; TString centrality, label; // FIXME: move this in the different sections below correlatedUnc = correlatedUncZero; std::cout << "Plotting " << what.Data() << std::endl; if (what == "frame" ) { correlatedUnc = correlatedUncZero; DrawFrame(isYield); // TH1 * h = GetHistoRatios(arrPbPb, AliParticleYield::kCSPbPb, 2760, "V0M0010", "NoLegend", kWhite); // h->Draw(); // h->GetYaxis()->SetDecimals(1); // h->GetYaxis()->SetNdivisions(505); // h->GetXaxis()->CenterLabels(1); // Int_t nratio = h->GetNbinsX(); if(!isYield) { for(Int_t iratio = 0; iratio < nratio; iratio++){ Double_t exp = TMath::Floor(TMath::Log10(TMath::Abs(scale[iratio]))); Double_t man = scale[iratio] / TMath::Power(10, exp); if(exp > 2) { // TLatex * scaleLabel = new TLatex(iratio+1+0.2,maxy*1.01, Form("#times %0.0f 10^{%0.0f}", man, exp)); TLatex * scaleLabel = new TLatex(iratio+1+0.2,0.005, Form("#times %0.0f 10^{%0.0f}", man, exp)); scaleLabel->SetTextFont(43); scaleLabel->SetTextSize(20); scaleLabel->Draw(); } else { Double_t shiftloc2 = scale[iratio] < 50 ? 0.3 : 0.2; TLatex * scaleLabel = new TLatex(iratio+1+shiftloc2, 0.005, Form("#times %g", scale[iratio])); scaleLabel->SetTextFont(43); scaleLabel->SetTextSize(20); scaleLabel->Draw(); } } } if(isYield) { TPaveText *pt = new TPaveText(0.691767, 0.86069, 0.893574, 0.944865,"brNDC"); pt->SetBorderSize(0); pt->SetFillColor(0); pt->SetTextAlign(12); pt->SetTextFont(43); pt->SetTextSize(23); pt->AddText("ALICE Preliminary"); pt->Draw(); } else { TPaveText *pt = new TPaveText( 0.176, 0.842881, 0.378514, 0.929595,"brNDC"); pt->SetBorderSize(0); pt->SetFillColor(0); pt->SetLineWidth(1); pt->SetTextFont(43); pt->SetTextSize(23); pt->AddText("ALICE Preliminary"); pt->Draw(); } gPad->SetGridx(); } else if (what == "PbPb_0010") { array = arrPbPb; system = 2; energy = 2760.; centrality = "V0M0010"; label = "Pb-Pb #sqrt{s}_{NN} = 2.76 TeV, 0-10%"; color = kRed+1; marker = kFullCircle; if(!shift) shiftloc = 0; correlatedUnc = correlatedUncLocalPbPbOnlyKStarPhi; } else if (what == "PbPb_6080") { array = arrPbPb; system = 2; energy = 2760.; centrality = "V0M6080"; label = "Pb-Pb #sqrt{s}_{NN} = 2.76 TeV, 60-80%"; color = kBlue+1; marker = kFullCircle; if(!shift) shiftloc = 0.0; correlatedUnc = correlatedUncLocalPbPbOnlyKStarPhi; } else if (what == "PbPb_2040") { array = arrPbPb; system = 2; energy = 2760.; centrality = "V0M2040"; label = "Pb-Pb #sqrt{s}_{NN} = 2.76 TeV, 20-40%"; color = kBlue+1; marker = kFullCircle; if(!shift) shiftloc = 0.0; correlatedUnc = correlatedUncLocalPbPbOnlyKStarPhi; } else if (what == "pp7") { array = arrpp7; system = 0; energy = 7000.; centrality = ""; label = "pp #sqrt{s} = 7 TeV"; color = kMagenta+1; marker = kFullCircle; if(!shift) shiftloc = 0.2; // correlatedUnc = correlatedUncLocalPP; } else if (what == "pp900") { array = arrpp900; system = 0; energy = 900.; centrality = ""; label = "pp #sqrt{s} = 0.9 TeV"; color = kCyan+2; marker = kFullCircle; if(!shift) shiftloc = -0.2; // correlatedUnc = correlatedUncLocalPP; } else if (what == "pp276") { array = arrpp276; system = 0; energy = 2760.; centrality = ""; label = "pp #sqrt{s} = 2.76 TeV"; color = kYellow+2; marker = kFullCircle; if(!shift) shiftloc = 0; // correlatedUnc = correlatedUncLocalPP; } else if (what == "pPb0005") { array = arrpPb; system = 1; energy = 5020.; centrality = "V0A0005"; // label = "p-Pb #sqrt{s}_{NN} = 5.02 TeV, V0A 0-5%"; label = "p-Pb #sqrt{s}_{NN} = 5.02 TeV, V0A Multiplicity (Pb-Side) 0-5%"; color = kBlack; marker = kFullCircle; if(!shift) shiftloc = -0.2; // correlatedUnc = correlatedUncLocalPP; } else if (what == "pPb2040") { array = arrpPb; system = 1; energy = 5020.; centrality = "V0A2040"; label = "p-Pb #sqrt{s}_{NN} = 5.02 TeV, V0A Multiplicity (Pb-Side) 20-40%"; color = kBlue+1; marker = kFullCircle; if(!shift) shiftloc = 0.; // correlatedUnc = correlatedUncLocalPP; } else if (what == "pPb6080") { array = arrpPb; system = 1; energy = 5020.; centrality = "V0A6080"; label = "p-Pb #sqrt{s}_{NN} = 5.02 TeV, V0A Multiplicity (Pb-Side) 60-80%"; color = kGreen+3; marker = kFullCircle; if(!shift) shiftloc = 0.; // correlatedUnc = correlatedUncLocalPP; } else if (what == "PbPbSTAR") { array = arrSTARPbPb; system = 2; energy = 200.; centrality = "0005"; label = "STAR, Au-Au #sqrt{s}_{NN} = 0.2 TeV, 0-5%"; color = kBlack; marker = kOpenStar; if(!shift) shiftloc = +0.2; // correlatedUnc = correlatedUncZero; } else if (what == "PbPbPHENIX") { array = arrPHENIXPbPb; system = 2; energy = 200.; centrality = "0005"; label = "PHENIX, Au-Au #sqrt{s}_{NN} = 0.2 TeV, 0-5%"; color = kBlack; marker = kOpenSquare; if(!shift) shiftloc = -0.15; // correlatedUnc = correlatedUncZero; } else if (what == "PbPbBRAHMS") { array = arrBRAHMSPbPb; system = 2; energy = 200.; centrality = "0010"; label = "BRAHMS, Au-Au #sqrt{s}_{NN} = 0.2 TeV, 0-10%"; color = kBlack; marker = kOpenCross; if(!shift) shiftloc = -0.3; // correlatedUnc = correlatedUncZero; } else if (what == "ppSTAR") { array = arrSTARpp; system = 0; energy = 200.; centrality = ""; label = "STAR, pp #sqrt{s} = 0.2 TeV"; color = kBlack; marker = kOpenStar; if(!shift) shiftloc = -0.15; // correlatedUnc = correlatedUncZero; } else if (what == "ppPHENIX") { array = arrPHENIXpp; system = 0; energy = 200.; centrality = ""; label = "PHENIX, pp #sqrt{s} = 0.2 TeV"; color = kBlack; marker = kOpenSquare; if(!shift) shiftloc = -0.2; // correlatedUnc = correlatedUncZero; } // From here on, it's meta names, to draw several series of ratios else if (what == "allpp"){ DrawRatio("frame"); DrawRatio("pp900"); DrawRatio("pp276"); DrawRatio("pp7"); array =0; NewLegendQM(0.62249, 0.635734, 0.910643, 0.94673); SaveCanvas("Ratios_pponly"); } else if (what == "allppWithRHIC"){ DrawRatio("frame"); DrawRatio("pp900", 0, 0.05); DrawRatio("pp276", 0, 0.20); DrawRatio("pp7", 0, 0.35); DrawRatio("ppPHENIX", 0, -0.35); DrawRatio("ppSTAR", 0, -0.15); array =0; NewLegendQM(0.588353, 0.636857, 0.910643, 0.948352); SaveCanvas("Ratios_pponly_withRHIC"); } else if (what == "PbPbWithPP7TeV"){ DrawRatio("frame"); DrawRatio("PbPb_0010", 0, 0.1); DrawRatio("pp7", 0, -0.1); array =0; NewLegendQM(0.538153, 0.749397, 0.893574, 0.950362); DrawExtrapolatedSymbolsAndLegendPbPb0010(); SaveCanvas("Ratios_withpp7tev"); } else if(what == "allsyst") { DrawRatio("frame"); DrawRatio("pp7", 0, -0.2); DrawRatio("pPb0005", 0, 0.00001); DrawRatio("PbPb_0010", 0, 0.2); array =0; NewLegendQM(0.462851, 0.631722, 0.89257, 0.936697); DrawExtrapolatedSymbolsAndLegendPbPb0010(); DrawExtrapolatedSymbolsAndLegendpPb0005(); SaveCanvas("Ratios_allsystems"); }else if(what =="PbPb6080andpPb0005") { DrawRatio("frame"); DrawRatio("pPb0005",0, -0.1); DrawRatio("PbPb_6080", 0, 0.1); array=0; NewLegendQM( 0.46988, 0.730036, 0.910643, 0.948736); DrawExtrapolatedSymbolsAndLegendpPb0005(); SaveCanvas("Ratios_6080vspPb"); }else if(what =="pp_vsRHIC") { DrawRatio("frame"); DrawRatio("pp7"); DrawRatio("ppPHENIX", 0, 0.00001); DrawRatio("ppSTAR"); array=0; NewLegendQM( 0.554217, 0.677869, 0.910643, 0.948736); SaveCanvas("Ratios_vsRHIC_pp"); } else if (what =="PbPb_vsRHIC") { DrawRatio("frame"); DrawRatio("PbPb_0010"); DrawRatio("PbPbSTAR"); DrawRatio("PbPbPHENIX"); DrawRatio("PbPbBRAHMS"); array = 0; NewLegendQM( 0.434739, 0.591593, 0.939759, 0.936697); DrawExtrapolatedSymbolsAndLegendPbPb0010(); SaveCanvas("Ratios_vsRHIC_PbPb"); } else if (what == "aliceall") { DrawRatio("frame"); DrawRatio("PbPb_0010"); DrawRatio("PbPb_6080"); DrawRatio("pPb0005"); DrawRatio("pp7"); DrawRatio("pp276"); DrawRatio("pp900"); } // FROM HERE: IT's yields else if( what == "fit_ReferenceFit_PbPb0010") { DrawRatio("frame",1); DrawRatio("PbPb_0010",1); particlesToExcludeFromChi2="[313]"; // do not consider K* legThermal->SetNColumns(4); AddLineToThermalLegend(legThermal, "Model,T (MeV), V (fm^{3}), #chi^{2}/NDF", "0"); // FIXME: sistemare valori rapporti shiftRatioDataModel=-0.2; PlotThermusYields("lhc2760_final_0005_single_gc_output_gs1_wevc_nkst.txt" , kBlack , kSolid , "THERMUS 2.3 , 155 #pm 2 , 5924 #pm 543 , 23.6/9"); shiftRatioDataModel =0; PlotGSIYields("data+therm_fit2_s2760_0-10qm14.dat" , kOrange-1 , kDashed , "GSI , 156 #pm 2 , 5330 #pm 505 , 17.4/9"); shiftRatioDataModel = 0.2; PlotThermusYields("NEW_fit_gamma_q_s_fixed_PbPb_0010_with_nuclei.txt" , kBlue+1 , kDashDotted , "SHARE 3 , 156 #pm 3 , 4476 #pm 696 , 14.1/9"); NewLegendQM(0.651606, 0.765993, 0.909639, 0.865951, 1); DrawMarkerKStarNoFit() ; DrawExtrapolatedSymbolsYieldsPbPb0010(); SaveCanvas("Fit_PbPb0010_Reference"); array =0; } else if( what == "fit_ReferenceFit_GSIONLY_PbPb0010") { DrawRatio("frame",1); DrawRatio("PbPb_0010",1); particlesToExcludeFromChi2="[313]"; // do not consider K* legThermal->SetNColumns(4); AddLineToThermalLegend(legThermal, "Model,T (MeV), V (fm^{3}), #chi^{2}/NDF", "0"); // FIXME: sistemare valori rapporti shiftRatioDataModel =0; PlotGSIYields("data+therm_fit2_s2760_0-10qm14.dat" , kBlack , kSolid , "GSI , 156 #pm 2 , 5330 #pm 505 , 17.4/9"); myPadHisto->cd(); NewLegendQM(0.651606, 0.765993, 0.909639, 0.865951, 1); DrawMarkerKStarNoFit() ; DrawExtrapolatedSymbolsYieldsPbPb0010(); SaveCanvas("Fit_PbPb0010_Reference_GSI"); array =0; } else if( what == "fit_ReferenceFit_GSITHERMUS_PbPb0010") { DrawRatio("frame",1); DrawRatio("PbPb_0010",1); particlesToExcludeFromChi2="[313]"; // do not consider K* legThermal->SetNColumns(4); AddLineToThermalLegend(legThermal, "Model,T (MeV), V (fm^{3}), #chi^{2}/NDF", "0"); // FIXME: sistemare valori rapporti shiftRatioDataModel =-0.1; PlotThermusYields("lhc2760_final_0005_single_gc_output_gs1_wevc_nkst.txt" , kBlack , kSolid , "THERMUS 2.3 , 155 #pm 2 , 5924 #pm 543 , 23.6/9"); shiftRatioDataModel =0.1; PlotGSIYields("data+therm_fit2_s2760_0-10qm14.dat" , kOrange-1 , kDashed , "GSI , 156 #pm 2 , 5330 #pm 505 , 17.4/9"); myPadHisto->cd(); NewLegendQM(0.651606, 0.765993, 0.909639, 0.865951, 1); DrawMarkerKStarNoFit() ; DrawExtrapolatedSymbolsYieldsPbPb0010(); SaveCanvas("Fit_PbPb0010_Reference_GSITHERMUS"); // SaveCanvas(""); array =0; }else if( what == "fitSHARE_NoPionsNoProtons_PbPb0010") { array =0; DrawRatio("frame",1); DrawRatio("PbPb_0010",1); legThermal->SetNColumns(4); AddLineToThermalLegend(legThermal, "Model,T (MeV), V (fm^{3}), #chi^{2}/NDF", "0"); particlesToExcludeFromChi2 = "[313]"; shiftRatioDataModel=-0.2; PlotThermusYields("NEW_fit_gamma_q_s_fixed_PbPb_0010_with_nuclei.txt" ,kBlack , kSolid ,"SHARE 3 , 156 #pm 3 , 4476 #pm 696 , 14.1/9 "); particlesToExcludeFromChi2 = "[313][2212]"; shiftRatioDataModel=0; PlotThermusYields("NEW_fit_gamma_q_s_fixed_PbPb_0010_with_nuclei_protons.txt" ,kOrange-1 , kDashed ,"SHARE 3 (no p) , 156 #pm 3 , 4520 #pm 623 , 8.2/8"); particlesToExcludeFromChi2 = "[313][211]"; shiftRatioDataModel=0.2; PlotThermusYields("NEW_fit_gamma_q_s_fixed_PbPb_0010_with_nuclei_pions.txt" ,kBlue+1 , kDashDotted ,"SHARE 3 (no #pi) , 157 #pm 3 , 4103 #pm 677 , 12.2/8"); myPadHisto->cd(); NewLegendQM(0.651606, 0.765993, 0.909639, 0.865951, 1); // Add markers for additional particles not in fit DrawMarkerKStarNoFit() ; DrawExtrapolatedSymbolsYieldsPbPb0010(); SaveCanvas("Fit_PbPb0010_SHARE_NoPiNoP"); } else if( what == "fitGSI_NoPionsNoProtons_PbPb0010") { array =0; DrawRatio("frame",1); DrawRatio("PbPb_0010",1); legThermal->SetNColumns(4); AddLineToThermalLegend(legThermal, "Model,T (MeV), V (fm^{3}), #chi^{2}/NDF", "0"); particlesToExcludeFromChi2 = "[313]"; shiftRatioDataModel=-0.2; PlotGSIYields("data+therm_fit2_s2760_0-10qm14.dat" , kBlack , kSolid , "GSI , 156 #pm 1.5 , 5330 #pm 505 , 18.1/9" ); particlesToExcludeFromChi2 = "[313][2212]"; shiftRatioDataModel=0.; PlotGSIYields("data+therm_fit2_s2760_0-10qm14NOp.dat" , kOrange-1 , kDashed , "GSI (no p) , 156 #pm 2 , 5590 #pm 330 , 7.7/8" ); particlesToExcludeFromChi2 = "[313][211]"; shiftRatioDataModel=0.2; PlotGSIYields("data+therm_fit2_s2760_0-10qm14NOpi.dat" , kBlue+1 , kDashDotted , "GSI (no #pi) , 157 #pm 2 , 4990 #pm 630 , 16.5/8"); myPadHisto->cd(); NewLegendQM(0.651606, 0.765993, 0.909639, 0.865951, 1); // Add markers for additional particles not in fit DrawMarkerKStarNoFit() ; DrawExtrapolatedSymbolsYieldsPbPb0010(); SaveCanvas("Fit_PbPb0010_GSI_NoPiNoP"); } else if (what == "fitShareWithWithoutNuclei_PbPb0010") { DrawRatio("frame",1); DrawRatio("PbPb_0010",1); legThermal->SetNColumns(4); AddLineToThermalLegend(legThermal, "Model,T (MeV), V (fm^{3}), #chi^{2}/NDF", "0"); shiftRatioDataModel = -0.1; particlesToExcludeFromChi2="[313]"; // do not consider K* and nuclei PlotThermusYields("NEW_fit_gamma_q_s_fixed_PbPb_0010_with_nuclei.txt" , kBlack , kSolid , "SHARE 3 , 156 #pm 3 , 4476 #pm 696 , 14.1/9"); shiftRatioDataModel = 0.1; particlesToExcludeFromChi2="[313][1000010020][1000020030][1010010030]"; // do not consider K* and nuclei PlotThermusYields("NEW_fit_gamma_q_fixed_PbPb_0010_without_nuclei.txt" , kCyan+2 , kDashDotted , "SHARE 3 (no nuclei), 156 #pm 4 , 4364 #pm 848 , 9.6/6"); NewLegendQM(0.651606, 0.765993, 0.909639, 0.865951, 1); DrawMarkerKStarNoFit() ; DrawExtrapolatedSymbolsYieldsPbPb0010(); SaveCanvas("Fit_PbPb0010_SHARE_WithWoNuclei"); } else if( what == "fitThermus_GammaSFree_PbPb0010") { std::cout << "MISSING DATA" << std::endl; array =0; } else if( what == "fitShare_GammaSGammaQFree_PbPb0010") { std::cout << "MISSING DATA" << std::endl; array =0; } else if( what == "fitShare_All_PbPb0010") { DrawRatio("frame",1); DrawRatio("PbPb_0010",1); legThermal->SetNColumns(6); AddLineToThermalLegend(legThermal, "Model,T (MeV), V (fm^{3}), #gamma_{s}, #gamma_{q}, #chi^{2}/NDF", "0"); particlesToExcludeFromChi2="[313][1000010020][1000020030][1010010030]"; // do not consider K* and nuclei shiftRatioDataModel = -0.3; PlotThermusYields("NEW_fit_gamma_q_s_fixed_PbPb_0010_without_nuclei.txt" , kBlack , kSolid , "SHARE 3 , 156 #pm 4 , 4364 #pm 848 , 1 (fix) , 1 (fix) , 12.4/6"); shiftRatioDataModel = -0.1; PlotThermusYields("NEW_fit_gamma_q_fixed_PbPb_0010_without_nuclei.txt" , kRed+1 , kDashDotted , "SHARE 3 , 155 #pm 3 , 4406 #pm 766 , 1.07 #pm 0.05 , 1 (fix) , 9.6/5"); shiftRatioDataModel = 0.1; PlotThermusYields("NEW_fit_gamma_q_s_free_PbPb_0010_without_nuclei.txt" , kCyan+2 , kDashed , "SHARE 3 , 138 #pm 6 , 3064 #pm 1319 , 1.98 #pm 0.68 , 1.63 #pm 0.38 , 3.1/4"); shiftRatioDataModel = 0.3; particlesToExcludeFromChi2="[313]"; // do not consider K* PlotThermusYields("NEW_fit_gamma_q_s_free_PbPb_0010_with_nuclei.txt" , kOrange - 1 , kDotted , "SHARE 3 (with nuclei) , 152 #pm 8 , 4445 #pm 743 , 1.16 #pm 0.20 , 1.06 #pm 0.12 , 9.0/7"); NewLegendQM(0.651606, 0.765993, 0.909639, 0.865951, 1); DrawMarkerKStarNoFit() ; DrawMarkerNucleiNoFit(); DrawExtrapolatedSymbolsYieldsPbPb0010(); legThermal->SetX1(0.12249 ); legThermal->SetY1(0.0454769); legThermal->SetX2(0.821285 ); legThermal->SetY2(0.383481 ); SaveCanvas("Fit_PbPb0010_SHARE_All"); array =0; } else if( what == "fitGSI_PbPb6080") { DrawRatio("frame",1); DrawRatio("PbPb_6080",1); legThermal->SetNColumns(4); AddLineToThermalLegend(legThermal, "Model,T (MeV), V (fm^{3}), #chi^{2}/NDF", "0"); particlesToExcludeFromChi2 = "[313][1000020030][1010010030]"; PlotGSIYields ("data+therm_fit2_s2760_60-80qm14.dat", kBlack, kSolid, "GSI, 157 #pm 2, 210 #pm 20, 8.2/7"); legThermal->SetX1(0.143574 ); legThermal->SetY1(0.0731318 ); legThermal->SetX2(0.659639 ); legThermal->SetY2(0.245206 ); myPadHisto->cd(); NewLegendQM(0.651606, 0.765993, 0.909639, 0.865951, 1); DrawMarkerKStarNoFit(1) ; // DrawExtrapolatedSymbolsYieldsPbPb0010(0.143574, 0.251352, 0.351406, 0.343535,0); //DrawExtrapolatedSymbolsYieldsPbPb0010(); SaveCanvas("Fit_PbPb6080_GSI"); array =0; }else if( what == "fitGSI_PbPb2040") { DrawRatio("frame",1); DrawRatio("PbPb_2040",1); legThermal->SetNColumns(4); AddLineToThermalLegend(legThermal, "Model,T (MeV), V (fm^{3}), #chi^{2}/NDF", "0"); particlesToExcludeFromChi2 = "[313][1000020030][1010010030]"; PlotGSIYields ("data+therm_fit2_s2760_20-40qm14.dat", kBlack, kSolid, "GSI, 161 #pm 3, 1725 #pm 220, 24.6/7"); legThermal->SetX1(0.143574 ); legThermal->SetY1(0.0731318 ); legThermal->SetX2(0.659639 ); legThermal->SetY2(0.245206 ); myPadHisto->cd(); NewLegendQM(0.651606, 0.765993, 0.909639, 0.865951, 1); DrawMarkerKStarNoFit(1) ; // DrawMarkerKStarNoFit() ; // DrawExtrapolatedSymbolsYieldsPbPb0010(0.143574, 0.251352, 0.351406, 0.343535,0); //DrawExtrapolatedSymbolsYieldsPbPb0010(); SaveCanvas("Fit_PbPb2040_GSI"); array =0; } else if( what == "fitGSI_pPb0005") { std::cout << "MISSING DATA" << std::endl; array =0; } else if( what == "fitGSI_pPb2040") { std::cout << "MISSING DATA" << std::endl; array =0; } else if( what == "fitThermus_GammaSFree_pPb0005") { DrawRatio("frame",1); DrawRatio("pPb0005",1, 0.00001); particlesToExcludeFromChi2="[313][1000020030][1010010030] "; // do not consider K* legThermal->SetNColumns(6); AddLineToThermalLegend(legThermal, "Model,T (MeV), #gamma_{s}, r_{C} (fm), r (fm), #chi^{2}/NDF", "0"); shiftRatioDataModel=-0.2; PlotThermusYields("lhc5020_final_0005_single_gc_output_gs1_wevc_nkst.txt" , kBlack , kSolid , "THERMUS 2.3 GC , 158 #pm 2 , 1 (fix) , N/A , 3.40 #pm 0.11 , 32.0/7"); shiftRatioDataModel =0; PlotThermusYields("lhc5020_final_0005_single_gc_output_gsf_wevc_nkst.txt" , kOrange-1 , kDashed , "THERMUS 2.3 GC , 159 #pm 2 , 0.98 #pm 0.03 , N/A , 3.40 #pm 0.11 , 31.3/6"); shiftRatioDataModel = 0.2; PlotThermusYields("lhc5020_final_0005_single_sc_output_gs1_woevc_nkst.txt", kCyan+2 , kDashDotted , "THERMUS 2.3 SC , 158 #pm 3 , 1 (fix) , 4.61 #pm 3.77 , 3.07 #pm 0.13 , 29.6/6"); //lhc5020_final_0005_single_gc_output_gsf.txt //lhc5020_final_0005_single_sc_output_gs1.txt NewLegendQM(0.650602, 0.694971, 0.909639, 0.865951, 1); DrawExtrapNotInFitpPb0005() ; legThermal->SetX1(0.121486 ); legThermal->SetY1(0.0741793); legThermal->SetX2(0.759036 ); legThermal->SetY2(0.384575 ); SaveCanvas("Fit_pPb0005_THERMUS"); //DrawExtrapolatedSymbolsAndLegendPbPb0010(); array =0; } else if( what == "fitThermus_GammaSFree_pPb2040") { DrawRatio("frame",1); DrawRatio("pPb2040",1, 0.00001); particlesToExcludeFromChi2="[313][1000020030][1010010030] "; // do not consider K* legThermal->SetNColumns(6); AddLineToThermalLegend(legThermal, "Model,T (MeV), #gamma_{s}, r_{C} (fm), r (fm), #chi^{2}/NDF", "0"); shiftRatioDataModel=-0.2; PlotThermusYields("lhc5020_final_2040_single_gc_output_gs1_wevc_nkst.txt" , kBlack , kSolid , "THERMUS 2.3 GC , 155 #pm 2 , 1 (fix) , N/A , 2.83 #pm 0.08 , 40.1/7"); shiftRatioDataModel =0; PlotThermusYields("lhc5020_final_2040_single_gc_output_gsf_wevc_nkst.txt" , kOrange-1 , kDashed , "THERMUS 2.3 GC , 156 #pm 2 , 0.93 #pm 0.03 , N/A , 2.83 #pm 0.08 , 34.6/6"); shiftRatioDataModel = 0.2; PlotThermusYields("lhc5020_final_2040_single_sc_output_gs1_woevc_nkst.txt", kCyan+2 , kDashDotted , "THERMUS 2.3 SC , 156 #pm 2 , 1 (fix) , 3.45 #pm 0.77 , 2.54 #pm 0.09 , 35.5/6"); //lhc5020_final_0005_single_gc_output_gsf.txt //lhc5020_final_0005_single_sc_output_gs1.txt NewLegendQM(0.650602, 0.694971, 0.909639, 0.865951, 1); DrawExtrapNotInFitpPb0005(0) ; legThermal->SetX1(0.121486 ); legThermal->SetY1(0.0741793); legThermal->SetX2(0.759036 ); legThermal->SetY2(0.384575 ); SaveCanvas("Fit_pPb2040_THERMUS"); array =0; } else if( what == "fitThermus_GammaSFree_pPb6080") { DrawRatio("frame",1); DrawRatio("pPb6080",1, 0.00001); particlesToExcludeFromChi2="[313][1000020030][1010010030][1000010020]"; // do not consider K* legThermal->SetNColumns(6); AddLineToThermalLegend(legThermal, "Model,T (MeV), #gamma_{s}, r_{C} (fm), r (fm), #chi^{2}/NDF", "0"); shiftRatioDataModel=-0.2; PlotThermusYields("lhc5020_final_6080_single_gc_output_gs1_wevc_nkst.txt" , kBlack , kSolid , "THERMUS 2.3 GC , 152 #pm 2 , 1 (fix) , N/A , 2.18 #pm 0.06 , 48.2/7"); shiftRatioDataModel =0; PlotThermusYields("lhc5020_final_6080_single_gc_output_gsf_wevc_nkst.txt" , kOrange-1 , kDashed , "THERMUS 2.3 GC , 154 #pm 2 , 0.88 #pm 3 , N/A , 2.21 #pm 0.07 , 28.8/6"); shiftRatioDataModel = 0.2; PlotThermusYields("lhc5020_final_6080_single_sc_output_gs1_woevc_nkst.txt", kCyan+2 , kDashDotted , "THERMUS 2.3 SC , 154 #pm 2 ,1 (fix) ,3.18 #pm 0.57 ,1.96 #pm 0.07 ,40.5/6"); //lhc5020_final_0005_single_gc_output_gsf.txt //lhc5020_final_0005_single_sc_output_gs1.txt NewLegendQM(0.650602, 0.694971, 0.909639, 0.865951, 1); DrawExtrapNotInFitpPb0005(0) ; legThermal->SetX1(0.121486 ); legThermal->SetY1(0.0268308 ); legThermal->SetX2(0.758032 ); legThermal->SetY2(0.337226 ); SaveCanvas("Fit_pPb6080_THERMUS"); array =0; } else if( what == "fitThermus_RC_pPb0005") { std::cout << "MISSING DATA" << std::endl; array =0; } else if( what == "fitThermus_RC_pPb2040") { std::cout << "MISSING DATA" << std::endl; array =0; } else if( what == "fitThermus_RC_pPb6080") { std::cout << "MISSING DATA" << std::endl; array =0; } else if( what == "fitShare_pPb0005") { DrawRatio("frame",1); DrawRatio("pPb0005",1, 0.00001); legThermal->SetNColumns(6); AddLineToThermalLegend(legThermal, "Model,T (MeV), V (fm^{3}), #gamma_{s}, #gamma_{q}, #chi^{2}/NDF", "0"); particlesToExcludeFromChi2="[313][1000010020][1000020030][1010010030]"; // do not consider K* and nuclei shiftRatioDataModel = -0.2; PlotThermusYields("NEW_fit_gamma_q_s_fixed_pPb_0005_without_nuclei.txt" , kBlack , kSolid , "SHARE 3 , 158 #pm 3 , 121 #pm 18 , 1 (fix) , 1 (fix) , 24.3/6"); shiftRatioDataModel = 0; PlotThermusYields("NEW_fit_gamma_q_fixed_pPb_0005_without_nuclei.txt" , kBlue+1 , kDashDotted , "SHARE 3 , 161 #pm 3 , 115 #pm 17 , 0.93 #pm 0.04 , 1 (fix) , 20.3/5"); shiftRatioDataModel = 0.2; PlotThermusYields("NEW_fit_gamma_q_s_free_pPb_0005_without_nuclei.txt" , kOrange+2 , kDashDotted , "SHARE 3 , 144 #pm 1 , 81 #pm 25 , 1.599 #pm 0 , 1.71 #pm 0.06 , 11.4/4"); NewLegendQM(0.650602, 0.694971, 0.909639, 0.865951, 1); DrawExtrapNotInFitpPb0005() ; DrawMarkerNucleiNoFit(); legThermal->SetX1(0.124498 ); legThermal->SetY1(0.0715488); legThermal->SetX2(0.672691 ); legThermal->SetY2(0.384575 ); SaveCanvas("Fit_pPb0005_SHARE"); array =0; } else if( what == "fitShare_pPb0005_NoOmega") { DrawRatio("frame",1); DrawRatio("pPb0005",1, 0.00001); legThermal->SetNColumns(6); AddLineToThermalLegend(legThermal, "Model,T (MeV), V (fm^{3}), #gamma_{s}, #gamma_{q}, #chi^{2}/NDF", "0"); particlesToExcludeFromChi2="[313][1000010020][1000020030][1010010030]"; // do not consider K* and nuclei shiftRatioDataModel = -0.3; PlotThermusYields("NEW_fit_gamma_q_s_fixed_pPb_0005_without_nuclei.txt" , kBlack , kSolid , "SHARE 3 , 158 #pm 3 , 121 #pm 18 , 1 (fix) , 1 (fix), 24.3/6"); shiftRatioDataModel = -.1; PlotThermusYields("NEW_fit_gamma_q_s_fixed_pPb_0005_without_nuclei_excluding_Omega.txt" , kBlue+1 , kDashDotted , "SHARE 3 (No #Omega) , 163 #pm 4 , 99 #pm 17 , 1 (fix) , 1 (fix), 15.6/5"); shiftRatioDataModel = 0.1; PlotThermusYields("NEW_fit_gamma_q_fixed_pPb_0005_without_nuclei_excluding_Omega.txt" , kOrange+2 , kDashed , "SHARE 3 (No #Omega) , 163 #pm 3 , 100 #pm 16 , 0.96 #pm 0.04 , 1 (fix), 14.7/4"); shiftRatioDataModel = 0.3; PlotThermusYields("NEW_fit_gamma_q_s_fixed_pPb_0005_with_nuclei_excluding_Omega.txt" , kCyan+2 , kDotted , "SHARE 3 (No #Omega + d) , 160 #pm 3 , 114 #pm 17 , 1 (fix) , 1 (fix), 18.6/6"); NewLegendQM(0.650602, 0.694971, 0.909639, 0.865951, 1); DrawExtrapNotInFitpPb0005() ; DrawMarkerNucleiNoFit(); legThermal->SetX1(0.124498 ); legThermal->SetY1(0.0715488); legThermal->SetX2(0.672691 ); legThermal->SetY2(0.384575 ); SaveCanvas("Fit_pPb0005_SHARE_NoOmega"); array =0; } else if( what == "fitShare_pPb2040") { std::cout << "MISSING DATA" << std::endl; array =0; } else if( what == "fitShare_pPb6080") { std::cout << "MISSING DATA" << std::endl; array =0; } else if( what == "fitGSI_pp") { DrawRatio("frame",1); DrawRatio("pp7",1, 0.00001); legThermal->SetNColumns(5); AddLineToThermalLegend(legThermal, "Model,T (MeV), V (fm^{3}), #gamma_{s}, #chi^{2}/NDF", "0"); particlesToExcludeFromChi2 = "[313][1000020030][1010010030]"; shiftRatioDataModel=-0.1; PlotGSIYields ("data+therm_fit2_s7000.dat", kBlack, kSolid, "GSI, 146 #pm 2, 25 #pm 2, 1 (fix), 78.2/7", 0); shiftRatioDataModel=0.1; PlotGSIYields ("data+therm_fit2_s7000gs.dat", kRed+1, kDashed, "GSI, 150 #pm 2, 23 #pm 2, 0.88, 45.6/7", 0); legThermal->SetX1(0.143574 ); legThermal->SetY1(0.0731318); legThermal->SetX2(0.659639 ); legThermal->SetY2(0.374263 ); myPadHisto->cd(); NewLegendQM(0.725904, 0.761431, 0.874498, 0.841323, 1); DrawMarkerKStarNoFit(); TLegend * leg = new TLegend(0.143574, 0.380408, 0.351406, 0.4603, NULL, "brNDC"); leg->SetBorderSize(0); leg->SetTextFont(43); leg->SetTextSize(14); leg->SetLineColor(1); leg->SetLineStyle(1); leg->SetLineWidth(1); leg->SetFillColor(0); leg->SetFillStyle(1001); TLegendEntry * entry=leg->AddEntry("TMarker","Not in fit","p"); entry->SetLineColor(1); entry->SetLineStyle(1); entry->SetLineWidth(1); entry->SetMarkerColor(1); entry->SetMarkerStyle(markerNoFit); entry->SetMarkerSize(1.2); entry->SetTextFont(43); leg->Draw(); SaveCanvas("Fit_pp7000_GSI"); //DrawExtrapNotInFitpPb0005(0); array =0; }else if( what == "fitFlorence_pp") { DrawRatio("frame",1); DrawRatio("pp7",1, 0.00001); legThermal->SetNColumns(1); AddLineToThermalLegend(legThermal, "Model", "0"); shiftRatioDataModel = -0.1; particlesToExcludeFromChi2 = "[1000020030][1010010030][1000010020]"; PlotFlorenceYields("pp7000_Florence.txt", kBlack, kSolid, "Becattini et al."); shiftRatioDataModel = 0.1; particlesToExcludeFromChi2 = "[313][1000020030][1010010030]"; PlotGSIYields ("data+therm_fit2_s7000gs.dat", kRed+1, kDashed, "GSI GC",0); myPadHisto->cd(); NewLegendQM(0.725904, 0.761431, 0.874498, 0.841323, 1); SaveCanvas("Fit_pp7000_Florence"); //DrawExtrapNotInFitpPb0005(0); array =0; } else if( what == "fitGSI_fullCanonical") { std::cout << "MISSING DATA" << std::endl; array =0; } else if( what == "fitThermus_RC_pp") { std::cout << "MISSING DATA" << std::endl; array =0; } else if( what == "fitShare_pp") { std::cout << "MISSING DATA" << std::endl; array =0; } else { std::cout << "Unknown ratio " << what.Data() << std::endl; return; } if(!correlatedUnc) { std::cout << "correlatedUnc not set!" << std::endl; } std::cout << "CORR: " << correlatedUnc[1] << std::endl; if(array) { if(isYield) { TGraphErrors * hstat = AliPWGHistoTools::GetGraphFromHisto(GetHistoYields(array, system, energy, centrality, label, color, marker, kStatError, shiftloc) ,0); hstat->SetMarkerSize(1.2); hstat->Draw("PZ"); AliPWGHistoTools::GetGraphFromHisto(GetHistoYields(array, system, energy, centrality, label+"NoLegend", color, marker, kSystError, shiftloc) ,0)->Draw("[]"); } else { AliPWGHistoTools::GetGraphFromHisto(GetHistoRatios(array, system, energy, centrality, label, color, marker, kStatError, shiftloc) ,0)->Draw("PZ"); AliPWGHistoTools::GetGraphFromHisto(GetHistoRatios(array, system, energy, centrality, label+"NoLegend", color, marker, kSystError, shiftloc) ,0)->Draw("[]"); } } } void DrawFrame(Bool_t isYield) { myCan = new TCanvas("myCan","ThermalFits",50,10,1000,isYield ? 950 : 650); myCan->Draw(); myCan->cd(); // Set the Pads Double_t boundaryLabels = isYield ? 0.88 : 0.85;//0.92; myPadLabel = new TPad("myPadLabel","myPadLabel",0.0, boundaryLabels,1.0,1.0); myPadSetUp(myPadLabel); myPadLabel->Draw(); myPadHisto = new TPad("myPadHisto","myPadHisto",0.0,isYield ? 0.4 : 0.05 ,1.0, boundaryLabels,0); myPadSetUp(myPadHisto); myPadHisto->Draw(); myPadStdDev = new TPad("myPadStdDev","myPadStdDev",0.0,0.035,1.0,0.215,0); myPadSetUp(myPadStdDev); if(isYield) myPadStdDev->Draw(); myPadStdDev->SetGridx(); myPadStdDev->SetGridy(); // This pad is for the ratios data/model myPadRatio = new TPad("myPadRatio","myPadRatio",0.0,0.22,1.0,0.4,0); myPadSetUp(myPadRatio); if(isYield) myPadRatio->Draw(); myPadRatio->SetGridx(); myPadRatio->SetGridy(); myPadLabel->cd(); double xLabelPosition[nratio] = {0.124498, 0.211847, 0.31, 0.38, 0.465, 0.575, 0.644, 0.72, 0.82, 0.905 }; double xLabelYields[npart] = {0.115, 0.185, 0.270, 0.330, 0.422, 0.485, 0.570, 0.625, 0.695, 0.785, 0.835, 0.915}; double yLabelPosition = 0.40; // labels if(isYield) { for(Int_t ipart = 0; ipart < npart; ipart++){ TLatex *myPart = new TLatex(xLabelYields[ipart],yLabelPosition, yieldsLabels[ipart]); myLatexDraw(myPart,20); } } else { for(Int_t iratio = 0; iratio < nratio; iratio++){ TLatex *myRatio = new TLatex(xLabelPosition[iratio],yLabelPosition, ratiosLabels[iratio]); myLatexDraw(myRatio,20); } } // Xi's and Omega's bar (there was no way to convince root to draw it properly) if(isYield) { TLine *line = new TLine(0.653,0.660,0.663,0.660); line->SetLineWidth(2); line->Draw(); line = new TLine(0.725,0.660,0.738,0.660); line->SetLineWidth(2); line->Draw(); line = new TLine(0.362,0.660,0.374,0.660); line->SetLineWidth(2); line->Draw(); } else { TLine *line = new TLine(0.408,0.68,0.418,0.68); line->SetLineWidth(2); line->Draw(); line = new TLine(0.498,0.68,0.513,0.68); line->SetLineWidth(2); line->Draw(); } if(isYield) { myPadStdDev->cd(); myPadStdDev->SetTopMargin(0.0); myPadStdDev->SetTicks(1,1); Float_t devMax = 4.7; TH2F *myBlankStdDev = new TH2F("myBlankStdDev","myBlankStdDev",npart,1,npart+1,10,-devMax,+devMax); myBlankStdDev->GetXaxis()->SetLabelFont(43); // precision 3: size will be in pixels myBlankStdDev->GetYaxis()->SetLabelFont(43); myBlankStdDev->GetYaxis()->SetTitleFont(43); myBlankStdDev->SetLabelSize(23,"xy"); myBlankStdDev->SetTitleSize(20,"y"); myBlankStdDev->SetNdivisions(20,"x"); myBlankStdDev->SetNdivisions(605,"y"); myBlankStdDev->SetLabelOffset(0.012,"xy"); myBlankStdDev->SetYTitle("(mod.-data)/#sigma_{data}"); myBlankStdDev->SetTitleOffset(1.65,"y"); myBlankStdDev->Draw(); TH2F *myBlankRatio = new TH2F("myBlankRatio","myBlankRatio",npart,1,npart+1,10,-0.8,0.8); myBlankRatio->GetXaxis()->SetLabelFont(43); // precision 3: size will be in pixels myBlankRatio->GetYaxis()->SetLabelFont(43); myBlankRatio->GetYaxis()->SetTitleFont(43); myBlankRatio->SetLabelSize(23,"xy"); myBlankRatio->SetTitleSize(20,"y"); myBlankRatio->SetNdivisions(20,"x"); myBlankRatio->SetNdivisions(605,"y"); myBlankRatio->SetLabelOffset(0.012,"xy"); myBlankRatio->SetYTitle("(mod.-data)/mod."); myBlankRatio->SetTitleOffset(1.65,"y"); myPadRatio->cd(); // myPadRatio->SetLogy(); myBlankRatio->Draw(); } myPadHisto->cd(); myPadHisto->SetBottomMargin(isYield ? 0.01 : 0.04); // myPadHisto->SetLogy(); myPadHisto->SetTicks(1,1); TH1 *myBlankHisto = 0; if(isYield) { myBlankHisto = new TH2F("NoLegend","NoLegend",npart,1,npart+1,10, 0.00002, maxy+0.01 ); gPad->SetLogy(); } else { myBlankHisto = new TH2F("NoLegend","NoLegend",nratio,1,nratio+1,10, 0, maxy+0.01 ); } myBlankHisto->GetXaxis()->SetLabelFont(43); // precision 3: size will be in pixels myBlankHisto->GetYaxis()->SetLabelFont(43); myBlankHisto->GetYaxis()->SetTitleFont(43); myBlankHisto->SetLabelSize(23,"y"); myBlankHisto->SetLabelSize(0,"x"); myBlankHisto->SetTitleSize(26,"y"); myBlankHisto->SetMaximum(10); myBlankHisto->SetMinimum(0); myBlankHisto->SetNdivisions(isYield? 20 :10,"x"); myBlankHisto->SetNdivisions(505,"y"); if(isYield) myBlankHisto->SetYTitle("d#it{N}/d#it{y}"); myBlankHisto->SetLabelOffset(0.012,"xy"); myBlankHisto->SetTitleOffset(isYield ? 1.3 : 1,"y"); myBlankHisto->Draw(); if(isYield) { legThermal = new TLegend(0.144578, 0.0702247, 0.659639, 0.383226); legThermal->SetBorderSize(1); legThermal->SetTextFont(43); legThermal->SetTextSize(18); // legThermal->SetNColumns(6); legThermal->SetFillColor(0); legThermal->SetLineWidth(1); legThermal->Draw(); } } void myLatexDraw(TLatex *currentLatex, Float_t currentSize, Int_t currentColor){ currentLatex->SetTextFont(43); currentLatex->SetTextSizePixels(Int_t(currentSize)); // currentLatex->SetTextAngle(0); currentLatex->Draw(); return; } void myPaveSetup(float rRatio, float rRange3, float rRange5, int rFillColor){ float cHiRange = 0, cLoRange = 0; if(rRange3<rRange5) {cHiRange=rRange5;cLoRange=rRange3;} else {cHiRange=rRange3;cLoRange=rRange5;} TPave *cPave= new TPave(rRatio-0.25,cLoRange,rRatio+0.25,cHiRange,0,"br"); cPave->SetFillColor(rFillColor); cPave->SetLineColor(1); cPave->Draw(); } void myPadSetUp(TPad *currentPad){ currentPad->SetLeftMargin(0.10); currentPad->SetRightMargin(0.02); currentPad->SetTopMargin(0.02); currentPad->SetBottomMargin(0.02); return; } TGraphErrors* PlotThermusYields(const char * filename, Int_t color, Int_t lineStyle, const char * tag) { Int_t lw = lineStyle == kSolid ? 2 : 3; // Set line width std::map<Int_t,Double_t> mapYields; std::map<Int_t,Double_t> mapStdDev; Int_t pdg; Double_t yield, stddev; ifstream thermusFile(filename); TString line; Double_t chi2 = 0; std::cout << "---"<<tag<<"---" << std::endl; // std::istream is(thermusFile); // Read the std dev and the ratio in 2 maps, then plot them in a graph. while(line.ReadLine(thermusFile, kTRUE)) { if(line.BeginsWith("#")) continue; TObjArray * tokens = line.Tokenize(" \t"); if(tokens->GetEntries() != 3) continue;// not a line with data // thermusFile >> pdg >> yield >> stddev; pdg = ((TObjString*)tokens->At(0))->String().Atof(); yield = ((TObjString*)tokens->At(1))->String().Atof(); stddev = ((TObjString*)tokens->At(2))->String().Atof(); if( thermusFile.eof() ) break; std::cout << "PDG " << pdg << " " << yield << " " << stddev << std::endl; mapYields[TMath::Abs(pdg)] += yield; mapStdDev[TMath::Abs(pdg)] += stddev; if(pdg < 0) { // found the antiparticle: now compute the mean mapYields[TMath::Abs(pdg)] /=2; mapStdDev[TMath::Abs(pdg)] /=2; } delete tokens; } // Now plot TGraphErrors * gThermus = new TGraphErrors; TGraphErrors * gThermusStdDev = new TGraphErrors; for(Int_t ipart = 0; ipart < npart; ipart++){ gThermus->SetPoint(ipart, ipart+1.5, mapYields[particleYields[ipart]]); gThermus->SetPointError(ipart, 0.3, 0); gThermusStdDev->SetPoint(ipart, ipart+1.5, mapStdDev[particleYields[ipart]]); gThermusStdDev->SetPointError(ipart, 0.3, 0); } myPadHisto->cd(); gThermus->Draw("PZ"); gThermus->SetLineWidth(lw); gThermus->SetLineColor(color); gThermus->SetLineStyle(lineStyle); gThermus->SetTitle("NoLegend"); // myPadStdDev->cd(); // gThermusStdDev->Draw("PZ"); // gThermusStdDev->SetLineWidth(lw); // gThermusStdDev->SetLineColor(color); // gThermusStdDev->SetLineStyle(lineStyle); TGraphErrors* gStdDev2 = 0; TGraphErrors* gRatio = 0; std::cout << "CHI2: " << GetGraphRatioAndStdDev(gThermus, gRatio, gStdDev2) << std::endl; myPadRatio->cd(); gRatio->Draw("PZ"); myPadStdDev->cd(); gStdDev2->Draw("PZ"); myPadHisto->cd(); AddLineToThermalLegend(gThermus, tag, "l"); return gThermus; } TGraphErrors* PlotFlorenceYields(const char * filename, Int_t color, Int_t lineStyle, const char * tag) { Int_t lw = lineStyle == kSolid ? 2 : 3; // Set line width std::map<Int_t,Double_t> mapYields; std::map<Int_t,Double_t> mapStdDev; Int_t pdg; Double_t yield, yieldbar, stddev; ifstream thermusFile(filename); TString line; std::cout << "---"<<tag<<"---" << std::endl; // std::istream is(thermusFile); // Read the std dev and the ratio in 2 maps, then plot them in a graph. while(line.ReadLine(thermusFile, kTRUE)) { if(line.BeginsWith("#")) continue; TObjArray * tokens = line.Tokenize(" \t"); if(tokens->GetEntries() != 4) continue;// not a line with data // thermusFile >> pdg >> yield >> stddev; pdg = ((TObjString*)tokens->At(0))->String().Atof(); yield = ((TObjString*)tokens->At(2))->String().Atof(); yieldbar = ((TObjString*)tokens->At(3))->String().Atof(); // Antiparticle yield if(pdg == 0) { // not a line with data delete tokens; continue ; } if( thermusFile.eof() ) break; std::cout << "PDG " << pdg << " " << yield << " " << yieldbar << std::endl; mapYields[TMath::Abs(pdg)] += yieldbar ? ((yield+yieldbar)/2) : yield; // If the antiparticle exists, use the average delete tokens; } // Now plot TGraphErrors * gFlorence = new TGraphErrors; for(Int_t ipart = 0; ipart < npart; ipart++){ gFlorence->SetPoint(ipart, ipart+1.5, mapYields[particleYields[ipart]]); gFlorence->SetPointError(ipart, 0.3, 0); } myPadHisto->cd(); gFlorence->Draw("PZ"); gFlorence->SetLineWidth(lw); gFlorence->SetLineColor(color); gFlorence->SetLineStyle(lineStyle); gFlorence->SetTitle("NoLegend"); TGraphErrors* gStdDev2 = 0; TGraphErrors* gRatio = 0; std::cout << "CHI2: " << GetGraphRatioAndStdDev(gFlorence, gRatio, gStdDev2) << std::endl; myPadRatio->cd(); gRatio->Draw("PZ"); myPadStdDev->cd(); gStdDev2->Draw("PZ"); myPadHisto->cd(); AddLineToThermalLegend(gFlorence, tag, "l"); return gFlorence; } TGraphErrors* PlotGSIYields(const char * filename, Int_t color, Int_t lineStyle, const char * tag, Bool_t isPbPb) { // tag is a comma separated list of elements to be added to the legend as diferent columns Int_t lw = lineStyle == kSolid ? 2 : 3; // Set line width const Int_t pdgPbPb0010[] = {211, -211, 321, -321, 310, 313, 333, 2212, -2212, 3122, 3312, -3312, 3334, -3334, 1000010020, 1000020030, 1010010030, -1010010030}; const Int_t pdgpp[] = {211, 321, 310, 313, 333, 2212, 3122, 3312, 3334, 1000010020}; const Int_t *pdgOrder = isPbPb ? pdgPbPb0010 : pdgpp; std::map<Int_t,Double_t> mapYields; std::map<Int_t,Double_t> mapStdDev; std::map<Int_t,Double_t> mapUncert; std::map<Int_t,Double_t> mapData; Double_t data, uncert, model; ifstream gsiFile(filename); // std::istream is(thermusFile); std::cout << "----- "<<tag<<" -----" << std::endl; // Read the std dev and the ratio in 2 maps, then plot them in a graph. Int_t ipart = 0; while(gsiFile) { gsiFile >> data >> uncert >> model; if( gsiFile.eof() ) break; Int_t pdg = pdgOrder[ipart]; std::cout << "PDG " << pdg << " " << data << std::endl; mapYields[TMath::Abs(pdg)] += model; mapUncert[TMath::Abs(pdg)] += uncert; mapData[TMath::Abs(pdg)] += data; if(pdg < 0) { // found the antiparticle: now compute the mean mapYields[TMath::Abs(pdg)] /=2; mapData[TMath::Abs(pdg)] /=2; mapUncert[TMath::Abs(pdg)] /=2; } ipart++; } // Now plot TGraphErrors * gGsi = new TGraphErrors; TGraphErrors * gGsiStdDev = new TGraphErrors; std::cout << "PDG \tmodel\tdata\tuncert\tstddev" << std::endl; // header for(Int_t ipart = 0; ipart < npart; ipart++){ // Here we use npart, as this is what we wnat to plot! Int_t pdg = particleYields[ipart]; mapStdDev[TMath::Abs(pdg)] = ( mapYields[TMath::Abs(pdg)] - mapData[TMath::Abs(pdg)]) / mapUncert[TMath::Abs(pdg)] ; std::cout << "PDG " << pdg <<"\t" << mapYields[TMath::Abs(pdg)] << "\t" << mapData[TMath::Abs(pdg)] <<"\t" << mapUncert[TMath::Abs(pdg)] << "\t" << mapStdDev[TMath::Abs(pdg)] << std::endl; if(!mapYields[particleYields[ipart]]) mapYields[particleYields[ipart]] = -10; if(!mapStdDev[particleYields[ipart]]) mapStdDev[particleYields[ipart]] = -10; gGsi->SetPoint(ipart, ipart+1.5, mapYields[particleYields[ipart]]); gGsi->SetPointError(ipart, 0.3, 0); gGsiStdDev->SetPoint(ipart, ipart+1.5, mapStdDev[particleYields[ipart]]); gGsiStdDev->SetPointError(ipart, 0.3, 0); } myPadHisto->cd(); gGsi->Draw("PZ"); gGsi->SetLineWidth(lw); gGsi->SetLineColor(color); gGsi->SetLineStyle(lineStyle); gGsi->SetTitle("NoLegend"); // myPadStdDev->cd(); // gGsiStdDev->Draw("PZ"); // gGsiStdDev->SetLineWidth(lw); // gGsiStdDev->SetLineColor(color); // gGsiStdDev->SetLineStyle(lineStyle); // myPadHisto->cd(); TGraphErrors* gStdDev2 = 0; TGraphErrors* gRatio = 0; std::cout << "CHI2: " << GetGraphRatioAndStdDev(gGsi, gRatio, gStdDev2) << std::endl; myPadRatio->cd(); gRatio->Draw("PZ"); myPadStdDev->cd(); gStdDev2->Draw("PZ"); AddLineToThermalLegend(gGsi, tag, "L"); return gGsi; } void DrawExtrapolatedSymbolsAndLegendPbPb0010() { myPadHisto->cd(); TLegend *leg = new TLegend( 0.149598, 0.782203, 0.415663, 0.858447,NULL,"pNDC"); leg->SetBorderSize(0); leg->SetTextFont(43); leg->SetTextSize(18); leg->SetLineColor(1); leg->SetLineStyle(1); leg->SetLineWidth(2); leg->SetFillColor(0); leg->SetFillStyle(1001); leg->SetMargin(0.1); TLegendEntry *entry=leg->AddEntry("TMarker","Extrapolated (Pb-Pb 0-10%)","p"); entry->SetLineColor(1); entry->SetLineStyle(1); entry->SetLineWidth(1); entry->SetMarkerColor(1); entry->SetMarkerStyle(27); entry->SetMarkerSize(1.2); entry->SetTextFont(43); leg->Draw(); myPadLabel->cd(); // Markers for extrapolated points TMarker *marker = new TMarker(0.666667,0.111825,27); marker->SetMarkerStyle(27); marker->SetMarkerSize(1.2); marker->Draw(); marker = new TMarker(0.920683,0.111825,27); marker->SetMarkerStyle(27); marker->SetMarkerSize(1.2); marker->Draw(); // BR for 3He myPadLabel->cd(); TLatex * tex = new TLatex(0.73,0.05,"BR = 25%"); tex->SetNDC(); tex->SetTextFont(43); tex->SetTextSize(14); tex->SetLineWidth(2); tex->Draw(); } void DrawExtrapolatedSymbolsAndLegendpPb0005() { myPadHisto->cd(); TLegend *leg = new TLegend( 0.149598, 0.709972, 0.415663, 0.786216,NULL,"pNDC"); leg->SetBorderSize(0); leg->SetTextFont(43); leg->SetTextSize(18); leg->SetLineColor(1); leg->SetLineStyle(1); leg->SetLineWidth(2); leg->SetFillColor(0); leg->SetFillStyle(1001); leg->SetMargin(0.1); TLegendEntry *entry=leg->AddEntry("TMarker","Extrapolated (p-Pb 0-5%)","p"); entry->SetLineColor(1); entry->SetLineStyle(1); entry->SetLineWidth(1); entry->SetMarkerColor(1); entry->SetMarkerStyle(28); entry->SetMarkerSize(1.2); entry->SetTextFont(43); leg->Draw(); myPadLabel->cd(); TMarker *marker = new TMarker(0.590361,0.111825,28); marker->SetMarkerStyle(28); marker->SetMarkerSize(1.2); marker->Draw(); marker = new TMarker(0.938755,0.111825,28); marker->SetMarkerStyle(28); marker->SetMarkerSize(1.2); marker->Draw(); } void AddLineToThermalLegend(TObject * obj, TString line, const char * optFirst) { // This should be a comma-separated list of text to be added to the // columns. If the number of entries does not match the numer of // columns, it returns an error TObjArray * tokens = line.Tokenize(","); if(tokens->GetEntries() != legThermal->GetNColumns()) { std::cout << "Wrong number of columns (" << tokens->GetEntries() << ","<<legThermal->GetNColumns()<<") for the thermal legend, not adding " << line.Data() << std::endl; return; } TIter iter(tokens); TObjString * col; Bool_t first = 1; while((col = (TObjString*)iter.Next())) { // Add entry removing whitespaces legThermal->AddEntry(obj, col->String().Strip(TString::kBoth, ' ').Data(), first ? optFirst : "0"); if (first) first = 0; } } void DrawExtrapolatedSymbolsYieldsPbPb0010(Double_t x1, Double_t y1, Double_t x2, Double_t y2, Bool_t plotExtraploatedLegend){ // Markers for extrapolated points myPadLabel->cd(); TMarker * marker = new TMarker(0.36245,0.111825,markerExtrap); marker->SetMarkerStyle(markerExtrap); marker->SetMarkerSize(1.2); marker->Draw(); marker = new TMarker(0.945783,0.111825,markerExtrap); marker->SetMarkerStyle(markerExtrap); marker->SetMarkerSize(1.2); marker->Draw(); // BR for 3He myPadHisto->cd(); TLatex * tex = new TLatex(11.15, 2.5e-5,"BR = 25%"); tex->SetTextFont(43); tex->SetTextSize(14); tex->SetLineWidth(2); tex->Draw(); myPadHisto->cd(); TLegend * leg = new TLegend(x1,y1,x2,y2,NULL,"brNDC"); leg->SetBorderSize(0); leg->SetTextFont(43); leg->SetTextSize(14); leg->SetLineColor(1); leg->SetLineStyle(1); leg->SetLineWidth(1); leg->SetFillColor(0); leg->SetFillStyle(1001); TLegendEntry * entry=leg->AddEntry("TMarker","Not in fit","p"); entry->SetLineColor(1); entry->SetLineStyle(1); entry->SetLineWidth(1); entry->SetMarkerColor(1); entry->SetMarkerStyle(markerNoFit); entry->SetMarkerSize(1.2); entry->SetTextFont(43); if(plotExtraploatedLegend) { entry=leg->AddEntry("TMarker","Extrapolated","p"); entry->SetLineColor(1); entry->SetLineStyle(1); entry->SetLineWidth(1); entry->SetMarkerColor(1); entry->SetMarkerStyle(markerExtrap); entry->SetMarkerSize(1.2); entry->SetTextFont(43); } leg->Draw(); leg->SetMargin(0.1); } void DrawMarkerKStarNoFit(Bool_t plotLegend) { myPadLabel->cd(); TMarker *marker = new TMarker(0.344378,0.111825,markerNoFit); marker->SetMarkerStyle(markerNoFit); marker->SetMarkerSize(1.2); marker->Draw(); myPadHisto->cd(); if(plotLegend) { TLegend * leg = new TLegend(0.126506, 0.253051, 0.335341, 0.345118,NULL,"brNDC"); leg->SetBorderSize(0); leg->SetTextFont(43); leg->SetTextSize(14); leg->SetLineColor(1); leg->SetLineStyle(1); leg->SetLineWidth(1); leg->SetFillColor(0); leg->SetFillStyle(1001); TLegendEntry * entry=leg->AddEntry("TMarker","Not in fit","p"); entry->SetLineColor(1); entry->SetLineStyle(1); entry->SetLineWidth(1); entry->SetMarkerColor(1); entry->SetMarkerStyle(markerNoFit); entry->SetMarkerSize(1.2); entry->SetTextFont(43); leg->Draw(); } } void DrawMarkerNucleiNoFit() { myPadLabel->cd(); TMarker *marker = new TMarker(0.928715,0.111825,markerNoFit); marker->SetMarkerStyle(markerNoFit); marker->SetMarkerSize(1.2); marker->Draw(); marker = new TMarker(0.791751,0.111825,markerNoFit); marker->SetMarkerStyle(markerNoFit); marker->SetMarkerSize(1.2); marker->Draw(); marker = new TMarker(0.866466,0.111825,markerNoFit); marker->SetMarkerStyle(markerNoFit); marker->SetMarkerSize(1.2); marker->Draw(); myPadHisto->cd(); } Double_t GetGraphRatioAndStdDev(TGraphErrors * gModel, TGraphErrors * &gRatio, TGraphErrors *&gStdDev) { // Plots the ratios data/model // I recomputed the stddev and the chi2 here, because some values // changed slightly due to typos in some of the input files with // respect to the ones used for those fits. if(!gModel) { std::cout << "EMPTY MODEL" << std::endl; return 0; } // 0. set up the graphs which we will need TGraphErrors * gTemp = 0; TGraphErrors * gStat = 0; TGraphErrors * gSyst = 0; // the cloning below takes care of the style gRatio = (TGraphErrors*)gModel->Clone(); gRatio->Clear(); gStdDev = (TGraphErrors*)gModel->Clone(); gStdDev->Clear(); // 1. Find the data graphs. We need both the stat and the syst, since we want the ratio with the total uncertainty (or not?) TVirtualPad * currentPad = gPad; myPadHisto->cd(); TList * list = myPadHisto->GetListOfPrimitives(); TIterator * iter = list->MakeIterator(); while ((gTemp = (TGraphErrors*) iter->Next())){ if(gTemp->InheritsFrom("TGraphErrors")) { // Found a graph, it is the correct one? TString name = gTemp->GetName(); TString title = gTemp->GetTitle(); std::cout << "name " << name.Data() << std::endl; if (name.Contains("hPart")) { // ok, it's the data if (title.Contains("NoLegend")) gSyst = gTemp; // it's the syst error FIXME: it would be better to add the error type to the data else gStat = gTemp; } if(gStat && gSyst) { std::cout << "Cannot find gStat or gSyst (" << gStat << "," << gSyst <<")" << std::endl; break; // found both stat and syst uncertainties } } } // Compute the ratio, the stddev and the chi2 Int_t npoint = gModel->GetN(); // We are sure that data and model have the same number of points in the same order, because they were created using the particleYields array (FIXME: is this also true for GSI?) Double_t chi2 = 0; for(Int_t ipoint = 0; ipoint < npoint; ipoint++){ Double_t yield = gStat->GetY()[ipoint]; Double_t stat = gStat->GetEY()[ipoint]; Double_t syst = gSyst->GetEY()[ipoint]; Double_t error = TMath::Sqrt(stat*stat+syst*syst); Double_t model = gModel->GetY()[ipoint]; Double_t width = gModel->GetEX()[ipoint]; Double_t ratio = (model-yield)/model; Double_t stddev = (model-yield)/error; if(!particlesToExcludeFromChi2.Contains(Form("[%d]", particleYields[ipoint]))) chi2 += TMath::Power(stddev,2); else std::cout << "Ecluding PDG "<< particleYields[ipoint] <<" from chi2 calculation" << std::endl; Double_t errorRatio = error/model; gRatio->SetPoint(ipoint, gModel->GetX()[ipoint]+shiftRatioDataModel, ratio); gRatio->SetPointError(ipoint, 0, errorRatio); if(model) { gStdDev->SetPoint(ipoint, gModel->GetX()[ipoint], stddev); gStdDev->SetPointError(ipoint, width, 0); } // The commented block down here was used to compare to the estimate provided directly by Boris and Benjamin // gStdDev->SetPoint(ipoint, gModel->GetX()[ipoint]-0.4, stddev); // gStdDev->SetPointError(ipoint, 0.2, 0); // std::cout << "PDG " << particleYields[ipoint] <<"\t" // << model << "\t" << yield <<"\t" // << error << "\t" << stddev // << std::endl; } gRatio->SetLineStyle(kSolid); gRatio->SetMarkerStyle(kOpenSquare); gRatio->SetMarkerColor(gRatio->GetLineColor()); gRatio->SetLineWidth(2); currentPad->cd(); return chi2; } void SaveCanvas(const char * name) { if(!saveCanvas) return; std::cout << "Saving " << name << ".{eps,pdf,root,C}" << std::endl; myCan->Update(); gSystem->ProcessEvents(); myCan->Print(Form("%s.eps",name)); myCan->Print(Form("%s.root",name)); myCan->Print(Form("%s.C",name)); gSystem->Exec(Form("epstopdf %s.eps", name)); gSystem->Exec(Form("if [ \"$USER\" = \"mfloris\" ]; then cp %s.{eps,pdf,root,C} /Users/mfloris/Documents/PapersNTalks/ALICE/ThermalFits/img/; fi ",name)); } void DrawExtrapNotInFitpPb0005(Bool_t drawExtrap) { myPadLabel->cd(); TMarker *marker = new TMarker(0.344378,0.111825,28); marker->SetMarkerStyle(28); marker->SetMarkerSize(1.2); marker->Draw(); // marker = new TMarker(0.7851406,0.111825,28); // marker->SetMarkerStyle(28); // marker->SetMarkerSize(1.2); // marker->Draw(); if(drawExtrap) { marker = new TMarker(0.364458,0.111825,27); marker->SetMarkerStyle(27); marker->SetMarkerSize(1.2); marker->Draw(); marker = new TMarker(0.792,0.111825,27); marker->SetMarkerStyle(27); marker->SetMarkerSize(1.2); marker->Draw(); } myPadHisto->cd(); TLegend * leg = 0; if (drawExtrap) leg = new TLegend(0.123494, 0.400358, 0.331325, 0.534512,NULL,"brNDC"); else leg = new TLegend(0.123494, 0.395097, 0.332329, 0.474011, NULL, "brNDC"); leg->SetBorderSize(0); leg->SetTextFont(43); leg->SetTextSize(14); leg->SetLineColor(1); leg->SetLineStyle(1); leg->SetLineWidth(1); leg->SetFillColor(0); leg->SetFillStyle(1001); TLegendEntry * entry=leg->AddEntry("TMarker","Not in fit","p"); entry->SetLineColor(1); entry->SetLineStyle(1); entry->SetLineWidth(1); entry->SetMarkerColor(1); entry->SetMarkerStyle(markerNoFit); entry->SetMarkerSize(1.2); entry->SetTextFont(43); if(drawExtrap) { entry=leg->AddEntry("TMarker","Extrapolated","p"); entry->SetLineColor(1); entry->SetLineStyle(1); entry->SetLineWidth(1); entry->SetMarkerColor(1); entry->SetMarkerStyle(markerExtrap); entry->SetMarkerSize(1.2); entry->SetTextFont(43); } leg->Draw(); leg->SetMargin(0.1); }
db9eb4be70389bace45af242fc9df5b2209b5f2f
abe704eb3b53944cdd6505f922f58558e334c589
/components/display/touch_panel/calibration/basic_painter/basic_painter.c
324c57ee532f115b8289bf9c339f379f538198b6
[ "Apache-2.0" ]
permissive
espressif/esp-iot-solution
c25079eb26a8f54ddacd23689a7288533c721916
2227f0ca21ab37df9cf9d74182fa84c52dffc76f
refs/heads/master
2023-09-01T15:06:17.000154
2023-08-31T10:26:21
2023-08-31T10:26:21
99,690,601
1,612
758
Apache-2.0
2023-09-08T08:43:59
2017-08-08T12:32:16
C
UTF-8
C
false
false
8,583
c
basic_painter.c
/* * SPDX-FileCopyrightText: 2022-2023 Espressif Systems (Shanghai) CO LTD * * SPDX-License-Identifier: Apache-2.0 */ # include <stdlib.h> #include <string.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_log.h" #include "screen_driver.h" #include "basic_painter.h" static const char *TAG = "basic painter"; #define PAINTER_CHECK(a, str) if(!(a)) { \ ESP_LOGE(TAG,"%s:%d (%s):%s", __FILE__, __LINE__, __FUNCTION__, str); \ return ; \ } typedef struct { uint16_t point_color; uint16_t back_color; scr_driver_t lcd; int16_t window_x1; ///< Dirty tracking window minimum x int16_t window_y1; ///< Dirty tracking window minimum y int16_t window_x2; ///< Dirty tracking window maximum x int16_t window_y2; ///< Dirty tracking window maximum y } painter_handle_t; static uint16_t g_point_color = COLOR_BLACK; static uint16_t g_back_color = COLOR_WHITE; static scr_driver_t g_lcd; esp_err_t painter_init(scr_driver_t *driver) { g_lcd = *driver; return ESP_OK; } void painter_set_point_color(uint16_t color) { g_point_color = color; } uint16_t painter_get_point_color(void) { return g_point_color; } void painter_set_back_color(uint16_t color) { g_back_color = color; } uint16_t painter_get_back_color(void) { return g_back_color; } void painter_clear(uint16_t color) { PAINTER_CHECK(NULL != g_lcd.init, "paint not initial"); scr_info_t info; g_lcd.get_info(&info); uint16_t *buffer = malloc(info.width * sizeof(uint16_t)); PAINTER_CHECK(NULL != buffer, "Memory not enough"); for (size_t i = 0; i < info.width; i++) { buffer[i] = color; } for (int y = 0; y < info.height; y++) { g_lcd.draw_bitmap(0, y, info.width, 1, buffer); } free(buffer); } void painter_draw_char(int x, int y, char ascii_char, const font_t *font, uint16_t color) { PAINTER_CHECK(ascii_char >= ' ', "ACSII code invalid"); PAINTER_CHECK(NULL != font, "Font pointer invalid"); int i, j; uint16_t char_size = font->Height * (font->Width / 8 + (font->Width % 8 ? 1 : 0)); unsigned int char_offset = (ascii_char - ' ') * char_size; const unsigned char *ptr = &font->table[char_offset]; uint16_t buf[18 * 25]; PAINTER_CHECK(font->Height * font->Width * sizeof(uint16_t) <= sizeof(buf), "Font size is too large"); int ox = 0; int oy = 0; for (i = 0; i < font->Width * font->Height; i++) { buf[i] = g_back_color; } for (j = 0; j < char_size; j++) { uint8_t temp = ptr[j]; for (i = 0; i < 8; i++) { if (temp & 0x80) { buf[ox + (font->Width * oy)] = g_point_color; } temp <<= 1; ox++; if (ox == font->Width) { ox = 0; oy++; break; } } } g_lcd.draw_bitmap(x, y, font->Width, font->Height, buf); // Draw NxN char } void painter_draw_string(int x, int y, const char *text, const font_t *font, uint16_t color) { PAINTER_CHECK(NULL != text, "string pointer invalid"); PAINTER_CHECK(NULL != font, "Font pointer invalid"); const char *p_text = text; uint16_t x0 = x; uint16_t y0 = y; scr_info_t info; g_lcd.get_info(&info); while (*p_text != 0) { if (x > (x0 + info.width - font->Width)) { y += font->Height; x = x0; } if (y > (y0 + info.height - font->Height)) { break; } if (*p_text == '\n') { y += font->Height; x = x0; } else { painter_draw_char(x, y, *p_text, font, color); } x += font->Width; p_text++; } } void painter_draw_num(int x, int y, uint32_t num, uint8_t len, const font_t *font, uint16_t color) { PAINTER_CHECK(len < 10, "The length of the number is too long"); PAINTER_CHECK(NULL != font, "Font pointer invalid"); char buf[10] = {0}; int8_t num_len; itoa(num, buf, 10); num_len = strlen(buf); x += (font->Width * (len - 1)); for (size_t i = 0; i < len; i++) { if (i < num_len) { painter_draw_char(x, y, buf[i], font, color); } else { painter_draw_char(x, y, '0', font, color); } x -= font->Width; } } void painter_draw_image(int x, int y, int width, int height, uint16_t *img) { PAINTER_CHECK(NULL != img, "Image pointer invalid"); g_lcd.draw_bitmap(x, y, width, height, img); } void painter_draw_horizontal_line(int x, int y, int line_length, uint16_t color) { int i; for (i = x; i < x + line_length; i++) { g_lcd.draw_pixel(i, y, color); } } void painter_draw_vertical_line(int x, int y, int line_length, uint16_t color) { int i; for (i = y; i < y + line_length; i++) { g_lcd.draw_pixel(x, i, color); } } void painter_draw_line(int x1, int y1, int x2, int y2, uint16_t color) { uint16_t t; int xerr = 0, yerr = 0, delta_x, delta_y, distance; int incx, incy, uRow, uCol; delta_x = x2 - x1; delta_y = y2 - y1; uRow = x1; uCol = y1; if (delta_x > 0) { incx = 1; //set direction } else if (delta_x == 0) { incx = 0; //vertical line } else { incx = -1; delta_x = -delta_x; } if (delta_y > 0) { incy = 1; } else if (delta_y == 0) { incy = 0; //horizontal line } else { incy = -1; delta_y = -delta_y; } if (delta_x > delta_y) { distance = delta_x; } else { distance = delta_y; } for (t = 0; t <= distance + 1; t++) { g_lcd.draw_pixel(uRow, uCol, color); xerr += delta_x ; yerr += delta_y ; if (xerr > distance) { xerr -= distance; uRow += incx; } if (yerr > distance) { yerr -= distance; uCol += incy; } } } void painter_draw_rectangle(int x0, int y0, int x1, int y1, uint16_t color) { int min_x, min_y, max_x, max_y; min_x = x1 > x0 ? x0 : x1; max_x = x1 > x0 ? x1 : x0; min_y = y1 > y0 ? y0 : y1; max_y = y1 > y0 ? y1 : y0; painter_draw_horizontal_line(min_x, min_y, max_x - min_x + 1, color); painter_draw_horizontal_line(min_x, max_y, max_x - min_x + 1, color); painter_draw_vertical_line(min_x, min_y, max_y - min_y + 1, color); painter_draw_vertical_line(max_x, min_y, max_y - min_y + 1, color); } void painter_draw_filled_rectangle(int x0, int y0, int x1, int y1, uint16_t color) { int min_x, min_y, max_x, max_y; int i; min_x = x1 > x0 ? x0 : x1; max_x = x1 > x0 ? x1 : x0; min_y = y1 > y0 ? y0 : y1; max_y = y1 > y0 ? y1 : y0; for (i = min_x; i <= max_x; i++) { painter_draw_vertical_line(i, min_y, max_y - min_y + 1, color); } } void painter_draw_circle(int x, int y, int radius, uint16_t color) { /* Bresenham algorithm */ int x_pos = -radius; int y_pos = 0; int err = 2 - 2 * radius; int e2; do { g_lcd.draw_pixel(x - x_pos, y + y_pos, color); g_lcd.draw_pixel(x + x_pos, y + y_pos, color); g_lcd.draw_pixel(x + x_pos, y - y_pos, color); g_lcd.draw_pixel(x - x_pos, y - y_pos, color); e2 = err; if (e2 <= y_pos) { err += ++y_pos * 2 + 1; if (-x_pos == y_pos && e2 <= x_pos) { e2 = 0; } } if (e2 > x_pos) { err += ++x_pos * 2 + 1; } } while (x_pos <= 0); } void painter_draw_filled_circle(int x, int y, int radius, uint16_t color) { /* Bresenham algorithm */ int x_pos = -radius; int y_pos = 0; int err = 2 - 2 * radius; int e2; do { g_lcd.draw_pixel(x - x_pos, y + y_pos, color); g_lcd.draw_pixel(x + x_pos, y + y_pos, color); g_lcd.draw_pixel(x + x_pos, y - y_pos, color); g_lcd.draw_pixel(x - x_pos, y - y_pos, color); painter_draw_horizontal_line(x + x_pos, y + y_pos, 2 * (-x_pos) + 1, color); painter_draw_horizontal_line(x + x_pos, y - y_pos, 2 * (-x_pos) + 1, color); e2 = err; if (e2 <= y_pos) { err += ++y_pos * 2 + 1; if (-x_pos == y_pos && e2 <= x_pos) { e2 = 0; } } if (e2 > x_pos) { err += ++x_pos * 2 + 1; } } while (x_pos <= 0); }
0759db91c8c12365af8d860022bb5dd01637813d
8447eb38a4fc71b32b6b82a99f7828a2c50621aa
/ppu/sprx/libfont/font_wrapper.c
4816e2f26ae617cf68c3c09511e4bdfb79e69fb5
[ "MIT" ]
permissive
ps3dev/PSL1GHT
9ecc1f0a2996b39d35cc98303c58c79966b9388b
5bc0961c66a3615c74f15e0c29bbeaa33f867ab3
refs/heads/master
2023-08-04T06:50:55.256801
2023-07-30T13:34:19
2023-07-30T13:34:19
1,541,223
159
357
MIT
2023-07-23T07:26:09
2011-03-29T12:34:15
C
UTF-8
C
false
false
1,593
c
font_wrapper.c
#include <ppu-asm.h> #include <ppu-types.h> #include <font/font.h> extern s32 fontGetLibraryEx(font *f,const fontLibrary* ATTRIBUTE_PRXPTR *lib,u32 *type); extern s32 fontGetBindingRendererEx(font *f,fontRenderer* ATTRIBUTE_PRXPTR *renderer); extern s32 fontGenerateCharGlyphEx(font *f,u32 code,fontGlyph* ATTRIBUTE_PRXPTR *glyph); extern s32 fontGenerateCharGlyphVerticalEx(font *f,u32 code,fontGlyph* ATTRIBUTE_PRXPTR *glyph); void fontGetStubRevisionFlags(u64 *revisionFlags) { if(revisionFlags == NULL) return; *revisionFlags = 0x14; } s32 fontGetLibrary(font *f,const fontLibrary **lib,u32 *type) { s32 ret; const fontLibrary *l ATTRIBUTE_PRXPTR; if(f == NULL || lib == NULL || type == NULL) return 0x80540002; ret = fontGetLibraryEx(f,&l,type); *lib = ret == 0 ? l : NULL; return ret; } s32 fontGetBindingRenderer(font *f,fontRenderer **renderer) { s32 ret; fontRenderer *r ATTRIBUTE_PRXPTR; if(f == NULL || renderer == NULL) return 0x80540002; ret = fontGetBindingRendererEx(f,&r); *renderer = ret == 0 ? r : NULL; return ret; } s32 fontGenerateCharGlyph(font *f,u32 code,fontGlyph **glyph) { s32 ret; fontGlyph *g ATTRIBUTE_PRXPTR; if(f == NULL || glyph == NULL) return 0x80540002; ret = fontGenerateCharGlyphEx(f,code,&g); *glyph = ret == 0 ? g : NULL; return ret; } s32 fontGenerateCharGlyphVertical(font *f,u32 code,fontGlyph **glyph) { s32 ret; fontGlyph *g ATTRIBUTE_PRXPTR; if(f == NULL || glyph == NULL) return 0x80540002; ret = fontGenerateCharGlyphVerticalEx(f,code,&g); *glyph = ret == 0 ? g : NULL; return ret; }
6ab60ac7c49f05f1702767294f5796fe4a343c60
347334f675bc31ecab5d74ca6388827b13097ed9
/src/lib/vendor/html-entities.h
0aaf63599bece17d1172c1583ccbd8846a4e7804
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
Bionus/imgbrd-grabber
442108d9663a06a848ef49837943d5950bca9d8c
4ab008d5d0f62ab2bc34aff7de02e05d598e058a
refs/heads/master
2023-08-20T21:50:37.649081
2023-08-17T22:54:55
2023-08-17T22:54:55
32,276,615
2,226
301
Apache-2.0
2023-08-12T16:31:57
2015-03-15T18:26:31
HTML
UTF-8
C
false
false
546
h
html-entities.h
/* Copyright 2012 Christoph Gärtner Distributed under the Boost Software License, Version 1.0 */ #ifndef DECODE_HTML_ENTITIES_UTF8_ #define DECODE_HTML_ENTITIES_UTF8_ #include <stddef.h> extern size_t decode_html_entities_utf8(char *dest, const char *src); /* Takes input from <src> and decodes into <dest>, which should be a buffer large enough to hold <strlen(src) + 1> characters. If <src> is <NULL>, input will be taken from <dest>, decoding the entities in-place. The function returns the length of the decoded string. */ #endif
dbd8604051296befd4f40fc7918411aed871aab2
8e3c9ccc2c77e734331cb2b3753b8a394c6c8c3c
/CBLAS/caxpy.c
26c31e23fa62875c7ab17f3804bd10b36b5f8d96
[ "BSD-2-Clause" ]
permissive
xiaoyeli/superlu
ca84bb9f28c0ae97953308edcf07489f3287e1a2
1ad483880d9cc5f3eb824b058d95fba7941949cd
refs/heads/master
2023-09-01T23:43:04.721587
2023-08-12T20:39:42
2023-08-12T20:39:42
51,040,874
210
101
NOASSERTION
2023-09-09T19:16:55
2016-02-04T00:21:41
C
UTF-8
C
false
false
1,757
c
caxpy.c
/* -- translated by f2c (version 19940927). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ #include "f2c.h" /* Subroutine */ int caxpy_(integer *n, complex *ca, complex *cx, integer * incx, complex *cy, integer *incy) { /* System generated locals */ real r__1, r__2; complex q__1, q__2; /* Builtin functions */ double r_imag(complex *); /* Local variables */ integer i, ix, iy; /* constant times a vector plus a vector. jack dongarra, linpack, 3/11/78. modified 12/3/93, array(1) declarations changed to array(*) Parameter adjustments Function Body */ #define CY(I) cy[(I)-1] #define CX(I) cx[(I)-1] if (*n <= 0) { return 0; } if ((r__1 = ca->r, dabs(r__1)) + (r__2 = r_imag(ca), dabs(r__2)) == 0.f) { return 0; } if (*incx == 1 && *incy == 1) { goto L20; } /* code for unequal increments or equal increments not equal to 1 */ ix = 1; iy = 1; if (*incx < 0) { ix = (-(*n) + 1) * *incx + 1; } if (*incy < 0) { iy = (-(*n) + 1) * *incy + 1; } for (i = 1; i <= *n; ++i) { q__2.r = ca->r * CX(ix).r - ca->i * CX(ix).i, q__2.i = ca->r * CX( ix).i + ca->i * CX(ix).r; q__1.r = CY(iy).r + q__2.r, q__1.i = CY(iy).i + q__2.i; CY(iy).r = q__1.r, CY(iy).i = q__1.i; ix += *incx; iy += *incy; /* L10: */ } return 0; /* code for both increments equal to 1 */ L20: for (i = 1; i <= *n; ++i) { q__2.r = ca->r * CX(i).r - ca->i * CX(i).i, q__2.i = ca->r * CX( i).i + ca->i * CX(i).r; q__1.r = CY(i).r + q__2.r, q__1.i = CY(i).i + q__2.i; CY(i).r = q__1.r, CY(i).i = q__1.i; /* L30: */ } return 0; } /* caxpy_ */
7d774b91495d667f597b63cc173eec5eea08bfa0
fbe68d84e97262d6d26dd65c704a7b50af2b3943
/third_party/virtualbox/src/VBox/RDP/client-1.8.4/seamless.c
6fd1f2b46dc6ca67725a857515ccb40314d3132d
[ "MIT", "GPL-3.0-only", "GPL-1.0-or-later", "GPL-3.0-or-later", "GPL-2.0-only", "LGPL-2.0-or-later", "LicenseRef-scancode-unknown-license-reference", "CDDL-1.0", "LicenseRef-scancode-warranty-disclaimer", "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
11,188
c
seamless.c
/* -*- c-basic-offset: 8 -*- rdesktop: A Remote Desktop Protocol client. Seamless Windows support Copyright 2005-2008 Peter Astrand <astrand@cendio.se> for Cendio AB Copyright 2007-2008 Pierre Ossman <ossman@cendio.se> for Cendio AB Copyright 2013-2014 Henrik Andersson <hean01@cendio.se> for Cendio AB This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Oracle GPL Disclaimer: For the avoidance of doubt, except that if any license choice * other than GPL or LGPL is available it will apply instead, Oracle elects to use only * the General Public License version 2 (GPLv2) at this time for any software where * a choice of GPL license versions is made available with the language indicating * that GPLv2 or any later version may be used, or where a choice of which version * of the GPL is applied is otherwise unspecified. */ #include "rdesktop.h" #include <stdarg.h> #include <assert.h> #ifdef WITH_DEBUG_SEAMLESS #define DEBUG_SEAMLESS(args) printf args; #else #define DEBUG_SEAMLESS(args) #endif extern RD_BOOL g_seamless_rdp; static VCHANNEL *seamless_channel; static unsigned int seamless_serial; static char *seamless_rest = NULL; static char icon_buf[1024]; static char * seamless_get_token(char **s) { char *comma, *head; head = *s; if (!head) return NULL; comma = strchr(head, ','); if (comma) { *comma = '\0'; *s = comma + 1; } else { *s = NULL; } return head; } static RD_BOOL seamless_process_line(const char *line, void *data) { char *p, *l; char *tok1, *tok2, *tok3, *tok4, *tok5, *tok6, *tok7, *tok8; unsigned long id, flags; char *endptr; l = xstrdup(line); p = l; DEBUG_SEAMLESS(("seamlessrdp got:%s\n", p)); tok1 = seamless_get_token(&p); tok2 = seamless_get_token(&p); tok3 = seamless_get_token(&p); tok4 = seamless_get_token(&p); tok5 = seamless_get_token(&p); tok6 = seamless_get_token(&p); tok7 = seamless_get_token(&p); tok8 = seamless_get_token(&p); if (!strcmp("CREATE", tok1)) { unsigned long group, parent; if (!tok6) return False; id = strtoul(tok3, &endptr, 0); if (*endptr) return False; group = strtoul(tok4, &endptr, 0); if (*endptr) return False; parent = strtoul(tok5, &endptr, 0); if (*endptr) return False; flags = strtoul(tok6, &endptr, 0); if (*endptr) return False; ui_seamless_create_window(id, group, parent, flags); } else if (!strcmp("DESTROY", tok1)) { if (!tok4) return False; id = strtoul(tok3, &endptr, 0); if (*endptr) return False; flags = strtoul(tok4, &endptr, 0); if (*endptr) return False; ui_seamless_destroy_window(id, flags); } else if (!strcmp("DESTROYGRP", tok1)) { if (!tok4) return False; id = strtoul(tok3, &endptr, 0); if (*endptr) return False; flags = strtoul(tok4, &endptr, 0); if (*endptr) return False; ui_seamless_destroy_group(id, flags); } else if (!strcmp("SETICON", tok1)) { int chunk, width, height, len; char byte[3]; if (!tok8) return False; id = strtoul(tok3, &endptr, 0); if (*endptr) return False; chunk = strtoul(tok4, &endptr, 0); if (*endptr) return False; width = strtoul(tok6, &endptr, 0); if (*endptr) return False; height = strtoul(tok7, &endptr, 0); if (*endptr) return False; byte[2] = '\0'; len = 0; while (*tok8 != '\0') { byte[0] = *tok8; tok8++; if (*tok8 == '\0') return False; byte[1] = *tok8; tok8++; icon_buf[len] = strtol(byte, NULL, 16); len++; if ((size_t)len >= sizeof(icon_buf)) { warning("seamless_process_line(), icon data would overrun icon_buf"); break; } } ui_seamless_seticon(id, tok5, width, height, chunk, icon_buf, len); } else if (!strcmp("DELICON", tok1)) { int width, height; if (!tok6) return False; id = strtoul(tok3, &endptr, 0); if (*endptr) return False; width = strtoul(tok5, &endptr, 0); if (*endptr) return False; height = strtoul(tok6, &endptr, 0); if (*endptr) return False; ui_seamless_delicon(id, tok4, width, height); } else if (!strcmp("POSITION", tok1)) { int x, y, width, height; if (!tok8) return False; id = strtoul(tok3, &endptr, 0); if (*endptr) return False; x = strtol(tok4, &endptr, 0); if (*endptr) return False; y = strtol(tok5, &endptr, 0); if (*endptr) return False; width = strtol(tok6, &endptr, 0); if (*endptr) return False; height = strtol(tok7, &endptr, 0); if (*endptr) return False; flags = strtoul(tok8, &endptr, 0); if (*endptr) return False; ui_seamless_move_window(id, x, y, width, height, flags); } else if (!strcmp("ZCHANGE", tok1)) { unsigned long behind; id = strtoul(tok3, &endptr, 0); if (*endptr) return False; behind = strtoul(tok4, &endptr, 0); if (*endptr) return False; flags = strtoul(tok5, &endptr, 0); if (*endptr) return False; ui_seamless_restack_window(id, behind, flags); } else if (!strcmp("TITLE", tok1)) { if (!tok5) return False; id = strtoul(tok3, &endptr, 0); if (*endptr) return False; flags = strtoul(tok5, &endptr, 0); if (*endptr) return False; ui_seamless_settitle(id, tok4, flags); } else if (!strcmp("STATE", tok1)) { unsigned int state; if (!tok5) return False; id = strtoul(tok3, &endptr, 0); if (*endptr) return False; state = strtoul(tok4, &endptr, 0); if (*endptr) return False; flags = strtoul(tok5, &endptr, 0); if (*endptr) return False; ui_seamless_setstate(id, state, flags); } else if (!strcmp("DEBUG", tok1)) { DEBUG_SEAMLESS(("SeamlessRDP:%s\n", line)); } else if (!strcmp("SYNCBEGIN", tok1)) { if (!tok3) return False; flags = strtoul(tok3, &endptr, 0); if (*endptr) return False; ui_seamless_syncbegin(flags); } else if (!strcmp("SYNCEND", tok1)) { if (!tok3) return False; flags = strtoul(tok3, &endptr, 0); if (*endptr) return False; /* do nothing, currently */ } else if (!strcmp("HELLO", tok1)) { if (!tok3) return False; flags = strtoul(tok3, &endptr, 0); if (*endptr) return False; ui_seamless_begin(! !(flags & SEAMLESSRDP_HELLO_HIDDEN)); } else if (!strcmp("ACK", tok1)) { unsigned int serial; serial = strtoul(tok3, &endptr, 0); if (*endptr) return False; ui_seamless_ack(serial); } else if (!strcmp("HIDE", tok1)) { if (!tok3) return False; flags = strtoul(tok3, &endptr, 0); if (*endptr) return False; ui_seamless_hide_desktop(); } else if (!strcmp("UNHIDE", tok1)) { if (!tok3) return False; flags = strtoul(tok3, &endptr, 0); if (*endptr) return False; ui_seamless_unhide_desktop(); } xfree(l); return True; } static RD_BOOL seamless_line_handler(const char *line, void *data) { if (!seamless_process_line(line, data)) { warning("SeamlessRDP: Invalid request:%s\n", line); } return True; } static void seamless_process(STREAM s) { unsigned int pkglen; char *buf; struct stream packet = *s; if (!s_check(s)) { rdp_protocol_error("seamless_process(), stream is in unstable state", &packet); } pkglen = s->end - s->p; /* str_handle_lines requires null terminated strings */ buf = xmalloc(pkglen + 1); STRNCPY(buf, (char *) s->p, pkglen + 1); #if 0 printf("seamless recv:\n"); hexdump(s->p, pkglen); #endif str_handle_lines(buf, &seamless_rest, seamless_line_handler, NULL); xfree(buf); } RD_BOOL seamless_init(void) { if (!g_seamless_rdp) return False; seamless_serial = 0; seamless_channel = channel_register("seamrdp", CHANNEL_OPTION_INITIALIZED | CHANNEL_OPTION_ENCRYPT_RDP, seamless_process); return (seamless_channel != NULL); } void seamless_reset_state(void) { if (seamless_rest != NULL) { xfree(seamless_rest); seamless_rest = NULL; } } static unsigned int seamless_send(const char *command, const char *format, ...) { STREAM s; size_t len; va_list argp; char *escaped, buf[1025]; len = snprintf(buf, sizeof(buf) - 1, "%s,%u,", command, seamless_serial); assert(len < (sizeof(buf) - 1)); va_start(argp, format); len += vsnprintf(buf + len, sizeof(buf) - len - 1, format, argp); va_end(argp); assert(len < (sizeof(buf) - 1)); escaped = utils_string_escape(buf); len = snprintf(buf, sizeof(buf), "%s", escaped); free(escaped); assert(len < (sizeof(buf) - 1)); buf[len] = '\n'; buf[len + 1] = '\0'; len++; s = channel_init(seamless_channel, len); out_uint8p(s, buf, len) s_mark_end(s); DEBUG_SEAMLESS(("seamlessrdp sending:%s", buf)); #if 0 printf("seamless send:\n"); hexdump(s->channel_hdr + 8, s->end - s->channel_hdr - 8); #endif channel_send(s, seamless_channel); return seamless_serial++; } unsigned int seamless_send_sync() { if (!g_seamless_rdp) return (unsigned int) -1; return seamless_send("SYNC", ""); } unsigned int seamless_send_state(unsigned long id, unsigned int state, unsigned long flags) { if (!g_seamless_rdp) return (unsigned int) -1; return seamless_send("STATE", "0x%08lx,0x%x,0x%lx", id, state, flags); } unsigned int seamless_send_position(unsigned long id, int x, int y, int width, int height, unsigned long flags) { return seamless_send("POSITION", "0x%08lx,%d,%d,%d,%d,0x%lx", id, x, y, width, height, flags); } /* Update select timeout */ void seamless_select_timeout(struct timeval *tv) { struct timeval ourtimeout = { 0, SEAMLESSRDP_POSITION_TIMER }; if (g_seamless_rdp) { if (timercmp(&ourtimeout, tv, <)) { tv->tv_sec = ourtimeout.tv_sec; tv->tv_usec = ourtimeout.tv_usec; } } } unsigned int seamless_send_zchange(unsigned long id, unsigned long below, unsigned long flags) { if (!g_seamless_rdp) return (unsigned int) -1; return seamless_send("ZCHANGE", "0x%08lx,0x%08lx,0x%lx", id, below, flags); } unsigned int seamless_send_focus(unsigned long id, unsigned long flags) { if (!g_seamless_rdp) return (unsigned int) -1; return seamless_send("FOCUS", "0x%08lx,0x%lx", id, flags); } /* Send client-to-server message to destroy process on the server. */ unsigned int seamless_send_destroy(unsigned long id) { return seamless_send("DESTROY", "0x%08lx", id); } unsigned int seamless_send_spawn(char *cmdline) { unsigned int res; if (!g_seamless_rdp) return (unsigned int) -1; res = seamless_send("SPAWN", cmdline); return res; } unsigned int seamless_send_persistent(RD_BOOL enable) { unsigned int res; if (!g_seamless_rdp) return (unsigned int) -1; printf("%s persistent seamless mode.\n", enable?"Enable":"Disable"); res = seamless_send("PERSISTENT", "%d", enable); return res; }
14ace66743bac72f30633111380086c9b5229e57
98e838b6e6401dc4aa43cfbf3eb8c5dcff37ab9b
/ext/rugged/rugged_reference_collection.c
907fa4c39b2611f737ef09c708ab7b915571ba66
[ "MIT" ]
permissive
libgit2/rugged
a01cf74e9692dcdd49217f7178c667b13d420fc5
fefa6e644fecacad1d56b98e787d344fd632836a
refs/heads/master
2023-08-31T14:27:08.896691
2023-08-25T10:13:54
2023-08-25T10:13:54
901,663
1,258
229
MIT
2023-09-04T13:56:50
2010-09-10T16:18:17
C
UTF-8
C
false
false
13,463
c
rugged_reference_collection.c
/* * Copyright (C) the Rugged contributors. All rights reserved. * * This file is part of Rugged, distributed under the MIT license. * For full terms see the included LICENSE file. */ #include "rugged.h" extern VALUE rb_mRugged; extern VALUE rb_cRuggedRepo; extern VALUE rb_cRuggedReference; VALUE rb_cRuggedReferenceCollection; /* * call-seq: * ReferenceCollection.new(repo) -> refs * * Creates and returns a new collection of references for the given +repo+. */ static VALUE rb_git_reference_collection_initialize(VALUE self, VALUE repo) { rugged_set_owner(self, repo); return self; } /* * call-seq: * references.create(name, oid, options = {}) -> new_ref * references.create(name, target, options = {}) -> new_ref * * Create a symbolic or direct reference on the collection's +repository+ with the given +name+. * * If the second argument is a valid OID, the reference will be created as direct. * Otherwise, it will be assumed the target is the name of another reference. * * The following options can be passed in the +options+ Hash: * * :force :: * Overwrites the reference with the given +name+, if it already exists, * instead of raising an exception. * * If a reference with the given +name+ already exists and +:force+ is not +true+, * an exception will be raised. */ static VALUE rb_git_reference_collection_create(int argc, VALUE *argv, VALUE self) { VALUE rb_repo = rugged_owner(self), rb_name, rb_target, rb_options; git_repository *repo; git_reference *ref; git_oid oid; char *log_message = NULL; int error, force = 0; rb_scan_args(argc, argv, "20:", &rb_name, &rb_target, &rb_options); rugged_check_repo(rb_repo); Data_Get_Struct(rb_repo, git_repository, repo); Check_Type(rb_name, T_STRING); Check_Type(rb_target, T_STRING); if (!NIL_P(rb_options)) { VALUE rb_val = rb_hash_aref(rb_options, CSTR2SYM("message")); if (!NIL_P(rb_val)) log_message = StringValueCStr(rb_val); force = RTEST(rb_hash_aref(rb_options, CSTR2SYM("force"))); } if (git_oid_fromstr(&oid, StringValueCStr(rb_target)) == GIT_OK) { error = git_reference_create( &ref, repo, StringValueCStr(rb_name), &oid, force, log_message); } else { error = git_reference_symbolic_create( &ref, repo, StringValueCStr(rb_name), StringValueCStr(rb_target), force, log_message); } rugged_exception_check(error); return rugged_ref_new(rb_cRuggedReference, rb_repo, ref); } /* * call-seq: * references[name] -> new_ref * * Lookup a reference in the collection with the given +name+. * * Returns a new Rugged::Reference object. */ static VALUE rb_git_reference_collection_aref(VALUE self, VALUE rb_name) { VALUE rb_repo = rugged_owner(self); git_repository *repo; git_reference *ref; int error; Data_Get_Struct(rb_repo, git_repository, repo); error = git_reference_lookup(&ref, repo, StringValueCStr(rb_name)); if (error == GIT_ENOTFOUND) return Qnil; rugged_exception_check(error); return rugged_ref_new(rb_cRuggedReference, rb_repo, ref); } static VALUE rb_git_reference_collection__each(int argc, VALUE *argv, VALUE self, int only_names) { VALUE rb_glob, rb_repo = rugged_owner(self); git_repository *repo; git_reference_iterator *iter; int error, exception = 0; RETURN_ENUMERATOR(self, argc, argv); rb_scan_args(argc, argv, "01", &rb_glob); rugged_check_repo(rb_repo); Data_Get_Struct(rb_repo, git_repository, repo); if (!NIL_P(rb_glob)) { Check_Type(rb_glob, T_STRING); error = git_reference_iterator_glob_new(&iter, repo, StringValueCStr(rb_glob)); } else { error = git_reference_iterator_new(&iter, repo); } rugged_exception_check(error); if (only_names) { const char *ref_name; while (!exception && (error = git_reference_next_name(&ref_name, iter)) == GIT_OK) { rb_protect(rb_yield, rb_str_new_utf8(ref_name), &exception); } } else { git_reference *ref; while (!exception && (error = git_reference_next(&ref, iter)) == GIT_OK) { rb_protect(rb_yield, rugged_ref_new(rb_cRuggedReference, rb_repo, ref), &exception); } } git_reference_iterator_free(iter); if (exception) rb_jump_tag(exception); if (error != GIT_ITEROVER) rugged_exception_check(error); return Qnil; } /* * call-seq: * references.each(glob = nil) { |ref| block } -> nil * references.each(glob = nil) -> enumerator * * Iterate through all the references in the collection's +repository+. Iteration * can be optionally filtered to the ones matching the given * +glob+, a standard Unix filename glob. * * The given block will be called once with a Rugged::Reference * instance for each reference. * * If no block is given, an enumerator will be returned. */ static VALUE rb_git_reference_collection_each(int argc, VALUE *argv, VALUE self) { return rb_git_reference_collection__each(argc, argv, self, 0); } /* * call-seq: * references.each_name(glob = nil) { |ref_name| block } -> nil * references.each_name(glob = nil) -> enumerator * * Iterate through all the reference names in the collection's +repository+. Iteration * can be optionally filtered to the ones matching the given * +glob+, a standard Unix filename glob. * * The given block will be called once with the name of each reference. * * If no block is given, an enumerator will be returned. */ static VALUE rb_git_reference_collection_each_name(int argc, VALUE *argv, VALUE self) { return rb_git_reference_collection__each(argc, argv, self, 1); } /* * call-seq: * references.exist?(name) -> true or false * references.exists?(name) -> true or false * * Check if a given reference exists with the given +name+. */ static VALUE rb_git_reference_collection_exist_p(VALUE self, VALUE rb_name_or_ref) { VALUE rb_repo = rugged_owner(self); git_repository *repo; git_reference *ref; int error; if (rb_obj_is_kind_of(rb_name_or_ref, rb_cRuggedReference)) rb_name_or_ref = rb_funcall(rb_name_or_ref, rb_intern("canonical_name"), 0); if (TYPE(rb_name_or_ref) != T_STRING) rb_raise(rb_eTypeError, "Expecting a String or Rugged::Reference instance"); Data_Get_Struct(rb_repo, git_repository, repo); error = git_reference_lookup(&ref, repo, StringValueCStr(rb_name_or_ref)); git_reference_free(ref); if (error == GIT_ENOTFOUND) return Qfalse; else rugged_exception_check(error); return Qtrue; } /* * call-seq: * references.rename(old_name, new_name, options = {}) -> new_ref * references.rename(ref, new_name, options = {}) -> new_ref * * Change the name of a reference. If +force+ is +true+, any previously * existing references will be overwritten when renaming. * * Return a new reference object with the new object * * reference.name #=> 'refs/heads/master' * new_ref = references.rename(ref, 'refs/heads/development') #=> <Reference> * new_ref.name #=> 'refs/heads/development' * * The following options can be passed in the +options+ Hash: * * :force :: * Overwrites the reference with the given +name+, if it already exists, * instead of raising an exception. * * If a reference with the given +new_name+ already exists and +:force+ is not +true+, * an exception will be raised. */ static VALUE rb_git_reference_collection_rename(int argc, VALUE *argv, VALUE self) { VALUE rb_new_name, rb_name_or_ref, rb_options; VALUE rb_repo = rugged_owner(self); git_reference *ref, *out = NULL; git_repository *repo; char *log_message = NULL; int error, force = 0; rb_scan_args(argc, argv, "20:", &rb_name_or_ref, &rb_new_name, &rb_options); Check_Type(rb_new_name, T_STRING); if (rb_obj_is_kind_of(rb_name_or_ref, rb_cRuggedReference)) rb_name_or_ref = rb_funcall(rb_name_or_ref, rb_intern("canonical_name"), 0); if (TYPE(rb_name_or_ref) != T_STRING) rb_raise(rb_eTypeError, "Expecting a String or Rugged::Reference instance"); rugged_check_repo(rb_repo); Data_Get_Struct(rb_repo, git_repository, repo); if (!NIL_P(rb_options)) { VALUE rb_val = rb_hash_aref(rb_options, CSTR2SYM("message")); if (!NIL_P(rb_val)) log_message = StringValueCStr(rb_val); force = RTEST(rb_hash_aref(rb_options, CSTR2SYM("force"))); } if ((error = git_reference_lookup(&ref, repo, StringValueCStr(rb_name_or_ref))) == GIT_OK) error = git_reference_rename(&out, ref, StringValueCStr(rb_new_name), force, log_message); git_reference_free(ref); rugged_exception_check(error); return rugged_ref_new(rb_cRuggedReference, rugged_owner(self), out); } /* * call-seq: * references.update(ref, oid) -> new_ref * references.update(name, oid) -> new_ref * references.update(ref, other_ref) -> new_ref * references.update(name, other_ref_name) -> new_ref * * Set the target of a reference. If +ref+ is a direct reference, * the new target must be a +String+ representing a SHA1 OID. * * If +reference+ is symbolic, the new target must be a +String+ with * the name of another reference. * * The original reference is unaltered; a new reference object is * returned with the new target, and the changes are persisted to * disk. * * r1.type #=> :symbolic * references.update(r1, "refs/heads/master") #=> <Reference> * * r2.type #=> :direct * references.update(r2, "de5ba987198bcf2518885f0fc1350e5172cded78") #=> <Reference> */ static VALUE rb_git_reference_collection_update(int argc, VALUE *argv, VALUE self) { VALUE rb_repo = rugged_owner(self), rb_name_or_ref, rb_target, rb_options; git_repository *repo = NULL; git_reference *ref = NULL, *out = NULL; char *log_message = NULL; int error; rb_scan_args(argc, argv, "20:", &rb_name_or_ref, &rb_target, &rb_options); if (rb_obj_is_kind_of(rb_name_or_ref, rb_cRuggedReference)) rb_name_or_ref = rb_funcall(rb_name_or_ref, rb_intern("canonical_name"), 0); if (TYPE(rb_name_or_ref) != T_STRING) rb_raise(rb_eTypeError, "Expecting a String or Rugged::Reference instance"); if (rb_obj_is_kind_of(rb_target, rb_cRuggedReference)) rb_target = rb_funcall(rb_target, rb_intern("canonical_name"), 0); if (TYPE(rb_target) != T_STRING) rb_raise(rb_eTypeError, "Expecting a String or Rugged::Reference instance"); if (!NIL_P(rb_options)) { VALUE rb_val = rb_hash_aref(rb_options, CSTR2SYM("message")); if (!NIL_P(rb_val)) log_message = StringValueCStr(rb_val); } rugged_check_repo(rb_repo); Data_Get_Struct(rb_repo, git_repository, repo); error = git_reference_lookup(&ref, repo, StringValueCStr(rb_name_or_ref)); rugged_exception_check(error); if (git_reference_type(ref) == GIT_REF_OID) { git_oid target; error = git_oid_fromstr(&target, StringValueCStr(rb_target)); if (error) goto cleanup; error = git_reference_set_target(&out, ref, &target, log_message); } else { error = git_reference_symbolic_set_target(&out, ref, StringValueCStr(rb_target), log_message); } cleanup: git_reference_free(ref); rugged_exception_check(error); return rugged_ref_new(rb_cRuggedReference, rb_repo, out); } /* * call-seq: * references.delete(ref) -> nil * references.delete(name) -> nil * * Delete specified reference. * * If a Rugged::Reference object was passed, the object will become * invalidated and won't be able to be used for any other operations. * * repo.references.delete("HEAD") * # Reference no longer exists on disk */ static VALUE rb_git_reference_collection_delete(VALUE self, VALUE rb_name_or_ref) { VALUE rb_repo = rugged_owner(self); git_reference *ref; git_repository *repo; int error; if (rb_obj_is_kind_of(rb_name_or_ref, rb_cRuggedReference)) rb_name_or_ref = rb_funcall(rb_name_or_ref, rb_intern("canonical_name"), 0); if (TYPE(rb_name_or_ref) != T_STRING) rb_raise(rb_eTypeError, "Expecting a String or Rugged::Reference instance"); rugged_check_repo(rb_repo); Data_Get_Struct(rb_repo, git_repository, repo); error = git_reference_lookup(&ref, repo, StringValueCStr(rb_name_or_ref)); rugged_exception_check(error); error = git_reference_delete(ref); git_reference_free(ref); rugged_exception_check(error); return Qnil; } void Init_rugged_reference_collection(void) { rb_cRuggedReferenceCollection = rb_define_class_under(rb_mRugged, "ReferenceCollection", rb_cObject); rb_include_module(rb_cRuggedReferenceCollection, rb_mEnumerable); rb_define_method(rb_cRuggedReferenceCollection, "initialize", rb_git_reference_collection_initialize, 1); rb_define_method(rb_cRuggedReferenceCollection, "create", rb_git_reference_collection_create, -1); rb_define_method(rb_cRuggedReferenceCollection, "[]", rb_git_reference_collection_aref, 1); rb_define_method(rb_cRuggedReferenceCollection, "each", rb_git_reference_collection_each, -1); rb_define_method(rb_cRuggedReferenceCollection, "each_name", rb_git_reference_collection_each_name, -1); rb_define_method(rb_cRuggedReferenceCollection, "exist?", rb_git_reference_collection_exist_p, 1); rb_define_method(rb_cRuggedReferenceCollection, "exists?", rb_git_reference_collection_exist_p, 1); rb_define_method(rb_cRuggedReferenceCollection, "move", rb_git_reference_collection_rename, -1); rb_define_method(rb_cRuggedReferenceCollection, "rename", rb_git_reference_collection_rename, -1); rb_define_method(rb_cRuggedReferenceCollection, "update", rb_git_reference_collection_update, -1); rb_define_method(rb_cRuggedReferenceCollection, "delete", rb_git_reference_collection_delete, 1); }
2aed70e387866f63d02e6d41f6053e1832e15088
1232ad844f7cd26a8557c9e4857511bcfc15a4dc
/src/nimble/porting/npl/freertos/src/npl_os_freertos.c
27338b262ec376f7f443810aef50e34c49cce126
[ "LicenseRef-scancode-gary-s-brown", "BSD-3-Clause", "Apache-2.0" ]
permissive
h2zero/NimBLE-Arduino
ed248f407e3444d1868a71b6a09c75dae61190a6
bc333ccb6e8d9ff2059af9cbd5006a290a4de3a5
refs/heads/release/1.4
2023-08-10T17:13:05.681059
2023-05-29T13:56:31
2023-05-29T14:00:01
244,276,348
520
129
Apache-2.0
2023-08-19T03:52:45
2020-03-02T04:00:48
C
UTF-8
C
false
false
49,065
c
npl_os_freertos.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 "nimble/porting/nimble/include/syscfg/syscfg.h" #if CONFIG_NIMBLE_STACK_USE_MEM_POOLS #include <assert.h> #include <stddef.h> #include <string.h> #include <stdlib.h> #include "nimble/console/console.h" #include "nimble/nimble/include/nimble/nimble_npl.h" #include "freertos/FreeRTOS.h" #include "freertos/queue.h" #include "freertos/semphr.h" #include "freertos/task.h" #include "freertos/timers.h" #include "freertos/portable.h" #include "../include/nimble/npl_freertos.h" #include "nimble/porting/nimble/include/os/os_mempool.h" #ifdef ESP_PLATFORM #include "esp_log.h" #include "soc/soc_caps.h" portMUX_TYPE ble_port_mutex = portMUX_INITIALIZER_UNLOCKED; #else #include "nrf.h" static void *radio_isr_addr; static void *rng_isr_addr; static void *rtc0_isr_addr; #endif #if CONFIG_BT_NIMBLE_USE_ESP_TIMER static const char *TAG = "Timer"; #endif #define OS_MEM_ALLOC (1) #if CONFIG_BT_NIMBLE_ENABLED #define BT_LE_HCI_EVT_HI_BUF_COUNT MYNEWT_VAL(BLE_HCI_EVT_HI_BUF_COUNT) #define BT_LE_HCI_EVT_LO_BUF_COUNT MYNEWT_VAL(BLE_HCI_EVT_LO_BUF_COUNT) #define BT_LE_MAX_EXT_ADV_INSTANCES MYNEWT_VAL(BLE_MULTI_ADV_INSTANCES) #define BT_LE_MAX_CONNECTIONS MYNEWT_VAL(BLE_MAX_CONNECTIONS) #else #include "esp_bt.h" #define BT_LE_HCI_EVT_HI_BUF_COUNT DEFAULT_BT_LE_HCI_EVT_HI_BUF_COUNT #define BT_LE_HCI_EVT_LO_BUF_COUNT DEFAULT_BT_LE_HCI_EVT_LO_BUF_COUNT #define BT_LE_MAX_EXT_ADV_INSTANCES DEFAULT_BT_LE_MAX_EXT_ADV_INSTANCES #define BT_LE_MAX_CONNECTIONS DEFAULT_BT_LE_MAX_CONNECTIONS #endif #define BLE_HS_HCI_EVT_COUNT \ (BT_LE_HCI_EVT_HI_BUF_COUNT + \ BT_LE_HCI_EVT_LO_BUF_COUNT) #define LL_NPL_BASE_EVENT_COUNT (11) #define LL_SCAN_EXT_AUX_EVT_CNT (MYNEWT_VAL(BLE_LL_EXT_ADV_AUX_PTR_CNT)) #define HCI_LL_NPL_EVENT_COUNT (1) #define ADV_LL_NPL_EVENT_COUNT ((BT_LE_MAX_EXT_ADV_INSTANCES+1)*3) #define SCAN_LL_NPL_EVENT_COUNT (2) #define RL_LL_NPL_EVENT_COUNT (1) #define SYNC_LL_NPL_EVENT_COUNT (7) #if MYNEWT_VAL(BLE_LL_CFG_FEAT_CTRL_TO_HOST_FLOW_CONTROL) #define LL_CTRL_TO_HOST_FLOW_CTRL_EVT (1) #else #define LL_CTRL_TO_HOST_FLOW_CTRL_EVT (0) #endif #if MYNEWT_VAL(BLE_LL_CFG_FEAT_LE_PING) #define LL_CFG_FEAT_LE_PING_EVT (1) #else #define LL_CFG_FEAT_LE_PING_EVT (0) #endif #define CONN_MODULE_NPL_EVENT_COUNT (((LL_CFG_FEAT_LE_PING_EVT+2)*BT_LE_MAX_CONNECTIONS)+LL_CTRL_TO_HOST_FLOW_CTRL_EVT) #define BLE_LL_EV_COUNT (LL_NPL_BASE_EVENT_COUNT + \ LL_SCAN_EXT_AUX_EVT_CNT + \ HCI_LL_NPL_EVENT_COUNT + \ ADV_LL_NPL_EVENT_COUNT + \ SCAN_LL_NPL_EVENT_COUNT + \ RL_LL_NPL_EVENT_COUNT + \ SYNC_LL_NPL_EVENT_COUNT + \ CONN_MODULE_NPL_EVENT_COUNT) #define BLE_TOTAL_EV_COUNT (BLE_LL_EV_COUNT + BLE_HS_HCI_EVT_COUNT) #define BLE_TOTAL_EVQ_COUNT (10) #define BLE_TOTAL_CO_COUNT (40) #define BLE_TOTAL_SEM_COUNT (10) #define BLE_TOTAL_MUTEX_COUNT (10) #if SOC_ESP_NIMBLE_CONTROLLER struct os_mempool ble_freertos_ev_pool; static os_membuf_t *ble_freertos_ev_buf = NULL; struct os_mempool ble_freertos_evq_pool; static os_membuf_t *ble_freertos_evq_buf = NULL; struct os_mempool ble_freertos_co_pool; static os_membuf_t *ble_freertos_co_buf = NULL; struct os_mempool ble_freertos_sem_pool; static os_membuf_t *ble_freertos_sem_buf = NULL; struct os_mempool ble_freertos_mutex_pool; static os_membuf_t *ble_freertos_mutex_buf = NULL; #else struct os_mempool ble_freertos_ev_pool; static os_membuf_t ble_freertos_ev_buf[ OS_MEMPOOL_SIZE(BLE_TOTAL_EV_COUNT, sizeof (struct ble_npl_event_freertos)) ]; struct os_mempool ble_freertos_evq_pool; static os_membuf_t ble_freertos_evq_buf[ OS_MEMPOOL_SIZE(BLE_TOTAL_EVQ_COUNT, sizeof (struct ble_npl_eventq_freertos)) ]; struct os_mempool ble_freertos_co_pool; static os_membuf_t ble_freertos_co_buf[ OS_MEMPOOL_SIZE(BLE_TOTAL_CO_COUNT, sizeof (struct ble_npl_callout_freertos)) ]; struct os_mempool ble_freertos_sem_pool; static os_membuf_t ble_freertos_sem_buf[ OS_MEMPOOL_SIZE(BLE_TOTAL_SEM_COUNT, sizeof (struct ble_npl_sem_freertos)) ]; struct os_mempool ble_freertos_mutex_pool; static os_membuf_t ble_freertos_mutex_buf[ OS_MEMPOOL_SIZE(BLE_TOTAL_MUTEX_COUNT, sizeof (struct ble_npl_mutex_freertos)) ]; #endif bool IRAM_ATTR npl_freertos_os_started(void) { return xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED; } void * IRAM_ATTR npl_freertos_get_current_task_id(void) { return xTaskGetCurrentTaskHandle(); } void IRAM_ATTR npl_freertos_event_init(struct ble_npl_event *ev, ble_npl_event_fn *fn, void *arg) { struct ble_npl_event_freertos *event = NULL; #if OS_MEM_ALLOC if (!os_memblock_from(&ble_freertos_ev_pool,ev->event)) { ev->event = os_memblock_get(&ble_freertos_ev_pool); } #else if(!ev->event) { ev->event = malloc(sizeof(struct ble_npl_event_freertos)); } #endif event = (struct ble_npl_event_freertos *)ev->event; PLATFORM_BLE_LL_ASSERT(event); memset(event, 0, sizeof(*event)); event->fn = fn; event->arg = arg; } void IRAM_ATTR npl_freertos_event_deinit(struct ble_npl_event *ev) { PLATFORM_BLE_LL_ASSERT(ev->event); #if OS_MEM_ALLOC os_memblock_put(&ble_freertos_ev_pool,ev->event); #else free(ev->event); #endif ev->event = NULL; } void IRAM_ATTR npl_freertos_event_reset(struct ble_npl_event *ev) { struct ble_npl_event_freertos *event = (struct ble_npl_event_freertos *)ev->event; PLATFORM_BLE_LL_ASSERT(event); event->queued = 0; } void IRAM_ATTR npl_freertos_eventq_init(struct ble_npl_eventq *evq) { struct ble_npl_eventq_freertos *eventq = NULL; #if OS_MEM_ALLOC if (!os_memblock_from(&ble_freertos_evq_pool,evq->eventq)) { evq->eventq = os_memblock_get(&ble_freertos_evq_pool); eventq = (struct ble_npl_eventq_freertos*)evq->eventq; PLATFORM_BLE_LL_ASSERT(eventq); memset(eventq, 0, sizeof(*eventq)); eventq->q = xQueueCreate(BLE_TOTAL_EV_COUNT, sizeof(struct ble_npl_eventq *)); PLATFORM_BLE_LL_ASSERT(eventq->q); } #else if(!evq->eventq) { evq->eventq = malloc(sizeof(struct ble_npl_eventq_freertos)); eventq = (struct ble_npl_eventq_freertos*)evq->eventq; PLATFORM_BLE_LL_ASSERT(eventq); memset(eventq, 0, sizeof(*eventq)); eventq->q = xQueueCreate(BLE_TOTAL_EV_COUNT, sizeof(struct ble_npl_eventq *)); PLATFORM_BLE_LL_ASSERT(eventq->q); } #endif } void IRAM_ATTR npl_freertos_eventq_deinit(struct ble_npl_eventq *evq) { struct ble_npl_eventq_freertos *eventq = (struct ble_npl_eventq_freertos *)evq->eventq; PLATFORM_BLE_LL_ASSERT(eventq); vQueueDelete(eventq->q); #if OS_MEM_ALLOC os_memblock_put(&ble_freertos_evq_pool,eventq); #else free((void *)eventq); #endif evq->eventq = NULL; } void IRAM_ATTR npl_freertos_callout_mem_reset(struct ble_npl_callout *co) { struct ble_npl_callout_freertos *callout = (struct ble_npl_callout_freertos *)co->co; PLATFORM_BLE_LL_ASSERT(callout); PLATFORM_BLE_LL_ASSERT(callout->handle); ble_npl_event_reset(&callout->ev); } #ifdef ESP_PLATFORM static inline bool IRAM_ATTR in_isr(void) { /* XXX hw specific! */ return xPortInIsrContext() != 0; } #else static inline bool in_isr(void) { /* XXX hw specific! */ return (SCB->ICSR & SCB_ICSR_VECTACTIVE_Msk) != 0; } void RADIO_IRQHandler(void) { ((void (*)(void))radio_isr_addr)(); } void RNG_IRQHandler(void) { ((void (*)(void))rng_isr_addr)(); } void RTC0_IRQHandler(void) { ((void (*)(void))rtc0_isr_addr)(); } /* This is called by NimBLE radio driver to set interrupt handlers */ void npl_freertos_hw_set_isr(int irqn, void (*addr)(void)) { switch (irqn) { case RADIO_IRQn: radio_isr_addr = addr; break; case RNG_IRQn: rng_isr_addr = addr; break; case RTC0_IRQn: rtc0_isr_addr = addr; break; } } #endif struct ble_npl_event * IRAM_ATTR npl_freertos_eventq_get(struct ble_npl_eventq *evq, ble_npl_time_t tmo) { struct ble_npl_event *ev = NULL; struct ble_npl_eventq_freertos *eventq = (struct ble_npl_eventq_freertos *)evq->eventq; BaseType_t woken; BaseType_t ret; if (in_isr()) { PLATFORM_BLE_LL_ASSERT(tmo == 0); ret = xQueueReceiveFromISR(eventq->q, &ev, &woken); #ifdef ESP_PLATFORM if( woken == pdTRUE ) { portYIELD_FROM_ISR(); } #else portYIELD_FROM_ISR(woken); #endif } else { ret = xQueueReceive(eventq->q, &ev, tmo); } PLATFORM_BLE_LL_ASSERT(ret == pdPASS || ret == errQUEUE_EMPTY); if (ev) { struct ble_npl_event_freertos *event = (struct ble_npl_event_freertos *)ev->event; if (event) { event->queued = false; } } return ev; } void IRAM_ATTR npl_freertos_eventq_put(struct ble_npl_eventq *evq, struct ble_npl_event *ev) { BaseType_t woken; BaseType_t ret; struct ble_npl_eventq_freertos *eventq = (struct ble_npl_eventq_freertos *)evq->eventq; struct ble_npl_event_freertos *event = (struct ble_npl_event_freertos *)ev->event; if (event->queued) { return; } event->queued = true; if (in_isr()) { ret = xQueueSendToBackFromISR(eventq->q, &ev, &woken); #ifdef ESP_PLATFORM if( woken == pdTRUE ) { portYIELD_FROM_ISR(); } #else portYIELD_FROM_ISR(woken); #endif } else { ret = xQueueSendToBack(eventq->q, &ev, portMAX_DELAY); } PLATFORM_BLE_LL_ASSERT(ret == pdPASS); } void IRAM_ATTR npl_freertos_eventq_remove(struct ble_npl_eventq *evq, struct ble_npl_event *ev) { struct ble_npl_event *tmp_ev; BaseType_t ret; int i; int count; BaseType_t woken, woken2; struct ble_npl_eventq_freertos *eventq = (struct ble_npl_eventq_freertos *)evq->eventq; struct ble_npl_event_freertos *event = (struct ble_npl_event_freertos *)ev->event; if (!event->queued) { return; } /* * XXX We cannot extract element from inside FreeRTOS queue so as a quick * workaround we'll just remove all elements and add them back except the * one we need to remove. This is silly, but works for now - we probably * better use counting semaphore with os_queue to handle this in future. */ if (in_isr()) { woken = pdFALSE; count = uxQueueMessagesWaitingFromISR(eventq->q); for (i = 0; i < count; i++) { ret = xQueueReceiveFromISR(eventq->q, &tmp_ev, &woken2); PLATFORM_BLE_LL_ASSERT(ret == pdPASS); woken |= woken2; if (tmp_ev == ev) { continue; } ret = xQueueSendToBackFromISR(eventq->q, &tmp_ev, &woken2); PLATFORM_BLE_LL_ASSERT(ret == pdPASS); woken |= woken2; } #ifdef ESP_PLATFORM if( woken == pdTRUE ) { portYIELD_FROM_ISR(); } #else portYIELD_FROM_ISR(woken); #endif } else { #ifdef ESP_PLATFORM portMUX_TYPE ble_npl_mut = portMUX_INITIALIZER_UNLOCKED; portENTER_CRITICAL(&ble_npl_mut); count = uxQueueMessagesWaiting(eventq->q); #else vPortEnterCritical(); count = uxQueueMessagesWaiting(eventq->q); #endif for (i = 0; i < count; i++) { ret = xQueueReceive(eventq->q, &tmp_ev, 0); PLATFORM_BLE_LL_ASSERT(ret == pdPASS); if (tmp_ev == ev) { continue; } ret = xQueueSendToBack(eventq->q, &tmp_ev, 0); PLATFORM_BLE_LL_ASSERT(ret == pdPASS); } #ifdef ESP_PLATFORM portEXIT_CRITICAL(&ble_npl_mut); #else vPortExitCritical(); #endif } event->queued = 0; } ble_npl_error_t IRAM_ATTR npl_freertos_mutex_init(struct ble_npl_mutex *mu) { struct ble_npl_mutex_freertos *mutex = NULL; #if OS_MEM_ALLOC if (!os_memblock_from(&ble_freertos_mutex_pool,mu->mutex)) { mu->mutex = os_memblock_get(&ble_freertos_mutex_pool); mutex = (struct ble_npl_mutex_freertos *)mu->mutex; if (!mutex) { return BLE_NPL_INVALID_PARAM; } memset(mutex, 0, sizeof(*mutex)); mutex->handle = xSemaphoreCreateRecursiveMutex(); PLATFORM_BLE_LL_ASSERT(mutex->handle); } #else if(!mu->mutex) { mu->mutex = malloc(sizeof(struct ble_npl_mutex_freertos)); mutex = (struct ble_npl_mutex_freertos *)mu->mutex; if (!mutex) { return BLE_NPL_INVALID_PARAM; } memset(mutex, 0, sizeof(*mutex)); mutex->handle = xSemaphoreCreateRecursiveMutex(); PLATFORM_BLE_LL_ASSERT(mutex->handle); } #endif return BLE_NPL_OK; } ble_npl_error_t IRAM_ATTR npl_freertos_mutex_deinit(struct ble_npl_mutex *mu) { struct ble_npl_mutex_freertos *mutex = (struct ble_npl_mutex_freertos *)mu->mutex; if (!mutex) { return BLE_NPL_INVALID_PARAM; } PLATFORM_BLE_LL_ASSERT(mutex->handle); vSemaphoreDelete(mutex->handle); #if OS_MEM_ALLOC os_memblock_put(&ble_freertos_mutex_pool,mutex); #else free((void *)mutex); #endif mu->mutex = NULL; return BLE_NPL_OK; } void IRAM_ATTR npl_freertos_event_run(struct ble_npl_event *ev) { struct ble_npl_event_freertos *event = (struct ble_npl_event_freertos *)ev->event; event->fn(ev); } bool IRAM_ATTR npl_freertos_eventq_is_empty(struct ble_npl_eventq *evq) { struct ble_npl_eventq_freertos *eventq = (struct ble_npl_eventq_freertos *)evq->eventq; return xQueueIsQueueEmptyFromISR(eventq->q); } bool IRAM_ATTR npl_freertos_event_is_queued(struct ble_npl_event *ev) { struct ble_npl_event_freertos *event = (struct ble_npl_event_freertos *)ev->event; return event->queued; } void * IRAM_ATTR npl_freertos_event_get_arg(struct ble_npl_event *ev) { struct ble_npl_event_freertos *event = (struct ble_npl_event_freertos *)ev->event; return event->arg; } void IRAM_ATTR npl_freertos_event_set_arg(struct ble_npl_event *ev, void *arg) { struct ble_npl_event_freertos *event = (struct ble_npl_event_freertos *)ev->event; event->arg = arg; } ble_npl_error_t IRAM_ATTR npl_freertos_mutex_pend(struct ble_npl_mutex *mu, ble_npl_time_t timeout) { BaseType_t ret; struct ble_npl_mutex_freertos *mutex = (struct ble_npl_mutex_freertos *)mu->mutex; if (!mutex) { return BLE_NPL_INVALID_PARAM; } PLATFORM_BLE_LL_ASSERT(mutex->handle); if (in_isr()) { ret = pdFAIL; PLATFORM_BLE_LL_ASSERT(0); } else { ret = xSemaphoreTakeRecursive(mutex->handle, timeout); } return ret == pdPASS ? BLE_NPL_OK : BLE_NPL_TIMEOUT; } ble_npl_error_t IRAM_ATTR npl_freertos_mutex_release(struct ble_npl_mutex *mu) { struct ble_npl_mutex_freertos *mutex = (struct ble_npl_mutex_freertos *)mu->mutex; if (!mutex) { return BLE_NPL_INVALID_PARAM; } PLATFORM_BLE_LL_ASSERT(mutex->handle); if (in_isr()) { PLATFORM_BLE_LL_ASSERT(0); } else { if (xSemaphoreGiveRecursive(mutex->handle) != pdPASS) { return BLE_NPL_BAD_MUTEX; } } return BLE_NPL_OK; } ble_npl_error_t IRAM_ATTR npl_freertos_sem_init(struct ble_npl_sem *sem, uint16_t tokens) { struct ble_npl_sem_freertos *semaphor = NULL; #if OS_MEM_ALLOC if (!os_memblock_from(&ble_freertos_sem_pool,sem->sem)) { sem->sem = os_memblock_get(&ble_freertos_sem_pool); semaphor = (struct ble_npl_sem_freertos *)sem->sem; if (!semaphor) { return BLE_NPL_INVALID_PARAM; } memset(semaphor, 0, sizeof(*semaphor)); semaphor->handle = xSemaphoreCreateCounting(128, tokens); PLATFORM_BLE_LL_ASSERT(semaphor->handle); } #else if(!sem->sem) { sem->sem = malloc(sizeof(struct ble_npl_sem_freertos)); semaphor = (struct ble_npl_sem_freertos *)sem->sem; if (!semaphor) { return BLE_NPL_INVALID_PARAM; } memset(semaphor, 0, sizeof(*semaphor)); semaphor->handle = xSemaphoreCreateCounting(128, tokens); PLATFORM_BLE_LL_ASSERT(semaphor->handle); } #endif return BLE_NPL_OK; } ble_npl_error_t IRAM_ATTR npl_freertos_sem_deinit(struct ble_npl_sem *sem) { struct ble_npl_sem_freertos *semaphor = (struct ble_npl_sem_freertos *)sem->sem; if (!semaphor) { return BLE_NPL_INVALID_PARAM; } PLATFORM_BLE_LL_ASSERT(semaphor->handle); vSemaphoreDelete(semaphor->handle); #if OS_MEM_ALLOC os_memblock_put(&ble_freertos_sem_pool,semaphor); #else free((void *)semaphor); #endif sem->sem = NULL; return BLE_NPL_OK; } ble_npl_error_t IRAM_ATTR npl_freertos_sem_pend(struct ble_npl_sem *sem, ble_npl_time_t timeout) { BaseType_t woken; BaseType_t ret; struct ble_npl_sem_freertos *semaphor = (struct ble_npl_sem_freertos *)sem->sem; if (!semaphor) { return BLE_NPL_INVALID_PARAM; } PLATFORM_BLE_LL_ASSERT(semaphor->handle); if (in_isr()) { PLATFORM_BLE_LL_ASSERT(timeout == 0); ret = xSemaphoreTakeFromISR(semaphor->handle, &woken); #ifdef ESP_PLATFORM if( woken == pdTRUE ) { portYIELD_FROM_ISR(); } #else portYIELD_FROM_ISR(woken); #endif } else { ret = xSemaphoreTake(semaphor->handle, timeout); } return ret == pdPASS ? BLE_NPL_OK : BLE_NPL_TIMEOUT; } ble_npl_error_t IRAM_ATTR npl_freertos_sem_release(struct ble_npl_sem *sem) { BaseType_t ret; BaseType_t woken; struct ble_npl_sem_freertos *semaphor = (struct ble_npl_sem_freertos *)sem->sem; if (!semaphor) { return BLE_NPL_INVALID_PARAM; } PLATFORM_BLE_LL_ASSERT(semaphor->handle); if (in_isr()) { ret = xSemaphoreGiveFromISR(semaphor->handle, &woken); #ifdef ESP_PLATFORM if( woken == pdTRUE ) { portYIELD_FROM_ISR(); } #else portYIELD_FROM_ISR(woken); #endif } else { ret = xSemaphoreGive(semaphor->handle); } PLATFORM_BLE_LL_ASSERT(ret == pdPASS); return BLE_NPL_OK; } #if CONFIG_BT_NIMBLE_USE_ESP_TIMER static void IRAM_ATTR ble_npl_event_fn_wrapper(void *arg) { struct ble_npl_callout_freertos *callout = (struct ble_npl_callout_freertos *)arg; PLATFORM_BLE_LL_ASSERT(callout); if (callout->evq) { ble_npl_eventq_put(callout->evq, &callout->ev); } else { struct ble_npl_event_freertos *event = (struct ble_npl_event_freertos *)callout->ev.event; event->fn(&callout->ev); } } static IRAM_ATTR ble_npl_error_t esp_err_to_npl_error(esp_err_t err) { switch(err) { case ESP_ERR_INVALID_ARG: return BLE_NPL_INVALID_PARAM; case ESP_ERR_INVALID_STATE: return BLE_NPL_EINVAL; case ESP_OK: return BLE_NPL_OK; default: return BLE_NPL_ERROR; } } #else static void IRAM_ATTR os_callout_timer_cb(TimerHandle_t timer) { struct ble_npl_callout_freertos *callout; callout = pvTimerGetTimerID(timer); PLATFORM_BLE_LL_ASSERT(callout); if (callout->evq) { ble_npl_eventq_put(callout->evq, &callout->ev); } else { struct ble_npl_event_freertos *event = (struct ble_npl_event_freertos *)callout->ev.event; event->fn(&callout->ev); } } #endif void IRAM_ATTR npl_freertos_callout_init(struct ble_npl_callout *co, struct ble_npl_eventq *evq, ble_npl_event_fn *ev_cb, void *ev_arg) { struct ble_npl_callout_freertos *callout = NULL; #if OS_MEM_ALLOC if (!os_memblock_from(&ble_freertos_co_pool, co->co)) { co->co = os_memblock_get(&ble_freertos_co_pool); callout = (struct ble_npl_callout_freertos *)co->co; PLATFORM_BLE_LL_ASSERT(callout); memset(callout, 0, sizeof(*callout)); ble_npl_event_init(&callout->ev, ev_cb, ev_arg); #if CONFIG_BT_NIMBLE_USE_ESP_TIMER callout->evq = evq; esp_timer_create_args_t create_args = { .callback = ble_npl_event_fn_wrapper, .arg = callout, .name = "nimble_timer" }; ESP_ERROR_CHECK(esp_timer_create(&create_args, &callout->handle)); #else callout->handle = xTimerCreate("co", 1, pdFALSE, callout, os_callout_timer_cb); #endif PLATFORM_BLE_LL_ASSERT(callout->handle); } else { callout = (struct ble_npl_callout_freertos *)co->co; PLATFORM_BLE_LL_ASSERT(callout); callout->evq = evq; ble_npl_event_init(&callout->ev, ev_cb, ev_arg); } #else if(!co->co) { co->co = malloc(sizeof(struct ble_npl_callout_freertos)); callout = (struct ble_npl_callout_freertos *)co->co; PLATFORM_BLE_LL_ASSERT(callout); memset(callout, 0, sizeof(*callout)); ble_npl_event_init(&callout->ev, ev_cb, ev_arg); #if CONFIG_BT_NIMBLE_USE_ESP_TIMER callout->evq = evq; esp_timer_create_args_t create_args = { .callback = ble_npl_event_fn_wrapper, .arg = callout, .name = "nimble_timer" }; ESP_ERROR_CHECK(esp_timer_create(&create_args, &callout->handle)); #else callout->handle = xTimerCreate("co", 1, pdFALSE, callout, os_callout_timer_cb); #endif PLATFORM_BLE_LL_ASSERT(callout->handle); } else { callout = (struct ble_npl_callout_freertos *)co->co; PLATFORM_BLE_LL_ASSERT(callout); callout->evq = evq; ble_npl_event_init(&callout->ev, ev_cb, ev_arg); } #endif } void IRAM_ATTR npl_freertos_callout_deinit(struct ble_npl_callout *co) { struct ble_npl_callout_freertos *callout = (struct ble_npl_callout_freertos *)co->co; /* Since we dynamically deinit timers, function can be called for NULL timers. Return for such scenarios */ if (!callout) { return; } PLATFORM_BLE_LL_ASSERT(callout->handle); #if CONFIG_BT_NIMBLE_USE_ESP_TIMER if(esp_timer_stop(callout->handle)) ESP_LOGD(TAG, "Timer not stopped"); if(esp_timer_delete(callout->handle)) ESP_LOGW(TAG, "Timer not deleted"); #else xTimerDelete(callout->handle, portMAX_DELAY); ble_npl_event_deinit(&callout->ev); #if OS_MEM_ALLOC os_memblock_put(&ble_freertos_co_pool,callout); #else free((void *)callout); #endif #endif co->co = NULL; memset(co, 0, sizeof(struct ble_npl_callout)); } uint16_t IRAM_ATTR npl_freertos_sem_get_count(struct ble_npl_sem *sem) { struct ble_npl_sem_freertos *semaphor = (struct ble_npl_sem_freertos *)sem->sem; return uxSemaphoreGetCount(semaphor->handle); } ble_npl_error_t IRAM_ATTR npl_freertos_callout_reset(struct ble_npl_callout *co, ble_npl_time_t ticks) { struct ble_npl_callout_freertos *callout = (struct ble_npl_callout_freertos *)co->co; #if CONFIG_BT_NIMBLE_USE_ESP_TIMER esp_timer_stop(callout->handle); return esp_err_to_npl_error(esp_timer_start_once(callout->handle, ticks*1000)); #else BaseType_t woken1, woken2, woken3; if (ticks == 0) { ticks = 1; } if (in_isr()) { xTimerStopFromISR(callout->handle, &woken1); xTimerChangePeriodFromISR(callout->handle, ticks, &woken2); xTimerResetFromISR(callout->handle, &woken3); #ifdef ESP_PLATFORM if( woken1 == pdTRUE || woken2 == pdTRUE || woken3 == pdTRUE) { portYIELD_FROM_ISR(); } #else portYIELD_FROM_ISR(woken1 || woken2 || woken3); #endif } else { xTimerStop(callout->handle, portMAX_DELAY); xTimerChangePeriod(callout->handle, ticks, portMAX_DELAY); xTimerReset(callout->handle, portMAX_DELAY); } return BLE_NPL_OK; #endif } void IRAM_ATTR npl_freertos_callout_stop(struct ble_npl_callout *co) { struct ble_npl_callout_freertos *callout = (struct ble_npl_callout_freertos *)co->co; if (!callout) { return; } #if CONFIG_BT_NIMBLE_USE_ESP_TIMER esp_timer_stop(callout->handle); #else xTimerStop(callout->handle, portMAX_DELAY); #endif } bool IRAM_ATTR npl_freertos_callout_is_active(struct ble_npl_callout *co) { struct ble_npl_callout_freertos *callout = (struct ble_npl_callout_freertos *)co->co; #if CONFIG_BT_NIMBLE_USE_ESP_TIMER return esp_timer_is_active(callout->handle); #else /* Workaround for bug in xTimerIsTimerActive with FreeRTOS V10.2.0, fixed in V10.4.4 * See: https://github.com/FreeRTOS/FreeRTOS-Kernel/pull/305 * Sometimes xTimerIsTimerActive returns pdTRUE even though the timer has expired, so we double check. */ return xTimerIsTimerActive(callout->handle) == pdTRUE && xTimerGetExpiryTime(callout->handle) > xTaskGetTickCountFromISR(); #endif } ble_npl_time_t IRAM_ATTR npl_freertos_callout_get_ticks(struct ble_npl_callout *co) { #if CONFIG_BT_NIMBLE_USE_ESP_TIMER /* Currently, esp_timer does not support an API which gets the expiry time for * current timer. * Returning 0 from here should not cause any effect. * Drawback of this approach is that existing code to reset timer would be called * more often (since the if condition to invoke reset timer would always succeed if * timer is active). */ return 0; #else struct ble_npl_callout_freertos *callout = (struct ble_npl_callout_freertos *)co->co; return xTimerGetExpiryTime(callout->handle); #endif } ble_npl_time_t IRAM_ATTR npl_freertos_callout_remaining_ticks(struct ble_npl_callout *co, ble_npl_time_t now) { ble_npl_time_t rt; uint32_t exp = 0; struct ble_npl_callout_freertos *callout = (struct ble_npl_callout_freertos *)co->co; #if CONFIG_BT_NIMBLE_USE_ESP_TIMER #if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0) uint64_t expiry = 0; esp_err_t err; //Fetch expiry time in microseconds err = esp_timer_get_expiry_time((esp_timer_handle_t)(callout->handle), &expiry); if (err != ESP_OK) { //Error. Could not fetch the expiry time return 0; } //Convert microseconds to ticks npl_freertos_time_ms_to_ticks((uint32_t)(expiry / 1000), &exp); #else //esp_timer_get_expiry_time() is only available from IDF 5.0 onwards //Set expiry to 0 exp = 0; #endif //ESP_IDF_VERSION #else exp = xTimerGetExpiryTime(callout->handle); #endif if (exp > now) { rt = exp - now; } else { rt = 0; } return rt; } void IRAM_ATTR npl_freertos_callout_set_arg(struct ble_npl_callout *co, void *arg) { struct ble_npl_callout_freertos *callout = (struct ble_npl_callout_freertos *)co->co; struct ble_npl_event_freertos *event = (struct ble_npl_event_freertos *)callout->ev.event; event->arg = arg; } uint32_t IRAM_ATTR npl_freertos_time_get(void) { #if CONFIG_BT_NIMBLE_USE_ESP_TIMER return esp_timer_get_time() / 1000; #else return xTaskGetTickCountFromISR(); #endif } ble_npl_error_t IRAM_ATTR npl_freertos_time_ms_to_ticks(uint32_t ms, ble_npl_time_t *out_ticks) { uint64_t ticks; #if CONFIG_BT_NIMBLE_USE_ESP_TIMER ticks = (uint64_t)ms; #else ticks = ((uint64_t)ms * configTICK_RATE_HZ) / 1000; #endif if (ticks > UINT32_MAX) { return BLE_NPL_EINVAL; } *out_ticks = ticks; return 0; } ble_npl_error_t IRAM_ATTR npl_freertos_time_ticks_to_ms(ble_npl_time_t ticks, uint32_t *out_ms) { uint64_t ms; #if CONFIG_BT_NIMBLE_USE_ESP_TIMER ms = ((uint64_t)ticks); #else ms = ((uint64_t)ticks * 1000) / configTICK_RATE_HZ; #endif if (ms > UINT32_MAX) { return BLE_NPL_EINVAL; } *out_ms = ms; return 0; } ble_npl_time_t IRAM_ATTR npl_freertos_time_ms_to_ticks32(uint32_t ms) { #if CONFIG_BT_NIMBLE_USE_ESP_TIMER return ms; #else return ms * configTICK_RATE_HZ / 1000; #endif } uint32_t IRAM_ATTR npl_freertos_time_ticks_to_ms32(ble_npl_time_t ticks) { #if CONFIG_BT_NIMBLE_USE_ESP_TIMER return ticks; #else return ticks * 1000 / configTICK_RATE_HZ; #endif } void IRAM_ATTR npl_freertos_time_delay(ble_npl_time_t ticks) { #if CONFIG_BT_NIMBLE_USE_ESP_TIMER vTaskDelay(ticks / portTICK_PERIOD_MS); #else vTaskDelay(ticks); #endif } #ifdef ESP_PLATFORM #if NIMBLE_CFG_CONTROLLER || CONFIG_NIMBLE_CONTROLLER_MODE void IRAM_ATTR npl_freertos_hw_set_isr(int irqn, uint32_t addr) { //Do nothing } #endif #endif uint8_t hw_critical_state_status = 0; uint32_t IRAM_ATTR npl_freertos_hw_enter_critical(void) { ++hw_critical_state_status; #ifdef ESP_PLATFORM portENTER_CRITICAL(&ble_port_mutex); #else portENTER_CRITICAL(); #endif return 0; } uint8_t IRAM_ATTR npl_freertos_hw_is_in_critical(void) { return hw_critical_state_status; } void IRAM_ATTR npl_freertos_hw_exit_critical(uint32_t ctx) { --hw_critical_state_status; #ifdef ESP_PLATFORM portEXIT_CRITICAL(&ble_port_mutex); #else portEXIT_CRITICAL(); #endif } uint32_t IRAM_ATTR npl_freertos_get_time_forever(void) { return portMAX_DELAY; } const struct npl_funcs_t npl_funcs_ro = { .p_ble_npl_os_started = npl_freertos_os_started, .p_ble_npl_get_current_task_id = npl_freertos_get_current_task_id, .p_ble_npl_eventq_init = npl_freertos_eventq_init, .p_ble_npl_eventq_deinit = npl_freertos_eventq_deinit, .p_ble_npl_eventq_get = npl_freertos_eventq_get, .p_ble_npl_eventq_put = npl_freertos_eventq_put, .p_ble_npl_eventq_remove = npl_freertos_eventq_remove, .p_ble_npl_event_run = npl_freertos_event_run, .p_ble_npl_eventq_is_empty = npl_freertos_eventq_is_empty, .p_ble_npl_event_init = npl_freertos_event_init, .p_ble_npl_event_deinit = npl_freertos_event_deinit, .p_ble_npl_event_reset = npl_freertos_event_reset, .p_ble_npl_event_is_queued = npl_freertos_event_is_queued, .p_ble_npl_event_get_arg = npl_freertos_event_get_arg, .p_ble_npl_event_set_arg = npl_freertos_event_set_arg, .p_ble_npl_mutex_init = npl_freertos_mutex_init, .p_ble_npl_mutex_deinit = npl_freertos_mutex_deinit, .p_ble_npl_mutex_pend = npl_freertos_mutex_pend, .p_ble_npl_mutex_release = npl_freertos_mutex_release, .p_ble_npl_sem_init = npl_freertos_sem_init, .p_ble_npl_sem_deinit = npl_freertos_sem_deinit, .p_ble_npl_sem_pend = npl_freertos_sem_pend, .p_ble_npl_sem_release = npl_freertos_sem_release, .p_ble_npl_sem_get_count = npl_freertos_sem_get_count, .p_ble_npl_callout_init = npl_freertos_callout_init, .p_ble_npl_callout_reset = npl_freertos_callout_reset, .p_ble_npl_callout_stop = npl_freertos_callout_stop, .p_ble_npl_callout_deinit = npl_freertos_callout_deinit, .p_ble_npl_callout_mem_reset = npl_freertos_callout_mem_reset, .p_ble_npl_callout_is_active = npl_freertos_callout_is_active, .p_ble_npl_callout_get_ticks = npl_freertos_callout_get_ticks, .p_ble_npl_callout_remaining_ticks = npl_freertos_callout_remaining_ticks, .p_ble_npl_callout_set_arg = npl_freertos_callout_set_arg, .p_ble_npl_time_get = npl_freertos_time_get, .p_ble_npl_time_ms_to_ticks = npl_freertos_time_ms_to_ticks, .p_ble_npl_time_ticks_to_ms = npl_freertos_time_ticks_to_ms, .p_ble_npl_time_ms_to_ticks32 = npl_freertos_time_ms_to_ticks32, .p_ble_npl_time_ticks_to_ms32 = npl_freertos_time_ticks_to_ms32, .p_ble_npl_time_delay = npl_freertos_time_delay, #if NIMBLE_CFG_CONTROLLER || CONFIG_NIMBLE_CONTROLLER_MODE .p_ble_npl_hw_set_isr = npl_freertos_hw_set_isr, #endif .p_ble_npl_hw_enter_critical = npl_freertos_hw_enter_critical, .p_ble_npl_hw_exit_critical = npl_freertos_hw_exit_critical, .p_ble_npl_get_time_forever = npl_freertos_get_time_forever, .p_ble_npl_hw_is_in_critical = npl_freertos_hw_is_in_critical }; struct npl_funcs_t *npl_funcs = NULL; struct npl_funcs_t * npl_freertos_funcs_get(void) { return npl_funcs; } void npl_freertos_funcs_init(void) { npl_funcs = (struct npl_funcs_t *)malloc(sizeof(struct npl_funcs_t)); if(!npl_funcs) { printf("npl funcs init failed\n"); assert(0); } memcpy(npl_funcs, &npl_funcs_ro, sizeof(struct npl_funcs_t)); } int npl_freertos_mempool_init(void) { int rc = -1; #if SOC_ESP_NIMBLE_CONTROLLER ble_freertos_ev_buf = malloc(OS_MEMPOOL_SIZE(BLE_TOTAL_EV_COUNT, sizeof (struct ble_npl_event_freertos)) * sizeof(os_membuf_t)); if(!ble_freertos_ev_buf) { goto _error; } ble_freertos_evq_buf = malloc(OS_MEMPOOL_SIZE(BLE_TOTAL_EVQ_COUNT, sizeof (struct ble_npl_eventq_freertos)) * sizeof(os_membuf_t)); if(!ble_freertos_evq_buf) { goto _error; } ble_freertos_co_buf = malloc(OS_MEMPOOL_SIZE(BLE_TOTAL_CO_COUNT, sizeof (struct ble_npl_callout_freertos)) * sizeof(os_membuf_t)); if(!ble_freertos_co_buf) { goto _error; } ble_freertos_sem_buf = malloc(OS_MEMPOOL_SIZE(BLE_TOTAL_SEM_COUNT, sizeof (struct ble_npl_sem_freertos)) * sizeof(os_membuf_t)); if(!ble_freertos_sem_buf) { goto _error; } ble_freertos_mutex_buf = malloc( OS_MEMPOOL_SIZE(BLE_TOTAL_MUTEX_COUNT, sizeof (struct ble_npl_mutex_freertos)) * sizeof(os_membuf_t)); if(!ble_freertos_mutex_buf) { goto _error; } #endif rc = os_mempool_init(&ble_freertos_ev_pool, BLE_TOTAL_EV_COUNT, sizeof (struct ble_npl_event_freertos), ble_freertos_ev_buf, "ble_freertos_ev_pool"); if(rc != 0) { goto _error; } rc = os_mempool_init(&ble_freertos_evq_pool, BLE_TOTAL_EVQ_COUNT, sizeof (struct ble_npl_eventq_freertos), ble_freertos_evq_buf, "ble_freertos_evq_pool"); if(rc != 0) { goto _error; } rc = os_mempool_init(&ble_freertos_co_pool, BLE_TOTAL_CO_COUNT, sizeof (struct ble_npl_callout_freertos), ble_freertos_co_buf, "ble_freertos_co_pool"); if(rc != 0) { goto _error; } rc = os_mempool_init(&ble_freertos_sem_pool, BLE_TOTAL_SEM_COUNT, sizeof (struct ble_npl_sem_freertos), ble_freertos_sem_buf, "ble_freertos_sem_pool"); if(rc != 0) { goto _error; } rc = os_mempool_init(&ble_freertos_mutex_pool, BLE_TOTAL_MUTEX_COUNT, sizeof (struct ble_npl_mutex_freertos), ble_freertos_mutex_buf, "ble_freertos_mutex_pool"); if(rc == 0) { return rc; } _error: #if SOC_ESP_NIMBLE_CONTROLLER if(ble_freertos_ev_buf) { free(ble_freertos_ev_buf); } if(ble_freertos_evq_buf) { free(ble_freertos_evq_buf); } if(ble_freertos_co_buf) { free(ble_freertos_co_buf); } if(ble_freertos_sem_buf) { free(ble_freertos_sem_buf); } if(ble_freertos_mutex_buf) { free(ble_freertos_mutex_buf); } return -1; #else PLATFORM_BLE_LL_ASSERT(rc == 0); return rc; #endif } void npl_freertos_mempool_deinit(void) { #if SOC_ESP_NIMBLE_CONTROLLER if(ble_freertos_ev_buf) { free(ble_freertos_ev_buf); } if(ble_freertos_evq_buf) { free(ble_freertos_evq_buf); } if(ble_freertos_co_buf) { free(ble_freertos_co_buf); } if(ble_freertos_sem_buf) { free(ble_freertos_sem_buf); } if(ble_freertos_mutex_buf) { free(ble_freertos_mutex_buf); } #endif } void npl_freertos_funcs_deinit(void) { if (npl_funcs) { free(npl_funcs); } npl_funcs = NULL; } #else // Not using MEM pools #include <assert.h> #include <stddef.h> #include <string.h> #include "nimble/nimble/include/nimble/nimble_npl.h" #ifdef ESP_PLATFORM #include "freertos/portable.h" #include "esp_log.h" portMUX_TYPE ble_port_mutex = portMUX_INITIALIZER_UNLOCKED; # if CONFIG_BT_NIMBLE_USE_ESP_TIMER static const char *TAG = "Timer"; # endif #else #include "nrf.h" static void *radio_isr_addr; static void *rng_isr_addr; static void *rtc0_isr_addr; #endif #ifdef ESP_PLATFORM static inline bool in_isr(void) { /* XXX hw specific! */ return xPortInIsrContext() != 0; } #else static inline bool in_isr(void) { /* XXX hw specific! */ return (SCB->ICSR & SCB_ICSR_VECTACTIVE_Msk) != 0; } void RADIO_IRQHandler(void) { ((void (*)(void))radio_isr_addr)(); } void RNG_IRQHandler(void) { ((void (*)(void))rng_isr_addr)(); } void RTC0_IRQHandler(void) { ((void (*)(void))rtc0_isr_addr)(); } /* This is called by NimBLE radio driver to set interrupt handlers */ void npl_freertos_hw_set_isr(int irqn, void (*addr)(void)) { switch (irqn) { case RADIO_IRQn: radio_isr_addr = addr; break; case RNG_IRQn: rng_isr_addr = addr; break; case RTC0_IRQn: rtc0_isr_addr = addr; break; } } #endif struct ble_npl_event * npl_freertos_eventq_get(struct ble_npl_eventq *evq, ble_npl_time_t tmo) { struct ble_npl_event *ev = NULL; BaseType_t woken; BaseType_t ret; if (in_isr()) { assert(tmo == 0); ret = xQueueReceiveFromISR(evq->q, &ev, &woken); #ifdef ESP_PLATFORM if( woken == pdTRUE ) { portYIELD_FROM_ISR(); } #else portYIELD_FROM_ISR(woken); #endif } else { ret = xQueueReceive(evq->q, &ev, tmo); } assert(ret == pdPASS || ret == errQUEUE_EMPTY); if (ev) { ev->queued = false; } return ev; } void npl_freertos_eventq_put(struct ble_npl_eventq *evq, struct ble_npl_event *ev) { BaseType_t woken; BaseType_t ret; if (ev->queued) { return; } ev->queued = true; if (in_isr()) { ret = xQueueSendToBackFromISR(evq->q, &ev, &woken); #ifdef ESP_PLATFORM if( woken == pdTRUE ) { portYIELD_FROM_ISR(); } #else portYIELD_FROM_ISR(woken); #endif } else { ret = xQueueSendToBack(evq->q, &ev, portMAX_DELAY); } assert(ret == pdPASS); } void npl_freertos_eventq_remove(struct ble_npl_eventq *evq, struct ble_npl_event *ev) { struct ble_npl_event *tmp_ev; BaseType_t ret; int i; int count; BaseType_t woken, woken2; if (!ev->queued) { return; } /* * XXX We cannot extract element from inside FreeRTOS queue so as a quick * workaround we'll just remove all elements and add them back except the * one we need to remove. This is silly, but works for now - we probably * better use counting semaphore with os_queue to handle this in future. */ if (in_isr()) { woken = pdFALSE; count = uxQueueMessagesWaitingFromISR(evq->q); for (i = 0; i < count; i++) { ret = xQueueReceiveFromISR(evq->q, &tmp_ev, &woken2); assert(ret == pdPASS); woken |= woken2; if (tmp_ev == ev) { continue; } ret = xQueueSendToBackFromISR(evq->q, &tmp_ev, &woken2); assert(ret == pdPASS); woken |= woken2; } #ifdef ESP_PLATFORM if( woken == pdTRUE ) { portYIELD_FROM_ISR(); } #else portYIELD_FROM_ISR(woken); #endif } else { #ifdef ESP_PLATFORM portMUX_TYPE ble_npl_mut = portMUX_INITIALIZER_UNLOCKED; portENTER_CRITICAL(&ble_npl_mut); #else vPortEnterCritical(); #endif count = uxQueueMessagesWaiting(evq->q); for (i = 0; i < count; i++) { ret = xQueueReceive(evq->q, &tmp_ev, 0); assert(ret == pdPASS); if (tmp_ev == ev) { continue; } ret = xQueueSendToBack(evq->q, &tmp_ev, 0); assert(ret == pdPASS); } #ifdef ESP_PLATFORM portEXIT_CRITICAL(&ble_npl_mut); #else vPortExitCritical(); #endif } ev->queued = 0; } ble_npl_error_t npl_freertos_mutex_init(struct ble_npl_mutex *mu) { if (!mu) { return BLE_NPL_INVALID_PARAM; } mu->handle = xSemaphoreCreateRecursiveMutex(); assert(mu->handle); return BLE_NPL_OK; } ble_npl_error_t npl_freertos_mutex_deinit(struct ble_npl_mutex *mu) { if (!mu) { return BLE_NPL_INVALID_PARAM; } if (mu->handle) { vSemaphoreDelete(mu->handle); } return BLE_NPL_OK; } ble_npl_error_t npl_freertos_mutex_pend(struct ble_npl_mutex *mu, ble_npl_time_t timeout) { BaseType_t ret; if (!mu) { return BLE_NPL_INVALID_PARAM; } assert(mu->handle); if (in_isr()) { ret = pdFAIL; assert(0); } else { ret = xSemaphoreTakeRecursive(mu->handle, timeout); } return ret == pdPASS ? BLE_NPL_OK : BLE_NPL_TIMEOUT; } ble_npl_error_t npl_freertos_mutex_release(struct ble_npl_mutex *mu) { if (!mu) { return BLE_NPL_INVALID_PARAM; } assert(mu->handle); if (in_isr()) { assert(0); } else { if (xSemaphoreGiveRecursive(mu->handle) != pdPASS) { return BLE_NPL_BAD_MUTEX; } } return BLE_NPL_OK; } ble_npl_error_t npl_freertos_sem_init(struct ble_npl_sem *sem, uint16_t tokens) { if (!sem) { return BLE_NPL_INVALID_PARAM; } sem->handle = xSemaphoreCreateCounting(128, tokens); assert(sem->handle); return BLE_NPL_OK; } ble_npl_error_t npl_freertos_sem_deinit(struct ble_npl_sem *sem) { if (!sem) { return BLE_NPL_INVALID_PARAM; } if (sem->handle) { vSemaphoreDelete(sem->handle); } return BLE_NPL_OK; } ble_npl_error_t npl_freertos_sem_pend(struct ble_npl_sem *sem, ble_npl_time_t timeout) { BaseType_t woken; BaseType_t ret; if (!sem) { return BLE_NPL_INVALID_PARAM; } assert(sem->handle); if (in_isr()) { assert(timeout == 0); ret = xSemaphoreTakeFromISR(sem->handle, &woken); #ifdef ESP_PLATFORM if( woken == pdTRUE ) { portYIELD_FROM_ISR(); } #else portYIELD_FROM_ISR(woken); #endif } else { ret = xSemaphoreTake(sem->handle, timeout); } return ret == pdPASS ? BLE_NPL_OK : BLE_NPL_TIMEOUT; } ble_npl_error_t npl_freertos_sem_release(struct ble_npl_sem *sem) { BaseType_t ret; BaseType_t woken; if (!sem) { return BLE_NPL_INVALID_PARAM; } assert(sem->handle); if (in_isr()) { ret = xSemaphoreGiveFromISR(sem->handle, &woken); #ifdef ESP_PLATFORM if( woken == pdTRUE ) { portYIELD_FROM_ISR(); } #else portYIELD_FROM_ISR(woken); #endif } else { ret = xSemaphoreGive(sem->handle); } assert(ret == pdPASS); return BLE_NPL_OK; } #if CONFIG_BT_NIMBLE_USE_ESP_TIMER static void ble_npl_event_fn_wrapper(void *arg) { struct ble_npl_callout *co = (struct ble_npl_callout *)arg; if (co->evq) { ble_npl_eventq_put(co->evq, &co->ev); } else { co->ev.fn(&co->ev); } } static ble_npl_error_t esp_err_to_npl_error(esp_err_t err) { switch(err) { case ESP_ERR_INVALID_ARG: return BLE_NPL_INVALID_PARAM; case ESP_ERR_INVALID_STATE: return BLE_NPL_EINVAL; case ESP_OK: return BLE_NPL_OK; default: return BLE_NPL_ERROR; } } #else static void os_callout_timer_cb(TimerHandle_t timer) { struct ble_npl_callout *co; co = pvTimerGetTimerID(timer); assert(co); if (co->evq) { ble_npl_eventq_put(co->evq, &co->ev); } else { co->ev.fn(&co->ev); } } #endif void npl_freertos_callout_init(struct ble_npl_callout *co, struct ble_npl_eventq *evq, ble_npl_event_fn *ev_cb, void *ev_arg) { #if CONFIG_BT_NIMBLE_USE_ESP_TIMER co->ev.fn = ev_cb; co->ev.arg = ev_arg; co->evq = evq; esp_timer_create_args_t create_args = { .callback = ble_npl_event_fn_wrapper, .arg = co, .name = "nimble_timer" }; ESP_ERROR_CHECK(esp_timer_create(&create_args, &co->handle)); #else if (co->handle == NULL) { co->handle = xTimerCreate("co", 1, pdFALSE, co, os_callout_timer_cb); } co->evq = evq; ble_npl_event_init(&co->ev, ev_cb, ev_arg); #endif } void npl_freertos_callout_deinit(struct ble_npl_callout *co) { if (!co->handle) { return; } #if CONFIG_BT_NIMBLE_USE_ESP_TIMER if(esp_timer_stop(co->handle)) ESP_LOGW(TAG, "Timer not stopped"); if(esp_timer_delete(co->handle)) ESP_LOGW(TAG, "Timer not deleted"); #else xTimerDelete(co->handle, portMAX_DELAY); ble_npl_event_deinit(&co->ev); #endif memset(co, 0, sizeof(struct ble_npl_callout)); } ble_npl_error_t npl_freertos_callout_reset(struct ble_npl_callout *co, ble_npl_time_t ticks) { #if CONFIG_BT_NIMBLE_USE_ESP_TIMER esp_timer_stop(co->handle); return esp_err_to_npl_error(esp_timer_start_once(co->handle, ticks*1000)); #else BaseType_t woken1, woken2, woken3; if (ticks == 0) { ticks = 1; } if (in_isr()) { xTimerStopFromISR(co->handle, &woken1); xTimerChangePeriodFromISR(co->handle, ticks, &woken2); xTimerResetFromISR(co->handle, &woken3); #ifdef ESP_PLATFORM if( woken1 == pdTRUE || woken2 == pdTRUE || woken3 == pdTRUE) { portYIELD_FROM_ISR(); } #else portYIELD_FROM_ISR(woken1 || woken2 || woken3); #endif } else { xTimerStop(co->handle, portMAX_DELAY); xTimerChangePeriod(co->handle, ticks, portMAX_DELAY); xTimerReset(co->handle, portMAX_DELAY); } return BLE_NPL_OK; #endif } void npl_freertos_callout_stop(struct ble_npl_callout *co) { if (!co->handle) { return; } #if CONFIG_BT_NIMBLE_USE_ESP_TIMER esp_timer_stop(co->handle); #else xTimerStop(co->handle, portMAX_DELAY); #endif } bool npl_freertos_callout_is_active(struct ble_npl_callout *co) { #if CONFIG_BT_NIMBLE_USE_ESP_TIMER return esp_timer_is_active(co->handle); #else /* Workaround for bug in xTimerIsTimerActive with FreeRTOS V10.2.0, fixed in V10.4.4 * See: https://github.com/FreeRTOS/FreeRTOS-Kernel/pull/305 * Sometimes xTimerIsTimerActive returns pdTRUE even though the timer has expired, so we double check. */ return xTimerIsTimerActive(co->handle) == pdTRUE && xTimerGetExpiryTime(co->handle) > xTaskGetTickCountFromISR(); #endif } ble_npl_time_t npl_freertos_callout_get_ticks(struct ble_npl_callout *co) { #if CONFIG_BT_NIMBLE_USE_ESP_TIMER /* Currently, esp_timer does not support an API which gets the expiry time for * current timer. * Returning 0 from here should not cause any effect. * Drawback of this approach is that existing code to reset timer would be called * more often (since the if condition to invoke reset timer would always succeed if * timer is active). */ return 0; #else return xTimerGetExpiryTime(co->handle); #endif } ble_npl_time_t npl_freertos_callout_remaining_ticks(struct ble_npl_callout *co, ble_npl_time_t now) { ble_npl_time_t rt; uint32_t exp = 0; #if CONFIG_BT_NIMBLE_USE_ESP_TIMER #if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0) uint64_t expiry = 0; esp_err_t err; //Fetch expiry time in microseconds err = esp_timer_get_expiry_time((esp_timer_handle_t)(co->handle), &expiry); if (err != ESP_OK) { //Error. Could not fetch the expiry time return 0; } //Convert microseconds to ticks npl_freertos_time_ms_to_ticks((uint32_t)(expiry / 1000), &exp); #else //esp_timer_get_expiry_time() is only available from IDF 5.0 onwards //Set expiry to 0 exp = 0; #endif //ESP_IDF_VERSION #else exp = xTimerGetExpiryTime(co->handle); #endif if (exp > now) { rt = exp - now; } else { rt = 0; } return rt; } ble_npl_error_t npl_freertos_time_ms_to_ticks(uint32_t ms, ble_npl_time_t *out_ticks) { uint64_t ticks; ticks = ((uint64_t)ms * configTICK_RATE_HZ) / 1000; if (ticks > UINT32_MAX) { return BLE_NPL_EINVAL; } *out_ticks = ticks; return 0; } ble_npl_error_t npl_freertos_time_ticks_to_ms(ble_npl_time_t ticks, uint32_t *out_ms) { uint64_t ms; ms = ((uint64_t)ticks * 1000) / configTICK_RATE_HZ; if (ms > UINT32_MAX) { return BLE_NPL_EINVAL; } *out_ms = ms; return 0; } #endif // CONFIG_NIMBLE_STACK_USE_MEM_POOLS
710292dbec6de20aa562b26bce4326318af733c3
cf60f9591fef521d3092f81785de7942d0ca568e
/PubNub/include/PNURLBuilder.h
72cea1a3aadd2a1f898a0cf60b121c2f3ace29dc
[ "MIT" ]
permissive
pubnub/objective-c
a49e2e5c7898eb893b601ae31a098361fb8b4406
eef06ae76fd45931ea09900e3b3ce50133870eca
refs/heads/master
2023-04-07T08:28:47.174178
2023-01-05T11:15:57
2023-01-05T11:15:57
8,490,984
137
145
NOASSERTION
2023-03-30T08:47:36
2013-03-01T00:10:41
Objective-C
UTF-8
C
false
false
25
h
PNURLBuilder.h
../Network/PNURLBuilder.h
0b4577345fc1f39155fd3bd4eadace679686a730
e3e7da042dcef56cd654d6599898eee34e7f1a08
/strings/apr_cpystrn.c
b70b1048b13aaaa1030d126d16fc1fa164df3441
[ "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
9,001
c
apr_cpystrn.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.h" #include "apr_strings.h" #include "apr_private.h" #include "apr_lib.h" #if APR_HAVE_SYS_TYPES_H #include <sys/types.h> #endif #if APR_HAVE_STRING_H #include <string.h> #endif #if APR_HAVE_CTYPE_H #include <ctype.h> #endif /* * Apache's "replacement" for the strncpy() function. We roll our * own to implement these specific changes: * (1) strncpy() doesn't always null terminate and we want it to. * (2) strncpy() null fills, which is bogus, esp. when copy 8byte * strings into 8k blocks. * (3) Instead of returning the pointer to the beginning of * the destination string, we return a pointer to the * terminating '\0' to allow us to "check" for truncation * (4) If src is NULL, null terminate dst (empty string copy) * * apr_cpystrn() follows the same call structure as strncpy(). */ APR_DECLARE(char *) apr_cpystrn(char *dst, const char *src, apr_size_t dst_size) { char *d = dst, *end; if (dst_size == 0) { return (dst); } if (src) { end = dst + dst_size - 1; for (; d < end; ++d, ++src) { if (!(*d = *src)) { return (d); } } } *d = '\0'; /* always null terminate */ return (d); } /* * This function provides a way to parse a generic argument string * into a standard argv[] form of argument list. It respects the * usual "whitespace" and quoteing rules. In the future this could * be expanded to include support for the apr_call_exec command line * string processing (including converting '+' to ' ' and doing the * url processing. It does not currently support this function. * * token_context: Context from which pool allocations will occur. * arg_str: Input argument string for conversion to argv[]. * argv_out: Output location. This is a pointer to an array * of pointers to strings (ie. &(char *argv[]). * This value will be allocated from the contexts * pool and filled in with copies of the tokens * found during parsing of the arg_str. */ APR_DECLARE(apr_status_t) apr_tokenize_to_argv(const char *arg_str, char ***argv_out, apr_pool_t *token_context) { const char *cp; const char *ct; char *cleaned, *dirty; int escaped; int isquoted, numargs = 0, argnum; #define SKIP_WHITESPACE(cp) \ for ( ; *cp == ' ' || *cp == '\t'; ) { \ cp++; \ }; #define CHECK_QUOTATION(cp,isquoted) \ isquoted = 0; \ if (*cp == '"') { \ isquoted = 1; \ cp++; \ } \ else if (*cp == '\'') { \ isquoted = 2; \ cp++; \ } /* DETERMINE_NEXTSTRING: * At exit, cp will point to one of the following: NULL, SPACE, TAB or QUOTE. * NULL implies the argument string has been fully traversed. */ #define DETERMINE_NEXTSTRING(cp,isquoted) \ for ( ; *cp != '\0'; cp++) { \ if ( (*cp == '\\' && (*(cp+1) == ' ' || *(cp+1) == '\t' || \ *(cp+1) == '"' || *(cp+1) == '\''))) { \ cp++; \ continue; \ } \ if ( (!isquoted && (*cp == ' ' || *cp == '\t')) \ || (isquoted == 1 && *cp == '"') \ || (isquoted == 2 && *cp == '\'') ) { \ break; \ } \ } /* REMOVE_ESCAPE_CHARS: * Compresses the arg string to remove all of the '\' escape chars. * The final argv strings should not have any extra escape chars in it. */ #define REMOVE_ESCAPE_CHARS(cleaned, dirty, escaped) \ escaped = 0; \ while(*dirty) { \ if (!escaped && *dirty == '\\') { \ escaped = 1; \ } \ else { \ escaped = 0; \ *cleaned++ = *dirty; \ } \ ++dirty; \ } \ *cleaned = 0; /* last line of macro... */ cp = arg_str; SKIP_WHITESPACE(cp); ct = cp; /* This is ugly and expensive, but if anyone wants to figure a * way to support any number of args without counting and * allocating, please go ahead and change the code. * * Must account for the trailing NULL arg. */ numargs = 1; while (*ct != '\0') { CHECK_QUOTATION(ct, isquoted); DETERMINE_NEXTSTRING(ct, isquoted); if (*ct != '\0') { ct++; } numargs++; SKIP_WHITESPACE(ct); } *argv_out = apr_palloc(token_context, numargs * sizeof(char*)); /* determine first argument */ for (argnum = 0; argnum < (numargs-1); argnum++) { SKIP_WHITESPACE(cp); CHECK_QUOTATION(cp, isquoted); ct = cp; DETERMINE_NEXTSTRING(cp, isquoted); cp++; (*argv_out)[argnum] = apr_palloc(token_context, cp - ct); apr_cpystrn((*argv_out)[argnum], ct, cp - ct); cleaned = dirty = (*argv_out)[argnum]; REMOVE_ESCAPE_CHARS(cleaned, dirty, escaped); } (*argv_out)[argnum] = NULL; return APR_SUCCESS; } /* Filepath_name_get returns the final element of the pathname. * Using the current platform's filename syntax. * "/foo/bar/gum" -> "gum" * "/foo/bar/gum/" -> "" * "gum" -> "gum" * "wi\\n32\\stuff" -> "stuff * * Corrected Win32 to accept "a/b\\stuff", "a:stuff" */ APR_DECLARE(const char *) apr_filepath_name_get(const char *pathname) { const char path_separator = '/'; const char *s = strrchr(pathname, path_separator); #ifdef WIN32 const char path_separator_win = '\\'; const char drive_separator_win = ':'; const char *s2 = strrchr(pathname, path_separator_win); if (s2 > s) s = s2; if (!s) s = strrchr(pathname, drive_separator_win); #endif return s ? ++s : pathname; } /* length of dest assumed >= length of src * collapse in place (src == dest) is legal. * returns terminating null ptr to dest string. */ APR_DECLARE(char *) apr_collapse_spaces(char *dest, const char *src) { while (*src) { if (!apr_isspace(*src)) *dest++ = *src; ++src; } *dest = 0; return (dest); } #if !APR_HAVE_STRDUP char *strdup(const char *str) { char *sdup; size_t len = strlen(str) + 1; sdup = (char *) malloc(len); if (sdup == NULL) return NULL; memcpy(sdup, str, len); return sdup; } #endif /* The following two routines were donated for SVR4 by Andreas Vogel */ #if (!APR_HAVE_STRCASECMP && !APR_HAVE_STRICMP) int strcasecmp(const char *a, const char *b) { const char *p = a; const char *q = b; for (p = a, q = b; *p && *q; p++, q++) { int diff = apr_tolower(*p) - apr_tolower(*q); if (diff) return diff; } if (*p) return 1; /* p was longer than q */ if (*q) return -1; /* p was shorter than q */ return 0; /* Exact match */ } #endif #if (!APR_HAVE_STRNCASECMP && !APR_HAVE_STRNICMP) int strncasecmp(const char *a, const char *b, size_t n) { const char *p = a; const char *q = b; for (p = a, q = b; /*NOTHING */ ; p++, q++) { int diff; if (p == a + n) return 0; /* Match up to n characters */ if (!(*p && *q)) return *p - *q; diff = apr_tolower(*p) - apr_tolower(*q); if (diff) return diff; } /*NOTREACHED */ } #endif /* The following routine was donated for UTS21 by dwd@bell-labs.com */ #if (!APR_HAVE_STRSTR) char *strstr(char *s1, char *s2) { char *p1, *p2; if (*s2 == '\0') { /* an empty s2 */ return(s1); } while((s1 = strchr(s1, *s2)) != NULL) { /* found first character of s2, see if the rest matches */ p1 = s1; p2 = s2; while (*++p1 == *++p2) { if (*p1 == '\0') { /* both strings ended together */ return(s1); } } if (*p2 == '\0') { /* second string ended, a match */ break; } /* didn't find a match here, try starting at next character in s1 */ s1++; } return(s1); } #endif
cea2ed54f1f5dc41610ab057a20e98805d890ffd
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
/www/mod_auth_xradius/files/patch-src_mod__auth__xradius.c
c48fdda9a160c871f18df50a8b0c4dc2538ac84e
[ "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
1,477
c
patch-src_mod__auth__xradius.c
--- src/mod_auth_xradius.c.orig 2005-04-28 07:58:25 UTC +++ src/mod_auth_xradius.c @@ -125,15 +125,15 @@ static int xrad_run_auth_check(request_r rctx = xrad_auth_open(); /* Loop through the array of RADIUS Servers, adding them to the rctx object */ - sr = (xrad_server_info *) dc->servers->elts; for (i = 0; i < dc->servers->nelts; ++i) { - rc = xrad_add_server(rctx, sr[i].hostname, sr[i].port, sr[i].secret, + sr = &(((xrad_server_info*)dc->servers->elts)[i]); + rc = xrad_add_server(rctx, sr->hostname, sr->port, sr->secret, dc->timeout, dc->maxtries); if (rc != 0) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "xradius: Failed to add server '%s:%d': (%d) %s", - sr[i].hostname, sr[i].port, rc, xrad_strerror(rctx)); + sr->hostname, sr->port, rc, xrad_strerror(rctx)); goto run_cleanup; } } @@ -294,7 +294,7 @@ static const char *xrad_conf_add_server( /* To properly use the Pools, this array is allocated from the here, instead of inside the directory configuration creation function. */ if (dc->servers == NULL) { - dc->servers = apr_array_make(parms->pool, 4, sizeof(xrad_server_info*)); + dc->servers = apr_array_make(parms->pool, 4, sizeof(xrad_server_info)); } sr = apr_array_push(dc->servers);
683451d91dd1772946f087da5355efed38aa486b
88ae8695987ada722184307301e221e1ba3cc2fa
/third_party/grpc/src/src/core/ext/upb-generated/xds/type/matcher/v3/domain.upb.h
6d335866d64de8aeae837a11c160b2eb17a6e710
[ "BSD-3-Clause", "MPL-2.0", "Apache-2.0", "LGPL-2.0-or-later", "MIT", "GPL-1.0-or-later" ]
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
10,052
h
domain.upb.h
/* This file was generated by upbc (the upb compiler) from the input * file: * * xds/type/matcher/v3/domain.proto * * Do not edit -- your changes will be discarded when the file is * regenerated. */ #ifndef XDS_TYPE_MATCHER_V3_DOMAIN_PROTO_UPB_H_ #define XDS_TYPE_MATCHER_V3_DOMAIN_PROTO_UPB_H_ #include "upb/msg_internal.h" #include "upb/decode.h" #include "upb/decode_fast.h" #include "upb/encode.h" #include "upb/port_def.inc" #ifdef __cplusplus extern "C" { #endif struct xds_type_matcher_v3_ServerNameMatcher; struct xds_type_matcher_v3_ServerNameMatcher_DomainMatcher; typedef struct xds_type_matcher_v3_ServerNameMatcher xds_type_matcher_v3_ServerNameMatcher; typedef struct xds_type_matcher_v3_ServerNameMatcher_DomainMatcher xds_type_matcher_v3_ServerNameMatcher_DomainMatcher; extern const upb_MiniTable xds_type_matcher_v3_ServerNameMatcher_msginit; extern const upb_MiniTable xds_type_matcher_v3_ServerNameMatcher_DomainMatcher_msginit; struct xds_type_matcher_v3_Matcher_OnMatch; extern const upb_MiniTable xds_type_matcher_v3_Matcher_OnMatch_msginit; /* xds.type.matcher.v3.ServerNameMatcher */ UPB_INLINE xds_type_matcher_v3_ServerNameMatcher* xds_type_matcher_v3_ServerNameMatcher_new(upb_Arena* arena) { return (xds_type_matcher_v3_ServerNameMatcher*)_upb_Message_New(&xds_type_matcher_v3_ServerNameMatcher_msginit, arena); } UPB_INLINE xds_type_matcher_v3_ServerNameMatcher* xds_type_matcher_v3_ServerNameMatcher_parse(const char* buf, size_t size, upb_Arena* arena) { xds_type_matcher_v3_ServerNameMatcher* ret = xds_type_matcher_v3_ServerNameMatcher_new(arena); if (!ret) return NULL; if (upb_Decode(buf, size, ret, &xds_type_matcher_v3_ServerNameMatcher_msginit, NULL, 0, arena) != kUpb_DecodeStatus_Ok) { return NULL; } return ret; } UPB_INLINE xds_type_matcher_v3_ServerNameMatcher* xds_type_matcher_v3_ServerNameMatcher_parse_ex(const char* buf, size_t size, const upb_ExtensionRegistry* extreg, int options, upb_Arena* arena) { xds_type_matcher_v3_ServerNameMatcher* ret = xds_type_matcher_v3_ServerNameMatcher_new(arena); if (!ret) return NULL; if (upb_Decode(buf, size, ret, &xds_type_matcher_v3_ServerNameMatcher_msginit, extreg, options, arena) != kUpb_DecodeStatus_Ok) { return NULL; } return ret; } UPB_INLINE char* xds_type_matcher_v3_ServerNameMatcher_serialize(const xds_type_matcher_v3_ServerNameMatcher* msg, upb_Arena* arena, size_t* len) { char* ptr; (void)upb_Encode(msg, &xds_type_matcher_v3_ServerNameMatcher_msginit, 0, arena, &ptr, len); return ptr; } UPB_INLINE char* xds_type_matcher_v3_ServerNameMatcher_serialize_ex(const xds_type_matcher_v3_ServerNameMatcher* msg, int options, upb_Arena* arena, size_t* len) { char* ptr; (void)upb_Encode(msg, &xds_type_matcher_v3_ServerNameMatcher_msginit, options, arena, &ptr, len); return ptr; } UPB_INLINE bool xds_type_matcher_v3_ServerNameMatcher_has_domain_matchers(const xds_type_matcher_v3_ServerNameMatcher* msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(0, 0)); } UPB_INLINE void xds_type_matcher_v3_ServerNameMatcher_clear_domain_matchers(const xds_type_matcher_v3_ServerNameMatcher* msg) { _upb_array_detach(msg, UPB_SIZE(0, 0)); } UPB_INLINE const xds_type_matcher_v3_ServerNameMatcher_DomainMatcher* const* xds_type_matcher_v3_ServerNameMatcher_domain_matchers(const xds_type_matcher_v3_ServerNameMatcher* msg, size_t* len) { return (const xds_type_matcher_v3_ServerNameMatcher_DomainMatcher* const*)_upb_array_accessor(msg, UPB_SIZE(0, 0), len); } UPB_INLINE xds_type_matcher_v3_ServerNameMatcher_DomainMatcher** xds_type_matcher_v3_ServerNameMatcher_mutable_domain_matchers(xds_type_matcher_v3_ServerNameMatcher* msg, size_t* len) { return (xds_type_matcher_v3_ServerNameMatcher_DomainMatcher**)_upb_array_mutable_accessor(msg, UPB_SIZE(0, 0), len); } UPB_INLINE xds_type_matcher_v3_ServerNameMatcher_DomainMatcher** xds_type_matcher_v3_ServerNameMatcher_resize_domain_matchers(xds_type_matcher_v3_ServerNameMatcher* msg, size_t len, upb_Arena* arena) { return (xds_type_matcher_v3_ServerNameMatcher_DomainMatcher**)_upb_Array_Resize_accessor2(msg, UPB_SIZE(0, 0), len, UPB_SIZE(2, 3), arena); } UPB_INLINE struct xds_type_matcher_v3_ServerNameMatcher_DomainMatcher* xds_type_matcher_v3_ServerNameMatcher_add_domain_matchers(xds_type_matcher_v3_ServerNameMatcher* msg, upb_Arena* arena) { struct xds_type_matcher_v3_ServerNameMatcher_DomainMatcher* sub = (struct xds_type_matcher_v3_ServerNameMatcher_DomainMatcher*)_upb_Message_New(&xds_type_matcher_v3_ServerNameMatcher_DomainMatcher_msginit, arena); bool ok = _upb_Array_Append_accessor2(msg, UPB_SIZE(0, 0), UPB_SIZE(2, 3), &sub, arena); if (!ok) return NULL; return sub; } /* xds.type.matcher.v3.ServerNameMatcher.DomainMatcher */ UPB_INLINE xds_type_matcher_v3_ServerNameMatcher_DomainMatcher* xds_type_matcher_v3_ServerNameMatcher_DomainMatcher_new(upb_Arena* arena) { return (xds_type_matcher_v3_ServerNameMatcher_DomainMatcher*)_upb_Message_New(&xds_type_matcher_v3_ServerNameMatcher_DomainMatcher_msginit, arena); } UPB_INLINE xds_type_matcher_v3_ServerNameMatcher_DomainMatcher* xds_type_matcher_v3_ServerNameMatcher_DomainMatcher_parse(const char* buf, size_t size, upb_Arena* arena) { xds_type_matcher_v3_ServerNameMatcher_DomainMatcher* ret = xds_type_matcher_v3_ServerNameMatcher_DomainMatcher_new(arena); if (!ret) return NULL; if (upb_Decode(buf, size, ret, &xds_type_matcher_v3_ServerNameMatcher_DomainMatcher_msginit, NULL, 0, arena) != kUpb_DecodeStatus_Ok) { return NULL; } return ret; } UPB_INLINE xds_type_matcher_v3_ServerNameMatcher_DomainMatcher* xds_type_matcher_v3_ServerNameMatcher_DomainMatcher_parse_ex(const char* buf, size_t size, const upb_ExtensionRegistry* extreg, int options, upb_Arena* arena) { xds_type_matcher_v3_ServerNameMatcher_DomainMatcher* ret = xds_type_matcher_v3_ServerNameMatcher_DomainMatcher_new(arena); if (!ret) return NULL; if (upb_Decode(buf, size, ret, &xds_type_matcher_v3_ServerNameMatcher_DomainMatcher_msginit, extreg, options, arena) != kUpb_DecodeStatus_Ok) { return NULL; } return ret; } UPB_INLINE char* xds_type_matcher_v3_ServerNameMatcher_DomainMatcher_serialize(const xds_type_matcher_v3_ServerNameMatcher_DomainMatcher* msg, upb_Arena* arena, size_t* len) { char* ptr; (void)upb_Encode(msg, &xds_type_matcher_v3_ServerNameMatcher_DomainMatcher_msginit, 0, arena, &ptr, len); return ptr; } UPB_INLINE char* xds_type_matcher_v3_ServerNameMatcher_DomainMatcher_serialize_ex(const xds_type_matcher_v3_ServerNameMatcher_DomainMatcher* msg, int options, upb_Arena* arena, size_t* len) { char* ptr; (void)upb_Encode(msg, &xds_type_matcher_v3_ServerNameMatcher_DomainMatcher_msginit, options, arena, &ptr, len); return ptr; } UPB_INLINE void xds_type_matcher_v3_ServerNameMatcher_DomainMatcher_clear_domains(const xds_type_matcher_v3_ServerNameMatcher_DomainMatcher* msg) { _upb_array_detach(msg, UPB_SIZE(4, 8)); } UPB_INLINE upb_StringView const* xds_type_matcher_v3_ServerNameMatcher_DomainMatcher_domains(const xds_type_matcher_v3_ServerNameMatcher_DomainMatcher* msg, size_t* len) { return (upb_StringView const*)_upb_array_accessor(msg, UPB_SIZE(4, 8), len); } UPB_INLINE bool xds_type_matcher_v3_ServerNameMatcher_DomainMatcher_has_on_match(const xds_type_matcher_v3_ServerNameMatcher_DomainMatcher* msg) { return _upb_hasbit(msg, 1); } UPB_INLINE void xds_type_matcher_v3_ServerNameMatcher_DomainMatcher_clear_on_match(const xds_type_matcher_v3_ServerNameMatcher_DomainMatcher* msg) { *UPB_PTR_AT(msg, UPB_SIZE(8, 16), const upb_Message*) = NULL; } UPB_INLINE const struct xds_type_matcher_v3_Matcher_OnMatch* xds_type_matcher_v3_ServerNameMatcher_DomainMatcher_on_match(const xds_type_matcher_v3_ServerNameMatcher_DomainMatcher* msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 16), const struct xds_type_matcher_v3_Matcher_OnMatch*); } UPB_INLINE upb_StringView* xds_type_matcher_v3_ServerNameMatcher_DomainMatcher_mutable_domains(xds_type_matcher_v3_ServerNameMatcher_DomainMatcher* msg, size_t* len) { return (upb_StringView*)_upb_array_mutable_accessor(msg, UPB_SIZE(4, 8), len); } UPB_INLINE upb_StringView* xds_type_matcher_v3_ServerNameMatcher_DomainMatcher_resize_domains(xds_type_matcher_v3_ServerNameMatcher_DomainMatcher* msg, size_t len, upb_Arena* arena) { return (upb_StringView*)_upb_Array_Resize_accessor2(msg, UPB_SIZE(4, 8), len, UPB_SIZE(3, 4), arena); } UPB_INLINE bool xds_type_matcher_v3_ServerNameMatcher_DomainMatcher_add_domains(xds_type_matcher_v3_ServerNameMatcher_DomainMatcher* msg, upb_StringView val, upb_Arena* arena) { return _upb_Array_Append_accessor2(msg, UPB_SIZE(4, 8), UPB_SIZE(3, 4), &val, arena); } UPB_INLINE void xds_type_matcher_v3_ServerNameMatcher_DomainMatcher_set_on_match(xds_type_matcher_v3_ServerNameMatcher_DomainMatcher *msg, struct xds_type_matcher_v3_Matcher_OnMatch* value) { _upb_sethas(msg, 1); *UPB_PTR_AT(msg, UPB_SIZE(8, 16), struct xds_type_matcher_v3_Matcher_OnMatch*) = value; } UPB_INLINE struct xds_type_matcher_v3_Matcher_OnMatch* xds_type_matcher_v3_ServerNameMatcher_DomainMatcher_mutable_on_match(xds_type_matcher_v3_ServerNameMatcher_DomainMatcher* msg, upb_Arena* arena) { struct xds_type_matcher_v3_Matcher_OnMatch* sub = (struct xds_type_matcher_v3_Matcher_OnMatch*)xds_type_matcher_v3_ServerNameMatcher_DomainMatcher_on_match(msg); if (sub == NULL) { sub = (struct xds_type_matcher_v3_Matcher_OnMatch*)_upb_Message_New(&xds_type_matcher_v3_Matcher_OnMatch_msginit, arena); if (!sub) return NULL; xds_type_matcher_v3_ServerNameMatcher_DomainMatcher_set_on_match(msg, sub); } return sub; } extern const upb_MiniTable_File xds_type_matcher_v3_domain_proto_upb_file_layout; #ifdef __cplusplus } /* extern "C" */ #endif #include "upb/port_undef.inc" #endif /* XDS_TYPE_MATCHER_V3_DOMAIN_PROTO_UPB_H_ */
60038c5e6cc2ea380691fecbb39f48ad56d262e6
2e33733495155d73e4ce3611b768141358fad99f
/test/unit/src/test-reader.h
0a3f5962a3ac920c678829d3020fced179ebf529
[ "MIT", "GPL-1.0-or-later", "LicenseRef-scancode-unknown-license-reference" ]
permissive
ludocode/mpack
982b98228adaa95b9e342788d42a46311c18d0fd
111b292716679c9f1b5b08db246c2760f6211ceb
refs/heads/develop
2023-06-21T13:22:48.432194
2023-04-18T22:07:33
2023-04-18T22:07:33
31,540,903
510
93
MIT
2023-01-08T23:13:37
2015-03-02T13:14:49
C
UTF-8
C
false
false
5,680
h
test-reader.h
/* * Copyright (c) 2015-2021 Nicholas Fraser and the MPack authors * * 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 MPACK_TEST_READER_H #define MPACK_TEST_READER_H 1 #include "test.h" #ifdef __cplusplus extern "C" { #endif #if MPACK_READER extern mpack_error_t test_read_error; void test_read_error_handler(mpack_reader_t* reader, mpack_error_t error); // these setup and destroy test readers and check them for errors. // they are generally macros so that the checks are on the line of the test. // destroy wrappers expecting error or no error // tears down a reader, ensuring it has no errors and no extra data #define TEST_READER_DESTROY_NOERROR(reader) do { \ size_t remaining = mpack_reader_remaining(reader, NULL); \ mpack_error_t error = mpack_reader_destroy(reader); \ TEST_TRUE(error == mpack_ok, "reader is in error state %i (%s)", \ (int)error, mpack_error_to_string(error)); \ TEST_TRUE(remaining == 0, \ "reader has %i extra bytes", (int)remaining); \ } while (0) // tears down a reader, ensuring it is in the given error state #define TEST_READER_DESTROY_ERROR(reader, error) do { \ mpack_error_t expected = (error); \ mpack_error_t actual = mpack_reader_destroy(reader); \ TEST_TRUE(actual == expected, "reader is in error state %i (%s) instead of %i (%s)", \ (int)actual, mpack_error_to_string(actual), \ (int)expected, mpack_error_to_string(expected)); \ } while (0) // reader helpers // performs an operation on a reader, ensuring no error occurs #define TEST_READ_NOERROR(reader, read_expr) do { \ TEST_TRUE((read_expr), "read did not pass: " #read_expr); \ TEST_TRUE(mpack_reader_error(reader) == mpack_ok, \ "reader flagged error %i", (int)mpack_reader_error(reader)); \ } while (0) // simple read tests // initializes a reader from a literal string #define TEST_READER_INIT_STR(reader, data) \ mpack_reader_init_data(reader, data, sizeof(data) - 1) // runs a simple reader test, ensuring the expression is true and no errors occur #define TEST_SIMPLE_READ(data, read_expr) do { \ TEST_READER_INIT_STR(&reader, data); \ mpack_reader_set_error_handler(&reader, test_read_error_handler); \ TEST_TRUE((read_expr), "simple read test did not pass: " #read_expr); \ TEST_READER_DESTROY_NOERROR(&reader); \ TEST_TRUE(test_read_error == mpack_ok); \ test_read_error = mpack_ok; \ } while (0) // runs a simple reader test, ensuring the expression is true and no errors occur, cancelling to ignore tracking info #define TEST_SIMPLE_READ_CANCEL(data, read_expr) do { \ TEST_READER_INIT_STR(&reader, data); \ TEST_TRUE((read_expr), "simple read test did not pass: " #read_expr); \ mpack_reader_flag_error(&reader, mpack_error_data); \ TEST_READER_DESTROY_ERROR(&reader, mpack_error_data); \ } while (0) // runs a simple reader test, ensuring the expression is true and the given error is raised #define TEST_SIMPLE_READ_ERROR(data, read_expr, error) do { \ TEST_READER_INIT_STR(&reader, data); \ mpack_reader_set_error_handler(&reader, test_read_error_handler); \ TEST_TRUE((read_expr), "simple read error test did not pass: " #read_expr); \ TEST_READER_DESTROY_ERROR(&reader, (error)); \ TEST_TRUE(test_read_error == (error)); \ test_read_error = mpack_ok; \ } while (0) // simple read bug tests #if MPACK_DEBUG // runs a simple reader test, ensuring it causes an assert. // we flag mpack_error_data to cancel out of any tracking. // (note about volatile, see TEST_ASSERT()) #define TEST_SIMPLE_READ_ASSERT(data, read_expr) do { \ volatile mpack_reader_t v_reader; \ TEST_MPACK_SILENCE_SHADOW_BEGIN \ mpack_reader_t* reader = (mpack_reader_t*)(uintptr_t)&v_reader; \ TEST_MPACK_SILENCE_SHADOW_END \ mpack_reader_init_data(reader, data, sizeof(data) - 1); \ TEST_ASSERT(read_expr); \ mpack_reader_flag_error(reader, mpack_error_data); \ mpack_reader_destroy(reader); \ } while (0) #else // we cannot test asserts in release mode because they are // compiled away; code would continue to run and cause // undefined behavior. #define TEST_SIMPLE_READ_ASSERT(data, read_expr) ((void)0) #endif // runs a simple reader test, ensuring it causes a break in // debug mode and flags mpack_error_bug in both debug and release. #define TEST_SIMPLE_READ_BREAK(data, read_expr) do { \ mpack_reader_init_data(&reader, data, sizeof(data) - 1); \ TEST_BREAK(read_expr); \ TEST_READER_DESTROY_ERROR(&reader, mpack_error_bug); \ } while (0) void test_reader(void); #endif #ifdef __cplusplus } #endif #endif
0b863263ece61a6596849a6f2edaccdaf25734a5
55540f3e86f1d5d86ef6b5d295a63518e274efe3
/components/platform/soc/bl602/bl602_std/bl602_std/Common/libc/src/strtoimax.c
ba4bd1e6ff406ef144790b30b1d01fb99d8bff3c
[ "GPL-1.0-or-later", "LicenseRef-scancode-unknown", "BSD-4-Clause-UC", "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
bouffalolab/bl_iot_sdk
bc5eaf036b70f8c65dd389439062b169f8d09daa
b90664de0bd4c1897a9f1f5d9e360a9631d38b34
refs/heads/master
2023-08-31T03:38:03.369853
2023-08-16T08:50:33
2023-08-18T09:13:27
307,347,250
244
101
Apache-2.0
2023-08-28T06:29:02
2020-10-26T11:16:30
C
UTF-8
C
false
false
136
c
strtoimax.c
/* * Derived from: * http://www.kernel.org/pub/linux/libs/klibc/ */ #define TYPE intmax_t #define NAME strtoimax #include "strtox.c"
7e2960cc5096ffbcf18685bd87a71251fee99e1e
d4166e3dbfed91f40a1fef9e87c2f38461d00c79
/log.c
cb460396655b15848ad8f7bb9ad3c0e38b8c42dd
[ "MIT" ]
permissive
swaywm/swaylock
d64e5cb63923f389eb1ea15a64c9097f5a8ef772
10df946671a12b4c0f4c13d4556a8bae6fc30394
refs/heads/master
2023-09-05T04:53:00.808818
2023-08-06T17:13:07
2023-08-06T19:27:54
165,581,769
680
146
MIT
2023-09-02T12:49:54
2019-01-14T02:25:09
C
UTF-8
C
false
false
1,434
c
log.c
#define _POSIX_C_SOURCE 199506L #include <errno.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #include "log.h" static enum log_importance log_importance = LOG_ERROR; static const char *verbosity_colors[] = { [LOG_SILENT] = "", [LOG_ERROR ] = "\x1B[1;31m", [LOG_INFO ] = "\x1B[1;34m", [LOG_DEBUG ] = "\x1B[1;30m", }; void swaylock_log_init(enum log_importance verbosity) { if (verbosity < LOG_IMPORTANCE_LAST) { log_importance = verbosity; } } void _swaylock_log(enum log_importance verbosity, const char *fmt, ...) { if (verbosity > log_importance) { return; } va_list args; va_start(args, fmt); // prefix the time to the log message struct tm result; time_t t = time(NULL); struct tm *tm_info = localtime_r(&t, &result); char buffer[26]; // generate time prefix strftime(buffer, sizeof(buffer), "%F %T - ", tm_info); fprintf(stderr, "%s", buffer); unsigned c = (verbosity < LOG_IMPORTANCE_LAST) ? verbosity : LOG_IMPORTANCE_LAST - 1; if (isatty(STDERR_FILENO)) { fprintf(stderr, "%s", verbosity_colors[c]); } vfprintf(stderr, fmt, args); if (isatty(STDERR_FILENO)) { fprintf(stderr, "\x1B[0m"); } fprintf(stderr, "\n"); va_end(args); } const char *_swaylock_strip_path(const char *filepath) { if (*filepath == '.') { while (*filepath == '.' || *filepath == '/') { ++filepath; } } return filepath; }
0e1edd5c8679a74e3120f37fdbf7873daf6e8e8c
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/net/sctp/input.c
bd4fb459c63b3c2e48b676d713cbd3732c6ca86c
[ "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
32,237
c
input.c
/* SCTP kernel implementation * Copyright (c) 1999-2000 Cisco, Inc. * Copyright (c) 1999-2001 Motorola, Inc. * Copyright (c) 2001-2003 International Business Machines, Corp. * Copyright (c) 2001 Intel Corp. * Copyright (c) 2001 Nokia, Inc. * Copyright (c) 2001 La Monte H.P. Yarroll * * This file is part of the SCTP kernel implementation * * These functions handle all input from the IP layer into SCTP. * * This SCTP implementation is free software; * you can redistribute it and/or modify it under the terms of * the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This SCTP implementation 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 GNU CC; see the file COPYING. If not, write to * the Free Software Foundation, 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * Please send any bug reports or fixes you make to the * email address(es): * lksctp developers <lksctp-developers@lists.sourceforge.net> * * Or submit a bug report through the following website: * http://www.sf.net/projects/lksctp * * Written or modified by: * La Monte H.P. Yarroll <piggy@acm.org> * Karl Knutson <karl@athena.chicago.il.us> * Xingang Guo <xingang.guo@intel.com> * Jon Grimm <jgrimm@us.ibm.com> * Hui Huang <hui.huang@nokia.com> * Daisy Chang <daisyc@us.ibm.com> * Sridhar Samudrala <sri@us.ibm.com> * Ardelle Fan <ardelle.fan@intel.com> * * Any bugs reported given to us we will try to fix... any fixes shared will * be incorporated into the next SCTP release. */ #include <linux/types.h> #include <linux/list.h> /* For struct list_head */ #include <linux/socket.h> #include <linux/ip.h> #include <linux/time.h> /* For struct timeval */ #include <linux/slab.h> #include <net/ip.h> #include <net/icmp.h> #include <net/snmp.h> #include <net/sock.h> #include <net/xfrm.h> #include <net/sctp/sctp.h> #include <net/sctp/sm.h> #include <net/sctp/checksum.h> #include <net/net_namespace.h> /* Forward declarations for internal helpers. */ static int sctp_rcv_ootb(struct sk_buff *); static struct sctp_association *__sctp_rcv_lookup(struct net *net, struct sk_buff *skb, const union sctp_addr *paddr, const union sctp_addr *laddr, struct sctp_transport **transportp); static struct sctp_endpoint *__sctp_rcv_lookup_endpoint(struct net *net, const union sctp_addr *laddr); static struct sctp_association *__sctp_lookup_association( struct net *net, const union sctp_addr *local, const union sctp_addr *peer, struct sctp_transport **pt); static int sctp_add_backlog(struct sock *sk, struct sk_buff *skb); /* Calculate the SCTP checksum of an SCTP packet. */ static inline int sctp_rcv_checksum(struct net *net, struct sk_buff *skb) { struct sctphdr *sh = sctp_hdr(skb); __le32 cmp = sh->checksum; struct sk_buff *list; __le32 val; __u32 tmp = sctp_start_cksum((__u8 *)sh, skb_headlen(skb)); skb_walk_frags(skb, list) tmp = sctp_update_cksum((__u8 *)list->data, skb_headlen(list), tmp); val = sctp_end_cksum(tmp); if (val != cmp) { /* CRC failure, dump it. */ SCTP_INC_STATS_BH(net, SCTP_MIB_CHECKSUMERRORS); return -1; } return 0; } struct sctp_input_cb { union { struct inet_skb_parm h4; #if IS_ENABLED(CONFIG_IPV6) struct inet6_skb_parm h6; #endif } header; struct sctp_chunk *chunk; }; #define SCTP_INPUT_CB(__skb) ((struct sctp_input_cb *)&((__skb)->cb[0])) /* * This is the routine which IP calls when receiving an SCTP packet. */ int sctp_rcv(struct sk_buff *skb) { struct sock *sk; struct sctp_association *asoc; struct sctp_endpoint *ep = NULL; struct sctp_ep_common *rcvr; struct sctp_transport *transport = NULL; struct sctp_chunk *chunk; struct sctphdr *sh; union sctp_addr src; union sctp_addr dest; int family; struct sctp_af *af; struct net *net = dev_net(skb->dev); if (skb->pkt_type!=PACKET_HOST) goto discard_it; SCTP_INC_STATS_BH(net, SCTP_MIB_INSCTPPACKS); if (skb_linearize(skb)) goto discard_it; sh = sctp_hdr(skb); /* Pull up the IP and SCTP headers. */ __skb_pull(skb, skb_transport_offset(skb)); if (skb->len < sizeof(struct sctphdr)) goto discard_it; if (!sctp_checksum_disable && !skb_csum_unnecessary(skb) && sctp_rcv_checksum(net, skb) < 0) goto discard_it; skb_pull(skb, sizeof(struct sctphdr)); /* Make sure we at least have chunk headers worth of data left. */ if (skb->len < sizeof(struct sctp_chunkhdr)) goto discard_it; family = ipver2af(ip_hdr(skb)->version); af = sctp_get_af_specific(family); if (unlikely(!af)) goto discard_it; /* Initialize local addresses for lookups. */ af->from_skb(&src, skb, 1); af->from_skb(&dest, skb, 0); /* If the packet is to or from a non-unicast address, * silently discard the packet. * * This is not clearly defined in the RFC except in section * 8.4 - OOTB handling. However, based on the book "Stream Control * Transmission Protocol" 2.1, "It is important to note that the * IP address of an SCTP transport address must be a routable * unicast address. In other words, IP multicast addresses and * IP broadcast addresses cannot be used in an SCTP transport * address." */ if (!af->addr_valid(&src, NULL, skb) || !af->addr_valid(&dest, NULL, skb)) goto discard_it; asoc = __sctp_rcv_lookup(net, skb, &src, &dest, &transport); if (!asoc) ep = __sctp_rcv_lookup_endpoint(net, &dest); /* Retrieve the common input handling substructure. */ rcvr = asoc ? &asoc->base : &ep->base; sk = rcvr->sk; /* * If a frame arrives on an interface and the receiving socket is * bound to another interface, via SO_BINDTODEVICE, treat it as OOTB */ if (sk->sk_bound_dev_if && (sk->sk_bound_dev_if != af->skb_iif(skb))) { if (asoc) { sctp_association_put(asoc); asoc = NULL; } else { sctp_endpoint_put(ep); ep = NULL; } sk = net->sctp.ctl_sock; ep = sctp_sk(sk)->ep; sctp_endpoint_hold(ep); rcvr = &ep->base; } /* * RFC 2960, 8.4 - Handle "Out of the blue" Packets. * An SCTP packet is called an "out of the blue" (OOTB) * packet if it is correctly formed, i.e., passed the * receiver's checksum check, but the receiver is not * able to identify the association to which this * packet belongs. */ if (!asoc) { if (sctp_rcv_ootb(skb)) { SCTP_INC_STATS_BH(net, SCTP_MIB_OUTOFBLUES); goto discard_release; } } if (!xfrm_policy_check(sk, XFRM_POLICY_IN, skb, family)) goto discard_release; nf_reset(skb); if (sk_filter(sk, skb)) goto discard_release; /* Create an SCTP packet structure. */ chunk = sctp_chunkify(skb, asoc, sk); if (!chunk) goto discard_release; SCTP_INPUT_CB(skb)->chunk = chunk; /* Remember what endpoint is to handle this packet. */ chunk->rcvr = rcvr; /* Remember the SCTP header. */ chunk->sctp_hdr = sh; /* Set the source and destination addresses of the incoming chunk. */ sctp_init_addrs(chunk, &src, &dest); /* Remember where we came from. */ chunk->transport = transport; /* Acquire access to the sock lock. Note: We are safe from other * bottom halves on this lock, but a user may be in the lock too, * so check if it is busy. */ sctp_bh_lock_sock(sk); if (sk != rcvr->sk) { /* Our cached sk is different from the rcvr->sk. This is * because migrate()/accept() may have moved the association * to a new socket and released all the sockets. So now we * are holding a lock on the old socket while the user may * be doing something with the new socket. Switch our veiw * of the current sk. */ sctp_bh_unlock_sock(sk); sk = rcvr->sk; sctp_bh_lock_sock(sk); } if (sock_owned_by_user(sk)) { if (sctp_add_backlog(sk, skb)) { sctp_bh_unlock_sock(sk); sctp_chunk_free(chunk); skb = NULL; /* sctp_chunk_free already freed the skb */ goto discard_release; } SCTP_INC_STATS_BH(net, SCTP_MIB_IN_PKT_BACKLOG); } else { SCTP_INC_STATS_BH(net, SCTP_MIB_IN_PKT_SOFTIRQ); sctp_inq_push(&chunk->rcvr->inqueue, chunk); } sctp_bh_unlock_sock(sk); /* Release the asoc/ep ref we took in the lookup calls. */ if (asoc) sctp_association_put(asoc); else sctp_endpoint_put(ep); return 0; discard_it: SCTP_INC_STATS_BH(net, SCTP_MIB_IN_PKT_DISCARDS); kfree_skb(skb); return 0; discard_release: /* Release the asoc/ep ref we took in the lookup calls. */ if (asoc) sctp_association_put(asoc); else sctp_endpoint_put(ep); goto discard_it; } /* Process the backlog queue of the socket. Every skb on * the backlog holds a ref on an association or endpoint. * We hold this ref throughout the state machine to make * sure that the structure we need is still around. */ int sctp_backlog_rcv(struct sock *sk, struct sk_buff *skb) { struct sctp_chunk *chunk = SCTP_INPUT_CB(skb)->chunk; struct sctp_inq *inqueue = &chunk->rcvr->inqueue; struct sctp_ep_common *rcvr = NULL; int backloged = 0; rcvr = chunk->rcvr; /* If the rcvr is dead then the association or endpoint * has been deleted and we can safely drop the chunk * and refs that we are holding. */ if (rcvr->dead) { sctp_chunk_free(chunk); goto done; } if (unlikely(rcvr->sk != sk)) { /* In this case, the association moved from one socket to * another. We are currently sitting on the backlog of the * old socket, so we need to move. * However, since we are here in the process context we * need to take make sure that the user doesn't own * the new socket when we process the packet. * If the new socket is user-owned, queue the chunk to the * backlog of the new socket without dropping any refs. * Otherwise, we can safely push the chunk on the inqueue. */ sk = rcvr->sk; sctp_bh_lock_sock(sk); if (sock_owned_by_user(sk)) { if (sk_add_backlog(sk, skb, sk->sk_rcvbuf)) sctp_chunk_free(chunk); else backloged = 1; } else sctp_inq_push(inqueue, chunk); sctp_bh_unlock_sock(sk); /* If the chunk was backloged again, don't drop refs */ if (backloged) return 0; } else { sctp_inq_push(inqueue, chunk); } done: /* Release the refs we took in sctp_add_backlog */ if (SCTP_EP_TYPE_ASSOCIATION == rcvr->type) sctp_association_put(sctp_assoc(rcvr)); else if (SCTP_EP_TYPE_SOCKET == rcvr->type) sctp_endpoint_put(sctp_ep(rcvr)); else BUG(); return 0; } static int sctp_add_backlog(struct sock *sk, struct sk_buff *skb) { struct sctp_chunk *chunk = SCTP_INPUT_CB(skb)->chunk; struct sctp_ep_common *rcvr = chunk->rcvr; int ret; ret = sk_add_backlog(sk, skb, sk->sk_rcvbuf); if (!ret) { /* Hold the assoc/ep while hanging on the backlog queue. * This way, we know structures we need will not disappear * from us */ if (SCTP_EP_TYPE_ASSOCIATION == rcvr->type) sctp_association_hold(sctp_assoc(rcvr)); else if (SCTP_EP_TYPE_SOCKET == rcvr->type) sctp_endpoint_hold(sctp_ep(rcvr)); else BUG(); } return ret; } /* Handle icmp frag needed error. */ void sctp_icmp_frag_needed(struct sock *sk, struct sctp_association *asoc, struct sctp_transport *t, __u32 pmtu) { if (!t || (t->pathmtu <= pmtu)) return; if (sock_owned_by_user(sk)) { asoc->pmtu_pending = 1; t->pmtu_pending = 1; return; } if (t->param_flags & SPP_PMTUD_ENABLE) { /* Update transports view of the MTU */ sctp_transport_update_pmtu(sk, t, pmtu); /* Update association pmtu. */ sctp_assoc_sync_pmtu(sk, asoc); } /* Retransmit with the new pmtu setting. * Normally, if PMTU discovery is disabled, an ICMP Fragmentation * Needed will never be sent, but if a message was sent before * PMTU discovery was disabled that was larger than the PMTU, it * would not be fragmented, so it must be re-transmitted fragmented. */ sctp_retransmit(&asoc->outqueue, t, SCTP_RTXR_PMTUD); } void sctp_icmp_redirect(struct sock *sk, struct sctp_transport *t, struct sk_buff *skb) { struct dst_entry *dst; if (!t) return; dst = sctp_transport_dst_check(t); if (dst) dst->ops->redirect(dst, sk, skb); } /* * SCTP Implementer's Guide, 2.37 ICMP handling procedures * * ICMP8) If the ICMP code is a "Unrecognized next header type encountered" * or a "Protocol Unreachable" treat this message as an abort * with the T bit set. * * This function sends an event to the state machine, which will abort the * association. * */ void sctp_icmp_proto_unreachable(struct sock *sk, struct sctp_association *asoc, struct sctp_transport *t) { SCTP_DEBUG_PRINTK("%s\n", __func__); if (sock_owned_by_user(sk)) { if (timer_pending(&t->proto_unreach_timer)) return; else { if (!mod_timer(&t->proto_unreach_timer, jiffies + (HZ/20))) sctp_association_hold(asoc); } } else { struct net *net = sock_net(sk); if (del_timer(&t->proto_unreach_timer)) sctp_association_put(asoc); sctp_do_sm(net, SCTP_EVENT_T_OTHER, SCTP_ST_OTHER(SCTP_EVENT_ICMP_PROTO_UNREACH), asoc->state, asoc->ep, asoc, t, GFP_ATOMIC); } } /* Common lookup code for icmp/icmpv6 error handler. */ struct sock *sctp_err_lookup(struct net *net, int family, struct sk_buff *skb, struct sctphdr *sctphdr, struct sctp_association **app, struct sctp_transport **tpp) { union sctp_addr saddr; union sctp_addr daddr; struct sctp_af *af; struct sock *sk = NULL; struct sctp_association *asoc; struct sctp_transport *transport = NULL; struct sctp_init_chunk *chunkhdr; __u32 vtag = ntohl(sctphdr->vtag); int len = skb->len - ((void *)sctphdr - (void *)skb->data); *app = NULL; *tpp = NULL; af = sctp_get_af_specific(family); if (unlikely(!af)) { return NULL; } /* Initialize local addresses for lookups. */ af->from_skb(&saddr, skb, 1); af->from_skb(&daddr, skb, 0); /* Look for an association that matches the incoming ICMP error * packet. */ asoc = __sctp_lookup_association(net, &saddr, &daddr, &transport); if (!asoc) return NULL; sk = asoc->base.sk; /* RFC 4960, Appendix C. ICMP Handling * * ICMP6) An implementation MUST validate that the Verification Tag * contained in the ICMP message matches the Verification Tag of * the peer. If the Verification Tag is not 0 and does NOT * match, discard the ICMP message. If it is 0 and the ICMP * message contains enough bytes to verify that the chunk type is * an INIT chunk and that the Initiate Tag matches the tag of the * peer, continue with ICMP7. If the ICMP message is too short * or the chunk type or the Initiate Tag does not match, silently * discard the packet. */ if (vtag == 0) { chunkhdr = (void *)sctphdr + sizeof(struct sctphdr); if (len < sizeof(struct sctphdr) + sizeof(sctp_chunkhdr_t) + sizeof(__be32) || chunkhdr->chunk_hdr.type != SCTP_CID_INIT || ntohl(chunkhdr->init_hdr.init_tag) != asoc->c.my_vtag) { goto out; } } else if (vtag != asoc->c.peer_vtag) { goto out; } sctp_bh_lock_sock(sk); /* If too many ICMPs get dropped on busy * servers this needs to be solved differently. */ if (sock_owned_by_user(sk)) NET_INC_STATS_BH(net, LINUX_MIB_LOCKDROPPEDICMPS); *app = asoc; *tpp = transport; return sk; out: if (asoc) sctp_association_put(asoc); return NULL; } /* Common cleanup code for icmp/icmpv6 error handler. */ void sctp_err_finish(struct sock *sk, struct sctp_association *asoc) { sctp_bh_unlock_sock(sk); if (asoc) sctp_association_put(asoc); } /* * This routine is called by the ICMP module when it gets some * sort of error condition. If err < 0 then the socket should * be closed and the error returned to the user. If err > 0 * it's just the icmp type << 8 | icmp code. After adjustment * header points to the first 8 bytes of the sctp header. We need * to find the appropriate port. * * The locking strategy used here is very "optimistic". When * someone else accesses the socket the ICMP is just dropped * and for some paths there is no check at all. * A more general error queue to queue errors for later handling * is probably better. * */ void sctp_v4_err(struct sk_buff *skb, __u32 info) { const struct iphdr *iph = (const struct iphdr *)skb->data; const int ihlen = iph->ihl * 4; const int type = icmp_hdr(skb)->type; const int code = icmp_hdr(skb)->code; struct sock *sk; struct sctp_association *asoc = NULL; struct sctp_transport *transport; struct inet_sock *inet; sk_buff_data_t saveip, savesctp; int err; struct net *net = dev_net(skb->dev); if (skb->len < ihlen + 8) { ICMP_INC_STATS_BH(net, ICMP_MIB_INERRORS); return; } /* Fix up skb to look at the embedded net header. */ saveip = skb->network_header; savesctp = skb->transport_header; skb_reset_network_header(skb); skb_set_transport_header(skb, ihlen); sk = sctp_err_lookup(net, AF_INET, skb, sctp_hdr(skb), &asoc, &transport); /* Put back, the original values. */ skb->network_header = saveip; skb->transport_header = savesctp; if (!sk) { ICMP_INC_STATS_BH(net, ICMP_MIB_INERRORS); return; } /* Warning: The sock lock is held. Remember to call * sctp_err_finish! */ switch (type) { case ICMP_PARAMETERPROB: err = EPROTO; break; case ICMP_DEST_UNREACH: if (code > NR_ICMP_UNREACH) goto out_unlock; /* PMTU discovery (RFC1191) */ if (ICMP_FRAG_NEEDED == code) { sctp_icmp_frag_needed(sk, asoc, transport, info); goto out_unlock; } else { if (ICMP_PROT_UNREACH == code) { sctp_icmp_proto_unreachable(sk, asoc, transport); goto out_unlock; } } err = icmp_err_convert[code].errno; break; case ICMP_TIME_EXCEEDED: /* Ignore any time exceeded errors due to fragment reassembly * timeouts. */ if (ICMP_EXC_FRAGTIME == code) goto out_unlock; err = EHOSTUNREACH; break; case ICMP_REDIRECT: sctp_icmp_redirect(sk, transport, skb); /* Fall through to out_unlock. */ default: goto out_unlock; } inet = inet_sk(sk); if (!sock_owned_by_user(sk) && inet->recverr) { sk->sk_err = err; sk->sk_error_report(sk); } else { /* Only an error on timeout */ sk->sk_err_soft = err; } out_unlock: sctp_err_finish(sk, asoc); } /* * RFC 2960, 8.4 - Handle "Out of the blue" Packets. * * This function scans all the chunks in the OOTB packet to determine if * the packet should be discarded right away. If a response might be needed * for this packet, or, if further processing is possible, the packet will * be queued to a proper inqueue for the next phase of handling. * * Output: * Return 0 - If further processing is needed. * Return 1 - If the packet can be discarded right away. */ static int sctp_rcv_ootb(struct sk_buff *skb) { sctp_chunkhdr_t *ch; __u8 *ch_end; ch = (sctp_chunkhdr_t *) skb->data; /* Scan through all the chunks in the packet. */ do { /* Break out if chunk length is less then minimal. */ if (ntohs(ch->length) < sizeof(sctp_chunkhdr_t)) break; ch_end = ((__u8 *)ch) + WORD_ROUND(ntohs(ch->length)); if (ch_end > skb_tail_pointer(skb)) break; /* RFC 8.4, 2) If the OOTB packet contains an ABORT chunk, the * receiver MUST silently discard the OOTB packet and take no * further action. */ if (SCTP_CID_ABORT == ch->type) goto discard; /* RFC 8.4, 6) If the packet contains a SHUTDOWN COMPLETE * chunk, the receiver should silently discard the packet * and take no further action. */ if (SCTP_CID_SHUTDOWN_COMPLETE == ch->type) goto discard; /* RFC 4460, 2.11.2 * This will discard packets with INIT chunk bundled as * subsequent chunks in the packet. When INIT is first, * the normal INIT processing will discard the chunk. */ if (SCTP_CID_INIT == ch->type && (void *)ch != skb->data) goto discard; ch = (sctp_chunkhdr_t *) ch_end; } while (ch_end < skb_tail_pointer(skb)); return 0; discard: return 1; } /* Insert endpoint into the hash table. */ static void __sctp_hash_endpoint(struct sctp_endpoint *ep) { struct net *net = sock_net(ep->base.sk); struct sctp_ep_common *epb; struct sctp_hashbucket *head; epb = &ep->base; epb->hashent = sctp_ep_hashfn(net, epb->bind_addr.port); head = &sctp_ep_hashtable[epb->hashent]; sctp_write_lock(&head->lock); hlist_add_head(&epb->node, &head->chain); sctp_write_unlock(&head->lock); } /* Add an endpoint to the hash. Local BH-safe. */ void sctp_hash_endpoint(struct sctp_endpoint *ep) { sctp_local_bh_disable(); __sctp_hash_endpoint(ep); sctp_local_bh_enable(); } /* Remove endpoint from the hash table. */ static void __sctp_unhash_endpoint(struct sctp_endpoint *ep) { struct net *net = sock_net(ep->base.sk); struct sctp_hashbucket *head; struct sctp_ep_common *epb; epb = &ep->base; epb->hashent = sctp_ep_hashfn(net, epb->bind_addr.port); head = &sctp_ep_hashtable[epb->hashent]; sctp_write_lock(&head->lock); hlist_del_init(&epb->node); sctp_write_unlock(&head->lock); } /* Remove endpoint from the hash. Local BH-safe. */ void sctp_unhash_endpoint(struct sctp_endpoint *ep) { sctp_local_bh_disable(); __sctp_unhash_endpoint(ep); sctp_local_bh_enable(); } /* Look up an endpoint. */ static struct sctp_endpoint *__sctp_rcv_lookup_endpoint(struct net *net, const union sctp_addr *laddr) { struct sctp_hashbucket *head; struct sctp_ep_common *epb; struct sctp_endpoint *ep; int hash; hash = sctp_ep_hashfn(net, ntohs(laddr->v4.sin_port)); head = &sctp_ep_hashtable[hash]; read_lock(&head->lock); sctp_for_each_hentry(epb, &head->chain) { ep = sctp_ep(epb); if (sctp_endpoint_is_match(ep, net, laddr)) goto hit; } ep = sctp_sk(net->sctp.ctl_sock)->ep; hit: sctp_endpoint_hold(ep); read_unlock(&head->lock); return ep; } /* Insert association into the hash table. */ static void __sctp_hash_established(struct sctp_association *asoc) { struct net *net = sock_net(asoc->base.sk); struct sctp_ep_common *epb; struct sctp_hashbucket *head; epb = &asoc->base; /* Calculate which chain this entry will belong to. */ epb->hashent = sctp_assoc_hashfn(net, epb->bind_addr.port, asoc->peer.port); head = &sctp_assoc_hashtable[epb->hashent]; sctp_write_lock(&head->lock); hlist_add_head(&epb->node, &head->chain); sctp_write_unlock(&head->lock); } /* Add an association to the hash. Local BH-safe. */ void sctp_hash_established(struct sctp_association *asoc) { if (asoc->temp) return; sctp_local_bh_disable(); __sctp_hash_established(asoc); sctp_local_bh_enable(); } /* Remove association from the hash table. */ static void __sctp_unhash_established(struct sctp_association *asoc) { struct net *net = sock_net(asoc->base.sk); struct sctp_hashbucket *head; struct sctp_ep_common *epb; epb = &asoc->base; epb->hashent = sctp_assoc_hashfn(net, epb->bind_addr.port, asoc->peer.port); head = &sctp_assoc_hashtable[epb->hashent]; sctp_write_lock(&head->lock); hlist_del_init(&epb->node); sctp_write_unlock(&head->lock); } /* Remove association from the hash table. Local BH-safe. */ void sctp_unhash_established(struct sctp_association *asoc) { if (asoc->temp) return; sctp_local_bh_disable(); __sctp_unhash_established(asoc); sctp_local_bh_enable(); } /* Look up an association. */ static struct sctp_association *__sctp_lookup_association( struct net *net, const union sctp_addr *local, const union sctp_addr *peer, struct sctp_transport **pt) { struct sctp_hashbucket *head; struct sctp_ep_common *epb; struct sctp_association *asoc; struct sctp_transport *transport; int hash; /* Optimize here for direct hit, only listening connections can * have wildcards anyways. */ hash = sctp_assoc_hashfn(net, ntohs(local->v4.sin_port), ntohs(peer->v4.sin_port)); head = &sctp_assoc_hashtable[hash]; read_lock(&head->lock); sctp_for_each_hentry(epb, &head->chain) { asoc = sctp_assoc(epb); transport = sctp_assoc_is_match(asoc, net, local, peer); if (transport) goto hit; } read_unlock(&head->lock); return NULL; hit: *pt = transport; sctp_association_hold(asoc); read_unlock(&head->lock); return asoc; } /* Look up an association. BH-safe. */ SCTP_STATIC struct sctp_association *sctp_lookup_association(struct net *net, const union sctp_addr *laddr, const union sctp_addr *paddr, struct sctp_transport **transportp) { struct sctp_association *asoc; sctp_local_bh_disable(); asoc = __sctp_lookup_association(net, laddr, paddr, transportp); sctp_local_bh_enable(); return asoc; } /* Is there an association matching the given local and peer addresses? */ int sctp_has_association(struct net *net, const union sctp_addr *laddr, const union sctp_addr *paddr) { struct sctp_association *asoc; struct sctp_transport *transport; if ((asoc = sctp_lookup_association(net, laddr, paddr, &transport))) { sctp_association_put(asoc); return 1; } return 0; } /* * SCTP Implementors Guide, 2.18 Handling of address * parameters within the INIT or INIT-ACK. * * D) When searching for a matching TCB upon reception of an INIT * or INIT-ACK chunk the receiver SHOULD use not only the * source address of the packet (containing the INIT or * INIT-ACK) but the receiver SHOULD also use all valid * address parameters contained within the chunk. * * 2.18.3 Solution description * * This new text clearly specifies to an implementor the need * to look within the INIT or INIT-ACK. Any implementation that * does not do this, may not be able to establish associations * in certain circumstances. * */ static struct sctp_association *__sctp_rcv_init_lookup(struct net *net, struct sk_buff *skb, const union sctp_addr *laddr, struct sctp_transport **transportp) { struct sctp_association *asoc; union sctp_addr addr; union sctp_addr *paddr = &addr; struct sctphdr *sh = sctp_hdr(skb); union sctp_params params; sctp_init_chunk_t *init; struct sctp_transport *transport; struct sctp_af *af; /* * This code will NOT touch anything inside the chunk--it is * strictly READ-ONLY. * * RFC 2960 3 SCTP packet Format * * Multiple chunks can be bundled into one SCTP packet up to * the MTU size, except for the INIT, INIT ACK, and SHUTDOWN * COMPLETE chunks. These chunks MUST NOT be bundled with any * other chunk in a packet. See Section 6.10 for more details * on chunk bundling. */ /* Find the start of the TLVs and the end of the chunk. This is * the region we search for address parameters. */ init = (sctp_init_chunk_t *)skb->data; /* Walk the parameters looking for embedded addresses. */ sctp_walk_params(params, init, init_hdr.params) { /* Note: Ignoring hostname addresses. */ af = sctp_get_af_specific(param_type2af(params.p->type)); if (!af) continue; af->from_addr_param(paddr, params.addr, sh->source, 0); asoc = __sctp_lookup_association(net, laddr, paddr, &transport); if (asoc) return asoc; } return NULL; } /* ADD-IP, Section 5.2 * When an endpoint receives an ASCONF Chunk from the remote peer * special procedures may be needed to identify the association the * ASCONF Chunk is associated with. To properly find the association * the following procedures SHOULD be followed: * * D2) If the association is not found, use the address found in the * Address Parameter TLV combined with the port number found in the * SCTP common header. If found proceed to rule D4. * * D2-ext) If more than one ASCONF Chunks are packed together, use the * address found in the ASCONF Address Parameter TLV of each of the * subsequent ASCONF Chunks. If found, proceed to rule D4. */ static struct sctp_association *__sctp_rcv_asconf_lookup( struct net *net, sctp_chunkhdr_t *ch, const union sctp_addr *laddr, __be16 peer_port, struct sctp_transport **transportp) { sctp_addip_chunk_t *asconf = (struct sctp_addip_chunk *)ch; struct sctp_af *af; union sctp_addr_param *param; union sctp_addr paddr; /* Skip over the ADDIP header and find the Address parameter */ param = (union sctp_addr_param *)(asconf + 1); af = sctp_get_af_specific(param_type2af(param->p.type)); if (unlikely(!af)) return NULL; af->from_addr_param(&paddr, param, peer_port, 0); return __sctp_lookup_association(net, laddr, &paddr, transportp); } /* SCTP-AUTH, Section 6.3: * If the receiver does not find a STCB for a packet containing an AUTH * chunk as the first chunk and not a COOKIE-ECHO chunk as the second * chunk, it MUST use the chunks after the AUTH chunk to look up an existing * association. * * This means that any chunks that can help us identify the association need * to be looked at to find this association. */ static struct sctp_association *__sctp_rcv_walk_lookup(struct net *net, struct sk_buff *skb, const union sctp_addr *laddr, struct sctp_transport **transportp) { struct sctp_association *asoc = NULL; sctp_chunkhdr_t *ch; int have_auth = 0; unsigned int chunk_num = 1; __u8 *ch_end; /* Walk through the chunks looking for AUTH or ASCONF chunks * to help us find the association. */ ch = (sctp_chunkhdr_t *) skb->data; do { /* Break out if chunk length is less then minimal. */ if (ntohs(ch->length) < sizeof(sctp_chunkhdr_t)) break; ch_end = ((__u8 *)ch) + WORD_ROUND(ntohs(ch->length)); if (ch_end > skb_tail_pointer(skb)) break; switch(ch->type) { case SCTP_CID_AUTH: have_auth = chunk_num; break; case SCTP_CID_COOKIE_ECHO: /* If a packet arrives containing an AUTH chunk as * a first chunk, a COOKIE-ECHO chunk as the second * chunk, and possibly more chunks after them, and * the receiver does not have an STCB for that * packet, then authentication is based on * the contents of the COOKIE- ECHO chunk. */ if (have_auth == 1 && chunk_num == 2) return NULL; break; case SCTP_CID_ASCONF: if (have_auth || net->sctp.addip_noauth) asoc = __sctp_rcv_asconf_lookup( net, ch, laddr, sctp_hdr(skb)->source, transportp); default: break; } if (asoc) break; ch = (sctp_chunkhdr_t *) ch_end; chunk_num++; } while (ch_end < skb_tail_pointer(skb)); return asoc; } /* * There are circumstances when we need to look inside the SCTP packet * for information to help us find the association. Examples * include looking inside of INIT/INIT-ACK chunks or after the AUTH * chunks. */ static struct sctp_association *__sctp_rcv_lookup_harder(struct net *net, struct sk_buff *skb, const union sctp_addr *laddr, struct sctp_transport **transportp) { sctp_chunkhdr_t *ch; ch = (sctp_chunkhdr_t *) skb->data; /* The code below will attempt to walk the chunk and extract * parameter information. Before we do that, we need to verify * that the chunk length doesn't cause overflow. Otherwise, we'll * walk off the end. */ if (WORD_ROUND(ntohs(ch->length)) > skb->len) return NULL; /* If this is INIT/INIT-ACK look inside the chunk too. */ switch (ch->type) { case SCTP_CID_INIT: case SCTP_CID_INIT_ACK: return __sctp_rcv_init_lookup(net, skb, laddr, transportp); break; default: return __sctp_rcv_walk_lookup(net, skb, laddr, transportp); break; } return NULL; } /* Lookup an association for an inbound skb. */ static struct sctp_association *__sctp_rcv_lookup(struct net *net, struct sk_buff *skb, const union sctp_addr *paddr, const union sctp_addr *laddr, struct sctp_transport **transportp) { struct sctp_association *asoc; asoc = __sctp_lookup_association(net, laddr, paddr, transportp); /* Further lookup for INIT/INIT-ACK packets. * SCTP Implementors Guide, 2.18 Handling of address * parameters within the INIT or INIT-ACK. */ if (!asoc) asoc = __sctp_rcv_lookup_harder(net, skb, laddr, transportp); return asoc; }
f00e3f19ac562e1cf586dd893ab1ff9e8369c1ec
55540f3e86f1d5d86ef6b5d295a63518e274efe3
/toolchain/riscv/Linux/lib/gcc/riscv64-unknown-elf/10.2.0/plugin/include/trans-mem.h
a093cd59b8e42f2af22e73b84a14656654de63d2
[ "Apache-2.0" ]
permissive
bouffalolab/bl_iot_sdk
bc5eaf036b70f8c65dd389439062b169f8d09daa
b90664de0bd4c1897a9f1f5d9e360a9631d38b34
refs/heads/master
2023-08-31T03:38:03.369853
2023-08-16T08:50:33
2023-08-18T09:13:27
307,347,250
244
101
Apache-2.0
2023-08-28T06:29:02
2020-10-26T11:16:30
C
UTF-8
C
false
false
1,937
h
trans-mem.h
/* Miscellaneous transactional memory support definitions. Copyright (C) 2009-2020 Free Software Foundation, Inc. Contributed by Richard Henderson <rth@redhat.com> and Aldy Hernandez <aldyh@redhat.com>. This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. GCC 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 GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ #ifndef GCC_TRANS_MEM_H #define GCC_TRANS_MEM_H /* These defines must match the enumerations in libitm.h. */ #define PR_INSTRUMENTEDCODE 0x0001 #define PR_UNINSTRUMENTEDCODE 0x0002 #define PR_MULTIWAYCODE (PR_INSTRUMENTEDCODE | PR_UNINSTRUMENTEDCODE) #define PR_HASNOXMMUPDATE 0x0004 #define PR_HASNOABORT 0x0008 #define PR_HASNOIRREVOCABLE 0x0020 #define PR_DOESGOIRREVOCABLE 0x0040 #define PR_HASNOSIMPLEREADS 0x0080 #define PR_AWBARRIERSOMITTED 0x0100 #define PR_RARBARRIERSOMITTED 0x0200 #define PR_UNDOLOGCODE 0x0400 #define PR_PREFERUNINSTRUMENTED 0x0800 #define PR_EXCEPTIONBLOCK 0x1000 #define PR_HASELSE 0x2000 #define PR_READONLY 0x4000 extern void compute_transaction_bits (void); extern bool is_tm_ending (gimple *); extern tree build_tm_abort_call (location_t, bool); extern bool is_tm_safe (const_tree); extern bool is_tm_pure (const_tree); extern bool is_tm_may_cancel_outer (tree); extern bool is_tm_ending_fndecl (tree); extern void record_tm_replacement (tree, tree); extern void tm_malloc_replacement (tree); #endif // GCC_TRANS_MEM_H
e6d5ad815b8ebf74aaa52811117d54d2a05291e9
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/fs/cifs/cache.c
6c665bf4a27c2985b9baa5b0f888fc0f0a7bed65
[ "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
8,154
c
cache.c
/* * fs/cifs/cache.c - CIFS filesystem cache index structure definitions * * Copyright (c) 2010 Novell, Inc. * Authors(s): Suresh Jayaraman (sjayaraman@suse.de> * * This library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See * the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "fscache.h" #include "cifs_debug.h" /* * CIFS filesystem definition for FS-Cache */ struct fscache_netfs cifs_fscache_netfs = { .name = "cifs", .version = 0, }; /* * Register CIFS for caching with FS-Cache */ int cifs_fscache_register(void) { return fscache_register_netfs(&cifs_fscache_netfs); } /* * Unregister CIFS for caching */ void cifs_fscache_unregister(void) { fscache_unregister_netfs(&cifs_fscache_netfs); } /* * Key layout of CIFS server cache index object */ struct cifs_server_key { uint16_t family; /* address family */ __be16 port; /* IP port */ union { struct in_addr ipv4_addr; struct in6_addr ipv6_addr; } addr[0]; }; /* * Server object keyed by {IPaddress,port,family} tuple */ static uint16_t cifs_server_get_key(const void *cookie_netfs_data, void *buffer, uint16_t maxbuf) { const struct TCP_Server_Info *server = cookie_netfs_data; const struct sockaddr *sa = (struct sockaddr *) &server->dstaddr; const struct sockaddr_in *addr = (struct sockaddr_in *) sa; const struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *) sa; struct cifs_server_key *key = buffer; uint16_t key_len = sizeof(struct cifs_server_key); memset(key, 0, key_len); /* * Should not be a problem as sin_family/sin6_family overlays * sa_family field */ switch (sa->sa_family) { case AF_INET: key->family = sa->sa_family; key->port = addr->sin_port; key->addr[0].ipv4_addr = addr->sin_addr; key_len += sizeof(key->addr[0].ipv4_addr); break; case AF_INET6: key->family = sa->sa_family; key->port = addr6->sin6_port; key->addr[0].ipv6_addr = addr6->sin6_addr; key_len += sizeof(key->addr[0].ipv6_addr); break; default: cifs_dbg(VFS, "Unknown network family '%d'\n", sa->sa_family); key_len = 0; break; } return key_len; } /* * Server object for FS-Cache */ const struct fscache_cookie_def cifs_fscache_server_index_def = { .name = "CIFS.server", .type = FSCACHE_COOKIE_TYPE_INDEX, .get_key = cifs_server_get_key, }; /* * Auxiliary data attached to CIFS superblock within the cache */ struct cifs_fscache_super_auxdata { u64 resource_id; /* unique server resource id */ }; static char *extract_sharename(const char *treename) { const char *src; char *delim, *dst; int len; /* skip double chars at the beginning */ src = treename + 2; /* share name is always preceded by '\\' now */ delim = strchr(src, '\\'); if (!delim) return ERR_PTR(-EINVAL); delim++; len = strlen(delim); /* caller has to free the memory */ dst = kstrndup(delim, len, GFP_KERNEL); if (!dst) return ERR_PTR(-ENOMEM); return dst; } /* * Superblock object currently keyed by share name */ static uint16_t cifs_super_get_key(const void *cookie_netfs_data, void *buffer, uint16_t maxbuf) { const struct cifs_tcon *tcon = cookie_netfs_data; char *sharename; uint16_t len; sharename = extract_sharename(tcon->treeName); if (IS_ERR(sharename)) { cifs_dbg(FYI, "%s: couldn't extract sharename\n", __func__); sharename = NULL; return 0; } len = strlen(sharename); if (len > maxbuf) return 0; memcpy(buffer, sharename, len); kfree(sharename); return len; } static uint16_t cifs_fscache_super_get_aux(const void *cookie_netfs_data, void *buffer, uint16_t maxbuf) { struct cifs_fscache_super_auxdata auxdata; const struct cifs_tcon *tcon = cookie_netfs_data; memset(&auxdata, 0, sizeof(auxdata)); auxdata.resource_id = tcon->resource_id; if (maxbuf > sizeof(auxdata)) maxbuf = sizeof(auxdata); memcpy(buffer, &auxdata, maxbuf); return maxbuf; } static enum fscache_checkaux cifs_fscache_super_check_aux(void *cookie_netfs_data, const void *data, uint16_t datalen) { struct cifs_fscache_super_auxdata auxdata; const struct cifs_tcon *tcon = cookie_netfs_data; if (datalen != sizeof(auxdata)) return FSCACHE_CHECKAUX_OBSOLETE; memset(&auxdata, 0, sizeof(auxdata)); auxdata.resource_id = tcon->resource_id; if (memcmp(data, &auxdata, datalen) != 0) return FSCACHE_CHECKAUX_OBSOLETE; return FSCACHE_CHECKAUX_OKAY; } /* * Superblock object for FS-Cache */ const struct fscache_cookie_def cifs_fscache_super_index_def = { .name = "CIFS.super", .type = FSCACHE_COOKIE_TYPE_INDEX, .get_key = cifs_super_get_key, .get_aux = cifs_fscache_super_get_aux, .check_aux = cifs_fscache_super_check_aux, }; /* * Auxiliary data attached to CIFS inode within the cache */ struct cifs_fscache_inode_auxdata { struct timespec last_write_time; struct timespec last_change_time; u64 eof; }; static uint16_t cifs_fscache_inode_get_key(const void *cookie_netfs_data, void *buffer, uint16_t maxbuf) { const struct cifsInodeInfo *cifsi = cookie_netfs_data; uint16_t keylen; /* use the UniqueId as the key */ keylen = sizeof(cifsi->uniqueid); if (keylen > maxbuf) keylen = 0; else memcpy(buffer, &cifsi->uniqueid, keylen); return keylen; } static void cifs_fscache_inode_get_attr(const void *cookie_netfs_data, uint64_t *size) { const struct cifsInodeInfo *cifsi = cookie_netfs_data; *size = cifsi->vfs_inode.i_size; } static uint16_t cifs_fscache_inode_get_aux(const void *cookie_netfs_data, void *buffer, uint16_t maxbuf) { struct cifs_fscache_inode_auxdata auxdata; const struct cifsInodeInfo *cifsi = cookie_netfs_data; memset(&auxdata, 0, sizeof(auxdata)); auxdata.eof = cifsi->server_eof; auxdata.last_write_time = cifsi->vfs_inode.i_mtime; auxdata.last_change_time = cifsi->vfs_inode.i_ctime; if (maxbuf > sizeof(auxdata)) maxbuf = sizeof(auxdata); memcpy(buffer, &auxdata, maxbuf); return maxbuf; } static enum fscache_checkaux cifs_fscache_inode_check_aux(void *cookie_netfs_data, const void *data, uint16_t datalen) { struct cifs_fscache_inode_auxdata auxdata; struct cifsInodeInfo *cifsi = cookie_netfs_data; if (datalen != sizeof(auxdata)) return FSCACHE_CHECKAUX_OBSOLETE; memset(&auxdata, 0, sizeof(auxdata)); auxdata.eof = cifsi->server_eof; auxdata.last_write_time = cifsi->vfs_inode.i_mtime; auxdata.last_change_time = cifsi->vfs_inode.i_ctime; if (memcmp(data, &auxdata, datalen) != 0) return FSCACHE_CHECKAUX_OBSOLETE; return FSCACHE_CHECKAUX_OKAY; } static void cifs_fscache_inode_now_uncached(void *cookie_netfs_data) { struct cifsInodeInfo *cifsi = cookie_netfs_data; struct pagevec pvec; pgoff_t first; int loop, nr_pages; pagevec_init(&pvec, 0); first = 0; cifs_dbg(FYI, "%s: cifs inode 0x%p now uncached\n", __func__, cifsi); for (;;) { nr_pages = pagevec_lookup(&pvec, cifsi->vfs_inode.i_mapping, first, PAGEVEC_SIZE - pagevec_count(&pvec)); if (!nr_pages) break; for (loop = 0; loop < nr_pages; loop++) ClearPageFsCache(pvec.pages[loop]); first = pvec.pages[nr_pages - 1]->index + 1; pvec.nr = nr_pages; pagevec_release(&pvec); cond_resched(); } } const struct fscache_cookie_def cifs_fscache_inode_object_def = { .name = "CIFS.uniqueid", .type = FSCACHE_COOKIE_TYPE_DATAFILE, .get_key = cifs_fscache_inode_get_key, .get_attr = cifs_fscache_inode_get_attr, .get_aux = cifs_fscache_inode_get_aux, .check_aux = cifs_fscache_inode_check_aux, .now_uncached = cifs_fscache_inode_now_uncached, };
4cff6376969398e4026cf6f93e57b8c935ff8a6e
343e288dd5c57d990d6c395395cdde513cb8e8d8
/include/template.h
a56c8131cb73916a8346c2f891b16d8edcbd3c75
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
jserv/facebooc
584a3e4d208e85bca854bbb0572b26604b42263e
f59c3c6cf6331fb50b576cfc5487f3166b58314d
refs/heads/master
2023-08-23T17:06:12.073197
2022-10-18T13:28:10
2022-10-18T13:28:10
56,661,818
611
161
NOASSERTION
2022-10-21T08:26:07
2016-04-20T06:35:09
C
UTF-8
C
false
false
290
h
template.h
#ifndef TEMPLATE_H #define TEMPLATE_H #include "list.h" typedef struct Template { char *filename; ListCell *context; } Template; Template *templateNew(char *); void templateDel(Template *); void templateSet(Template *, char *, char *); char *templateRender(Template *); #endif
8684bf810520c2d6fd4534ad1216dcea7f154ba4
ed98b77f3f09b392e68a0d59c48eec299e883bb9
/tests/src/lpi/solve_behavior.c
91104cc780901569b16012bd9b3a484614b12799
[ "Apache-2.0" ]
permissive
scipopt/scip
c8ddbe7cdec0a3af5a230c04b74b76ffacbdcc33
dc856a4c966ea50bd5f52c58d7be4fea33706f4c
refs/heads/master
2023-08-19T11:39:12.578790
2023-08-15T20:05:58
2023-08-15T20:05:58
342,522,859
262
46
NOASSERTION
2023-08-03T07:37:45
2021-02-26T09:16:17
C
UTF-8
C
false
false
6,480
c
solve_behavior.c
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* SCIP --- Solving Constraint Integer Programs */ /* */ /* Copyright (c) 2002-2023 Zuse Institute Berlin (ZIB) */ /* */ /* 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. */ /* */ /* You should have received a copy of the Apache-2.0 license */ /* along with SCIP; see the file LICENSE. If not visit scipopt.org. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /**@file solve_behavior.c * @brief unit tests for testing the behaviour of the LP solver when calling solving methods and * getting the solving state afterwards. * * Methods tested are: * SCIPlpiSolveBarier(), SCIPlpiWasSolved() * SCIPlpiHas{Simplex,Barrier}Solve() * * @author Franziska Schloesser */ /*---+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----+----9----+----0----+----1----+----2*/ #include <scip/scip.h> #include <lpi/lpi.h> #include <signal.h> #include "include/scip_test.h" #define EPS 1e-6 /* GLOBAL VARIABLES */ static SCIP_LPI* lpi = NULL; /** initialize a 3x3 maximization problem, write nrows and ncols in variables for later use. */ static void initProb(int* ncols, int* nrows) { int beg = 0; int inds[2]; SCIP_Real vals[2]; SCIP_Real lb; SCIP_Real ub; SCIP_Real obj; SCIP_Real lhs; SCIP_Real rhs; *ncols = 3; *nrows = 3; /* clean up after old problem */ if ( lpi != NULL ) { SCIP_CALL( SCIPlpiFree(&lpi) ); } /* create LPI */ SCIP_CALL( SCIPlpiCreate(&lpi, NULL, "prob", SCIP_OBJSEN_MAXIMIZE) ); /* use the following LP (same as in bases.c): * max 1 x1 + 1 x2 + 1 x3 * -8 <= -x1 - x3 <= -1 * -7 <= -x1 - x2 <= -1 * x1 + 2 x2 <= 12 * x1, x2, x3 >= 0 */ /* add columns */ lb = 0.0; ub = SCIPlpiInfinity(lpi); obj = 1.0; SCIP_CALL( SCIPlpiAddCols(lpi, 1, &obj, &lb, &ub, NULL, 0, NULL, NULL, NULL) ); SCIP_CALL( SCIPlpiAddCols(lpi, 1, &obj, &lb, &ub, NULL, 0, NULL, NULL, NULL) ); SCIP_CALL( SCIPlpiAddCols(lpi, 1, &obj, &lb, &ub, NULL, 0, NULL, NULL, NULL) ); /* add rows */ lhs = -8.0; rhs = -1.0; inds[0] = 0; inds[1] = 2; vals[0] = -1.0; vals[1] = -1.0; SCIP_CALL( SCIPlpiAddRows(lpi, 1, &lhs, &rhs, NULL, 2, &beg, inds, vals) ); lhs = -7.0; rhs = -1.0; inds[0] = 0; inds[1] = 1; vals[0] = -1.0; vals[1] = -1.0; SCIP_CALL( SCIPlpiAddRows(lpi, 1, &lhs, &rhs, NULL, 2, &beg, inds, vals) ); lhs = -SCIPlpiInfinity(lpi); rhs = 12.0; inds[0] = 0; inds[1] = 1; vals[0] = 1.0; vals[1] = 2.0; SCIP_CALL( SCIPlpiAddRows(lpi, 1, &lhs, &rhs, NULL, 2, &beg, inds, vals) ); cr_assert( !SCIPlpiWasSolved(lpi) ); } /* TEST SUITE */ static void setup(void) { /* create LPI */ SCIP_CALL( SCIPlpiCreate(&lpi, NULL, "prob", SCIP_OBJSEN_MAXIMIZE) ); cr_assert( !SCIPlpiWasSolved(lpi) ); } static void teardown(void) { SCIP_CALL( SCIPlpiFree(&lpi) ); cr_assert_eq(BMSgetMemoryUsed(), 0, "There is a memory leak!"); } TestSuite(solve_behavior, .init = setup, .fini = teardown); /** Tests */ /** Test SCIPlpiSolveBarrier */ Test(solve_behavior, testbarriersolve) { SCIP_Real objval; int i; bool crossover = true; int nrows, ncols; SCIP_Real exp_primsol[3] = { 0.0, 6.0, 8.0}; SCIP_Real exp_dualsol[3] = {-1.0, 0.0, 0.5}; SCIP_Real* primsol; SCIP_Real* dualsol; if ( SCIPlpiHasBarrierSolve() ) { /* do this twice, with and without crossover */ for (i = 0; i < 2; ++i) { /* initialize */ initProb(&nrows, &ncols); /* solve problem */ SCIP_CALL( SCIPlpiSolveBarrier(lpi, crossover) ); /* very short check (subset of complex test1 in bases.c) */ cr_assert( SCIPlpiWasSolved(lpi) ); SCIP_CALL( SCIPlpiGetObjval(lpi, &objval) ); cr_assert_float_eq(objval, 14.0, EPS); /* allocate storage for solution */ BMSallocMemoryArray(&primsol, ncols); BMSallocMemoryArray(&dualsol, nrows); /* get solution */ SCIP_CALL( SCIPlpiGetSol(lpi, &objval, primsol, dualsol, NULL, NULL) ); for (i = 0; i < ncols; ++i) { cr_assert_float_eq(primsol[i], exp_primsol[i], EPS, "Violation of primal solution %d: %g != %g\n", i, primsol[i], exp_primsol[i]); } for (i = 0; i < nrows; ++i) { cr_assert_float_eq(dualsol[i], exp_dualsol[i], EPS, "Violation of dual solution %d: %g != %g\n", i, dualsol[i], exp_dualsol[i]); } /* free up memory */ BMSfreeMemoryArray(&primsol); BMSfreeMemoryArray(&dualsol); /* prepare for second run */ crossover = !crossover; } } } /** Test if the two method giving information about availability of solve methods do not crash. */ Test(solve_behavior, testhassolve) { /* try calling all methods at least once */ SCIPlpiHasPrimalSolve(); SCIPlpiHasDualSolve(); SCIPlpiHasBarrierSolve(); }
9f55b5a385fae5675842b722114711376e5082bc
aa3befea459382dc5c01c925653d54f435b3fb0f
/arch/arm/src/s32k3xx/hardware/s32k3xx_wkpu.h
8880855ef9afb87ff2f85884acc1a4fcf615d9a6
[ "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
7,996
h
s32k3xx_wkpu.h
/**************************************************************************** * arch/arm/src/s32k3xx/hardware/s32k3xx_wkpu.h * * 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. * ****************************************************************************/ /* Copyright 2022 NXP */ #ifndef __ARCH_ARM_SRC_S32K3XX_HARDWARE_S32K3XX_WKPU_H #define __ARCH_ARM_SRC_S32K3XX_HARDWARE_S32K3XX_WKPU_H /**************************************************************************** * Included Files ****************************************************************************/ #include <hardware/s32k3xx_memorymap.h> /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ /* WKPU Register Offsets ****************************************************/ #define S32K3XX_WKPU_NSR_OFFSET (0x00) /* WKPU NMI Status Flag Register (NSR) */ #define S32K3XX_WKPU_NCR_OFFSET (0x08) /* WKPU NMI Configuration Register (NCR) */ #define S32K3XX_WKPU_WISR_OFFSET (0x14) /* WKPU Wakeup/Interrupt Status Flag Register (WISR) */ #define S32K3XX_WKPU_IRER_OFFSET (0x18) /* WKPU Interrupt Request Enable Register (IRER) */ #define S32K3XX_WKPU_WRER_OFFSET (0x1c) /* WKPU Wakeup Request Enable Register (WRER) */ #define S32K3XX_WKPU_WIREER_OFFSET (0x28) /* WKPU Wakeup/Interrupt Rising-Edge Event Enable Register (WIREER) */ #define S32K3XX_WKPU_WIFEER_OFFSET (0x2c) /* WKPU Wakeup/Interrupt Falling-Edge Event Enable Register (WIFEER) */ #define S32K3XX_WKPU_WIFER_OFFSET (0x30) /* WKPU Wakeup/Interrupt Filter Enable Register (WIFER) */ #define S32K3XX_WKPU_WISR_64_OFFSET (0x54) /* WKPU Wakeup/Interrupt Status Flag Register (WISR_64) */ #define S32K3XX_WKPU_IRER_64_OFFSET (0x58) /* WKPU Interrupt Request Enable Register (IRER_64) */ #define S32K3XX_WKPU_WRER_64_OFFSET (0x5c) /* WKPU Wakeup Request Enable Register (WRER_64) */ #define S32K3XX_WKPU_WIREER_64_OFFSET (0x68) /* WKPU Wakeup/Interrupt Rising-Edge Event Enable Register (WIREER_64) */ #define S32K3XX_WKPU_WIFEER_64_OFFSET (0x6c) /* WKPU Wakeup/Interrupt Falling-Edge Event Enable Register (WIFEER_64) */ #define S32K3XX_WKPU_WIFER_64_OFFSET (0x70) /* WKPU Wakeup/Interrupt Filter Enable Register (WIFER_64) */ /* WKPU Register Addresses **************************************************/ #define S32K3XX_WKPU_NSR (S32K3XX_WKPU_BASE + S32K3XX_WKPU_NSR_OFFSET) #define S32K3XX_WKPU_NCR (S32K3XX_WKPU_BASE + S32K3XX_WKPU_NCR_OFFSET) #define S32K3XX_WKPU_WISR (S32K3XX_WKPU_BASE + S32K3XX_WKPU_WISR_OFFSET) #define S32K3XX_WKPU_IRER (S32K3XX_WKPU_BASE + S32K3XX_WKPU_IRER_OFFSET) #define S32K3XX_WKPU_WRER (S32K3XX_WKPU_BASE + S32K3XX_WKPU_WRER_OFFSET) #define S32K3XX_WKPU_WIREER (S32K3XX_WKPU_BASE + S32K3XX_WKPU_WIREER_OFFSET) #define S32K3XX_WKPU_WIFEER (S32K3XX_WKPU_BASE + S32K3XX_WKPU_WIFEER_OFFSET) #define S32K3XX_WKPU_WIFER (S32K3XX_WKPU_BASE + S32K3XX_WKPU_WIFER_OFFSET) #define S32K3XX_WKPU_WISR_64 (S32K3XX_WKPU_BASE + S32K3XX_WKPU_WISR_64_OFFSET) #define S32K3XX_WKPU_IRER_64 (S32K3XX_WKPU_BASE + S32K3XX_WKPU_IRER_64_OFFSET) #define S32K3XX_WKPU_WRER_64 (S32K3XX_WKPU_BASE + S32K3XX_WKPU_WRER_64_OFFSET) #define S32K3XX_WKPU_WIREER_64 (S32K3XX_WKPU_BASE + S32K3XX_WKPU_WIREER_64_OFFSET) #define S32K3XX_WKPU_WIFEER_64 (S32K3XX_WKPU_BASE + S32K3XX_WKPU_WIFEER_64_OFFSET) #define S32K3XX_WKPU_WIFER_64 (S32K3XX_WKPU_BASE + S32K3XX_WKPU_WIFER_64_OFFSET) /* WKPU Register Bitfield Definitions ***************************************/ /* WKPU NMI Status Flag Register (NSR) */ /* Bits 0-21: Reserved */ #define WKPU_NSR_NOVF1 (1 << 22) /* Bit 22: NMI Overrun Status Flag 1 (NOVF1) */ #define WKPU_NSR_NIF1 (1 << 23) /* Bit 23: NMI Status Flag 1 (NIF1) */ /* Bits 24-29: Reserved */ #define WKPU_NSR_NOVF0 (1 << 30) /* Bit 30: NMI Overrun Status Flag 0 (NOVF0) */ #define WKPU_NSR_NIF0 (1 << 31) /* Bit 31: NMI Status Flag 0 (NIF0) */ /* WKPU NMI Configuration Register (NCR) */ /* Bits 0-15: Reserved */ #define WKPU_NCR_NFE1 (1 << 16) /* Bit 16: NMI Filter Enable 1 (NFE1) */ #define WKPU_NCR_NFEE1 (1 << 17) /* Bit 17: NMI Falling-edge Events Enable 1 (NFEE1) */ #define WKPU_NCR_NREE1 (1 << 18) /* Bit 18: NMI Rising-Edge Events Enable 1 (NREE1) */ /* Bit 19: Reserved */ #define WKPU_NCR_NWRE1 (1 << 20) /* Bit 20: NMI Wakeup Request Enable 1 (NWRE1) */ #define WKPU_NCR_NDSS1_SHIFT (21) /* Bits 21-22: NMI Destination Source Select 1 (NDSS1) */ #define WKPU_NCR_NDSS1_MASK (0x03 << WKPU_NCR_NDSS1_SHIFT) # define WKPU_NCR_NDSS1_NMI (0x00 << WKPU_NCR_NDSS1_SHIFT) /* Non-maskable interrupt */ #define WKPU_NCR_NLOCK1 (1 << 23) /* Bit 23: NMI Configuration Lock Register 1 (NLOCK1) */ #define WKPU_NCR_NFE0 (1 << 24) /* Bit 24: NMI Filter Enable 0 (NFE0) */ #define WKPU_NCR_NFEE0 (1 << 25) /* Bit 25: NMI Falling-edge Events Enable 0 (NFEE0) */ #define WKPU_NCR_NREE0 (1 << 26) /* Bit 26: NMI Rising-Edge Events Enable 0 (NREE0) */ /* Bit 27: Reserved */ #define WKPU_NCR_NWRE0 (1 << 28) /* Bit 28: NMI Wakeup Request Enable 0 (NWRE0) */ #define WKPU_NCR_NDSS0_SHIFT (29) /* Bits 29-30: NMI Destination Source Select 0 (NDSS0) */ #define WKPU_NCR_NDSS0_MASK (0x03 << WKPU_NCR_NDSS0_SHIFT) # define WKPU_NCR_NDSS0_NMI (0x00 << WKPU_NCR_NDSS0_SHIFT) /* Non-maskable interrupt */ #define WKPU_NCR_NLOCK0 (1 << 31) /* Bit 31: NMI Configuration Lock Register 0 (NLOCK0) */ /* WKPU Wakeup/Interrupt Status Flag Register (WISR, WISR_64) */ #define WKPU_WISR_EIF(n) (1 << (n)) /* Bit n: External Wakeup/Interrupt Status Flag n (EIFn) */ /* WKPU Interrupt Request Enable Register (IRER, IRER_64) */ #define WKPU_IRER_EIRE(n) (1 << (n)) /* Bit n: External Interrupt Request Enable n (EIREn) */ /* WKPU Wakeup Request Enable Register (WRER, WRER_64) */ #define WKPU_WRER_WRE(n) (1 << (n)) /* Bit n: External Wakeup Request Enable n (WREn) */ /* WKPU Wakeup/Interrupt Rising-Edge Event Enable Register * (WIREER, WIREER_64) */ #define WKPU_WIREER_IREE(n) (1 << (n)) /* Bit n: External Interrupt Rising-edge Events Enable n (IREEn) */ /* WKPU Wakeup/Interrupt Falling-Edge Event Enable Register * (WIFEER, WIFEER_64) */ #define WKPU_WIFEER_IFEE(n) (1 << (n)) /* Bit n: External Interrupt Falling-edge Events Enable n (IFEEn) */ /* WKPU Wakeup/Interrupt Filter Enable Register (WIFER, WIFER_64) */ #define WKPU_WIFER_IFE(n) (1 << (n)) /* Bit n: External Interrupt Filter Enable n (IFEn) */ #endif /* __ARCH_ARM_SRC_S32K3XX_HARDWARE_S32K3XX_WKPU_H */
e527d49a8259fc3318bcc75cb9d983f32060d042
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/arch/m68k/kernel/dma.c
e546a5534dd48581c8a1e1a9fc7cf9cc9edb5e21
[ "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,857
c
dma.c
/* * This file is subject to the terms and conditions of the GNU General Public * License. See the file COPYING in the main directory of this archive * for more details. */ #undef DEBUG #include <linux/dma-mapping.h> #include <linux/device.h> #include <linux/kernel.h> #include <linux/scatterlist.h> #include <linux/slab.h> #include <linux/vmalloc.h> #include <linux/export.h> #include <asm/pgalloc.h> #if defined(CONFIG_MMU) && !defined(CONFIG_COLDFIRE) void *dma_alloc_coherent(struct device *dev, size_t size, dma_addr_t *handle, gfp_t flag) { struct page *page, **map; pgprot_t pgprot; void *addr; int i, order; pr_debug("dma_alloc_coherent: %d,%x\n", size, flag); size = PAGE_ALIGN(size); order = get_order(size); page = alloc_pages(flag, order); if (!page) return NULL; *handle = page_to_phys(page); map = kmalloc(sizeof(struct page *) << order, flag & ~__GFP_DMA); if (!map) { __free_pages(page, order); return NULL; } split_page(page, order); order = 1 << order; size >>= PAGE_SHIFT; map[0] = page; for (i = 1; i < size; i++) map[i] = page + i; for (; i < order; i++) __free_page(page + i); pgprot = __pgprot(_PAGE_PRESENT | _PAGE_ACCESSED | _PAGE_DIRTY); if (CPU_IS_040_OR_060) pgprot_val(pgprot) |= _PAGE_GLOBAL040 | _PAGE_NOCACHE_S; else pgprot_val(pgprot) |= _PAGE_NOCACHE030; addr = vmap(map, size, VM_MAP, pgprot); kfree(map); return addr; } void dma_free_coherent(struct device *dev, size_t size, void *addr, dma_addr_t handle) { pr_debug("dma_free_coherent: %p, %x\n", addr, handle); vfree(addr); } #else #include <asm/cacheflush.h> void *dma_alloc_coherent(struct device *dev, size_t size, dma_addr_t *dma_handle, gfp_t gfp) { void *ret; /* ignore region specifiers */ gfp &= ~(__GFP_DMA | __GFP_HIGHMEM); if (dev == NULL || (*dev->dma_mask < 0xffffffff)) gfp |= GFP_DMA; ret = (void *)__get_free_pages(gfp, get_order(size)); if (ret != NULL) { memset(ret, 0, size); *dma_handle = virt_to_phys(ret); } return ret; } void dma_free_coherent(struct device *dev, size_t size, void *vaddr, dma_addr_t dma_handle) { free_pages((unsigned long)vaddr, get_order(size)); } #endif /* CONFIG_MMU && !CONFIG_COLDFIRE */ EXPORT_SYMBOL(dma_alloc_coherent); EXPORT_SYMBOL(dma_free_coherent); void dma_sync_single_for_device(struct device *dev, dma_addr_t handle, size_t size, enum dma_data_direction dir) { switch (dir) { case DMA_BIDIRECTIONAL: case DMA_TO_DEVICE: cache_push(handle, size); break; case DMA_FROM_DEVICE: cache_clear(handle, size); break; default: if (printk_ratelimit()) printk("dma_sync_single_for_device: unsupported dir %u\n", dir); break; } } EXPORT_SYMBOL(dma_sync_single_for_device); void dma_sync_sg_for_device(struct device *dev, struct scatterlist *sg, int nents, enum dma_data_direction dir) { int i; for (i = 0; i < nents; sg++, i++) dma_sync_single_for_device(dev, sg->dma_address, sg->length, dir); } EXPORT_SYMBOL(dma_sync_sg_for_device); dma_addr_t dma_map_single(struct device *dev, void *addr, size_t size, enum dma_data_direction dir) { dma_addr_t handle = virt_to_bus(addr); dma_sync_single_for_device(dev, handle, size, dir); return handle; } EXPORT_SYMBOL(dma_map_single); dma_addr_t dma_map_page(struct device *dev, struct page *page, unsigned long offset, size_t size, enum dma_data_direction dir) { dma_addr_t handle = page_to_phys(page) + offset; dma_sync_single_for_device(dev, handle, size, dir); return handle; } EXPORT_SYMBOL(dma_map_page); int dma_map_sg(struct device *dev, struct scatterlist *sg, int nents, enum dma_data_direction dir) { int i; for (i = 0; i < nents; sg++, i++) { sg->dma_address = sg_phys(sg); dma_sync_single_for_device(dev, sg->dma_address, sg->length, dir); } return nents; } EXPORT_SYMBOL(dma_map_sg);
bc760b01064b34d45441989fdf06658ec010b31f
9907672fcd81ab73ac63b2a83422a82bf31eadde
/euler/tyama_euler31.c
48d5ecced2c30831de924a95f91f13b0af1b0ec6
[ "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
248
c
tyama_euler31.c
a[]={1,2,5,10,20,50,100,200},m[100001]; main(i,d){ m[0]=1; for(d=0;d<8;d++){ for(i=a[d];i<100001;i++){ if(i-a[d]>=0)m[i]=(m[i]+m[i-a[d]])%1000000007; } } for(scanf("%d",&i);i--;)scanf("%d",&d),printf("%d\n",m[d]); exit(0); } /* 1 200 */
0e20cc7e065ef82ffd2db470e1800a7b6600e104
16562bb52c1be895800765cb5242ecb442a81fd5
/src/libtommath/s_mp_copy_digs.c
4079c33a62fe8d3d3de807b5c05d1fbf4c63a718
[ "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "Unlicense" ]
permissive
odin-lang/Odin
c046115a8029cdacdd50ace26f65da42640c0d2c
434c84043d7de8e2d579e4b3444da9f579b32237
refs/heads/master
2023-08-31T10:48:14.047795
2023-08-31T08:08:02
2023-08-31T08:08:02
74,583,692
4,708
606
BSD-3-Clause
2023-09-14T19:08:51
2016-11-23T14:22:10
Odin
UTF-8
C
false
false
456
c
s_mp_copy_digs.c
#include "tommath_private.h" #ifdef S_MP_COPY_DIGS_C /* LibTomMath, multiple-precision integer library -- Tom St Denis */ /* SPDX-License-Identifier: Unlicense */ #ifdef MP_USE_MEMOPS # include <string.h> #endif void s_mp_copy_digs(mp_digit *d, const mp_digit *s, int digits) { #ifdef MP_USE_MEMOPS if (digits > 0) { memcpy(d, s, (size_t)digits * sizeof(mp_digit)); } #else while (digits-- > 0) { *d++ = *s++; } #endif } #endif
cf85687a0518b19899e4bda5f868851833c68998
5ab69c8644a936a3d9dec1669a86c7369c911bf8
/arch/cpu/cc2538/dev/bignum-driver.h
6b74a82b895c35002cbc3535698fb8f8c990059c
[ "BSD-3-Clause" ]
permissive
contiki-ng/contiki-ng
393d36f68b98f5ee3544ea32502cf662ffb2fe9f
31fcaadf7a0dc8ceea07f438cd69db73174879e6
refs/heads/develop
2023-09-01T20:10:30.000765
2023-09-01T14:37:12
2023-09-01T14:37:12
91,191,972
1,242
788
BSD-3-Clause
2023-09-14T19:08:35
2017-05-13T17:37:59
C
UTF-8
C
false
false
20,409
h
bignum-driver.h
/* * Original file: * Copyright (C) 2013 Texas Instruments Incorporated - http://www.ti.com/ * All rights reserved. * * Port to Contiki: * Authors: Andreas Dröscher <contiki@anticat.ch> * Hu Luo * Hossein Shafagh <shafagh@inf.ethz.ch> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * \addtogroup cc2538-pka * @{ * * \defgroup cc2538-bignum cc2538 BigNum math function driver * * Driver for the cc2538 BigNum math functions of the PKC engine * @{ * * \file * Header file for the cc2538 BigNum driver * * bignum_subtract_start bignum_subtract_get_result (subtraction) * bignum_add_start bignum_add_get_result (addition) * bignum_mod_start bignum_mod_get_result (modulo) * bignum_exp_mod_start bignum_exp_mod_get_result (modular exponentiation operation) * bignum_inv_mod_start bignum_inv_mod_get_result (inverse modulo operation) * bignum_mul_start bignum_mul_get_result (multiplication) * bignum_divide_start bignum_divide_get_result (division) * bignum_cmp_start bignum_cmp_get_result (comparison) */ #ifndef BIGNUM_DRIVER_H_ #define BIGNUM_DRIVER_H_ #include "contiki.h" #include "dev/pka.h" #include <stdint.h> /** @} */ /*---------------------------------------------------------------------------*/ /** \brief Starts the big number modulus operation. * * \param number Pointer to the big number on which modulo operation * needs to be carried out. * \param number_size Size of the big number \sa number in 32-bit word. * \param modulus Pointer to the divisor. * \param modulus_size Size of the divisor \sa modulus. * \param result_vector Pointer to the result vector location * which will be set by this function. * \param process Process to be polled upon completion of the * operation, or \c NULL * * This function starts the modulo operation on the big num \sa number * using the divisor \sa modulus. The PKA RAM location where the result * will be available is stored in \sa result_vector. * * \retval PKA_STATUS_SUCCESS if successful in starting the operation. * \retval PKA_STATUS_OPERATION_INPRG if the PKA hw module is busy doing * some other operation. */ uint8_t bignum_mod_start(const uint32_t *number, const uint8_t number_size, const uint32_t *modulus, const uint8_t modulus_size, uint32_t *result_vector, struct process *process); /** \brief Gets the result of the big number modulus operation. * * \param buffer Pointer to buffer where the result needs to * be stored. * \param buffer_size Size of the provided buffer in 32 bit size word. * \param result_vector Address of the result location which * was provided by the start function \sa PKABigNumModStart(). * * This function gets the result of the big number modulus operation which was * previously started using the function \sa PKABigNumModStart(). * * \retval PKA_STATUS_SUCCESS if successful. * \retval PKA_STATUS_OPERATION_INPRG if the PKA hw module is busy doing * the operation. * \retval PKA_STATUS_RESULT_0 if the result is all zeroes. * \retval PKA_STATUS_BUF_UNDERFLOW if the \e size is less than the length * of the result. */ uint8_t bignum_mod_get_result(uint32_t *buffer, const uint8_t buffer_size, const uint32_t result_vector); /** \brief Starts the comparison of two big numbers. * * \param number1 Pointer to the first big number. * \param number2 Pointer to the second big number. * \param size Size of the big number in 32 bit size word. * \param process Process to be polled upon completion of the * operation, or \c NULL * * This function starts the comparison of two big numbers pointed by * \e number1 and \e number2. * Note this function expects the size of the two big numbers equal. * * \retval PKA_STATUS_SUCCESS if successful in starting the operation. * \retval PKA_STATUS_OPERATION_INPRG if the PKA hw module is busy doing * some other operation. */ uint8_t bignum_cmp_start(const uint32_t *number1, const uint32_t *number2, uint8_t size, struct process *process); /** \brief Gets the result of the comparison operation of two big numbers. * * This function provides the results of the comparison of two big numbers * which was started using the \sa PKABigNumCmpStart(). * * \retval PKA_STATUS_OPERATION_INPRG if the operation is in progress. * \retval PKA_STATUS_SUCCESS if the two big numbers are equal. * \retval PKA_STATUS_A_GR_B if the first number is greater than the second. * \retval PKA_STATUS_A_LT_B if the first number is less than the second. */ uint8_t bignum_cmp_get_result(void); /** \brief Starts the big number inverse modulo operation. * * \param number Pointer to the buffer containing the big number * (dividend). * \param number_size Size of the \e number in 32 bit word. * \param modulus Pointer to the buffer containing the modulus. * \param modulus_size Size of the modulus in 32 bit word. * \param result_vector Pointer to the result vector location * which will be set by this function. * \param process Process to be polled upon completion of the * operation, or \c NULL * * This function starts the the inverse modulo operation on \e number * using the divisor \e modulus. * * \retval PKA_STATUS_SUCCESS if successful in starting the operation. * \retval PKA_STATUS_OPERATION_INPRG if the PKA hw module is busy doing * some other operation. */ uint8_t bignum_inv_mod_start(const uint32_t *number, const uint8_t number_size, const uint32_t *modulus, const uint8_t modulus_size, uint32_t *result_vector, struct process *process); /** \brief Gets the result of the big number inverse modulo operation. * * \param buffer Pointer to buffer where the result needs to be * stored. * \param buffer_size Size of the provided buffer in 32 bit size * word. * \param result_vector Address of the result location which * was provided by the start function \sa PKABigNumInvModStart(). * * This function gets the result of the big number inverse modulo operation * previously started using the function \sa PKABigNumInvModStart(). * * \retval PKA_STATUS_SUCCESS if the operation is successful. * \retval PKA_STATUS_OPERATION_INPRG if the PKA hw module is busy performing * the operation. * \retval PKA_STATUS_RESULT_0 if the result is all zeroes. * \retval PKA_STATUS_BUF_UNDERFLOW if the length of the provided buffer is less * then the result. */ uint8_t bignum_inv_mod_get_result(uint32_t *buffer, const uint8_t buffer_size, const uint32_t result_vector); /** \brief Starts the big number multiplication. * * \param multiplicand Pointer to the buffer containing the big * number multiplicand. * \param multiplicand_size Size of the multiplicand in 32-bit word. * \param multiplier Pointer to the buffer containing the big * number multiplier. * \param multiplier_size Size of the multiplier in 32-bit word. * \param result_vector Pointer to the result vector location * which will be set by this function. * \param process Process to be polled upon completion of the * operation, or \c NULL * * This function starts the multiplication of the two big numbers. * * \retval PKA_STATUS_SUCCESS if successful in starting the operation. * \retval PKA_STATUS_OPERATION_INPRG if the PKA hw module is busy doing * some other operation. */ uint8_t bignum_mul_start(const uint32_t *multiplicand, const uint8_t multiplicand_size, const uint32_t *multiplier, const uint8_t multiplier_size, uint32_t *result_vector, struct process *process); /** \brief Gets the results of the big number multiplication. * * \param buffer Pointer to buffer where the result needs to be stored. * \param buffer_size Address of the variable containing the length of the * buffer. After the operation, the actual length of the resultant is * stored at this address. * \param result_vector Address of the result location which * was provided by the start function \sa PKABigNumMultiplyStart(). * * This function gets the result of the multiplication of two big numbers * operation previously started using the function \sa * PKABigNumMultiplyStart(). * * \retval PKA_STATUS_SUCCESS if the operation is successful. * \retval PKA_STATUS_OPERATION_INPRG if the PKA hw module is busy performing * the operation. * \retval PKA_STATUS_RESULT_0 if the result is all zeroes. * \retval PKA_STATUS_FAILURE if the operation is not successful. * \retval PKA_STATUS_BUF_UNDERFLOW if the length of the provided buffer is less * then the length of the result. */ uint8_t bignum_mul_get_result(uint32_t *buffer, uint32_t *buffer_size, const uint32_t result_vector); /** \brief Starts the addition of two big number. * * \param number1 Pointer to the buffer containing the first big mumber. * \param number1_size Size of the first big number in 32-bit word. * \param number2 Pointer to the buffer containing the second big number. * \param number2_size Size of the second big number in 32-bit word. * \param result_vector Pointer to the result vector location * which will be set by this function. * \param process Process to be polled upon completion of the * operation, or \c NULL * * This function starts the addition of the two big numbers. * * \retval PKA_STATUS_SUCCESS if successful in starting the operation. * \retval PKA_STATUS_OPERATION_INPRG if the PKA hw module is busy doing * some other operation. */ uint8_t bignum_add_start(const uint32_t *number1, const uint8_t number1_size, const uint32_t *number2, const uint8_t number2_size, uint32_t *result_vector, struct process *process); /** \brief Gets the result of the addition operation on two big number. * * \param buffer Pointer to buffer where the result * needs to be stored. * \param buffer_size Address of the variable containing the length of * the buffer. After the operation the actual length of the * resultant is stored at this address. * \param result_vector Address of the result location which * was provided by the start function \sa PKABigNumAddStart(). * * This function gets the result of the addition operation on two big numbers, * previously started using the function \sa PKABigNumAddStart(). * * \retval PKA_STATUS_SUCCESS if the operation is successful. * \retval PKA_STATUS_OPERATION_INPRG if the PKA hw module is busy performing * the operation. * \retval PKA_STATUS_RESULT_0 if the result is all zeroes. * \retval PKA_STATUS_FAILURE if the operation is not successful. * \retval PKA_STATUS_BUF_UNDERFLOW if the length of the provided buffer is less * then the length of the result. */ uint8_t bignum_add_get_result(uint32_t *buffer, uint32_t *buffer_size, const uint32_t result_vector); /** \brief Starts the substract of two big number. * * \param number1 Pointer to the buffer containing the first big mumber. * \param number1_size Size of the first big number in 32-bit word. * \param number2 Pointer to the buffer containing the second big number. * \param number2_size Size of the second big number in 32-bit word. * \param result_vector Pointer to the result vector location * which will be set by this function. * \param process Process to be polled upon completion of the * operation, or \c NULL * * This function starts the substraction of the two big numbers. * * \retval PKA_STATUS_SUCCESS if successful in starting the operation. * \retval PKA_STATUS_OPERATION_INPRG if the PKA hw module is busy doing * some other operation. */ uint8_t bignum_subtract_start(const uint32_t *number1, const uint8_t number1_size, const uint32_t *number2, const uint8_t number2_size, uint32_t *result_vector, struct process *process); /** \brief Gets the result of big number subtract. * * \param buffer Pointer to store the result of subtraction. * \param buffer_size Address of the variable containing the length of the * buffer. After the operation, the actual length of the resultant is * stored at this address. * \param result_vector Address of the result location which * was provided by the start function PKABigNumSubtractStart(). * * This function gets the result of PKABigNumSubtractStart(). * * \retval PKA_STATUS_SUCCESS if the operation is successful. * \retval PKA_STATUS_OPERATION_INPRG if the PKA hw module is busy performing * the operation. * \retval PKA_STATUS_RESULT_0 if the result is all zeroes. * \retval PKA_STATUS_FAILURE if the operation is not successful. */ uint8_t bignum_subtract_get_result(uint32_t *buffer, uint32_t *buffer_size, const uint32_t result_vector); /** \brief Starts the big number moduluar Exponentiation operation. * * \param number Pointer to the Exponent on which moduluar Exponentiation operation * needs to be carried out. * \param number_size Size of the the Exponent number number in 32-bit word. * \param modulus Pointer to the divisor. * \param modulus_size Size of the divisor modulus. * \param base Pointer to the Base. * \param base_size Size of the divisor base. * \param result_vector Pointer to the result vector location * which will be set by this function. * \param process Process to be polled upon completion of the * operation, or \c NULL * * This function starts the moduluar Exponentiation operation on the base num base * using the Exponent number and the Modulus num modulus. The PKA RAM location where the result * will be available is stored in \sa result_vector. * IMPORTANT = Modulus and Based should have buffers of the same length! * * \retval PKA_STATUS_SUCCESS if successful in starting the operation. * \retval PKA_STATUS_OPERATION_INPRG if the PKA hw module is busy doing * some other operation. */ uint8_t bignum_exp_mod_start(const uint32_t *number, const uint8_t number_size, const uint32_t *modulus, const uint8_t modulus_size, const uint32_t *base, const uint8_t base_size, uint32_t *result_vector, struct process *process); /** \brief Gets the result of the big number modulus operation result. * * \param buffer Pointer to buffer where the result needs to * be stored. * \param buffer_size Size of the provided buffer in 32 bit size word. * \param result_vector Address of the result location which * was provided by the start function \sa PKABigNumExpModStart(). * * This function gets the result of the big number modulus operation which was * previously started using the function \sa PKABigNumExpModStart(). * * \retval PKA_STATUS_SUCCESS if successful. * \retval PKA_STATUS_OPERATION_INPRG if the PKA hw module is busy doing * the operation. * \retval PKA_STATUS_RESULT_0 if the result is all zeroes. * \retval PKA_STATUS_BUF_UNDERFLOW if the \e size is less than the length * of the result. * * \note * - 0 < number_size <= Max_Len * - 1 < modulus_size <=Max_Len * - modulus must be odd and modulus > 232 * - base < modulus */ uint8_t bignum_exp_mod_get_result(uint32_t *buffer, const uint8_t buffer_size, const uint32_t result_vector); /** \brief Starts the big number Divide. * * \param dividend Pointer to the buffer containing the big * number dividend. * \param dividend_size Size of the dividend in 32-bit word. * \param divisor Pointer to the buffer containing the big * number divisor. * \param divisor_size Size of the divisor in 32-bit word. * \param result_vector Pointer to the result vector location * which will be set by this function. * \param process Process to be polled upon completion of the * operation, or \c NULL * * This function starts the divide of the two big numbers. * * \retval PKA_STATUS_SUCCESS if successful in starting the operation. * \retval PKA_STATUS_OPERATION_INPRG if the PKA hw module is busy doing * some other operation. */ uint8_t bignum_divide_start(const uint32_t *dividend, const uint8_t dividend_size, const uint32_t *divisor, const uint8_t divisor_size, uint32_t *result_vector, struct process *process); /** \brief Gets the results of the big number Divide. * * \param buffer Pointer to buffer where the result needs to be stored. * \param buffer_size Address of the variable containing the length of the * buffer. After the operation, the actual length of the resultant is * stored at this address. * \param result_vector Address of the result location which * was provided by the start function \sa PKABigNumMultiplyStart(). * * This function gets the result of the Divide of two big numbers * operation previously started using the function \sa * PKABigNumDivideStart(). * * \retval PKA_STATUS_SUCCESS if the operation is successful. * \retval PKA_STATUS_OPERATION_INPRG if the PKA hw module is busy performing * the operation. * \retval PKA_STATUS_RESULT_0 if the result is all zeroes. * \retval PKA_STATUS_FAILURE if the operation is not successful. * \retval PKA_STATUS_BUF_UNDERFLOW if the length of the provided buffer is less * then the length of the result. */ uint8_t bignum_divide_get_result(uint32_t *buffer, uint32_t *buffer_size, const uint32_t result_vector); /** @} */ #endif /* BIGNUM_DRIVER_H_ */
f25d861b320a1b9a44d8d172342d2d6af03c45bf
0744dcc5394cebf57ebcba343747af6871b67017
/os/board/rtl8730e/src/component/wifi/inic/inic_ipc_host_api_basic.c
ec4596bfd70daf568e8aeb969680f8df716e0e6c
[ "Apache-2.0", "GPL-1.0-or-later", "BSD-3-Clause", "ISC", "MIT", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-other-permissive" ]
permissive
Samsung/TizenRT
96abf62f1853f61fcf91ff14671a5e0c6ca48fdb
1a5c2e00a4b1bbf4c505bbf5cc6a8259e926f686
refs/heads/master
2023-08-31T08:59:33.327998
2023-08-08T06:09:20
2023-08-31T04:38:20
82,517,252
590
719
Apache-2.0
2023-09-14T06:54:49
2017-02-20T04:38:30
C
UTF-8
C
false
false
11,246
c
inic_ipc_host_api_basic.c
//----------------------------------------------------------------------------// #include "main.h" #if CONFIG_LWIP_LAYER #include <lwip_netconf.h> #ifndef CONFIG_PLATFORM_TIZENRT_OS #include <dhcp/dhcps.h> #endif #endif #include <wifi_ind.h> #include <osdep_service.h> #include <rtw_timer.h> #if defined(CONFIG_AS_INIC_AP) #include "inic_ipc_api.h" #endif /****************************************************** * Constants ******************************************************/ #define RTW_JOIN_TIMEOUT 20000 //INIC_IPC_API_TODO /****************************************************** * Variables Declarations ******************************************************/ #if CONFIG_LWIP_LAYER extern struct netif xnetif[NET_IF_NUM]; #endif /****************************************************** * Variables Definitions ******************************************************/ internal_join_block_param_t *join_block_param = NULL; rtw_result_t (*scan_user_callback_ptr)(unsigned int, void *) = NULL; rtw_result_t (*scan_each_report_user_callback_ptr)(rtw_scan_result_t *, void *) = NULL; extern void *param_indicator; rtw_join_status_t rtw_join_status; rtw_joinstatus_callback_t p_wifi_joinstatus_user_callback = NULL; rtw_joinstatus_callback_t p_wifi_joinstatus_internal_callback = NULL; wifi_do_fast_connect_ptr p_wifi_do_fast_connect = NULL; write_fast_connect_info_ptr p_store_fast_connect_info = NULL; extern void wifi_set_user_config(void); /* Give default value if not defined */ /****************************************************** * Function Definitions ******************************************************/ #if CONFIG_WLAN #if defined(CONFIG_PLATFORM_TIZENRT_OS) #include "rtk_wifi_utils.h" unsigned char ap_bssid[ETH_ALEN]; rtk_network_link_callback_t g_link_up = NULL; rtk_network_link_callback_t g_link_down = NULL; typedef void (*rtk_network_link_callback_t)(rtk_reason_t *reason); int8_t WiFiRegisterLinkCallback(rtk_network_link_callback_t link_up, rtk_network_link_callback_t link_down) { if (!g_link_up) { g_link_up = link_up; } if (!g_link_down) { g_link_down = link_down; } return RTK_STATUS_SUCCESS; } extern void linkup_handler(rtk_reason_t *reason); extern void linkdown_handler(rtk_reason_t *reason); #endif //----------------------------------------------------------------------------// int wifi_connect(rtw_network_info_t *connect_param, unsigned char block) { rtw_result_t result = RTW_SUCCESS; internal_join_block_param_t *block_param = NULL; u32 param_buf[1] = {0}; #if defined(CONFIG_PLATFORM_TIZENRT_OS) rtk_reason_t reason; #endif /* check if SoftAP is running */ if ((wifi_user_config.concurrent_enabled == _FALSE) && wifi_is_running(SOFTAP_WLAN_INDEX)) { RTW_API_INFO("Concurrent mode is disabled. To use it, please set concurrent_enabled to _TRUE in wifi_set_user_config() !!\n"); return RTW_ERROR; } if (connect_param == NULL) { RTW_API_INFO("\nwifi connect param not set!"); return RTW_ERROR; } /* step1: check if there's ongoing connect*/ if ((rtw_join_status > RTW_JOINSTATUS_UNKNOWN) && (rtw_join_status < RTW_JOINSTATUS_SUCCESS)) { RTW_API_INFO("\nthere is ongoing wifi connect!"); return RTW_BUSY; } p_wifi_joinstatus_user_callback = connect_param->joinstatus_user_callback; p_wifi_joinstatus_internal_callback = wifi_join_status_indicate; /*clear for last connect status */ rtw_join_status = RTW_JOINSTATUS_STARTING; wifi_join_status_indicate(RTW_JOINSTATUS_STARTING); /* step2: malloc and set synchronous connection related variables*/ if (block) { block_param = (internal_join_block_param_t *)rtw_zmalloc(sizeof(internal_join_block_param_t)); if (!block_param) { result = (rtw_result_t) RTW_NOMEM; rtw_join_status = RTW_JOINSTATUS_FAIL; goto error; } block_param->block = block; rtw_init_sema(&block_param->join_sema, 0); if (!block_param->join_sema) { result = (rtw_result_t) RTW_NOMEM; rtw_join_status = RTW_JOINSTATUS_FAIL; goto error; } } /* step3: set connect cmd to driver*/ if (connect_param->password_len) { DCache_Clean((u32)connect_param->password, connect_param->password_len); } DCache_Clean((u32)connect_param, sizeof(rtw_network_info_t)); param_buf[0] = (u32)connect_param; result = inic_ipc_api_host_message_send(IPC_API_WIFI_CONNECT, param_buf, 1); if (result != RTW_SUCCESS) { rtw_join_status = RTW_JOINSTATUS_FAIL; goto error; } /* step4: wait connect finished for synchronous connection*/ if (block) { join_block_param = block_param; #ifdef CONFIG_ENABLE_EAP // for eap connection, timeout should be longer (default value in wpa_supplicant: 60s) if (wifi_get_eap_phase()) { block_param->join_timeout = 60000; } else #endif block_param->join_timeout = RTW_JOIN_TIMEOUT; if (rtw_down_timeout_sema(&block_param->join_sema, block_param->join_timeout) == _FAIL) { RTW_API_INFO("RTW API: Join bss timeout\r\n"); rtw_join_status = RTW_JOINSTATUS_FAIL; result = RTW_TIMEOUT; goto error; } else { if (wifi_is_connected_to_ap() != RTW_SUCCESS) { result = RTW_ERROR; rtw_join_status = RTW_JOINSTATUS_FAIL; goto error; } #if defined(CONFIG_PLATFORM_TIZENRT_OS) memset(&reason, 0, sizeof(rtk_reason_t)); reason.reason_code = RTK_STATUS_SUCCESS; if (g_link_up) { if (reason.reason_code) { nvdbg("reason.reason_code=%d\n", reason.reason_code); } printf("RTK_API %s() send link_up\n", __func__); g_link_up(&reason); } #endif } } error: if (block_param) { if (block_param->join_sema) { rtw_free_sema(&block_param->join_sema); } rtw_free((u8 *)block_param); join_block_param = NULL; } if (rtw_join_status == RTW_JOINSTATUS_FAIL) { wifi_join_status_indicate(RTW_JOINSTATUS_FAIL); } return result; } int wifi_disconnect(void) { int ret = 0; ret = inic_ipc_api_host_message_send(IPC_API_WIFI_DISCONNECT, NULL, 0); #if defined(CONFIG_PLATFORM_TIZENRT_OS) rtk_reason_t dummy_reason; memset(&dummy_reason, 0, sizeof(rtk_reason_t)); if (g_link_down) { nvdbg("RTK_API rtk_handle_disconnect send link_down\n"); g_link_down(&dummy_reason); //dummy_reason was not processed in _wt_sta_disconnected callback in TizenRT } #endif return ret; } //----------------------------------------------------------------------------// int wifi_is_running(unsigned char wlan_idx) { int ret; u32 param_buf[1]; param_buf[0] = wlan_idx; ret = inic_ipc_api_host_message_send(IPC_API_WIFI_IS_RUNNING, param_buf, 1); return ret; } rtw_join_status_t wifi_get_join_status(void) { return rtw_join_status; } int wifi_on(rtw_mode_t mode) { int ret = 1; u32 param_buf[1]; static u32 wifi_boot = 0; #if defined(CONFIG_PLATFORM_TIZENRT_OS) ret = WiFiRegisterLinkCallback(&linkup_handler, &linkdown_handler); if (ret != RTK_STATUS_SUCCESS) { printf("[RTK] Link callback handles: register failed !\n"); return -1; } else { printf("[RTK] Link callback handles: registered\n"); } #endif wifi_set_user_config(); param_buf[0] = mode; inic_ipc_host_init_skb(); ret = inic_ipc_api_host_message_send(IPC_API_WIFI_ON, param_buf, 1); if (wifi_boot == 0) { wifi_boot = 1; init_timer_wrapper(); init_timer_pool(); if (p_wifi_do_fast_connect && (mode == RTW_MODE_STA)) { p_wifi_do_fast_connect(); } } if (ret == RTW_SUCCESS) { //wifi on success #if !defined(CONFIG_PLATFORM_TIZENRT_OS) #if CONFIG_LWIP_LAYER if (mode == RTW_MODE_STA) { LwIP_netif_set_up(0); } #endif #endif } return ret; } int wifi_off(void) { int ret = 0; //inic_ipc_host_deinit_skb();/*should be called after np deinit*/ return ret; } int wifi_set_mode(rtw_mode_t mode) { (void) mode; return 0; } #if defined(CONFIG_PLATFORM_TIZENRT_OS) static void wifi_ap_sta_assoc_hdl( char* buf, int buf_len, int flags, void* userdata) { /* To avoid gcc warnings */ ( void ) buf; ( void ) buf_len; ( void ) flags; ( void ) userdata; //USER TODO #if defined(CONFIG_PLATFORM_TIZENRT_OS) rtk_reason_t reason; memset(&reason, 0, sizeof(rtk_reason_t)); if (strlen(buf) >= 17) { // bssid is a 17 character string memcpy(&(reason.bssid), buf, 17); // Exclude null-termination } if (g_link_up) { nvdbg("RTK_API rtk_link_event_handler send link_up\n"); g_link_up(&reason); } #endif } static void wifi_ap_sta_disassoc_hdl( char* buf, int buf_len, int flags, void* userdata) { /* To avoid gcc warnings */ ( void ) buf; ( void ) buf_len; ( void ) flags; ( void ) userdata; //USER TODO #if defined(CONFIG_PLATFORM_TIZENRT_OS) rtk_reason_t reason; memset(&reason, 0, sizeof(rtk_reason_t)); if (strlen(buf) >= 17) { // bssid is a 17 character string memcpy(&(reason.bssid), buf, 17); } if (g_link_down) { nvdbg("RTK_API rtk_handle_disconnect send link_down\n"); g_link_down(&reason); } #endif } #endif int wifi_start_ap(rtw_softap_info_t *softAP_config) { int ret = 0; u32 param_buf[1]; /* check if STA is running */ if ((wifi_user_config.concurrent_enabled == _FALSE) && (rtw_join_status > RTW_JOINSTATUS_UNKNOWN) && (rtw_join_status <= RTW_JOINSTATUS_SUCCESS)) { RTW_API_INFO("Concurrent mode is disabled. To use it, please set concurrent_enabled to _TRUE in wifi_set_user_config() !!\n"); ret = RTW_ERROR; goto exit; } DCache_Clean((u32)softAP_config->password, softAP_config->password_len); DCache_Clean((u32)softAP_config, sizeof(rtw_softap_info_t)); param_buf[0] = (u32)softAP_config; #if defined(CONFIG_PLATFORM_TIZENRT_OS) wifi_reg_event_handler(WIFI_EVENT_STA_ASSOC, wifi_ap_sta_assoc_hdl, NULL); wifi_reg_event_handler(WIFI_EVENT_STA_DISASSOC, wifi_ap_sta_disassoc_hdl, NULL); #endif ret = inic_ipc_api_host_message_send(IPC_API_WIFI_START_AP, param_buf, 1); if (ret == RTW_SUCCESS) { #if !defined(CONFIG_PLATFORM_TIZENRT_OS) #if CONFIG_LWIP_LAYER LwIP_netif_set_up(SOFTAP_WLAN_INDEX); LwIP_netif_set_link_up(SOFTAP_WLAN_INDEX); #endif #endif } exit: return ret; } int wifi_stop_ap(void) { int ret = 0; if (wifi_is_running(SOFTAP_WLAN_INDEX) == 0) { RTW_API_INFO("\n\rWIFI is not running"); return 0; } #if !defined(CONFIG_PLATFORM_TIZENRT_OS) #if CONFIG_LWIP_LAYER dhcps_deinit(); LwIP_netif_set_down(1); LwIP_netif_set_link_down(1); #endif #endif ret = inic_ipc_api_host_message_send(IPC_API_WIFI_STOP_AP, NULL, 0); return ret; } int wifi_scan_networks(rtw_scan_param_t *scan_param, unsigned char block) { assert_param(scan_param); int ret = 0; u32 param_buf[3]; /* lock 2s to forbid suspend under scan */ rtw_wakelock_timeout(2 * 1000); scan_user_callback_ptr = scan_param->scan_user_callback; scan_each_report_user_callback_ptr = scan_param->scan_report_each_mode_user_callback; if (scan_param->ssid) { DCache_Clean((u32)scan_param->ssid, strlen(scan_param->ssid)); } if (scan_param->channel_list) { DCache_Clean((u32)scan_param->channel_list, scan_param->channel_list_num); } DCache_Clean((u32)scan_param, sizeof(rtw_scan_param_t)); param_buf[0] = (u32)scan_param; param_buf[1] = block; if (scan_param->ssid) { param_buf[2] = strlen(scan_param->ssid); } else { param_buf[2] = 0; } ret = inic_ipc_api_host_message_send(IPC_API_WIFI_SCAN_NETWROKS, param_buf, 3); return ret; } #endif //#if CONFIG_WLAN
3ca710827e08151362e6f47cd0dab61ffd10f183
f3eed0234b4d0ad2bbb2abd700cf1e2c7a0e8a1d
/AKWF-c/AKWF_aguitar/AKWF_aguitar_0034.h
11162af53a5d7053898b423b4cd31ba6d2cb4167
[ "CC0-1.0" ]
permissive
KristofferKarlAxelEkstrand/AKWF-FREE
b2defa1a2d389d309be6dd2e9f968923daf80d1b
cf8171df36e9fec25416b5f568b72a6e2cb69194
refs/heads/master
2023-07-23T18:22:36.939705
2023-07-10T17:14:40
2023-07-10T17:14:40
145,817,187
359
59
CC0-1.0
2023-07-10T17:14:41
2018-08-23T07:26:56
null
UTF-8
C
false
false
4,688
h
AKWF_aguitar_0034.h
/* Adventure Kid Waveforms (AKWF) converted for use with Teensy Audio Library * * Adventure Kid Waveforms(AKWF) Open waveforms library * https://www.adventurekid.se/akrt/waveforms/adventure-kid-waveforms/ * * This code is in the public domain, CC0 1.0 Universal (CC0 1.0) * https://creativecommons.org/publicdomain/zero/1.0/ * * Converted by Brad Roy, https://github.com/prosper00 */ /* AKWF_aguitar_0034 256 samples +-----------------------------------------------------------------------------------------------------------------+ | *** *** | | ** *** | | *** ** | | ** *** | | *** *** | | ** *** | | ** ** | |*** *** | |* ****** | | ******** ************ ***| | ******** **** **** ****** | | **** **** *** | | ***** *** | | **** *** | | **** ***** | +-----------------------------------------------------------------------------------------------------------------+ */ const uint16_t AKWF_aguitar_0034 [] = { 33045, 33960, 34924, 35981, 37071, 38190, 39267, 40302, 41274, 42161, 42975, 43736, 44470, 45205, 45990, 46838, 47767, 48774, 49891, 51065, 52289, 53515, 54715, 55863, 56941, 57954, 58922, 59849, 60746, 61614, 62427, 63179, 63849, 64410, 64869, 65204, 65419, 65522, 65529, 65468, 65343, 65187, 65019, 64840, 64655, 64450, 64216, 63933, 63566, 63080, 62452, 61670, 60740, 59671, 58521, 57326, 56102, 54890, 53726, 52631, 51613, 50678, 49826, 49062, 48345, 47665, 47015, 46367, 45693, 44975, 44210, 43362, 42422, 41409, 40336, 39235, 38160, 37152, 36229, 35433, 34773, 34241, 33848, 33564, 33370, 33237, 33130, 33006, 32856, 32660, 32415, 32147, 31877, 31624, 31391, 31191, 31024, 30868, 30705, 30519, 30296, 30045, 29772, 29502, 29253, 29046, 28900, 28807, 28770, 28775, 28800, 28824, 28839, 28821, 28754, 28621, 28416, 28137, 27762, 27300, 26747, 26116, 25422, 24680, 23928, 23211, 22557, 21996, 21541, 21195, 20937, 20731, 20545, 20350, 20112, 19801, 19406, 18914, 18336, 17686, 16981, 16262, 15557, 14891, 14292, 13759, 13296, 12895, 12547, 12233, 11940, 11664, 11396, 11133, 10866, 10609, 10372, 10160, 9994, 9888, 9846, 9878, 9991, 10166, 10391, 10660, 10945, 11247, 11554, 11859, 12176, 12507, 12866, 13251, 13686, 14174, 14718, 15323, 15985, 16692, 17441, 18226, 19017, 19804, 20571, 21321, 22022, 22669, 23276, 23830, 24343, 24833, 25318, 25808, 26312, 26824, 27332, 27823, 28266, 28655, 28963, 29183, 29323, 29378, 29373, 29318, 29248, 29195, 29188, 29252, 29399, 29624, 29904, 30223, 30540, 30810, 31003, 31097, 31066, 30905, 30612, 30204, 29713, 29168, 28613, 28076, 27572, 27109, 26684, 26305, 25971, 25675, 25440, 25269, 25172, 25151, 25229, 25386, 25614, 25891, 26208, 26535, 26863, 27174, 27464, 27755, 28042, 28352, 28673, 29028, 29408, 29862, 30340, 30911, 31519, 32288, };
e365fd79df6a3a322d0440b27e8855a6be93e56f
0878580d8373128457cff2809284c999caf7c7d8
/Source/Sources/Windows/Windows_Game.c
a7a1a52d8abdadc7805de3d93a3098a0f04daf81
[]
no_license
NovFR/DoS-2-Savegame-Editor
a9618ca7d317055475cae3f26a8aa7dd242864e7
267d7b594aa4723b696bb8883698a274e70ab3d1
refs/heads/master
2023-01-28T01:25:00.186332
2021-04-20T10:27:38
2021-04-20T10:27:38
186,271,246
113
19
null
null
null
null
UTF-8
C
false
false
13,330
c
Windows_Game.c
//<<>-<>>---------------------------------------------------------------------() /* Gestion des messages de la fenêtre des attributs */ //()-------------------------------------------------------------------<<>-<>>// // ¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤ // // ¤¤¤ ¤¤¤ // // ¤¤¤ Données ¤¤¤ // // ¤¤¤ ¤¤¤ // // ¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤ // #include "Application.h" #include "Game.h" #include "Utils.h" #include "Texts.h" extern APPLICATION App; // ¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤ // // ¤¤¤ ¤¤¤ // // ¤¤¤ Conteneur ¤¤¤ // // ¤¤¤ ¤¤¤ // // ¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤ // // «»»» Initialisation de la fenêtre ««««««««««««««««««««««««««««««««««««» LRESULT Game_ContainerCreate(HWND hWnd) { RECT rcWindow; GetClientRect(hWnd,&rcWindow); App.Game.Layout.hwndDecoTop = CreateWindowEx(WS_EX_TRANSPARENT|WS_EX_TOPMOST,szStaticClass,NULL,WS_CHILD|WS_VISIBLE|SS_OWNERDRAW,0,0,rcWindow.right-rcWindow.left,WINDOW_DECO_HEIGHT,hWnd,(HMENU)CTLID_ATTRS_DECOTOP,App.hInstance,NULL); if (!App.Game.Layout.hwndDecoTop) return(-1); App.Game.Layout.hwndDecoBottom = CreateWindowEx(WS_EX_TRANSPARENT|WS_EX_TOPMOST,szStaticClass,NULL,WS_CHILD|WS_VISIBLE|SS_OWNERDRAW,0,0,rcWindow.right-rcWindow.left,WINDOW_DECO_HEIGHT,hWnd,(HMENU)CTLID_ATTRS_DECOBOTTOM,App.hInstance,NULL); if (!App.Game.Layout.hwndDecoBottom) return(-1); App.Game.Layout.hwndScrollbar = CreateWindowEx(WS_EX_TOPMOST,szScrollClass,NULL,WS_CHILD|SBS_VERT,0,0,MAIN_ATTR_SCROLLBAR_WIDTH,100,hWnd,(HMENU)CTLID_ATTRS_SCROLLBAR,App.hInstance,NULL); if (!App.Game.Layout.hwndScrollbar) return(-1); App.Game.Layout.hwndAttributes = CreateWindowEx(WS_EX_CONTROLPARENT,szWindowClass,NULL,WS_CHILD|WS_VISIBLE,0,0,rcWindow.right-rcWindow.left,100,hWnd,NULL,App.hInstance,(void *)WINDOW_GAME_ATTRIBUTES); if (!App.Game.Layout.hwndAttributes) return(-1); return(0); } // «»»» Messages provenant de la fenêtre ««««««««««««««««««««««««««««««««» LRESULT Game_ProcessContainerMessages(HWND hWnd, UINT uMsgId, WPARAM wParam, LPARAM lParam) { switch(uMsgId) { case WM_DRAWITEM: switch(((DRAWITEMSTRUCT *)lParam)->CtlID) { case CTLID_ATTRS_DECOTOP: Game_PaintDecorationBorder((DRAWITEMSTRUCT *)lParam,TRUE); Game_PaintDecoration(((DRAWITEMSTRUCT *)lParam)->hDC,-8,0,App.Game.Layout.hDecoTop); break; case CTLID_ATTRS_DECOBOTTOM: Game_PaintDecorationBorder((DRAWITEMSTRUCT *)lParam,FALSE); Game_PaintDecoration(((DRAWITEMSTRUCT *)lParam)->hDC,-8,0,App.Game.Layout.hDecoBottom); break; } break; case WM_PAINT: if (GetUpdateRect(hWnd,NULL,FALSE)) { HDC hDC; PAINTSTRUCT paintStruct; RECT rcWindow; hDC = BeginPaint(hWnd,&paintStruct); GetClientRect(hWnd,&rcWindow); FillRect(hDC,&rcWindow,GetSysColorBrush(COLOR_WINDOW)); EndPaint(hWnd,&paintStruct); } break; case WM_VSCROLL: Game_ContainerScroll(LOWORD(wParam)); break; case WM_SIZE: Game_ContainerResize(hWnd,LOWORD(lParam),HIWORD(lParam)); break; case WM_MOUSEWHEEL: Game_ContainerMouseWheel(hWnd,(int)GET_WHEEL_DELTA_WPARAM(wParam)); break; default: return(DefWindowProc(hWnd,uMsgId,wParam,lParam)); } return(0); } // «»»» Redimension du conteneur ««««««««««««««««««««««««««««««««««««««««» void Game_ContainerResize(HWND hWnd, int iWidth, int iHeight) { RECT rcAttributes; GetWindowRect(App.Game.Layout.hwndAttributes,&rcAttributes); MapWindowPoints(NULL,hWnd,(POINT *)&rcAttributes,2); rcAttributes.right = rcAttributes.left+iWidth; if (rcAttributes.bottom-rcAttributes.top > iHeight) rcAttributes.right -= MAIN_ATTR_SCROLLBAR_TOTALWIDTH-MAIN_ATTR_RIGHTMARGIN; SetWindowPos(App.Game.Layout.hwndAttributes,NULL,rcAttributes.left,Game_ContainerTopOffset(rcAttributes.top,&rcAttributes),rcAttributes.right-rcAttributes.left,rcAttributes.bottom-rcAttributes.top,SWP_NOACTIVATE|SWP_NOOWNERZORDER|SWP_NOZORDER); SetWindowPos(App.Game.Layout.hwndScrollbar,NULL,iWidth-MAIN_ATTR_SCROLLBAR_TOTALWIDTH+(MAIN_ATTR_SCROLLBAR_TOTALWIDTH-MAIN_ATTR_SCROLLBAR_WIDTH)/2,MAIN_ATTR_SCROLLBAR_VERTMARGIN,MAIN_ATTR_SCROLLBAR_WIDTH,iHeight-MAIN_ATTR_SCROLLBAR_VERTMARGIN*2,SWP_NOACTIVATE|SWP_NOOWNERZORDER|SWP_NOZORDER); SetWindowPos(App.Game.Layout.hwndDecoTop,NULL,0,0,iWidth,WINDOW_DECO_HEIGHT,SWP_NOACTIVATE|SWP_NOOWNERZORDER|SWP_NOZORDER); SetWindowPos(App.Game.Layout.hwndDecoBottom,NULL,0,iHeight-WINDOW_DECO_HEIGHT,iWidth,WINDOW_DECO_HEIGHT,SWP_NOACTIVATE|SWP_NOOWNERZORDER|SWP_NOZORDER); Game_ContainerScrollInfo(SIF_PAGE|SIF_RANGE); return; } // «»»» Déplacement des attributs «««««««««««««««««««««««««««««««««««««««» //--- WM_MOUSEWHEEL --- void Game_ContainerMouseWheel(HWND hWnd, int iDelta) { RECT rcWindow; LONG lTop; GetWindowRect(App.Game.Layout.hwndAttributes,&rcWindow); MapWindowPoints(NULL,hWnd,(POINT *)&rcWindow,2); lTop = rcWindow.top; if (iDelta < 0) lTop -= App.Font.uFontHeight; else lTop += App.Font.uFontHeight; rcWindow.bottom = rcWindow.bottom-rcWindow.top; rcWindow.top = lTop; rcWindow.bottom += rcWindow.top; lTop = Game_ContainerTopOffset(lTop,&rcWindow); SetWindowPos(App.Game.Layout.hwndAttributes,NULL,0,lTop,0,0,SWP_NOSIZE|SWP_NOACTIVATE|SWP_NOOWNERZORDER|SWP_NOZORDER); return; } //--- WM_VSCROLL --- void Game_ContainerScroll(UINT uRequest) { SCROLLINFO scrollInfo; RECT rcAttributes; scrollInfo.cbSize = sizeof(SCROLLINFO); scrollInfo.fMask = SIF_ALL; GetScrollInfo(App.Game.Layout.hwndScrollbar,SB_CTL,&scrollInfo); switch(uRequest) { case SB_TOP: scrollInfo.nPos = scrollInfo.nMin; break; case SB_BOTTOM: scrollInfo.nPos = scrollInfo.nMax; break; case SB_LINEUP: scrollInfo.nPos -= 1; break; case SB_LINEDOWN: scrollInfo.nPos += 1; break; case SB_PAGEUP: scrollInfo.nPos -= scrollInfo.nPage; break; case SB_PAGEDOWN: scrollInfo.nPos += scrollInfo.nPage; break; case SB_THUMBTRACK: scrollInfo.nPos = scrollInfo.nTrackPos; break; } scrollInfo.fMask = SIF_POS; SetScrollInfo(App.Game.Layout.hwndScrollbar,SB_CTL,&scrollInfo,TRUE); GetScrollInfo(App.Game.Layout.hwndScrollbar,SB_CTL,&scrollInfo); GetWindowRect(App.Game.Layout.hwndAttributes,&rcAttributes); MapWindowPoints(NULL,App.Game.Layout.hwndContainer,(POINT *)&rcAttributes,2); if (rcAttributes.top != -scrollInfo.nPos) SetWindowPos(App.Game.Layout.hwndAttributes,NULL,0,-scrollInfo.nPos,0,0,SWP_NOSIZE|SWP_NOACTIVATE|SWP_NOOWNERZORDER|SWP_NOZORDER); return; } // «»»» Corrige la position des attributs si nécessaire «««««««««««««««««» // Parameters: // lTop - Top offset of hwndAttributes // rcChild - RECT of hwndAttributes relative to hwndContainer // // Return value: // Corrected top offset of hwndAttributes long Game_ContainerTopOffset(LONG lTop, RECT *rcChild) { RECT rcWindow; RECT rcContainer; if (!rcChild) { GetWindowRect(App.Game.Layout.hwndAttributes,&rcWindow); MapWindowPoints(NULL,App.Game.Layout.hwndContainer,(POINT *)&rcWindow,2); } GetClientRect(App.Game.Layout.hwndContainer,&rcContainer); if (rcContainer.bottom > rcChild->bottom-rcChild->top) return(0); // Fits entirely CopyRect(&rcWindow,rcChild); if (rcWindow.top > 0) return(0); if (rcWindow.bottom < rcContainer.bottom) return(-(rcChild->bottom-rcChild->top-rcContainer.bottom)); return(lTop); } // «»»» Taille et position de la scrollbar ««««««««««««««««««««««««««««««» void Game_ContainerScrollInfo(UINT fMask) { SCROLLINFO scrollInfo; RECT rcContainer; RECT rcAttributes; GetClientRect(App.Game.Layout.hwndContainer,&rcContainer); GetWindowRect(App.Game.Layout.hwndAttributes,&rcAttributes); MapWindowPoints(NULL,App.Game.Layout.hwndContainer,(POINT *)&rcAttributes,2); scrollInfo.cbSize = sizeof(SCROLLINFO); scrollInfo.fMask = fMask; scrollInfo.nMin = 0; scrollInfo.nMax = (rcAttributes.bottom-rcAttributes.top)-1; scrollInfo.nPage = rcContainer.bottom; scrollInfo.nPos = -rcAttributes.top; SetScrollInfo(App.Game.Layout.hwndScrollbar,SB_CTL,&scrollInfo,TRUE); return; } // ¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤ // // ¤¤¤ ¤¤¤ // // ¤¤¤ Attributs ¤¤¤ // // ¤¤¤ ¤¤¤ // // ¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤ // // «»»» Initialisation de la fenêtre ««««««««««««««««««««««««««««««««««««» LRESULT Game_AttributesCreate(HWND hWnd) { int W,H; int i; // NOTE: Positions are set in Game_PaintAttributes() W = MAIN_ATTR_BTN_WIDTH; H = App.Font.uFontHeight+12; // Attributs & points for (i = 0; i != 6; i++) if (!Game_CreateButton(hWnd,0,0,W,H,NULL,CTLID_ATTRIBUTES+i,&App.Game.Layout.hwndAttrBtn[i],BS_OWNERDRAW)) return(-1); for (i = 0; i != 4; i++) if (!Game_CreateButton(hWnd,0,0,W,H,NULL,CTLID_POINTS+i,&App.Game.Layout.hwndPointsBtn[i],BS_OWNERDRAW)) return(-1); // Vie & Armures if (!Game_CreateButton(hWnd,0,0,W,H,NULL,CTLID_LIFE,&App.Game.Layout.hwndLifeBtn,BS_OWNERDRAW)) return(-1); if (!Game_CreateButton(hWnd,0,0,W,H,NULL,CTLID_PHYSICAL,&App.Game.Layout.hwndPhysicalBtn,BS_OWNERDRAW)) return(-1); if (!Game_CreateButton(hWnd,0,0,W,H,NULL,CTLID_MAGICAL,&App.Game.Layout.hwndMagicalBtn,BS_OWNERDRAW)) return(-1); // Expérience if (!Game_CreateButton(hWnd,0,0,W,H,NULL,CTLID_EXPERIENCE,&App.Game.Layout.hwndExperienceBtn,BS_OWNERDRAW)) return(-1); if (!Game_CreateButton(hWnd,0,0,W,H,NULL,CTLID_NEXTLEVEL,&App.Game.Layout.hwndNextLevelBtn,BS_OWNERDRAW)) return(-1); return(0); } // «»»» Messages provenant de la fenêtre ««««««««««««««««««««««««««««««««» LRESULT Game_ProcessAttributesMessages(HWND hWnd, UINT uMsgId, WPARAM wParam, LPARAM lParam) { switch(uMsgId) { case WM_DRAWITEM: return(SendMessage(App.hWnd,WM_DRAWITEM,wParam,lParam)); case WM_PAINT: if (GetUpdateRect(hWnd,NULL,FALSE)) { HDC hDC; PAINTSTRUCT paintStruct; RECT rcWindow; hDC = BeginPaint(hWnd,&paintStruct); GetClientRect(hWnd,&rcWindow); FillRect(hDC,&rcWindow,GetSysColorBrush(COLOR_WINDOW)); Game_PaintAttributes(hWnd,hDC,&rcWindow); EndPaint(hWnd,&paintStruct); } break; case WM_MOVE: Game_ContainerScrollInfo(SIF_POS); break; case WM_SIZE: Game_AttributesResize(hWnd,LOWORD(lParam),HIWORD(lParam)); break; case WM_COMMAND: return(SendMessage(App.hWnd,WM_COMMAND,wParam,lParam)); default: return(DefWindowProc(hWnd,uMsgId,wParam,lParam)); } return(0); } // «»»» Redimension des attributs «««««««««««««««««««««««««««««««««««««««» void Game_AttributesResize(HWND hWnd, int iWidth, int iHeight) { RECT rcContainer; GetClientRect(App.Game.Layout.hwndContainer,&rcContainer); if (rcContainer.bottom < iHeight) { ShowWindow(App.Game.Layout.hwndScrollbar,SW_SHOW); Game_ContainerScrollInfo(SIF_PAGE|SIF_RANGE); } else ShowWindow(App.Game.Layout.hwndScrollbar,SW_HIDE); return; } // «»»» Fait en sorte que le bouton en focus soit visible «««««««««««««««» void Game_AttributesMakeFocusVisible() { if (IsWindow(App.Game.Layout.hwndAttributes)) { HWND hwndFocus; RECT rcControl; RECT rcContainer; RECT rcAttributes; LONG lTop; hwndFocus = GetFocus(); if (!hwndFocus) return; if (GetParent(hwndFocus) != App.Game.Layout.hwndAttributes) return; GetWindowRect(hwndFocus,&rcControl); GetClientRect(App.Game.Layout.hwndContainer,&rcContainer); GetWindowRect(App.Game.Layout.hwndAttributes,&rcAttributes); MapWindowPoints(NULL,App.Game.Layout.hwndContainer,(POINT *)&rcControl,2); MapWindowPoints(NULL,App.Game.Layout.hwndContainer,(POINT *)&rcAttributes,2); rcContainer.top += rcControl.bottom-rcControl.top; rcContainer.bottom -= rcControl.bottom-rcControl.top; lTop = rcAttributes.top; if (rcControl.top < rcContainer.top) // Above the visible area { lTop += rcContainer.top-rcControl.top; } else if (rcControl.bottom > rcContainer.bottom) // Below the visible area { lTop -= rcControl.bottom-rcContainer.bottom; } else return; rcAttributes.bottom = rcAttributes.bottom-rcAttributes.top; rcAttributes.top = lTop; rcAttributes.bottom += rcAttributes.top; lTop = Game_ContainerTopOffset(lTop,&rcAttributes); SetWindowPos(App.Game.Layout.hwndAttributes,NULL,0,lTop,0,0,SWP_NOSIZE|SWP_NOACTIVATE|SWP_NOOWNERZORDER|SWP_NOZORDER); } return; }
70e3dac4073d89b255d1a8d1b98c2259b46f18fe
971b2cea2d1c3001aadc8ca1a48110b7db1ed5f2
/deps/abc/src/bdd/reo/reo.h
3916ac067a05bbd0f7f7dcd51b02c09e9b120a70
[ "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
10,708
h
reo.h
/**CFile**************************************************************** FileName [reo.h] PackageName [REO: A specialized DD reordering engine.] Synopsis [External and internal declarations.] Author [Alan Mishchenko] Affiliation [UC Berkeley] Date [Ver. 1.0. Started - October 15, 2002.] Revision [$Id: reo.h,v 1.0 2002/15/10 03:00:00 alanmi Exp $] ***********************************************************************/ #ifndef ABC__bdd__reo__reo_h #define ABC__bdd__reo__reo_h #include <stdio.h> #include <stdlib.h> #include "bdd/extrab/extraBdd.h" //////////////////////////////////////////////////////////////////////// /// MACRO DEFINITIONS /// //////////////////////////////////////////////////////////////////////// ABC_NAMESPACE_HEADER_START // reordering parameters #define REO_REORDER_LIMIT 1.15 // determines the quality/runtime trade-off #define REO_QUAL_PAR 3 // the quality [1 = simple lower bound, 2 = strict, larger = heuristic] // internal parameters #define REO_CONST_LEVEL 30000 // the number of the constant level #define REO_TOPREF_UNDEF 30000 // the undefined top reference #define REO_CHUNK_SIZE 5000 // the number of units allocated at one time #define REO_COST_EPSILON 0.0000001 // difference in cost large enough so that it counted as an error #define REO_HIGH_VALUE 10000000 // a large value used to initialize some variables // interface parameters #define REO_ENABLE 1 // the value of the enable flag #define REO_DISABLE 0 // the value of the disable flag // the types of minimization currently supported typedef enum { REO_MINIMIZE_NODES, REO_MINIMIZE_WIDTH, // may not work for BDDs with complemented edges REO_MINIMIZE_APL } reo_min_type; //////////////////////////////////////////////////////////////////////// /// DATA STRUCTURES /// //////////////////////////////////////////////////////////////////////// typedef struct _reo_unit reo_unit; // the unit representing one DD node during reordering typedef struct _reo_plane reo_plane; // the set of nodes on one level typedef struct _reo_hash reo_hash; // the entry in the hash table typedef struct _reo_man reo_man; // the reordering manager typedef struct _reo_test reo_test; // struct _reo_unit { short lev; // the level of this node at the beginning short TopRef; // the top level from which this node is refed (used to update BDD width) short TopRefNew; // the new top level from which this node is refed (used to update BDD width) short n; // the number of incoming edges (similar to ref count in the BDD) int Sign; // the signature reo_unit * pE; // the pointer to the "else" branch reo_unit * pT; // the pointer to the "then" branch reo_unit * Next; // the link to the next one in the list double Weight; // the probability of traversing this node }; struct _reo_plane { int fSifted; // to mark the sifted variables int statsNodes; // the number of nodes in the current level int statsWidth; // the width on the current level double statsApl; // the sum of node probabilities on this level double statsCost; // the current cost is stored here double statsCostAbove; // the current cost is stored here double statsCostBelow; // the current cost is stored here reo_unit * pHead; // the pointer to the beginning of the unit list }; struct _reo_hash { int Sign; // signature of the current cache operation reo_unit * Arg1; // the first argument reo_unit * Arg2; // the second argument reo_unit * Arg3; // the third argument }; struct _reo_man { // these paramaters can be set by the API functions int fMinWidth; // the flag to enable reordering for minimum width int fMinApl; // the flag to enable reordering for minimum APL int fVerbose; // the verbosity level int fVerify; // the flag toggling verification int fRemapUp; // the flag to enable remapping int nIters; // the number of iterations of sifting to perform // parameters given by the user when reordering is called DdManager * dd; // the CUDD BDD manager int * pOrder; // the resulting variable order will be returned here // derived parameters int fThisIsAdd; // this flag is one if the function is the ADD int * pSupp; // the support of the given function int nSuppAlloc; // the max allowed number of support variables int nSupp; // the number of support variables int * pOrderInt; // the array storing the internal variable permutation double * pVarCosts; // other arrays int * pLevelOrder; // other arrays reo_unit ** pWidthCofs; // temporary storage for cofactors used during reordering for width // parameters related to cost int nNodesBeg; int nNodesCur; int nNodesEnd; int nWidthCur; int nWidthBeg; int nWidthEnd; double nAplCur; double nAplBeg; double nAplEnd; // mapping of the function into planes and back int * pMapToPlanes; // the mapping of var indexes into plane levels int * pMapToDdVarsOrig;// the mapping of plane levels into the original indexes int * pMapToDdVarsFinal;// the mapping of plane levels into the final indexes // the planes table reo_plane * pPlanes; int nPlanes; reo_unit ** pTops; int nTops; int nTopsAlloc; // the hash table reo_hash * HTable; // the table itself int nTableSize; // the size of the hash table int Signature; // the signature counter // the referenced node list int nNodesMaxAlloc; // this parameters determins how much memory is allocated DdNode ** pRefNodes; int nRefNodes; int nRefNodesAlloc; // unit memory management reo_unit * pUnitFreeList; reo_unit ** pMemChunks; int nMemChunks; int nMemChunksAlloc; int nUnitsUsed; // statistic variables int HashSuccess; int HashFailure; int nSwaps; // the number of swaps int nNISwaps; // the number of swaps without interaction }; // used to manipulate units #define Unit_Regular(u) ((reo_unit *)((ABC_PTRUINT_T)(u) & ~01)) #define Unit_Not(u) ((reo_unit *)((ABC_PTRUINT_T)(u) ^ 01)) #define Unit_NotCond(u,c) ((reo_unit *)((ABC_PTRUINT_T)(u) ^ (c))) #define Unit_IsConstant(u) ((int)((u)->lev == REO_CONST_LEVEL)) //////////////////////////////////////////////////////////////////////// /// FUNCTION DECLARATIONS /// //////////////////////////////////////////////////////////////////////// // ======================= reoApi.c ======================================== extern reo_man * Extra_ReorderInit( int nDdVarsMax, int nNodesMax ); extern void Extra_ReorderQuit( reo_man * p ); extern void Extra_ReorderSetMinimizationType( reo_man * p, reo_min_type fMinType ); extern void Extra_ReorderSetRemapping( reo_man * p, int fRemapUp ); extern void Extra_ReorderSetIterations( reo_man * p, int nIters ); extern void Extra_ReorderSetVerbosity( reo_man * p, int fVerbose ); extern void Extra_ReorderSetVerification( reo_man * p, int fVerify ); extern DdNode * Extra_Reorder( reo_man * p, DdManager * dd, DdNode * Func, int * pOrder ); extern void Extra_ReorderArray( reo_man * p, DdManager * dd, DdNode * Funcs[], DdNode * FuncsRes[], int nFuncs, int * pOrder ); // ======================= reoCore.c ======================================= extern void reoReorderArray( reo_man * p, DdManager * dd, DdNode * Funcs[], DdNode * FuncsRes[], int nFuncs, int * pOrder ); extern void reoResizeStructures( reo_man * p, int nDdVarsMax, int nNodesMax, int nFuncs ); // ======================= reoProfile.c ====================================== extern void reoProfileNodesStart( reo_man * p ); extern void reoProfileAplStart( reo_man * p ); extern void reoProfileWidthStart( reo_man * p ); extern void reoProfileWidthStart2( reo_man * p ); extern void reoProfileAplPrint( reo_man * p ); extern void reoProfileNodesPrint( reo_man * p ); extern void reoProfileWidthPrint( reo_man * p ); extern void reoProfileWidthVerifyLevel( reo_plane * pPlane, int Level ); // ======================= reoSift.c ======================================= extern void reoReorderSift( reo_man * p ); // ======================= reoSwap.c ======================================= extern double reoReorderSwapAdjacentVars( reo_man * p, int Level, int fMovingUp ); // ======================= reoTransfer.c =================================== extern reo_unit * reoTransferNodesToUnits_rec( reo_man * p, DdNode * F ); extern DdNode * reoTransferUnitsToNodes_rec( reo_man * p, reo_unit * pUnit ); // ======================= reoUnits.c ====================================== extern reo_unit * reoUnitsGetNextUnit(reo_man * p ); extern void reoUnitsRecycleUnit( reo_man * p, reo_unit * pUnit ); extern void reoUnitsRecycleUnitList( reo_man * p, reo_plane * pPlane ); extern void reoUnitsAddUnitToPlane( reo_plane * pPlane, reo_unit * pUnit ); extern void reoUnitsStopDispenser( reo_man * p ); // ======================= reoTest.c ======================================= extern void Extra_ReorderTest( DdManager * dd, DdNode * Func ); extern DdNode * Extra_ReorderCudd( DdManager * dd, DdNode * aFunc, int pPermuteReo[] ); extern int Extra_bddReorderTest( DdManager * dd, DdNode * bF ); extern int Extra_addReorderTest( DdManager * dd, DdNode * aF ); ABC_NAMESPACE_HEADER_END #endif //////////////////////////////////////////////////////////////////////// /// END OF FILE /// ////////////////////////////////////////////////////////////////////////
08df0d4cdb27f9278a96b95007c37ed17d970e2b
1873690f92fb432936397c24e5b900a31711c140
/include/bigendianuniversal.h
68e305d4bcf764f2733a5af82a7b5dc92ec7d54e
[ "Apache-2.0", "MIT", "LicenseRef-scancode-public-domain" ]
permissive
lemire/StronglyUniversalStringHashing
328ca976259228c717fbbfe032fdfa2ff02f35bb
a80e04fc75d34885b5c31ae714c4f24e5ea49be9
refs/heads/master
2023-08-18T23:59:54.136257
2020-10-15T13:26:08
2020-10-15T13:26:08
10,040,230
126
10
Apache-2.0
2020-10-15T13:03:02
2013-05-13T20:13:50
C++
UTF-8
C
false
false
20,078
h
bigendianuniversal.h
#ifndef BIGENDIANUNIVERSAL_H #define BIGENDIANUNIVERSAL_H // A family of hash functions from U to D is said to be // "epsilon-almost big-endian universal" when, for any x != y in U and // s < lg D, the probability that h(x) >> s = h(y) >> s is less than // 2^s * epsilon. These functions may be suitable for use in hash // tables when the most significant bits, rather than the least // significant bits, are used as the index into the table. // // The famous multiply-shift family from Z_{2^u} to Z_{2^d} of // { h_a : a \in Z_{2^u}, a odd } where h_a(x) is defined as (a * x) >> (u-d) // is 2^{1-d}-almost big-endian universal. // // By iterating this hash function over a string with words in // Z_{2^u}, we get an L*2^{1-d}-almost big-endian universal family, // where L is the maximum length of a string. #include <string.h> // Unsigned 128-bit integers typedef struct U128 { uint64_t hi, lo; } u128; // Multuply two uint64_ts and get the most significant 64 bits // of the result; Intel only. static inline uint64_t hi64mul(uint64_t x, uint64_t y) { uint64_t lo, hi; __asm__ ("mulq %3" : "=a,a" (lo), "=d,d" (hi) : "%0,0" (x), "r,m" (y)); return hi; } // Multiply two u128s, but don't compute the least significant 64 bits // or the most significant 128 bits. static inline u128 multHi128(u128 x, u128 y) { const u128 result = {x.hi * y.lo + x.lo * y.hi + hi64mul(x.lo, y.lo), 0}; return result; } // An L*2^{1-d} almost bigendian universal hash function on strings of // 64-bit words, producing a 64-bit output. uint64_t hornerHash(const void * randomSource, const uint64_t * x, const size_t length) { u128 h; memcpy(&h, randomSource, sizeof(u128)); // h must be odd: h.lo |= 1; // We treat the length as the first word in the string, ensuring // that no string is a prefix of any other. u128 accum = {length, x[0]}; accum = multHi128(h, accum); for (size_t i = 1; i < length; ++i) { // accum.hi holds the hash value we have accumulated so far. We // put the next word to hash into accum.lo to make one two-word // integer that we hash with h: accum.lo = x[i]; accum = multHi128(h, accum); } return accum.hi; } // Hashes two 64-bit words (newer and accum) down to one, // universally. h0 and h1 must be chosen uniformly at random. // // This method first rehashes `accum` using `h0` and `h1`. It is // essentially (accum * (h0 + (h1<<64))) >> 64, where all operations // are performed on 128-bit words. This is a variant on the // multiply-shift hashing in Dietzfelbinger's "Universal hashing and // k-wise independent random variables via integer arithmetic without // primes". It doesn't use the addition component. This makes it only // delta-universal, not strongly universal. However, that is enough so // that adding `newer` maintains the universailty, as has been noted // by many. static inline void univHash(const uint64_t h0, const uint64_t h1, const uint64_t newer, uint64_t *accum) { *accum = newer + *accum * h1 + hi64mul(*accum, h0); } // Horner's method can only dispatch one 128-bit multiplication at a // time, since each loop iteration depends on the one before // it. unrolledHorner changes the order in which the words are hashed // and can hash multiple words simultaneously, if the processor // supports it. #define DECLARE_UNROLLED_HORNER(MANY) \ uint64_t unrolledHorner##MANY(const void *randomSource, const uint64_t *x, \ const size_t length) { \ uint64_t accums[MANY]; \ accums[0] = length; \ accums[1] = x[1]; \ for (size_t i = 2; i < MANY; ++i) { \ accums[i] = (i < length) ? x[i] : 0; \ } \ size_t i = (length < MANY) ? length : MANY; \ const uint64_t *r64 = (const uint64_t *)randomSource; \ for (; i + MANY <= length; i += MANY) { \ for (size_t j = 0; j < MANY; ++j) { \ univHash(r64[0], r64[1], x[i + j], &accums[j]); \ } \ } \ for (size_t j = 0; i+j < length; j += 1) { \ univHash(r64[0], r64[1], x[i+j], &accums[j]); \ } \ for (size_t j = 1; j < MANY; ++j) { \ univHash(r64[0], r64[1], accums[j], &accums[0]); \ } \ return accums[0] * (r64[2] | ((uint64_t)1)); \ } DECLARE_UNROLLED_HORNER(3) DECLARE_UNROLLED_HORNER(4) DECLARE_UNROLLED_HORNER(5) DECLARE_UNROLLED_HORNER(6) DECLARE_UNROLLED_HORNER(7) DECLARE_UNROLLED_HORNER(8) DECLARE_UNROLLED_HORNER(9) // One other way to calculate a 64-bit hash value is to calculate two // 32-bit hash values. In order to make this almost big-endian // universal, we have to rehash these two 32-bit values with an // almost-big-endian universal function, too. // // This function is further from being big-endian universal, in that // its epsilon is larger. The two 32-bit hash values each have // collision probability approximately L*2^{-31}, so the probability // that they both collide is about L^2 * 2^{-62}, rather than // L*{2^-63} in the constructions above. This method is thus better // suited for shorter strings than longer ones. // // This function is unrolled in a manenr similar to unrolledHorner, // above. uint64_t twiceHorner32(const void * randomSource, const uint64_t * x, const size_t length) { u128 h; memcpy(&h, randomSource, sizeof(u128)); // h.lo and h.hi must be odd: h.lo |= 1; h.hi |= 1; if (1 == length) { const u128 tmp = {length, x[0]}; return multHi128(h, tmp).hi; } if (2 == length) { u128 tmp = {length, x[0]}; tmp = multHi128(h, tmp); tmp.lo = x[1]; return multHi128(h, tmp).hi; } u128 accums[4]; accums[0].hi = length; accums[1].hi = x[0]; accums[2].hi = x[1]; accums[3].hi = x[2]; size_t i = 3; // This is the main loop. for (; i + 3 < length; i += 4) { for (size_t j = 0; j < 4; ++j) { accums[j].lo = x[i+j] * h.lo; accums[j].hi *= h.hi; accums[j].hi &= 0xffffffff00000000ull; accums[j].hi |= accums[j].lo >> 32; } } // We might have 1, 2, or 3 words left over at the end that we // couldn't handle in our unrolled loop which could only do 4 at // once: for(; i < length; i += 1) { for (size_t j = 0; j < 1; ++j) { accums[j].lo = x[i+j] * h.lo; accums[j].hi *= h.hi; accums[j].hi &= 0xffffffff00000000ull; accums[j].hi |= accums[j].lo >> 32; } } // Finally, we combine all of the hash values we have already computed. for (size_t j = 1; j < 4; ++j) { accums[0].lo = accums[j].hi; accums[0] = multHi128(h, accums[0]); } return accums[0].hi; } // Fast universal hashing using the CLNH family: // Using the random words in `r64`, universally hash `data` down to 64 bits static inline uint64_t bigHashDown(const uint64_t *r64, const __m128i *data) { int64_t d64[2] = {_mm_extract_epi64(*data, 0), _mm_extract_epi64(*data, 1)}; uint64_t * u64 = (uint64_t *)d64; univHash(r64[0], r64[1], u64[0], &u64[1]); return u64[1]; } // Big-endian universally hash `data` with the random bits in `r64`. static inline uint64_t bie(const uint64_t r64, const uint64_t data) { return data * (r64 | 0x1ul); } // Hash universally `accum` and `data` using the random bits in `r128`. static inline void clCombine(const __m128i r128, __m128i *accum, const __m128i data) { *accum = _mm_xor_si128(*accum, r128); *accum = _mm_clmulepi64_si128(*accum, *accum, 1); *accum = _mm_xor_si128(*accum, data); } // Helper functions for hashing an array of __m128i `accum` and a // single __m128i `extra` down into `accum[0]` using the random bits // in `r128`. static inline void clArrayCombineExtra2(const __m128i r128, __m128i *accum, const __m128i extra) { clCombine(r128, &accum[0], extra); clCombine(r128, &accum[0], accum[1]); } static inline void clArrayCombineExtra3(const __m128i r128, __m128i *accum, const __m128i extra) { clCombine(r128, &accum[0], extra); clCombine(r128, &accum[1], accum[2]); clCombine(r128, &accum[0], accum[1]); } static inline void clArrayCombineExtra4(const __m128i r128, __m128i *accum, const __m128i extra) { for (size_t i = 0; i < 2; ++i) { clCombine(r128, &accum[i], accum[i + 2]); } clArrayCombineExtra2(r128, accum, extra); } static inline void clArrayCombineExtra5(const __m128i r128, __m128i *accum, const __m128i extra) { clCombine(r128, &accum[0], extra); for (size_t i = 1; i <= 2; ++i) { clCombine(r128, &accum[i], accum[i + 2]); } clArrayCombineExtra2(r128, accum, accum[2]); } static inline void clArrayCombineExtra6(const __m128i r128, __m128i *accum, const __m128i extra) { for (size_t i = 0; i < 3; ++i) { clCombine(r128, &accum[i], accum[i + 3]); } clArrayCombineExtra3(r128, accum, extra); } static inline void clArrayCombineExtra8(const __m128i r128, __m128i *accum, const __m128i extra) { for (size_t i = 0; i < 4; ++i) { clCombine(r128, &accum[i], accum[i + 4]); } clArrayCombineExtra4(r128, accum, extra); } static inline void clArrayCombineExtra9(const __m128i r128, __m128i *accum, const __m128i extra) { clCombine(r128, &accum[0], extra); for (size_t i = 1; i <= 4; ++i) { clCombine(r128, &accum[i], accum[i + 4]); } clArrayCombineExtra4(r128, accum, accum[4]); } static inline void clArrayCombineExtra10(const __m128i r128, __m128i *accum, const __m128i extra) { for (size_t i = 0; i < 5; ++i) { clCombine(r128, &accum[i], accum[i + 5]); } clArrayCombineExtra5(r128, accum, extra); } static inline void clArrayCombineExtra11(const __m128i r128, __m128i *accum, const __m128i extra) { clCombine(r128, &accum[0], extra); for (size_t i = 1; i <= 5; ++i) { clCombine(r128, &accum[i], accum[i + 5]); } clArrayCombineExtra5(r128, accum, accum[5]); } static inline void clArrayCombineExtra12(const __m128i r128, __m128i *accum, const __m128i extra) { for (size_t i = 0; i < 6; ++i) { clCombine(r128, &accum[i], accum[i + 6]); } clArrayCombineExtra6(r128, accum, extra); } // Iterated hashing using the CLNH family #define ITERATECL(MANY) \ uint64_t iterateCL##MANY(const void *randomSource, const uint64_t *x, \ const size_t length) { \ const uint64_t *r64 = &(((const uint64_t *)(randomSource))[2]); \ const __m128i *z = (const __m128i *)x; \ const size_t zlen = length / 2; \ __m128i accum[MANY]; \ for (size_t j = 0; j < MANY; ++j) { \ accum[j] = (j < zlen) ? _mm_lddqu_si128(&z[j]) : _mm_setzero_si128(); \ } \ size_t i = (zlen >= MANY) ? MANY : zlen; \ const __m128i r128 = _mm_lddqu_si128((const __m128i *)randomSource); \ for (; i + MANY <= zlen; i += MANY) { \ for (size_t j = 0; j < MANY; ++j) { \ clCombine(r128, &accum[j], _mm_lddqu_si128(&z[i + j])); \ } \ } \ for (size_t j = 0; j < MANY; ++j) { \ if (i + j < zlen) { \ clCombine(r128, &accum[j], _mm_lddqu_si128(&z[i + j])); \ } \ } \ clArrayCombineExtra##MANY( \ r128, accum, \ _mm_set_epi64x(length, (length & 1) ? x[length - 1] : 0)); \ const uint64_t bhd = bigHashDown(r64, &accum[0]); \ return bie(r64[2], bhd); \ } ITERATECL(8) ITERATECL(9) ITERATECL(10) ITERATECL(11) ITERATECL(12) #undef ITERATECL static inline __m128i clCombineFar(const __m128i r128, const __m128i x, const __m128i y) { __m128i result = _mm_xor_si128(x, r128); result = _mm_clmulepi64_si128(result, result, 1); result = _mm_xor_si128(result, y); return result; } // Unrolled Carter & Wegman tree-hash with clCombineFar as the // reducing function. This is basically "Badger - A Fast and Provably // Secure MAC", by Boesgaard et al. #define HALVE(MANY) \ static inline void halve##MANY(const __m128i r128, const __m128i *from, \ __m128i *to) { \ for (size_t i = 0; i < MANY; ++i) { \ to[i] = clCombineFar(r128, from[2 * i], from[2 * i + 1]); \ } \ } #define HALVE_LOAD(MANY) \ static inline void halveLoad##MANY(const __m128i r128, const __m128i *from, \ __m128i *to) { \ for (size_t i = 0; i < MANY; ++i) { \ to[i] = clCombineFar(r128, _mm_lddqu_si128(&from[2 * i]), \ _mm_lddqu_si128(&from[2 * i + 1])); \ } \ } #define TREECL(MANY) \ uint64_t treeCL##MANY(const void *randomSource, const uint64_t *x, \ const size_t length) { \ const __m128i *r128 = (const __m128i *)randomSource; \ const size_t depth = 64 - __builtin_clzll(1 + length); \ __m128i rLevel[64]; \ for (size_t i = 0; i < depth; ++i) { \ rLevel[i] = _mm_lddqu_si128(&r128[i]); \ } \ __m128i tree[64][2 * MANY]; \ size_t fill[64]; \ for (size_t i = 0; i < depth; ++i) { \ fill[i] = 0; \ } \ const __m128i *z = (const __m128i *)x; \ const size_t zlen = length / 2; \ size_t i = 0; \ for (; i + 2 * MANY <= zlen; i += 2 * MANY) { \ for (size_t j = 0; 2 * MANY == fill[j]; ++j) { \ halve##MANY(rLevel[j + 1], tree[j], &tree[j + 1][fill[j + 1]]); \ fill[j] = 0; \ fill[j + 1] += MANY; \ } \ halveLoad##MANY(rLevel[0], &z[i], &tree[0][fill[0]]); \ fill[0] += MANY; \ } \ size_t max_fill_level = depth - 1; \ for (; fill[max_fill_level] > 0; --max_fill_level) { \ } \ for (size_t j = 0; 2 * MANY == fill[j]; ++j) { \ halve##MANY(rLevel[j + 1], tree[j], &tree[j + 1][fill[j + 1]]); \ fill[j] = 0; \ fill[j + 1] += MANY; \ } \ for (; i < zlen; i += 2) { \ tree[0][fill[0]] = clCombineFar(rLevel[0], _mm_lddqu_si128(&z[i]), \ _mm_lddqu_si128(&z[i + 1])); \ ++fill[0]; \ } \ const __m128i final = \ _mm_set_epi64x(length, (length & 1) ? x[length - 1] : 0); \ tree[0][fill[0]] = \ (i < zlen) ? clCombineFar(rLevel[0], _mm_lddqu_si128(&z[i]), final) \ : final; \ ++fill[0]; \ i = 0; \ for (; (i < max_fill_level) || (fill[i] > 1); ++i) { \ size_t j = 0; \ for (; j + 2 <= fill[i]; j += 2) { \ tree[i + 1][fill[i + 1]] = \ clCombineFar(rLevel[i + 1], tree[i][j], tree[i][j + 1]); \ ++fill[i + 1]; \ } \ if (j < fill[i]) { \ tree[i + 1][fill[i + 1]] = tree[i][j]; \ ++fill[i + 1]; \ } \ } \ const uint64_t *r64 = (const uint64_t *)randomSource; \ r64 += 2 * MANY; \ const uint64_t bhd = bigHashDown(r64, &tree[i][0]); \ return bie(r64[2], bhd); \ } #define TREECLALL(MANY) HALVE(MANY) HALVE_LOAD(MANY) TREECL(MANY) TREECLALL(8) TREECLALL(9) TREECLALL(10) #endif // BIGENDIANUNIVERSAL_H
92d1dd99aad81cae96fa1485f8c38b11237722a7
e814383d36a10839104efaa4df277996ab220fa3
/3rd-party/romio341/mpi-io/wr_atalle.c
53a1be53f0752ecb9f11a63e91f6c2217325e272
[ "mpich2", "BSD-3-Clause-Open-MPI" ]
permissive
open-mpi/ompi
a1d7483ae1d83dd8fd8ae3ee95e832e0a0ee04e3
1edfdb025c4450f694600083ad871cf06c8d45cd
refs/heads/main
2023-09-01T01:30:02.040705
2023-08-29T17:32:18
2023-08-29T17:32:18
24,107,001
2,008
973
NOASSERTION
2023-09-14T20:59:26
2014-09-16T16:08:30
C
UTF-8
C
false
false
1,301
c
wr_atalle.c
/* * Copyright (C) by Argonne National Laboratory * See COPYRIGHT in top-level directory */ #include "mpioimpl.h" #ifdef HAVE_WEAK_SYMBOLS #if defined(HAVE_PRAGMA_WEAK) #pragma weak MPI_File_write_at_all_end = PMPI_File_write_at_all_end #elif defined(HAVE_PRAGMA_HP_SEC_DEF) #pragma _HP_SECONDARY_DEF PMPI_File_write_at_all_end MPI_File_write_at_all_end #elif defined(HAVE_PRAGMA_CRI_DUP) #pragma _CRI duplicate MPI_File_write_at_all_end as PMPI_File_write_at_all_end /* end of weak pragmas */ #elif defined(HAVE_WEAK_ATTRIBUTE) int MPI_File_write_at_all_end(MPI_File fh, const void *buf, MPI_Status * status) __attribute__ ((weak, alias("PMPI_File_write_at_all_end"))); #endif /* Include mapping from MPI->PMPI */ #define MPIO_BUILD_PROFILING #include "mpioprof.h" #endif /*@ MPI_File_write_at_all_end - Complete a split collective write using explicit offset Input Parameters: . fh - file handle (handle) . buf - initial address of buffer (choice) Output Parameters: . status - status object (Status) .N fortran @*/ int MPI_File_write_at_all_end(MPI_File fh, ROMIO_CONST void *buf, MPI_Status * status) { int error_code; static char myname[] = "MPI_FILE_WRITE_AT_ALL_END"; error_code = MPIOI_File_write_all_end(fh, buf, myname, status); return error_code; }
c32b80ce0e954511338e75021fa2d63fe7567d44
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
/sys/arch/zaurus/dev/ziic.c
9f91947b271f86a6e2311ebe2a5f5f7238915943
[]
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
5,660
c
ziic.c
/* $NetBSD: ziic.c,v 1.6 2021/08/07 16:19:08 thorpej Exp $ */ /*- * Copyright (c) 2011 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by NONAKA Kimihiro. * * 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. */ #include <sys/cdefs.h> __KERNEL_RCSID(0, "$NetBSD: ziic.c,v 1.6 2021/08/07 16:19:08 thorpej Exp $"); #include <sys/param.h> #include <sys/systm.h> #include <sys/device.h> #include <sys/bus.h> #include <sys/mutex.h> #include <dev/i2c/i2cvar.h> #include <arm/xscale/pxa2x0reg.h> #include <arm/xscale/pxa2x0var.h> #include <arm/xscale/pxa2x0_i2c.h> #ifdef PXAIIC_DEBUG #define DPRINTF(s) printf s #else #define DPRINTF(s) do { } while (/*CONSTCOND*/0) #endif struct pxaiic_softc { struct pxa2x0_i2c_softc sc_pxa_i2c; void * sc_ih; struct i2c_controller sc_i2c; }; static int pxaiic_match(device_t, cfdata_t, void *); static void pxaiic_attach(device_t, device_t, void *); CFATTACH_DECL_NEW(pxaiic, sizeof(struct pxaiic_softc), pxaiic_match, pxaiic_attach, NULL, NULL); static int pxaiic_acquire_bus(void *, int); static void pxaiic_release_bus(void *, int); static int pxaiic_send_start(void *, int); static int pxaiic_send_stop(void *, int); static int pxaiic_initiate_xfer(void *, uint16_t, int); static int pxaiic_read_byte(void *, uint8_t *, int); static int pxaiic_write_byte(void *, uint8_t, int); static int pxaiic_match(device_t parent, cfdata_t cf, void *aux) { struct pxaip_attach_args *pxa = aux; if (strcmp(cf->cf_name, pxa->pxa_name)) return 0; pxa->pxa_addr = PXA2X0_I2C_BASE; pxa->pxa_size = PXA2X0_I2C_SIZE; return 1; } static void pxaiic_attach(device_t parent, device_t self, void *aux) { struct pxaiic_softc *sc = device_private(self); struct pxa2x0_i2c_softc *psc = &sc->sc_pxa_i2c; struct pxaip_attach_args *pxa = aux; struct i2cbus_attach_args iba; aprint_normal(": I2C controller\n"); aprint_naive("\n"); psc->sc_dev = self; psc->sc_iot = pxa->pxa_iot; psc->sc_addr = pxa->pxa_addr; psc->sc_size = pxa->pxa_size; psc->sc_flags = 0; if (pxa2x0_i2c_attach_sub(psc)) { aprint_error_dev(self, "unable to attach PXA I2C controller\n"); return; } #if 0 mutex_init(&sc->sc_intr_lock, MUTEX_DEFAULT, IPL_TTY); sc->sc_ih = pxa2x0_intr_establish(PXA2X0_INT_I2C, IPL_TTY, pxa2x0_i2c_intr, &psc); if (sc->sc_ih == NULL) { aprint_error_dev(self, "unable to establish intr\n"); return; /* XXX: mutex_destroy, bus_space_unmap */ } #endif /* Initialize i2c_controller */ iic_tag_init(&sc->sc_i2c); sc->sc_i2c.ic_cookie = sc; sc->sc_i2c.ic_acquire_bus = pxaiic_acquire_bus; sc->sc_i2c.ic_release_bus = pxaiic_release_bus; sc->sc_i2c.ic_send_start = pxaiic_send_start; sc->sc_i2c.ic_send_stop = pxaiic_send_stop; sc->sc_i2c.ic_initiate_xfer = pxaiic_initiate_xfer; sc->sc_i2c.ic_read_byte = pxaiic_read_byte; sc->sc_i2c.ic_write_byte = pxaiic_write_byte; memset(&iba, 0, sizeof(iba)); iba.iba_tag = &sc->sc_i2c; config_found(psc->sc_dev, &iba, iicbus_print, CFARGS_NONE); } static int pxaiic_acquire_bus(void *cookie, int flags) { struct pxaiic_softc *sc = cookie; struct pxa2x0_i2c_softc *psc = &sc->sc_pxa_i2c; pxa2x0_i2c_open(psc); return 0; } static void pxaiic_release_bus(void *cookie, int flags) { struct pxaiic_softc *sc = cookie; struct pxa2x0_i2c_softc *psc = &sc->sc_pxa_i2c; pxa2x0_i2c_close(psc); } static int pxaiic_send_start(void *cookie, int flags) { struct pxaiic_softc *sc = cookie; struct pxa2x0_i2c_softc *psc = &sc->sc_pxa_i2c; return pxa2x0_i2c_send_start(psc, flags); } static int pxaiic_send_stop(void *cookie, int flags) { struct pxaiic_softc *sc = cookie; struct pxa2x0_i2c_softc *psc = &sc->sc_pxa_i2c; return pxa2x0_i2c_send_stop(psc, flags); } static int pxaiic_initiate_xfer(void *cookie, uint16_t addr, int flags) { struct pxaiic_softc *sc = cookie; struct pxa2x0_i2c_softc *psc = &sc->sc_pxa_i2c; return pxa2x0_i2c_initiate_xfer(psc, addr, flags); } static int pxaiic_read_byte(void *cookie, uint8_t *bytep, int flags) { struct pxaiic_softc *sc = cookie; struct pxa2x0_i2c_softc *psc = &sc->sc_pxa_i2c; return pxa2x0_i2c_read_byte(psc, bytep, flags); } static int pxaiic_write_byte(void *cookie, uint8_t byte, int flags) { struct pxaiic_softc *sc = cookie; struct pxa2x0_i2c_softc *psc = &sc->sc_pxa_i2c; return pxa2x0_i2c_write_byte(psc, byte, flags); }
abb24a872bb4c27cba776aa8e574803a552f5030
10a8580aa44d33b7458429023c00de8c01ceda98
/axiom/tests/test_guid.c
757831c8a1e627c87444db56d0fe4392d0f80655
[ "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
846
c
test_guid.c
/* * Copyright 2020 New Relic Corporation. All rights reserved. * SPDX-License-Identifier: Apache-2.0 */ #include "nr_axiom.h" #include "nr_guid.h" #include "util_memory.h" #include "tlib_main.h" static void test_create(void) { char* guid; nr_random_t* rnd = nr_random_create(); nr_random_seed(rnd, 345345); guid = nr_guid_create(NULL); tlib_pass_if_str_equal("NULL random", guid, "0000000000000000"); nr_free(guid); guid = nr_guid_create(rnd); tlib_pass_if_str_equal("guid creation", guid, "078ad44c1960eab7"); nr_free(guid); guid = nr_guid_create(rnd); tlib_pass_if_str_equal("repeat guid creation", guid, "11da3087c4400533"); nr_free(guid); nr_random_destroy(&rnd); } tlib_parallel_info_t parallel_info = {.suggested_nthreads = 2, .state_size = 0}; void test_main(void* p NRUNUSED) { test_create(); }
f13569e40023dfe77feaa145dad900204507340c
9de0cec678bc4a3bec2b4adabef9f39ff5b4afac
/PWGLF/SPECTRA/ChargedHadrons/dNdPt/macros/AddTask_yelmardb_Unified.C
90b3b613b4e0a63cdedf16191f3b94afc581361b
[]
permissive
alisw/AliPhysics
91bf1bd01ab2af656a25ff10b25e618a63667d3e
5df28b2b415e78e81273b0d9bf5c1b99feda3348
refs/heads/master
2023-08-31T20:41:44.927176
2023-08-31T14:51:12
2023-08-31T14:51:12
61,661,378
129
1,150
BSD-3-Clause
2023-09-14T18:48:45
2016-06-21T19:31:29
C++
UTF-8
C
false
false
7,213
c
AddTask_yelmardb_Unified.C
#include <array> AlidNdPtUnifiedAnalysisTask* anAddTask(Int_t cutModeLow=100, Int_t cutModeHigh=105, TString controll = "") // cut variation for studdy of cut systematics (cutMode == 100 - 119) and Matching Eff (cutMode == 2100 - 2199) // controll = "vz10" for vz<10 cut { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr){ Error("anAddTask.C", "No analysis manager found."); return 0; } // Switch off all AliInfo (too much output!!!) AliLog::SetGlobalLogLevel(AliLog::kError); mgr->SetDebugLevel(0); TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD" Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0); char taskName[100] = ""; AlidNdPtUnifiedAnalysisTask* task125 = NULL; for(Int_t cutMode = cutModeLow; cutMode < cutModeHigh; cutMode++){ sprintf(taskName, "dNdPt_cutMode_%d", cutMode); AlidNdPtUnifiedAnalysisTask *task = new AlidNdPtUnifiedAnalysisTask(Form("AlidNdPtUnifiedAnalysisTask_%d", cutMode)); task125 = task; task->SetUseMC(hasMC); if(type.Contains("ESD")) task->SetUseESD(); else task->SetUseAOD(); task->SetUseMultiplicity(kFALSE); task->SetTriggerMask(AliVEvent::kINT7); task->SelectCollisionCandidates(AliVEvent::kINT7); // kINT7 or kMB Int_t multNbins = 100; Double_t binsMult[101]; for (int i=0; i<=multNbins; i++) { binsMult[i] = -0.5 + i; } binsMult[100] = 100.; task->SetBinsMultCent(multNbins,binsMult); // change pt binning const Int_t ptNbins = 81; Double_t bins[82] = {0.0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0, 3.2, 3.4, 3.6, 3.8, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 18.0, 20.0, 22.0, 24.0, 26.0, 28.0, 30.0, 32.0, 34.0, 36.0, 40.0, 45.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0, 110.0, 120.0, 130.0, 140.0, 150.0, 160.0, 180.0, 200.0}; Double_t* binsPt = new Double_t[82]; for (int i=0; i<82; i++) {binsPt[i] = bins[i];} task->SetBinsPt(ptNbins-1, binsPt); task->SetBinsPtReso(ptNbins-1, binsPt); task->SetMinEta(-0.8); task->SetMaxEta(0.8); task->SetMinPt(0.15); ///TOF pileup, kTRUE only for Matching efficiency studies task->SetTOFbunchCrossing(kFALSE); task->SetMeanXYZv(0.0,0.0,0.0); task->SetSigmaMeanXYZv(1.0,1.0,10.0); task->SetZvtx(10.); task->Set2015data(kTRUE); //only p-Pb 2013!!! /// Quality cuts for tracks if(cutMode != 122) { // TPC task->SetTPCRefit(kTRUE); task->SetRatioCrossedRowsOverFindableClustersTPC(0.8); task->SetMaxchi2perTPCclu(4.); task->SetFractionSharedClustersTPC(0.4); // ITS task->SetITSRefit(kTRUE); task->SetClusterReqITS(kTRUE); task->SetMaxchi2perITSclu(36.); // primary selection task->SetSigmaToVertex(kFALSE); task->SetDCAtoVertexZ(2.0); task->SetDCAtoVertexXYPtDep("0.0182+0.0350/pt^1.01"); task->SetKinkDaughters(kFALSE); task->SetDCAtoVertex2D(kFALSE); task->SetMaxChi2TPCConstrained(36.); task->SetMinLenghtInActiveZoneTPC(0); task->SetGeometricalCut(kTRUE,3,130,1.5,0.85,0.7); ///if kTRUE comment CrossedRowsTPC cut //task->SetMinCrossedRowsTPC(120); } ///Switch Low/High to study systematics uncertanties if(cutMode==101){task->SetDCAtoVertexZ(1.0); } if(cutMode==102){task->SetDCAtoVertexZ(5.0); } if(cutMode==103){task->SetDCAtoVertexXYPtDep("0.0104+0.0200/pt^1.01");} if(cutMode==104){task->SetDCAtoVertexXYPtDep("0.0260+0.0500/pt^1.01");} if(cutMode==105){task->SetRatioCrossedRowsOverFindableClustersTPC(0.7);} if(cutMode==106){task->SetRatioCrossedRowsOverFindableClustersTPC(0.9);} if(cutMode==107){task->SetFractionSharedClustersTPC(0.2);} if(cutMode==108){task->SetFractionSharedClustersTPC(1.0);} if(cutMode==109){task->SetMaxchi2perTPCclu(3); } if(cutMode==110){task->SetMaxchi2perTPCclu(5); } if(cutMode==111){task->SetMaxchi2perITSclu(25.); } if(cutMode==112){task->SetMaxchi2perITSclu(49.); } if(cutMode==113){task->SetClusterReqITS(kFALSE);} if(cutMode==114){task->SetGeometricalCut(kTRUE,4,130,1.5,0.85,0.7); } if(cutMode==115){task->SetGeometricalCut(kTRUE,2,130,1.5,0.85,0.7); } if(cutMode==116){task->SetGeometricalCut(kTRUE,3,140,1.5,0.85,0.7); } if(cutMode==117){task->SetGeometricalCut(kTRUE,3,120,1.5,0.85,0.7); } if(cutMode==118){task->SetMaxChi2TPCConstrained(25.); } if(cutMode==119){task->SetMaxChi2TPCConstrained(49.); } ///event cuts study if(cutMode == 120) {task->SetZvtx(5.);} if(cutMode == 121) {task->SetZvtx(15.);} ///event cut for trigger efficieny if(cutMode == 122) {task->SetZvtx(30.);} ///secondary scaling study if(cutMode == 123) { // TPC // task->SetTPCRefit(kTRUE); task->SetRatioCrossedRowsOverFindableClustersTPC(0.8); task->SetMaxchi2perTPCclu(4); task->SetFractionSharedClustersTPC(0.4); task->SetGeometricalCut(kTRUE,3,130,1.5,0.85,0.7); // default // // primary selection // task->SetDCAtoVertex2D(kFALSE); task->SetSigmaToVertex(kFALSE); task->SetDCAtoVertexZ(2.0); task->SetKinkDaughters(kFALSE); } ///Matching Efficiency /* if(cutMode==200) { /// Calculate matching efficiency: TPC only with Crossed Rows task->SetTPCRefit(kTRUE); task->SetDCAtoVertexZ(3.2); task->SetDCAtoVertexXY(2.4); task->SetGeometricalCut(kTRUE,3,130,1.5,0.85,0.7); task->SetRatioCrossedRowsOverFindableClustersTPC(0.8); task->SetFractionSharedClustersTPC(0.4); task->SetMaxchi2perTPCclu(4.0); task->SetITSRefit(kFALSE); task->SetClusterReqITS(kFALSE); } ///Calculate matching efficiency: TPC + ITS with Crossed Rows if (cutMode==201){ task->SetTPCRefit(kTRUE); task->SetDCAtoVertexZ(3.2); task->SetDCAtoVertexXY(2.4); task->SetGeometricalCut(kTRUE,3,130,1.5,0.85,0.7); task->SetRatioCrossedRowsOverFindableClustersTPC(0.8); task->SetFractionSharedClustersTPC(0.4); task->SetMaxchi2perTPCclu(4.0); task->SetITSRefit(kTRUE); task->SetClusterReqITS(kTRUE); } ///Calculate matching efficiency: TPC + ITS without SPD hit with Crossed Rows if (cutMode==202){ task->SetTPCRefit(kTRUE); task->SetDCAtoVertexZ(3.2); task->SetDCAtoVertexXY(2.4); task->SetGeometricalCut(kTRUE,3,130,1.5,0.85,0.7); task->SetRatioCrossedRowsOverFindableClustersTPC(0.8); task->SetFractionSharedClustersTPC(0.4); task->SetMaxchi2perTPCclu(4.0); task->SetITSRefit(kTRUE); task->SetClusterReqITS(kFALSE); }*/ mgr->AddTask(task); AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer(); AliAnalysisDataContainer *coutput = mgr->CreateContainer(taskName, TList::Class(), AliAnalysisManager::kOutputContainer, "AnalysisResults.root"); mgr->ConnectInput(task, 0, cinput); mgr->ConnectOutput(task, 1, coutput); } return task125; }
80ffd78593db7e0d4c8e9452627d690acdf10942
035660e8cc10571ebbd0d4393fef063bb7eb98f6
/src/overlays/actors/ovl_Dm_An/z_dm_an.h
c1e85d3eb105a668b91c69470292ee4b6a17b364
[]
no_license
zeldaret/mm
f163a5e7c4314105777369fa7671ce9c2a99922a
4ae00e909e74044f05155683b49d2561f91de7ba
refs/heads/master
2023-08-06T07:22:04.912966
2023-08-04T20:36:03
2023-08-04T20:36:03
247,875,852
915
328
null
2023-09-14T11:48:59
2020-03-17T04:03:07
C
UTF-8
C
false
false
1,074
h
z_dm_an.h
#ifndef Z_DM_AN_H #define Z_DM_AN_H #include "global.h" #include "objects/object_an1/object_an1.h" struct DmAn; typedef void (*DmAnActionFunc)(struct DmAn*, PlayState*); typedef struct DmAn { /* 0x000 */ Actor actor; /* 0x144 */ SkelAnime skelAnime; /* 0x188 */ DmAnActionFunc actionFunc; /* 0x18C */ Vec3f unk_18C; /* 0x18C */ Vec3f unk_194; /* 0x1A4 */ Vec3s unk_1A4; /* 0x1A4 */ Vec3s unk_1AA; /* 0x1B0 */ Vec3s jointTable[OBJECT_AN1_LIMB_MAX]; /* 0x22E */ Vec3s morphTable[OBJECT_AN1_LIMB_MAX]; /* 0x2AC */ s8 unk_2AC; /* 0x2AD */ s8 unk_2AD; /* 0x2AE */ u16 unk_2AE; /* 0x2B0 */ u8 cueId; /* 0x2B4 */ Actor* unk_2B4; /* 0x2B8 */ s16 unk_2B8; /* 0x2BA */ s16 unk_2BA; /* 0x2BC */ s16 unk_2BC; /* 0x2BE */ s16 unk_2BE; /* 0x2C0 */ s16 unk_2C0; /* 0x2C2 */ s16 unk_2C2; /* 0x2C4 */ s16 unk_2C4; /* 0x2C8 */ s32 animIndex; /* 0x2CC */ s32 prevAnimIndex; /* 0x2D0 */ s32 isCutscenePlaying; /* 0x2D4 */ s32 didAnimChangeInCs; } DmAn; // size = 0x2D8 #endif // Z_DM_AN_H
a883f17b59dcdce0c9f52c23753c57c67691762c
b04663400b05fd638e41f3d7f61953c514d835ed
/driver/driver.c
30ad1ca613c930ce1b9210d096478875f038800f
[]
permissive
LiteOS/LiteOS_Lab
0ee3edc08eb9d4c9ea5b52099da307adf1c06bfd
187e628b3f151515d920801b402bf38a19eee98c
refs/heads/iot-device-sdk-tiny
2023-09-04T16:22:21.579294
2023-04-25T03:09:46
2023-04-25T03:09:46
154,946,914
141
125
BSD-3-Clause
2022-08-25T09:12:56
2018-10-27T09:25:01
C
UTF-8
C
false
false
18,727
c
driver.c
/*---------------------------------------------------------------------------- * Copyright (c) <2018>, <Huawei Technologies Co., Ltd> * All rights reserved. * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written * permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- * Notice of Export Control Law * =============================================== * Huawei LiteOS may be subject to applicable export control laws and regulations, which might * include those applicable to Huawei LiteOS of U.S. and the country in which you are located. * Import, export and usage of Huawei LiteOS in any manner by you shall be in compliance with such * applicable export control laws and regulations. *---------------------------------------------------------------------------*/ #include <string.h> #include <stdio.h> #include <stdlib.h> #include "driver.h" #include <sys/fcntl.h> #define cn_driv_status_initialized (1<<0) #define cn_driv_status_opend (1<<1) //define the error type has happened in the driver typedef enum { en_dev_err_none = 0, //no err happened en_dev_err_init, //call bsp open function failed en_dev_err_open, //call bsp init function failed }en_dev_error_type; struct driv_cb { void *nxt; //add the deice to device list void *pri; //bsp developed para const char *name; //the device name int flagmask; //copy from the register const los_driv_op_t *op; //operation method unsigned int drivstatus; //show the state here like init or something like this los_dev_t devlst; //the open list,support the multi open //following member used for the debug size_t total_write; //how many data has been sent size_t total_read; //how many data has received size_t opencounter; //reference counter unsigned int errno; //the last errno has happend }; typedef struct { osal_mutex_t lock; //used to lock the devlst struct driv_cb *drivlst; //all the dev will be added to the list unsigned int drivnum; }los_driv_module; static los_driv_module s_los_driv_module ; //manage all the driver here //used this function to find a dev static struct driv_cb *__driv_match(const char *name) { struct driv_cb *ret = NULL; ret = s_los_driv_module.drivlst; while(NULL != ret) { if(0 == strcmp(name,ret->name)) { break; } ret = ret->nxt; } return ret; } /******************************************************************************* function :bsp developer use this function to add a device to the system parameters : instruction :NULL if failed else return the device handle *******************************************************************************/ los_driv_t los_driv_register(os_driv_para_t *para) { struct driv_cb *driv = NULL; if((NULL == para->name)||(NULL == para->op)) { goto EXIT_PARAS; } driv = osal_malloc(sizeof(struct driv_cb)); if(NULL == driv) { goto EXIT_MALLOC; } (void) memset(driv,0,sizeof(struct driv_cb)); //do the member initialize driv->name = para->name; driv->op = para->op; driv->pri = para->pri; driv->flagmask = para->flag; //add it to the device list if no device with the same name exsit if(false == osal_mutex_lock(s_los_driv_module.lock)) { goto EXIT_MUTEX; } if(NULL != __driv_match(para->name)) { goto EXIT_EXISTED; } driv->nxt = s_los_driv_module.drivlst; s_los_driv_module.drivlst = driv; (void) osal_mutex_unlock(s_los_driv_module.lock); s_los_driv_module.drivnum++; return driv; EXIT_EXISTED: (void) osal_mutex_unlock(s_los_driv_module.lock); EXIT_MUTEX: osal_free(driv); driv = NULL; EXIT_MALLOC: EXIT_PARAS: return driv; } /******************************************************************************* function :bsp developer use this function to remove a device from the system parameters : instruction :if the device has been refered,then will fail here *******************************************************************************/ bool_t los_driv_unregister(const char *name) { struct driv_cb *tmp = NULL; struct driv_cb *pre = NULL; bool_t ret = false; if(NULL == name) { return ret; } if(osal_mutex_lock(s_los_driv_module.lock)) { tmp = s_los_driv_module.drivlst; pre = NULL; while(NULL != tmp) { if( 0 == strcmp(name,tmp->name)) { break; } pre = tmp; tmp = tmp->nxt; } if(NULL != tmp) //find the device here { if(pre == NULL) { s_los_driv_module.drivlst = tmp->nxt; } else { pre->nxt = tmp->nxt; } osal_free(tmp); ret = true; s_los_driv_module.drivnum--; } (void) osal_mutex_unlock(s_los_driv_module.lock); } return ret; } /******************************************************************************* function :bsp developer use this function to notify the application any event has happened parameters : instruction :not implement yet,we will do it as the asynchronize call *******************************************************************************/ bool_t los_driv_event(los_driv_t driv,unsigned int event,void *para) { return false; } #ifdef __CC_ARM /* ARM C Compiler ,like keil,options for linker:--keep *.o(osdriv)*/ extern unsigned int osdriv$$Base; extern unsigned int osdriv$$Limit; #elif defined(__GNUC__) extern unsigned int __osdriv_start; extern unsigned int __osdriv_end; #else #error("unknown compiler here"); #endif static void osdriv_load_static(void){ os_driv_para_t *para; unsigned int num = 0; unsigned int i = 0; #if defined (__CC_ARM) //you could add other compiler like this num = ((unsigned int)&osdriv$$Limit-(unsigned int)&osdriv$$Base)/sizeof(os_driv_para_t); para = (os_driv_para_t *) &osdriv$$Base; #elif defined(__GNUC__) para = (os_driv_para_t *)&__osdriv_start; num = ((unsigned int )(uintptr_t)&__osdriv_end - (unsigned int)(uintptr_t)&__osdriv_start)/sizeof(os_driv_para_t); #endif for(i =0;i<num;i++) { (void) los_driv_register(para); para++; } return; } /******************************************************************************* function :the device module entry parameters : instruction :call this function to initialize the device module here load the static init from section os_device *******************************************************************************/ bool_t los_driv_init() { bool_t ret = false; ret = osal_mutex_create(&s_los_driv_module.lock); if(false == ret) { goto EXIT_MUTEX; } //load all the static device init osdriv_load_static(); EXIT_MUTEX: return ret; } //here we define the data structure which used by the driv application apis struct dev_cb { void *nxt; //used by the open lst void *driv; //which attached dri here int openflag; //here means the open state here unsigned int offset; //the following for the debug unsigned int readbytes; unsigned int writebytes; }; /******************************************************************************* function :open the device with the specified name parameters : instruction :if first open the device,then will call the init function if exsited *******************************************************************************/ los_dev_t los_dev_open (const char *name,unsigned int flag) { bool_t opret = true; //operate result struct driv_cb *driv = NULL; //the driver attached struct dev_cb *dev = NULL; //the device opened if ( NULL == name ) { goto EXIT_PARAERR; } dev = osal_malloc(sizeof(struct dev_cb)); if (NULL == dev) { goto EXIT_MEMERR; } (void) memset(dev,0,sizeof(struct dev_cb)); opret = osal_mutex_lock(s_los_driv_module.lock); if(false == opret) { goto EXIT_MUTEXERR; } driv = __driv_match(name); if(NULL == driv) { goto EXIT_DRIVERR; } //WE DON'T CARE TOO MUCH ABOUT THE RD AND WR FLAG,MAY BE TODO IT IN THE NEXT VERSION HERE if((O_EXCL & (unsigned int )driv->flagmask) && (NULL != driv->devlst)) { goto EXIT_EXCLERR; } if((0 == (driv->drivstatus & cn_driv_status_initialized)) && \ (NULL != driv->op->init)) { opret = driv->op->init(driv->pri); if(false == opret) { driv->errno = en_dev_err_init; goto EXIT_INITERR; } driv->drivstatus |= cn_driv_status_initialized; } if(NULL != driv->op->open) { opret = driv->op->open(driv->pri,flag); if(false == opret) { driv->errno = en_dev_err_open; goto EXIT_OPENERR; } } //reach here means all the initialize is ok //add the dev to the list of the drive and attach the driv to the device driv->opencounter++; dev->nxt = driv->devlst; driv->devlst = dev; dev->driv = driv; dev->openflag = flag; (void) osal_mutex_unlock(s_los_driv_module.lock); return dev; EXIT_OPENERR: EXIT_INITERR: EXIT_EXCLERR: EXIT_DRIVERR: (void) osal_mutex_unlock(s_los_driv_module.lock); EXIT_MUTEXERR: osal_free(dev); dev = NULL; EXIT_MEMERR: EXIT_PARAERR: return dev; } /******************************************************************************* function :close the device of opened parameters :handle returned by open instruction : *******************************************************************************/ bool_t los_dev_close (los_dev_t dev) { bool_t ret = false; struct dev_cb *devcb = NULL; struct dev_cb *tmp = NULL; struct driv_cb *driv = NULL; if ( NULL == dev ) { goto EXIT_PARAERR; } devcb = dev; if(false == osal_mutex_lock(s_los_driv_module.lock)) { goto EXIT_MUTEXERR; } //deattach the dev from the driv driv = devcb->driv; if(NULL == driv) { goto EXIT_DRIVERR; } if(devcb == driv->devlst) { driv->devlst = devcb->nxt; } else { tmp = driv->devlst; while(NULL != tmp) { if(tmp->nxt == devcb) { tmp->nxt = devcb->nxt; break; } tmp = tmp->nxt; } if(NULL == tmp) { goto EXIT_DETACHERR; } } if(NULL != driv->op->close) { driv->op->close(driv->pri); } if((NULL == driv->devlst) && (NULL != driv->op->deinit)) { driv->op->deinit(driv->pri); driv->drivstatus &= (~cn_driv_status_initialized); } osal_free(dev); driv->opencounter--; (void) osal_mutex_unlock(s_los_driv_module.lock); ret = true; EXIT_DETACHERR: EXIT_DRIVERR: (void) osal_mutex_unlock(s_los_driv_module.lock); EXIT_MUTEXERR: EXIT_PARAERR: return ret; } /******************************************************************************* function :use this function to read data from the device parameters :dev,returned by the los_dev_open function offet:from where to read,only used for storage device buf:used to storage the data len:the length of the buf timeout:the waittime if no data current instruction :how many data has been read to the buf *******************************************************************************/ ssize_t los_dev_read (los_dev_t dev,size_t offset, void *buf,size_t len,uint32_t timeout) { ssize_t ret = 0; struct dev_cb *devcb; struct driv_cb *drivcb; if((NULL != dev)&&(NULL != buf)&&(0 != len)) { devcb = dev; if((0 == ((uint32_t)devcb->openflag & O_WRONLY))) { drivcb = devcb->driv; if((NULL != drivcb->op)&&(NULL != drivcb->op->read)) { ret = drivcb->op->read( drivcb->pri,offset,buf,len,timeout); if(ret > 0) { drivcb->total_read += ret; } } } } return ret; } /******************************************************************************* function :use this function to write data to the device parameters :dev,returned by the los_dev_open function offset: from where to write,only used for storage device buf:the data to be written len:the length of the buf timeout:the waittime if no data current instruction :how many data has been written to the device *******************************************************************************/ ssize_t los_dev_write (los_dev_t dev,size_t offset,const void *buf,size_t len, uint32_t timeout) { ssize_t ret = 0; struct dev_cb *devcb; struct driv_cb *drivcb; if((NULL != dev) && (NULL != buf) && (len != 0)) { devcb = dev; if((((uint32_t)devcb->openflag) & O_WRONLY) || (((uint32_t)devcb->openflag) & O_RDWR)) { drivcb = devcb->driv; if((NULL != drivcb->op)&&(NULL != drivcb->op->write)) { ret = drivcb->op->write( drivcb->pri,offset,buf,len,timeout); if(ret > 0) { drivcb->total_write += ret; } } } } return ret; } /******************************************************************************* function :use this function to control the device parameters :dev,returned by the los_dev_open function cmd, must compatible with bsp develop para,used with cmd, its length and format depend on the bsp develop instruction :ctrol true or false *******************************************************************************/ bool_t los_dev_ioctl (los_dev_t dev,unsigned int cmd,void *para,int paralen) { bool_t ret = false; struct dev_cb *devcb; struct driv_cb *drivcb; if(NULL != dev) { devcb = dev; drivcb = devcb->driv; if((NULL != drivcb->op)&&(NULL != drivcb->op->ioctl)) { ret = drivcb->op->ioctl( drivcb->pri,cmd,para,paralen); } } return ret; } /******************************************************************************* function :use this function to set the buffer current position,like lseek parameters :dev,returned by the los_dev_open function offset, refer to the lseek fromwhere, refer to the lseek instruction :return the current write/read position if success, else -1 *******************************************************************************/ off_t los_dev_seek (los_dev_t dev,off_t offset,int fromwhere) { off_t ret = -1; struct dev_cb *devcb; struct driv_cb *drivcb; if(NULL != dev) { devcb = dev; drivcb = devcb->driv; if((NULL != drivcb->op)&&(NULL != drivcb->op->seek)) { ret = drivcb->op->seek( drivcb->pri,offset,fromwhere); } } return ret; } //the following function should be implement by the vfs, //this is very important for the multi io operation, like the select epoll and so on //bool_t los_dev_upara_set (los_dev_t dev,void *para); //void* los_dev_upara_get (los_dev_t dev); //export some shell for the driver debug #ifdef CONFIG_SHELL_ENABLE #include <shell.h> //use this function to show all the driver infomation static int __driv_show_shell(int argc,const char *argv[]) { struct driv_cb *driv; if(osal_mutex_lock(s_los_driv_module.lock)) { link_printf("%s:total %d drivers\n\r",__FUNCTION__,s_los_driv_module.drivnum); if(s_los_driv_module.drivnum != 0) //print all the driver { link_printf("%-16s %-8s %-8s %-8s %-8s %-8s %-8s\r\n",\ "drivername","flagmask","status","writbyte","readbyte","open","errno"); driv = s_los_driv_module.drivlst; while(NULL != driv) { link_printf("%-16s %08x %08x %08x %08x %08x %08x\r\n",driv->name,driv->flagmask,\ driv->drivstatus,driv->total_write,driv->total_read,driv->opencounter,driv->errno); driv=driv->nxt; } } (void) osal_mutex_unlock(s_los_driv_module.lock); } return 0; } OSSHELL_EXPORT_CMD(__driv_show_shell,"devlst","devlst"); #endif ///< end for CONFIG_SHELL_ENABLE
95d5cfee8c174406f5e078a051efc6178f6a0c8a
f9e7d65cb784c01a0200145ba8d289afe41d4a56
/chip/stm32/adc-stm32f0.c
d900cbc5147ac91c69312f2571c0e92cd2376fe9
[ "BSD-3-Clause" ]
permissive
FrameworkComputer/EmbeddedController
ad7086769e87d0a4179eae96a7c9ff5e383ff54e
f6d6b927eed71550d3475411cfc3e59abe5cef2a
refs/heads/hx20-hx30
2023-08-08T20:45:10.621169
2023-05-26T07:03:59
2023-05-26T07:03:59
447,021,040
846
48
BSD-3-Clause
2023-05-26T07:04:59
2022-01-12T00:11:14
C
UTF-8
C
false
false
8,121
c
adc-stm32f0.c
/* Copyright 2014 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "adc.h" #include "adc_chip.h" #include "clock.h" #include "common.h" #include "console.h" #include "dma.h" #include "hooks.h" #include "hwtimer.h" #include "registers.h" #include "task.h" #include "timer.h" #include "util.h" struct mutex adc_lock; struct adc_profile_t { /* Register values. */ uint32_t cfgr1_reg; uint32_t cfgr2_reg; uint32_t smpr_reg; /* Default Sampling Rate */ uint32_t ier_reg; /* DMA config. */ const struct dma_option *dma_option; /* Size of DMA buffer, in units of ADC_CH_COUNT. */ int dma_buffer_size; }; #ifdef CONFIG_ADC_PROFILE_SINGLE static const struct dma_option dma_single = { STM32_DMAC_ADC, (void *)&STM32_ADC_DR, STM32_DMA_CCR_MSIZE_32_BIT | STM32_DMA_CCR_PSIZE_32_BIT, }; #ifndef CONFIG_ADC_SAMPLE_TIME #define CONFIG_ADC_SAMPLE_TIME STM32_ADC_SMPR_13_5_CY #endif static const struct adc_profile_t profile = { /* Sample all channels once using DMA */ .cfgr1_reg = STM32_ADC_CFGR1_OVRMOD, .cfgr2_reg = 0, .smpr_reg = CONFIG_ADC_SAMPLE_TIME, .ier_reg = 0, .dma_option = &dma_single, .dma_buffer_size = 1, }; #endif #ifdef CONFIG_ADC_PROFILE_FAST_CONTINUOUS #ifndef CONFIG_ADC_SAMPLE_TIME #define CONFIG_ADC_SAMPLE_TIME STM32_ADC_SMPR_1_5_CY #endif static const struct dma_option dma_continuous = { STM32_DMAC_ADC, (void *)&STM32_ADC_DR, STM32_DMA_CCR_MSIZE_32_BIT | STM32_DMA_CCR_PSIZE_32_BIT | STM32_DMA_CCR_CIRC, }; static const struct adc_profile_t profile = { /* Sample all channels continuously using DMA */ .cfgr1_reg = STM32_ADC_CFGR1_OVRMOD | STM32_ADC_CFGR1_CONT | STM32_ADC_CFGR1_DMACFG, .cfgr2_reg = 0, .smpr_reg = CONFIG_ADC_SAMPLE_TIME, /* Fire interrupt at end of sequence. */ .ier_reg = STM32_ADC_IER_EOSEQIE, .dma_option = &dma_continuous, /* Double-buffer our samples. */ .dma_buffer_size = 2, }; #endif static void adc_init(const struct adc_t *adc) { /* * If clock is already enabled, and ADC module is enabled * then this is a warm reboot and ADC is already initialized. */ if (STM32_RCC_APB2ENR & BIT(9) && (STM32_ADC_CR & STM32_ADC_CR_ADEN)) return; /* Enable ADC clock */ clock_enable_module(MODULE_ADC, 1); /* check HSI14 in RCC ? ON by default */ /* ADC calibration (done with ADEN = 0) */ STM32_ADC_CR = STM32_ADC_CR_ADCAL; /* set ADCAL = 1, ADC off */ /* wait for the end of calibration */ while (STM32_ADC_CR & STM32_ADC_CR_ADCAL) ; /* Single conversion, right aligned, 12-bit */ STM32_ADC_CFGR1 = profile.cfgr1_reg; /* clock is ADCCLK (ADEN must be off when writing this reg) */ STM32_ADC_CFGR2 = profile.cfgr2_reg; /* * ADC enable (note: takes 4 ADC clocks between end of calibration * and setting ADEN). */ STM32_ADC_CR = STM32_ADC_CR_ADEN; while (!(STM32_ADC_ISR & STM32_ADC_ISR_ADRDY)) STM32_ADC_CR = STM32_ADC_CR_ADEN; } static void adc_configure(int ain_id, enum stm32_adc_smpr sample_rate) { /* Sampling time */ if (sample_rate == STM32_ADC_SMPR_DEFAULT || sample_rate >= STM32_ADC_SMPR_COUNT) STM32_ADC_SMPR = profile.smpr_reg; else STM32_ADC_SMPR = STM32_ADC_SMPR_SMP(sample_rate); /* Select channel to convert */ STM32_ADC_CHSELR = BIT(ain_id); /* Disable DMA */ STM32_ADC_CFGR1 &= ~STM32_ADC_CFGR1_DMAEN; } #ifdef CONFIG_ADC_WATCHDOG static int watchdog_ain_id; static int watchdog_delay_ms; static void adc_continuous_read(int ain_id) { adc_configure(ain_id, STM32_ADC_SMPR_DEFAULT); /* CONT=1 -> continuous mode on */ STM32_ADC_CFGR1 |= STM32_ADC_CFGR1_CONT; /* Start continuous conversion */ STM32_ADC_CR |= BIT(2); /* ADSTART */ } static void adc_continuous_stop(void) { /* Stop on-going conversion */ STM32_ADC_CR |= BIT(4); /* ADSTP */ /* Wait for conversion to stop */ while (STM32_ADC_CR & BIT(4)) ; /* CONT=0 -> continuous mode off */ STM32_ADC_CFGR1 &= ~STM32_ADC_CFGR1_CONT; } static void adc_interval_read(int ain_id, int interval_ms) { adc_configure(ain_id, STM32_ADC_SMPR_DEFAULT); /* EXTEN=01 -> hardware trigger detection on rising edge */ STM32_ADC_CFGR1 = (STM32_ADC_CFGR1 & ~STM32_ADC_CFGR1_EXTEN_MASK) | STM32_ADC_CFGR1_EXTEN_RISE; /* EXTSEL=TRG3 -> Trigger on TIM3_TRGO */ STM32_ADC_CFGR1 = (STM32_ADC_CFGR1 & ~STM32_ADC_CFGR1_TRG_MASK) | STM32_ADC_CFGR1_TRG3; __hw_timer_enable_clock(TIM_ADC, 1); /* Upcounter, counter disabled, update event only on underflow */ STM32_TIM_CR1(TIM_ADC) = 0x0004; /* TRGO on update event */ STM32_TIM_CR2(TIM_ADC) = 0x0020; STM32_TIM_SMCR(TIM_ADC) = 0x0000; /* Auto-reload value */ STM32_TIM_ARR(TIM_ADC) = interval_ms & 0xffff; /* Set prescaler to tick per millisecond */ STM32_TIM_PSC(TIM_ADC) = (clock_get_freq() / MSEC) - 1; /* Start counting */ STM32_TIM_CR1(TIM_ADC) |= 1; /* Start ADC conversion */ STM32_ADC_CR |= BIT(2); /* ADSTART */ } static void adc_interval_stop(void) { /* EXTEN=00 -> hardware trigger detection disabled */ STM32_ADC_CFGR1 &= ~STM32_ADC_CFGR1_EXTEN_MASK; /* Set ADSTP to clear ADSTART */ STM32_ADC_CR |= BIT(4); /* ADSTP */ /* Wait for conversion to stop */ while (STM32_ADC_CR & BIT(4)) ; /* Stop the timer */ STM32_TIM_CR1(TIM_ADC) &= ~0x1; } static int adc_watchdog_enabled(void) { return STM32_ADC_CFGR1 & STM32_ADC_CFGR1_AWDEN; } static int adc_enable_watchdog_no_lock(void) { /* Select channel */ STM32_ADC_CFGR1 = (STM32_ADC_CFGR1 & ~STM32_ADC_CFGR1_AWDCH_MASK) | (watchdog_ain_id << 26); adc_configure(watchdog_ain_id, STM32_ADC_SMPR_DEFAULT); /* Clear AWD interrupt flag */ STM32_ADC_ISR = 0x80; /* Set Watchdog enable bit on a single channel */ STM32_ADC_CFGR1 |= STM32_ADC_CFGR1_AWDEN | STM32_ADC_CFGR1_AWDSGL; /* Enable interrupt */ STM32_ADC_IER |= STM32_ADC_IER_AWDIE; if (watchdog_delay_ms) adc_interval_read(watchdog_ain_id, watchdog_delay_ms); else adc_continuous_read(watchdog_ain_id); return EC_SUCCESS; } int adc_enable_watchdog(int ain_id, int high, int low) { int ret; mutex_lock(&adc_lock); watchdog_ain_id = ain_id; /* Set thresholds */ STM32_ADC_TR = ((high & 0xfff) << 16) | (low & 0xfff); ret = adc_enable_watchdog_no_lock(); mutex_unlock(&adc_lock); return ret; } static int adc_disable_watchdog_no_lock(void) { if (watchdog_delay_ms) adc_interval_stop(); else adc_continuous_stop(); /* Clear Watchdog enable bit */ STM32_ADC_CFGR1 &= ~STM32_ADC_CFGR1_AWDEN; return EC_SUCCESS; } int adc_disable_watchdog(void) { int ret; mutex_lock(&adc_lock); ret = adc_disable_watchdog_no_lock(); mutex_unlock(&adc_lock); return ret; } int adc_set_watchdog_delay(int delay_ms) { int resume_watchdog = 0; mutex_lock(&adc_lock); if (adc_watchdog_enabled()) { resume_watchdog = 1; adc_disable_watchdog_no_lock(); } watchdog_delay_ms = delay_ms; if (resume_watchdog) adc_enable_watchdog_no_lock(); mutex_unlock(&adc_lock); return EC_SUCCESS; } #else /* CONFIG_ADC_WATCHDOG */ static int adc_watchdog_enabled(void) { return 0; } static int adc_enable_watchdog_no_lock(void) { return 0; } static int adc_disable_watchdog_no_lock(void) { return 0; } #endif /* CONFIG_ADC_WATCHDOG */ int adc_read_channel(enum adc_channel ch) { const struct adc_t *adc = adc_channels + ch; int value; int restore_watchdog = 0; mutex_lock(&adc_lock); adc_init(adc); if (adc_watchdog_enabled()) { restore_watchdog = 1; adc_disable_watchdog_no_lock(); } adc_configure(adc->channel, adc->sample_rate); /* Clear flags */ STM32_ADC_ISR = 0xe; /* Start conversion */ STM32_ADC_CR |= BIT(2); /* ADSTART */ /* Wait for end of conversion */ while (!(STM32_ADC_ISR & BIT(2))) ; /* read converted value */ value = STM32_ADC_DR; if (restore_watchdog) adc_enable_watchdog_no_lock(); mutex_unlock(&adc_lock); return value * adc->factor_mul / adc->factor_div + adc->shift; } void adc_disable(void) { STM32_ADC_CR |= STM32_ADC_CR_ADDIS; /* * Note that the ADC is not in OFF state immediately. * Once the ADC is effectively put into OFF state, * STM32_ADC_CR_ADDIS bit will be cleared by hardware. */ }
fafc3f6598c1e4498086d297ecc7835d90e37932
0f389714669bea5a68bea1acef38782f44d7d0c1
/balong_flash.c
a7aee1daed1a1a94a56c8b2e42e888acb677b06f
[]
no_license
forth32/balongflash
033ad61af0190584497d990fe044db9a35214da2
bf43faa4b5f60205a7950b8ecee5fe81a3226239
refs/heads/master
2021-12-01T16:57:20.415312
2021-11-11T09:55:00
2021-11-11T09:55:00
33,260,841
180
86
null
2021-11-11T09:55:01
2015-04-01T17:04:58
C
UTF-8
C
false
false
7,461
c
balong_flash.c
#include <stdio.h> #include <stdint.h> #ifndef WIN32 #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <strings.h> #include <termios.h> #include <unistd.h> #include <arpa/inet.h> #else #include <windows.h> #include "getopt.h" #include "printf.h" #include "buildno.h" #endif #include "hdlcio.h" #include "ptable.h" #include "flasher.h" #include "util.h" #include "signver.h" #include "zlib.h" // флаг ошибки структуры файла unsigned int errflag=0; // флаг цифровой подписи int gflag=0; // флаг типа прошивки int dflag=0; // тип прошивки из заголовка файла int dload_id=-1; //*********************************************** //* Таблица разделов //*********************************************** struct ptb_t ptable[120]; int npart=0; // число разделов в таблице //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ int main(int argc, char* argv[]) { unsigned int opt; int res; FILE* in; char devname[50] = ""; unsigned int mflag=0,eflag=0,rflag=0,sflag=0,nflag=0,kflag=0,fflag=0; unsigned char fdir[40]; // каталог для мультифайловой прошивки // разбор командной строки while ((opt = getopt(argc, argv, "d:hp:mersng:kf")) != -1) { switch (opt) { case 'h': printf("\n Утилита предназначена для прошивки модемов на чипсете Balong V7\n\n\ %s [ключи] <имя файла для загрузки или имя каталога с файлами>\n\n\ Допустимы следующие ключи:\n\n" #ifndef WIN32 "-p <tty> - последовательный порт для общения с загрузчиком (по умолчанию /dev/ttyUSB0)\n" #else "-p # - номер последовательного порта для общения с загрузчиком (например, -p8)\n" " если ключ -p не указан, производится автоопределение порта\n" #endif "-n - режим мультифайловой прошивки из указанного каталога\n\ -g# - установка режима цифровой подписи\n\ -gl - описание параметров\n\ -gd - запрет автоопределения подписи\n\ -m - вывести карту файла прошивки и завершить работу\n\ -e - разобрать файл прошивки на разделы без заголовков\n\ -s - разобрать файл прошивки на разделы с заголовками\n\ -k - не перезагружать модем по окончании прошивки\n\ -r - принудительно перезагрузить модем без прошивки разделов\n\ -f - прошить даже при наличии ошибок CRC в исходном файле\n\ -d# - установка типа прошивки (DLOAD_ID, 0..7), -dl - список типов\n\ \n",argv[0]); return 0; case 'p': strcpy(devname,optarg); break; case 'm': mflag=1; break; case 'n': nflag=1; break; case 'f': fflag=1; break; case 'r': rflag=1; break; case 'k': kflag=1; break; case 'e': eflag=1; break; case 's': sflag=1; break; case 'g': gparm(optarg); break; case 'd': dparm(optarg); break; case '?': case ':': return -1; } } printf("\n Программа для прошивки устройств на Balong-чипсете, V3.0.%i, (c) forth32, 2015, GNU GPLv3",BUILDNO); #ifdef WIN32 printf("\n Порт для Windows 32bit (c) rust3028, 2016"); #endif printf("\n--------------------------------------------------------------------------------------------------\n"); if (eflag&sflag) { printf("\n Ключи -s и -e несовместимы\n"); return -1; } if (kflag&rflag) { printf("\n Ключи -k и -r несовместимы\n"); return -1; } if (nflag&(eflag|sflag|mflag)) { printf("\n Ключ -n несовместим с ключами -s, -m и -e\n"); return -1; } // ------ перезагрузка без указания файла //-------------------------------------------- if ((optind>=argc)&rflag) goto sio; // Открытие входного файла //-------------------------------------------- if (optind>=argc) { if (nflag) printf("\n - Не указан каталог с файлами\n"); else printf("\n - Не указано имя файла для загрузки, используйте ключ -h для подсказки\n"); return -1; } if (nflag) // для -n - просто копируем префикс strncpy(fdir,argv[optind],39); else { // для однофайловых операций in=fopen(argv[optind],"rb"); if (in == 0) { printf("\n Ошибка открытия %s",argv[optind]); return -1; } } // Поиск разделов внутри файла if (!nflag) { findparts(in); show_fw_info(); } // Поиск файлов прошивок в указанном каталоге else findfiles(fdir); //------ Режим вывода карты файла прошивки if (mflag) show_file_map(); // выход по ошибкам CRC if (!fflag && errflag) { printf("\n\n! Входной файл содержит ошибки - завершаем работу\n"); return -1; } //------- Режим разрезания файла прошивки if (eflag|sflag) { fwsplit(sflag); printf("\n"); return 0; } sio: //--------- Основной режим - запись прошивки //-------------------------------------------- // Настройка SIO open_port(devname); // Определяем режим порта и версию dload-протокола res=dloadversion(); if (res == -1) return -2; if (res == 0) { printf("\n Модем уже находится в HDLC-режиме"); goto hdlc; } // Если надо, отправляем команду цифровой подписи if (gflag != -1) send_signver(); // Входим в HDLC-режим usleep(100000); enter_hdlc(); // Вошли в HDLC //------------------------------ hdlc: // получаем версию протокола и идентификатор устройства protocol_version(); dev_ident(); printf("\n----------------------------------------------------\n"); if ((optind>=argc)&rflag) { // перезагрузка без указания файла restart_modem(); exit(0); } // Записываем всю флешку flash_all(); printf("\n"); port_timeout(1); // выходим из режима HDLC и перезагружаемся if (rflag || !kflag) restart_modem(); // выход из HDLC без перезагрузки else leave_hdlc(); }
140a33de0b1df8f8a064d9d368a36b0fba49e017
2af283f8a587bcc3d2a744f7d86007ab2428f9bc
/src/mqtt/examples/mqtt_example.c
2aa24ba8febaf7d8dfcf63d1e7b96f2c48e2d43f
[ "Apache-2.0" ]
permissive
aliyun/iotkit-embedded
bfda585c8a5db3fea215ad15fe7699cebde1dfc8
3010153fb53865ce3925f8e43900adbbfa358874
refs/heads/v3.0.1
2023-03-12T23:14:04.902446
2022-11-11T07:12:05
2022-11-11T09:01:43
106,364,205
544
289
Apache-2.0
2023-08-22T06:00:04
2017-10-10T03:30:08
C
UTF-8
C
false
false
7,315
c
mqtt_example.c
#include "dev_sign_api.h" #include "mqtt_api.h" char DEMO_PRODUCT_KEY[IOTX_PRODUCT_KEY_LEN + 1] = {0}; char DEMO_DEVICE_NAME[IOTX_DEVICE_NAME_LEN + 1] = {0}; char DEMO_DEVICE_SECRET[IOTX_DEVICE_SECRET_LEN + 1] = {0}; void *HAL_Malloc(uint32_t size); void HAL_Free(void *ptr); void HAL_Printf(const char *fmt, ...); int HAL_GetProductKey(char product_key[IOTX_PRODUCT_KEY_LEN + 1]); int HAL_GetDeviceName(char device_name[IOTX_DEVICE_NAME_LEN + 1]); int HAL_GetDeviceSecret(char device_secret[IOTX_DEVICE_SECRET_LEN]); uint64_t HAL_UptimeMs(void); int HAL_Snprintf(char *str, const int len, const char *fmt, ...); #define EXAMPLE_TRACE(fmt, ...) \ do { \ HAL_Printf("%s|%03d :: ", __func__, __LINE__); \ HAL_Printf(fmt, ##__VA_ARGS__); \ HAL_Printf("%s", "\r\n"); \ } while(0) void example_message_arrive(void *pcontext, void *pclient, iotx_mqtt_event_msg_pt msg) { iotx_mqtt_topic_info_t *topic_info = (iotx_mqtt_topic_info_pt) msg->msg; switch (msg->event_type) { case IOTX_MQTT_EVENT_PUBLISH_RECEIVED: /* print topic name and topic message */ EXAMPLE_TRACE("Message Arrived:"); EXAMPLE_TRACE("Topic : %.*s", topic_info->topic_len, topic_info->ptopic); EXAMPLE_TRACE("Payload: %.*s", topic_info->payload_len, topic_info->payload); EXAMPLE_TRACE("\n"); break; default: break; } } int example_subscribe(void *handle) { int res = 0; const char *fmt = "/%s/%s/user/get"; char *topic = NULL; int topic_len = 0; topic_len = strlen(fmt) + strlen(DEMO_PRODUCT_KEY) + strlen(DEMO_DEVICE_NAME) + 1; topic = HAL_Malloc(topic_len); if (topic == NULL) { EXAMPLE_TRACE("memory not enough"); return -1; } memset(topic, 0, topic_len); HAL_Snprintf(topic, topic_len, fmt, DEMO_PRODUCT_KEY, DEMO_DEVICE_NAME); res = IOT_MQTT_Subscribe(handle, topic, IOTX_MQTT_QOS0, example_message_arrive, NULL); if (res < 0) { EXAMPLE_TRACE("subscribe failed"); HAL_Free(topic); return -1; } HAL_Free(topic); return 0; } int example_publish(void *handle) { int res = 0; const char *fmt = "/%s/%s/user/get"; char *topic = NULL; int topic_len = 0; char *payload = "{\"message\":\"hello!\"}"; topic_len = strlen(fmt) + strlen(DEMO_PRODUCT_KEY) + strlen(DEMO_DEVICE_NAME) + 1; topic = HAL_Malloc(topic_len); if (topic == NULL) { EXAMPLE_TRACE("memory not enough"); return -1; } memset(topic, 0, topic_len); HAL_Snprintf(topic, topic_len, fmt, DEMO_PRODUCT_KEY, DEMO_DEVICE_NAME); res = IOT_MQTT_Publish_Simple(0, topic, IOTX_MQTT_QOS0, payload, strlen(payload)); if (res < 0) { EXAMPLE_TRACE("publish failed, res = %d", res); HAL_Free(topic); return -1; } HAL_Free(topic); return 0; } void example_event_handle(void *pcontext, void *pclient, iotx_mqtt_event_msg_pt msg) { EXAMPLE_TRACE("msg->event_type : %d", msg->event_type); } /* * NOTE: About demo topic of /${productKey}/${deviceName}/user/get * * The demo device has been configured in IoT console (https://iot.console.aliyun.com) * so that its /${productKey}/${deviceName}/user/get can both be subscribed and published * * We design this to completely demonstrate publish & subscribe process, in this way * MQTT client can receive original packet sent by itself * * For new devices created by yourself, pub/sub privilege also requires being granted * to its /${productKey}/${deviceName}/user/get for successfully running whole example */ int main(int argc, char *argv[]) { void *pclient = NULL; int res = 0; int loop_cnt = 0; iotx_mqtt_param_t mqtt_params; HAL_GetProductKey(DEMO_PRODUCT_KEY); HAL_GetDeviceName(DEMO_DEVICE_NAME); HAL_GetDeviceSecret(DEMO_DEVICE_SECRET); EXAMPLE_TRACE("mqtt example"); /* Initialize MQTT parameter */ /* * Note: * * If you did NOT set value for members of mqtt_params, SDK will use their default values * If you wish to customize some parameter, just un-comment value assigning expressions below * **/ memset(&mqtt_params, 0x0, sizeof(mqtt_params)); /** * * MQTT connect hostname string * * MQTT server's hostname can be customized here * * default value is ${productKey}.iot-as-mqtt.cn-shanghai.aliyuncs.com */ /* mqtt_params.host = "something.iot-as-mqtt.cn-shanghai.aliyuncs.com"; */ /** * * MQTT connect port number * * TCP/TLS port which can be 443 or 1883 or 80 or etc, you can customize it here * * default value is 1883 in TCP case, and 443 in TLS case */ /* mqtt_params.port = 1883; */ /** * * MQTT request timeout interval * * MQTT message request timeout for waiting ACK in MQTT Protocol * * default value is 2000ms. */ /* mqtt_params.request_timeout_ms = 2000; */ /** * * MQTT clean session flag * * If CleanSession is set to 0, the Server MUST resume communications with the Client based on state from * the current Session (as identified by the Client identifier). * * If CleanSession is set to 1, the Client and Server MUST discard any previous Session and Start a new one. * * default value is 0. */ /* mqtt_params.clean_session = 0; */ /** * * MQTT keepAlive interval * * KeepAlive is the maximum time interval that is permitted to elapse between the point at which * the Client finishes transmitting one Control Packet and the point it starts sending the next. * * default value is 60000. */ /* mqtt_params.keepalive_interval_ms = 60000; */ /** * * MQTT write buffer size * * Write buffer is allocated to place upstream MQTT messages, MQTT client will be limitted * to send packet no longer than this to Cloud * * default value is 1024. * */ /* mqtt_params.write_buf_size = 1024; */ /** * * MQTT read buffer size * * Write buffer is allocated to place downstream MQTT messages, MQTT client will be limitted * to recv packet no longer than this from Cloud * * default value is 1024. * */ /* mqtt_params.read_buf_size = 1024; */ /** * * MQTT event callback function * * Event callback function will be called by SDK when it want to notify user what is happening inside itself * * default value is NULL, which means PUB/SUB event won't be exposed. * */ mqtt_params.handle_event.h_fp = example_event_handle; pclient = IOT_MQTT_Construct(&mqtt_params); if (NULL == pclient) { EXAMPLE_TRACE("MQTT construct failed"); return -1; } res = example_subscribe(pclient); if (res < 0) { IOT_MQTT_Destroy(&pclient); return -1; } while (1) { if (0 == loop_cnt % 20) { example_publish(pclient); } IOT_MQTT_Yield(pclient, 200); loop_cnt += 1; } return 0; }
ac218acef416d24a925f367ac2e2e5e523afe120
5f86fc385c7dcfcb5b166cdea7c8b13057b8bb5f
/common/tdx/collateral.h
edceb641011c4bd7b633472e9ac2f652ee451c96
[ "MIT" ]
permissive
openenclave/openenclave
54a38e12d9aa73357d9f438a07cd8c07ffe5e6df
cdeb95c1ec163117de409295333b6b2702013e08
refs/heads/master
2023-08-14T16:43:32.049533
2023-07-21T15:58:54
2023-07-21T15:58:54
101,804,230
800
372
MIT
2023-09-12T20:26:02
2017-08-29T20:31:38
C
UTF-8
C
false
false
584
h
collateral.h
// Copyright (c) Open Enclave SDK contributors. // Licensed under the MIT License. #ifndef _OE_COMMON_TDX_COLLATERAL_H #define _OE_COMMON_TDX_COLLATERAL_H #include <openenclave/internal/crypto/cert.h> #include <openenclave/internal/report.h> OE_EXTERNC_BEGIN oe_result_t oe_get_tdx_quote_verification_collateral( const uint8_t* p_quote, uint32_t quote_size, uint8_t** pp_quote_collateral, uint32_t* p_collateral_size); oe_result_t oe_free_tdx_quote_verification_collateral( uint8_t* p_quote_collateral); OE_EXTERNC_END #endif // _OE_COMMON_TDX_COLLATERAL_H
3f26d109e42808a3a74e4257a288f8f39667e014
99bdb3251fecee538e0630f15f6574054dfc1468
/bsp/acm32/acm32f0x0-nucleo/libraries/HAL_Driver/Inc/HAL_SPI.h
42748e5a70eee11418d9846f5617e0d0e46b2d61
[ "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
11,358
h
HAL_SPI.h
/* ****************************************************************************** * @file HAL_SPI.h * @version V1.0.0 * @date 2020 * @brief Header file of SPI HAL module. ****************************************************************************** */ #ifndef __HAL_SPI_H__ #define __HAL_SPI_H__ #include "ACM32Fxx_HAL.h" /**************** Bit definition for SPI_CTL register **************************/ #define SPI_CTL_CS_TIME (BIT11|BIT12|BIT13|BIT14|BIT15|BIT16|BIT17|BIT18) #define SPI_CTL_CS_FILTER BIT10 #define SPI_CTL_CS_RST BIT9 #define SPI_CTL_SLAVE_EN BIT8 #define SPI_CTL_IO_MODE BIT7 #define SPI_CTL_X_MODE (BIT6|BIT5) #define SPI_CTL_LSB_FIRST BIT4 #define SPI_CTL_CPOL BIT3 #define SPI_CTL_CPHA BIT2 #define SPI_CTL_SFILTER BIT1 #define SPI_CTL_MST_MODE BIT0 /**************** Bit definition for SPI_TX_CTL register ***********************/ #define SPI_TX_CTL_DMA_LEVEL (BIT4|BIT5|BIT6|BIT7) #define SPI_TX_CTL_DMA_LEVEL_3 BIT7 #define SPI_TX_CTL_DMA_LEVEL_2 BIT6 #define SPI_TX_CTL_DMA_LEVEL_1 BIT5 #define SPI_TX_CTL_DMA_LEVEL_0 BIT4 #define SPI_TX_CTL_DMA_REQ_EN BIT3 #define SPI_TX_CTL_MODE BIT2 #define SPI_TX_CTL_FIFO_RESET BIT1 #define SPI_TX_CTL_EN BIT0 /**************** Bit definition for SPI_RX_CTL register ***********************/ #define SPI_RX_CTL_DMA_LEVEL (BIT4|BIT5|BIT6|BIT7) #define SPI_RX_CTL_DMA_LEVEL_3 BIT7 #define SPI_RX_CTL_DMA_LEVEL_2 BIT6 #define SPI_RX_CTL_DMA_LEVEL_1 BIT5 #define SPI_RX_CTL_DMA_LEVEL_0 BIT4 #define SPI_RX_CTL_DMA_REQ_EN BIT3 #define SPI_RX_CTL_FIFO_RESET BIT1 #define SPI_RX_CTL_EN BIT0 /**************** Bit definition for SPI_IE register ***************************/ #define SPI_IE_RX_BATCH_DONE_EN BIT15 #define SPI_IE_TX_BATCH_DONE_EN BIT14 #define SPI_IE_RX_FIFO_FULL_OV_EN BIT13 #define SPI_IE_RX_FIFO_EMPTY_OV_EN BIT12 #define SPI_IE_RX_NOT_EMPTY_EN BIT11 #define SPI_IE_CS_POS_EN BIT10 #define SPI_IE_RX_FIFO_HALF_FULL_EN BIT9 #define SPI_IE_RX_FIFO_HALF_EMPTY_EN BIT8 #define SPI_IE_TX_FIFO_HALF_FULL_EN BIT7 #define SPI_IE_TX_FIFO_HALF_EMPTY_EN BIT6 #define SPI_IE_RX_FIFO_FULL_EN BIT5 #define SPI_IE_RX_FIFO_EMPTY_EN BIT4 #define SPI_IE_TX_FIFO_FULL_EN BIT3 #define SPI_IE_TX_FIFO_EMPTY_EN BIT2 #define SPI_IE_BATCH_DONE_EN BIT1 /**************** Bit definition for SPI_STATUS register ***********************/ #define SPI_STATUS_RX_BATCH_DONE BIT15 #define SPI_STATUS_TX_BATCH_DONE BIT14 #define SPI_STATUS_RX_FIFO_FULL_OV BIT13 #define SPI_STATUS_RX_FIFO_EMPTY_OV BIT12 #define SPI_STATUS_RX_NOT_EMPTY BIT11 #define SPI_STATUS_CS_POS BIT10 #define SPI_STATUS_RX_FIFO_HALF_FULL BIT9 #define SPI_STATUS_RX_FIFO_HALF_EMPTY BIT8 #define SPI_STATUS_TX_FIFO_HALF_FULL BIT7 #define SPI_STATUS_TX_FIFO_HALF_EMPTY BIT6 #define SPI_STATUS_RX_FIFO_FULL BIT5 #define SPI_STATUS_RX_FIFO_EMPTY BIT4 #define SPI_STATUS_TX_FIFO_FULL BIT3 #define SPI_STATUS_TX_FIFO_EMPTY BIT2 #define SPI_STATUS_BATCH_DONE BIT1 #define SPI_STATUS_TX_BUSY BIT0 /**************** Bit definition for SPI_CS register ***************************/ #define SPI_CS_CSX BIT1 #define SPI_CS_CS0 BIT0 /**************** Bit definition for SPI_OUT_EN register ***********************/ #define SPI_HOLD_EN BIT3 #define SPI_HOLD_WP_EN BIT2 #define SPI_HOLD_MISO_EN BIT1 #define SPI_HOLD_MOSI_EN BIT0 /**************** Bit definition for SPI_MEMO_ACC register ***********************/ #define SPI_ADDR_WIDTH (BIT14|BIT15|BIT16|BIT17|BIT18) #define SPI_PARA_NO2 (BIT9|BIT10|BIT11|BIT12|BIT13) #define SPI_PARA_NO1 (BIT5|BIT6|BIT7|BIT8) #define SPI_CON_RD_EN BIT3 #define SPI_PARA_ORD2 BIT2 #define SPI_PARA_ORD1 BIT1 #define SPI_ACC_EN BIT0 /** @defgroup SLAVE State machine * @{ */ #define SPI_RX_STATE_IDLE (0U) #define SPI_RX_STATE_RECEIVING (1U) #define SPI_TX_STATE_IDLE (0U) #define SPI_TX_STATE_SENDING (1U) /** * @} */ /** @defgroup SPI_MODE * @{ */ #define SPI_MODE_SLAVE (0U) #define SPI_MODE_MASTER (1U) /** * @} */ /** @defgroup SPI_WORK_MODE * @{ */ #define SPI_WORK_MODE_0 (0x00000000) #define SPI_WORK_MODE_1 (0x00000004) #define SPI_WORK_MODE_2 (0x00000008) #define SPI_WORK_MODE_3 (0x0000000C) /** * @} */ /** @defgroup SPI_CLOCK_PHASE SPI Clock Phase * @{ */ #define SPI_PHASE_1EDGE (0U) #define SPI_PHASE_2EDGE (1U) /** * @} */ /** @defgroup X_MODE SPI Clock Phase * @{ */ #define SPI_1X_MODE (0x00000000) #define SPI_2X_MODE (0x00000020) #define SPI_4X_MODE (0x00000040) /** * @} */ /** @defgroup SPI_MSB_LSB_FIRST * @{ */ #define SPI_FIRSTBIT_MSB (0U) #define SPI_FIRSTBIT_LSB (1U) /** * @} */ /** @defgroup BAUDRATE_PRESCALER * @{ */ #define SPI_BAUDRATE_PRESCALER_4 (4U) #define SPI_BAUDRATE_PRESCALER_8 (8U) #define SPI_BAUDRATE_PRESCALER_16 (16U) #define SPI_BAUDRATE_PRESCALER_32 (32U) #define SPI_BAUDRATE_PRESCALER_64 (64U) #define SPI_BAUDRATE_PRESCALER_128 (128U) #define SPI_BAUDRATE_PRESCALER_254 (254U) /** * @} */ /** * @brief SPI Configuration Structure definition */ typedef struct { uint32_t SPI_Mode; /* This parameter can be a value of @ref SPI_MODE */ uint32_t SPI_Work_Mode; /* This parameter can be a value of @ref SPI_WORK_MODE */ uint32_t X_Mode; /* This parameter can be a value of @ref X_MODE */ uint32_t First_Bit; /* This parameter can be a value of @ref SPI_MSB_LSB_FIRST */ uint32_t BaudRate_Prescaler; /* This parameter can be a value of @ref BAUDRATE_PRESCALER */ }SPI_InitTypeDef; /******************************** Check SPI Parameter *******************************/ #define IS_SPI_ALL_MODE(SPI_Mode) (((SPI_Mode) == SPI_MODE_SLAVE) || \ ((SPI_Mode) == SPI_MODE_MASTER)) #define IS_SPI_WORK_MODE(WORK_MODE) (((WORK_MODE) == SPI_WORK_MODE_0) || \ ((WORK_MODE) == SPI_WORK_MODE_1) || \ ((WORK_MODE) == SPI_WORK_MODE_2) || \ ((WORK_MODE) == SPI_WORK_MODE_3)) #define IS_SPI_X_MODE(X_MODE) (((X_MODE) == SPI_1X_MODE) || \ ((X_MODE) == SPI_2X_MODE) || \ ((X_MODE) == SPI_4X_MODE)) #define IS_SPI_FIRST_BIT(FIRST_BIT) (((FIRST_BIT) == SPI_FIRSTBIT_MSB) || \ ((FIRST_BIT) == SPI_FIRSTBIT_LSB)) #define IS_SPI_BAUDRATE_PRESCALER(BAUDRATE) (((BAUDRATE) == SPI_BAUDRATE_PRESCALER_4) || \ ((BAUDRATE) == SPI_BAUDRATE_PRESCALER_8) || \ ((BAUDRATE) == SPI_BAUDRATE_PRESCALER_16) || \ ((BAUDRATE) == SPI_BAUDRATE_PRESCALER_32) || \ ((BAUDRATE) == SPI_BAUDRATE_PRESCALER_64) || \ ((BAUDRATE) == SPI_BAUDRATE_PRESCALER_128) || \ ((BAUDRATE) == SPI_BAUDRATE_PRESCALER_254)) /** * @brief SPI handle Structure definition */ typedef struct { SPI_TypeDef *Instance; /* SPI registers base address */ SPI_InitTypeDef Init; /* SPI communication parameters */ uint32_t RxState; /* SPI state machine */ uint32_t TxState; /* SPI state machine */ uint8_t *Rx_Buffer; /* SPI Rx Buffer */ uint8_t *Tx_Buffer; /* SPI Tx Buffer */ uint32_t Rx_Size; /* SPI Rx Size */ uint32_t Tx_Size; /* SPI Tx Size */ uint32_t Rx_Count; /* SPI RX Count */ uint32_t Tx_Count; /* SPI TX Count */ DMA_HandleTypeDef *HDMA_Rx; /* SPI Rx DMA handle parameters */ DMA_HandleTypeDef *HDMA_Tx; /* SPI Tx DMA handle parameters */ }SPI_HandleTypeDef; /******************************** SPI Instances *******************************/ #define IS_SPI_ALL_INSTANCE(INSTANCE) (((INSTANCE) == SPI1) || ((INSTANCE) == SPI2)) /* Function : HAL_SPI_IRQHandler */ void HAL_SPI_IRQHandler(SPI_HandleTypeDef *hspi); /* Function : HAL_SPI_MspInit */ void HAL_SPI_MspInit(SPI_HandleTypeDef *hspi); /* Function : HAL_SPI_MspDeInit */ void HAL_SPI_MspDeInit(SPI_HandleTypeDef *hspi); /* Function : HAL_SPI_Init */ HAL_StatusTypeDef HAL_SPI_Init(SPI_HandleTypeDef *hspi); /* Function : HAL_SPI_DeInit */ HAL_StatusTypeDef HAL_SPI_DeInit(SPI_HandleTypeDef *hspi); /* Function : HAL_SPI_Transmit */ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint32_t Size, uint32_t Timeout); /* Function : HAL_SPI_Transmit_DMA */ HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint32_t Size); /* Function : HAL_SPI_Receive */ HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint32_t Size, uint32_t Timeout); /* Function : HAL_SPI_Receive_DMA */ HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint32_t Size); /* Function : HAL_SPI_Wire_Config */ HAL_StatusTypeDef HAL_SPI_Wire_Config(SPI_HandleTypeDef *hspi, uint32_t X_Mode); /* Function : HAL_SPI_Transmit_IT */ HAL_StatusTypeDef HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint32_t Size); /* Function : HAL_SPI_Receive_IT */ HAL_StatusTypeDef HAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint32_t Size); /* Function : HAL_SPI_TransmitReceive */ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint32_t Size, uint32_t Timeout); /* Function : HAL_SPI_GetTxState */ uint8_t HAL_SPI_GetTxState(SPI_HandleTypeDef *hspi); /* Function : HAL_SPI_GetRxState */ uint8_t HAL_SPI_GetRxState(SPI_HandleTypeDef *hspi); #endif
e1c0ecc6f4041762732aad2037898f10921ce151
51de1ebe7fa09fb262e015fb454829987ed5fc83
/serializer/inc/codefirst.h
16c91f2fb91608ceb93540a241a86384cd825100
[ "MIT" ]
permissive
Azure/azure-iot-sdk-c
54bf46938f5b8089ba06081cb4d7967fa3a8f777
1f3d95b4dae09927ae4bbe479e52d48acef1f93c
refs/heads/main
2023-08-31T03:36:13.694208
2023-08-30T23:56:13
2023-08-30T23:56:13
70,934,373
629
902
NOASSERTION
2023-09-06T17:41:38
2016-10-14T17:54:57
C
UTF-8
C
false
false
6,648
h
codefirst.h
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #ifndef CODEFIRST_H #define CODEFIRST_H #include "methodreturn.h" #include "agenttypesystem.h" #include "schema.h" #include "azure_macro_utils/macro_utils.h" #include "azure_c_shared_utility/strings.h" #include "iotdevice.h" #ifdef __cplusplus #include <cstddef> #include <cstdarg> extern "C" { #else #include <stddef.h> #include <stdarg.h> #include <stdbool.h> #endif typedef char* ascii_char_ptr; typedef char* ascii_char_ptr_no_quotes; typedef enum REFLECTION_TYPE_TAG { REFLECTION_METHOD_TYPE, REFLECTION_DESIRED_PROPERTY_TYPE, REFLECTION_REPORTED_PROPERTY_TYPE, REFLECTION_STRUCT_TYPE, REFLECTION_FIELD_TYPE, REFLECTION_PROPERTY_TYPE, REFLECTION_ACTION_TYPE, REFLECTION_MODEL_TYPE, REFLECTION_NOTHING }REFLECTION_TYPE; typedef EXECUTE_COMMAND_RESULT (*actionWrapper)(void* device, size_t ParameterCount, const AGENT_DATA_TYPE* values); typedef METHODRETURN_HANDLE (*methodWrapper)(void* device, size_t ParameterCount, const AGENT_DATA_TYPE* values); typedef struct REFLECTION_STRUCT_TAG { const char* name; }REFLECTION_STRUCT; typedef struct WRAPPER_ARGUMENT_TAG { const char* type; const char* name; }WRAPPER_ARGUMENT; typedef struct REFLECTION_ACTION_TAG { const char* name; size_t nArguments; const WRAPPER_ARGUMENT* arguments; actionWrapper wrapper; const char* modelName; }REFLECTION_ACTION; typedef struct REFLECTION_METHOD_TAG { const char* name; size_t nArguments; const WRAPPER_ARGUMENT* arguments; methodWrapper wrapper; const char* modelName; }REFLECTION_METHOD; typedef struct REFLECTION_FIELD_TAG { const char* fieldName; const char* fieldType; const char* structName; }REFLECTION_FIELD; typedef struct REFLECTION_PROPERTY_TAG { const char* name; const char* type; int(*Create_AGENT_DATA_TYPE_from_Ptr)(void* param, AGENT_DATA_TYPE* dest); size_t offset; size_t size; const char* modelName; } REFLECTION_PROPERTY; typedef struct REFLECTION_REPORTED_PROPERTY_TAG { const char* name; const char* type; int(*Create_AGENT_DATA_TYPE_from_Ptr)(void* param, AGENT_DATA_TYPE* dest); size_t offset; size_t size; const char* modelName; } REFLECTION_REPORTED_PROPERTY; typedef struct REFLECTION_DESIRED_PROPERTY_TAG { pfOnDesiredProperty onDesiredProperty; void(*desiredPropertInitialize)(void* destination); void(*desiredPropertDeinitialize)(void* destination); const char* name; const char* type; int(*FromAGENT_DATA_TYPE)(const AGENT_DATA_TYPE* source, void* dest); /*destination is "something" everytime. When the DESIRED_PROPERTY is a MODEL, the function is empty*/ size_t offset; size_t size; const char* modelName; } REFLECTION_DESIRED_PROPERTY; typedef struct REFLECTION_MODEL_TAG { const char* name; } REFLECTION_MODEL; typedef struct REFLECTED_SOMETHING_TAG { REFLECTION_TYPE type; const struct REFLECTED_SOMETHING_TAG* next; struct what { REFLECTION_METHOD method; REFLECTION_DESIRED_PROPERTY desiredProperty; REFLECTION_REPORTED_PROPERTY reportedProperty; REFLECTION_STRUCT structure; REFLECTION_FIELD field; REFLECTION_PROPERTY property; REFLECTION_ACTION action; REFLECTION_MODEL model; } what; } REFLECTED_SOMETHING; typedef struct REFLECTED_DATA_FROM_DATAPROVIDER_TAG { const REFLECTED_SOMETHING* reflectedData; }REFLECTED_DATA_FROM_DATAPROVIDER; #define ALL_SOMETHING_REFLECTED(schemaNamespace) MU_C2(schemaNamespace, _allSomethingReflected) #define ALL_REFLECTED(schemaNamespace) MU_C2(schemaNamespace, _allReflected) #define ADDRESS_OF_ALL_REFLECTED(schemaNamespace) & MU_C2(schemaNamespace, _allReflected), #define DECLARE_EXTERN_CONST_DATAPROVIDER_DATA(x) extern const REFLECTED_DATA_FROM_DATAPROVIDER ALL_REFLECTED(x); #define CODEFIRST_RESULT_VALUES \ CODEFIRST_OK, \ CODEFIRST_INVALID_ARG, \ CODEFIRST_ALREADY_INIT, \ CODEFIRST_NOT_INIT, \ CODEFIRST_ERROR, \ CODEFIRST_NOT_ENOUGH_MEMORY, \ CODEFIRST_ACTION_NOT_FOUND, \ CODEFIRST_ACTION_EXECUTION_ERROR, \ CODEFIRST_SCHEMA_ERROR, \ CODEFIRST_AGENT_DATA_TYPE_ERROR, \ CODEFIRST_VALUES_FROM_DIFFERENT_DEVICES_ERROR, \ CODEFIRST_DEVICE_FAILED, \ CODEFIRST_DEVICE_PUBLISH_FAILED, \ CODEFIRST_NOT_A_PROPERTY MU_DEFINE_ENUM_WITHOUT_INVALID(CODEFIRST_RESULT, CODEFIRST_RESULT_VALUES) #include "umock_c/umock_c_prod.h" MOCKABLE_FUNCTION(, CODEFIRST_RESULT, CodeFirst_Init, const char*, overrideSchemaNamespace); MOCKABLE_FUNCTION(, void, CodeFirst_Deinit); MOCKABLE_FUNCTION(, SCHEMA_HANDLE, CodeFirst_RegisterSchema, const char*, schemaNamespace, const REFLECTED_DATA_FROM_DATAPROVIDER*, metadata); MOCKABLE_FUNCTION(, EXECUTE_COMMAND_RESULT, CodeFirst_InvokeAction, DEVICE_HANDLE, deviceHandle, void*, callbackUserContext, const char*, relativeActionPath, const char*, actionName, size_t, parameterCount, const AGENT_DATA_TYPE*, parameterValues); MOCKABLE_FUNCTION(, METHODRETURN_HANDLE, CodeFirst_InvokeMethod, DEVICE_HANDLE, deviceHandle, void*, callbackUserContext, const char*, relativeMethodPath, const char*, methodName, size_t, parameterCount, const AGENT_DATA_TYPE*, parameterValues); MOCKABLE_FUNCTION(, EXECUTE_COMMAND_RESULT, CodeFirst_ExecuteCommand, void*, device, const char*, command); MOCKABLE_FUNCTION(, METHODRETURN_HANDLE, CodeFirst_ExecuteMethod, void*, device, const char*, methodName, const char*, methodPayload); MOCKABLE_FUNCTION(, void*, CodeFirst_CreateDevice, SCHEMA_MODEL_TYPE_HANDLE, model, const REFLECTED_DATA_FROM_DATAPROVIDER*, metadata, size_t, dataSize, bool, includePropertyPath); MOCKABLE_FUNCTION(, void, CodeFirst_DestroyDevice, void*, device); extern CODEFIRST_RESULT CodeFirst_SendAsync(unsigned char** destination, size_t* destinationSize, size_t numProperties, ...); extern CODEFIRST_RESULT CodeFirst_SendAsyncReported(unsigned char** destination, size_t* destinationSize, size_t numReportedProperties, ...); MOCKABLE_FUNCTION(, CODEFIRST_RESULT, CodeFirst_IngestDesiredProperties, void*, device, const char*, jsonPayload, bool, parseDesiredNode); MOCKABLE_FUNCTION(, AGENT_DATA_TYPE_TYPE, CodeFirst_GetPrimitiveType, const char*, typeName); #ifdef __cplusplus } #endif #endif /* CODEFIRST_H */
14789e7f90155064652d04a05b91a8abb09f3ae0
19f730c72461d36e457466c4805f3a5da840d806
/sdk/userspace/fpga_libs/fpga_mgmt/fpga_mgmt.c
5eba76c1924fed39cdeb6a350e7492fb621c4d67
[ "Apache-2.0" ]
permissive
aws/aws-fpga
7e0fbc7af80df50e80927946b16ce3dc8c2686a6
863d963308231d0789a48f8840ceb1141368b34a
refs/heads/master
2023-09-02T10:37:11.067887
2023-06-05T21:22:03
2023-06-05T21:22:03
72,888,735
1,469
631
NOASSERTION
2023-07-24T03:37:32
2016-11-04T22:04:05
VHDL
UTF-8
C
false
false
20,747
c
fpga_mgmt.c
/* * Copyright 2015-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may * not use this file except in compliance with the License. A copy of the * License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <string.h> #include <errno.h> #include <fpga_mgmt.h> #include <afi_cmd_api.h> #include <fpga_hal_mbox.h> #include <utils/lcd.h> #include "fpga_mgmt_internal.h" /** Synchronous API (load/clear) default timeout and delay msecs */ #define FPGA_MGMT_SYNC_TIMEOUT 30000 #define FPGA_MGMT_SYNC_DELAY_MSEC 2 struct fgpa_mgmt_state_s fpga_mgmt_state = { .timeout = FPGA_MGMT_TIMEOUT_DFLT, .delay_msec = FPGA_MGMT_DELAY_MSEC_DFLT, }; int fpga_mgmt_init(void) { for (unsigned int i = 0; i < sizeof_array(fpga_mgmt_state.slots); ++i) { fpga_mgmt_state.slots[i].handle = PCI_BAR_HANDLE_INIT; } fpga_mgmt_state.initialized = true; return fpga_pci_init(); } int fpga_mgmt_close(void) { if (!fpga_mgmt_state.initialized) { return FPGA_ERR_OK; } fpga_mgmt_state.initialized = false; for (unsigned int i = 0; i < sizeof_array(fpga_mgmt_state.slots); ++i) { if (fpga_mgmt_state.slots[i].handle != PCI_BAR_HANDLE_INIT) { fpga_mgmt_mbox_detach(i); } } return FPGA_ERR_OK; } void fpga_mgmt_set_cmd_timeout(uint32_t value) { fpga_mgmt_state.timeout = value; } void fpga_mgmt_set_cmd_delay_msec(uint32_t value) { fpga_mgmt_state.delay_msec = value; } static int fpga_mgmt_get_sh_version(int slot_id, uint32_t *sh_version) { pci_bar_handle_t handle = PCI_BAR_HANDLE_INIT; int ret = -EINVAL; fail_on(!sh_version, err, "sh_version is NULL"); fail_slot_id(slot_id, err, ret); ret = fpga_mgmt_mbox_attach(slot_id); fail_on(ret, err, "fpga_mgmt_mbox_attach failed"); handle = fpga_mgmt_state.slots[slot_id].handle; struct fpga_hal_mbox_versions ver; ret = fpga_hal_mbox_get_versions(handle, &ver); fail_on(ret, err, "fpga_hal_mbox_get_versions failed"); *sh_version = ver.sh_version; err: return ret; } static int fpga_mgmt_describe_cmd(int slot_id, struct fpga_mgmt_image_info *info, uint32_t flags) { int ret; uint32_t len; union afi_cmd cmd; union afi_cmd rsp; fail_slot_id(slot_id, out, ret); if (!info) { return -EINVAL; } memset(&cmd, 0, sizeof(union afi_cmd)); memset(&rsp, 0, sizeof(union afi_cmd)); /* initialize the command structure */ fpga_mgmt_cmd_init_metrics(&cmd, &len, flags); /* send the command and wait for the response */ ret = fpga_mgmt_process_cmd(slot_id, &cmd, &rsp, &len); fail_on(ret, out, "fpga_mgmt_process_cmd failed"); /* extract the relevant data from the response */ struct afi_cmd_metrics_rsp *metrics; ret = fpga_mgmt_cmd_handle_metrics(&rsp, len, &metrics); fail_on(ret, out, "fpga_mgmt_cmd_handle_metrics failed"); /* translate the response structure to the API structure */ info->status = metrics->status; info->status_q = metrics->status_q; info->slot_id = slot_id; char *afi_id = (!metrics->ids.afi_id[0]) ? "none" : metrics->ids.afi_id; info->ids = metrics->ids; strncpy(info->ids.afi_id, afi_id, sizeof(info->ids.afi_id)); uint32_t sh_version; ret = fpga_mgmt_get_sh_version(slot_id, &sh_version); fail_on(ret, out, "fpga_mgmt_get_sh_version failed"); info->sh_version = sh_version; /* copy the metrics into the out param */ info->metrics = metrics->fmc; out: return ret; } int fpga_mgmt_describe_local_image(int slot_id, struct fpga_mgmt_image_info *info, uint32_t flags) { int ret; fail_on_with_code(!fpga_mgmt_state.initialized, out, ret, FPGA_ERR_SOFTWARE_PROBLEM, "fpga_mgmt_init must be called before the library can be used"); ret = fpga_mgmt_describe_cmd(slot_id, info, flags); fail_on(ret, out, "fpga_mgmt_describe_cmd"); ret = fpga_pci_get_slot_spec(slot_id, &info->spec); fail_on(ret, out, "fpga_pci_get_slot_spec failed"); out: return ret; } int fpga_mgmt_get_status(int slot_id, int *status, int *status_q) { int ret; struct fpga_mgmt_image_info info; fail_on_with_code(!fpga_mgmt_state.initialized, out, ret, FPGA_ERR_SOFTWARE_PROBLEM, "fpga_mgmt_init must be called before the library can be used"); fail_slot_id(slot_id, out, ret); if (!status) { return -EINVAL; } memset(&info, 0, sizeof(struct fpga_mgmt_image_info)); ret = fpga_mgmt_describe_local_image(slot_id, &info, 0); fail_on(ret, out, "fpga_mgmt_describe_local_image failed"); *status = info.status; *status_q = info.status_q; out: return ret; } const char *fpga_mgmt_get_status_name(int status) { return FPGA_STATUS2STR(status); } const char *fpga_mgmt_strerror(int err) { if (err < 0) { return strerror(-err); } return FPGA_ERR2STR(err); } static const char * long_help_FPGA_ERR_AFI_CMD_BUSY = "The FPGA is busy with an operation such as a load or a clear.\n"; static const char * long_help_FPGA_ERR_AFI_ID_INVALID = "The agfi id passed is invalid or you do not have permission to load\n" "the AFI.\n"; static const char * long_help_FPGA_ERR_AFI_CMD_API_VERSION_INVALID = "The FPGA images tools are outdated. Newer tools are available at\n" "https://github.com/aws/aws-fpga\n"; static const char * long_help_FPGA_ERR_CL_ID_MISMATCH = "The vendor and device ID presented by the CL did not match expected\n" "values provided at ingestion time.\n"; static const char * long_help_FPGA_ERR_CL_DDR_CALIB_FAILED = "The DDR controllers in the CL did not correctly calibrate DDR.\n"; static const char * long_help_FPGA_ERR_SHELL_MISMATCH = "The requested AFI relies on a shell which is not supported on this\n" "instance type.\n"; static const char * long_help_FPGA_ERR_POWER_VIOLATION = "The loaded CL exceeded maximum allowed power consumption and was\n" "automatically disabled. To clear this condition, simply reload the AFI.\n"; static const char * long_help_FPGA_ERR_PCI_MISSING = "Unable to locate a PCI device or resource for communicating with the\n" "FPGA API. This can happen if the FPGA has stopped behaving correctly\n" "and the instance will need to be stopped and restarted. This can also\n" "happen if the tools are run on a system with no AWS FPGA attached.\n"; static const char * long_help_ETIMEDOUT = "A time out error is usually spurious and the request can be retried. If\n" "it continues to fail, the FPGA may be inaccessible or the the FPGA API\n" "may be unresponsive.\n"; static const char * long_help_FPGA_ERR_AFI_CMD_MALFORMED = "A malformed response from the FPGA API can indicate that the FPGA has\n" "stopped behaving correctly and the instance will need to be stopped and\n" "and restarted. If this continues to happen (after an instance restart),\n" "this may be an indication that your AFI is exceeding allowed power\n" "consumption limits.\n"; static const char * long_help_FPGA_ERR_SOFTWARE_PROBLEM = "This usually indicates a bug in the fpga image tools, but can also be a\n" "symptom of a bug in the code which is using the library in cases where\n" "the customer is using the library directly.\n"; static const char * long_help_FPGA_ERR_UNRESPONSIVE = "The FPGA or PCI subsytem is not responding. This can happen if the FPGA\n" "stopped behaving correctly and the instance will need to be stopped and\n" "restarted.\n"; const char *fpga_mgmt_strerror_long(int err) { switch (err) { default: case FPGA_ERR_FAIL: case FPGA_ERR_OK: return NULL; case FPGA_ERR_AFI_CMD_BUSY: return long_help_FPGA_ERR_AFI_CMD_BUSY; case FPGA_ERR_AFI_ID_INVALID: return long_help_FPGA_ERR_AFI_ID_INVALID; case FPGA_ERR_AFI_CMD_API_VERSION_INVALID: return long_help_FPGA_ERR_AFI_CMD_API_VERSION_INVALID; case FPGA_ERR_CL_ID_MISMATCH: return long_help_FPGA_ERR_CL_ID_MISMATCH; case FPGA_ERR_CL_DDR_CALIB_FAILED: return long_help_FPGA_ERR_CL_DDR_CALIB_FAILED; case FPGA_ERR_SHELL_MISMATCH: return long_help_FPGA_ERR_SHELL_MISMATCH; case FPGA_ERR_POWER_VIOLATION: return long_help_FPGA_ERR_POWER_VIOLATION; case FPGA_ERR_PCI_MISSING: return long_help_FPGA_ERR_PCI_MISSING; case FPGA_ERR_AFI_CMD_MALFORMED: return long_help_FPGA_ERR_AFI_CMD_MALFORMED; case -EINVAL: case FPGA_ERR_SOFTWARE_PROBLEM: return long_help_FPGA_ERR_SOFTWARE_PROBLEM; case FPGA_ERR_UNRESPONSIVE: return long_help_FPGA_ERR_UNRESPONSIVE; case -ETIMEDOUT: return long_help_ETIMEDOUT; } } int fpga_mgmt_clear_local_image(int slot_id) { int ret; uint32_t len; union afi_cmd cmd; union afi_cmd rsp; fail_on_with_code(!fpga_mgmt_state.initialized, out, ret, FPGA_ERR_SOFTWARE_PROBLEM, "fpga_mgmt_init must be called before the library can be used"); fail_slot_id(slot_id, out, ret); memset(&cmd, 0, sizeof(union afi_cmd)); memset(&rsp, 0, sizeof(union afi_cmd)); /* initialize the command structure */ fpga_mgmt_cmd_init_clear(&cmd, &len); /* send the command and wait for the response */ ret = fpga_mgmt_process_cmd(slot_id, &cmd, &rsp, &len); fail_on(ret, out, "fpga_mgmt_process_cmd failed"); /* the clear command does not have an interesting response payload */ out: return ret; } int fpga_mgmt_clear_local_image_sync(int slot_id, uint32_t timeout, uint32_t delay_msec, struct fpga_mgmt_image_info *info) { struct fpga_mgmt_image_info tmp_info; struct fpga_pci_resource_map app_map; uint32_t prev_sh_version = 0; uint32_t sh_version = 0; uint32_t retries = 0; bool done = false; int status; int ret; fail_on_with_code(!fpga_mgmt_state.initialized, out, ret, FPGA_ERR_SOFTWARE_PROBLEM, "fpga_mgmt_init must be called before the library can be used"); /** Allow timeout adjustments that are greater than the defaults */ uint32_t timeout_tmp = (timeout > FPGA_MGMT_SYNC_TIMEOUT) ? timeout : FPGA_MGMT_SYNC_TIMEOUT; uint32_t delay_msec_tmp = (delay_msec > FPGA_MGMT_SYNC_DELAY_MSEC) ? delay_msec : FPGA_MGMT_SYNC_DELAY_MSEC; fail_on_with_code(slot_id >= FPGA_SLOT_MAX, out, ret, -EINVAL, "invalid slot"); memset(&tmp_info, 0, sizeof(tmp_info)); /** * Get the current SH version and PCI resource map for the app_pf * that will be used after the clear has completed. */ ret = fpga_mgmt_get_sh_version(slot_id, &prev_sh_version); fail_on(ret != 0, out, "fpga_mgmt_get_sh_version failed"); ret = fpga_pci_get_resource_map(slot_id, FPGA_APP_PF, &app_map); fail_on(ret != 0, out, "fpga_pci_get_resource_map failed"); /** Clear the FPGA image (async completion) */ ret = fpga_mgmt_clear_local_image(slot_id); fail_on(ret, out, "fpga_mgmt_clear_local_image failed"); /** Wait until the status is "cleared" or timeout */ while (!done) { ret = fpga_mgmt_describe_cmd(slot_id, &tmp_info, 0); /** flags==0 */ status = (ret == 0) ? tmp_info.status : FPGA_STATUS_END; if (status == FPGA_STATUS_CLEARED) { done = true; } else if (status == FPGA_STATUS_BUSY) { fail_on(ret = (retries >= timeout_tmp) ? -ETIMEDOUT : 0, out, "fpga_mgmt_describe_local_image timed out, status=%s(%d), retries=%u", FPGA_STATUS2STR(status), status, retries); retries++; msleep(delay_msec_tmp); } else { /** * Catch error status cases here. * -the caller can then display the error status and cause upon return. */ ret = tmp_info.status_q; goto out; } } /** * Do not perform a remove/rescan of the APP PF if the SH version and PCI IDs * have not changed. */ struct afi_device_ids *afi_device_ids = &tmp_info.ids.afi_device_ids; ret = fpga_mgmt_get_sh_version(slot_id, &sh_version); fail_on(ret != 0, out, "fpga_mgmt_get_sh_version failed"); if ((sh_version != prev_sh_version) || !((afi_device_ids->vendor_id == app_map.vendor_id) && (afi_device_ids->device_id == app_map.device_id) && (afi_device_ids->svid == app_map.subsystem_vendor_id) && (afi_device_ids->ssid == app_map.subsystem_device_id))) { /** * Perform a PCI device remove and recan in order to expose the default AFI * Vendor and Device Id. */ log_info("remove+rescan required, sh_version=0x%08x, prev_sh_version=0x%08x, " "expected_ids={0x%04x, 0x%04x, 0x%04x, 0x%04x}, " "sysfs_ids={0x%04x, 0x%04x, 0x%04x, 0x%04x}", sh_version, prev_sh_version, afi_device_ids->vendor_id, afi_device_ids->device_id, afi_device_ids->svid, afi_device_ids->ssid, app_map.vendor_id, app_map.device_id, app_map.subsystem_vendor_id, app_map.subsystem_device_id); ret = fpga_pci_rescan_slot_app_pfs(slot_id); fail_on(ret, out, "fpga_pci_rescan_slot_app_pfs failed"); } /* now fill in the slot spec information after the rescan */ ret = fpga_pci_get_slot_spec(slot_id, &tmp_info.spec); fail_on(ret, out, "fpga_pci_get_slot_spec failed"); if (info) { *info = tmp_info; } out: return ret; } int fpga_mgmt_load_local_image(int slot_id, char *afi_id) { return fpga_mgmt_load_local_image_flags(slot_id, afi_id, 0); } int fpga_mgmt_init_load_local_image_options(union fpga_mgmt_load_local_image_options *opt){ memset(opt, 0, sizeof(union fpga_mgmt_load_local_image_options)); return 0; } int fpga_mgmt_load_local_image_flags(int slot_id, char *afi_id, uint32_t flags) { union fpga_mgmt_load_local_image_options opt; fpga_mgmt_init_load_local_image_options(&opt); opt.slot_id = slot_id; opt.afi_id = afi_id; opt.flags = flags; return fpga_mgmt_load_local_image_with_options(&opt); } int fpga_mgmt_load_local_image_with_options(union fpga_mgmt_load_local_image_options *opt){ int ret; uint32_t len; union afi_cmd cmd; union afi_cmd rsp; fail_on_with_code(!fpga_mgmt_state.initialized, out, ret, FPGA_ERR_SOFTWARE_PROBLEM, "fpga_mgmt_init must be called before the library can be used"); fail_slot_id(opt->slot_id, out, ret); memset(&cmd, 0, sizeof(union afi_cmd)); memset(&rsp, 0, sizeof(union afi_cmd)); /* mask off any unsupported flags */ opt->flags &= FPGA_CMD_ALL_FLAGS; /* initialize the command structure */ fpga_mgmt_cmd_init_load(&cmd, &len, opt); /* send the command and wait for the response */ ret = fpga_mgmt_process_cmd(opt->slot_id, &cmd, &rsp, &len); fail_on(ret, out, "fpga_mgmt_process_cmd failed"); /* the load command does not have an interesting response payload */ out: return ret; } int fpga_mgmt_load_local_image_sync(int slot_id, char *afi_id, uint32_t timeout, uint32_t delay_msec, struct fpga_mgmt_image_info *info) { return fpga_mgmt_load_local_image_sync_flags(slot_id, afi_id, 0, timeout, delay_msec, info); } int fpga_mgmt_load_local_image_sync_flags(int slot_id, char *afi_id, uint32_t flags, uint32_t timeout, uint32_t delay_msec, struct fpga_mgmt_image_info *info) { union fpga_mgmt_load_local_image_options opt; fpga_mgmt_init_load_local_image_options(&opt); opt.slot_id = slot_id; opt.afi_id = afi_id; opt.flags = flags; return fpga_mgmt_load_local_image_sync_with_options(&opt, timeout, delay_msec, info); } int fpga_mgmt_load_local_image_sync_with_options(union fpga_mgmt_load_local_image_options *opt, uint32_t timeout, uint32_t delay_msec, struct fpga_mgmt_image_info *info) { struct fpga_mgmt_image_info tmp_info; struct fpga_pci_resource_map app_map; uint32_t prev_sh_version = 0; uint32_t sh_version = 0; uint32_t retries = 0; bool done = false; int status; int ret; fail_on_with_code(!fpga_mgmt_state.initialized, out, ret, FPGA_ERR_SOFTWARE_PROBLEM, "fpga_mgmt_init must be called before the library can be used"); /** Allow timeout adjustments that are greater than the defaults */ uint32_t timeout_tmp = (timeout > FPGA_MGMT_SYNC_TIMEOUT) ? timeout : FPGA_MGMT_SYNC_TIMEOUT; uint32_t delay_msec_tmp = (delay_msec > FPGA_MGMT_SYNC_DELAY_MSEC) ? delay_msec : FPGA_MGMT_SYNC_DELAY_MSEC; fail_on_with_code(opt->slot_id >= FPGA_SLOT_MAX, out, ret, -EINVAL, "invalid slot"); memset(&tmp_info, 0, sizeof(tmp_info)); /** * Get the current SH version and PCI resource map for the app_pf * that will be used after the load has completed. */ ret = fpga_mgmt_get_sh_version(opt->slot_id, &prev_sh_version); fail_on(ret != 0, out, "fpga_mgmt_get_sh_version failed"); ret = fpga_pci_get_resource_map(opt->slot_id, FPGA_APP_PF, &app_map); fail_on(ret != 0, out, "fpga_pci_get_resource_map failed"); /** Load the FPGA image (async completion) */ ret = fpga_mgmt_load_local_image_with_options(opt); fail_on(ret, out, "fpga_mgmt_load_local_image failed"); /** Wait until the status is "loaded" or timeout */ while (!done) { ret = fpga_mgmt_describe_cmd(opt->slot_id, &tmp_info, 0); /** flags==0 */ status = (ret == 0) ? tmp_info.status : FPGA_STATUS_END; if (status == FPGA_STATUS_LOADED) { /** Sanity check the afi_id */ ret = (strncmp(opt->afi_id, tmp_info.ids.afi_id, sizeof(tmp_info.ids.afi_id))) ? FPGA_ERR_FAIL : 0; fail_on(ret, out, "AFI ID mismatch: requested afi_id=%s, loaded afi_id=%s", opt->afi_id, tmp_info.ids.afi_id); done = true; } else if (status == FPGA_STATUS_BUSY) { fail_on(ret = (retries >= timeout_tmp) ? -ETIMEDOUT : 0, out, "fpga_mgmt_describe_local_image timed out, status=%s(%d), retries=%u", FPGA_STATUS2STR(status), status, retries); retries++; msleep(delay_msec_tmp); } else { /** * Catch error status cases here. * -the caller can then display the error status and cause upon return. */ ret = tmp_info.status_q; goto out; } } /** * Do not perform a remove/rescan of the APP PF if the SH version and PCI IDs * have not changed. */ struct afi_device_ids *afi_device_ids = &tmp_info.ids.afi_device_ids; ret = fpga_mgmt_get_sh_version(opt->slot_id, &sh_version); fail_on(ret != 0, out, "fpga_mgmt_get_sh_version failed"); if ((sh_version != prev_sh_version) || !((afi_device_ids->vendor_id == app_map.vendor_id) && (afi_device_ids->device_id == app_map.device_id) && (afi_device_ids->svid == app_map.subsystem_vendor_id) && (afi_device_ids->ssid == app_map.subsystem_device_id))) { /** * Perform a PCI device remove and recan in order to expose the unique AFI * Vendor and Device Id. */ log_info("remove+rescan required, sh_version=0x%08x, prev_sh_version=0x%08x, " "expected_ids={0x%04x, 0x%04x, 0x%04x, 0x%04x}, " "sysfs_ids={0x%04x, 0x%04x, 0x%04x, 0x%04x}", sh_version, prev_sh_version, afi_device_ids->vendor_id, afi_device_ids->device_id, afi_device_ids->svid, afi_device_ids->ssid, app_map.vendor_id, app_map.device_id, app_map.subsystem_vendor_id, app_map.subsystem_device_id); ret = fpga_pci_rescan_slot_app_pfs(opt->slot_id); fail_on(ret, out, "fpga_pci_rescan_slot_app_pfs failed"); } /* now fill in the slot spec information after the rescan */ ret = fpga_pci_get_slot_spec(opt->slot_id, &tmp_info.spec); fail_on(ret, out, "fpga_pci_get_slot_spec failed"); if (info) { *info = tmp_info; } out: return ret; } int fpga_mgmt_get_vLED_status(int slot_id, uint16_t *status) { pci_bar_handle_t led_pci_bar; uint32_t read_data; int ret; ret = fpga_pci_attach(slot_id, FPGA_MGMT_PF, MGMT_PF_BAR0, 0, &led_pci_bar); fail_on(ret, out, "fpga_pci_attach failed"); ret = fpga_pci_peek(led_pci_bar, F1_VIRTUAL_LED_REG_OFFSET, &read_data); fail_on(ret, out, "fpga_pci_peek failed"); /* All this code assumes little endian, it would need rework for supporting non x86/arm platforms */ *status = (uint16_t)(read_data & 0x0000FFFF); ret = fpga_pci_detach(led_pci_bar); fail_on(ret, out, "fpga_pci_detach failed"); out: return ret; } int fpga_mgmt_set_vDIP(int slot_id, uint16_t value) { pci_bar_handle_t dip_pci_bar; uint32_t write_data; int ret; ret = fpga_pci_attach(slot_id, FPGA_MGMT_PF, MGMT_PF_BAR0, 0, &dip_pci_bar); fail_on(ret, out, "fpga_pci_attach failed"); write_data = (uint32_t) value; ret = fpga_pci_poke(dip_pci_bar, F1_VIRTUAL_DIP_REG_OFFSET, write_data); fail_on(ret, out, "fpga_pci_poke failed"); ret = fpga_pci_detach(dip_pci_bar); fail_on(ret, out, "fpga_pci_detach failed"); out: return ret; } int fpga_mgmt_get_vDIP_status(int slot_id, uint16_t *value) { pci_bar_handle_t dip_pci_bar; uint32_t read_data; int ret; ret = fpga_pci_attach(slot_id, FPGA_MGMT_PF, MGMT_PF_BAR0, 0, &dip_pci_bar); fail_on(ret, out, "fpga_pci_attach failed"); ret = fpga_pci_peek(dip_pci_bar, F1_VIRTUAL_DIP_REG_OFFSET, &read_data); fail_on(ret, out, "fpga_pci_peek failed"); /* All this code assumes little endian, it would need rework for supporting non x86/arm platforms */ *value = (uint16_t)read_data; ret = fpga_pci_detach(dip_pci_bar); fail_on(ret, out, "fpga_pci_detach failed"); out: return ret; }
a846b0448d88cceb8c0937aed735818fba129964
7f86525d675d31795376ab3b070befb6af5f8a9f
/str.c
eb47c86cd2b11acd6ba8c5aa9acc9e6c24400b5a
[ "LicenseRef-scancode-public-domain" ]
permissive
wryun/es-shell
8f61d87338e3ea0cda34835e65b5c71cbf2e141c
4945413062a0a5707694f3c64184d04fbff573c8
refs/heads/master
2023-05-14T12:03:15.000531
2023-01-04T22:30:03
2023-01-04T22:30:03
5,487,041
293
32
NOASSERTION
2023-04-30T16:22:31
2012-08-20T21:31:00
C
UTF-8
C
false
false
2,626
c
str.c
/* str.c -- es string operations ($Revision: 1.1.1.1 $) */ #include "es.h" #include "gc.h" #include "print.h" /* grow -- buffer grow function for str() */ static void str_grow(Format *f, size_t more) { Buffer *buf = expandbuffer(f->u.p, more); f->u.p = buf; f->buf = buf->str + (f->buf - f->bufbegin); f->bufbegin = buf->str; f->bufend = buf->str + buf->len; } /* strv -- print a formatted string into gc space */ extern char *strv(const char *fmt, va_list args) { Buffer *buf; Format format; gcdisable(); buf = openbuffer(0); format.u.p = buf; #if NO_VA_LIST_ASSIGN memcpy(format.args, args, sizeof(va_list)); #else format.args = args; #endif format.buf = buf->str; format.bufbegin = buf->str; format.bufend = buf->str + buf->len; format.grow = str_grow; format.flushed = 0; printfmt(&format, fmt); fmtputc(&format, '\0'); gcenable(); return sealbuffer(format.u.p); } /* str -- create a string (in garbage collection space) by printing to it */ extern char *str VARARGS1(const char *, fmt) { char *s; va_list args; VA_START(args, fmt); s = strv(fmt, args); va_end(args); return s; } #define PRINT_ALLOCSIZE 64 /* mprint_grow -- buffer grow function for mprint() */ static void mprint_grow(Format *format, size_t more) { char *buf; size_t len = format->bufend - format->bufbegin + 1; len = (len >= more) ? len * 2 : ((len + more) + PRINT_ALLOCSIZE) &~ (PRINT_ALLOCSIZE - 1); buf = erealloc(format->bufbegin, len); format->buf = buf + (format->buf - format->bufbegin); format->bufbegin = buf; format->bufend = buf + len - 1; } /* mprint -- create a string in ealloc space by printing to it */ extern char *mprint VARARGS1(const char *, fmt) { Format format; format.u.n = 1; VA_START(format.args, fmt); format.buf = ealloc(PRINT_ALLOCSIZE); format.bufbegin = format.buf; format.bufend = format.buf + PRINT_ALLOCSIZE - 1; format.grow = mprint_grow; format.flushed = 0; printfmt(&format, fmt); *format.buf = '\0'; va_end(format.args); return format.bufbegin; } /* * StrList -- lists of strings * to even include these is probably a premature optimization */ DefineTag(StrList, static); extern StrList *mkstrlist(char *str, StrList *next) { gcdisable(); assert(str != NULL); Ref(StrList *, list, gcnew(StrList)); list->str = str; list->next = next; gcenable(); RefReturn(list); } static void *StrListCopy(void *op) { void *np = gcnew(StrList); memcpy(np, op, sizeof (StrList)); return np; } static size_t StrListScan(void *p) { StrList *list = p; list->str = forward(list->str); list->next = forward(list->next); return sizeof (StrList); }
0523531fce3ef59755d9a7a3cca17982c97176f9
522eccce9de282e1b9b7e0aef31c2fbb9685611e
/src/gl/debug.h
f4d7ff857ddb423ef5743851bc2b01805e8c969c
[ "MIT" ]
permissive
ptitSeb/gl4es
b4f5049488134103db0c22dbf570d8b093d597c2
bfcdd3a452e0d04d41afd2693a879c073b5ad8c9
refs/heads/master
2023-08-14T08:42:11.310554
2023-07-09T21:05:08
2023-07-09T21:05:08
18,032,918
624
173
MIT
2023-09-04T08:34:28
2014-03-23T12:33:23
C
UTF-8
C
false
false
203
h
debug.h
#ifndef _GL4ES_DEBUG_H_ #define _GL4ES_DEBUG_H_ #include "gles.h" const char* PrintEnum(GLenum what); const char* PrintEGLError(int onlyerror); void CheckGLError(int fwd); #endif // _GL4ES_DEBUG_H_
ecde8f18e063f6036e34d1db4de53761040e0951
e5f4f37d941ceb8145d65f92028cc54658b1ac01
/Code/Engine/Foundation/Basics/Platform/Win/Platform_win.h
1f8f353a22545ec22287ea3a6f3a8816717ae987
[ "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
986
h
Platform_win.h
#pragma once #if EZ_DISABLED(EZ_PLATFORM_WINDOWS) # error "This header should only be included on windows platforms" #endif #ifdef _WIN64 # undef EZ_PLATFORM_64BIT # define EZ_PLATFORM_64BIT EZ_ON #else # undef EZ_PLATFORM_32BIT # define EZ_PLATFORM_32BIT EZ_ON #endif #ifndef _CRT_SECURE_NO_WARNINGS # define _CRT_SECURE_NO_WARNINGS #endif #include <winapifamily.h> #undef EZ_PLATFORM_WINDOWS_UWP #undef EZ_PLATFORM_WINDOWS_DESKTOP // Distinguish between Windows desktop and Windows UWP. #if WINAPI_FAMILY == WINAPI_FAMILY_APP # define EZ_PLATFORM_WINDOWS_UWP EZ_ON # define EZ_PLATFORM_WINDOWS_DESKTOP EZ_OFF #else # define EZ_PLATFORM_WINDOWS_UWP EZ_OFF # define EZ_PLATFORM_WINDOWS_DESKTOP EZ_ON #endif #ifndef NULL # define NULL 0 #endif #undef EZ_PLATFORM_LITTLE_ENDIAN #define EZ_PLATFORM_LITTLE_ENDIAN EZ_ON #include <Foundation/Basics/Compiler/Clang/Clang.h> #include <Foundation/Basics/Compiler/GCC/GCC.h> #include <Foundation/Basics/Compiler/MSVC/MSVC.h>
a1b9c7929b4a38db9e1388bb3f0ee18ce70692d7
88ae8695987ada722184307301e221e1ba3cc2fa
/native_client/src/nonsfi/linux/irt_signal_handling.c
9734eb59dc43b86b3f69531713c0edf985a96f75
[ "BSD-3-Clause", "Zlib", "Classpath-exception-2.0", "BSD-Source-Code", "LZMA-exception", "LicenseRef-scancode-unicode", "LGPL-3.0-only", "LGPL-2.0-or-later", "LicenseRef-scancode-philippe-de-muyter", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-intel-osl-1993", "HPND-sell-variant", "ICU", "LicenseRef-scancode-protobuf", "bzip2-1.0.6", "Spencer-94", "NCSA", "LicenseRef-scancode-nilsson-historical", "CC0-1.0", "LicenseRef-scancode-proprietary-license", "LGPL-2.1-only", "LicenseRef-scancode-other-copyleft", "GPL-2.0-or-later", "NTP", "GPL-2.0-only", "LicenseRef-scancode-other-permissive", "GPL-3.0-only", "GFDL-1.1-only", "W3C", "LicenseRef-scancode-python-cwi", "GCC-exception-3.1", "BSL-1.0", "Python-2.0", "GPL-1.0-or-later", "LGPL-2.1-or-later", "LicenseRef-scancode-unknown-license-reference", "CPL-1.0", "GFDL-1.1-or-later", "W3C-19980720", "LGPL-2.0-only", "LicenseRef-scancode-amd-historical", "LicenseRef-scancode-ietf", "SAX-PD", "LicenseRef-scancode-x11-hanson", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "dtoa", "MIT", "LicenseRef-scancode-public-domain-disclaimer", "PSF-2.0", "LicenseRef-scancode-newlib-historical", "LicenseRef-scancode-generic-exception", "SMLNJ", "HP-1986", "LicenseRef-scancode-free-unknown", "SunPro", "MPL-1.1" ]
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
13,988
c
irt_signal_handling.c
/* * Copyright (c) 2015 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <errno.h> #include <pthread.h> #include <signal.h> #include <stdint.h> #include <string.h> #include <unistd.h> #include "native_client/src/include/elf_constants.h" #include "native_client/src/include/nacl/nacl_exception.h" #include "native_client/src/include/nacl_macros.h" #include "native_client/src/nonsfi/linux/irt_signal_handling.h" #include "native_client/src/nonsfi/linux/linux_sys_private.h" #include "native_client/src/nonsfi/linux/linux_syscall_defines.h" #include "native_client/src/nonsfi/linux/linux_syscall_structs.h" #include "native_client/src/public/linux_syscalls/sys/syscall.h" #include "native_client/src/public/nonsfi/irt_signal_handling.h" #include "native_client/src/untrusted/irt/irt.h" typedef struct compat_sigaltstack { uint32_t ss_sp; int32_t ss_flags; uint32_t ss_size; } linux_stack_t; #if defined(__i386__) /* From linux/arch/x86/include/uapi/asm/sigcontext32.h */ struct sigcontext_ia32 { uint16_t gs, __gsh; uint16_t fs, __fsh; uint16_t es, __esh; uint16_t ds, __dsh; uint32_t di; uint32_t si; uint32_t bp; uint32_t sp; uint32_t bx; uint32_t dx; uint32_t cx; uint32_t ax; uint32_t trapno; uint32_t err; uint32_t ip; uint16_t cs, __csh; uint32_t flags; uint32_t sp_at_signal; uint16_t ss, __ssh; uint32_t fpstate; uint32_t oldmask; uint32_t cr2; }; typedef struct sigcontext_ia32 linux_mcontext_t; #elif defined(__arm__) /* From linux/arch/arm/include/uapi/asm/sigcontext.h */ struct sigcontext_arm { uint32_t trap_no; uint32_t error_code; uint32_t oldmask; uint32_t arm_r0; uint32_t arm_r1; uint32_t arm_r2; uint32_t arm_r3; uint32_t arm_r4; uint32_t arm_r5; uint32_t arm_r6; uint32_t arm_r7; uint32_t arm_r8; uint32_t arm_r9; uint32_t arm_r10; uint32_t arm_r11; /* fp */ uint32_t arm_r12; /* ip */ uint32_t arm_sp; uint32_t arm_lr; uint32_t arm_pc; uint32_t arm_cpsr; uint32_t fault_address; }; typedef struct sigcontext_arm linux_mcontext_t; #else #error "unsupported architecture" #endif /* From linux/arch/arm/include/asm/ucontext.h */ struct linux_ucontext_t { uint32_t uc_flags; uint32_t uc_link; linux_stack_t uc_stack; linux_mcontext_t uc_mcontext; linux_sigset_t uc_sigmask; /* More data follows which we don't care about. */ }; /* * Crash signals to handle. The differences from SFI NaCl are that * NonSFI NaCl does not use NACL_THREAD_SUSPEND_SIGNAL (==SIGUSR1), */ static const int kSignals[] = { LINUX_SIGSTKFLT, LINUX_SIGINT, LINUX_SIGQUIT, LINUX_SIGILL, LINUX_SIGTRAP, LINUX_SIGBUS, LINUX_SIGFPE, LINUX_SIGSEGV, /* Handle SIGABRT in case someone sends it asynchronously using kill(). */ LINUX_SIGABRT, }; static pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER; static NaClExceptionHandler g_signal_handler_function_pointer = NULL; static NaClExceptionHandler g_exception_handler_function_pointer = NULL; static int g_signal_handler_initialized = 0; static int g_tgid = 0; static int g_main_tid; struct NonSfiExceptionFrame { struct NaClExceptionContext context; struct NaClExceptionPortableContext portable; }; static void machine_context_to_register(const linux_mcontext_t *mctx, NaClUserRegisterState *dest) { #if defined(__i386__) #define COPY_REG(A) dest->e##A = mctx->A COPY_REG(ax); COPY_REG(cx); COPY_REG(dx); COPY_REG(bx); COPY_REG(bp); COPY_REG(si); COPY_REG(di); #undef COPY_REG dest->stack_ptr = mctx->sp; dest->prog_ctr = mctx->ip; dest->flags = mctx->flags; #elif defined(__arm__) #define COPY_REG(A) dest->A = mctx->arm_##A COPY_REG(r0); COPY_REG(r1); COPY_REG(r2); COPY_REG(r3); COPY_REG(r4); COPY_REG(r5); COPY_REG(r6); COPY_REG(r7); COPY_REG(r8); COPY_REG(r9); COPY_REG(r10); COPY_REG(r11); COPY_REG(r12); #undef COPY_REG dest->stack_ptr = mctx->arm_sp; dest->lr = mctx->arm_lr; dest->prog_ctr = mctx->arm_pc; dest->cpsr = mctx->arm_cpsr; #else # error Unsupported architecture #endif } static void nonsfi_exception_frame_from_signal_context( struct NonSfiExceptionFrame *frame, const void *raw_ctx) { const struct linux_ucontext_t *uctx = (struct linux_ucontext_t *) raw_ctx; const linux_mcontext_t *mctx = &uctx->uc_mcontext; frame->context.size = (((uintptr_t) (&frame->portable + 1)) - (uintptr_t) &frame->context); frame->context.portable_context_offset = ((uintptr_t) &frame->portable - (uintptr_t) &frame->context); frame->context.portable_context_size = sizeof(frame->portable); frame->context.regs_size = sizeof(frame->context.regs); memset(frame->context.reserved, 0, sizeof(frame->context.reserved)); machine_context_to_register(mctx, &frame->context.regs); frame->portable.prog_ctr = frame->context.regs.prog_ctr; frame->portable.stack_ptr = frame->context.regs.stack_ptr; #if defined(__i386__) frame->context.arch = EM_386; frame->portable.frame_ptr = frame->context.regs.ebp; #elif defined(__arm__) frame->context.arch = EM_ARM; /* R11 is frame pointer in ARM mode, R8 is frame pointer in thumb mode. */ frame->portable.frame_ptr = frame->context.regs.r11; #else # error Unsupported architecture #endif } /* A replacement of sigreturn. It does not restore the signal mask. */ static void __attribute__((noreturn)) nonsfi_restore_context(const linux_mcontext_t *mctx) { #if defined(__i386__) #define OFFSET(name) \ [name] "i" (offsetof(linux_mcontext_t, name)) #define RESTORE_SEGMENT(name) \ "mov %c[" #name "](%%eax), %%" #name "\n" #define RESTORE(name) \ "movl %c[" #name "](%%eax), %%e" #name "\n" __asm__ __volatile__( /* TODO(lhchavez): Restore floating-point environment */ /* Restore all segment registers */ RESTORE_SEGMENT(gs) RESTORE_SEGMENT(fs) RESTORE_SEGMENT(es) RESTORE_SEGMENT(ds) /* * Restore most of the other registers. */ RESTORE(di) RESTORE(si) RESTORE(bp) RESTORE(bx) /* * Prepare the last registers. eip *must* be one slot above the original * stack, since that is the only way eip and esp can be simultaneously * restored. Here, we are using ecx as the pseudo stack pointer, and edx * as a scratch register. Once the stack is laid out the way we want it to * be, restore edx and eax last. */ "mov %c[sp](%%eax), %%ecx\n" "mov %c[ip](%%eax), %%edx\n" "mov %%edx, -4(%%ecx)\n" "mov %c[flags](%%eax), %%edx\n" "mov %%edx, -8(%%ecx)\n" "mov %c[cx](%%eax), %%edx\n" "mov %%edx, -12(%%ecx)\n" RESTORE(dx) RESTORE(ax) "lea -12(%%ecx), %%esp\n" /* * Finally pop ecx off the stack, restore the processor flags, and return * to simultaneously restore esp and eip. */ "pop %%ecx\n" "popf\n" "ret\n" : : "a" (mctx), OFFSET(gs), OFFSET(fs), OFFSET(es), OFFSET(ds), OFFSET(di), OFFSET(si), OFFSET(bp), OFFSET(sp), OFFSET(bx), OFFSET(dx), OFFSET(cx), OFFSET(ax), OFFSET(ip), OFFSET(flags), OFFSET(fpstate) ); #undef OFFSET #undef RESTORE #undef RESTORE_SEGMENT #elif defined(__arm__) #define OFFSET(name) \ [name] "I" (offsetof(linux_mcontext_t, arm_ ## name) - \ offsetof(linux_mcontext_t, arm_r0)) register uint32_t a14 __asm__("r14") = (uint32_t) &mctx->arm_r0; __asm__ __volatile__( /* Restore flags */ "ldr r0, [r14, %[cpsr]]\n" "msr APSR_nzcvqg, r0\n" /* TODO(lhchavez): Restore floating-point environment */ /* * Restore general-purpose registers. * This code does not use the simpler 'ldmia r14, {r0-pc}' since using * ldmia with either sp or with both lr and pc is deprecated. */ "ldmia r14, {r0-r10}\n" /* * Copy r11, r12, lr, and pc just before the original sp. * r12 will work as a temporary sp. r11 will be the scratch register, and * will be restored just before moving sp. */ "ldr r12, [r14, %[sp]]\n" "ldr r11, [r14, %[pc]]\n" "stmdb r12!, {r11}\n" "ldr r11, [r14, %[lr]]\n" "stmdb r12!, {r11}\n" "ldr r11, [r14, %[r12]]\n" "stmdb r12!, {r11}\n" "ldr r11, [r14, %[r11]]\n" "mov sp, r12\n" /* * Restore r12, lr, and pc. sp will point to the correct location once * we're done. */ "pop {r12, lr}\n" "pop {pc}\n" : : "r" (a14), OFFSET(cpsr), OFFSET(r11), OFFSET(r12), OFFSET(sp), OFFSET(lr), OFFSET(pc) ); #undef OFFSET #else # error Unsupported architecture #endif /* Should never reach this. */ __builtin_trap(); } static __attribute__((noreturn)) void restore_context(void *raw_ctx) { const struct linux_ucontext_t *uctx = (struct linux_ucontext_t *) raw_ctx; const linux_mcontext_t *mctx = &uctx->uc_mcontext; nonsfi_restore_context(mctx); } /* Signal handlers, responsible for calling the registered handlers. */ static void exception_catch(int sig, linux_siginfo_t *info, void *uc) { if (g_exception_handler_function_pointer) { struct NonSfiExceptionFrame exception_frame; nonsfi_exception_frame_from_signal_context(&exception_frame, uc); g_exception_handler_function_pointer(&exception_frame.context); } _exit(-sig); } static void signal_catch(int sig, linux_siginfo_t *info, void *uc) { if (g_signal_handler_function_pointer) { struct NonSfiExceptionFrame exception_frame; nonsfi_exception_frame_from_signal_context(&exception_frame, uc); g_signal_handler_function_pointer(&exception_frame.context); } restore_context(uc); } static void nonsfi_install_exception_handler_locked(void) { struct linux_sigaction sa; unsigned int a; memset(&sa, 0, sizeof(sa)); sa.sa_sigaction = exception_catch; sa.sa_flags = LINUX_SA_SIGINFO | LINUX_SA_ONSTACK; /* * Reuse the sigemptyset/sigaddset for the first 32 bits of the * sigmask. Works on little endian systems only. */ sigset_t *mask = (sigset_t*)&sa.sa_mask; sigemptyset(mask); /* Mask all signals we catch to prevent re-entry. */ for (a = 0; a < NACL_ARRAY_SIZE(kSignals); a++) { sigaddset(mask, kSignals[a]); } /* Install all handlers. */ for (a = 0; a < NACL_ARRAY_SIZE(kSignals); a++) { if (linux_sigaction(kSignals[a], &sa, NULL) != 0) abort(); } } static void nonsfi_install_signal_handler_locked(void) { struct linux_sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_sigaction = signal_catch; /* * User signal handler can be recursively interrupted to avoid having * to allow sigreturn/sigprocmask. */ sa.sa_flags = LINUX_SA_SIGINFO | LINUX_SA_NODEFER | LINUX_SA_RESTART; sigset_t *mask = (sigset_t*)&sa.sa_mask; sigemptyset(mask); /* * Install a single handler. Multiple signals can be multiplexed in * userspace. */ if (linux_sigaction(LINUX_SIGUSR1, &sa, NULL) != 0) abort(); } static void nonsfi_initialize_signal_handler_locked(void) { if (g_signal_handler_initialized) return; pid_t tgid = getpid(); if (tgid == -1) abort(); pid_t main_tid = syscall(__NR_gettid); if (main_tid == -1) abort(); nonsfi_install_exception_handler_locked(); nonsfi_install_signal_handler_locked(); g_tgid = tgid; g_main_tid = main_tid; g_signal_handler_initialized = 1; } /* * Initialize signal handlers before entering sandbox. */ void nonsfi_initialize_signal_handler(void) { if (pthread_mutex_lock(&g_mutex) != 0) abort(); nonsfi_initialize_signal_handler_locked(); if (pthread_mutex_unlock(&g_mutex) != 0) abort(); } int nacl_exception_get_and_set_handler(NaClExceptionHandler handler, NaClExceptionHandler *old_handler) { if (pthread_mutex_lock(&g_mutex) != 0) abort(); nonsfi_initialize_signal_handler_locked(); if (old_handler) *old_handler = g_exception_handler_function_pointer; g_exception_handler_function_pointer = handler; if (pthread_mutex_unlock(&g_mutex) != 0) abort(); return 0; } int nacl_exception_set_handler(NaClExceptionHandler handler) { return nacl_exception_get_and_set_handler(handler, NULL); } int nacl_exception_clear_flag(void) { /* * Unblock signals, useful for unit testing and continuing to * process after fatal signal. */ /* Allocate the 8 bytes of signal mask. */ linux_sigset_t mask; /* * sigemptyset will only clear first 4 bytes of sigset_t, and * compat_sigset_t has 8 bytes, clear with memset. */ memset(&mask, 0, sizeof(mask)); /* * Hack to be able to reuse sigset_t utilities from newlib for the * first lower 4 bytes of the signal, works because we are all * little endians. */ sigset_t *maskptr = (sigset_t *) &mask; sigemptyset(maskptr); for (size_t a = 0; a < NACL_ARRAY_SIZE(kSignals); a++) { if (sigaddset(maskptr, kSignals[a]) != 0) abort(); } if (linux_sigprocmask(LINUX_SIG_UNBLOCK, &mask, NULL) != 0) abort(); return 0; } int nacl_exception_set_stack(void *p, size_t s) { /* Not implemented yet. */ return ENOSYS; } int nacl_async_signal_set_handler(NaClIrtAsyncSignalHandler handler) { if (pthread_mutex_lock(&g_mutex) != 0) abort(); nonsfi_initialize_signal_handler_locked(); g_signal_handler_function_pointer = handler; if (pthread_mutex_unlock(&g_mutex) != 0) abort(); return 0; } int nacl_async_signal_send_async_signal(nacl_irt_tid_t tid) { if (!g_signal_handler_initialized) return ESRCH; if (tid == 0) tid = g_main_tid; if (linux_tgkill(g_tgid, tid, LINUX_SIGUSR1) == -1) return errno; return 0; }
c0604c99748b5a3e786c933a538d0459e134d427
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
/sys/dev/marvell/obio.c
46ab6c6b42adfa29f15541e8c8b2143a756d6dc1
[]
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
5,174
c
obio.c
/* $NetBSD: obio.c,v 1.17 2021/08/07 16:19:13 thorpej Exp $ */ /* * Copyright (c) 2002 Allegro Networks, Inc., Wasabi Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 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 for the NetBSD Project by * Allegro Networks, Inc., and Wasabi Systems, Inc. * 4. The name of Allegro Networks, Inc. may not be used to endorse * or promote products derived from this software without specific prior * written permission. * 5. The name of Wasabi Systems, Inc. may not be used to endorse * or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY ALLEGRO NETWORKS, INC. AND * WASABI SYSTEMS, INC. ``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 EITHER ALLEGRO NETWORKS, INC. OR WASABI SYSTEMS, INC. * 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 <sys/cdefs.h> __KERNEL_RCSID(0, "$NetBSD: obio.c,v 1.17 2021/08/07 16:19:13 thorpej Exp $"); #include "opt_marvell.h" #include <sys/param.h> #include <sys/types.h> #include <sys/extent.h> #include <sys/device.h> #include <sys/kernel.h> #include <dev/pci/pcivar.h> #include <dev/marvell/gtreg.h> #include <dev/marvell/gtvar.h> #include <dev/marvell/gtdevbusvar.h> #include <dev/marvell/marvellvar.h> #include <prop/proplib.h> #ifdef DEBUG #include <sys/systm.h> /* for Debugger() */ #endif #include "locators.h" static int obio_match(device_t, cfdata_t, void *); static void obio_attach(device_t, device_t, void *); static int obio_cfprint(void *, const char *); static int obio_cfsearch(device_t, cfdata_t, const int *, void *); struct obio_softc { device_t sc_dev; bus_space_tag_t sc_iot; }; CFATTACH_DECL_NEW(obio, sizeof(struct obio_softc), obio_match, obio_attach, NULL, NULL); /* ARGSUSED */ int obio_match(device_t parent, cfdata_t cf, void *aux) { struct marvell_attach_args *mva = aux; if (strcmp(mva->mva_name, cf->cf_name) != 0) return 0; #define NUM_OBIO 5 if (mva->mva_unit == MVA_UNIT_DEFAULT || mva->mva_unit > NUM_OBIO) return 0; return 1; } /* ARGSUSED */ void obio_attach(device_t parent, device_t self, void *aux) { struct obio_softc *sc = device_private(self); struct marvell_attach_args *mva = aux; prop_data_t bst; uint32_t datal, datah; aprint_naive("\n"); aprint_normal(": Device Bus\n"); sc->sc_dev = self; if (gt_devbus_addr(parent, mva->mva_unit, &datal, &datah)) { aprint_error_dev(self, "unknown unit number %d\n", mva->mva_unit); return; } if (GT_LowAddr_GET(datal) > GT_HighAddr_GET(datah)) { aprint_normal_dev(self, "disabled\n"); return; } bst = prop_dictionary_get(device_properties(sc->sc_dev), "bus-tag"); if (bst != NULL) { KASSERT(prop_object_type(bst) == PROP_TYPE_DATA); KASSERT(prop_data_size(bst) == sizeof(bus_space_tag_t)); memcpy(&sc->sc_iot, prop_data_data_nocopy(bst), sizeof(bus_space_tag_t)); } else sc->sc_iot = mva->mva_iot; if (sc->sc_iot == NULL) { aprint_normal_dev(self, "unused\n"); return; } aprint_normal_dev(self, "addr %#x-%#x\n", GT_LowAddr_GET(datal), GT_HighAddr_GET(datah)); config_search(self, NULL, CFARGS(.search = obio_cfsearch)); } int obio_cfprint(void *aux, const char *pnp) { struct obio_attach_args *oa = aux; if (pnp) aprint_normal("%s at %s", oa->oa_name, pnp); aprint_normal(" addr %#x size %#x", oa->oa_offset, oa->oa_size); if (oa->oa_irq != OBIOCF_IRQ_DEFAULT) aprint_normal(" irq %d", oa->oa_irq); return UNCONF; } /* ARGSUSED */ int obio_cfsearch(device_t parent, cfdata_t cf, const int *ldesc, void *aux) { struct obio_softc *sc = device_private(parent); struct obio_attach_args oa; oa.oa_name = cf->cf_name; oa.oa_memt = sc->sc_iot; oa.oa_offset = cf->cf_loc[OBIOCF_OFFSET]; oa.oa_size = cf->cf_loc[OBIOCF_SIZE]; oa.oa_irq = cf->cf_loc[OBIOCF_IRQ]; if (config_probe(parent, cf, &oa)) config_attach(parent, cf, &oa, obio_cfprint, CFARGS_NONE); return 0; }
51ec9b7e0535b9d8fdacf093341503a11806fab2
99bdb3251fecee538e0630f15f6574054dfc1468
/bsp/nuvoton/libraries/nuc980/Driver/Source/nu_rtc.c
1ace1099240662c5360cf75f85da65ba793d5c99
[ "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
30,160
c
nu_rtc.c
/**************************************************************************//** * @file rtc.c * @version V3.00 * $Revision: 5 $ * $Date: 14/06/10 5:49p $ * @brief NUC980 series RTC driver source file * * @note * SPDX-License-Identifier: Apache-2.0 * @copyright (C) 2016 Nuvoton Technology Corp. All rights reserved. *****************************************************************************/ #include "nu_rtc.h" /** @cond HIDDEN_SYMBOLS */ /*---------------------------------------------------------------------------------------------------------*/ /* Macro, type and constant definitions */ /*---------------------------------------------------------------------------------------------------------*/ #define RTC_GLOBALS /*---------------------------------------------------------------------------------------------------------*/ /* Global file scope (static) variables */ /*---------------------------------------------------------------------------------------------------------*/ static volatile uint32_t g_u32hiYear, g_u32loYear, g_u32hiMonth, g_u32loMonth, g_u32hiDay, g_u32loDay; static volatile uint32_t g_u32hiHour, g_u32loHour, g_u32hiMin, g_u32loMin, g_u32hiSec, g_u32loSec; /** @endcond HIDDEN_SYMBOLS */ /** @addtogroup Standard_Driver Standard Driver @{ */ /** @addtogroup RTC_Driver RTC Driver @{ */ /** @addtogroup RTC_EXPORTED_FUNCTIONS RTC Exported Functions @{ */ /** * @brief Initialize RTC module and start counting * * @param[in] sPt Specify the time property and current date and time. It includes: \n * u32Year: Year value, range between 2000 ~ 2099. \n * u32Month: Month value, range between 1 ~ 12. \n * u32Day: Day value, range between 1 ~ 31. \n * u32DayOfWeek: Day of the week. [RTC_SUNDAY / RTC_MONDAY / RTC_TUESDAY / * RTC_WEDNESDAY / RTC_THURSDAY / RTC_FRIDAY / * RTC_SATURDAY] \n * u32Hour: Hour value, range between 0 ~ 23. \n * u32Minute: Minute value, range between 0 ~ 59. \n * u32Second: Second value, range between 0 ~ 59. \n * u32TimeScale: [RTC_CLOCK_12 / RTC_CLOCK_24] \n * u8AmPm: [RTC_AM / RTC_PM] \n * * @return None * * @details This function is used to: \n * 1. Write initial key to let RTC start count. \n * 2. Input parameter indicates start date/time. \n * 3. User has to make sure that parameters of RTC date/time are reasonable. \n * @note Null pointer for using default starting date/time. */ void RTC_Open(S_RTC_TIME_DATA_T *sPt) { RTC->INIT = RTC_INIT_KEY; RTC_Check(); if (RTC->INIT != RTC_INIT_ACTIVE_Msk) { RTC->INIT = RTC_INIT_KEY; while (RTC->INIT != RTC_INIT_ACTIVE_Msk) { } } if (sPt == 0) { } else { /* Set RTC date and time */ RTC_SetDateAndTime(sPt); } } /** * @brief Disable RTC Clock * * @param None * * @return None * * @details This API will disable RTC peripheral clock and stops RTC counting. */ void RTC_Close(void) { outp32(REG_CLK_PCLKEN0, inp32(REG_CLK_PCLKEN0 & ~(0x1 << 1))); } /** * @brief Set Frequency Compensation Data * * @param[in] i32FrequencyX100 Specify the RTC clock X100, ex: 3277365 means 32773.65. * * @return None * */ void RTC_32KCalibration(int32_t i32FrequencyX100) { INT32 i32RegInt, i32RegFra; UINT32 u32Reg; /* Compute integer and fraction for RTC FCR register */ i32RegInt = (i32FrequencyX100 / 100) - RTC_FCR_REFERENCE; i32RegFra = (((i32FrequencyX100 % 100)) * 60) / 100; /* Judge Integer part is reasonable */ if (i32RegInt < 0) i32RegInt = 0; if (i32RegInt > 15) i32RegInt = 15; u32Reg = (uint32_t)((i32RegInt << 8) | i32RegFra); RTC_WaitAccessEnable(); outp32(REG_RTC_FREQADJ, u32Reg); RTC_Check(); } /** * @brief Get Current RTC Date and Time * * @param[out] sPt The returned pointer is specified the current RTC value. It includes: \n * u32Year: Year value \n * u32Month: Month value \n * u32Day: Day value \n * u32DayOfWeek: Day of week \n * u32Hour: Hour value \n * u32Minute: Minute value \n * u32Second: Second value \n * u32TimeScale: [RTC_CLOCK_12 / RTC_CLOCK_24] \n * u8AmPm: [RTC_AM / RTC_PM] \n * * @return None * * @details This API is used to get the current RTC date and time value. */ void RTC_GetDateAndTime(S_RTC_TIME_DATA_T *sPt) { uint32_t u32Tmp; sPt->u32TimeScale = RTC->CLKFMT & RTC_CLKFMT_24HEN_Msk; /* 12/24-hour */ sPt->u32DayOfWeek = RTC->WEEKDAY & RTC_WEEKDAY_WEEKDAY_Msk; /* Day of the week */ /* Get [Date digit] data */ g_u32hiYear = (RTC->CAL & RTC_CAL_TENYEAR_Msk) >> RTC_CAL_TENYEAR_Pos; g_u32loYear = (RTC->CAL & RTC_CAL_YEAR_Msk) >> RTC_CAL_YEAR_Pos; g_u32hiMonth = (RTC->CAL & RTC_CAL_TENMON_Msk) >> RTC_CAL_TENMON_Pos; g_u32loMonth = (RTC->CAL & RTC_CAL_MON_Msk) >> RTC_CAL_MON_Pos; g_u32hiDay = (RTC->CAL & RTC_CAL_TENDAY_Msk) >> RTC_CAL_TENDAY_Pos; g_u32loDay = (RTC->CAL & RTC_CAL_DAY_Msk) >> RTC_CAL_DAY_Pos; /* Get [Time digit] data */ g_u32hiHour = (RTC->TIME & RTC_TIME_TENHR_Msk) >> RTC_TIME_TENHR_Pos; g_u32loHour = (RTC->TIME & RTC_TIME_HR_Msk) >> RTC_TIME_HR_Pos; g_u32hiMin = (RTC->TIME & RTC_TIME_TENMIN_Msk) >> RTC_TIME_TENMIN_Pos; g_u32loMin = (RTC->TIME & RTC_TIME_MIN_Msk) >> RTC_TIME_MIN_Pos; g_u32hiSec = (RTC->TIME & RTC_TIME_TENSEC_Msk) >> RTC_TIME_TENSEC_Pos; g_u32loSec = (RTC->TIME & RTC_TIME_SEC_Msk) >> RTC_TIME_SEC_Pos; /* Compute to 20XX year */ u32Tmp = (g_u32hiYear * 10ul); u32Tmp += g_u32loYear; sPt->u32Year = u32Tmp + RTC_YEAR2000; /* Compute 0~12 month */ u32Tmp = (g_u32hiMonth * 10ul); sPt->u32Month = u32Tmp + g_u32loMonth; /* Compute 0~31 day */ u32Tmp = (g_u32hiDay * 10ul); sPt->u32Day = u32Tmp + g_u32loDay; /* Compute 12/24 hour */ if (sPt->u32TimeScale == RTC_CLOCK_12) { u32Tmp = (g_u32hiHour * 10ul); u32Tmp += g_u32loHour; sPt->u32Hour = u32Tmp; /* AM: 1~12. PM: 21~32. */ if (sPt->u32Hour >= 21ul) { sPt->u32AmPm = RTC_PM; sPt->u32Hour -= 20ul; } else { sPt->u32AmPm = RTC_AM; } u32Tmp = (g_u32hiMin * 10ul); u32Tmp += g_u32loMin; sPt->u32Minute = u32Tmp; u32Tmp = (g_u32hiSec * 10ul); u32Tmp += g_u32loSec; sPt->u32Second = u32Tmp; } else { u32Tmp = (g_u32hiHour * 10ul); u32Tmp += g_u32loHour; sPt->u32Hour = u32Tmp; u32Tmp = (g_u32hiMin * 10ul); u32Tmp += g_u32loMin; sPt->u32Minute = u32Tmp; u32Tmp = (g_u32hiSec * 10ul); u32Tmp += g_u32loSec; sPt->u32Second = u32Tmp; } } /** * @brief Get RTC Alarm Date and Time * * @param[out] sPt The returned pointer is specified the RTC alarm value. It includes: \n * u32Year: Year value \n * u32Month: Month value \n * u32Day: Day value \n * u32DayOfWeek: Day of week \n * u32Hour: Hour value \n * u32Minute: Minute value \n * u32Second: Second value \n * u32TimeScale: [RTC_CLOCK_12 / RTC_CLOCK_24] \n * u8AmPm: [RTC_AM / RTC_PM] \n * * @return None * * @details This API is used to get the RTC alarm date and time setting. */ void RTC_GetAlarmDateAndTime(S_RTC_TIME_DATA_T *sPt) { uint32_t u32Tmp; sPt->u32TimeScale = RTC->CLKFMT & RTC_CLKFMT_24HEN_Msk; /* 12/24-hour */ sPt->u32DayOfWeek = RTC->WEEKDAY & RTC_WEEKDAY_WEEKDAY_Msk; /* Day of the week */ /* Get alarm [Date digit] data */ RTC_WaitAccessEnable(); g_u32hiYear = (RTC->CALM & RTC_CALM_TENYEAR_Msk) >> RTC_CALM_TENYEAR_Pos; g_u32loYear = (RTC->CALM & RTC_CALM_YEAR_Msk) >> RTC_CALM_YEAR_Pos; g_u32hiMonth = (RTC->CALM & RTC_CALM_TENMON_Msk) >> RTC_CALM_TENMON_Pos; g_u32loMonth = (RTC->CALM & RTC_CALM_MON_Msk) >> RTC_CALM_MON_Pos; g_u32hiDay = (RTC->CALM & RTC_CALM_TENDAY_Msk) >> RTC_CALM_TENDAY_Pos; g_u32loDay = (RTC->CALM & RTC_CALM_DAY_Msk) >> RTC_CALM_DAY_Pos; /* Get alarm [Time digit] data */ RTC_WaitAccessEnable(); g_u32hiHour = (RTC->TALM & RTC_TALM_TENHR_Msk) >> RTC_TALM_TENHR_Pos; g_u32loHour = (RTC->TALM & RTC_TALM_HR_Msk) >> RTC_TALM_HR_Pos; g_u32hiMin = (RTC->TALM & RTC_TALM_TENMIN_Msk) >> RTC_TALM_TENMIN_Pos; g_u32loMin = (RTC->TALM & RTC_TALM_MIN_Msk) >> RTC_TALM_MIN_Pos; g_u32hiSec = (RTC->TALM & RTC_TALM_TENSEC_Msk) >> RTC_TALM_TENSEC_Pos; g_u32loSec = (RTC->TALM & RTC_TALM_SEC_Msk) >> RTC_TALM_SEC_Pos; /* Compute to 20XX year */ u32Tmp = (g_u32hiYear * 10ul); u32Tmp += g_u32loYear; sPt->u32Year = u32Tmp + RTC_YEAR2000; /* Compute 0~12 month */ u32Tmp = (g_u32hiMonth * 10ul); sPt->u32Month = u32Tmp + g_u32loMonth; /* Compute 0~31 day */ u32Tmp = (g_u32hiDay * 10ul); sPt->u32Day = u32Tmp + g_u32loDay; /* Compute 12/24 hour */ if (sPt->u32TimeScale == RTC_CLOCK_12) { u32Tmp = (g_u32hiHour * 10ul); u32Tmp += g_u32loHour; sPt->u32Hour = u32Tmp; /* AM: 1~12. PM: 21~32. */ if (sPt->u32Hour >= 21ul) { sPt->u32AmPm = RTC_PM; sPt->u32Hour -= 20ul; } else { sPt->u32AmPm = RTC_AM; } u32Tmp = (g_u32hiMin * 10ul); u32Tmp += g_u32loMin; sPt->u32Minute = u32Tmp; u32Tmp = (g_u32hiSec * 10ul); u32Tmp += g_u32loSec; sPt->u32Second = u32Tmp; } else { u32Tmp = (g_u32hiHour * 10ul); u32Tmp += g_u32loHour; sPt->u32Hour = u32Tmp; u32Tmp = (g_u32hiMin * 10ul); u32Tmp += g_u32loMin; sPt->u32Minute = u32Tmp; u32Tmp = (g_u32hiSec * 10ul); u32Tmp += g_u32loSec; sPt->u32Second = u32Tmp; } } /** * @brief Update Current RTC Date and Time * * @param[in] sPt Specify the time property and current date and time. It includes: \n * u32Year: Year value, range between 2000 ~ 2099. \n * u32Month: Month value, range between 1 ~ 12. \n * u32Day: Day value, range between 1 ~ 31. \n * u32DayOfWeek: Day of the week. [RTC_SUNDAY / RTC_MONDAY / RTC_TUESDAY / * RTC_WEDNESDAY / RTC_THURSDAY / RTC_FRIDAY / * RTC_SATURDAY] \n * u32Hour: Hour value, range between 0 ~ 23. \n * u32Minute: Minute value, range between 0 ~ 59. \n * u32Second: Second value, range between 0 ~ 59. \n * u32TimeScale: [RTC_CLOCK_12 / RTC_CLOCK_24] \n * u8AmPm: [RTC_AM / RTC_PM] \n * * @return None * * @details This API is used to update current date and time to RTC. */ void RTC_SetDateAndTime(S_RTC_TIME_DATA_T *sPt) { uint32_t u32RegCAL, u32RegTIME; if (sPt == NULL) { } else { /*-----------------------------------------------------------------------------------------------------*/ /* Set RTC 24/12 hour setting and Day of the Week */ /*-----------------------------------------------------------------------------------------------------*/ RTC_WaitAccessEnable(); if (sPt->u32TimeScale == RTC_CLOCK_12) { RTC_WaitAccessEnable(); RTC->CLKFMT &= ~RTC_CLKFMT_24HEN_Msk; RTC_Check(); /*-------------------------------------------------------------------------------------------------*/ /* Important, range of 12-hour PM mode is 21 up to 32 */ /*-------------------------------------------------------------------------------------------------*/ if (sPt->u32AmPm == RTC_PM) { sPt->u32Hour += 20ul; } } else { RTC_WaitAccessEnable(); RTC->CLKFMT |= RTC_CLKFMT_24HEN_Msk; RTC_Check(); } /* Set Day of the Week */ RTC_WaitAccessEnable(); RTC->WEEKDAY = sPt->u32DayOfWeek; RTC_Check(); /*-----------------------------------------------------------------------------------------------------*/ /* Set RTC Current Date and Time */ /*-----------------------------------------------------------------------------------------------------*/ u32RegCAL = ((sPt->u32Year - RTC_YEAR2000) / 10ul) << 20; u32RegCAL |= (((sPt->u32Year - RTC_YEAR2000) % 10ul) << 16); u32RegCAL |= ((sPt->u32Month / 10ul) << 12); u32RegCAL |= ((sPt->u32Month % 10ul) << 8); u32RegCAL |= ((sPt->u32Day / 10ul) << 4); u32RegCAL |= (sPt->u32Day % 10ul); u32RegTIME = ((sPt->u32Hour / 10ul) << 20); u32RegTIME |= ((sPt->u32Hour % 10ul) << 16); u32RegTIME |= ((sPt->u32Minute / 10ul) << 12); u32RegTIME |= ((sPt->u32Minute % 10ul) << 8); u32RegTIME |= ((sPt->u32Second / 10ul) << 4); u32RegTIME |= (sPt->u32Second % 10ul); /*-----------------------------------------------------------------------------------------------------*/ /* Set RTC Calender and Time Loading */ /*-----------------------------------------------------------------------------------------------------*/ RTC_WaitAccessEnable(); RTC->CAL = (uint32_t)u32RegCAL; RTC_Check(); RTC_WaitAccessEnable(); RTC->TIME = (uint32_t)u32RegTIME; RTC_Check(); } } /** * @brief Update RTC Alarm Date and Time * * @param[in] sPt Specify the time property and alarm date and time. It includes: \n * u32Year: Year value, range between 2000 ~ 2099. \n * u32Month: Month value, range between 1 ~ 12. \n * u32Day: Day value, range between 1 ~ 31. \n * u32DayOfWeek: Day of the week. [RTC_SUNDAY / RTC_MONDAY / RTC_TUESDAY / * RTC_WEDNESDAY / RTC_THURSDAY / RTC_FRIDAY / * RTC_SATURDAY] \n * u32Hour: Hour value, range between 0 ~ 23. \n * u32Minute: Minute value, range between 0 ~ 59. \n * u32Second: Second value, range between 0 ~ 59. \n * u32TimeScale: [RTC_CLOCK_12 / RTC_CLOCK_24] \n * u8AmPm: [RTC_AM / RTC_PM] \n * * @return None * * @details This API is used to update alarm date and time setting to RTC. */ void RTC_SetAlarmDateAndTime(S_RTC_TIME_DATA_T *sPt) { uint32_t u32RegCALM, u32RegTALM; if (sPt == 0) { } else { /*-----------------------------------------------------------------------------------------------------*/ /* Set RTC 24/12 hour setting and Day of the Week */ /*-----------------------------------------------------------------------------------------------------*/ RTC_WaitAccessEnable(); if (sPt->u32TimeScale == RTC_CLOCK_12) { RTC->CLKFMT &= ~RTC_CLKFMT_24HEN_Msk; /*-------------------------------------------------------------------------------------------------*/ /* Important, range of 12-hour PM mode is 21 up to 32 */ /*-------------------------------------------------------------------------------------------------*/ if (sPt->u32AmPm == RTC_PM) { sPt->u32Hour += 20ul; } } else { RTC->CLKFMT |= RTC_CLKFMT_24HEN_Msk; } RTC_Check(); /*-----------------------------------------------------------------------------------------------------*/ /* Set RTC Alarm Date and Time */ /*-----------------------------------------------------------------------------------------------------*/ u32RegCALM = ((sPt->u32Year - RTC_YEAR2000) / 10ul) << 20; u32RegCALM |= (((sPt->u32Year - RTC_YEAR2000) % 10ul) << 16); u32RegCALM |= ((sPt->u32Month / 10ul) << 12); u32RegCALM |= ((sPt->u32Month % 10ul) << 8); u32RegCALM |= ((sPt->u32Day / 10ul) << 4); u32RegCALM |= (sPt->u32Day % 10ul); u32RegCALM |= (sPt->u32DayOfWeek << 24); u32RegTALM = ((sPt->u32Hour / 10ul) << 20); u32RegTALM |= ((sPt->u32Hour % 10ul) << 16); u32RegTALM |= ((sPt->u32Minute / 10ul) << 12); u32RegTALM |= ((sPt->u32Minute % 10ul) << 8); u32RegTALM |= ((sPt->u32Second / 10ul) << 4); u32RegTALM |= (sPt->u32Second % 10ul); RTC_WaitAccessEnable(); RTC->CALM = (uint32_t)u32RegCALM; RTC_Check(); RTC_WaitAccessEnable(); RTC->TALM = (uint32_t)u32RegTALM; RTC_Check(); } } /** * @brief Update RTC Current Date * * @param[in] u32Year The year calendar digit of current RTC setting. * @param[in] u32Month The month calendar digit of current RTC setting. * @param[in] u32Day The day calendar digit of current RTC setting. * @param[in] u32DayOfWeek The Day of the week. [RTC_SUNDAY / RTC_MONDAY / RTC_TUESDAY / * RTC_WEDNESDAY / RTC_THURSDAY / RTC_FRIDAY / * RTC_SATURDAY] * * @return None * * @details This API is used to update current date to RTC. */ void RTC_SetDate(uint32_t u32Year, uint32_t u32Month, uint32_t u32Day, uint32_t u32DayOfWeek) { uint32_t u32RegCAL; u32RegCAL = ((u32Year - RTC_YEAR2000) / 10ul) << 20; u32RegCAL |= (((u32Year - RTC_YEAR2000) % 10ul) << 16); u32RegCAL |= ((u32Month / 10ul) << 12); u32RegCAL |= ((u32Month % 10ul) << 8); u32RegCAL |= ((u32Day / 10ul) << 4); u32RegCAL |= (u32Day % 10ul); /* Set Day of the Week */ RTC_WaitAccessEnable(); RTC->WEEKDAY = u32DayOfWeek & RTC_WEEKDAY_WEEKDAY_Msk; RTC_Check(); /* Set RTC Calender Loading */ RTC_WaitAccessEnable(); RTC->CAL = (uint32_t)u32RegCAL; RTC_Check(); } /** * @brief Update RTC Current Time * * @param[in] u32Hour The hour time digit of current RTC setting. * @param[in] u32Minute The minute time digit of current RTC setting. * @param[in] u32Second The second time digit of current RTC setting. * @param[in] u32TimeMode The 24-Hour / 12-Hour Time Scale Selection. [RTC_CLOCK_12 / RTC_CLOCK_24] * @param[in] u32AmPm 12-hour time scale with AM and PM indication. Only Time Scale select 12-hour used. [RTC_AM / RTC_PM] * * @return None * * @details This API is used to update current time to RTC. */ void RTC_SetTime(uint32_t u32Hour, uint32_t u32Minute, uint32_t u32Second, uint32_t u32TimeMode, uint32_t u32AmPm) { uint32_t u32RegTIME; /* Important, range of 12-hour PM mode is 21 up to 32 */ if ((u32TimeMode == RTC_CLOCK_12) && (u32AmPm == RTC_PM)) { u32Hour += 20ul; } u32RegTIME = ((u32Hour / 10ul) << 20); u32RegTIME |= ((u32Hour % 10ul) << 16); u32RegTIME |= ((u32Minute / 10ul) << 12); u32RegTIME |= ((u32Minute % 10ul) << 8); u32RegTIME |= ((u32Second / 10ul) << 4); u32RegTIME |= (u32Second % 10ul); /*-----------------------------------------------------------------------------------------------------*/ /* Set RTC 24/12 hour setting and Day of the Week */ /*-----------------------------------------------------------------------------------------------------*/ RTC_WaitAccessEnable(); if (u32TimeMode == RTC_CLOCK_12) { RTC->CLKFMT &= ~RTC_CLKFMT_24HEN_Msk; } else { RTC->CLKFMT |= RTC_CLKFMT_24HEN_Msk; } RTC_Check(); RTC_WaitAccessEnable(); RTC->TIME = (uint32_t)u32RegTIME; RTC_Check(); } /** * @brief Update RTC Alarm Date * * @param[in] u32Year The year calendar digit of RTC alarm setting. * @param[in] u32Month The month calendar digit of RTC alarm setting. * @param[in] u32Day The day calendar digit of RTC alarm setting. * @param[in] u32DayOfWeek The day of week * * @return None * * @details This API is used to update alarm date setting to RTC. */ void RTC_SetAlarmDate(uint32_t u32Year, uint32_t u32Month, uint32_t u32Day, uint32_t u32DayOfWeek) { uint32_t u32RegCALM; u32RegCALM = ((u32Year - RTC_YEAR2000) / 10ul) << 20; u32RegCALM |= (((u32Year - RTC_YEAR2000) % 10ul) << 16); u32RegCALM |= ((u32Month / 10ul) << 12); u32RegCALM |= ((u32Month % 10ul) << 8); u32RegCALM |= ((u32Day / 10ul) << 4); u32RegCALM |= (u32Day % 10ul); u32RegCALM |= (u32DayOfWeek << 24); RTC_WaitAccessEnable(); /* Set RTC Alarm Date */ RTC->CALM = (uint32_t)u32RegCALM; RTC_Check(); } /** * @brief Update RTC Alarm Time * * @param[in] u32Hour The hour time digit of RTC alarm setting. * @param[in] u32Minute The minute time digit of RTC alarm setting. * @param[in] u32Second The second time digit of RTC alarm setting. * @param[in] u32TimeMode The 24-Hour / 12-Hour Time Scale Selection. [RTC_CLOCK_12 / RTC_CLOCK_24] * @param[in] u32AmPm 12-hour time scale with AM and PM indication. Only Time Scale select 12-hour used. [RTC_AM / RTC_PM] * * @return None * * @details This API is used to update alarm time setting to RTC. */ void RTC_SetAlarmTime(uint32_t u32Hour, uint32_t u32Minute, uint32_t u32Second, uint32_t u32TimeMode, uint32_t u32AmPm) { uint32_t u32RegTALM; /* Important, range of 12-hour PM mode is 21 up to 32 */ if ((u32TimeMode == RTC_CLOCK_12) && (u32AmPm == RTC_PM)) { u32Hour += 20ul; } u32RegTALM = ((u32Hour / 10ul) << 20); u32RegTALM |= ((u32Hour % 10ul) << 16); u32RegTALM |= ((u32Minute / 10ul) << 12); u32RegTALM |= ((u32Minute % 10ul) << 8); u32RegTALM |= ((u32Second / 10ul) << 4); u32RegTALM |= (u32Second % 10ul); /*-----------------------------------------------------------------------------------------------------*/ /* Set RTC 24/12 hour setting and Day of the Week */ /*-----------------------------------------------------------------------------------------------------*/ RTC_WaitAccessEnable(); if (u32TimeMode == RTC_CLOCK_12) { RTC->CLKFMT &= ~RTC_CLKFMT_24HEN_Msk; } else { RTC->CLKFMT |= RTC_CLKFMT_24HEN_Msk; } RTC_Check(); /* Set RTC Alarm Time */ RTC_WaitAccessEnable(); RTC->TALM = (uint32_t)u32RegTALM; RTC_Check(); } /** * @brief Get Day of the Week * * @param None * * @retval 0 Sunday * @retval 1 Monday * @retval 2 Tuesday * @retval 3 Wednesday * @retval 4 Thursday * @retval 5 Friday * @retval 6 Saturday * * @details This API is used to get day of the week of current RTC date. */ uint32_t RTC_GetDayOfWeek(void) { return (RTC->WEEKDAY & RTC_WEEKDAY_WEEKDAY_Msk); } /** * @brief Set RTC Tick Period Time * * @param[in] u32TickSelection It is used to set the RTC tick period time for Periodic Time Tick request. \n * It consists of: * - \ref RTC_TICK_1_SEC : Time tick is 1 second * - \ref RTC_TICK_1_2_SEC : Time tick is 1/2 second * - \ref RTC_TICK_1_4_SEC : Time tick is 1/4 second * - \ref RTC_TICK_1_8_SEC : Time tick is 1/8 second * - \ref RTC_TICK_1_16_SEC : Time tick is 1/16 second * - \ref RTC_TICK_1_32_SEC : Time tick is 1/32 second * - \ref RTC_TICK_1_64_SEC : Time tick is 1/64 second * - \ref RTC_TICK_1_128_SEC : Time tick is 1/128 second * * @return None * * @details This API is used to set RTC tick period time for each tick interrupt. */ void RTC_SetTickPeriod(uint32_t u32TickSelection) { RTC_WaitAccessEnable(); RTC->TICK = (RTC->TICK & ~RTC_TICK_TICK_Msk) | u32TickSelection; RTC_Check(); } /** * @brief Enable RTC Interrupt * * @param[in] u32IntFlagMask Specify the interrupt source. It consists of: * - \ref RTC_INTEN_ALMIEN_Msk : Alarm interrupt * - \ref RTC_INTEN_TICKIEN_Msk : Tick interrupt * * @return None * * @details This API is used to enable the specify RTC interrupt function. */ void RTC_EnableInt(uint32_t u32IntFlagMask) { RTC_WaitAccessEnable(); RTC->INTEN |= u32IntFlagMask; RTC_Check(); if (u32IntFlagMask & RTC_INTEN_ALMIEN_Msk) { RTC_WaitAccessEnable(); RTC->PWRCTL |= RTC_PWRCTL_ALARM_EN_Msk; RTC_Check(); } if (u32IntFlagMask & RTC_INTEN_RELALMIEN_Msk) { RTC_WaitAccessEnable(); RTC->PWRCTL |= RTC_PWRCTL_REL_ALARM_EN_Msk; RTC_Check(); } } /** * @brief Disable RTC Interrupt * * @param[in] u32IntFlagMask Specify the interrupt source. It consists of: * - \ref RTC_INTEN_ALMIEN_Msk : Alarm interrupt * - \ref RTC_INTEN_TICKIEN_Msk : Tick interrupt * * @return None * * @details This API is used to disable the specify RTC interrupt function. */ void RTC_DisableInt(uint32_t u32IntFlagMask) { RTC_WaitAccessEnable(); RTC->INTEN &= ~u32IntFlagMask; RTC_Check(); RTC_WaitAccessEnable(); RTC->INTSTS = u32IntFlagMask; RTC_Check(); } /** * @brief Wait RTC Access Enable * * @param None * * @return None * * @details This function is used to enable the maximum RTC read/write accessible time. */ void RTC_WaitAccessEnable(void) { INT32 volatile i32i; RTC_Check(); outp32(REG_RTC_RWEN, RTC_WRITE_KEY); RTC_Check(); while (!(inp32(REG_RTC_RWEN) & 0x10000)); } void RTC_Check(void) { uint32_t i = 0; uint32_t Wait; Wait = inp32(REG_RTC_INTSTS) & RTC_INTSTS_REGWRBUSY_Msk; while (Wait == RTC_INTSTS_REGWRBUSY_Msk) { Wait = inp32(REG_RTC_INTSTS) & RTC_INTSTS_REGWRBUSY_Msk; i++; if (i > RTC_WAIT_COUNT) { //printf("Time out\n"); break; } } } /*@}*/ /* end of group RTC_EXPORTED_FUNCTIONS */ /*@}*/ /* end of group RTC_Driver */ /*@}*/ /* end of group Standard_Driver */ /*** (C) COPYRIGHT 2016 Nuvoton Technology Corp. ***/
634cd11ab1abcff32142746cfada985137c15039
bbfaa979248a82d2510b4e0c4bd56fc9bf63e149
/src/iks_grammar.c
3fdd27f9496f671613c1f7572432b6842a39de60
[]
no_license
germanoa/compiladores
4100d257a142f710f0678a3c6ce62780bb4038ca
389327e810d9c5da2ca1655fb6e27c05aab1d5c9
refs/heads/master
2022-08-13T05:50:51.436789
2022-07-15T02:45:40
2022-07-15T02:45:40
12,012,798
713
299
null
2013-10-15T14:28:39
2013-08-09T23:46:26
C
UTF-8
C
false
false
11,263
c
iks_grammar.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "iks_grammar.h" #include "iks_dict.h" #include "iks_types.h" #include "iks_ast.h" static inline void __iks_grammar_symbol_init(iks_grammar_symbol_t *grammar_symbol) { grammar_symbol->token_type = IKS_SIMBOLO_INDEFINIDO; grammar_symbol->code_line_number = 0; grammar_symbol->value = NULL; grammar_symbol->decl_type = 0; grammar_symbol->iks_type = IKS_NOTYPE; grammar_symbol->iks_size = 0; grammar_symbol->symbol_table = NULL; grammar_symbol->params = new_iks_list(); grammar_symbol->addr_offset = 0; grammar_symbol->num_dimen = 0; grammar_symbol->dimens = new_iks_list(); } iks_grammar_symbol_t *new_iks_grammar_symbol() { iks_grammar_symbol_t *grammar_symbol; grammar_symbol = malloc(sizeof(iks_grammar_symbol_t)); __iks_grammar_symbol_init(grammar_symbol); return grammar_symbol; } void iks_grammar_symbol_delete(iks_grammar_symbol_t *grammar_symbol) { free(grammar_symbol->value); grammar_symbol->value = NULL; free(grammar_symbol); grammar_symbol = NULL; } void iks_grammar_symbol_set(iks_grammar_symbol_t *grammar_symbol, int token_type, int code_line_number, char *value) { grammar_symbol->token_type = token_type; grammar_symbol->code_line_number = code_line_number; grammar_symbol->value = value; } void iks_grammar_symbol_print(iks_grammar_symbol_t *grammar_symbol) { printf("%s\n",grammar_symbol->value); } void symbol_table_append(char *identifier, iks_grammar_symbol_t *symbol, iks_dict_t *symbol_table) { iks_dict_t *new_entry; new_entry = new_iks_dict(); if (iks_dict_is_empty(symbol_table)) { symbol_table->item = new_iks_dict_item(); iks_dict_item_set(symbol_table->item,identifier,(void *)symbol); symbol_table->next=new_entry; symbol_table->prev=new_entry; new_entry->next=symbol_table; new_entry->prev=symbol_table; //new_entry->item = new_iks_dict_item(); //iks_grammar_symbol_t *symbol; //symbol = new_iks_grammar_symbol(); //iks_dict_item_set(new_entry->item,NULL,(void *)symbol); } else { new_entry->item = new_iks_dict_item(); iks_dict_item_set(new_entry->item,identifier,(void *)symbol); iks_dict_append(symbol_table,new_entry); } } void symbol_table_init() { //symbol_table = new_iks_dict(); //iks_grammar_symbol_t *symbol; //symbol = new_iks_grammar_symbol(); //symbol_table->item = new_iks_dict_item(); //iks_dict_item_set(symbol_table->item,"empty",(void *)symbol); } void symbol_table_delete(iks_dict_t *dict) { if (!iks_dict_is_empty(dict)) { iks_dict_t *temp; temp = dict->next; do { temp = temp->next; if (temp->prev->item) { iks_grammar_symbol_delete((iks_grammar_symbol_t*)temp->prev->item); } free(temp->prev); temp->prev = NULL; } while(temp != dict); } if (dict->item) { iks_ast_node_value_delete((iks_ast_node_value_t*)dict->item); } free(dict); dict = NULL; } void symbol_table_print(iks_dict_t *symbol_table) { //printf("imprimindo: %X\n",symbol_table); iks_dict_t *temp; temp = symbol_table; int i=0; do { if (temp->item) { if (temp->item->value) { iks_grammar_symbol_t *s; s = temp->item->value; printf("symbol: %s\n\ttoken_type: %d\n\tline: %d\n\tidentifier: %s\n\tsymbol_table: %X\n\tdecl_type: %d\n\tiks_size: %d\n\t iks_type: %d\n", \ iks_dict_item_key_get(temp->item),\ s->token_type,\ s->code_line_number,\ s->value,\ s->symbol_table,\ s->decl_type,\ s->iks_size,\ s->iks_type); }} temp = temp->next; } while(temp != symbol_table); printf("\n"); } iks_grammar_symbol_t *search_symbol_global(iks_grammar_symbol_t *symbol, iks_stack_t *scope) { iks_grammar_symbol_t *ret=NULL; iks_stack_t *it_scope; it_scope = scope; scope_t *scp; iks_dict_t *symbol_table; do { //symbol_table = iks_stack_top(it_scope); scp = iks_stack_top(it_scope); symbol_table = scp->st; //printf("global looking for %s at: %X\n",symbol->value,symbol_table); ret = search_symbol_local(symbol,symbol_table); it_scope = it_scope->below; } while ((ret==NULL) && (it_scope != it_scope->below)); if (ret==NULL) { //look at global //ret = search_symbol_local(symbol,iks_stack_top(it_scope)); scp = iks_stack_top(it_scope); symbol_table = scp->st; ret = search_symbol_local(symbol,symbol_table); } return ret; } iks_grammar_symbol_t *search_symbol_local(iks_grammar_symbol_t *symbol, iks_dict_t *symbol_table) { iks_grammar_symbol_t *ret =NULL; //printf("local looking at: %X\n",symbol_table); if (!iks_dict_is_empty(symbol_table)) { iks_dict_t *temp; temp = symbol_table; do { if (temp->item) { if (temp->item->value) { iks_grammar_symbol_t *s; s = temp->item->value; int diff = strcmp(symbol->value,s->value); //printf("%s == %s :%d\n",symbol->value,s->value,diff); if (!diff) { ret = s; break; } }} temp = temp->next; } while(temp != symbol_table); } return ret; } int exist_symbol_local(iks_grammar_symbol_t *symbol, iks_dict_t *symbol_table) { int ret = 0; //printf("local looking at: %X\n",symbol_table); if (!iks_dict_is_empty(symbol_table)) { iks_dict_t *temp; temp = symbol_table; do { if (temp->item) { if (temp->item->value) { iks_grammar_symbol_t *s; s = temp->item->value; int diff = strcmp(symbol->value,s->value); //printf("%s == %s :%d\n",symbol->value,s->value,diff); if (!diff) { ret = 1; break; } }} temp = temp->next; } while(temp != symbol_table); } return ret; } //int decl_symbol(iks_grammar_symbol_t *s,int iks_type, int decl_type, void *symbol_table, iks_grammar_symbol_t *function_with_param) { int decl_symbol(iks_grammar_symbol_t *s,int iks_type, int decl_type, scope_t *scope, iks_grammar_symbol_t *function_with_param) { int ret=1; s->iks_type = iks_type; //iks_dict_t *symbol_table = (iks_dict_t*) iks_stack_top(scope->st); iks_dict_t *symbol_table = scope->st; switch (iks_type) { case IKS_INT: s->iks_size=4; break; case IKS_FLOAT: s->iks_size=8; break; case IKS_BOOL: s->iks_size=1; break; case IKS_CHAR: s->iks_size=1; break; case IKS_STRING: s->iks_size=1; break; } s->decl_type = decl_type; s->symbol_table = (iks_dict_t*)symbol_table; s->scope_type = scope->type; if (s->decl_type==IKS_DECL_VAR) { if (scope->type==IKS_SCOPE_LOCAL) { s->addr_offset = scope->next_addr + 16; //RA offset } else { s->addr_offset = scope->next_addr; } scope->next_addr += s->iks_size; } if (!exist_symbol_local(s,s->symbol_table)) { symbol_table_append(s->value,s,s->symbol_table); if (function_with_param) { iks_list_append(function_with_param->params,(void*)s); } } else { ret=0; fprintf(stderr,"line %d: identificador '%s' já declarado\n",s->code_line_number,s->value); } return ret; } int update_vector_symbol(iks_grammar_symbol_t *s,unsigned int dimen_counter,iks_list_t *dimens) { //s->iks_size = s->iks_size * atoi(lit->value); if(s != NULL && dimens != NULL) { s->decl_type = IKS_DECL_VECTOR; s->num_dimen = dimen_counter; s->dimens = dimens; iks_list_t *d = dimens; int *size = NULL; do { size = d->item; if(*size < 0) return iks_error(s, IKS_ERROR_DECL); d = d->next; } while(d != dimens); } else fprintf(stderr,"erro interno: parâmetros inválidos para update_vector_symbol.\n"); return 0; } int symbol_is_decl_type(iks_grammar_symbol_t *s,int decl_type) { int ret=1; if (!(s->decl_type==decl_type)) { ret=0; } return ret; } int iks_error(iks_grammar_symbol_t *s, int error_type) { int ret=0; switch(error_type) { case IKS_ERROR_USE: if (s->decl_type==IKS_DECL_VAR) { fprintf(stderr,"line %d: identificador '%s' deve ser usado como variavel\n",s->code_line_number,s->value); ret=IKS_ERROR_VARIABLE; } else if (s->decl_type==IKS_DECL_VECTOR) { fprintf(stderr,"line %d: identificador '%s' deve ser usado como vetor\n",s->code_line_number,s->value); ret=IKS_ERROR_VECTOR; } else if (s->decl_type==IKS_DECL_FUNCTION) { fprintf(stderr,"line %d: identificador '%s' deve ser usado como funcao\n",s->code_line_number,s->value); ret=IKS_ERROR_FUNCTION; } else { fprintf(stderr,"line %d: identificador '%s' ???????????\n",s->code_line_number,s->value); ret=99999; } break; case IKS_ERROR_WRONG_PAR_RETURN: fprintf(stderr,"parametro nao e compativel com expressao de retorno.\n"); ret=IKS_ERROR_WRONG_PAR_RETURN; break; case IKS_ERROR_WRONG_PAR_INPUT: if(s != NULL) fprintf(stderr,"line %d: '%s' deve ser identificador\n",s->code_line_number,s->value); else fprintf(stderr,"parâmetro para input deve ser identificador\n"); ret = IKS_ERROR_WRONG_PAR_INPUT; break; case IKS_ERROR_DECL: if(s != NULL) { if(s->decl_type == IKS_DECL_VECTOR) fprintf(stderr,"line %d: declaração de vetor %s inválida. dimensões negativas?\n", s->code_line_number,s->value); else fprintf(stderr,"line %d: declaração de %s inválida.\n", s->code_line_number,s->value); } else fprintf(stderr,"declaração inválida.\n"); ret = IKS_ERROR_DECL; break; default: fprintf(stderr,"código de erro %d indesperado.\n", error_type); break; } return ret; } int verify_function_args(iks_grammar_symbol_t *s, iks_list_t *args) { int ret=0; iks_grammar_symbol_t *s1,*s2; iks_list_t *l1,*l2; int sl1,sl2,diff; l1 = s->params->next; l2 = args->next; sl1 = iks_list_size(s->params->next); sl2 = iks_list_size(args->next); diff = sl1-sl2; if (diff!=0) { if (sl1>sl2) { fprintf(stderr,"faltam %d argumentos em '%s'\n",diff,s->value); ret=IKS_ERROR_MISSING_ARGS; } else { fprintf(stderr,"sobram %d argumentos em '%s'\n",diff*-1,s->value); ret=IKS_ERROR_EXCESS_ARGS; } } else if (sl1!=0){ do { s1 = l1->item; s2 = l2->item; if (s1->iks_type!=s2->iks_type) { fprintf(stderr,"tipos incompativeis entre '%s' e '%s'\n",s1->value,s2->value); ret=IKS_ERROR_WRONG_TYPE_ARGS; break; } l1 = l1->next; l2 = l2->next; } while(l1 != s->params); } return ret; } int symbol_is_iks_type(iks_grammar_symbol_t *s,int iks_type) { int ret=1; //printf("%d vs %d\n",s->iks_type,iks_type); if (!(s->iks_type==iks_type)) { ret=0; } return ret; }
63e0001d0d389b5aa19c756eea4bc15249cf1166
13e2a9bf3ebb4d2c6cdcc5b3cadaa9d87d94933e
/src/game/scenes/mechlab/lab_menu_main.c
379124cae60dd5a1c334d550cf275352fa23c3eb
[ "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
10,230
c
lab_menu_main.c
#include "game/scenes/mechlab/lab_menu_main.h" #include "formats/chr.h" #include "game/common_defines.h" #include "game/gui/sizer.h" #include "game/gui/spritebutton.h" #include "game/gui/text_render.h" #include "game/gui/trn_menu.h" #include "game/scenes/mechlab.h" #include "game/scenes/mechlab/button_details.h" #include "game/scenes/mechlab/lab_menu_customize.h" #include "game/scenes/mechlab/lab_menu_training.h" #include "resources/bk.h" #include "resources/languages.h" #include "resources/sgmanager.h" #include "utils/allocator.h" #include "utils/log.h" void lab_menu_main_arena(component *c, void *userdata) { scene *s = userdata; sd_chr_enemy *enemy = mechlab_next_opponent(s); if(enemy) { // make a new AI controller controller *ctrl = omf_calloc(1, sizeof(controller)); controller_init(ctrl); sd_pilot *pilot = &enemy->pilot; game_player *p1 = game_state_get_player(s->gs, 0); game_player *p2 = game_state_get_player(s->gs, 1); p2->selectable = 0; p2->pilot = pilot; // there's not an exact difficulty mapping // for aluminum to 1p mode, but round up to // veteran int difficulty = AI_DIFFICULTY_VETERAN; if(p1->pilot->difficulty == 1) { // Iron == Champion difficulty = AI_DIFFICULTY_CHAMPION; } else if(p1->pilot->difficulty == 2) { // Steel == Deadly difficulty = AI_DIFFICULTY_DEADLY; } else if(p1->pilot->difficulty == 3) { // Heavy Metal == F.A.A.K. 2 difficulty = AI_DIFFICULTY_ULTIMATE; } ai_controller_create(ctrl, difficulty, pilot, p2->pilot->pilot_id); game_player_set_ctrl(p2, ctrl); // reset the score between matches in tournament mode // assume we used the score by now if we need it for // winnings calculations, etc chr_score_reset_wins(game_player_get_score(p1)); chr_score_reset(game_player_get_score(p1), 1); // set the score difficulty chr_score_set_difficulty(game_player_get_score(game_state_get_player(s->gs, 0)), difficulty); game_state_set_next(s->gs, SCENE_VS); } } void lab_menu_main_quit(component *c, void *userdata) { scene *s = userdata; game_state_set_next(s->gs, SCENE_MENU); } void lab_menu_main_buy_enter(component *c, void *userdata) { scene *s = userdata; mechlab_set_selling(s, false); trnmenu_set_submenu(c->parent, lab_menu_customize_create(s)); } void lab_menu_main_sell_enter(component *c, void *userdata) { scene *s = userdata; mechlab_set_selling(s, true); trnmenu_set_submenu(c->parent, lab_menu_customize_create(s)); } void lab_menu_main_training_enter(component *c, void *userdata) { scene *s = userdata; trnmenu_set_submenu(c->parent, lab_menu_training_create(s)); } void lab_menu_main_new(component *c, void *userdata) { scene *s = userdata; mechlab_select_dashboard(s, DASHBOARD_NEW); } void lab_menu_main_tournament(component *c, void *userdata) { scene *s = userdata; mechlab_select_dashboard(s, DASHBOARD_SELECT_TOURNAMENT); mechlab_enter_trnselect_menu(s); } void lab_menu_main_load(component *c, void *userdata) { scene *s = userdata; game_player *p1 = game_state_get_player(s->gs, 0); if(sg_count() == 1 && p1->chr) { // TODO one and only loaded return; } else if(sg_count() == 0) { // TODO none to load return; } trnmenu_set_submenu(c->parent, mechlab_chrload_menu_create(s)); } void lab_menu_main_delete(component *c, void *userdata) { scene *s = userdata; game_player *p1 = game_state_get_player(s->gs, 0); if(sg_count() < 2 && p1->chr) { // none to delete return; } trnmenu_set_submenu(c->parent, mechlab_chrdelete_menu_create(s)); } static const button_details details_list[] = { // CB, Text, Text align, Halign, Valigh, Pad top, Pad bottom, Pad left, Pad right, Disable by default {lab_menu_main_arena, "ARENA", TEXT_HORIZONTAL, TEXT_CENTER, TEXT_TOP, 2, 0, 0, 0, COM_DISABLED}, {lab_menu_main_training_enter, "TRAINING COURSES", TEXT_HORIZONTAL, TEXT_CENTER, TEXT_MIDDLE, 0, 0, 28, 0, COM_DISABLED }, {lab_menu_main_buy_enter, "BUY", TEXT_HORIZONTAL, TEXT_CENTER, TEXT_TOP, 2, 0, 0, 0, COM_DISABLED}, {lab_menu_main_sell_enter, "SELL", TEXT_HORIZONTAL, TEXT_CENTER, TEXT_TOP, 2, 0, 0, 0, COM_DISABLED}, {lab_menu_main_load, "LOAD", TEXT_HORIZONTAL, TEXT_CENTER, TEXT_MIDDLE, 0, 0, 14, 0, COM_ENABLED }, {lab_menu_main_new, "NEW", TEXT_HORIZONTAL, TEXT_CENTER, TEXT_MIDDLE, 0, 0, 14, 0, COM_ENABLED }, {lab_menu_main_delete, "DELETE", TEXT_HORIZONTAL, TEXT_CENTER, TEXT_MIDDLE, 0, 0, 14, 0, COM_DISABLED}, {NULL, "SIM", TEXT_HORIZONTAL, TEXT_CENTER, TEXT_TOP, 2, 0, 0, 0, COM_DISABLED}, {lab_menu_main_quit, "QUIT", TEXT_VERTICAL, TEXT_CENTER, TEXT_MIDDLE, 0, 0, 0, 0, COM_ENABLED }, {lab_menu_main_tournament, "NEW TOURNAMENT", TEXT_HORIZONTAL, TEXT_CENTER, TEXT_MIDDLE, 0, 0, 0, 0, COM_DISABLED}, }; void lab_menu_focus_arena(component *c, bool focused, void *userdata) { if(focused) { scene *s = userdata; sd_chr_enemy *enemy = mechlab_next_opponent(s); if(enemy) { char tmp[100]; snprintf(tmp, 100, lang_get(537), enemy->pilot.name); mechlab_set_hint(s, tmp); } } } void lab_menu_focus_training(component *c, bool focused, void *userdata) { if(focused) { scene *s = userdata; mechlab_set_hint(s, lang_get(538)); } } void lab_menu_focus_buy(component *c, bool focused, void *userdata) { if(focused) { scene *s = userdata; mechlab_set_hint(s, lang_get(539)); } } void lab_menu_focus_sell(component *c, bool focused, void *userdata) { if(focused) { scene *s = userdata; mechlab_set_hint(s, lang_get(540)); } } void lab_menu_focus_load(component *c, bool focused, void *userdata) { if(focused) { scene *s = userdata; mechlab_set_hint(s, lang_get(541)); } } void lab_menu_focus_new(component *c, bool focused, void *userdata) { if(focused) { scene *s = userdata; mechlab_set_hint(s, lang_get(542)); } } void lab_menu_focus_delete(component *c, bool focused, void *userdata) { if(focused) { scene *s = userdata; mechlab_set_hint(s, lang_get(543)); } } void lab_menu_focus_sim(component *c, bool focused, void *userdata) { if(focused) { scene *s = userdata; mechlab_set_hint(s, lang_get(544)); } } void lab_menu_focus_quit(component *c, bool focused, void *userdata) { if(focused) { scene *s = userdata; mechlab_set_hint(s, lang_get(545)); } } void lab_menu_focus_tournament(component *c, bool focused, void *userdata) { if(focused) { scene *s = userdata; mechlab_set_hint(s, lang_get(546)); } } static const spritebutton_focus_cb focus_cbs[] = { lab_menu_focus_arena, lab_menu_focus_training, lab_menu_focus_buy, lab_menu_focus_sell, lab_menu_focus_load, lab_menu_focus_new, lab_menu_focus_delete, lab_menu_focus_sim, lab_menu_focus_quit, lab_menu_focus_tournament, }; void lab_menu_tick_arena(component *c, void *userdata) { scene *s = userdata; game_player *p1 = game_state_get_player(s->gs, 0); if(p1->chr && p1->chr->pilot.rank > 1) { component_disable(c, 0); c->supports_select = true; } else { component_disable(c, 1); c->supports_select = false; } } static const spritebutton_tick_cb tick_cbs[] = { lab_menu_tick_arena, NULL, // lab_menu_tick_training, NULL, // lab_menu_tick_buy, NULL, // lab_menu_tick_sell, NULL, // lab_menu_tick_load, NULL, // lab_menu_tick_new, NULL, // lab_menu_tick_delete, NULL, // lab_menu_tick_sim, NULL, // lab_menu_tick_quit, NULL, // lab_menu_tick_tournament, }; component *lab_menu_main_create(scene *s, bool character_loaded) { animation *main_sheets = &bk_get_info(&s->bk_data, 1)->ani; animation *main_buttons = &bk_get_info(&s->bk_data, 8)->ani; animation *hand_of_doom = &bk_get_info(&s->bk_data, 29)->ani; // Initialize menu, and set button sheet sprite *msprite = animation_get_sprite(main_sheets, 2); component *menu = trnmenu_create(msprite->data, msprite->pos.x, msprite->pos.y); // Default text configuration text_settings tconf; text_defaults(&tconf); tconf.font = FONT_SMALL; tconf.cforeground = color_create(0, 0, 123, 255); // Init GUI buttons with locations from the "select" button sprites for(int i = 0; i < animation_get_sprite_count(main_buttons); i++) { tconf.valign = details_list[i].valign; tconf.halign = details_list[i].halign; tconf.padding.top = details_list[i].top; tconf.padding.bottom = details_list[i].bottom; tconf.padding.left = details_list[i].left; tconf.padding.right = details_list[i].right; tconf.direction = details_list[i].dir; sprite *bsprite = animation_get_sprite(main_buttons, i); bool enabled = details_list[i].enabled; if(details_list[i].enabled == COM_DISABLED && character_loaded == true) { enabled = COM_ENABLED; } component *button = spritebutton_create(&tconf, details_list[i].text, bsprite->data, enabled, details_list[i].cb, s); component_set_size_hints(button, bsprite->data->w, bsprite->data->h); component_set_pos_hints(button, bsprite->pos.x, bsprite->pos.y); spritebutton_set_focus_cb(button, focus_cbs[i]); spritebutton_set_tick_cb(button, tick_cbs[i]); component_tick(button); trnmenu_attach(menu, button); } // Bind hand animation trnmenu_bind_hand(menu, hand_of_doom, s->gs); return menu; }
29ecbb3125ac0725b3e6cef49a83e1521283d4d3
5239f49116d3115ca917118c5f2ae0c21364a345
/kernel/fbsd/ena/ena.h
8eaa6c3b9132e47076fb8236499dee994047c071
[ "BSD-2-Clause" ]
permissive
amzn/amzn-drivers
faede4f6aeb42afc9e4e9a21c65ae79b37d22d1f
ff33e2f3144201cac8996fd10a88655bbc98dcd1
refs/heads/master
2023-09-01T07:20:42.549128
2023-08-24T09:27:08
2023-08-24T09:27:08
52,391,212
451
184
null
2023-08-24T08:26:21
2016-02-23T20:59:03
C
UTF-8
C
false
false
14,348
h
ena.h
/*- * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2015-2020 Amazon.com, Inc. or its affiliates. * 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 * 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. * * $FreeBSD$ * */ #ifndef ENA_H #define ENA_H #include "ena_com/ena_com.h" #include "ena_com/ena_eth_com.h" #define ENA_DRV_MODULE_VER_MAJOR 2 #define ENA_DRV_MODULE_VER_MINOR 6 #define ENA_DRV_MODULE_VER_SUBMINOR 3 #define ENA_DRV_MODULE_NAME "ena" #ifndef ENA_DRV_MODULE_VERSION #define ENA_DRV_MODULE_VERSION \ __XSTRING(ENA_DRV_MODULE_VER_MAJOR) "." \ __XSTRING(ENA_DRV_MODULE_VER_MINOR) "." \ __XSTRING(ENA_DRV_MODULE_VER_SUBMINOR) #endif #define ENA_DEVICE_NAME "Elastic Network Adapter (ENA)" #define ENA_DEVICE_DESC "ENA adapter" /* Calculate DMA mask - width for ena cannot exceed 48, so it is safe */ #define ENA_DMA_BIT_MASK(x) ((1ULL << (x)) - 1ULL) /* 1 for AENQ + ADMIN */ #define ENA_ADMIN_MSIX_VEC 1 #define ENA_MAX_MSIX_VEC(io_queues) (ENA_ADMIN_MSIX_VEC + (io_queues)) #define ENA_REG_BAR 0 #define ENA_MEM_BAR 2 #define ENA_BUS_DMA_SEGS 32 #define ENA_DEFAULT_BUF_RING_SIZE 4096 #define ENA_DEFAULT_RING_SIZE 1024 #define ENA_MIN_RING_SIZE 256 /* * Refill Rx queue when number of required descriptors is above * QUEUE_SIZE / ENA_RX_REFILL_THRESH_DIVIDER or ENA_RX_REFILL_THRESH_PACKET */ #define ENA_RX_REFILL_THRESH_DIVIDER 8 #define ENA_RX_REFILL_THRESH_PACKET 256 #define ENA_IRQNAME_SIZE 40 #define ENA_PKT_MAX_BUFS 19 #define ENA_RX_RSS_TABLE_LOG_SIZE 7 #define ENA_RX_RSS_TABLE_SIZE (1 << ENA_RX_RSS_TABLE_LOG_SIZE) #define ENA_HASH_KEY_SIZE 40 #define ENA_MAX_FRAME_LEN 10000 #define ENA_MIN_FRAME_LEN 60 #define ENA_TX_RESUME_THRESH (ENA_PKT_MAX_BUFS + 2) #define ENA_DB_THRESHOLD 64 #define ENA_TX_COMMIT 32 /* * TX budget for cleaning. It should be half of the RX budget to reduce amount * of TCP retransmissions. */ #define ENA_TX_BUDGET 128 /* RX cleanup budget. -1 stands for infinity. */ #define ENA_RX_BUDGET 256 /* * How many times we can repeat cleanup in the io irq handling routine if the * RX or TX budget was depleted. */ #define ENA_CLEAN_BUDGET 8 #define ENA_RX_IRQ_INTERVAL 20 #define ENA_TX_IRQ_INTERVAL 50 #define ENA_MIN_MTU 128 #define ENA_TSO_MAXSIZE 65536 #define ENA_MMIO_DISABLE_REG_READ BIT(0) #define ENA_TX_RING_IDX_NEXT(idx, ring_size) (((idx) + 1) & ((ring_size) - 1)) #define ENA_RX_RING_IDX_NEXT(idx, ring_size) (((idx) + 1) & ((ring_size) - 1)) #define ENA_IO_TXQ_IDX(q) (2 * (q)) #define ENA_IO_RXQ_IDX(q) (2 * (q) + 1) #define ENA_IO_TXQ_IDX_TO_COMBINED_IDX(q) ((q) / 2) #define ENA_IO_RXQ_IDX_TO_COMBINED_IDX(q) (((q) - 1) / 2) #define ENA_MGMNT_IRQ_IDX 0 #define ENA_IO_IRQ_FIRST_IDX 1 #define ENA_IO_IRQ_IDX(q) (ENA_IO_IRQ_FIRST_IDX + (q)) #define ENA_MAX_NO_INTERRUPT_ITERATIONS 3 /* * ENA device should send keep alive msg every 1 sec. * We wait for 6 sec just to be on the safe side. */ #define ENA_DEFAULT_KEEP_ALIVE_TO (SBT_1S * 6) /* Time in jiffies before concluding the transmitter is hung. */ #define ENA_DEFAULT_TX_CMP_TO (SBT_1S * 5) /* Number of queues to check for missing queues per timer tick */ #define ENA_DEFAULT_TX_MONITORED_QUEUES (4) /* Max number of timeouted packets before device reset */ #define ENA_DEFAULT_TX_CMP_THRESHOLD (128) /* * Supported PCI vendor and devices IDs */ #define PCI_VENDOR_ID_AMAZON 0x1d0f #define PCI_DEV_ID_ENA_PF 0x0ec2 #define PCI_DEV_ID_ENA_PF_RSERV0 0x1ec2 #define PCI_DEV_ID_ENA_VF 0xec20 #define PCI_DEV_ID_ENA_VF_RSERV0 0xec21 /* * Flags indicating current ENA driver state */ enum ena_flags_t { ENA_FLAG_DEVICE_RUNNING, ENA_FLAG_DEV_UP, ENA_FLAG_LINK_UP, ENA_FLAG_MSIX_ENABLED, ENA_FLAG_TRIGGER_RESET, ENA_FLAG_ONGOING_RESET, ENA_FLAG_DEV_UP_BEFORE_RESET, ENA_FLAG_RSS_ACTIVE, ENA_FLAGS_NUMBER = ENA_FLAG_RSS_ACTIVE }; BITSET_DEFINE(_ena_state, ENA_FLAGS_NUMBER); typedef struct _ena_state ena_state_t; #define ENA_FLAG_ZERO(adapter) \ BIT_ZERO(ENA_FLAGS_NUMBER, &(adapter)->flags) #define ENA_FLAG_ISSET(bit, adapter) \ BIT_ISSET(ENA_FLAGS_NUMBER, (bit), &(adapter)->flags) #define ENA_FLAG_SET_ATOMIC(bit, adapter) \ BIT_SET_ATOMIC(ENA_FLAGS_NUMBER, (bit), &(adapter)->flags) #define ENA_FLAG_CLEAR_ATOMIC(bit, adapter) \ BIT_CLR_ATOMIC(ENA_FLAGS_NUMBER, (bit), &(adapter)->flags) struct msix_entry { int entry; int vector; }; typedef struct _ena_vendor_info_t { uint16_t vendor_id; uint16_t device_id; unsigned int index; } ena_vendor_info_t; struct ena_irq { /* Interrupt resources */ struct resource *res; driver_filter_t *handler; void *data; void *cookie; unsigned int vector; bool requested; #ifdef RSS int cpu; #endif char name[ENA_IRQNAME_SIZE]; }; struct ena_que { struct ena_adapter *adapter; struct ena_ring *tx_ring; struct ena_ring *rx_ring; struct task cleanup_task; struct taskqueue *cleanup_tq; uint32_t id; #ifdef RSS int cpu; cpuset_t cpu_mask; #endif int domain; struct sysctl_oid *oid; }; struct ena_calc_queue_size_ctx { struct ena_com_dev_get_features_ctx *get_feat_ctx; struct ena_com_dev *ena_dev; device_t pdev; uint32_t tx_queue_size; uint32_t rx_queue_size; uint32_t max_tx_queue_size; uint32_t max_rx_queue_size; uint16_t max_tx_sgl_size; uint16_t max_rx_sgl_size; }; #ifdef DEV_NETMAP struct ena_netmap_tx_info { uint32_t socket_buf_idx[ENA_PKT_MAX_BUFS]; bus_dmamap_t map_seg[ENA_PKT_MAX_BUFS]; unsigned int sockets_used; }; #endif struct ena_tx_buffer { struct mbuf *mbuf; /* # of ena desc for this specific mbuf * (includes data desc and metadata desc) */ unsigned int tx_descs; /* # of buffers used by this mbuf */ unsigned int num_of_bufs; bus_dmamap_t dmamap; /* Used to detect missing tx packets */ struct bintime timestamp; bool print_once; #ifdef DEV_NETMAP struct ena_netmap_tx_info nm_info; #endif /* DEV_NETMAP */ struct ena_com_buf bufs[ENA_PKT_MAX_BUFS]; } __aligned(CACHE_LINE_SIZE); struct ena_rx_buffer { struct mbuf *mbuf; bus_dmamap_t map; struct ena_com_buf ena_buf; #ifdef DEV_NETMAP uint32_t netmap_buf_idx; #endif /* DEV_NETMAP */ } __aligned(CACHE_LINE_SIZE); struct ena_stats_tx { counter_u64_t cnt; counter_u64_t bytes; counter_u64_t prepare_ctx_err; counter_u64_t dma_mapping_err; counter_u64_t doorbells; counter_u64_t missing_tx_comp; counter_u64_t bad_req_id; counter_u64_t collapse; counter_u64_t collapse_err; counter_u64_t queue_wakeup; counter_u64_t queue_stop; counter_u64_t llq_buffer_copy; counter_u64_t unmask_interrupt_num; }; struct ena_stats_rx { counter_u64_t cnt; counter_u64_t bytes; counter_u64_t refil_partial; counter_u64_t csum_bad; counter_u64_t mjum_alloc_fail; counter_u64_t mbuf_alloc_fail; counter_u64_t dma_mapping_err; counter_u64_t bad_desc_num; counter_u64_t bad_req_id; counter_u64_t empty_rx_ring; counter_u64_t csum_good; }; struct ena_ring { /* Holds the empty requests for TX/RX out of order completions */ union { uint16_t *free_tx_ids; uint16_t *free_rx_ids; }; struct ena_com_dev *ena_dev; struct ena_adapter *adapter; struct ena_com_io_cq *ena_com_io_cq; struct ena_com_io_sq *ena_com_io_sq; uint16_t qid; /* Determines if device will use LLQ or normal mode for TX */ enum ena_admin_placement_policy_type tx_mem_queue_type; union { /* The maximum length the driver can push to the device (For LLQ) */ uint8_t tx_max_header_size; /* The maximum (and default) mbuf size for the Rx descriptor. */ uint16_t rx_mbuf_sz; }; uint8_t first_interrupt; uint16_t no_interrupt_event_cnt; struct ena_com_rx_buf_info ena_bufs[ENA_PKT_MAX_BUFS]; struct ena_que *que; struct lro_ctrl lro; uint16_t next_to_use; uint16_t next_to_clean; union { struct ena_tx_buffer *tx_buffer_info; /* contex of tx packet */ struct ena_rx_buffer *rx_buffer_info; /* contex of rx packet */ }; int ring_size; /* number of tx/rx_buffer_info's entries */ struct buf_ring *br; /* only for TX */ uint32_t buf_ring_size; struct mtx ring_mtx; char mtx_name[16]; struct { struct task enqueue_task; struct taskqueue *enqueue_tq; }; union { struct ena_stats_tx tx_stats; struct ena_stats_rx rx_stats; }; union { int empty_rx_queue; /* For Tx ring to indicate if it's running or not */ bool running; }; /* How many packets are sent in one Tx loop, used for doorbells */ uint32_t acum_pkts; /* Used for LLQ */ uint8_t *push_buf_intermediate_buf; int tx_last_cleanup_ticks; #ifdef DEV_NETMAP bool initialized; #endif /* DEV_NETMAP */ } __aligned(CACHE_LINE_SIZE); struct ena_stats_dev { counter_u64_t wd_expired; counter_u64_t interface_up; counter_u64_t interface_down; counter_u64_t admin_q_pause; }; struct ena_hw_stats { counter_u64_t rx_packets; counter_u64_t tx_packets; counter_u64_t rx_bytes; counter_u64_t tx_bytes; counter_u64_t rx_drops; counter_u64_t tx_drops; }; /* Board specific private data structure */ struct ena_adapter { struct ena_com_dev *ena_dev; /* OS defined structs */ if_t ifp; device_t pdev; struct ifmedia media; /* OS resources */ struct resource *memory; struct resource *registers; struct resource *msix; int msix_rid; /* MSI-X */ struct msix_entry *msix_entries; int msix_vecs; /* DMA tags used throughout the driver adapter for Tx and Rx */ bus_dma_tag_t tx_buf_tag; bus_dma_tag_t rx_buf_tag; int dma_width; uint32_t max_mtu; uint32_t num_io_queues; uint32_t max_num_io_queues; uint32_t requested_tx_ring_size; uint32_t requested_rx_ring_size; uint32_t max_tx_ring_size; uint32_t max_rx_ring_size; uint16_t max_tx_sgl_size; uint16_t max_rx_sgl_size; uint32_t tx_offload_cap; uint32_t buf_ring_size; /* RSS*/ int first_bind; struct ena_indir *rss_indir; uint8_t mac_addr[ETHER_ADDR_LEN]; /* mdio and phy*/ ena_state_t flags; /* Queue will represent one TX and one RX ring */ struct ena_que que[ENA_MAX_NUM_IO_QUEUES] __aligned(CACHE_LINE_SIZE); /* TX */ struct ena_ring tx_ring[ENA_MAX_NUM_IO_QUEUES] __aligned(CACHE_LINE_SIZE); /* RX */ struct ena_ring rx_ring[ENA_MAX_NUM_IO_QUEUES] __aligned(CACHE_LINE_SIZE); struct ena_irq irq_tbl[ENA_MAX_MSIX_VEC(ENA_MAX_NUM_IO_QUEUES)]; /* Timer service */ struct callout timer_service; sbintime_t keep_alive_timestamp; uint32_t next_monitored_tx_qid; struct task reset_task; struct taskqueue *reset_tq; struct task metrics_task; struct taskqueue *metrics_tq; int wd_active; sbintime_t keep_alive_timeout; sbintime_t missing_tx_timeout; uint32_t missing_tx_max_queues; uint32_t missing_tx_threshold; bool disable_meta_caching; uint16_t eni_metrics_sample_interval; uint16_t eni_metrics_sample_interval_cnt; /* Statistics */ struct ena_stats_dev dev_stats; struct ena_hw_stats hw_stats; struct ena_admin_eni_stats eni_metrics; enum ena_regs_reset_reason_types reset_reason; }; #define ENA_RING_MTX_LOCK(_ring) mtx_lock(&(_ring)->ring_mtx) #define ENA_RING_MTX_TRYLOCK(_ring) mtx_trylock(&(_ring)->ring_mtx) #define ENA_RING_MTX_UNLOCK(_ring) mtx_unlock(&(_ring)->ring_mtx) #define ENA_RING_MTX_ASSERT(_ring) \ mtx_assert(&(_ring)->ring_mtx, MA_OWNED) #define ENA_LOCK_INIT() \ sx_init(&ena_global_lock, "ENA global lock") #define ENA_LOCK_DESTROY() sx_destroy(&ena_global_lock) #define ENA_LOCK_LOCK() sx_xlock(&ena_global_lock) #define ENA_LOCK_UNLOCK() sx_unlock(&ena_global_lock) #define ENA_LOCK_ASSERT() sx_assert(&ena_global_lock, SA_XLOCKED) #define ENA_TIMER_INIT(_adapter) \ callout_init(&(_adapter)->timer_service, true) #define ENA_TIMER_DRAIN(_adapter) \ callout_drain(&(_adapter)->timer_service) #define ENA_TIMER_RESET(_adapter) \ callout_reset_sbt(&(_adapter)->timer_service, SBT_1S, SBT_1S, \ ena_timer_service, (void*)(_adapter), 0) #define clamp_t(type, _x, min, max) min_t(type, max_t(type, _x, min), max) #define clamp_val(val, lo, hi) clamp_t(__typeof(val), val, lo, hi) extern struct sx ena_global_lock; int ena_up(struct ena_adapter *adapter); void ena_down(struct ena_adapter *adapter); int ena_restore_device(struct ena_adapter *adapter); void ena_destroy_device(struct ena_adapter *adapter, bool graceful); int ena_refill_rx_bufs(struct ena_ring *rx_ring, uint32_t num); int ena_update_buf_ring_size(struct ena_adapter *adapter, uint32_t new_buf_ring_size); int ena_update_queue_size(struct ena_adapter *adapter, uint32_t new_tx_size, uint32_t new_rx_size); int ena_update_io_queue_nb(struct ena_adapter *adapter, uint32_t new_num); static inline int ena_mbuf_count(struct mbuf *mbuf) { int count = 1; while ((mbuf = mbuf->m_next) != NULL) ++count; return count; } static inline void ena_trigger_reset(struct ena_adapter *adapter, enum ena_regs_reset_reason_types reset_reason) { if (likely(!ENA_FLAG_ISSET(ENA_FLAG_TRIGGER_RESET, adapter))) { adapter->reset_reason = reset_reason; ENA_FLAG_SET_ATOMIC(ENA_FLAG_TRIGGER_RESET, adapter); } } static inline void ena_ring_tx_doorbell(struct ena_ring *tx_ring) { ena_com_write_sq_doorbell(tx_ring->ena_com_io_sq); counter_u64_add(tx_ring->tx_stats.doorbells, 1); tx_ring->acum_pkts = 0; } #endif /* !(ENA_H) */
f0e8a5f3e518cc14d373d48525b321a0be69bda2
aa3befea459382dc5c01c925653d54f435b3fb0f
/include/nuttx/net/loopback.h
f2f5de944e2bc55313ef381c38a4e348aa214d28
[ "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
2,761
h
loopback.h
/**************************************************************************** * include/nuttx/net/loopback.h * Definitions for use with local loopback device * * 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. * ****************************************************************************/ #ifndef __INCLUDE_NUTTX_NET_LOOPBACK_H #define __INCLUDE_NUTTX_NET_LOOPBACK_H /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <nuttx/net/netconfig.h> #include <nuttx/net/ip.h> #ifdef CONFIG_NET_LOOPBACK /**************************************************************************** * Public Data ****************************************************************************/ #ifdef __cplusplus #define EXTERN extern "C" extern "C" { #else #define EXTERN extern #endif #ifdef CONFIG_LIBC_NETDB /* Local loopback hostname */ EXTERN const char g_lo_hostname[]; #endif /* Local loopback addresses */ #ifdef CONFIG_NET_IPv4 EXTERN const in_addr_t g_lo_ipv4addr; EXTERN const in_addr_t g_lo_ipv4mask; #endif #ifdef CONFIG_NET_IPv6 EXTERN const net_ipv6addr_t g_lo_ipv6addr; EXTERN const net_ipv6addr_t g_lo_ipv6mask; #endif /**************************************************************************** * Public Function Prototypes ****************************************************************************/ /**************************************************************************** * Name: localhost_initialize * * Description: * Initialize the localhost, loopback network driver * * Input Parameters: * None * * Returned Value: * OK on success; Negated errno on failure. * ****************************************************************************/ int localhost_initialize(void); #undef EXTERN #ifdef __cplusplus } #endif #endif /* CONFIG_NET_LOOPBACK */ #endif /* __INCLUDE_NUTTX_NET_LOOPBACK_H */
9a20123c57e8646bb6cd5461d4886d60a99be5ae
35c04ea32351dc95bc18d46e5c70dda9c1e08668
/Examples/KDS/tinyK20/tinyK20_Sumo/Sources/Shell.c
c31de8a5fc25fc3be09e8cef5212fe9342b033c9
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
ErichStyger/mcuoneclipse
0f8e7a2056a26ed79d9d4a0afd64777ff0b2b2fe
04ad311b11860ae5f8285316010961a87fa06d0c
refs/heads/master
2023-08-28T22:54:08.501719
2023-08-25T15:11:44
2023-08-25T15:11:44
7,446,094
620
1,191
NOASSERTION
2020-10-16T03:13:28
2013-01-04T19:38:12
Batchfile
UTF-8
C
false
false
1,338
c
Shell.c
/* * Shell.c * * Created on: 04.08.2011 * Author: Erich Styger */ #include "Platform.h" #include "FRTOS1.h" #include "Shell.h" #include "CLS1.h" #include "RTT1.h" #include "Q4CLeft.h" #include "Q4CRight.h" #if PL_CONFIG_HAS_MOTOR #include "Motor.h" #endif static const CLS1_ParseCommandCallback CmdParserTable[] = { CLS1_ParseCommand, FRTOS1_ParseCommand, #if PL_CONFIG_HAS_MOTOR MOT_ParseCommand, #endif Q4CLeft_ParseCommand, Q4CRight_ParseCommand, NULL /* sentinel */ }; typedef struct { CLS1_ConstStdIOType *stdio; unsigned char *buf; size_t bufSize; } SHELL_IODesc; static const SHELL_IODesc ios[] = { {&CLS1_stdio, CLS1_DefaultShellBuffer, sizeof(CLS1_DefaultShellBuffer)}, }; static void ShellTask(void *pvParameters) { int i; (void)pvParameters; /* not used */ for(i=0;i<sizeof(ios)/sizeof(ios[0]);i++) { ios[i].buf[0] = '\0'; } CLS1_SendStr("Shell task started!\r\n", CLS1_GetStdio()->stdOut); for(;;) { for(i=0;i<sizeof(ios)/sizeof(ios[0]);i++) { (void)CLS1_ReadAndParseWithCommandTable(ios[i].buf, ios[i].bufSize, ios[i].stdio, CmdParserTable); } vTaskDelay(pdMS_TO_TICKS(10)); } } void SHELL_Init(void) { if (xTaskCreate(ShellTask, "Shell", configMINIMAL_STACK_SIZE+150, NULL, tskIDLE_PRIORITY+2, NULL) != pdPASS) { for(;;){} /* error */ } }
a7629cd636bf533af84ef71047a5bc1290b0c500
d38ed5f31d74a79a054ed55dd9123a8d615283b9
/third_party/libgit2/src/delta.c
1ff7752c7d8210099e858e2b2303508a1e54f8b2
[ "GPL-2.0-only", "LicenseRef-scancode-public-domain", "GCC-exception-2.0", "LGPL-2.0-or-later", "Zlib", "LGPL-2.1-or-later", "LGPL-2.1-only", "ISC", "MIT", "Apache-2.0" ]
permissive
chigraph/chigraph
8ff76a14337da29fa2b2a84d5c35f2eac4156c6e
6981bdd6763db54edfe284c1f7d223193584c69a
refs/heads/master
2022-12-21T13:46:57.273039
2022-12-17T18:41:19
2022-12-17T18:41:19
60,776,831
364
65
Apache-2.0
2019-12-13T14:46:43
2016-06-09T13:27:37
C++
UTF-8
C
false
false
18,998
c
delta.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "delta.h" /* maximum hash entry list for the same hash bucket */ #define HASH_LIMIT 64 #define RABIN_SHIFT 23 #define RABIN_WINDOW 16 static const unsigned int T[256] = { 0x00000000, 0xab59b4d1, 0x56b369a2, 0xfdeadd73, 0x063f6795, 0xad66d344, 0x508c0e37, 0xfbd5bae6, 0x0c7ecf2a, 0xa7277bfb, 0x5acda688, 0xf1941259, 0x0a41a8bf, 0xa1181c6e, 0x5cf2c11d, 0xf7ab75cc, 0x18fd9e54, 0xb3a42a85, 0x4e4ef7f6, 0xe5174327, 0x1ec2f9c1, 0xb59b4d10, 0x48719063, 0xe32824b2, 0x1483517e, 0xbfdae5af, 0x423038dc, 0xe9698c0d, 0x12bc36eb, 0xb9e5823a, 0x440f5f49, 0xef56eb98, 0x31fb3ca8, 0x9aa28879, 0x6748550a, 0xcc11e1db, 0x37c45b3d, 0x9c9defec, 0x6177329f, 0xca2e864e, 0x3d85f382, 0x96dc4753, 0x6b369a20, 0xc06f2ef1, 0x3bba9417, 0x90e320c6, 0x6d09fdb5, 0xc6504964, 0x2906a2fc, 0x825f162d, 0x7fb5cb5e, 0xd4ec7f8f, 0x2f39c569, 0x846071b8, 0x798aaccb, 0xd2d3181a, 0x25786dd6, 0x8e21d907, 0x73cb0474, 0xd892b0a5, 0x23470a43, 0x881ebe92, 0x75f463e1, 0xdeadd730, 0x63f67950, 0xc8afcd81, 0x354510f2, 0x9e1ca423, 0x65c91ec5, 0xce90aa14, 0x337a7767, 0x9823c3b6, 0x6f88b67a, 0xc4d102ab, 0x393bdfd8, 0x92626b09, 0x69b7d1ef, 0xc2ee653e, 0x3f04b84d, 0x945d0c9c, 0x7b0be704, 0xd05253d5, 0x2db88ea6, 0x86e13a77, 0x7d348091, 0xd66d3440, 0x2b87e933, 0x80de5de2, 0x7775282e, 0xdc2c9cff, 0x21c6418c, 0x8a9ff55d, 0x714a4fbb, 0xda13fb6a, 0x27f92619, 0x8ca092c8, 0x520d45f8, 0xf954f129, 0x04be2c5a, 0xafe7988b, 0x5432226d, 0xff6b96bc, 0x02814bcf, 0xa9d8ff1e, 0x5e738ad2, 0xf52a3e03, 0x08c0e370, 0xa39957a1, 0x584ced47, 0xf3155996, 0x0eff84e5, 0xa5a63034, 0x4af0dbac, 0xe1a96f7d, 0x1c43b20e, 0xb71a06df, 0x4ccfbc39, 0xe79608e8, 0x1a7cd59b, 0xb125614a, 0x468e1486, 0xedd7a057, 0x103d7d24, 0xbb64c9f5, 0x40b17313, 0xebe8c7c2, 0x16021ab1, 0xbd5bae60, 0x6cb54671, 0xc7ecf2a0, 0x3a062fd3, 0x915f9b02, 0x6a8a21e4, 0xc1d39535, 0x3c394846, 0x9760fc97, 0x60cb895b, 0xcb923d8a, 0x3678e0f9, 0x9d215428, 0x66f4eece, 0xcdad5a1f, 0x3047876c, 0x9b1e33bd, 0x7448d825, 0xdf116cf4, 0x22fbb187, 0x89a20556, 0x7277bfb0, 0xd92e0b61, 0x24c4d612, 0x8f9d62c3, 0x7836170f, 0xd36fa3de, 0x2e857ead, 0x85dcca7c, 0x7e09709a, 0xd550c44b, 0x28ba1938, 0x83e3ade9, 0x5d4e7ad9, 0xf617ce08, 0x0bfd137b, 0xa0a4a7aa, 0x5b711d4c, 0xf028a99d, 0x0dc274ee, 0xa69bc03f, 0x5130b5f3, 0xfa690122, 0x0783dc51, 0xacda6880, 0x570fd266, 0xfc5666b7, 0x01bcbbc4, 0xaae50f15, 0x45b3e48d, 0xeeea505c, 0x13008d2f, 0xb85939fe, 0x438c8318, 0xe8d537c9, 0x153feaba, 0xbe665e6b, 0x49cd2ba7, 0xe2949f76, 0x1f7e4205, 0xb427f6d4, 0x4ff24c32, 0xe4abf8e3, 0x19412590, 0xb2189141, 0x0f433f21, 0xa41a8bf0, 0x59f05683, 0xf2a9e252, 0x097c58b4, 0xa225ec65, 0x5fcf3116, 0xf49685c7, 0x033df00b, 0xa86444da, 0x558e99a9, 0xfed72d78, 0x0502979e, 0xae5b234f, 0x53b1fe3c, 0xf8e84aed, 0x17bea175, 0xbce715a4, 0x410dc8d7, 0xea547c06, 0x1181c6e0, 0xbad87231, 0x4732af42, 0xec6b1b93, 0x1bc06e5f, 0xb099da8e, 0x4d7307fd, 0xe62ab32c, 0x1dff09ca, 0xb6a6bd1b, 0x4b4c6068, 0xe015d4b9, 0x3eb80389, 0x95e1b758, 0x680b6a2b, 0xc352defa, 0x3887641c, 0x93ded0cd, 0x6e340dbe, 0xc56db96f, 0x32c6cca3, 0x999f7872, 0x6475a501, 0xcf2c11d0, 0x34f9ab36, 0x9fa01fe7, 0x624ac294, 0xc9137645, 0x26459ddd, 0x8d1c290c, 0x70f6f47f, 0xdbaf40ae, 0x207afa48, 0x8b234e99, 0x76c993ea, 0xdd90273b, 0x2a3b52f7, 0x8162e626, 0x7c883b55, 0xd7d18f84, 0x2c043562, 0x875d81b3, 0x7ab75cc0, 0xd1eee811 }; static const unsigned int U[256] = { 0x00000000, 0x7eb5200d, 0x5633f4cb, 0x2886d4c6, 0x073e5d47, 0x798b7d4a, 0x510da98c, 0x2fb88981, 0x0e7cba8e, 0x70c99a83, 0x584f4e45, 0x26fa6e48, 0x0942e7c9, 0x77f7c7c4, 0x5f711302, 0x21c4330f, 0x1cf9751c, 0x624c5511, 0x4aca81d7, 0x347fa1da, 0x1bc7285b, 0x65720856, 0x4df4dc90, 0x3341fc9d, 0x1285cf92, 0x6c30ef9f, 0x44b63b59, 0x3a031b54, 0x15bb92d5, 0x6b0eb2d8, 0x4388661e, 0x3d3d4613, 0x39f2ea38, 0x4747ca35, 0x6fc11ef3, 0x11743efe, 0x3eccb77f, 0x40799772, 0x68ff43b4, 0x164a63b9, 0x378e50b6, 0x493b70bb, 0x61bda47d, 0x1f088470, 0x30b00df1, 0x4e052dfc, 0x6683f93a, 0x1836d937, 0x250b9f24, 0x5bbebf29, 0x73386bef, 0x0d8d4be2, 0x2235c263, 0x5c80e26e, 0x740636a8, 0x0ab316a5, 0x2b7725aa, 0x55c205a7, 0x7d44d161, 0x03f1f16c, 0x2c4978ed, 0x52fc58e0, 0x7a7a8c26, 0x04cfac2b, 0x73e5d470, 0x0d50f47d, 0x25d620bb, 0x5b6300b6, 0x74db8937, 0x0a6ea93a, 0x22e87dfc, 0x5c5d5df1, 0x7d996efe, 0x032c4ef3, 0x2baa9a35, 0x551fba38, 0x7aa733b9, 0x041213b4, 0x2c94c772, 0x5221e77f, 0x6f1ca16c, 0x11a98161, 0x392f55a7, 0x479a75aa, 0x6822fc2b, 0x1697dc26, 0x3e1108e0, 0x40a428ed, 0x61601be2, 0x1fd53bef, 0x3753ef29, 0x49e6cf24, 0x665e46a5, 0x18eb66a8, 0x306db26e, 0x4ed89263, 0x4a173e48, 0x34a21e45, 0x1c24ca83, 0x6291ea8e, 0x4d29630f, 0x339c4302, 0x1b1a97c4, 0x65afb7c9, 0x446b84c6, 0x3adea4cb, 0x1258700d, 0x6ced5000, 0x4355d981, 0x3de0f98c, 0x15662d4a, 0x6bd30d47, 0x56ee4b54, 0x285b6b59, 0x00ddbf9f, 0x7e689f92, 0x51d01613, 0x2f65361e, 0x07e3e2d8, 0x7956c2d5, 0x5892f1da, 0x2627d1d7, 0x0ea10511, 0x7014251c, 0x5facac9d, 0x21198c90, 0x099f5856, 0x772a785b, 0x4c921c31, 0x32273c3c, 0x1aa1e8fa, 0x6414c8f7, 0x4bac4176, 0x3519617b, 0x1d9fb5bd, 0x632a95b0, 0x42eea6bf, 0x3c5b86b2, 0x14dd5274, 0x6a687279, 0x45d0fbf8, 0x3b65dbf5, 0x13e30f33, 0x6d562f3e, 0x506b692d, 0x2ede4920, 0x06589de6, 0x78edbdeb, 0x5755346a, 0x29e01467, 0x0166c0a1, 0x7fd3e0ac, 0x5e17d3a3, 0x20a2f3ae, 0x08242768, 0x76910765, 0x59298ee4, 0x279caee9, 0x0f1a7a2f, 0x71af5a22, 0x7560f609, 0x0bd5d604, 0x235302c2, 0x5de622cf, 0x725eab4e, 0x0ceb8b43, 0x246d5f85, 0x5ad87f88, 0x7b1c4c87, 0x05a96c8a, 0x2d2fb84c, 0x539a9841, 0x7c2211c0, 0x029731cd, 0x2a11e50b, 0x54a4c506, 0x69998315, 0x172ca318, 0x3faa77de, 0x411f57d3, 0x6ea7de52, 0x1012fe5f, 0x38942a99, 0x46210a94, 0x67e5399b, 0x19501996, 0x31d6cd50, 0x4f63ed5d, 0x60db64dc, 0x1e6e44d1, 0x36e89017, 0x485db01a, 0x3f77c841, 0x41c2e84c, 0x69443c8a, 0x17f11c87, 0x38499506, 0x46fcb50b, 0x6e7a61cd, 0x10cf41c0, 0x310b72cf, 0x4fbe52c2, 0x67388604, 0x198da609, 0x36352f88, 0x48800f85, 0x6006db43, 0x1eb3fb4e, 0x238ebd5d, 0x5d3b9d50, 0x75bd4996, 0x0b08699b, 0x24b0e01a, 0x5a05c017, 0x728314d1, 0x0c3634dc, 0x2df207d3, 0x534727de, 0x7bc1f318, 0x0574d315, 0x2acc5a94, 0x54797a99, 0x7cffae5f, 0x024a8e52, 0x06852279, 0x78300274, 0x50b6d6b2, 0x2e03f6bf, 0x01bb7f3e, 0x7f0e5f33, 0x57888bf5, 0x293dabf8, 0x08f998f7, 0x764cb8fa, 0x5eca6c3c, 0x207f4c31, 0x0fc7c5b0, 0x7172e5bd, 0x59f4317b, 0x27411176, 0x1a7c5765, 0x64c97768, 0x4c4fa3ae, 0x32fa83a3, 0x1d420a22, 0x63f72a2f, 0x4b71fee9, 0x35c4dee4, 0x1400edeb, 0x6ab5cde6, 0x42331920, 0x3c86392d, 0x133eb0ac, 0x6d8b90a1, 0x450d4467, 0x3bb8646a }; struct index_entry { const unsigned char *ptr; unsigned int val; struct index_entry *next; }; struct git_delta_index { unsigned long memsize; const void *src_buf; size_t src_size; unsigned int hash_mask; struct index_entry *hash[GIT_FLEX_ARRAY]; }; static int lookup_index_alloc( void **out, unsigned long *out_len, size_t entries, size_t hash_count) { size_t entries_len, hash_len, index_len; GIT_ERROR_CHECK_ALLOC_MULTIPLY(&entries_len, entries, sizeof(struct index_entry)); GIT_ERROR_CHECK_ALLOC_MULTIPLY(&hash_len, hash_count, sizeof(struct index_entry *)); GIT_ERROR_CHECK_ALLOC_ADD(&index_len, sizeof(struct git_delta_index), entries_len); GIT_ERROR_CHECK_ALLOC_ADD(&index_len, index_len, hash_len); if (!git__is_ulong(index_len)) { git_error_set(GIT_ERROR_NOMEMORY, "overly large delta"); return -1; } *out = git__malloc(index_len); GIT_ERROR_CHECK_ALLOC(*out); *out_len = (unsigned long)index_len; return 0; } int git_delta_index_init( git_delta_index **out, const void *buf, size_t bufsize) { unsigned int i, hsize, hmask, entries, prev_val, *hash_count; const unsigned char *data, *buffer = buf; struct git_delta_index *index; struct index_entry *entry, **hash; void *mem; unsigned long memsize; *out = NULL; if (!buf || !bufsize) return 0; /* Determine index hash size. Note that indexing skips the first byte to allow for optimizing the rabin polynomial initialization in create_delta(). */ entries = (unsigned int)(bufsize - 1) / RABIN_WINDOW; if (bufsize >= 0xffffffffUL) { /* * Current delta format can't encode offsets into * reference buffer with more than 32 bits. */ entries = 0xfffffffeU / RABIN_WINDOW; } hsize = entries / 4; for (i = 4; i < 31 && (1u << i) < hsize; i++); hsize = 1 << i; hmask = hsize - 1; if (lookup_index_alloc(&mem, &memsize, entries, hsize) < 0) return -1; index = mem; mem = index->hash; hash = mem; mem = hash + hsize; entry = mem; index->memsize = memsize; index->src_buf = buf; index->src_size = bufsize; index->hash_mask = hmask; memset(hash, 0, hsize * sizeof(*hash)); /* allocate an array to count hash entries */ hash_count = git__calloc(hsize, sizeof(*hash_count)); if (!hash_count) { git__free(index); return -1; } /* then populate the index */ prev_val = ~0; for (data = buffer + entries * RABIN_WINDOW - RABIN_WINDOW; data >= buffer; data -= RABIN_WINDOW) { unsigned int val = 0; for (i = 1; i <= RABIN_WINDOW; i++) val = ((val << 8) | data[i]) ^ T[val >> RABIN_SHIFT]; if (val == prev_val) { /* keep the lowest of consecutive identical blocks */ entry[-1].ptr = data + RABIN_WINDOW; } else { prev_val = val; i = val & hmask; entry->ptr = data + RABIN_WINDOW; entry->val = val; entry->next = hash[i]; hash[i] = entry++; hash_count[i]++; } } /* * Determine a limit on the number of entries in the same hash * bucket. This guard us against patological data sets causing * really bad hash distribution with most entries in the same hash * bucket that would bring us to O(m*n) computing costs (m and n * corresponding to reference and target buffer sizes). * * Make sure none of the hash buckets has more entries than * we're willing to test. Otherwise we cull the entry list * uniformly to still preserve a good repartition across * the reference buffer. */ for (i = 0; i < hsize; i++) { if (hash_count[i] < HASH_LIMIT) continue; entry = hash[i]; do { struct index_entry *keep = entry; int skip = hash_count[i] / HASH_LIMIT / 2; do { entry = entry->next; } while(--skip && entry); keep->next = entry; } while (entry); } git__free(hash_count); *out = index; return 0; } void git_delta_index_free(git_delta_index *index) { git__free(index); } size_t git_delta_index_size(git_delta_index *index) { assert(index); return index->memsize; } /* * The maximum size for any opcode sequence, including the initial header * plus rabin window plus biggest copy. */ #define MAX_OP_SIZE (5 + 5 + 1 + RABIN_WINDOW + 7) int git_delta_create_from_index( void **out, size_t *out_len, const struct git_delta_index *index, const void *trg_buf, size_t trg_size, size_t max_size) { unsigned int i, bufpos, bufsize, moff, msize, val; int inscnt; const unsigned char *ref_data, *ref_top, *data, *top; unsigned char *buf; *out = NULL; *out_len = 0; if (!trg_buf || !trg_size) return 0; if (index->src_size > UINT_MAX || trg_size > UINT_MAX || max_size > (UINT_MAX - MAX_OP_SIZE - 1)) { git_error_set(GIT_ERROR_INVALID, "buffer sizes too large for delta processing"); return -1; } bufpos = 0; bufsize = 8192; if (max_size && bufsize >= max_size) bufsize = (unsigned int)(max_size + MAX_OP_SIZE + 1); buf = git__malloc(bufsize); GIT_ERROR_CHECK_ALLOC(buf); /* store reference buffer size */ i = (unsigned int)index->src_size; while (i >= 0x80) { buf[bufpos++] = i | 0x80; i >>= 7; } buf[bufpos++] = i; /* store target buffer size */ i = (unsigned int)trg_size; while (i >= 0x80) { buf[bufpos++] = i | 0x80; i >>= 7; } buf[bufpos++] = i; ref_data = index->src_buf; ref_top = ref_data + index->src_size; data = trg_buf; top = (const unsigned char *) trg_buf + trg_size; bufpos++; val = 0; for (i = 0; i < RABIN_WINDOW && data < top; i++, data++) { buf[bufpos++] = *data; val = ((val << 8) | *data) ^ T[val >> RABIN_SHIFT]; } inscnt = i; moff = 0; msize = 0; while (data < top) { if (msize < 4096) { struct index_entry *entry; val ^= U[data[-RABIN_WINDOW]]; val = ((val << 8) | *data) ^ T[val >> RABIN_SHIFT]; i = val & index->hash_mask; for (entry = index->hash[i]; entry; entry = entry->next) { const unsigned char *ref = entry->ptr; const unsigned char *src = data; unsigned int ref_size = (unsigned int)(ref_top - ref); if (entry->val != val) continue; if (ref_size > (unsigned int)(top - src)) ref_size = (unsigned int)(top - src); if (ref_size <= msize) break; while (ref_size-- && *src++ == *ref) ref++; if (msize < (unsigned int)(ref - entry->ptr)) { /* this is our best match so far */ msize = (unsigned int)(ref - entry->ptr); moff = (unsigned int)(entry->ptr - ref_data); if (msize >= 4096) /* good enough */ break; } } } if (msize < 4) { if (!inscnt) bufpos++; buf[bufpos++] = *data++; inscnt++; if (inscnt == 0x7f) { buf[bufpos - inscnt - 1] = inscnt; inscnt = 0; } msize = 0; } else { unsigned int left; unsigned char *op; if (inscnt) { while (moff && ref_data[moff-1] == data[-1]) { /* we can match one byte back */ msize++; moff--; data--; bufpos--; if (--inscnt) continue; bufpos--; /* remove count slot */ inscnt--; /* make it -1 */ break; } buf[bufpos - inscnt - 1] = inscnt; inscnt = 0; } /* A copy op is currently limited to 64KB (pack v2) */ left = (msize < 0x10000) ? 0 : (msize - 0x10000); msize -= left; op = buf + bufpos++; i = 0x80; if (moff & 0x000000ff) buf[bufpos++] = moff >> 0, i |= 0x01; if (moff & 0x0000ff00) buf[bufpos++] = moff >> 8, i |= 0x02; if (moff & 0x00ff0000) buf[bufpos++] = moff >> 16, i |= 0x04; if (moff & 0xff000000) buf[bufpos++] = moff >> 24, i |= 0x08; if (msize & 0x00ff) buf[bufpos++] = msize >> 0, i |= 0x10; if (msize & 0xff00) buf[bufpos++] = msize >> 8, i |= 0x20; *op = i; data += msize; moff += msize; msize = left; if (msize < 4096) { int j; val = 0; for (j = -RABIN_WINDOW; j < 0; j++) val = ((val << 8) | data[j]) ^ T[val >> RABIN_SHIFT]; } } if (bufpos >= bufsize - MAX_OP_SIZE) { void *tmp = buf; bufsize = bufsize * 3 / 2; if (max_size && bufsize >= max_size) bufsize = (unsigned int)(max_size + MAX_OP_SIZE + 1); if (max_size && bufpos > max_size) break; buf = git__realloc(buf, bufsize); if (!buf) { git__free(tmp); return -1; } } } if (inscnt) buf[bufpos - inscnt - 1] = inscnt; if (max_size && bufpos > max_size) { git_error_set(GIT_ERROR_NOMEMORY, "delta would be larger than maximum size"); git__free(buf); return GIT_EBUFS; } *out_len = bufpos; *out = buf; return 0; } /* * Delta application was heavily cribbed from BinaryDelta.java in JGit, which * itself was heavily cribbed from <code>patch-delta.c</code> in the * GIT project. The original delta patching code was written by * Nicolas Pitre <nico@cam.org>. */ static int hdr_sz( size_t *size, const unsigned char **delta, const unsigned char *end) { const unsigned char *d = *delta; size_t r = 0; unsigned int c, shift = 0; do { if (d == end) { git_error_set(GIT_ERROR_INVALID, "truncated delta"); return -1; } c = *d++; r |= (c & 0x7f) << shift; shift += 7; } while (c & 0x80); *delta = d; *size = r; return 0; } int git_delta_read_header( size_t *base_out, size_t *result_out, const unsigned char *delta, size_t delta_len) { const unsigned char *delta_end = delta + delta_len; if ((hdr_sz(base_out, &delta, delta_end) < 0) || (hdr_sz(result_out, &delta, delta_end) < 0)) return -1; return 0; } #define DELTA_HEADER_BUFFER_LEN 16 int git_delta_read_header_fromstream( size_t *base_sz, size_t *res_sz, git_packfile_stream *stream) { static const size_t buffer_len = DELTA_HEADER_BUFFER_LEN; unsigned char buffer[DELTA_HEADER_BUFFER_LEN]; const unsigned char *delta, *delta_end; size_t len; ssize_t read; len = read = 0; while (len < buffer_len) { read = git_packfile_stream_read(stream, &buffer[len], buffer_len - len); if (read == 0) break; if (read == GIT_EBUFS) continue; len += read; } delta = buffer; delta_end = delta + len; if ((hdr_sz(base_sz, &delta, delta_end) < 0) || (hdr_sz(res_sz, &delta, delta_end) < 0)) return -1; return 0; } int git_delta_apply( void **out, size_t *out_len, const unsigned char *base, size_t base_len, const unsigned char *delta, size_t delta_len) { const unsigned char *delta_end = delta + delta_len; size_t base_sz, res_sz, alloc_sz; unsigned char *res_dp; *out = NULL; *out_len = 0; /* * Check that the base size matches the data we were given; * if not we would underflow while accessing data from the * base object, resulting in data corruption or segfault. */ if ((hdr_sz(&base_sz, &delta, delta_end) < 0) || (base_sz != base_len)) { git_error_set(GIT_ERROR_INVALID, "failed to apply delta: base size does not match given data"); return -1; } if (hdr_sz(&res_sz, &delta, delta_end) < 0) { git_error_set(GIT_ERROR_INVALID, "failed to apply delta: base size does not match given data"); return -1; } GIT_ERROR_CHECK_ALLOC_ADD(&alloc_sz, res_sz, 1); res_dp = git__malloc(alloc_sz); GIT_ERROR_CHECK_ALLOC(res_dp); res_dp[res_sz] = '\0'; *out = res_dp; *out_len = res_sz; while (delta < delta_end) { unsigned char cmd = *delta++; if (cmd & 0x80) { /* cmd is a copy instruction; copy from the base. */ size_t off = 0, len = 0, end; #define ADD_DELTA(o, shift) { if (delta < delta_end) (o) |= ((unsigned) *delta++ << shift); else goto fail; } if (cmd & 0x01) ADD_DELTA(off, 0UL); if (cmd & 0x02) ADD_DELTA(off, 8UL); if (cmd & 0x04) ADD_DELTA(off, 16UL); if (cmd & 0x08) ADD_DELTA(off, 24UL); if (cmd & 0x10) ADD_DELTA(len, 0UL); if (cmd & 0x20) ADD_DELTA(len, 8UL); if (cmd & 0x40) ADD_DELTA(len, 16UL); if (!len) len = 0x10000; #undef ADD_DELTA if (GIT_ADD_SIZET_OVERFLOW(&end, off, len) || base_len < end || res_sz < len) goto fail; memcpy(res_dp, base + off, len); res_dp += len; res_sz -= len; } else if (cmd) { /* * cmd is a literal insert instruction; copy from * the delta stream itself. */ if (delta_end - delta < cmd || res_sz < cmd) goto fail; memcpy(res_dp, delta, cmd); delta += cmd; res_dp += cmd; res_sz -= cmd; } else { /* cmd == 0 is reserved for future encodings. */ goto fail; } } if (delta != delta_end || res_sz) goto fail; return 0; fail: git__free(*out); *out = NULL; *out_len = 0; git_error_set(GIT_ERROR_INVALID, "failed to apply delta"); return -1; }
f39288b51f7382d877ddf40b2d64ea0249b83548
41eb0837713f297134529591b66f3d4d82bcf98e
/src/Raine/source/games/lsystem.c
8d5b5ab5798804dc7f36943d0b539aad6c7562ae
[]
no_license
AlexxandreFS/Batocera.PLUS
27b196b3cbb781b6fc99e62cad855396d1d5f8f2
997ee763ae7135fdf0c34a081e789918bd2eb169
refs/heads/master
2023-08-17T21:52:39.083687
2023-08-17T15:03:44
2023-08-17T15:03:44
215,869,486
135
57
null
2023-08-14T14:46:14
2019-10-17T19:23:42
C
ISO-8859-7
C
false
false
134,962
c
lsystem.c
#define DRV_DEF_EXEC execute_kurikint #define DRV_DEF_SOUND taito_ym2203_sound #define DRV_DEF_VIDEO &video_kurikint /******************************************************************************/ /* */ /* TAITO L-SYSTEM (C) 1988-1990 TAITO CORPORATION */ /* */ /* Z80+YM2203 or Z80+Z80+YM2610 or Z80+Z80+YM2203 */ /* */ /******************************************************************************/ // Started to cleanup the code, not sure I'll finish this... ! #include "gameinc.h" #include "tc220ioc.h" #include "taitosnd.h" #include "2203intf.h" #include "decode.h" #include "savegame.h" #include "sasound.h" // sample support routines #include "emumain.h" // set_reset_function #include "blit.h" // clear_game_screen static struct ROMSW_DATA romsw_data_fighting_hawk_0[] = { { "Taito Japan (Notice)", 0x01 }, { "Taito America", 0x02 }, { "Taito Japan", 0x03 }, { "Taito Corporation", 0x04 }, { NULL, 0 }, }; static struct ROMSW_INFO romsw_fhawk[] = { { 0x007FFF, 0x01, romsw_data_fighting_hawk_0 }, { 0, 0, NULL }, }; /************************ AMERICAN HORSESHOES ************************/ static struct ROM_INFO rom_horshoes[] = { { "c47.01", 0x00020000, 0x031c73d8, 0, 0, 0, }, { "c47.02", 0x00020000, 0x35f96526, 0, 0, 0, }, { "c47.03", 0x00020000, 0x37e15b20, 0, 0, 0, }, { "c47.04", 0x00020000, 0xaeac7121, 0, 0, 0, }, { "c47.05", 0x00020000, 0xb2a3dafe, 0, 0, 0, }, { NULL, 0, 0, 0, 0, 0, }, }; static struct INPUT_INFO input_horshoes[] = { INP0( COIN1, 0x02C200, 0x02 ), INP0( COIN2, 0x02C201, 0x02 ), INP0( TILT, 0x02C201, 0x01 ), INP0( SERVICE, 0x02C200, 0x01 ), INP1( P1_UP, 0x02C208, 0xFF ), INP1( P1_DOWN, 0x02C209, 0xFF ), INP1( P1_LEFT, 0x02C20A, 0xFF ), INP1( P1_RIGHT, 0x02C20B, 0xFF ), INP0( P1_B1, 0x02C200, 0x80 ), INP0( P1_B2, 0x02C201, 0x80 ), END_INPUT }; static struct DSW_DATA dsw_data_american_horseshoes_0[] = { DSW_CABINET( 0x00, 0x01), DSW_SCREEN( 0x02, 0x00), DSW_TEST_MODE( 0x00, 0x04), DSW_DEMO_SOUND( 0x08, 0x00), { MSG_COIN1, 0x30, 0x04 }, { MSG_1COIN_1PLAY, 0x30}, { MSG_2COIN_1PLAY, 0x20}, { MSG_3COIN_1PLAY, 0x10}, { MSG_4COIN_1PLAY, 0x00}, { MSG_DSWA_BIT7, 0x40, 0x02 }, { MSG_OFF, 0x40}, { MSG_ON, 0x00}, { MSG_DSWA_BIT8, 0x80, 0x02 }, { MSG_OFF, 0x80}, { MSG_ON, 0x00}, { NULL, 0, }, }; static struct DSW_DATA dsw_data_american_horseshoes_1[] = { { MSG_DIFFICULTY, 0x03, 0x04 }, { MSG_NORMAL, 0x03}, { MSG_EASY, 0x02}, { MSG_HARD, 0x01}, { MSG_HARDEST, 0x00}, { _("Time"), 0x04, 0x02 }, { _("30 seconds"), 0x04}, { _("20 seconds"), 0x00}, { MSG_DSWA_BIT4, 0x08, 0x02 }, { MSG_OFF, 0x08}, { MSG_ON, 0x00}, { _("Innings"), 0x10, 0x02 }, { _("3 per Credit"), 0x10}, { _("9 per Credit"), 0x00}, { MSG_DSWA_BIT6, 0x20, 0x02 }, { MSG_OFF, 0x20}, { MSG_ON, 0x00}, { MSG_DSWA_BIT7, 0x40, 0x02 }, { MSG_OFF, 0x40}, { MSG_ON, 0x00}, { MSG_DSWA_BIT8, 0x80, 0x02 }, { MSG_OFF, 0x80}, { MSG_ON, 0x00}, { NULL, 0, }, }; static struct DSW_INFO dsw_horshoes[] = { { 0x02C202, 0xFF, dsw_data_american_horseshoes_0 }, { 0x02C203, 0xFF, dsw_data_american_horseshoes_1 }, { 0, 0, NULL, }, }; #define O 8*8*2 #define O2 2*O static gfx_layout sp1_layout = { 16, 16, RGN_FRAC(1,2), 4, { RGN_FRAC(1,2)+0, RGN_FRAC(1,2)+4, 0, 4 }, { 3, 2, 1, 0, 8+3, 8+2, 8+1, 8+0, O+3, O+2, O+1, O+0, O+8+3, O+8+2, O+8+1, O+8+0 }, { 0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16, O2+0*16, O2+1*16, O2+2*16, O2+3*16, O2+4*16, O2+5*16, O2+6*16, O2+7*16 }, 8*8*2*4 }; #undef O #undef O2 static GFX_LAYOUT bg2_layout = { 8, 8, RGN_FRAC(1,1), 4, { 8, 12, 0, 4 }, { 3, 2, 1, 0, 19, 18, 17, 16 }, { 0*32, 1*32, 2*32, 3*32, 4*32, 5*32, 6*32, 7*32 }, 8*8*4 }; #define O 8*8*4 #define O2 2*O static GFX_LAYOUT sp2_layout = { 16, 16, RGN_FRAC(1,1), 4, { 8, 12, 0, 4 }, { 3, 2, 1, 0, 19, 18, 17, 16, O+3, O+2, O+1, O+0, O+19, O+18, O+17, O+16 }, { 0*32, 1*32, 2*32, 3*32, 4*32, 5*32, 6*32, 7*32, O2+0*32, O2+1*32, O2+2*32, O2+3*32, O2+4*32, O2+5*32, O2+6*32, O2+7*32 }, 8*8*4*4 }; #undef O #undef O2 static GFX_LIST gfxdecodeinfo2[] = { { REGION_GFX1, &bg2_layout, }, { REGION_GFX1, &sp2_layout, }, { 0, NULL}, // Ram-based { -1 } }; static gfx_layout bg1_layout = { 8, 8, RGN_FRAC(1,2), 4, { RGN_FRAC(1,2)+0, RGN_FRAC(1,2)+4, 0, 4 }, { 3, 2, 1, 0, 8+3, 8+2, 8+1, 8+0 }, { 0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16 }, 8*8*2 }; static GFX_LIST gfxdecodeinfo[] = { { REGION_GFX1, &bg1_layout, }, { REGION_GFX1, &sp1_layout, }, { 0, NULL}, // Ram-based { -1 } }; #define LSYS_INT0 1 // Usually does nothing #define LSYS_INT1 2 // Usually main int (frame start?) #define LSYS_INT2 4 // Usually second main int (frame end?) static int romset; static UINT8 *RAM2; static UINT8 *ROM2; static UINT8 *RAM_INP; static int spr_mask; static int tile_mask; static UINT8 *GFX_BG0; static UINT8 *GFX_BG0_SOLID; static UINT8 VectorData[4]; static void TrackBall(void) { int px,py; if(*MouseB&1) RAM_INP[0] &= ~0x80; if(*MouseB&2) RAM_INP[1] &= ~0x80; GetMouseMickeys(&px,&py); WriteWord(&RAM_INP[0x04], py<<3); WriteWord(&RAM_INP[0x06], px<<3); } static void execute_kurikint(void) { if(romset==1) TrackBall(); cpu_execute_cycles(CPU_Z80_1, 16); // Main Z80 8MHz (60fps) cpu_execute_cycles(CPU_Z80_1, CPU_FRAME_MHz(8,60)); // Main Z80 8MHz (60fps) if(romset==9) { if(VectorData[3] & LSYS_INT2){ cpu_interrupt(CPU_Z80_1, VectorData[2]); cpu_execute_cycles(CPU_Z80_1, CPU_FRAME_MHz(1,60)); cpu_interrupt(CPU_Z80_1, VectorData[2]); cpu_execute_cycles(CPU_Z80_1, CPU_FRAME_MHz(1,60)); cpu_interrupt(CPU_Z80_1, VectorData[2]); cpu_execute_cycles(CPU_Z80_1, CPU_FRAME_MHz(1,60)); cpu_interrupt(CPU_Z80_1, VectorData[2]); cpu_execute_cycles(CPU_Z80_1, CPU_FRAME_MHz(1,60)); cpu_interrupt(CPU_Z80_1, VectorData[2]); cpu_execute_cycles(CPU_Z80_1, CPU_FRAME_MHz(1,60)); cpu_interrupt(CPU_Z80_1, VectorData[2]); cpu_execute_cycles(CPU_Z80_1, CPU_FRAME_MHz(1,60)); cpu_interrupt(CPU_Z80_1, VectorData[2]); cpu_execute_cycles(CPU_Z80_1, CPU_FRAME_MHz(1,60)); cpu_interrupt(CPU_Z80_1, VectorData[2]); cpu_execute_cycles(CPU_Z80_1, CPU_FRAME_MHz(1,60)); } } else { if(VectorData[3] & LSYS_INT2){ cpu_interrupt(CPU_Z80_1, VectorData[2]); cpu_execute_cycles(CPU_Z80_1, CPU_FRAME_MHz(8,60)); } } if(VectorData[3] & LSYS_INT1){ cpu_interrupt(CPU_Z80_1, VectorData[1]); } if(VectorData[3] & LSYS_INT0){ cpu_interrupt(CPU_Z80_1, VectorData[0]); } if(romset==0){ cpu_execute_cycles(CPU_Z80_2, CPU_FRAME_MHz(8,60)); // Sub Z80 8MHz (60fps) } if(romset==3){ cpu_execute_cycles(CPU_Z80_2, CPU_FRAME_MHz(8,60)); // Sub Z80 8MHz (60fps) if(z80pc==0x10D) cpu_interrupt(CPU_Z80_2, 0x38); } if(romset==4){ cpu_execute_cycles(CPU_Z80_2, CPU_FRAME_MHz(8,60)); // Sub Z80 8MHz (60fps) /*#ifdef RAINE_DEBUG print_debug("Z80PC_SUB:%04x\n",z80pc); #endif*/ if(z80pc==0x025) cpu_interrupt(CPU_Z80_2, 0x38); } if(romset==5){ cpu_execute_cycles(CPU_Z80_2, CPU_FRAME_MHz(8,60)); // Sub Z80 8MHz (60fps) /*#ifdef RAINE_DEBUG print_debug("Z80PC_SUB:%04x\n",z80pc); #endif*/ if(z80pc==0x11B) cpu_interrupt(CPU_Z80_2, 0x38); } if(romset==0) Taito2610_Frame(); // Z80 and YM2610 if((romset==3)||(romset==4)) Taito2203_Frame(); // Z80 and YM2203 } /*************************** CHAMPION WRESTLER WORLD ***************************/ static struct ROM_INFO rom_champwr[] = { { "c01-13.rom", 0x20000, 0x7ef47525, REGION_ROM1, 0x00000, LOAD_NORMAL }, { "c01-13.rom", 0x20000, 0x7ef47525, REGION_ROM1, 0x06000, LOAD_NORMAL }, { "c01-04.rom", 0x20000, 0x358bd076, REGION_ROM1, 0x26000, LOAD_NORMAL }, { "c01-08.rom", 0x10000, 0x810efff8, REGION_ROM2, 0, LOAD_NORMAL }, { "c01-07.rom", 0x20000, 0x5117c98f, REGION_CPU3, 0x00000, LOAD_NORMAL }, { "c01-07.rom", 0x20000, 0x5117c98f, REGION_CPU3, 0x08000, LOAD_NORMAL }, { "c01-01.rom", 0x80000, 0xf302e6e9, REGION_GFX1, 0x000000, LOAD_NORMAL }, { "c01-02.rom", 0x80000, 0x1e0476c4, REGION_GFX1, 0x080000, LOAD_NORMAL }, { "c01-03.rom", 0x80000, 0x2a142dbc, REGION_GFX1, 0x100000, LOAD_NORMAL }, { "c01-05.rom", 0x20000, 0x22efad4a, REGION_SMP1, 0x00000, LOAD_NORMAL }, { NULL, 0, 0, 0, 0, 0 } }; static struct ROMSW_INFO romsw_champwr[] = { { 0x1025fff, 0x03, romsw_data_fighting_hawk_0 }, { 0, 0, NULL }, }; static struct INPUT_INFO input_champwr[] = { INP0( COIN1, 0x02C206, 0x02 ), INP0( COIN2, 0x02C206, 0x01 ), INP0( TILT, 0x02C204, 0x40 ), INP0( SERVICE, 0x02C204, 0x80 ), INP0( P1_START, 0x02C204, 0x04 ), INP0( P1_UP, 0x02C20E, 0x80 ), INP0( P1_DOWN, 0x02C20E, 0x40 ), INP0( P1_LEFT, 0x02C20E, 0x20 ), INP0( P1_RIGHT, 0x02C20E, 0x10 ), INP0( P1_B1, 0x02C204, 0x02 ), INP0( P1_B2, 0x02C204, 0x01 ), INP0( P2_START, 0x02C204, 0x08 ), INP0( P2_UP, 0x02C20E, 0x08 ), INP0( P2_DOWN, 0x02C20E, 0x04 ), INP0( P2_LEFT, 0x02C20E, 0x02 ), INP0( P2_RIGHT, 0x02C20E, 0x01 ), INP0( P2_B1, 0x02C204, 0x20 ), INP0( P2_B2, 0x02C204, 0x10 ), END_INPUT }; static struct DSW_DATA dsw_data_champion_wrestler_0[] = { DSW_SCREEN( 0x02, 0x00), DSW_TEST_MODE( 0x00, 0x04), DSW_DEMO_SOUND( 0x08, 0x00), { MSG_COIN1, 0x30, 0x04 }, { MSG_1COIN_1PLAY, 0x30}, { MSG_2COIN_1PLAY, 0x20}, { MSG_3COIN_1PLAY, 0x10}, { MSG_4COIN_1PLAY, 0x00}, { MSG_COIN2, 0xC0, 0x04 }, { MSG_1COIN_2PLAY, 0xC0}, { MSG_1COIN_3PLAY, 0x80}, { MSG_2COIN_1PLAY, 0x40}, { MSG_2COIN_3PLAY, 0x00}, { NULL, 0, }, }; static struct DSW_DATA dsw_data_champion_wrestler_1[] = { { MSG_DIFFICULTY, 0x03, 0x04 }, { MSG_NORMAL, 0x03}, { MSG_EASY, 0x02}, { MSG_HARD, 0x01}, { MSG_HARDEST, 0x00}, { _("Time"), 0x0C, 0x04 }, { _("3 Minutes"), 0x0C}, { _("2 Minutes"), 0x08}, { _("4 Minutes"), 0x04}, { _("5 Minutes"), 0x00}, { _("1 Minute Lenght"), 0x30, 0x04 }, { _("50 seconds"), 0x30}, { _("60 seconds"), 0x20}, { _("40 seconds"), 0x10}, { _("30 seconds"), 0x00}, DSW_CONTINUE_PLAY( 0x40, 0x00), { NULL, 0, }, }; static struct DSW_INFO dsw_champwr[] = { { 0x02C200, 0xFF, dsw_data_champion_wrestler_0 }, { 0x02C202, 0xFF, dsw_data_champion_wrestler_1 }, { 0, 0, NULL, }, }; /************************ CHAMPION WRESTLER US ************************/ static struct ROM_INFO rom_champwru[] = { { "c01-12.rom", 0x20000, 0x09f345b3, REGION_ROM1, 0x00000, LOAD_NORMAL }, { "c01-12.rom", 0x20000, 0x09f345b3, REGION_ROM1, 0x06000, LOAD_NORMAL }, { "c01-04.rom", 0x20000, 0x358bd076, REGION_ROM1, 0x26000, LOAD_NORMAL }, { NULL, 0, 0, 0, 0, 0 } }; static struct DSW_DATA dsw_data_champion_wrestler_us_0[] = { DSW_SCREEN( 0x02, 0x00), DSW_TEST_MODE( 0x00, 0x04), DSW_DEMO_SOUND( 0x08, 0x00), { MSG_COIN1, 0x30, 0x04 }, { MSG_COIN_SLOTS, 0x30, 0x04 }, { MSG_1COIN_1PLAY, 0x30}, { MSG_2COIN_1PLAY, 0x20}, { MSG_3COIN_1PLAY, 0x10}, { MSG_4COIN_1PLAY, 0x00}, { _("Continue cost"), 0xC0, 0x04 }, { _("Same as play"), 0xC0}, { _("1 extra coin"), 0x80}, { _("2 extra coins"), 0x40}, { _("3 extra coins"), 0x00}, { NULL, 0, }, }; static struct DSW_INFO dsw_champwru[] = { { 0x02C200, 0xFF, dsw_data_champion_wrestler_us_0 }, { 0x02C202, 0xFF, dsw_data_champion_wrestler_1 }, { 0, 0, NULL, }, }; /*************************** CHAMPION WRESTLER JAPAN ***************************/ static struct ROM_INFO rom_champwrj[] = { { "c01-06.bin", 0x20000, 0x90fa1409, REGION_ROM1, 0x00000, LOAD_NORMAL }, { "c01-06.bin", 0x20000, 0x90fa1409, REGION_ROM1, 0x06000, LOAD_NORMAL }, { "c01-04.rom", 0x20000, 0x358bd076, REGION_ROM1, 0x26000, LOAD_NORMAL }, { NULL, 0, 0, 0, 0, 0 } }; static struct DSW_DATA dsw_data_champion_wrestler_jp_0[] = { DSW_SCREEN( 0x02, 0x00), DSW_TEST_MODE( 0x00, 0x04), DSW_DEMO_SOUND( 0x08, 0x00), { MSG_COIN1, 0x30, 0x04 }, { MSG_1COIN_1PLAY, 0x30}, { MSG_1COIN_2PLAY, 0x20}, { MSG_2COIN_1PLAY, 0x10}, { MSG_2COIN_3PLAY, 0x00}, { MSG_COIN2, 0xC0, 0x04 }, { MSG_1COIN_1PLAY, 0xC0}, { MSG_1COIN_2PLAY, 0x80}, { MSG_2COIN_1PLAY, 0x40}, { MSG_2COIN_3PLAY, 0x00}, { NULL, 0, }, }; static struct DSW_INFO dsw_champwrj[] = { { 0x02C200, 0xFF, dsw_data_champion_wrestler_jp_0 }, { 0x02C202, 0xFF, dsw_data_champion_wrestler_1 }, { 0, 0, NULL, }, }; /********** CACHAT **********/ static struct ROM_INFO rom_cachat[] = { { "cac6", 0x00020000, 0x8105cf5f, 0, 0, 0, }, { "cac7", 0x00020000, 0x7fb71578, 0, 0, 0, }, { "cac8", 0x00020000, 0xd2a63799, 0, 0, 0, }, { "cac9", 0x00020000, 0xbc462914, 0, 0, 0, }, { "cac10", 0x00020000, 0xecc64b31, 0, 0, 0, }, { NULL, 0, 0, 0, 0, 0, }, }; static struct INPUT_INFO input_cachat[] = { INP0( COIN1, 0x02C200, 0x04 ), INP0( COIN2, 0x02C200, 0x08 ), INP0( TILT, 0x02C200, 0x02 ), INP0( SERVICE, 0x02C200, 0x01 ), INP0( P1_START, 0x02C200, 0x10 ), INP0( P1_UP, 0x02C202, 0x01 ), INP0( P1_DOWN, 0x02C202, 0x02 ), INP0( P1_LEFT, 0x02C202, 0x04 ), INP0( P1_RIGHT, 0x02C202, 0x08 ), INP0( P1_B1, 0x02C200, 0x40 ), INP0( P1_B2, 0x02C200, 0x80 ), INP0( P2_START, 0x02C200, 0x20 ), INP0( P2_UP, 0x02C202, 0x10 ), INP0( P2_DOWN, 0x02C202, 0x20 ), INP0( P2_LEFT, 0x02C202, 0x40 ), INP0( P2_RIGHT, 0x02C202, 0x80 ), INP0( P2_B1, 0x02C204, 0x01 ), INP0( P2_B2, 0x02C204, 0x02 ), END_INPUT }; static struct DSW_DATA dsw_data_cachat_0[] = { { MSG_DSWA_BIT1, 0x01, 0x02 }, { MSG_OFF, 0x01}, { MSG_ON, 0x00}, DSW_SCREEN( 0x00, 0x02), DSW_TEST_MODE( 0x00, 0x04), DSW_DEMO_SOUND( 0x08, 0x00), { MSG_COIN1, 0x30, 0x04 }, { MSG_1COIN_1PLAY, 0x30}, { MSG_1COIN_2PLAY, 0x20}, { MSG_2COIN_1PLAY, 0x10}, { MSG_3COIN_1PLAY, 0x00}, { MSG_COIN2, 0xC0, 0x04 }, { MSG_1COIN_1PLAY, 0xC0}, { MSG_1COIN_2PLAY, 0x80}, { MSG_2COIN_1PLAY, 0x40}, { MSG_3COIN_1PLAY, 0x00}, { NULL, 0, }, }; static struct DSW_DATA dsw_data_cachat_1[] = { { MSG_DIFFICULTY, 0x03, 0x04 }, { MSG_NORMAL, 0x03}, { MSG_EASY, 0x02}, { MSG_HARD, 0x01}, { MSG_HARDEST, 0x00}, { MSG_DSWB_BIT3, 0x04, 0x02 }, { MSG_OFF, 0x04}, { MSG_ON, 0x00}, { MSG_DSWB_BIT4, 0x08, 0x02 }, { MSG_OFF, 0x08}, { MSG_ON, 0x00}, { MSG_DSWB_BIT5, 0x10, 0x02 }, { MSG_OFF, 0x10}, { MSG_ON, 0x00}, { MSG_DSWB_BIT6, 0x20, 0x02 }, { MSG_OFF, 0x20}, { MSG_ON, 0x00}, { MSG_DSWB_BIT7, 0x40, 0x02 }, { MSG_OFF, 0x40}, { MSG_ON, 0x00}, { MSG_DSWB_BIT8, 0x80, 0x02 }, { MSG_OFF, 0x80}, { MSG_ON, 0x00}, { NULL, 0, }, }; static struct DSW_INFO dsw_cachat[] = { { 0x02C210, 0xFD, dsw_data_cachat_0 }, { 0x02C212, 0xFF, dsw_data_cachat_1 }, { 0, 0, NULL, }, }; /***************** FIGHTING HAWK *****************/ static struct ROM_INFO rom_fhawk[] = { { "b70-01.bin", 0x00080000, 0xfcdf67e2, 0, 0, 0, }, { "b70-02.bin", 0x00080000, 0x35f7172e, 0, 0, 0, }, { "b70-03.bin", 0x00080000, 0x42d5a9b8, 0, 0, 0, }, { "b70-07.bin", 0x00020000, 0x939114af, 0, 0, 0, }, { "b70-08.bin", 0x00020000, 0x4d795f48, 0, 0, 0, }, { "b70-09.bin", 0x00010000, 0x85cccaa2, 0, 0, 0, }, { NULL, 0, 0, 0, 0, 0, }, }; static struct INPUT_INFO input_fhawk[] = { INP0( COIN1, 0x02C20E, 0x04 ), INP0( COIN2, 0x02C20E, 0x08 ), INP0( TILT, 0x02C20E, 0x01 ), INP0( SERVICE, 0x02C20E, 0x02 ), INP0( P1_START, 0x02C20E, 0x40 ), INP0( P1_UP, 0x02C204, 0x01 ), INP0( P1_DOWN, 0x02C204, 0x02 ), INP0( P1_LEFT, 0x02C204, 0x04 ), INP0( P1_RIGHT, 0x02C204, 0x08 ), INP0( P1_B1, 0x02C204, 0x10 ), INP0( P1_B2, 0x02C204, 0x20 ), INP0( P2_START, 0x02C20E, 0x80 ), INP0( P2_UP, 0x02C206, 0x01 ), INP0( P2_DOWN, 0x02C206, 0x02 ), INP0( P2_LEFT, 0x02C206, 0x04 ), INP0( P2_RIGHT, 0x02C206, 0x08 ), INP0( P2_B1, 0x02C206, 0x10 ), INP0( P2_B2, 0x02C206, 0x20 ), END_INPUT }; static struct DSW_DATA dsw_data_fighting_hawk_0[] = { DSW_CABINET( 0x00, 0x01), DSW_SCREEN( 0x02, 0x00), DSW_TEST_MODE( 0x00, 0x04), DSW_DEMO_SOUND( 0x08, 0x00), { MSG_COIN1, 0x30, 0x04 }, { MSG_1COIN_1PLAY, 0x30}, { MSG_1COIN_2PLAY, 0x20}, { MSG_2COIN_1PLAY, 0x10}, { MSG_2COIN_3PLAY, 0x00}, { MSG_COIN2, 0xC0, 0x04 }, { MSG_1COIN_1PLAY, 0xC0}, { MSG_1COIN_2PLAY, 0x80}, { MSG_2COIN_1PLAY, 0x40}, { MSG_2COIN_3PLAY, 0x00}, { NULL, 0, }, }; static struct DSW_DATA dsw_data_fighting_hawk_1[] = { { MSG_DIFFICULTY, 0x03, 0x04 }, { MSG_NORMAL, 0x03}, { MSG_EASY, 0x02}, { MSG_HARD, 0x01}, { MSG_HARDEST, 0x00}, { _("Lives"), 0x30, 0x04 }, { "3", 0x30}, { "4", 0x20}, { "5", 0x10}, { "6", 0x00}, { NULL, 0, }, }; static struct DSW_INFO dsw_fhawk[] = { { 0x02C200, 0xFE, dsw_data_fighting_hawk_0 }, { 0x02C202, 0xFF, dsw_data_fighting_hawk_1 }, { 0, 0, NULL, }, }; /*************** KURI KINTON ***************/ static struct ROM_INFO rom_kurikina[] = { { "kk_ic2.rom", 0x00020000, 0x908603f2, 0, 0, 0, }, { "b42-07.22", 0x00010000, 0x0f2719c0, 0, 0, 0, }, { "kk_ic6.rom", 0x00020000, 0xa4a957b1, 0, 0, 0, }, { "kk_1-1l.rom", 0x00020000, 0xdf1d4fcd, 0, 0, 0, }, { "kk_2-2l.rom", 0x00020000, 0xfca7f647, 0, 0, 0, }, { "kk_3-1h.rom", 0x00020000, 0x71af848e, 0, 0, 0, }, { "kk_4-2h.rom", 0x00020000, 0xcebb5bac, 0, 0, 0, }, { "kk_5-3l.rom", 0x00020000, 0xd080fde1, 0, 0, 0, }, { "kk_6-3h.rom", 0x00020000, 0x322e3752, 0, 0, 0, }, { "kk_7-4l.rom", 0x00020000, 0xf5bf6829, 0, 0, 0, }, { "kk_8-4h.rom", 0x00020000, 0x117bde99, 0, 0, 0, }, { NULL, 0, 0, 0, 0, 0, }, }; static struct INPUT_INFO input_kurikint[] = { INP1( COIN1, 0x02C20E, 0x04 ), INP1( COIN2, 0x02C20E, 0x08 ), INP0( TILT, 0x02C20E, 0x01 ), INP0( SERVICE, 0x02C20E, 0x02 ), INP0( P1_START, 0x02C20E, 0x40 ), INP0( P1_UP, 0x02C204, 0x01 ), INP0( P1_DOWN, 0x02C204, 0x02 ), INP0( P1_LEFT, 0x02C204, 0x04 ), INP0( P1_RIGHT, 0x02C204, 0x08 ), INP0( P1_B1, 0x02C204, 0x10 ), INP0( P1_B2, 0x02C204, 0x20 ), INP0( P2_START, 0x02C20E, 0x80 ), INP0( P2_UP, 0x02C206, 0x01 ), INP0( P2_DOWN, 0x02C206, 0x02 ), INP0( P2_LEFT, 0x02C206, 0x04 ), INP0( P2_RIGHT, 0x02C206, 0x08 ), INP0( P2_B1, 0x02C206, 0x10 ), INP0( P2_B2, 0x02C206, 0x20 ), END_INPUT }; static struct DSW_DATA dsw_data_kuri_kinton_0[] = { DSW_CABINET( 0x00, 0x01), DSW_SCREEN( 0x02, 0x00), DSW_TEST_MODE( 0x00, 0x04), DSW_DEMO_SOUND( 0x08, 0x00), { MSG_COIN1, 0x30, 0x04 }, { MSG_1COIN_1PLAY, 0x30}, { MSG_1COIN_2PLAY, 0x20}, { MSG_2COIN_1PLAY, 0x10}, { MSG_2COIN_3PLAY, 0x00}, { MSG_COIN2, 0xC0, 0x04 }, { MSG_1COIN_1PLAY, 0xC0}, { MSG_1COIN_2PLAY, 0x80}, { MSG_2COIN_1PLAY, 0x40}, { MSG_2COIN_3PLAY, 0x00}, { NULL, 0, }, }; static struct DSW_INFO dsw_kurikina[] = { { 0x02C200, 0xFF, dsw_data_kuri_kinton_0 }, { 0x02C202, 0xFF, dsw_data_default_1 }, { 0, 0, NULL, }, }; /* Kuri kinton has quite a special romsw, it's in the data bank, bank 0xf * See read_kurikint_region and write_kurikint_region */ static struct ROMSW_DATA romsw_data_kuri_kinton_0[] = { { "Taito Japan (Notice)", 0x00 }, { "Taito America", 0x01 }, { "Taito Japan", 0x02 }, { "Taito Japan (Osaka Office)", 0x03 }, { NULL, 0 }, }; static struct ROMSW_INFO romsw_kurikint[] = { { 0x007FFF, 0x02, romsw_data_kuri_kinton_0 }, { 0, 0, NULL }, }; static struct ROM_INFO rom_kurikint[] = { { "b42-09.2", 0x00020000, 0xe97c4394, 0, 0, 0, }, { "b42-07.22", 0x00010000, 0x0f2719c0, 0, 0, 0, }, { "b42-06.6", 0x00020000, 0xfa15fd65, 0, 0, 0, }, { "b42-01.1", 0x00080000, 0x7d1a1fec, 0, 0, 0, }, { "b42-02.5", 0x00080000, 0x1a52e65c, 0, 0, 0, }, { NULL, 0, 0, 0, 0, 0, }, }; static struct ROM_INFO rom_kurikinj[] = { { "b42_05.2", 0x00020000, 0x077222b8, 0, 0, 0, }, { "b42-07.22", 0x00010000, 0x0f2719c0, 0, 0, 0, }, { "b42-06.6", 0x00020000, 0xfa15fd65, 0, 0, 0, }, { "b42-01.1", 0x00080000, 0x7d1a1fec, 0, 0, 0, }, { "b42-02.5", 0x00080000, 0x1a52e65c, 0, 0, 0, }, { NULL, 0, 0, 0, 0, 0, }, }; static struct DSW_DATA dsw_data_kuri_kinton_alt_0[] = { DSW_CABINET( 0x00, 0x01), DSW_SCREEN( 0x02, 0x00), DSW_TEST_MODE( 0x00, 0x04), DSW_DEMO_SOUND( 0x08, 0x00), { MSG_COIN1, 0x30, 0x04 }, { MSG_1COIN_1PLAY, 0x30}, { MSG_2COIN_1PLAY, 0x20}, { MSG_3COIN_1PLAY, 0x10}, { MSG_4COIN_1PLAY, 0x00}, { MSG_COIN2, 0xC0, 0x04 }, { MSG_1COIN_1PLAY, 0xC0}, { MSG_1COIN_2PLAY, 0x80}, { MSG_1COIN_4PLAY, 0x40}, { MSG_1COIN_6PLAY, 0x00}, { NULL, 0, }, }; static struct DSW_INFO dsw_kurikint[] = { { 0x02C200, 0xFF, dsw_data_kuri_kinton_alt_0 }, { 0x02C202, 0xFF, dsw_data_default_1 }, { 0, 0, NULL, }, }; /************ PLOTTING ************/ static struct ROM_INFO rom_plotting[] = { { "ic10", 0x10000, 0xbe240921, REGION_CPU1, 0x00000, LOAD_NORMAL }, { "b96-07.ic9", 0x10000, 0x0713a387, REGION_GFX1, 0x00000, LOAD_NORMAL }, { "b96-08.ic8", 0x10000, 0x55b8e294, REGION_GFX1, 0x10000, LOAD_NORMAL }, { NULL, 0, 0, 0, 0, 0 } }; static struct ROM_INFO rom_plottinga[] = // clone of plotting { { "plot01.ic10", 0x10000, 0x5b30bc25, REGION_CPU1, 0x00000, LOAD_NORMAL }, { "b96-02.ic9", 0x10000, 0x6e0bad2a, REGION_GFX1, 0x00000, LOAD_NORMAL }, { "b96-03.ic8", 0x10000, 0xfb5f3ca4, REGION_GFX1, 0x10000, LOAD_NORMAL }, { NULL, 0, 0, 0, 0, 0 } }; static struct ROM_INFO rom_plottingb[] = // clone of plotting { { "b96-06.ic10", 0x10000, 0xf89a54b1, REGION_CPU1, 0x00000, LOAD_NORMAL }, { "b96-02.ic9", 0x10000, 0x6e0bad2a, REGION_GFX1, 0x00000, LOAD_NORMAL }, { "b96-03.ic8", 0x10000, 0xfb5f3ca4, REGION_GFX1, 0x10000, LOAD_NORMAL }, { NULL, 0, 0, 0, 0, 0 } }; static struct INPUT_INFO input_plotting[] = { INP0( COIN1, 0x02C200, 0x02 ), INP0( COIN2, 0x02C201, 0x02 ), INP0( TILT, 0x02C201, 0x01 ), INP0( SERVICE, 0x02C200, 0x01 ), INP0( P1_START, 0x02C200, 0x04 ), INP0( P1_UP, 0x02C200, 0x08 ), INP0( P1_DOWN, 0x02C200, 0x10 ), INP0( P1_LEFT, 0x02C200, 0x20 ), INP0( P1_RIGHT, 0x02C200, 0x40 ), INP0( P1_B1, 0x02C200, 0x80 ), INP0( P2_START, 0x02C201, 0x04 ), INP0( P2_UP, 0x02C201, 0x08 ), INP0( P2_DOWN, 0x02C201, 0x10 ), INP0( P2_LEFT, 0x02C201, 0x20 ), INP0( P2_RIGHT, 0x02C201, 0x40 ), INP0( P2_B1, 0x02C201, 0x80 ), END_INPUT }; static struct DSW_DATA dsw_data_plotting_0[] = { { _("Max Players"), 0x01, 0x02 }, { "2", 0x01}, { "1", 0x00}, DSW_SCREEN( 0x02, 0x00), DSW_TEST_MODE( 0x00, 0x04), DSW_DEMO_SOUND( 0x08, 0x00), { MSG_COIN_SLOTS, 0x30, 0x04 }, { MSG_1COIN_1PLAY, 0x30}, { MSG_2COIN_1PLAY, 0x20}, { MSG_3COIN_1PLAY, 0x10}, { MSG_4COIN_1PLAY, 0x00}, { _("Continue cost"), 0xC0, 0x04 }, { _("Same as play"), 0xC0}, { _("1 extra coin"), 0x80}, { _("2 extra coins"), 0x40}, { _("3 extra coins"), 0x00}, { NULL, 0, }, }; static struct DSW_DATA dsw_data_plotting_1[] = { { MSG_DIFFICULTY, 0x03, 0x04 }, { MSG_NORMAL, 0x03}, { MSG_EASY, 0x02}, { MSG_HARD, 0x01}, { MSG_HARDEST, 0x00}, { _("Wild blocks"), 0x30, 0x04 }, { "2", 0x30}, { "1", 0x20}, { "3", 0x10}, { "4", 0x00}, DSW_CONTINUE_PLAY( 0x40, 0x00), { NULL, 0, }, }; static struct DSW_INFO dsw_plotting[] = { { 0x02C202, 0xFF, dsw_data_plotting_0 }, { 0x02C203, 0xFF, dsw_data_plotting_1 }, { 0, 0, NULL, }, }; static struct ROMSW_DATA romsw_data_plotting_0[] = { { "Taito Japan (Flipull)", 0x00 }, { "Taito America", 0x01 }, { "Taito Japan", 0x02 }, { NULL, 0 }, }; static struct ROMSW_INFO plotting_romsw[] = { { 0x007FFF, 0x02, romsw_data_plotting_0 }, { 0, 0, NULL }, }; /*********** PUZZNIC ***********/ static struct ROM_INFO rom_puzznic[] = { { "u09.rom", 0x00020000, 0x3c115f8b, 0, 0, 0, }, { "u10.rom", 0x00020000, 0x4264056c, 0, 0, 0, }, { "u11.rom", 0x00020000, 0xa4150b6c, 0, 0, 0, }, { NULL, 0, 0, 0, 0, 0, }, }; static struct INPUT_INFO input_puzznic[] = { INP0( COIN1, 0x02C200, 0x02 ), INP0( SERVICE, 0x02C200, 0x01 ), INP0( P1_START, 0x02C200, 0x04 ), INP0( P1_UP, 0x02C200, 0x08 ), INP0( P1_DOWN, 0x02C200, 0x10 ), INP0( P1_LEFT, 0x02C200, 0x20 ), INP0( P1_RIGHT, 0x02C200, 0x40 ), INP0( P1_B1, 0x02C201, 0x01 ), INP0( P1_B2, 0x02C200, 0x80 ), INP0( P2_START, 0x02C201, 0x04 ), INP0( P2_UP, 0x02C201, 0x08 ), INP0( P2_DOWN, 0x02C201, 0x10 ), INP0( P2_LEFT, 0x02C201, 0x20 ), INP0( P2_RIGHT, 0x02C201, 0x40 ), INP0( P2_B1, 0x02C201, 0x02 ), INP0( P2_B2, 0x02C201, 0x80 ), END_INPUT }; static struct DSW_DATA dsw_data_puzznic_0[] = { DSW_CABINET( 0x00, 0x01), DSW_SCREEN( 0x02, 0x00), DSW_TEST_MODE( 0x00, 0x04), DSW_DEMO_SOUND( 0x08, 0x00), { MSG_COIN_SLOTS, 0x30, 0x04 }, { MSG_1COIN_1PLAY, 0x30}, { MSG_1COIN_2PLAY, 0x20}, { MSG_2COIN_1PLAY, 0x10}, { MSG_2COIN_3PLAY, 0x00}, { NULL, 0, }, }; static struct DSW_DATA dsw_data_puzznic_1[] = { { MSG_DIFFICULTY, 0x03, 0x04 }, { MSG_NORMAL, 0x03}, { MSG_EASY, 0x02}, { MSG_HARD, 0x01}, { MSG_HARDEST, 0x00}, { _("Retries"), 0x0C, 0x04 }, { "2", 0x0C}, { "3", 0x08}, { "1", 0x04}, { "0", 0x00}, { _("Bombs"), 0x10, 0x02 }, { "0", 0x10}, { "2", 0x00}, { _("Girls"), 0x20, 0x02 }, { MSG_ON, 0x20}, { MSG_OFF, 0x00}, { _("Terms of Replay"), 0xC0, 0x04 }, { _("Stage Start/Timer Cont"),0xC0}, { _("Stage & Timer Start"), 0x80}, { _("One step back/Time Cnt"),0x40}, { _("No Use"), 0x00}, { NULL, 0, }, }; static struct DSW_INFO dsw_puzznic[] = { { 0x02C202, 0xFE, dsw_data_puzznic_0 }, { 0x02C203, 0x7F, dsw_data_puzznic_1 }, { 0, 0, NULL, }, }; static struct ROMSW_DATA romsw_data_puzznic_0[] = { { "Animation 20/Taito Japan", 0x01 }, { "Taito America", 0x02 }, { "Taito Japan", 0x03 }, { NULL, 0 }, }; static struct ROMSW_INFO romsw_puzznic[] = { { 0x007FFF, 0x01, romsw_data_puzznic_0 }, { 0, 0, NULL }, }; /************** PLAY GIRLS **************/ static struct ROM_INFO rom_plgirls[] = { { "pg01.ic7", 0x00040000, 0x79e41e74, 0, 0, 0, }, { "pg02.ic9", 0x00040000, 0x3cf05ca9, 0, 0, 0, }, { "pg03.ic6", 0x00040000, 0x6ca73092, 0, 0, 0, }, { NULL, 0, 0, 0, 0, 0, }, }; static struct INPUT_INFO input_plgirls[] = { INP0( COIN1, 0x0A800, 0x04 ), INP0( COIN2, 0x0A800, 0x08 ), INP0( TILT, 0x0A800, 0x02 ), INP0( SERVICE, 0x0A800, 0x01 ), INP0( P1_START, 0x0A800, 0x10 ), INP0( P1_UP, 0x0A801, 0x01 ), INP0( P1_DOWN, 0x0A801, 0x02 ), INP0( P1_LEFT, 0x0A801, 0x04 ), INP0( P1_RIGHT, 0x0A801, 0x08 ), INP0( P1_B1, 0x0A800, 0x40 ), INP0( P1_B2, 0x0A800, 0x80 ), INP0( P2_START, 0x0A800, 0x20 ), INP0( P2_UP, 0x0A801, 0x10 ), INP0( P2_DOWN, 0x0A801, 0x20 ), INP0( P2_LEFT, 0x0A801, 0x40 ), INP0( P2_RIGHT, 0x0A801, 0x80 ), INP0( P2_B1, 0x0A802, 0x01 ), INP0( P2_B2, 0x0A802, 0x02 ), END_INPUT }; static struct DSW_DATA dsw_data_plgirls_0[] = { DSW_CABINET( 0x00, 0x01), DSW_SCREEN( 0x02, 0x00), DSW_TEST_MODE( 0x00, 0x04), { MSG_COIN_SLOTS, 0x38, 0x07 }, { MSG_1COIN_1PLAY, 0x38}, { MSG_1COIN_2PLAY, 0x28}, { MSG_1COIN_4PLAY, 0x20}, { MSG_2COIN_1PLAY, 0x18}, { MSG_3COIN_1PLAY, 0x10}, { MSG_2COIN_3PLAY, 0x08}, { MSG_4COIN_1PLAY, 0x00}, { MSG_DSWA_BIT7, 0x40, 0x02 }, { MSG_OFF, 0x40}, { MSG_ON, 0x00}, { MSG_DSWA_BIT8, 0x80, 0x02 }, { MSG_OFF, 0x80}, { MSG_ON, 0x00}, { NULL, 0, }, }; static struct DSW_DATA dsw_data_plgirls_1[] = { { MSG_DIFFICULTY, 0x03, 0x04 }, { MSG_NORMAL, 0x03}, { MSG_EASY, 0x02}, { MSG_HARD, 0x01}, { MSG_HARDEST, 0x00}, { MSG_DSWA_BIT3, 0x04, 0x02 }, { MSG_OFF, 0x04}, { MSG_ON, 0x00}, { MSG_DSWA_BIT4, 0x08, 0x02 }, { MSG_OFF, 0x08}, { MSG_ON, 0x00}, { MSG_DSWA_BIT5, 0x10, 0x02 }, { MSG_OFF, 0x10}, { MSG_ON, 0x00}, { MSG_DSWA_BIT6, 0x20, 0x02 }, { MSG_OFF, 0x20}, { MSG_ON, 0x00}, { MSG_DSWA_BIT7, 0x40, 0x02 }, { MSG_OFF, 0x40}, { MSG_ON, 0x00}, { MSG_DSWA_BIT8, 0x80, 0x02 }, { MSG_OFF, 0x80}, { MSG_ON, 0x00}, { NULL, 0, }, }; static struct DSW_INFO dsw_plgirls[] = { { 0x02C202, 0xFE, dsw_data_plgirls_0 }, { 0x02C203, 0x7F, dsw_data_plgirls_1 }, { 0, 0, NULL, }, }; /**************** PLAY GIRLS 2 ****************/ static struct ROM_INFO rom_plgirls2[] = { { "cho-h.ic7", 0x00080000, 0x992f99b1, 0, 0, 0, }, { "cho-l.ic9", 0x00080000, 0x956384ec, 0, 0, 0, }, { "pg2_1j.ic6", 0x00040000, 0xf924197a, 0, 0, 0, }, { NULL, 0, 0, 0, 0, 0, }, }; static struct INPUT_INFO input_plgirls2[] = { INP0( COIN1, 0x0A800, 0x04 ), INP0( COIN2, 0x0A800, 0x08 ), INP0( TILT, 0x0A800, 0x02 ), INP0( SERVICE, 0x0A800, 0x01 ), INP0( P1_START, 0x0A800, 0x10 ), INP0( P1_UP, 0x0A801, 0x01 ), INP0( P1_DOWN, 0x0A801, 0x02 ), INP0( P1_LEFT, 0x0A801, 0x04 ), INP0( P1_RIGHT, 0x0A801, 0x08 ), INP0( P1_B1, 0x0A800, 0x40 ), INP0( P1_B2, 0x0A800, 0x80 ), INP0( P2_START, 0x0A800, 0x20 ), INP0( P2_UP, 0x0A801, 0x10 ), INP0( P2_DOWN, 0x0A801, 0x20 ), INP0( P2_LEFT, 0x0A801, 0x40 ), INP0( P2_RIGHT, 0x0A801, 0x80 ), INP0( P2_B1, 0x0A802, 0x01 ), INP0( P2_B2, 0x0A802, 0x02 ), END_INPUT }; static struct DSW_DATA dsw_data_plgirls2_0[] = { DSW_CABINET( 0x00, 0x01), DSW_SCREEN( 0x02, 0x00), DSW_TEST_MODE( 0x00, 0x04), { MSG_DSWA_BIT4, 0x08, 0x02 }, { MSG_OFF, 0x08}, { MSG_ON, 0x00}, { MSG_COIN1, 0x30, 0x04 }, { MSG_1COIN_1PLAY, 0x30}, { MSG_1COIN_2PLAY, 0x20}, { MSG_2COIN_1PLAY, 0x10}, { MSG_2COIN_3PLAY, 0x00}, { MSG_COIN2, 0xC0, 0x04 }, { MSG_1COIN_1PLAY, 0xC0}, { MSG_1COIN_2PLAY, 0x80}, { MSG_2COIN_1PLAY, 0x40}, { MSG_2COIN_3PLAY, 0x00}, { NULL, 0, }, }; static struct DSW_DATA dsw_data_plgirls2_1[] = { { MSG_DIFFICULTY, 0x03, 0x04 }, { MSG_NORMAL, 0x03}, { MSG_EASY, 0x02}, { MSG_HARD, 0x01}, { MSG_HARDEST, 0x00}, { MSG_DSWA_BIT3, 0x04, 0x02 }, { MSG_OFF, 0x04}, { MSG_ON, 0x00}, { _("Life"), 0x18, 0x04 }, { "4/3/4", 0x18}, { "3/2/3", 0x10}, { "5/4/5", 0x08}, { "6/5/6", 0x00}, { MSG_DSWA_BIT6, 0x20, 0x02 }, { MSG_OFF, 0x20}, { MSG_ON, 0x00}, { MSG_DSWA_BIT7, 0x40, 0x02 }, { MSG_OFF, 0x40}, { MSG_ON, 0x00}, { MSG_DSWA_BIT8, 0x80, 0x02 }, { MSG_OFF, 0x80}, { MSG_ON, 0x00}, { NULL, 0, }, }; static struct DSW_INFO dsw_plgirls2[] = { { 0x02C202, 0xFE, dsw_data_plgirls2_0 }, { 0x02C203, 0x7F, dsw_data_plgirls2_1 }, { 0, 0, NULL, }, }; /************* PALAMEDES *************/ static struct ROM_INFO rom_palamed[] = { { "c63.02", 0x00020000, 0x55a82bb2, 0, 0, 0, }, { "c63.03", 0x00020000, 0xfcd86e44, 0, 0, 0, }, { "c63.04", 0x00020000, 0xc7bbe460, 0, 0, 0, }, { NULL, 0, 0, 0, 0, 0, }, }; static struct INPUT_INFO input_palamed[] = { INP0( COIN1, 0x02C200, 0x04 ), INP0( COIN2, 0x02C200, 0x08 ), INP0( TILT, 0x02C200, 0x02 ), INP0( SERVICE, 0x02C200, 0x01 ), INP0( P1_START, 0x02C200, 0x10 ), INP0( P1_UP, 0x02C202, 0x01 ), INP0( P1_DOWN, 0x02C202, 0x02 ), INP0( P1_LEFT, 0x02C202, 0x04 ), INP0( P1_RIGHT, 0x02C202, 0x08 ), INP0( P1_B1, 0x02C200, 0x40 ), INP0( P1_B2, 0x02C200, 0x80 ), INP0( P2_START, 0x02C200, 0x20 ), INP0( P2_UP, 0x02C202, 0x10 ), INP0( P2_DOWN, 0x02C202, 0x20 ), INP0( P2_LEFT, 0x02C202, 0x40 ), INP0( P2_RIGHT, 0x02C202, 0x80 ), INP0( P2_B1, 0x02C204, 0x01 ), INP0( P2_B2, 0x02C204, 0x02 ), END_INPUT }; static struct DSW_DATA dsw_data_palamedes_0[] = { { MSG_DSWA_BIT1, 0x01, 0x02 }, { MSG_OFF, 0x01}, { MSG_ON, 0x00}, DSW_SCREEN( 0x02, 0x00), DSW_TEST_MODE( 0x00, 0x04), DSW_DEMO_SOUND( 0x08, 0x00), { MSG_COIN_SLOTS, 0x30, 0x04 }, { MSG_1COIN_1PLAY, 0x30}, { MSG_2COIN_1PLAY, 0x20}, { MSG_3COIN_1PLAY, 0x10}, { MSG_4COIN_1PLAY, 0x00}, { MSG_DSWA_BIT7, 0x40, 0x02 }, { MSG_OFF, 0x40}, { MSG_ON, 0x00}, { MSG_DSWA_BIT8, 0x80, 0x02 }, { MSG_OFF, 0x80}, { MSG_ON, 0x00}, { NULL, 0, }, }; static struct DSW_DATA dsw_data_palamedes_1[] = { { MSG_DIFFICULTY, 0x03, 0x04 }, { MSG_NORMAL, 0x03}, { MSG_EASY, 0x02}, { MSG_HARD, 0x01}, { MSG_HARDEST, 0x00}, { MSG_DSWB_BIT3, 0x04, 0x02 }, { MSG_OFF, 0x04}, { MSG_ON, 0x00}, { MSG_DSWB_BIT4, 0x08, 0x02 }, { MSG_OFF, 0x08}, { MSG_ON, 0x00}, { MSG_DSWB_BIT5, 0x10, 0x02 }, { MSG_OFF, 0x10}, { MSG_ON, 0x00}, { MSG_DSWB_BIT6, 0x20, 0x02 }, { MSG_OFF, 0x20}, { MSG_ON, 0x00}, { MSG_DSWB_BIT7, 0x40, 0x02 }, { MSG_OFF, 0x40}, { MSG_ON, 0x00}, { _("Versus Mode"), 0x80, 0x02 }, { MSG_ON, 0x80}, { MSG_OFF, 0x00}, { NULL, 0, }, }; static struct DSW_INFO dsw_palamed[] = { { 0x02C210, 0xFF, dsw_data_palamedes_0 }, { 0x02C212, 0xFF, dsw_data_palamedes_1 }, { 0, 0, NULL, }, }; static struct ROMSW_DATA romsw_data_palamedes_0[] = { { "Taito Japan (Japanese)", 0x00 }, { "Taito America", 0x01 }, { "Taito Japan", 0x02 }, { "Hot-B America", 0x03 }, { NULL, 0 }, }; static struct ROMSW_INFO romsw_palamed[] = { { 0x007FFF, 0x00, romsw_data_palamedes_0 }, { 0, 0, NULL }, }; /************* CUBYBOP *************/ static struct ROM_INFO rom_cubybop[] = { { "cb06.6", 0x00040000, 0x66b89a85, 0, 0, 0, }, { "cb07.7", 0x00040000, 0x3582de99, 0, 0, 0, }, { "cb08.8", 0x00040000, 0x09e18a51, 0, 0, 0, }, { "cb09.9", 0x00040000, 0x5f831e59, 0, 0, 0, }, { "cb10.10", 0x00040000, 0x430510fc, 0, 0, 0, }, { NULL, 0, 0, 0, 0, 0, }, }; static struct INPUT_INFO input_cubybop[] = { INP0( COIN1, 0x02C200, 0x04 ), INP0( COIN2, 0x02C200, 0x08 ), INP0( TILT, 0x02C200, 0x02 ), INP0( SERVICE, 0x02C200, 0x01 ), INP0( P1_START, 0x02C200, 0x10 ), INP0( P1_UP, 0x02C202, 0x01 ), INP0( P1_DOWN, 0x02C202, 0x02 ), INP0( P1_LEFT, 0x02C202, 0x04 ), INP0( P1_RIGHT, 0x02C202, 0x08 ), INP0( P1_B1, 0x02C200, 0x40 ), INP0( P1_B2, 0x02C200, 0x80 ), INP0( P2_START, 0x02C200, 0x20 ), INP0( P2_UP, 0x02C202, 0x10 ), INP0( P2_DOWN, 0x02C202, 0x20 ), INP0( P2_LEFT, 0x02C202, 0x40 ), INP0( P2_RIGHT, 0x02C202, 0x80 ), INP0( P2_B1, 0x02C204, 0x01 ), INP0( P2_B2, 0x02C204, 0x02 ), END_INPUT }; static struct DSW_DATA dsw_data_cubybop_0[] = { { MSG_DSWA_BIT1, 0x01, 0x02 }, { MSG_OFF, 0x01}, { MSG_ON, 0x00}, DSW_SCREEN( 0x02, 0x00), DSW_TEST_MODE( 0x00, 0x04), DSW_DEMO_SOUND( 0x08, 0x00), { MSG_COIN_SLOTS, 0x30, 0x04 }, { MSG_1COIN_1PLAY, 0x30}, { MSG_2COIN_1PLAY, 0x20}, { MSG_3COIN_1PLAY, 0x10}, { MSG_4COIN_1PLAY, 0x00}, { MSG_DSWA_BIT7, 0x40, 0x02 }, { MSG_OFF, 0x40}, { MSG_ON, 0x00}, { MSG_DSWA_BIT8, 0x80, 0x02 }, { MSG_OFF, 0x80}, { MSG_ON, 0x00}, { NULL, 0, }, }; static struct DSW_DATA dsw_data_cubybop_1[] = { { MSG_DIFFICULTY, 0x03, 0x04 }, { MSG_NORMAL, 0x03}, { MSG_EASY, 0x02}, { MSG_HARD, 0x01}, { MSG_HARDEST, 0x00}, { MSG_DSWB_BIT3, 0x04, 0x02 }, { MSG_OFF, 0x04}, { MSG_ON, 0x00}, { MSG_DSWB_BIT4, 0x08, 0x02 }, { MSG_OFF, 0x08}, { MSG_ON, 0x00}, { MSG_DSWB_BIT5, 0x10, 0x02 }, { MSG_OFF, 0x10}, { MSG_ON, 0x00}, { MSG_DSWB_BIT6, 0x20, 0x02 }, { MSG_OFF, 0x20}, { MSG_ON, 0x00}, { MSG_DSWB_BIT7, 0x40, 0x02 }, { MSG_OFF, 0x40}, { MSG_ON, 0x00}, { _("Versus Mode"), 0x80, 0x02 }, { MSG_ON, 0x80}, { MSG_OFF, 0x00}, { NULL, 0, }, }; static struct DSW_INFO dsw_cubybop[] = { { 0x02C210, 0xFF, dsw_data_cubybop_0 }, { 0x02C212, 0xFF, dsw_data_cubybop_1 }, { 0, 0, NULL, }, }; /************* TUBE IT *************/ static struct ROM_INFO rom_tubeit[] = { { "t-i_02.6", 0x00020000, 0x54730669, 0, 0, 0, }, { "t-i_03.7", 0x00040000, 0xe1c3fed0, 0, 0, 0, }, { "t-i_04.9", 0x00040000, 0xb4a6e31d, 0, 0, 0, }, { NULL, 0, 0, 0, 0, 0, }, }; /*********** RAIMAIS ***********/ static struct ROM_INFO rom_raimais[] = { { "b36-01.bin", 0x00080000, 0x89355cb2, 0, 0, 0, }, { "b36-02.bin", 0x00080000, 0xe71da5db, 0, 0, 0, }, { "b36-03.bin", 0x00080000, 0x96166516, 0, 0, 0, }, { "b36-06.bin", 0x00010000, 0x29bbc4f8, 0, 0, 0, }, { "b36-07.bin", 0x00010000, 0x4f3737e6, 0, 0, 0, }, { "b36-08-1.bin", 0x00020000, 0x6cc8f79f, 0, 0, 0, }, { "b36-09.bin", 0x00020000, 0x9c466e43, 0, 0, 0, }, { NULL, 0, 0, 0, 0, 0, }, }; static struct INPUT_INFO input_raimais[] = { INP1( COIN1, 0x02C20E, 0x04 ), INP1( COIN2, 0x02C20E, 0x08 ), INP0( TILT, 0x02C20E, 0x01 ), INP0( SERVICE, 0x02C20E, 0x02 ), INP0( P1_START, 0x02C20E, 0x40 ), INP0( P1_UP, 0x02C204, 0x01 ), INP0( P1_DOWN, 0x02C204, 0x02 ), INP0( P1_LEFT, 0x02C204, 0x04 ), INP0( P1_RIGHT, 0x02C204, 0x08 ), INP0( P1_B1, 0x02C204, 0x10 ), INP0( P1_B2, 0x02C204, 0x20 ), INP0( P2_START, 0x02C20E, 0x80 ), INP0( P2_UP, 0x02C206, 0x01 ), INP0( P2_DOWN, 0x02C206, 0x02 ), INP0( P2_LEFT, 0x02C206, 0x04 ), INP0( P2_RIGHT, 0x02C206, 0x08 ), INP0( P2_B1, 0x02C206, 0x10 ), INP0( P2_B2, 0x02C206, 0x20 ), END_INPUT }; static struct DSW_DATA dsw_data_raimais_0[] = { DSW_CABINET( 0x00, 0x01), DSW_SCREEN( 0x02, 0x00), DSW_TEST_MODE( 0x00, 0x04), DSW_DEMO_SOUND( 0x08, 0x00), { MSG_COIN1, 0x30, 0x04 }, { MSG_1COIN_1PLAY, 0x30}, { MSG_1COIN_2PLAY, 0x20}, { MSG_2COIN_1PLAY, 0x10}, { MSG_2COIN_3PLAY, 0x00}, { MSG_COIN2, 0xC0, 0x04 }, { MSG_1COIN_1PLAY, 0xC0}, { MSG_1COIN_2PLAY, 0x80}, { MSG_2COIN_1PLAY, 0x40}, { MSG_2COIN_3PLAY, 0x00}, { NULL, 0, }, }; static struct DSW_DATA dsw_data_raimais_1[] = { { MSG_DIFFICULTY, 0x03, 0x04 }, { MSG_NORMAL, 0x03}, { MSG_EASY, 0x02}, { MSG_HARD, 0x01}, { MSG_HARDEST, 0x00}, { _("Extra Life"), 0x0C, 0x04 }, { _("80k only"), 0x0C}, { _("80k and 160k"), 0x08}, { _("160k only"), 0x04}, { _("None"), 0x00}, { _("Lives"), 0x30, 0x04 }, { "3", 0x30}, { "4", 0x20}, { "5", 0x10}, { "6", 0x00}, { MSG_DSWB_BIT7, 0x40, 0x02 }, { MSG_OFF, 0x40}, { MSG_ON, 0x00}, DSW_CONTINUE_PLAY( 0x00, 0x80), { NULL, 0, }, }; static struct DSW_INFO dsw_raimais[] = { { 0x02C200, 0xFE, dsw_data_raimais_0 }, { 0x02C202, 0x7F, dsw_data_raimais_1 }, { 0, 0, NULL, }, }; /* TAITO L-SYSTEM -------------- Supported romsets: 0 - B36 - Raimais - 1988 - L-System 1 - C47 - American Horseshoes - 1990 - L-System (vertical) (trackball) (gfx bank) 2 - B96 - Plotting - 1989 - L-System 3 - C01 - Champion Wrestler - 1989 - L-System 4 - B70 - Fighting Hawk - 1988 - L-System (vertical) 5 - B42 - Kuri Kinton - 1988 - L-System . - ... - Kuri Kinton alternate - 1988 - L-System 6 - C20 - Puzznic - 1989 - L-System (mcu) 7 - C63 - Palamedes - 1990 - L-System 8 - D?? - Cachat - 1993 - L-System 9 - ??? - Cuby Bop - 1990 - L-System Z80 has banked Video RAM, it has 4 bank slots: C000-CFFF D000-DFFF E000-EFFF F000-FDFF (last 512 bytes are not accessable in this bank) Each bank can access any one of the following: ------+--------------+---------- Byte | Access | Range ------+--------------+---------- 14 | FG0 GFX RAM | 0000-0FFF 15 | FG0 GFX RAM | 1000-1FFF 16 | FG0 GFX RAM | 2000-2FFF 17 | FG0 GFX RAM | 3000-3FFF 18 | SCREEN RAM | 0000-0FFF 19 | SCREEN RAM | 1000-1FFF 1A | SCREEN RAM | 2000-2FFF 1B | SCREEN RAM | 3000-3FFF 1C | FG0 GFX RAM | 4000-4FFF (Champion Wrestler) 1D | FG0 GFX RAM | 5000-5FFF (Champion Wrestler) 1E | FG0 GFX RAM | 6000-6FFF (Champion Wrestler) 1F | FG0 GFX RAM | 7000-7FFF (Champion Wrestler) 80 | COLOR RAM | 0000-01FF ------+--------------+---------- SCREEN RAM ---------- ----------+---- Offset | Use ----------+---- 0000-0FFF | BG1 1000-1FFF | BG0 2000-2FFF | FG0 3000-33FF | SPR ----------+---- INTERRUPT VECTORS ----------------- 0 - Interrupt#0 1 - Interrupt#1 2 - Interrupt#2 3 - Bit#0 = Interrupt#0 Enable Bit#1 = Interrupt#1 Enable Bit#2 = Interrupt#2 Enable TILE BANK --------- 0 - Bank#0 1 - Bank#1 2 - Bank#2 3 - Bank#3 4 - Bit#3 = Sprite Dual Priority <?> Bit#4 = Screen Normal/Invert Bit#5 = Disable Layer <???> Bit#6 = Disable Layer <???> Bit#7 = Disable Layer <???> 5 - Unused <?> 6 - Unused <?> 7 - Unused <?> OBJECT RAM ---------- -----+--------+------------------------- Byte | Bit(s) | Use -----+76543210+------------------------- 1 |..xxxxxx| Sprite Tile (high) 0 |xxxxxxxx| Sprite Tile (low) 3 |......xx| Flip XY 2 |....xxxx| Colour Bank 5 |.......x| Sprite X (high) 4 |xxxxxxxx| Sprite X (low) 7 |........| Sprite Y (high) 6 |xxxxxxxx| Sprite Y (low) -----+--------+------------------------- Todo: - Language switches (Raimais). - Stuff not in RAM[] is unsaved. - American Horseshoes trackball emulation needs improving. */ static UINT8 ReadTrackBall(UINT16 offset) { return RAM_INP[4|((offset>>2)&3)]; } /******************************************************************************/ /* L-SYSTEM INTERRUPT VECTORS */ /******************************************************************************/ static void LSystemIntVecWrite(UINT16 offset, UINT8 data) { VectorData[offset&3] = data; } static UINT8 LSystemIntVecRead(UINT16 offset) { return VectorData[offset&3]; } static UINT8 ah_gfx_bank; static void LSystemTileBank2Write(UINT16 offset, UINT8 data) { static int kkk[4] = { 0,2,1,3, }; ah_gfx_bank = kkk[data]; /*#ifdef RAINE_DEBUG print_ingame(8000,gettext("ah_gfx_bank Bank(%04x,%02x) [%02x]\n"),offset,data,ah_gfx_bank); #endif*/ } /******************************************************************************/ /* L-SYSTEM TILE BANKING */ /******************************************************************************/ static UINT8 TileBank[8]; static void LSystemTileBankWrite(UINT16 offset, UINT8 data) { TileBank[offset&7] = data; #ifdef RAINE_DEBUG if((offset&7)>3) print_debug("Tile Bank(%02x,%02x)\n",offset&7,data); #endif } static UINT8 LSystemTileBankRead(UINT16 offset) { return TileBank[offset&7]; } /******************************************************************************/ /* L-SYSTEM Z80 ROM BANKING */ /******************************************************************************/ static UINT8 Z80BankCount; static void LSystemNewBankWrite(UINT16 offset, UINT8 data) { z80_set_bank(1,data); } static UINT8 LSystemBankRead(UINT16 offset) { return z80_get_current_bank(1); } extern UINT8 *ROM_BANK[]; static UINT8 lsystem_ym2203_reg; static UINT8 VRAMBank[4]; static void init_bank_rom(UINT8 *src ) { int i; UINT8 *dest; ah_gfx_bank = 0; lsystem_ym2203_reg = 0; memset(TileBank,0,8); memset(VRAMBank,0,4); z80_init_banks_area_ofs(1,src,Z80BankCount * 0x2000,0x6000,0x2000,3); // Here the first banks contain a copy of the roms (stupid !) for (i=0; i<3; i++) { dest = ROM_BANK[1] + i * 0x8000 + 0x6000; memcpy(dest,src+i*0x2000,0x2000); } } /******************************************************************************/ /* L-SYSTEM SUB Z80 ROM BANKING */ /******************************************************************************/ static UINT8 Z802Bank; static UINT8 Z802BankCount; static void LSystemSubCpuNewBankWrite(UINT16 offset, UINT8 data) { Z802Bank = data; z80_set_bank(2,data & 0xf); /* if((data&0x20)==0x20){ // WAS: 0xF0 */ /* data&=0x0F; */ /* if(data != Z802Bank){ */ /* if(data<Z802BankCount){ */ /* Z802Bank = data; */ /* Z80CSetBank( ROM_BANK_2[Z802Bank] ); */ /* } */ /* else{ */ /* print_debug("SUB Z80 ROM Bank out of range: %02x [%04x]\n", data, z80pc); */ /* } */ /* } */ /* } */ /* else{ */ /* print_debug("SUB Z80 ROM Bank strange: %02x [%04x]\n", data, z80pc); */ /* } */ } static UINT8 LSystemSubCpuBankRead(UINT16 offset) { return Z802Bank; } static void init_bank_rom2(UINT8 *src) { int i; UINT8 *dest; Z802Bank = -1; z80_init_banks_area_ofs(2,src,Z802BankCount * 0x4000,0x8000,0x4000,2); // Here the first banks contain a copy of the roms (stupid !) for (i=0; i<3; i++) { dest = ROM_BANK[2] + i * 0xc000 + 0x8000; memcpy(dest,src+i*0x4000,0x4000); } } /******************************************************************************/ /* L-SYSTEM FG0 GFX RAM */ /******************************************************************************/ static UINT8 *RAM_FG0; // $4000*2 bytes static UINT8 *GFX_FG0; // $8000*2 bytes static UINT32 gfx_fg0_dirty_count; static UINT32 GFX_FG0_DIRTY[0x400]; static UINT8 GFX_FG0_SOLID[0x400]; static void update_gfx_fg0(void) { UINT32 ta,tb,tc,td,te; UINT8 *source; for(ta = 0; ta < gfx_fg0_dirty_count; ta++){ tb = GFX_FG0_DIRTY[ta]; source = GFX_FG0 + (tb << 6); td=0; te=0; for(tc=0;tc<0x40;tc++){ if(source[tc]) td=1; else te=1; } if((td==0)&&(te==1)) GFX_FG0_SOLID[tb]=0; // All pixels are 0: Don't Draw if((td==1)&&(te==1)) GFX_FG0_SOLID[tb]=1; // Mixed: Draw Trans if((td==1)&&(te==0)) GFX_FG0_SOLID[tb]=2; // All pixels are !0: Draw Solid } gfx_fg0_dirty_count = 0; } static DEF_INLINE void LSystem_GFX_FG0_Write(UINT16 offset, UINT8 data) { UINT32 i,j,k; UINT8 *GFX_FG; if(data == RAM_FG0[offset]) return; RAM_FG0[offset] = data; i = (offset & 0x001E) << 1; k = (offset & 0x7FE0) >> 5; GFX_FG = GFX_FG0 + (k<<6); if(!(offset&1)){ j = tile_8x8_map[ i + 0 ]; GFX_FG[j] = (GFX_FG[j]&0x0C)|(((data&0x01)>>0)<<0)|(((data&0x10)>>4)<<1); j = tile_8x8_map[ i + 1 ]; GFX_FG[j] = (GFX_FG[j]&0x0C)|(((data&0x02)>>1)<<0)|(((data&0x20)>>5)<<1); j = tile_8x8_map[ i + 2 ]; GFX_FG[j] = (GFX_FG[j]&0x0C)|(((data&0x04)>>2)<<0)|(((data&0x40)>>6)<<1); j = tile_8x8_map[ i + 3 ]; GFX_FG[j] = (GFX_FG[j]&0x0C)|(((data&0x08)>>3)<<0)|(((data&0x80)>>7)<<1); } else{ j = tile_8x8_map[ i + 0 ]; GFX_FG[j] = (GFX_FG[j]&0x03)|(((data&0x01)>>0)<<2)|(((data&0x10)>>4)<<3); j = tile_8x8_map[ i + 1 ]; GFX_FG[j] = (GFX_FG[j]&0x03)|(((data&0x02)>>1)<<2)|(((data&0x20)>>5)<<3); j = tile_8x8_map[ i + 2 ]; GFX_FG[j] = (GFX_FG[j]&0x03)|(((data&0x04)>>2)<<2)|(((data&0x40)>>6)<<3); j = tile_8x8_map[ i + 3 ]; GFX_FG[j] = (GFX_FG[j]&0x03)|(((data&0x08)>>3)<<2)|(((data&0x80)>>7)<<3); } // request mask update if(GFX_FG0_SOLID[k] != 3){ GFX_FG0_SOLID[k] = 3; GFX_FG0_DIRTY[gfx_fg0_dirty_count++] = k; } } static DEF_INLINE UINT16 LSystem_GFX_FG0_Read(UINT16 offset) { return RAM_FG0[offset]; } /******************************************************************************/ /* L-SYSTEM BG0 RAM */ /******************************************************************************/ static UINT8 *RAM_BG0; // $4000 bytes static DEF_INLINE void LSystem_BG0_Write(UINT16 offset, UINT8 data) { RAM_BG0[offset] = data; } static DEF_INLINE UINT16 LSystem_BG0_Read(UINT16 offset) { return RAM_BG0[offset]; } /******************************************************************************/ /* L-SYSTEM COLOUR RAM */ /******************************************************************************/ static DEF_INLINE void LSystem_PAL_Write(UINT16 offset, UINT8 data) { RAM_PAL[offset&0x1FF] = data; } static DEF_INLINE UINT16 LSystem_PAL_Read(UINT16 offset) { return RAM_PAL[offset&0x1FF]; } /******************************************************************************/ /* L-SYSTEM VRAM BANKING */ /******************************************************************************/ static void LSystemVRAMBankWrite(UINT16 offset, UINT8 data) { VRAMBank[offset&3] = data; } static UINT8 LSystemVRAMBankRead(UINT16 offset) { return VRAMBank[offset&3]; } /******************************************************************************/ /* L-SYSTEM BANKED VRAM ACCESS */ /******************************************************************************/ static void LSystemVRAMWrite(UINT16 offset, UINT8 data) { int bank; bank=VRAMBank[(offset>>12)&3]; offset&=0xFFF; switch(bank){ case 0x14: case 0x15: case 0x16: case 0x17: LSystem_GFX_FG0_Write((UINT16) (offset|((bank&3)<<12)), data); break; case 0x18: case 0x19: case 0x1A: case 0x1B: LSystem_BG0_Write((UINT16) (offset|((bank&3)<<12)), data); break; case 0x1C: case 0x1D: case 0x1E: case 0x1F: LSystem_GFX_FG0_Write((UINT16) (offset|(((bank&3)|4)<<12)), data); break; case 0x80: LSystem_PAL_Write(offset, data); break; default: print_debug("VRAM Write to Strange Bank(%02x:%04x,%02x) [%04x]\n",bank,offset,data,z80pc); break; } } static UINT8 LSystemVRAMRead(UINT16 offset) { int bank; bank=VRAMBank[(offset>>12)&3]; offset&=0xFFF; switch(bank){ case 0x14: case 0x15: case 0x16: case 0x17: return(LSystem_GFX_FG0_Read((UINT16) (offset|((bank&3)<<12)))); break; case 0x18: case 0x19: case 0x1A: case 0x1B: return(LSystem_BG0_Read((UINT16) (offset|((bank&3)<<12)))); break; case 0x1C: case 0x1D: case 0x1E: case 0x1F: return(LSystem_GFX_FG0_Read((UINT16) (offset|(((bank&3)|4)<<12)))); break; case 0x80: return(LSystem_PAL_Read(offset)); break; default: print_debug("VRAM Read from Strange Bank(%02x:%04x) [%04x]\n",bank,offset,z80pc); return(0xFF); break; } } static int layer_id_data[5]; static void lsystem_vcu_init(int fg0_size) { memset(RAM_BG0,0x00,0x4000); memset(RAM_PAL,0x00,0x0200); VRAMBank[0] = 0; VRAMBank[1] = 0; VRAMBank[2] = 0; VRAMBank[3] = 0; memset(RAM_FG0,0x00,0x4000<<fg0_size); memset(GFX_FG0,0x00,0x8000<<fg0_size); gfx_fg0_dirty_count = 0; memset(GFX_FG0_DIRTY,0x00,0x400*4); memset(GFX_FG0_SOLID,0x00,0x400); layer_id_data[0] = add_layer_info(gettext("BG0")); layer_id_data[1] = add_layer_info(gettext("OBJ")); layer_id_data[2] = add_layer_info(gettext("BG1")); layer_id_data[3] = add_layer_info(gettext("OBJ 2")); layer_id_data[4] = add_layer_info(gettext("FG")); set_colour_mapper(&col_map_xxxx_bbbb_gggg_rrrr); InitPaletteMap(RAM_PAL, 0x10, 0x10, 0x8000); } /******************************************************************************/ /* L-SYSTEM YM2203 */ /******************************************************************************/ // YM2203 with dsw and inputs static UINT8 lsystem_ym2203_input_dsw_rb(UINT16 offset) { if(!(offset&1)){ return YM2203_status_port_0_r(offset); } else{ switch(lsystem_ym2203_reg){ case 0x0e: return get_dsw((offset>>1)&1); case 0x0f: return RAM_INP[(offset>>1)&1]; } return YM2203_read_port_0_r(offset); } } // YM2203 with dsw static UINT8 lsystem_ym2203_dsw_rb(UINT16 offset) { if(!(offset&1)){ return YM2203_status_port_0_r(offset); } else{ switch(lsystem_ym2203_reg){ case 0x0e: return get_dsw(0); case 0x0f: return get_dsw(1); } return YM2203_read_port_0_r(offset); } } // YM2203 with nothing static UINT8 lsystem_ym2203_rb(UINT16 offset) { if(!(offset&1)){ return YM2203_status_port_0_r(offset); } else{ return YM2203_read_port_0_r(offset); } } static void lsystem_ym2203_wb(UINT16 offset, UINT8 data) { if(!(offset&1)){ lsystem_ym2203_reg = data; YM2203_control_port_0_w(offset,data); } else{ YM2203_write_port_0_w(offset,data); } } /******************************************************************************/ /* PUZZNIC MCU */ /******************************************************************************/ static void PuzznicMCUWrite(UINT16 offset, UINT8 data) { if((offset&1)==0){ RAM[0xB800] = data; } } static UINT8 PuzznicMCURead(UINT16 offset) { int ret; if((offset&1)==0){ switch(RAM[0xB800]){ case 0x43: ret = 0x50; RAM[0xB800]++; break; // ID Check case 0x44: ret = 0x1F; RAM[0xB800]++; break; // Mask value case 0x45: ret = 0xA6; RAM[0xB800]++; break; // RAM A high +6 case 0x46: ret = 0xB6; RAM[0xB800]++; break; // RAM B high +6 case 0x47: ret = 0x06; RAM[0xB800]++; break; // RAM A/B low +6 case 0x48: ret = 0x03; RAM[0xB800]++; break; case 0x49: ret = 0x47; RAM[0xB800]++; break; case 0x4A: ret = 0x05; RAM[0xB800]++; break; case 0x4B: ret = 0x00; RAM[0xB800]++; break; default: ret = 0x00; break; } } else{ ret = 0x01; } return ret; } /******************************************************************************/ /* PALAMEDES LED */ /******************************************************************************/ static void palamedes_led_write(UINT16 offset, UINT8 data) { tc0220ioc_wb_z80(4, (UINT8) (((data>>4)&0x03) | ((data>>0)&0x0C)) ); } /******************************************************************************/ static void LSystemAddSaveData(void) { memset(VectorData,0,4); AddSaveData(SAVE_USER_0, (UINT8 *) &VectorData, sizeof(VectorData)); AddSaveData(SAVE_USER_1, (UINT8 *) &ah_gfx_bank, sizeof(ah_gfx_bank)); AddSaveData(SAVE_USER_2, (UINT8 *) &TileBank, sizeof(TileBank)); AddSaveData(SAVE_USER_4, (UINT8 *) &Z802Bank, sizeof(Z802Bank)); AddSaveData(SAVE_USER_5, (UINT8 *) &VRAMBank, sizeof(VRAMBank)); AddSaveData(SAVE_USER_6, (UINT8 *) &lsystem_ym2203_reg, sizeof(lsystem_ym2203_reg)); AddSaveData(SAVE_USER_7, (UINT8 *) &gfx_fg0_dirty_count, sizeof(gfx_fg0_dirty_count)); AddSaveData(SAVE_USER_8, (UINT8 *) &GFX_FG0_DIRTY, sizeof(GFX_FG0_DIRTY)); AddSaveData(SAVE_USER_9, (UINT8 *) &GFX_FG0_SOLID, sizeof(GFX_FG0_SOLID)); } /******************************************************************************/ static void DrawNibble0(UINT8 *out, int plane, UINT8 c) { int count, t; count = 4; do { t = c & 1; *out = t << plane; out++; c >>= 1; } while(--count); } static void DrawNibble(UINT8 *out, int plane, UINT8 c) { int count, t; count = 4; do { t = c & 1; *out |= t << plane; out++; c >>= 1; } while(--count); } static void load_raimais(void) { int ta, tb; UINT8 *TMP; romset=0; Z80BankCount=0x40000/0x2000; Z802BankCount=0x10000/0x4000; RAMSize=0x10000+0x8000+0x10000+0x4000+0x200+0x20+0x10000+0x10000; if(!(ROM =AllocateMem(0x8000*Z80BankCount))) return; if(!(ROM2 =AllocateMem(0xC000*Z802BankCount))) return; if(!(RAM =AllocateMem(RAMSize))) return; memset(RAM, 0x00, RAMSize); RAM_FG0=RAM+0x10000; GFX_FG0=RAM+0x10000+0x8000; RAM_BG0=RAM+0x10000+0x8000+0x10000; RAM_PAL=RAM+0x10000+0x8000+0x10000+0x4000; RAM_INP=RAM+0x10000+0x8000+0x10000+0x4000+0x200; Z80ROM =RAM+0x10000+0x8000+0x10000+0x4000+0x200+0x20; RAM2 =RAM+0x10000+0x8000+0x10000+0x4000+0x200+0x20+0x10000; if(!(TMP =AllocateMem(0x40000))) return; /*-----[Sound Setup]-----*/ if(!load_rom("b36-06.bin", Z80ROM, 0x10000)) return; // Z80 SOUND ROM if(!(PCMROM=AllocateMem(0x80000))) return; if(!load_rom("b36-03.bin",PCMROM,0x80000)) return; // ADPCM A rom YM2610SetBuffers(PCMROM, PCMROM, 0x080000, 0x080000); AddTaitoYM2610(0x02BA, 0x025E, 0x10000); /*-----------------------*/ if(!load_rom("b36-08-1.bin",TMP+0x00000,0x20000)) return; // Z80 MAIN ROM if(!load_rom("b36-09.bin", TMP+0x20000,0x20000)) return; // Z80 MAIN ROM // Skip Idle Z80 // ------------- TMP[0x0121]=0xD3; // OUTA (AAh) TMP[0x0122]=0xAA; // SetStopZ80BMode2(0x0121); init_bank_rom(TMP); memcpy(RAM, TMP, 0x6000+0x2000); AddZ80BROMBase(RAM, 0x0038, 0x0066); AddZ80BReadByte(0x0000, 0x7FFF, NULL, NULL); // BANK ROM AddZ80BReadByte(0x8000, 0x87FF, NULL, RAM+0x08000); // COMMON RAM AddZ80BReadByte(0xA000, 0xBFFF, NULL, RAM+0x0A000); // WORK RAM AddZ80BReadByte(0xC000, 0xFDFF, LSystemVRAMRead, NULL); // VIDEO RAM AddZ80BReadByte(0x8800, 0x8801, tc0220ioc_rb_z80_port, NULL); // INPUT AddZ80BReadByte(0x8C00, 0x8C01, tc0140syt_read_main_z80, NULL); // SOUND COMM AddZ80BReadByte(0xFE00, 0xFE07, LSystemTileBankRead, NULL); // TILE BANK AddZ80BReadByte(0xFF00, 0xFF03, LSystemIntVecRead, NULL); // INTERRUPT AddZ80BReadByte(0xFF04, 0xFF07, LSystemVRAMBankRead, NULL); // VRAM BANK AddZ80BReadByte(0xFF08, 0xFF08, LSystemBankRead, NULL); // ROM BANK AddZ80BReadByte(0x0000, 0xFFFF, DefBadReadZ80, NULL); // <bad reads> AddZ80BReadByte(-1, -1, NULL, NULL); AddZ80BWriteByte(0x8000, 0x87FF, NULL, RAM+0x08000); // COMMON RAM AddZ80BWriteByte(0xA000, 0xBFFF, NULL, RAM+0x0A000); // WORK RAM AddZ80BWriteByte(0xC000, 0xFDFF, LSystemVRAMWrite, NULL); // VIDEO RAM AddZ80BWriteByte(0x8800, 0x8801, tc0220ioc_wb_z80_port, NULL); // INPUT * AddZ80BWriteByte(0x8C00, 0x8C01, tc0140syt_write_main_z80, NULL); // SOUND COMM AddZ80BWriteByte(0xFE00, 0xFE07, LSystemTileBankWrite, NULL); // TILE BANK * AddZ80BWriteByte(0xFF00, 0xFF03, LSystemIntVecWrite, NULL); // INTERRUPT AddZ80BWriteByte(0xFF04, 0xFF07, LSystemVRAMBankWrite, NULL); // VRAM BANK AddZ80BWriteByte(0xFF08, 0xFF08, LSystemNewBankWrite, NULL); // ROM BANK AddZ80BWriteByte(0x0000, 0xFFFF, DefBadWriteZ80, NULL); // <bad writes> AddZ80BWriteByte(-1, -1, NULL, NULL); AddZ80BReadPort(0x00, 0xFF, DefBadReadZ80, NULL); // <bad reads> AddZ80BReadPort(-1, -1, NULL, NULL); AddZ80BWritePort(0xAA, 0xAA, StopZ80BMode2, NULL); // Trap Idle Z80 AddZ80BWritePort(0x00, 0xFF, DefBadWriteZ80, NULL); // <bad reads> AddZ80BWritePort(-1, -1, NULL, NULL); AddZ80BInit(); if(!load_rom("b36-07.bin", TMP, 0x10000)) return; // Z80 SUB ROM // Skip Idle Z80 // ------------- TMP[0x0038]=0xD3; // OUTA (AAh) TMP[0x0039]=0xAA; // SetStopZ80CMode2(0x0012); init_bank_rom2(TMP); memcpy(RAM2, TMP, 0x8000+0x4000); AddZ80CROMBase(RAM2, 0x0038, 0x0066); AddZ80CReadByte(0x0000, 0xBFFF, NULL, NULL); // BANK ROM AddZ80CReadByte(0xC000, 0xDFFF, NULL, RAM2+0x0C000); // WORK RAM AddZ80CReadByte(0xE000, 0xE7FF, NULL, RAM +0x08000); // COMMON RAM AddZ80CReadByte(0x0000, 0xFFFF, DefBadReadZ80, NULL); // <bad reads> AddZ80CReadByte(-1, -1, NULL, NULL); AddZ80CWriteByte(0xC000, 0xDFFF, NULL, RAM2+0x0C000); // WORK RAM AddZ80CWriteByte(0xE000, 0xE7FF, NULL, RAM +0x08000); // COMMON RAM AddZ80CWriteByte(0x0000, 0xFFFF, DefBadWriteZ80, NULL); // <bad writes> AddZ80CWriteByte(-1, -1, NULL, NULL); AddZ80CReadPort(0x00, 0xFF, DefBadReadZ80, NULL); // <bad reads> AddZ80CReadPort(-1, -1, NULL, NULL); AddZ80CWritePort(0xAA, 0xAA, StopZ80CMode2, NULL); // Trap Idle Z80 AddZ80CWritePort(0x00, 0xFF, DefBadWriteZ80, NULL); // <bad writes> AddZ80CWritePort(-1, -1, NULL, NULL); AddZ80CInit(); FreeMem(TMP); if(!(GFX=AllocateMem(0x200000))) return; if(!(TMP=AllocateMem(0x080000))) return; tb=0; if(!load_rom("b36-01.bin", TMP, 0x80000)) return; for(ta=0;ta<0x80000;ta+=4,tb+=8){ DrawNibble0(&GFX[tb+0],0, (UINT8) (TMP[ta+0]&15) ); DrawNibble(&GFX[tb+0], 1, (UINT8) (TMP[ta+0]>>4) ); DrawNibble(&GFX[tb+0], 2, (UINT8) (TMP[ta+1]&15) ); DrawNibble(&GFX[tb+0], 3, (UINT8) (TMP[ta+1]>>4) ); DrawNibble0(&GFX[tb+4],0, (UINT8) (TMP[ta+2]&15) ); DrawNibble(&GFX[tb+4], 1, (UINT8) (TMP[ta+2]>>4) ); DrawNibble(&GFX[tb+4], 2, (UINT8) (TMP[ta+3]&15) ); DrawNibble(&GFX[tb+4], 3, (UINT8) (TMP[ta+3]>>4) ); } if(!load_rom("b36-02.bin", TMP, 0x80000)) return; for(ta=0;ta<0x80000;ta+=4,tb+=8){ DrawNibble0(&GFX[tb+0],0, (UINT8) (TMP[ta+0]&15) ); DrawNibble(&GFX[tb+0], 1, (UINT8) (TMP[ta+0]>>4) ); DrawNibble(&GFX[tb+0], 2, (UINT8) (TMP[ta+1]&15) ); DrawNibble(&GFX[tb+0], 3, (UINT8) (TMP[ta+1]>>4) ); DrawNibble0(&GFX[tb+4],0, (UINT8) (TMP[ta+2]&15) ); DrawNibble(&GFX[tb+4], 1, (UINT8) (TMP[ta+2]>>4) ); DrawNibble(&GFX[tb+4], 2, (UINT8) (TMP[ta+3]&15) ); DrawNibble(&GFX[tb+4], 3, (UINT8) (TMP[ta+3]>>4) ); } FreeMem(TMP); GFX_BG0 = GFX+0x000000; GFX_BG0_SOLID = make_solid_mask_8x8(GFX_BG0, 0x8000); spr_mask = 0x1FFF; tile_mask = 0x7FFF; lsystem_vcu_init(0); set_white_pen(127); LSystemAddSaveData(); // Init tc0220ioc emulation // ------------------------ tc0220ioc.RAM = RAM_INP; tc0220ioc.ctrl = 0; //TC0220_STOPCPU; reset_tc0220ioc(); } static void load_horshoes(void) { int ta, tb; UINT8 *TMP; romset=1; Z80BankCount=0x20000/0x2000; Z802BankCount=0x00000/0x4000; RAMSize=0x10000+0x8000+0x10000+0x4000+0x200+0x10+0x10000; if(!(ROM =AllocateMem(0x8000*Z80BankCount))) return; if(!(RAM =AllocateMem(RAMSize))) return; memset(RAM, 0x00, RAMSize); RAM_FG0=RAM+0x10000; GFX_FG0=RAM+0x10000+0x8000; RAM_BG0=RAM+0x10000+0x8000+0x10000; RAM_PAL=RAM+0x10000+0x8000+0x10000+0x4000; RAM_INP=RAM+0x10000+0x8000+0x10000+0x4000+0x200; if(!(TMP =AllocateMem(0x20000))) return; if(!load_rom("c47.03", TMP,0x20000)) return; // Z80 MAIN ROM // Skip Idle Z80 // ------------- TMP[0x0151]=0xD3; // OUTA (AAh) TMP[0x0152]=0xAA; // SetStopZ80BMode2(0x0151); init_bank_rom(TMP); memcpy(RAM, TMP, 0x6000+0x2000); AddZ80BROMBase(RAM, 0x0038, 0x0066); AddZ80BReadByte(0x0000, 0x7FFF, NULL, NULL); // BANK ROM AddZ80BReadByte(0x8000, 0x9FFF, NULL, RAM+0x08000); // WORK RAM/COMMON RAM AddZ80BReadByte(0xC000, 0xFDFF, LSystemVRAMRead, NULL); // VIDEO RAM AddZ80BReadByte(0xA000, 0xA003, lsystem_ym2203_input_dsw_rb, NULL); // YM2203; INPUT AddZ80BReadByte(0xA800, 0xA810, ReadTrackBall, NULL); // TRACKBALL INPUT AddZ80BReadByte(0xB801, 0xB801, NULL, RAM+0x0B800); // ??? AddZ80BReadByte(0xFE00, 0xFE07, LSystemTileBankRead, NULL); // TILE BANK AddZ80BReadByte(0xFF00, 0xFF03, LSystemIntVecRead, NULL); // INTERRUPT AddZ80BReadByte(0xFF04, 0xFF07, LSystemVRAMBankRead, NULL); // VRAM BANK AddZ80BReadByte(0xFF08, 0xFF08, LSystemBankRead, NULL); // ROM BANK AddZ80BReadByte(0x0000, 0xFFFF, DefBadReadZ80, NULL); // <bad reads> AddZ80BReadByte(-1, -1, NULL, NULL); AddZ80BWriteByte(0x8000, 0x9FFF, NULL, RAM+0x08000); // WORK RAM/COMMON RAM AddZ80BWriteByte(0xC000, 0xFDFF, LSystemVRAMWrite, NULL); // VIDEO RAM AddZ80BWriteByte(0xA000, 0xA003, lsystem_ym2203_wb, NULL); // YM2203; INPUT AddZ80BWriteByte(0xB802, 0xB802, LSystemTileBank2Write, NULL); // EXTRA TILE BANK AddZ80BWriteByte(0xBC00, 0xBC00, NULL, RAM+0x0BC00); // ??? AddZ80BWriteByte(0xFE00, 0xFE07, LSystemTileBankWrite, NULL); // TILE BANK AddZ80BWriteByte(0xFF00, 0xFF03, LSystemIntVecWrite, NULL); // INTERRUPT AddZ80BWriteByte(0xFF04, 0xFF07, LSystemVRAMBankWrite, NULL); // VRAM BANK AddZ80BWriteByte(0xFF08, 0xFF08, LSystemNewBankWrite, NULL); // ROM BANK AddZ80BWriteByte(0x0000, 0xFFFF, DefBadWriteZ80, NULL); // <bad writes> AddZ80BWriteByte(-1, -1, NULL, NULL); AddZ80BReadPort(0x00, 0xFF, DefBadReadZ80, NULL); // <bad reads> AddZ80BReadPort(-1, -1, NULL, NULL); AddZ80BWritePort(0xAA, 0xAA, StopZ80BMode2, NULL); // Trap Idle Z80 AddZ80BWritePort(0x00, 0xFF, DefBadWriteZ80, NULL); // <bad reads> AddZ80BWritePort(-1, -1, NULL, NULL); AddZ80BInit(); FreeMem(TMP); /*-----------------------*/ if(!(GFX=AllocateMem(0x100000))) return; if(!(TMP=AllocateMem(0x040000))) return; tb=0; if(!load_rom("c47.02", TMP+0x00000, 0x20000)) return; if(!load_rom("c47.04", TMP+0x20000, 0x20000)) return; for(ta=0;ta<0x20000;ta+=2,tb+=8){ DrawNibble0(&GFX[tb+0],0, (UINT8) (TMP[ta+0]&15) ); DrawNibble0(&GFX[tb+4],0, (UINT8) (TMP[ta+1]&15) ); DrawNibble(&GFX[tb+0], 1, (UINT8) (TMP[ta+0]>>4) ); DrawNibble(&GFX[tb+4], 1, (UINT8) (TMP[ta+1]>>4) ); DrawNibble(&GFX[tb+0], 2, (UINT8) (TMP[ta+0x20000]&15) ); DrawNibble(&GFX[tb+4], 2, (UINT8) (TMP[ta+0x20001]&15) ); DrawNibble(&GFX[tb+0], 3, (UINT8) (TMP[ta+0x20000]>>4) ); DrawNibble(&GFX[tb+4], 3, (UINT8) (TMP[ta+0x20001]>>4) ); } if(!load_rom("c47.01", TMP+0x00000, 0x20000)) return; if(!load_rom("c47.05", TMP+0x20000, 0x20000)) return; for(ta=0;ta<0x20000;ta+=2,tb+=8){ DrawNibble0(&GFX[tb+0],0, (UINT8) (TMP[ta+0]&15) ); DrawNibble0(&GFX[tb+4],0, (UINT8) (TMP[ta+1]&15) ); DrawNibble(&GFX[tb+0], 1, (UINT8) (TMP[ta+0]>>4) ); DrawNibble(&GFX[tb+4], 1, (UINT8) (TMP[ta+1]>>4) ); DrawNibble(&GFX[tb+0], 2, (UINT8) (TMP[ta+0x20000]&15) ); DrawNibble(&GFX[tb+4], 2, (UINT8) (TMP[ta+0x20001]&15) ); DrawNibble(&GFX[tb+0], 3, (UINT8) (TMP[ta+0x20000]>>4) ); DrawNibble(&GFX[tb+4], 3, (UINT8) (TMP[ta+0x20001]>>4) ); } FreeMem(TMP); GFX_BG0 = GFX+0x000000; GFX_BG0_SOLID = make_solid_mask_8x8(GFX_BG0, 0x4000); spr_mask = 0x03FF; tile_mask = 0x0FFF; lsystem_vcu_init(0); set_white_pen(240); LSystemAddSaveData(); GameMouse=1; } static void load_plotting(void) { romset=2; Z80BankCount=get_region_size(REGION_CPU1)/0x2000; Z802BankCount=0; RAMSize=0x10000+0x8000+0x10000+0x4000+0x200+0x10+0x10000; if(!(RAM =AllocateMem(RAMSize))) return; memset(RAM, 0x00, RAMSize); RAM_FG0=RAM+0x10000; GFX_FG0=RAM+0x10000+0x8000; RAM_BG0=RAM+0x10000+0x8000+0x10000; RAM_PAL=RAM+0x10000+0x8000+0x10000+0x4000; RAM_INP=RAM+0x10000+0x8000+0x10000+0x4000+0x200; if(ReadLong68k(&ROM[0])==0xC3A2C000) DecodePlotting(ROM); // Fix ROM Checksum // ---------------- if (ReadWord68k(&ROM[0x434]) == 0xc2af) { ROM[0x434]=0x00; // NOP ROM[0x435]=0x00; // NOP ROM[0x436]=0x00; // NOP // Skip Idle Z80 // ------------- ROM[0x0bb]=0xC3; ROM[0x0bc]=0x18; ROM[0x0bd]=0x00; SetStopZ80BMode2(0x0Be); } else { ROM[0x396]=0x00; // NOP ROM[0x397]=0x00; // NOP ROM[0x398]=0x00; // NOP // // Skip Idle Z80 // ------------- ROM[0x0AF]=0xC3; ROM[0x0B0]=0x18; ROM[0x0B1]=0x00; SetStopZ80BMode2(0x0B2); } ROM[0x018]=0x3A; ROM[0x019]=0x31; ROM[0x01A]=0x82; ROM[0x01B]=0xD3; // OUTA (AAh) ROM[0x01C]=0xAA; // init_bank_rom(ROM); memcpy(RAM, ROM, 0x6000+0x2000); AddZ80BROMBase(RAM, 0x0038, 0x0066); AddZ80BReadByte(0x0000, 0x7FFF, NULL, NULL); // BANK ROM AddZ80BReadByte(0x8000, 0x9FFF, NULL, RAM+0x08000); // WORK RAM/COMMON RAM AddZ80BReadByte(0xC000, 0xFDFF, LSystemVRAMRead, NULL); // VIDEO RAM AddZ80BReadByte(0xA000, 0xA003, lsystem_ym2203_input_dsw_rb, NULL); // YM2203; INPUT AddZ80BReadByte(0xFE00, 0xFE07, LSystemTileBankRead, NULL); // TILE BANK AddZ80BReadByte(0xFF00, 0xFF03, LSystemIntVecRead, NULL); // INTERRUPT AddZ80BReadByte(0xFF04, 0xFF07, LSystemVRAMBankRead, NULL); // VRAM BANK AddZ80BReadByte(0xFF08, 0xFF08, LSystemBankRead, NULL); // ROM BANK AddZ80BReadByte(0x0000, 0xFFFF, DefBadReadZ80, NULL); // <bad reads> AddZ80BReadByte(-1, -1, NULL, NULL); AddZ80BWriteByte(0x8000, 0x9FFF, NULL, RAM+0x08000); // WORK RAM/COMMON RAM AddZ80BWriteByte(0xC000, 0xFDFF, LSystemVRAMWrite, NULL); // VIDEO RAM AddZ80BWriteByte(0xA000, 0xA003, lsystem_ym2203_wb, NULL); // YM2203; INPUT AddZ80BWriteByte(0xFE00, 0xFE07, LSystemTileBankWrite, NULL); // TILE BANK AddZ80BWriteByte(0xFF00, 0xFF03, LSystemIntVecWrite, NULL); // INTERRUPT AddZ80BWriteByte(0xFF04, 0xFF07, LSystemVRAMBankWrite, NULL); // VRAM BANK AddZ80BWriteByte(0xFF08, 0xFF08, LSystemNewBankWrite, NULL); // ROM BANK AddZ80BWriteByte(0x0000, 0xFFFF, DefBadWriteZ80, NULL); // <bad writes> AddZ80BWriteByte(-1, -1, NULL, NULL); AddZ80BReadPort(0x00, 0xFF, DefBadReadZ80, NULL); // <bad reads> AddZ80BReadPort(-1, -1, NULL, NULL); AddZ80BWritePort(0xAA, 0xAA, StopZ80BMode2, NULL); // Trap Idle Z80 AddZ80BWritePort(0x00, 0xFF, DefBadWriteZ80, NULL); // <bad reads> AddZ80BWritePort(-1, -1, NULL, NULL); AddZ80BInit(); /*-----------------------*/ spr_mask = 0x03FF; tile_mask = 0x0FFF; lsystem_vcu_init(0); LSystemAddSaveData(); } static void load_champwr(void) { romset=3; RAMSize=0x10000+0x8000+0x10000+0x4000+0x200+0x20+0x10000+0x10000; if(!(RAM =AllocateMem(RAMSize))) return; memset(RAM, 0x00, RAMSize); RAM_FG0=RAM+0x10000; GFX_FG0=RAM+0x10000+0x8000; RAM_BG0=RAM+0x10000+0x8000+0x10000; RAM_PAL=RAM+0x10000+0x8000+0x10000+0x4000; RAM_INP=RAM+0x10000+0x8000+0x10000+0x4000+0x200; RAM2 =RAM+0x10000+0x8000+0x10000+0x4000+0x200+0x20+0x10000; /*-----[Sound Setup]-----*/ AddTaitoYM2203(0x02CE, 0x025A, 0x10000, NULL, 0x00000); /*-----------------------*/ // Skip Idle Z80 // ------------- // if (is_current_game("champwr")) { ROM[0x0791]=0x00; // ROM[0x0792]=0x00; // ROM[0x01CD]=0xD3; // OUTA (AAh) ROM[0x01CE]=0xAA; // SetStopZ80BMode2(0x01CA); // } z80_init_banks(1,REGION_ROM1,0x6000,0x2000); // memcpy(RAM,ROM,0x10000); AddZ80BROMBase(ROM, 0x0038, 0x0066); AddZ80BReadByte(0x0000, 0x7FFF, NULL, NULL); // BANK ROM AddZ80BReadByte(0x8000, 0xBFFF, NULL, RAM+0x08000); // WORK RAM/COMMON RAM AddZ80BReadByte(0xC000, 0xFDFF, LSystemVRAMRead, NULL); // VIDEO RAM AddZ80BReadByte(0xFE00, 0xFE07, LSystemTileBankRead, NULL); // TILE BANK AddZ80BReadByte(0xFF00, 0xFF03, LSystemIntVecRead, NULL); // INTERRUPT AddZ80BReadByte(0xFF04, 0xFF07, LSystemVRAMBankRead, NULL); // VRAM BANK AddZ80BReadByte(0xFF08, 0xFF08, LSystemBankRead, NULL); // ROM BANK AddZ80BReadByte(0x0000, 0xFFFF, DefBadReadZ80, NULL); // <bad reads> AddZ80BReadByte(-1, -1, NULL, NULL); AddZ80BWriteByte(0x8000, 0xBFFF, NULL, RAM+0x08000); // WORK RAM/COMMON RAM AddZ80BWriteByte(0xC000, 0xFDFF, LSystemVRAMWrite, NULL); // VIDEO RAM AddZ80BWriteByte(0xFE00, 0xFE07, LSystemTileBankWrite, NULL); // TILE BANK AddZ80BWriteByte(0xFF00, 0xFF03, LSystemIntVecWrite, NULL); // INTERRUPT AddZ80BWriteByte(0xFF04, 0xFF07, LSystemVRAMBankWrite, NULL); // VRAM BANK AddZ80BWriteByte(0xFF08, 0xFF08, LSystemNewBankWrite, NULL); // ROM BANK AddZ80BWriteByte(0x0000, 0xFFFF, DefBadWriteZ80, NULL); // <bad writes> AddZ80BWriteByte(-1, -1, NULL, NULL); AddZ80BReadPort(0x00, 0xFF, DefBadReadZ80, NULL); // <bad reads> AddZ80BReadPort(-1, -1, NULL, NULL); AddZ80BWritePort(0xAA, 0xAA, StopZ80BMode2, NULL); // Trap Idle Z80 AddZ80BWritePort(0x00, 0xFF, DefBadWriteZ80, NULL); // <bad writes> AddZ80BWritePort(-1, -1, NULL, NULL); AddZ80BInit(); // Skip Idle Z80 // ------------- ROM = load_region[REGION_CPU3]; ROM[0x037A]=0x00; // ROM[0x037B]=0x00; // ROM[0x037F]=0x18; // ROM[0x010D]=0xD3; // OUTA (AAh) ROM[0x010E]=0xAA; // SetStopZ80CMode2(0x010D); z80_init_banks(2,REGION_ROM3,0x8000,0x4000); memcpy(RAM2, ROM, 0x8000+0x4000); AddZ80CROMBase(RAM2, 0x0038, 0x0066); AddZ80CReadByte(0x0000, 0xBFFF, NULL, NULL); // BANK ROM AddZ80CReadByte(0xD000, 0xDFFF, NULL, RAM2+0x0D000); // WORK RAM AddZ80CReadByte(0xC000, 0xCFFF, NULL, RAM +0x0A000); // COMMON RAM AddZ80CReadByte(0xE000, 0xE007, tc0220ioc_rb_z80, NULL); // INPUT AddZ80CReadByte(0xE008, 0xE00F, NULL, RAM +0x0E008); // PROTECTION? AddZ80CReadByte(0xE800, 0xE801, tc0140syt_read_main_z80, NULL); // SOUND COMM AddZ80CReadByte(0xF000, 0xF000, LSystemSubCpuBankRead, NULL); // ROM BANK AddZ80CReadByte(0x0000, 0xFFFF, DefBadReadZ80, NULL); // <bad reads> AddZ80CReadByte(-1, -1, NULL, NULL); AddZ80CWriteByte(0xD000, 0xDFFF, NULL, RAM2+0x0D000); // WORK RAM AddZ80CWriteByte(0xC000, 0xCFFF, NULL, RAM +0x0A000); // COMMON RAM AddZ80CWriteByte(0xE000, 0xE007, tc0220ioc_wb_z80, NULL); // VSYNC AddZ80CWriteByte(0xE800, 0xE801, tc0140syt_write_main_z80, NULL); // SOUND COMM AddZ80CWriteByte(0xF000, 0xF000, LSystemSubCpuNewBankWrite, NULL); // ROM BANK AddZ80CWriteByte(0x0000, 0xFFFF, DefBadWriteZ80, NULL); // <bad writes> AddZ80CWriteByte(-1, -1, NULL, NULL); AddZ80CReadPort(0x00, 0xFF, DefBadReadZ80, NULL); // <bad reads> AddZ80CReadPort(-1, -1, NULL, NULL); AddZ80CWritePort(0xAA, 0xAA, StopZ80CMode2, NULL); // Trap Idle Z80 AddZ80CWritePort(0x00, 0xFF, DefBadWriteZ80, NULL); // <bad writes> AddZ80CWritePort(-1, -1, NULL, NULL); AddZ80CInit(); spr_mask = 0x3FFF; tile_mask = 0xFFFF; lsystem_vcu_init(1); LSystemAddSaveData(); // Init tc0220ioc emulation // ------------------------ tc0220ioc.RAM = RAM_INP; tc0220ioc.ctrl = 0; //TC0220_STOPCPU; reset_tc0220ioc(); } static void load_fhawk(void) { int ta, tb; UINT8 *TMP; romset=4; Z80BankCount=0xA0000/0x2000; Z802BankCount=0x20000/0x4000; RAMSize=0x10000+0x8000+0x10000+0x4000+0x200+0x20+0x10000+0x10000; if(!(ROM =AllocateMem(0x8000*Z80BankCount))) return; if(!(ROM2 =AllocateMem(0xC000*Z802BankCount))) return; if(!(RAM=AllocateMem(RAMSize))) return; memset(RAM, 0x00, RAMSize); RAM_FG0=RAM+0x10000; GFX_FG0=RAM+0x10000+0x8000; RAM_BG0=RAM+0x10000+0x8000+0x10000; RAM_PAL=RAM+0x10000+0x8000+0x10000+0x4000; RAM_INP=RAM+0x10000+0x8000+0x10000+0x4000+0x200; Z80ROM =RAM+0x10000+0x8000+0x10000+0x4000+0x200+0x20; RAM2 =RAM+0x10000+0x8000+0x10000+0x4000+0x200+0x20+0x10000; /*-----[Sound Setup]-----*/ if(!load_rom("b70-09.bin", Z80ROM, 0x10000)) return; // Z80 SOUND ROM AddTaitoYM2203_B(0x02C3, 0x0254, 0x10000, NULL, 0x00000); /*-----------------------*/ if(!(TMP =AllocateMem(0xA0000))) return; if(!load_rom("b70-07.bin",TMP+0x00000,0x20000)) return; // Z80 MAIN ROM if(!load_rom("b70-03.bin",TMP+0x20000,0x80000)) return; // DATA ROM // Skip Idle Z80 // ------------- TMP[0x010D]=0xD3; // OUTA (AAh) TMP[0x010E]=0xAA; // SetStopZ80BMode2(0x010D); init_bank_rom(TMP); memcpy(RAM, TMP, 0x6000+0x2000); AddZ80BROMBase(RAM, 0x0038, 0x0066); AddZ80BReadByte(0x0000, 0x7FFF, NULL, NULL); // Z80 ROM AddZ80BReadByte(0x8000, 0xBFFF, NULL, RAM+0x08000); // COMMUNICATE RAM/WORK RAM AddZ80BReadByte(0xC000, 0xFDFF, LSystemVRAMRead, NULL); // VIDEO RAM AddZ80BReadByte(0xFE00, 0xFE07, LSystemTileBankRead, NULL); // TILE BANK AddZ80BReadByte(0xFF00, 0xFF03, LSystemIntVecRead, NULL); // INTERRUPT AddZ80BReadByte(0xFF04, 0xFF07, LSystemVRAMBankRead, NULL); // VRAM BANK AddZ80BReadByte(0xFF08, 0xFF08, LSystemBankRead, NULL); // ROM BANK AddZ80BReadByte(0x0000, 0xFFFF, DefBadReadZ80, NULL); // <bad reads> AddZ80BReadByte(-1, -1, NULL, NULL); AddZ80BWriteByte(0x8000, 0xBFFF, NULL, RAM+0x08000); // COMMUNICATE RAM/WORK RAM AddZ80BWriteByte(0xC000, 0xFDFF, LSystemVRAMWrite, NULL); // VIDEO RAM AddZ80BWriteByte(0xFE00, 0xFE07, LSystemTileBankWrite, NULL); // TILE BANK AddZ80BWriteByte(0xFF00, 0xFF03, LSystemIntVecWrite, NULL); // INTERRUPT AddZ80BWriteByte(0xFF04, 0xFF07, LSystemVRAMBankWrite, NULL); // VRAM BANK AddZ80BWriteByte(0xFF08, 0xFF08, LSystemNewBankWrite, NULL); // ROM BANK AddZ80BWriteByte(0x0000, 0xFFFF, DefBadWriteZ80, NULL); // <bad writes> AddZ80BWriteByte(-1, -1, NULL, NULL); AddZ80BReadPort(0x00, 0xFF, DefBadReadZ80, NULL); // <bad reads> AddZ80BReadPort(-1, -1, NULL, NULL); AddZ80BWritePort(0xAA, 0xAA, StopZ80BMode2, NULL); // Trap Idle Z80 AddZ80BWritePort(0x00, 0xFF, DefBadWriteZ80, NULL); // <bad reads> AddZ80BWritePort(-1, -1, NULL, NULL); AddZ80BInit(); if(!load_rom("b70-08.bin", TMP, 0x20000)) return; // Z80 SUB ROM // Skip Idle Z80 // ------------- TMP[0x003E]=0x00; // nop TMP[0x003F]=0x00; // nop TMP[0x0025]=0xD3; // OUTA (AAh) TMP[0x0026]=0xAA; // SetStopZ80CMode2(0x0025); init_bank_rom2(TMP); memcpy(RAM2, TMP, 0x8000+0x4000); AddZ80CROMBase(RAM2, 0x0038, 0x0066); AddZ80CReadByte(0x0000, 0xBFFF, NULL, NULL); // BANK ROM AddZ80CReadByte(0xE000, 0xFFFF, NULL, RAM +0x08000); // COMMON RAM AddZ80CReadByte(0xC800, 0xC801, tc0140syt_read_main_z80, NULL); // SOUND COMM AddZ80CReadByte(0xD000, 0xD007, tc0220ioc_rb_z80, NULL); // INPUT AddZ80CReadByte(0xC000, 0xC000, LSystemSubCpuBankRead, NULL); // ROM BANK AddZ80CReadByte(0x0000, 0xFFFF, DefBadReadZ80, NULL); // <bad reads> AddZ80CReadByte(-1, -1, NULL, NULL); AddZ80CWriteByte(0xE000, 0xFFFF, NULL, RAM +0x08000); // COMMON RAM AddZ80CWriteByte(0xC800, 0xC801, tc0140syt_write_main_z80, NULL); // SOUND COMM AddZ80CWriteByte(0xD000, 0xD007, tc0220ioc_wb_z80, NULL); // INPUT AddZ80CWriteByte(0xC000, 0xC000, LSystemSubCpuNewBankWrite, NULL); // ROM BANK AddZ80CWriteByte(0x0000, 0xFFFF, DefBadWriteZ80, NULL); // <bad writes> AddZ80CWriteByte(-1, -1, NULL, NULL); AddZ80CReadPort(0x00, 0xFF, DefBadReadZ80, NULL); // <bad reads> AddZ80CReadPort(-1, -1, NULL, NULL); AddZ80CWritePort(0xAA, 0xAA, StopZ80CMode2, NULL); // Trap Idle Z80 AddZ80CWritePort(0x00, 0xFF, DefBadWriteZ80, NULL); // <bad writes> AddZ80CWritePort(-1, -1, NULL, NULL); AddZ80CInit(); FreeMem(TMP); if(!(GFX=AllocateMem(0x200000))) return; if(!(TMP=AllocateMem(0x080000))) return; tb=0; if(!load_rom("b70-01.bin", TMP, 0x80000)) return; for(ta=0;ta<0x80000;ta+=4,tb+=8){ DrawNibble0(&GFX[tb+0],0, (UINT8) (TMP[ta+0]&15) ); DrawNibble(&GFX[tb+0], 1, (UINT8) (TMP[ta+0]>>4) ); DrawNibble(&GFX[tb+0], 2, (UINT8) (TMP[ta+1]&15) ); DrawNibble(&GFX[tb+0], 3, (UINT8) (TMP[ta+1]>>4) ); DrawNibble0(&GFX[tb+4],0, (UINT8) (TMP[ta+2]&15) ); DrawNibble(&GFX[tb+4], 1, (UINT8) (TMP[ta+2]>>4) ); DrawNibble(&GFX[tb+4], 2, (UINT8) (TMP[ta+3]&15) ); DrawNibble(&GFX[tb+4], 3, (UINT8) (TMP[ta+3]>>4) ); } if(!load_rom("b70-02.bin", TMP, 0x80000)) return; for(ta=0;ta<0x80000;ta+=4,tb+=8){ DrawNibble0(&GFX[tb+0],0, (UINT8) (TMP[ta+0]&15) ); DrawNibble(&GFX[tb+0], 1, (UINT8) (TMP[ta+0]>>4) ); DrawNibble(&GFX[tb+0], 2, (UINT8) (TMP[ta+1]&15) ); DrawNibble(&GFX[tb+0], 3, (UINT8) (TMP[ta+1]>>4) ); DrawNibble0(&GFX[tb+4],0, (UINT8) (TMP[ta+2]&15) ); DrawNibble(&GFX[tb+4], 1, (UINT8) (TMP[ta+2]>>4) ); DrawNibble(&GFX[tb+4], 2, (UINT8) (TMP[ta+3]&15) ); DrawNibble(&GFX[tb+4], 3, (UINT8) (TMP[ta+3]>>4) ); } FreeMem(TMP); GFX_BG0 = GFX+0x000000; GFX_BG0_SOLID = make_solid_mask_8x8(GFX_BG0, 0x8000); spr_mask = 0x1FFF; tile_mask = 0x7FFF; lsystem_vcu_init(0); LSystemAddSaveData(); // Init tc0220ioc emulation // ------------------------ tc0220ioc.RAM = RAM_INP; tc0220ioc.ctrl = 0; //TC0220_STOPCPU; reset_tc0220ioc(); } // read/write region from/to bank 0xf ! static int read_kurikint_region() { return read_z80_bank(1,0xf,0x7fff); } static void write_kurikint_region(int data) { write_z80_bank(1,0xf,0x7fff,data); } static void load_kurikint() { int ta, tb,romset_2; UINT8 *TMP; read_region_byte = &read_kurikint_region; write_region_byte = &write_kurikint_region; if (is_current_game("kurikina")) romset_2 = 0; else if (is_current_game("kurikint")) romset_2 = 1; else if (is_current_game("kurikinj")) romset_2 = 2; romset=5; Z80BankCount=0x40000/0x2000; Z802BankCount=0x10000/0x4000; RAMSize=0x10000+0x8000+0x10000+0x4000+0x200+0x20+0x10000+0x10000; if(!(ROM =AllocateMem(0x8000*Z80BankCount))) return; if(!(ROM2 =AllocateMem(0xC000*Z802BankCount))) return; if(!(RAM=AllocateMem(RAMSize))) return; memset(RAM, 0x00, RAMSize); RAM_FG0=RAM+0x10000; GFX_FG0=RAM+0x10000+0x8000; RAM_BG0=RAM+0x10000+0x8000+0x10000; RAM_PAL=RAM+0x10000+0x8000+0x10000+0x4000; RAM_INP=RAM+0x10000+0x8000+0x10000+0x4000+0x200; Z80ROM =RAM+0x10000+0x8000+0x10000+0x4000+0x200+0x20; RAM2 =RAM+0x10000+0x8000+0x10000+0x4000+0x200+0x20+0x10000; if(!(TMP =AllocateMem(0x40000))) return; if(!load_rom_index(0, TMP+0x00000, 0x20000)) return; // Z80 MAIN ROM if(!load_rom_index(2, TMP+0x20000, 0x20000)) return; // DATA ROM // Skip Idle Z80 // ------------- if(romset_2 == 0){ TMP[0x0241]=0xD3; // OUTA (AAh) TMP[0x0242]=0xAA; // SetStopZ80BMode2(0x023E); } else{ TMP[0x0290]=0xD3; // OUTA (AAh) TMP[0x0291]=0xAA; // SetStopZ80BMode2(0x028D); } init_bank_rom(TMP); memcpy(RAM, TMP, 0x6000+0x2000); AddZ80BROMBase(RAM, 0x0038, 0x0066); AddZ80BReadByte(0x0000, 0x7FFF, NULL, NULL); // Z80 ROM AddZ80BReadByte(0x8000, 0xA7FF, NULL, RAM+0x08000); // COMMUNICATE RAM/WORK RAM AddZ80BReadByte(0xC000, 0xFDFF, LSystemVRAMRead, NULL); // VIDEO RAM AddZ80BReadByte(0xA800, 0xA801, tc0220ioc_rb_z80_port, NULL); // INPUT AddZ80BReadByte(0xFE00, 0xFE07, LSystemTileBankRead, NULL); // TILE BANK AddZ80BReadByte(0xFF00, 0xFF03, LSystemIntVecRead, NULL); // INTERRUPT AddZ80BReadByte(0xFF04, 0xFF07, LSystemVRAMBankRead, NULL); // VRAM BANK AddZ80BReadByte(0xFF08, 0xFF08, LSystemBankRead, NULL); // ROM BANK AddZ80BReadByte(0x0000, 0xFFFF, DefBadReadZ80, NULL); // <bad reads> AddZ80BReadByte(-1, -1, NULL, NULL); AddZ80BWriteByte(0x8000, 0xA7FF, NULL, RAM+0x08000); // COMMUNICATE RAM/WORK RAM AddZ80BWriteByte(0xC000, 0xFDFF, LSystemVRAMWrite, NULL); // VIDEO RAM AddZ80BWriteByte(0xA800, 0xA801, tc0220ioc_wb_z80_port, NULL); // INPUT AddZ80BWriteByte(0xFE00, 0xFE07, LSystemTileBankWrite, NULL); // TILE BANK AddZ80BWriteByte(0xFF00, 0xFF03, LSystemIntVecWrite, NULL); // INTERRUPT AddZ80BWriteByte(0xFF04, 0xFF07, LSystemVRAMBankWrite, NULL); // VRAM BANK AddZ80BWriteByte(0xFF08, 0xFF08, LSystemNewBankWrite, NULL); // ROM BANK AddZ80BWriteByte(0x0000, 0xFFFF, DefBadWriteZ80, NULL); // <bad writes> AddZ80BWriteByte(-1, -1, NULL, NULL); AddZ80BReadPort(0x00, 0xFF, DefBadReadZ80, NULL); // <bad reads> AddZ80BReadPort(-1, -1, NULL, NULL); AddZ80BWritePort(0xAA, 0xAA, StopZ80BMode2, NULL); // Trap Idle Z80 AddZ80BWritePort(0x00, 0xFF, DefBadWriteZ80, NULL); // <bad reads> AddZ80BWritePort(-1, -1, NULL, NULL); AddZ80BInit(); if(!load_rom_index(1, TMP, 0x10000)) return; // Z80 SUB ROM // Skip Idle Z80 // ------------- TMP[0x011E]=0xD3; // OUTA (AAh) TMP[0x011F]=0xAA; // SetStopZ80CMode2(0x011B); init_bank_rom2(TMP); memcpy(RAM2, TMP, 0x8000+0x4000); AddZ80CROMBase(RAM2, 0x0038, 0x0066); AddZ80CReadByte(0x0000, 0xBFFF, NULL, NULL); // BANK ROM AddZ80CReadByte(0xC000, 0xDFFF, NULL, RAM2+0x0C000); // WORK RAM AddZ80CReadByte(0xE000, 0xE7FF, NULL, RAM +0x0A000); // COMMON RAM AddZ80CReadByte(0xE800, 0xE801, lsystem_ym2203_rb, NULL); // YM2203 AddZ80CReadByte(0xF000, 0xF000, LSystemSubCpuBankRead, NULL); // ROM BANK AddZ80CReadByte(0x0000, 0xFFFF, DefBadReadZ80, NULL); // <bad reads> AddZ80CReadByte(-1, -1, NULL, NULL); AddZ80CWriteByte(0xC000, 0xDFFF, NULL, RAM2+0x0C000); // WORK RAM AddZ80CWriteByte(0xE000, 0xE7FF, NULL, RAM +0x0A000); // COMMON RAM AddZ80CWriteByte(0xE800, 0xE801, lsystem_ym2203_wb, NULL); // YM2203 AddZ80CWriteByte(0xF000, 0xF000, LSystemSubCpuNewBankWrite, NULL); // ROM BANK AddZ80CWriteByte(0x0000, 0xFFFF, DefBadWriteZ80, NULL); // <bad writes> AddZ80CWriteByte(-1, -1, NULL, NULL); AddZ80CReadPort(0x00, 0xFF, DefBadReadZ80, NULL); // <bad reads> AddZ80CReadPort(-1, -1, NULL, NULL); AddZ80CWritePort(0xAA, 0xAA, StopZ80CMode2, NULL); // Trap Idle Z80 AddZ80CWritePort(0x00, 0xFF, DefBadWriteZ80, NULL); // <bad writes> AddZ80CWritePort(-1, -1, NULL, NULL); AddZ80CInit(); FreeMem(TMP); /*-----------------------*/ if(!(GFX=AllocateMem(0x200000))) return; if(!(TMP=AllocateMem(0x080000))) return; if (!strcmp(current_game->main_name,"kurikina")) { tb=0; if(!load_rom_index(3, TMP+0x00000, 0x20000)) return; if(!load_rom_index(4, TMP+0x20000, 0x20000)) return; if(!load_rom_index(5, TMP+0x40000, 0x20000)) return; if(!load_rom_index(6, TMP+0x60000, 0x20000)) return; for(ta=0;ta<0x40000;ta+=2,tb+=8){ DrawNibble0(&GFX[tb+0],0, (UINT8) (TMP[ta+0]&15) ); DrawNibble0(&GFX[tb+4],0, (UINT8) (TMP[ta+1]&15) ); DrawNibble(&GFX[tb+0], 1, (UINT8) (TMP[ta+0]>>4) ); DrawNibble(&GFX[tb+4], 1, (UINT8) (TMP[ta+1]>>4) ); DrawNibble(&GFX[tb+0], 2, (UINT8) (TMP[ta+0x40000]&15) ); DrawNibble(&GFX[tb+4], 2, (UINT8) (TMP[ta+0x40001]&15) ); DrawNibble(&GFX[tb+0], 3, (UINT8) (TMP[ta+0x40000]>>4) ); DrawNibble(&GFX[tb+4], 3, (UINT8) (TMP[ta+0x40001]>>4) ); } if(!load_rom_index( 7, TMP+0x00000, 0x20000)) return; if(!load_rom_index( 9, TMP+0x20000, 0x20000)) return; if(!load_rom_index( 8, TMP+0x40000, 0x20000)) return; if(!load_rom_index(10, TMP+0x60000, 0x20000)) return; for(ta=0;ta<0x40000;ta+=2,tb+=8){ DrawNibble0(&GFX[tb+0],0, (UINT8) (TMP[ta+0]&15) ); DrawNibble0(&GFX[tb+4],0, (UINT8) (TMP[ta+1]&15) ); DrawNibble(&GFX[tb+0], 1, (UINT8) (TMP[ta+0]>>4) ); DrawNibble(&GFX[tb+4], 1, (UINT8) (TMP[ta+1]>>4) ); DrawNibble(&GFX[tb+0], 2, (UINT8) (TMP[ta+0x40000]&15) ); DrawNibble(&GFX[tb+4], 2, (UINT8) (TMP[ta+0x40001]&15) ); DrawNibble(&GFX[tb+0], 3, (UINT8) (TMP[ta+0x40000]>>4) ); DrawNibble(&GFX[tb+4], 3, (UINT8) (TMP[ta+0x40001]>>4) ); } } else { tb=0; if(!load_rom_index(3, TMP, 0x80000)) return; for(ta=0;ta<0x80000;ta+=4,tb+=8){ DrawNibble0(&GFX[tb+0],0, (UINT8) (TMP[ta+0]&15) ); DrawNibble(&GFX[tb+0], 1, (UINT8) (TMP[ta+0]>>4) ); DrawNibble(&GFX[tb+0], 2, (UINT8) (TMP[ta+1]&15) ); DrawNibble(&GFX[tb+0], 3, (UINT8) (TMP[ta+1]>>4) ); DrawNibble0(&GFX[tb+4],0, (UINT8) (TMP[ta+2]&15) ); DrawNibble(&GFX[tb+4], 1, (UINT8) (TMP[ta+2]>>4) ); DrawNibble(&GFX[tb+4], 2, (UINT8) (TMP[ta+3]&15) ); DrawNibble(&GFX[tb+4], 3, (UINT8) (TMP[ta+3]>>4) ); } if(!load_rom_index(4, TMP, 0x80000)) return; for(ta=0;ta<0x80000;ta+=4,tb+=8){ DrawNibble0(&GFX[tb+0],0, (UINT8) (TMP[ta+0]&15) ); DrawNibble(&GFX[tb+0], 1, (UINT8) (TMP[ta+0]>>4) ); DrawNibble(&GFX[tb+0], 2, (UINT8) (TMP[ta+1]&15) ); DrawNibble(&GFX[tb+0], 3, (UINT8) (TMP[ta+1]>>4) ); DrawNibble0(&GFX[tb+4],0, (UINT8) (TMP[ta+2]&15) ); DrawNibble(&GFX[tb+4], 1, (UINT8) (TMP[ta+2]>>4) ); DrawNibble(&GFX[tb+4], 2, (UINT8) (TMP[ta+3]&15) ); DrawNibble(&GFX[tb+4], 3, (UINT8) (TMP[ta+3]>>4) ); } } FreeMem(TMP); GFX_BG0 = GFX+0x000000; GFX_BG0_SOLID = make_solid_mask_8x8(GFX_BG0, 0x8000); spr_mask = 0x1FFF; tile_mask = 0x7FFF; lsystem_vcu_init(1); LSystemAddSaveData(); // Init tc0220ioc emulation // ------------------------ tc0220ioc.RAM = RAM_INP; tc0220ioc.ctrl = 0; //TC0220_STOPCPU; reset_tc0220ioc(); } static void load_puzznic(void) { int ta, tb; UINT8 *TMP; romset=6; Z80BankCount=0x20000/0x2000; Z802BankCount=0x00000/0x4000; RAMSize=0x10000+0x8000+0x10000+0x4000+0x200+0x10+0x10000; if(!(ROM =AllocateMem(0x8000*Z80BankCount))) return; if(!(RAM =AllocateMem(RAMSize))) return; memset(RAM, 0x00, RAMSize); RAM_FG0=RAM+0x10000; GFX_FG0=RAM+0x10000+0x8000; RAM_BG0=RAM+0x10000+0x8000+0x10000; RAM_PAL=RAM+0x10000+0x8000+0x10000+0x4000; RAM_INP=RAM+0x10000+0x8000+0x10000+0x4000+0x200; if(!(TMP =AllocateMem(0x20000))) return; if(!load_rom("u11.rom",TMP,0x20000)) return; // Z80 MAIN ROM TMP[0x0706]=0xC9; // RET TMP[0x01B1]=0xD3; // OUTA (AAh) TMP[0x01B2]=0xAA; // SetStopZ80BMode2(0x01B1); init_bank_rom(TMP); memcpy(RAM, TMP, 0x6000+0x2000); AddZ80BROMBase(RAM, 0x0038, 0x0066); AddZ80BReadByte(0x0000, 0x7FFF, NULL, NULL); // BANK ROM AddZ80BReadByte(0x8000, 0x9FFF, NULL, RAM+0x08000); // WORK RAM AddZ80BReadByte(0xC000, 0xFDFF, LSystemVRAMRead, NULL); // VIDEO RAM AddZ80BReadByte(0xA000, 0xA003, lsystem_ym2203_input_dsw_rb, NULL); // YM2203; INPUT AddZ80BReadByte(0xB800, 0xB801, PuzznicMCURead, NULL); // MCU AddZ80BReadByte(0xA000, 0xBFFF, NULL, RAM+0x0A000); // HACK RAM AddZ80BReadByte(0xFE00, 0xFE07, LSystemTileBankRead, NULL); // TILE BANK AddZ80BReadByte(0xFF00, 0xFF03, LSystemIntVecRead, NULL); // INTERRUPT AddZ80BReadByte(0xFF04, 0xFF07, LSystemVRAMBankRead, NULL); // VRAM BANK AddZ80BReadByte(0xFF08, 0xFF08, LSystemBankRead, NULL); // ROM BANK AddZ80BReadByte(0x0000, 0xFFFF, DefBadReadZ80, NULL); // <bad reads> AddZ80BReadByte(-1, -1, NULL, NULL); AddZ80BWriteByte(0x8000, 0x9FFF, NULL, RAM+0x08000); // WORK RAM AddZ80BWriteByte(0xC000, 0xFDFF, LSystemVRAMWrite, NULL); // VIDEO RAM AddZ80BWriteByte(0xA000, 0xA003, lsystem_ym2203_wb, NULL); // YM2203; INPUT AddZ80BWriteByte(0xB800, 0xB801, PuzznicMCUWrite, NULL); // MCU AddZ80BWriteByte(0xA000, 0xBFFF, NULL, RAM+0x0A000); // HACK RAM AddZ80BWriteByte(0xFE00, 0xFE07, LSystemTileBankWrite, NULL); // TILE BANK AddZ80BWriteByte(0xFF00, 0xFF03, LSystemIntVecWrite, NULL); // INTERRUPT AddZ80BWriteByte(0xFF04, 0xFF07, LSystemVRAMBankWrite, NULL); // VRAM BANK AddZ80BWriteByte(0xFF08, 0xFF08, LSystemNewBankWrite, NULL); // ROM BANK AddZ80BWriteByte(0x0000, 0xFFFF, DefBadWriteZ80, NULL); // <bad writes> AddZ80BWriteByte(-1, -1, NULL, NULL); AddZ80BReadPort(0x00, 0xFF, DefBadReadZ80, NULL); // <bad reads> AddZ80BReadPort(-1, -1, NULL, NULL); AddZ80BWritePort(0xAA, 0xAA, StopZ80BMode2, NULL); // Trap Idle Z80 AddZ80BWritePort(0x00, 0xFF, DefBadWriteZ80, NULL); // <bad reads> AddZ80BWritePort(-1, -1, NULL, NULL); AddZ80BInit(); FreeMem(TMP); /*-----------------------*/ if(!(GFX=AllocateMem(0x080000))) return; if(!(TMP=AllocateMem(0x040000))) return; if(!load_rom("u10.rom", TMP+0x00000, 0x20000)) return; if(!load_rom("u09.rom", TMP+0x20000, 0x20000)) return; tb=0; for(ta=0;ta<0x20000;ta+=2,tb+=8){ DrawNibble0(&GFX[tb+0],0, (UINT8) (TMP[ta+0]&15) ); DrawNibble0(&GFX[tb+4],0, (UINT8) (TMP[ta+1]&15) ); DrawNibble(&GFX[tb+0], 1, (UINT8) (TMP[ta+0]>>4) ); DrawNibble(&GFX[tb+4], 1, (UINT8) (TMP[ta+1]>>4) ); DrawNibble(&GFX[tb+0], 2, (UINT8) (TMP[ta+0x20000]&15) ); DrawNibble(&GFX[tb+4], 2, (UINT8) (TMP[ta+0x20001]&15) ); DrawNibble(&GFX[tb+0], 3, (UINT8) (TMP[ta+0x20000]>>4) ); DrawNibble(&GFX[tb+4], 3, (UINT8) (TMP[ta+0x20001]>>4) ); } FreeMem(TMP); GFX_BG0 = GFX+0x000000; GFX_BG0_SOLID = make_solid_mask_8x8(GFX_BG0, 0x2000); spr_mask = 0x07FF; tile_mask = 0x1FFF; lsystem_vcu_init(1); LSystemAddSaveData(); } static void load_plgirls(void) { int ta, tb; UINT8 *TMP; romset=7; Z80BankCount=0x40000/0x2000; Z802BankCount=0x00000/0x4000; RAMSize=0x10000+0x8000+0x10000+0x4000+0x200+0x10+0x10000; if(!(ROM =AllocateMem(0x8000*Z80BankCount))) return; if(!(RAM =AllocateMem(RAMSize))) return; memset(RAM, 0x00, RAMSize); RAM_FG0=RAM+0x10000; GFX_FG0=RAM+0x10000+0x8000; RAM_BG0=RAM+0x10000+0x8000+0x10000; RAM_PAL=RAM+0x10000+0x8000+0x10000+0x4000; RAM_INP=RAM+0x10000+0x8000+0x10000+0x4000+0x200; if(!(TMP =AllocateMem(0x40000))) return; if(!load_rom("pg03.ic6",TMP,0x40000)) return; // Z80 MAIN ROM // TMP[0x0706]=0xC9; // RET // TMP[0x01B1]=0xD3; // OUTA (AAh) // TMP[0x01B2]=0xAA; // // SetStopZ80BMode2(0x01B1); init_bank_rom(TMP); memcpy(RAM, TMP, 0x6000+0x2000); AddZ80BROMBase(RAM, 0x0038, 0x0066); AddZ80BReadByte(0x0000, 0x7FFF, NULL, NULL); // BANK ROM AddZ80BReadByte(0x8000, 0x9FFF, NULL, RAM+0x08000); // WORK RAM AddZ80BReadByte(0xC000, 0xFDFF, LSystemVRAMRead, NULL); // VIDEO RAM AddZ80BReadByte(0xA000, 0xA003, lsystem_ym2203_dsw_rb, NULL); // YM2203; INPUT AddZ80BReadByte(0xA000, 0xBFFF, NULL, RAM+0x0A000); // HACK RAM AddZ80BReadByte(0xFE00, 0xFE07, LSystemTileBankRead, NULL); // TILE BANK AddZ80BReadByte(0xFF00, 0xFF03, LSystemIntVecRead, NULL); // INTERRUPT AddZ80BReadByte(0xFF04, 0xFF07, LSystemVRAMBankRead, NULL); // VRAM BANK AddZ80BReadByte(0xFF08, 0xFF08, LSystemBankRead, NULL); // ROM BANK AddZ80BReadByte(0x0000, 0xFFFF, DefBadReadZ80, NULL); // <bad reads> AddZ80BReadByte(-1, -1, NULL, NULL); AddZ80BWriteByte(0x8000, 0x9FFF, NULL, RAM+0x08000); // WORK RAM AddZ80BWriteByte(0xC000, 0xFDFF, LSystemVRAMWrite, NULL); // VIDEO RAM AddZ80BWriteByte(0xA000, 0xA003, lsystem_ym2203_wb, NULL); // YM2203; INPUT AddZ80BWriteByte(0xA000, 0xBFFF, NULL, RAM+0x0A000); // HACK RAM AddZ80BWriteByte(0xFE00, 0xFE07, LSystemTileBankWrite, NULL); // TILE BANK AddZ80BWriteByte(0xFF00, 0xFF03, LSystemIntVecWrite, NULL); // INTERRUPT AddZ80BWriteByte(0xFF04, 0xFF07, LSystemVRAMBankWrite, NULL); // VRAM BANK AddZ80BWriteByte(0xFF08, 0xFF08, LSystemNewBankWrite, NULL); // ROM BANK AddZ80BWriteByte(0x0000, 0xFFFF, DefBadWriteZ80, NULL); // <bad writes> AddZ80BWriteByte(-1, -1, NULL, NULL); AddZ80BReadPort(0x00, 0xFF, DefBadReadZ80, NULL); // <bad reads> AddZ80BReadPort(-1, -1, NULL, NULL); AddZ80BWritePort(0xAA, 0xAA, StopZ80BMode2, NULL); // Trap Idle Z80 AddZ80BWritePort(0x00, 0xFF, DefBadWriteZ80, NULL); // <bad reads> AddZ80BWritePort(-1, -1, NULL, NULL); AddZ80BInit(); FreeMem(TMP); /*-----------------------*/ if(!(GFX=AllocateMem(0x200000))) return; if(!(TMP=AllocateMem(0x080000))) return; if(!load_rom("pg02.ic9", TMP+0x00000, 0x40000)) return; if(!load_rom("pg01.ic7", TMP+0x40000, 0x40000)) return; tb=0; for(ta=0;ta<0x40000;ta+=2,tb+=8){ DrawNibble0(&GFX[tb+0],0, (UINT8) (TMP[ta+0]&15) ); DrawNibble0(&GFX[tb+4],0, (UINT8) (TMP[ta+1]&15) ); DrawNibble(&GFX[tb+0], 1, (UINT8) (TMP[ta+0]>>4) ); DrawNibble(&GFX[tb+4], 1, (UINT8) (TMP[ta+1]>>4) ); DrawNibble(&GFX[tb+0], 2, (UINT8) (TMP[ta+0x40000]&15) ); DrawNibble(&GFX[tb+4], 2, (UINT8) (TMP[ta+0x40001]&15) ); DrawNibble(&GFX[tb+0], 3, (UINT8) (TMP[ta+0x40000]>>4) ); DrawNibble(&GFX[tb+4], 3, (UINT8) (TMP[ta+0x40001]>>4) ); } FreeMem(TMP); GFX_BG0 = GFX+0x000000; GFX_BG0_SOLID = make_solid_mask_8x8(GFX_BG0, 0x8000); spr_mask = 0x1FFF; tile_mask = 0x7FFF; lsystem_vcu_init(1); LSystemAddSaveData(); // Init tc0220ioc emulation // ------------------------ //tc0220ioc.RAM = RAM_INP; //tc0220ioc.ctrl = 0; //TC0220_STOPCPU; //reset_tc0220ioc(); } static void load_plgirls2(void) { int ta, tb; UINT8 *TMP; romset=7; Z80BankCount=0x40000/0x2000; Z802BankCount=0x00000/0x4000; RAMSize=0x10000+0x8000+0x10000+0x4000+0x200+0x10+0x10000; if(!(ROM =AllocateMem(0x8000*Z80BankCount))) return; if(!(RAM =AllocateMem(RAMSize))) return; memset(RAM, 0x00, RAMSize); RAM_FG0=RAM+0x10000; GFX_FG0=RAM+0x10000+0x8000; RAM_BG0=RAM+0x10000+0x8000+0x10000; RAM_PAL=RAM+0x10000+0x8000+0x10000+0x4000; RAM_INP=RAM+0x10000+0x8000+0x10000+0x4000+0x200; if(!(TMP =AllocateMem(0x40000))) return; if(!load_rom("pg2_1j.ic6",TMP,0x40000)) return; // Z80 MAIN ROM // TMP[0x0706]=0xC9; // RET // TMP[0x01B1]=0xD3; // OUTA (AAh) // TMP[0x01B2]=0xAA; // // SetStopZ80BMode2(0x01B1); init_bank_rom(TMP); memcpy(RAM, TMP, 0x6000+0x2000); AddZ80BROMBase(RAM, 0x0038, 0x0066); AddZ80BReadByte(0x0000, 0x7FFF, NULL, NULL); // BANK ROM AddZ80BReadByte(0x8000, 0x9FFF, NULL, RAM+0x08000); // WORK RAM AddZ80BReadByte(0xC000, 0xFDFF, LSystemVRAMRead, NULL); // VIDEO RAM AddZ80BReadByte(0xA000, 0xA003, lsystem_ym2203_dsw_rb, NULL); // YM2203; INPUT AddZ80BReadByte(0xA000, 0xBFFF, NULL, RAM+0x0A000); // HACK RAM AddZ80BReadByte(0xFE00, 0xFE07, LSystemTileBankRead, NULL); // TILE BANK AddZ80BReadByte(0xFF00, 0xFF03, LSystemIntVecRead, NULL); // INTERRUPT AddZ80BReadByte(0xFF04, 0xFF07, LSystemVRAMBankRead, NULL); // VRAM BANK AddZ80BReadByte(0xFF08, 0xFF08, LSystemBankRead, NULL); // ROM BANK AddZ80BReadByte(0x0000, 0xFFFF, DefBadReadZ80, NULL); // <bad reads> AddZ80BReadByte(-1, -1, NULL, NULL); AddZ80BWriteByte(0x8000, 0x9FFF, NULL, RAM+0x08000); // WORK RAM AddZ80BWriteByte(0xC000, 0xFDFF, LSystemVRAMWrite, NULL); // VIDEO RAM AddZ80BWriteByte(0xA000, 0xA003, lsystem_ym2203_wb, NULL); // YM2203; INPUT AddZ80BWriteByte(0xA000, 0xBFFF, NULL, RAM+0x0A000); // HACK RAM AddZ80BWriteByte(0xFE00, 0xFE07, LSystemTileBankWrite, NULL); // TILE BANK AddZ80BWriteByte(0xFF00, 0xFF03, LSystemIntVecWrite, NULL); // INTERRUPT AddZ80BWriteByte(0xFF04, 0xFF07, LSystemVRAMBankWrite, NULL); // VRAM BANK AddZ80BWriteByte(0xFF08, 0xFF08, LSystemNewBankWrite, NULL); // ROM BANK AddZ80BWriteByte(0x0000, 0xFFFF, DefBadWriteZ80, NULL); // <bad writes> AddZ80BWriteByte(-1, -1, NULL, NULL); AddZ80BReadPort(0x00, 0xFF, DefBadReadZ80, NULL); // <bad reads> AddZ80BReadPort(-1, -1, NULL, NULL); AddZ80BWritePort(0xAA, 0xAA, StopZ80BMode2, NULL); // Trap Idle Z80 AddZ80BWritePort(0x00, 0xFF, DefBadWriteZ80, NULL); // <bad reads> AddZ80BWritePort(-1, -1, NULL, NULL); AddZ80BInit(); FreeMem(TMP); /*-----------------------*/ if(!(GFX=AllocateMem(0x400000))) return; if(!(TMP=AllocateMem(0x100000))) return; if(!load_rom("cho-l.ic9", TMP+0x00000, 0x80000)) return; if(!load_rom("cho-h.ic7", TMP+0x80000, 0x80000)) return; tb=0; for(ta=0;ta<0x80000;ta+=2,tb+=8){ DrawNibble0(&GFX[tb+0],0, (UINT8) (TMP[ta+0]&15) ); DrawNibble0(&GFX[tb+4],0, (UINT8) (TMP[ta+1]&15) ); DrawNibble(&GFX[tb+0], 1, (UINT8) (TMP[ta+0]>>4) ); DrawNibble(&GFX[tb+4], 1, (UINT8) (TMP[ta+1]>>4) ); DrawNibble(&GFX[tb+0], 2, (UINT8) (TMP[ta+0x80000]&15) ); DrawNibble(&GFX[tb+4], 2, (UINT8) (TMP[ta+0x80001]&15) ); DrawNibble(&GFX[tb+0], 3, (UINT8) (TMP[ta+0x80000]>>4) ); DrawNibble(&GFX[tb+4], 3, (UINT8) (TMP[ta+0x80001]>>4) ); } FreeMem(TMP); GFX_BG0 = GFX+0x000000; GFX_BG0_SOLID = make_solid_mask_8x8(GFX_BG0, 0x8000); spr_mask = 0x1FFF; tile_mask = 0x7FFF; lsystem_vcu_init(1); LSystemAddSaveData(); // Init tc0220ioc emulation // ------------------------ //tc0220ioc.RAM = RAM_INP; //tc0220ioc.ctrl = 0; //TC0220_STOPCPU; //reset_tc0220ioc(); } static void load_palamed(void) { int ta, tb; UINT8 *TMP; romset=7; Z80BankCount=0x20000/0x2000; Z802BankCount=0x00000/0x4000; RAMSize=0x10000+0x8000+0x10000+0x4000+0x200+0x20; if(!(ROM =AllocateMem(0x8000*Z80BankCount))) return; if(!(RAM =AllocateMem(RAMSize))) return; memset(RAM, 0x00, RAMSize); RAM_FG0=RAM+0x10000; GFX_FG0=RAM+0x10000+0x8000; RAM_BG0=RAM+0x10000+0x8000+0x10000; RAM_PAL=RAM+0x10000+0x8000+0x10000+0x4000; RAM_INP=RAM+0x10000+0x8000+0x10000+0x4000+0x200; if(!(TMP =AllocateMem(0x20000))) return; if(!load_rom("c63.02",TMP,0x20000)) return; // Z80 MAIN ROM TMP[0x0120]=0xD3; // OUTA (AAh) TMP[0x0121]=0xAA; // SetStopZ80BMode2(0x0120); init_bank_rom(TMP); memcpy(RAM, TMP, 0x6000+0x2000); AddZ80BROMBase(RAM, 0x0038, 0x0066); AddZ80BReadByte(0x0000, 0x7FFF, NULL, NULL); // BANK ROM AddZ80BReadByte(0x8000, 0x9FFF, NULL, RAM+0x08000); // WORK RAM AddZ80BReadByte(0xC000, 0xFDFF, LSystemVRAMRead, NULL); // VIDEO RAM AddZ80BReadByte(0xA000, 0xA001, lsystem_ym2203_dsw_rb, NULL); // YM2203; INPUT AddZ80BReadByte(0xA800, 0xA807, tc0220ioc_rb_z80, NULL); // INPUT AddZ80BReadByte(0xFE00, 0xFE07, LSystemTileBankRead, NULL); // TILE BANK AddZ80BReadByte(0xFF00, 0xFF03, LSystemIntVecRead, NULL); // INTERRUPT AddZ80BReadByte(0xFF04, 0xFF07, LSystemVRAMBankRead, NULL); // VRAM BANK AddZ80BReadByte(0xFF08, 0xFF08, LSystemBankRead, NULL); // ROM BANK AddZ80BReadByte(0x0000, 0xFFFF, DefBadReadZ80, NULL); // <bad reads> AddZ80BReadByte(-1, -1, NULL, NULL); AddZ80BWriteByte(0x8000, 0x9FFF, NULL, RAM+0x08000); // WORK RAM AddZ80BWriteByte(0xC000, 0xFDFF, LSystemVRAMWrite, NULL); // VIDEO RAM AddZ80BWriteByte(0xA000, 0xA001, lsystem_ym2203_wb, NULL); // YM2203; INPUT AddZ80BWriteByte(0xA800, 0xA807, tc0220ioc_wb_z80, NULL); // INPUT AddZ80BWriteByte(0xB000, 0xB000, palamedes_led_write, NULL); // LEDS AddZ80BWriteByte(0xFE00, 0xFE07, LSystemTileBankWrite, NULL); // TILE BANK AddZ80BWriteByte(0xFF00, 0xFF03, LSystemIntVecWrite, NULL); // INTERRUPT AddZ80BWriteByte(0xFF04, 0xFF07, LSystemVRAMBankWrite, NULL); // VRAM BANK AddZ80BWriteByte(0xFF08, 0xFF08, LSystemNewBankWrite, NULL); // ROM BANK AddZ80BWriteByte(0x0000, 0xFFFF, DefBadWriteZ80, NULL); // <bad writes> AddZ80BWriteByte(-1, -1, NULL, NULL); AddZ80BReadPort(0x00, 0xFF, DefBadReadZ80, NULL); // <bad reads> AddZ80BReadPort(-1, -1, NULL, NULL); AddZ80BWritePort(0xAA, 0xAA, StopZ80BMode2, NULL); // Trap Idle Z80 AddZ80BWritePort(0x00, 0xFF, DefBadWriteZ80, NULL); // <bad reads> AddZ80BWritePort(-1, -1, NULL, NULL); AddZ80BInit(); FreeMem(TMP); /*-----------------------*/ if(!(GFX=AllocateMem(0x080000))) return; if(!(TMP=AllocateMem(0x040000))) return; if(!load_rom("c63.04", TMP+0x00000, 0x20000)) return; if(!load_rom("c63.03", TMP+0x20000, 0x20000)) return; tb=0; for(ta=0;ta<0x20000;ta+=2,tb+=8){ DrawNibble0(&GFX[tb+0],0, (UINT8) (TMP[ta+0]&15) ); DrawNibble0(&GFX[tb+4],0, (UINT8) (TMP[ta+1]&15) ); DrawNibble(&GFX[tb+0], 1, (UINT8) (TMP[ta+0]>>4) ); DrawNibble(&GFX[tb+4], 1, (UINT8) (TMP[ta+1]>>4) ); DrawNibble(&GFX[tb+0], 2, (UINT8) (TMP[ta+0x20000]&15) ); DrawNibble(&GFX[tb+4], 2, (UINT8) (TMP[ta+0x20001]&15) ); DrawNibble(&GFX[tb+0], 3, (UINT8) (TMP[ta+0x20000]>>4) ); DrawNibble(&GFX[tb+4], 3, (UINT8) (TMP[ta+0x20001]>>4) ); } FreeMem(TMP); GFX_BG0 = GFX+0x000000; GFX_BG0_SOLID = make_solid_mask_8x8(GFX_BG0, 0x2000); spr_mask = 0x07FF; tile_mask = 0x1FFF; lsystem_vcu_init(1); LSystemAddSaveData(); // Init tc0220ioc emulation // ------------------------ tc0220ioc.RAM = RAM_INP; tc0220ioc.ctrl = 0; //TC0220_STOPCPU; reset_tc0220ioc(); } static void load_cubybop(void) { int ta, tb; UINT8 *TMP; romset=9; Z80BankCount=0x40000/0x2000; Z802BankCount=0x00000/0x4000; RAMSize=0x10000+0x8000+0x10000+0x4000+0x200+0x20; if(!(ROM =AllocateMem(0x8000*Z80BankCount))) return; if(!(RAM =AllocateMem(RAMSize))) return; memset(RAM, 0x00, RAMSize); RAM_FG0=RAM+0x10000; GFX_FG0=RAM+0x10000+0x8000; RAM_BG0=RAM+0x10000+0x8000+0x10000; RAM_PAL=RAM+0x10000+0x8000+0x10000+0x4000; RAM_INP=RAM+0x10000+0x8000+0x10000+0x4000+0x200; if(!(TMP =AllocateMem(0x40000))) return; if(!load_rom("cb06.6",TMP,0x40000)) return; // Z80 MAIN ROM /* TMP[0x0120]=0xD3; // OUTA (AAh) TMP[0x0121]=0xAA; // SetStopZ80BMode2(0x0120); */ init_bank_rom(TMP); memcpy(RAM, TMP, 0x6000+0x2000); AddZ80BROMBase(RAM, 0x0038, 0x0066); AddZ80BReadByte(0x0000, 0x7FFF, NULL, NULL); // BANK ROM AddZ80BReadByte(0x8000, 0x9FFF, NULL, RAM+0x08000); // WORK RAM AddZ80BReadByte(0xC000, 0xFDFF, LSystemVRAMRead, NULL); // VIDEO RAM AddZ80BReadByte(0xA000, 0xA001, lsystem_ym2203_dsw_rb, NULL); // YM2203; INPUT AddZ80BReadByte(0xA800, 0xA807, tc0220ioc_rb_z80, NULL); // INPUT AddZ80BReadByte(0xFE00, 0xFE07, LSystemTileBankRead, NULL); // TILE BANK AddZ80BReadByte(0xFF00, 0xFF03, LSystemIntVecRead, NULL); // INTERRUPT AddZ80BReadByte(0xFF04, 0xFF07, LSystemVRAMBankRead, NULL); // VRAM BANK AddZ80BReadByte(0xFF08, 0xFF08, LSystemBankRead, NULL); // ROM BANK AddZ80BReadByte(0x0000, 0xFFFF, DefBadReadZ80, NULL); // <bad reads> AddZ80BReadByte(-1, -1, NULL, NULL); AddZ80BWriteByte(0x8000, 0x9FFF, NULL, RAM+0x08000); // WORK RAM AddZ80BWriteByte(0xC000, 0xFDFF, LSystemVRAMWrite, NULL); // VIDEO RAM AddZ80BWriteByte(0xA000, 0xA001, lsystem_ym2203_wb, NULL); // YM2203; INPUT AddZ80BWriteByte(0xA800, 0xA807, tc0220ioc_wb_z80, NULL); // INPUT AddZ80BWriteByte(0xB000, 0xB000, palamedes_led_write, NULL); // LEDS AddZ80BWriteByte(0xFE00, 0xFE07, LSystemTileBankWrite, NULL); // TILE BANK AddZ80BWriteByte(0xFF00, 0xFF03, LSystemIntVecWrite, NULL); // INTERRUPT AddZ80BWriteByte(0xFF04, 0xFF07, LSystemVRAMBankWrite, NULL); // VRAM BANK AddZ80BWriteByte(0xFF08, 0xFF08, LSystemNewBankWrite, NULL); // ROM BANK AddZ80BWriteByte(0x0000, 0xFFFF, DefBadWriteZ80, NULL); // <bad writes> AddZ80BWriteByte(-1, -1, NULL, NULL); AddZ80BReadPort(0x00, 0xFF, DefBadReadZ80, NULL); // <bad reads> AddZ80BReadPort(-1, -1, NULL, NULL); AddZ80BWritePort(0xAA, 0xAA, StopZ80BMode2, NULL); // Trap Idle Z80 AddZ80BWritePort(0x00, 0xFF, DefBadWriteZ80, NULL); // <bad reads> AddZ80BWritePort(-1, -1, NULL, NULL); AddZ80BInit(); FreeMem(TMP); /*-----------------------*/ if(!(GFX=AllocateMem(0x200000))) return; if(!(TMP=AllocateMem(0x100000))) return; if(!load_rom("cb09.9", TMP+0x000000, 0x40000)) return; if(!load_rom("cb10.10",TMP+0x040000, 0x40000)) return; if(!load_rom("cb07.7", TMP+0x080000, 0x40000)) return; if(!load_rom("cb08.8", TMP+0x0C0000, 0x40000)) return; tb=0; for(ta=0;ta<0x80000;ta+=2,tb+=8){ DrawNibble0(&GFX[tb+0],0, (UINT8) (TMP[ta+0]&15) ); DrawNibble0(&GFX[tb+4],0, (UINT8) (TMP[ta+1]&15) ); DrawNibble(&GFX[tb+0], 1, (UINT8) (TMP[ta+0]>>4) ); DrawNibble(&GFX[tb+4], 1, (UINT8) (TMP[ta+1]>>4) ); DrawNibble(&GFX[tb+0], 2, (UINT8) (TMP[ta+0x80000]&15) ); DrawNibble(&GFX[tb+4], 2, (UINT8) (TMP[ta+0x80001]&15) ); DrawNibble(&GFX[tb+0], 3, (UINT8) (TMP[ta+0x80000]>>4) ); DrawNibble(&GFX[tb+4], 3, (UINT8) (TMP[ta+0x80001]>>4) ); } FreeMem(TMP); GFX_BG0 = GFX+0x000000; GFX_BG0_SOLID = make_solid_mask_8x8(GFX_BG0, 0x8000); spr_mask = 0x1FFF; tile_mask = 0x7FFF; lsystem_vcu_init(1); LSystemAddSaveData(); // Init tc0220ioc emulation // ------------------------ tc0220ioc.RAM = RAM_INP; tc0220ioc.ctrl = 0; //TC0220_STOPCPU; reset_tc0220ioc(); } static void load_tubeit(void) { int ta, tb; UINT8 *TMP; romset=7; Z80BankCount=0x20000/0x2000; Z802BankCount=0x00000/0x4000; RAMSize=0x10000+0x8000+0x10000+0x4000+0x200+0x20; if(!(ROM =AllocateMem(0x8000*Z80BankCount))) return; if(!(RAM =AllocateMem(RAMSize))) return; memset(RAM, 0x00, RAMSize); RAM_FG0=RAM+0x10000; GFX_FG0=RAM+0x10000+0x8000; RAM_BG0=RAM+0x10000+0x8000+0x10000; RAM_PAL=RAM+0x10000+0x8000+0x10000+0x4000; RAM_INP=RAM+0x10000+0x8000+0x10000+0x4000+0x200; if(!(TMP =AllocateMem(0x20000))) return; if(!load_rom("t-i_02.6",TMP,0x20000)) return; // Z80 MAIN ROM /* TMP[0x0120]=0xD3; // OUTA (AAh) TMP[0x0121]=0xAA; // SetStopZ80BMode2(0x0120); */ init_bank_rom(TMP); memcpy(RAM, TMP, 0x6000+0x2000); AddZ80BROMBase(RAM, 0x0038, 0x0066); AddZ80BReadByte(0x0000, 0x7FFF, NULL, NULL); // BANK ROM AddZ80BReadByte(0x8000, 0x9FFF, NULL, RAM+0x08000); // WORK RAM AddZ80BReadByte(0xC000, 0xFDFF, LSystemVRAMRead, NULL); // VIDEO RAM AddZ80BReadByte(0xA000, 0xA001, lsystem_ym2203_dsw_rb, NULL); // YM2203; INPUT AddZ80BReadByte(0xA800, 0xA807, tc0220ioc_rb_z80, NULL); // INPUT AddZ80BReadByte(0xFE00, 0xFE07, LSystemTileBankRead, NULL); // TILE BANK AddZ80BReadByte(0xFF00, 0xFF03, LSystemIntVecRead, NULL); // INTERRUPT AddZ80BReadByte(0xFF04, 0xFF07, LSystemVRAMBankRead, NULL); // VRAM BANK AddZ80BReadByte(0xFF08, 0xFF08, LSystemBankRead, NULL); // ROM BANK AddZ80BReadByte(0xFFF8, 0xFFF8, LSystemBankRead, NULL); // ROM BANK AddZ80BReadByte(0x0000, 0xFFFF, DefBadReadZ80, NULL); // <bad reads> AddZ80BReadByte(-1, -1, NULL, NULL); AddZ80BWriteByte(0x8000, 0x9FFF, NULL, RAM+0x08000); // WORK RAM AddZ80BWriteByte(0xC000, 0xFDFF, LSystemVRAMWrite, NULL); // VIDEO RAM AddZ80BWriteByte(0xA000, 0xA001, lsystem_ym2203_wb, NULL); // YM2203; INPUT AddZ80BWriteByte(0xA800, 0xA807, tc0220ioc_wb_z80, NULL); // INPUT AddZ80BWriteByte(0xB000, 0xB000, palamedes_led_write, NULL); // LEDS AddZ80BWriteByte(0xFE00, 0xFE07, LSystemTileBankWrite, NULL); // TILE BANK AddZ80BWriteByte(0xFF00, 0xFF03, LSystemIntVecWrite, NULL); // INTERRUPT AddZ80BWriteByte(0xFF04, 0xFF07, LSystemVRAMBankWrite, NULL); // VRAM BANK AddZ80BWriteByte(0xFF08, 0xFF08, LSystemNewBankWrite, NULL); // ROM BANK AddZ80BWriteByte(0xFFF8, 0xFFF8, LSystemNewBankWrite, NULL); // ROM BANK AddZ80BWriteByte(0x0000, 0xFFFF, DefBadWriteZ80, NULL); // <bad writes> AddZ80BWriteByte(-1, -1, NULL, NULL); AddZ80BReadPort(0x00, 0xFF, DefBadReadZ80, NULL); // <bad reads> AddZ80BReadPort(-1, -1, NULL, NULL); AddZ80BWritePort(0xAA, 0xAA, StopZ80BMode2, NULL); // Trap Idle Z80 AddZ80BWritePort(0x00, 0xFF, DefBadWriteZ80, NULL); // <bad reads> AddZ80BWritePort(-1, -1, NULL, NULL); AddZ80BInit(); FreeMem(TMP); /*-----------------------*/ if(!(GFX=AllocateMem(0x100000))) return; if(!(TMP=AllocateMem(0x080000))) return; if(!load_rom("t-i_04.9", TMP+0x000000, 0x40000)) return; if(!load_rom("t-i_03.7", TMP+0x040000, 0x40000)) return; tb=0; for(ta=0;ta<0x40000;ta+=2,tb+=8){ DrawNibble0(&GFX[tb+0],0, (UINT8) (TMP[ta+0]&15) ); DrawNibble0(&GFX[tb+4],0, (UINT8) (TMP[ta+1]&15) ); DrawNibble(&GFX[tb+0], 1, (UINT8) (TMP[ta+0]>>4) ); DrawNibble(&GFX[tb+4], 1, (UINT8) (TMP[ta+1]>>4) ); DrawNibble(&GFX[tb+0], 2, (UINT8) (TMP[ta+0x40000]&15) ); DrawNibble(&GFX[tb+4], 2, (UINT8) (TMP[ta+0x40001]&15) ); DrawNibble(&GFX[tb+0], 3, (UINT8) (TMP[ta+0x40000]>>4) ); DrawNibble(&GFX[tb+4], 3, (UINT8) (TMP[ta+0x40001]>>4) ); } FreeMem(TMP); GFX_BG0 = GFX+0x000000; GFX_BG0_SOLID = make_solid_mask_8x8(GFX_BG0, 0x4000); spr_mask = 0x0FFF; tile_mask = 0x3FFF; lsystem_vcu_init(1); LSystemAddSaveData(); // Init tc0220ioc emulation // ------------------------ tc0220ioc.RAM = RAM_INP; tc0220ioc.ctrl = 0; //TC0220_STOPCPU; reset_tc0220ioc(); } // Cachat supports a region in 7fff (in a bank !), but us region has its fbi // screen empty, and us and world look weird on the title screen, so it's // probably better to leave the default region (japan) static void load_cachat(void) { int ta, tb; UINT8 *TMP; romset=8; Z80BankCount=0x20000/0x2000; Z802BankCount=0x00000/0x4000; RAMSize=0x10000+0x8000+0x10000+0x4000+0x200+0x20; if(!(ROM =AllocateMem(0x8000*Z80BankCount))) return; if(!(RAM =AllocateMem(RAMSize))) return; memset(RAM, 0x00, RAMSize); RAM_FG0=RAM+0x10000; GFX_FG0=RAM+0x10000+0x8000; RAM_BG0=RAM+0x10000+0x8000+0x10000; RAM_PAL=RAM+0x10000+0x8000+0x10000+0x4000; RAM_INP=RAM+0x10000+0x8000+0x10000+0x4000+0x200; if(!(TMP =AllocateMem(0x20000))) return; if(!load_rom("cac6",TMP,0x20000)) return; // Z80 MAIN ROM TMP[0x0287]=0xD3; // OUTA (AAh) TMP[0x0288]=0xAA; // SetStopZ80BMode2(0x0289); init_bank_rom(TMP); memcpy(RAM, TMP, 0x6000+0x2000); AddZ80BROMBase(RAM, 0x0038, 0x0066); AddZ80BReadByte(0x0000, 0x7FFF, NULL, NULL); // BANK ROM AddZ80BReadByte(0x8000, 0x9FFF, NULL, RAM+0x08000); // WORK RAM AddZ80BReadByte(0xC000, 0xFDFF, LSystemVRAMRead, NULL); // VIDEO RAM AddZ80BReadByte(0xA000, 0xA001, lsystem_ym2203_dsw_rb, NULL); // YM2203; INPUT AddZ80BReadByte(0xA800, 0xA807, tc0220ioc_rb_z80, NULL); // INPUT AddZ80BReadByte(0xFE00, 0xFE07, LSystemTileBankRead, NULL); // TILE BANK AddZ80BReadByte(0xFF00, 0xFF03, LSystemIntVecRead, NULL); // INTERRUPT AddZ80BReadByte(0xFF04, 0xFF07, LSystemVRAMBankRead, NULL); // VRAM BANK AddZ80BReadByte(0xFF08, 0xFF08, LSystemBankRead, NULL); // ROM BANK AddZ80BReadByte(0xFFF8, 0xFFF8, LSystemBankRead, NULL); // ROM BANK [MIRROR] AddZ80BReadByte(0x0000, 0xFFFF, DefBadReadZ80, NULL); // <bad reads> AddZ80BReadByte(-1, -1, NULL, NULL); AddZ80BWriteByte(0x8000, 0x9FFF, NULL, RAM+0x08000); // WORK RAM AddZ80BWriteByte(0xC000, 0xFDFF, LSystemVRAMWrite, NULL); // VIDEO RAM AddZ80BWriteByte(0xA000, 0xA001, lsystem_ym2203_wb, NULL); // YM2203; INPUT AddZ80BWriteByte(0xA800, 0xA807, tc0220ioc_wb_z80, NULL); // INPUT AddZ80BWriteByte(0xB000, 0xB000, palamedes_led_write, NULL); // LEDS AddZ80BWriteByte(0xFE00, 0xFE07, LSystemTileBankWrite, NULL); // TILE BANK AddZ80BWriteByte(0xFF00, 0xFF03, LSystemIntVecWrite, NULL); // INTERRUPT AddZ80BWriteByte(0xFF04, 0xFF07, LSystemVRAMBankWrite, NULL); // VRAM BANK AddZ80BWriteByte(0xFF08, 0xFF08, LSystemNewBankWrite, NULL); // ROM BANK AddZ80BWriteByte(0xFFF8, 0xFFF8, LSystemNewBankWrite, NULL); // ROM BANK [MIRROR] AddZ80BWriteByte(0x0000, 0xFFFF, DefBadWriteZ80, NULL); // <bad writes> AddZ80BWriteByte(-1, -1, NULL, NULL); AddZ80BReadPort(0x00, 0xFF, DefBadReadZ80, NULL); // <bad reads> AddZ80BReadPort(-1, -1, NULL, NULL); AddZ80BWritePort(0xAA, 0xAA, StopZ80BMode2, NULL); // Trap Idle Z80 AddZ80BWritePort(0x00, 0xFF, DefBadWriteZ80, NULL); // <bad reads> AddZ80BWritePort(-1, -1, NULL, NULL); AddZ80BInit(); FreeMem(TMP); /*-----------------------*/ if(!(GFX=AllocateMem(0x100000))) return; if(!(TMP=AllocateMem(0x080000))) return; if(!load_rom("cac9", TMP+0x00000, 0x20000)) return; if(!load_rom("cac10",TMP+0x20000, 0x20000)) return; if(!load_rom("cac7", TMP+0x40000, 0x20000)) return; if(!load_rom("cac8", TMP+0x60000, 0x20000)) return; tb=0; for(ta=0;ta<0x40000;ta+=2,tb+=8){ DrawNibble0(&GFX[tb+0],0, (UINT8) (TMP[ta+0]&15) ); DrawNibble0(&GFX[tb+4],0, (UINT8) (TMP[ta+1]&15) ); DrawNibble(&GFX[tb+0], 1, (UINT8) (TMP[ta+0]>>4) ); DrawNibble(&GFX[tb+4], 1, (UINT8) (TMP[ta+1]>>4) ); DrawNibble(&GFX[tb+0], 2, (UINT8) (TMP[ta+0x40000]&15) ); DrawNibble(&GFX[tb+4], 2, (UINT8) (TMP[ta+0x40001]&15) ); DrawNibble(&GFX[tb+0], 3, (UINT8) (TMP[ta+0x40000]>>4) ); DrawNibble(&GFX[tb+4], 3, (UINT8) (TMP[ta+0x40001]>>4) ); } FreeMem(TMP); GFX_BG0 = GFX+0x000000; GFX_BG0_SOLID = make_solid_mask_8x8(GFX_BG0, 0x4000); spr_mask = 0x0FFF; tile_mask = 0x3FFF; lsystem_vcu_init(1); LSystemAddSaveData(); // Init tc0220ioc emulation // ------------------------ tc0220ioc.RAM = RAM_INP; tc0220ioc.ctrl = 0; //TC0220_STOPCPU; reset_tc0220ioc(); } static void DrawLSystem(void) { int w,x,y,code,ta; int zz,zzz,zzzz,x16,y16; UINT8 *p,colour,*map; UINT8 *GFX_BG,*MSK_BG; if (!GFX_BG0_SOLID) { GFX_BG0_SOLID = gfx_solid[0]; if (!GFX_BG0) { GFX_BG0 = gfx[0]; } } ClearPaletteMap(); GFX_BG = GFX_BG0; MSK_BG = GFX_BG0_SOLID; // American Horseshoes has an extra gfx bank switch if(romset==1){ GFX_BG = GFX_BG0 + (ah_gfx_bank*0x1000*0x40); MSK_BG = GFX_BG0_SOLID + (ah_gfx_bank*0x1000); } // BG0 // --- if(check_layer_enabled(layer_id_data[0])) { MAKE_SCROLL_512x256_2_8( 0-(ReadWord(&RAM_BG0[0x33FC])+28+10), 16-(ReadWord(&RAM_BG0[0x33FE])) ); START_SCROLL_512x256_2_8(32,32,320,224); code = ReadWord(&RAM_BG0[0x1000+zz]); ta = ((code&0x3FF)|(TileBank[(code>>10)&3]<<10))&tile_mask; colour = (UINT8) ((code>>8)&0xF0)>>4; MAP_PALETTE_MAPPED_NEW(colour, 16, map); Draw8x8_Mapped_Rot(&GFX_BG[ta<<6], x, y, map); END_SCROLL_512x256_2_8(); } else clear_game_screen(0); // OBJECT // ------ if(check_layer_enabled(layer_id_data[1])) { if((TileBank[4]&0x08)==0){ p = &RAM_BG0[0x33F0]; w = 0x7E; do { p -= 8; code = ReadWord(p) & spr_mask; if(code!=0){ if((colour = ((*(p+2)) & 15))>=8){ x = (ReadWord(p+4)+32)&0x1FF; y = (ReadWord(p+6)+16)&0xFF; if((x>16)&&(y>16)&&(x<320+32)&&(y<224+32)){ code <<= 8; MAP_PAL(colour, 16, map); switch((*(p+3)) & 3){ case 0x00: Draw8x8_Trans_Mapped_Rot(&GFX_BG[code+0x00], x, y, map); Draw8x8_Trans_Mapped_Rot(&GFX_BG[code+0x40], x+8, y, map); Draw8x8_Trans_Mapped_Rot(&GFX_BG[code+0x80], x, y+8, map); Draw8x8_Trans_Mapped_Rot(&GFX_BG[code+0xC0], x+8, y+8, map); break; case 0x01: Draw8x8_Trans_Mapped_FlipY_Rot(&GFX_BG[code+0x00], x+8, y, map); Draw8x8_Trans_Mapped_FlipY_Rot(&GFX_BG[code+0x40], x, y, map); Draw8x8_Trans_Mapped_FlipY_Rot(&GFX_BG[code+0x80], x+8, y+8, map); Draw8x8_Trans_Mapped_FlipY_Rot(&GFX_BG[code+0xC0], x, y+8, map); break; case 0x02: Draw8x8_Trans_Mapped_FlipX_Rot(&GFX_BG[code+0x00], x, y+8, map); Draw8x8_Trans_Mapped_FlipX_Rot(&GFX_BG[code+0x40], x+8, y+8, map); Draw8x8_Trans_Mapped_FlipX_Rot(&GFX_BG[code+0x80], x, y, map); Draw8x8_Trans_Mapped_FlipX_Rot(&GFX_BG[code+0xC0], x+8, y, map); break; case 0x03: Draw8x8_Trans_Mapped_FlipXY_Rot(&GFX_BG[code+0x00], x+8, y+8, map); Draw8x8_Trans_Mapped_FlipXY_Rot(&GFX_BG[code+0x40], x, y+8, map); Draw8x8_Trans_Mapped_FlipXY_Rot(&GFX_BG[code+0x80], x+8, y, map); Draw8x8_Trans_Mapped_FlipXY_Rot(&GFX_BG[code+0xC0], x, y, map); break; } } }} } while(--w); } } // BG1 // --- if(check_layer_enabled(layer_id_data[2])) { MAKE_SCROLL_512x256_2_8( 0-(ReadWord(&RAM_BG0[0x33F4])+28), 16-(ReadWord(&RAM_BG0[0x33F6])) ); START_SCROLL_512x256_2_8(32,32,320,224); code = ReadWord(&RAM_BG0[0x0000+zz]); ta = ((code&0x3FF)|(TileBank[(code>>10)&3]<<10))&tile_mask; colour = (UINT8) ((code>>8)&0xF0)>>4; MAP_PAL(colour, 16, map); if(MSK_BG[ta]!=0){ // No pixels; skip if(MSK_BG[ta]==1){ // Some pixels; trans Draw8x8_Trans_Mapped_Rot(&GFX_BG[ta<<6], x, y, map); } else{ // all pixels; solid Draw8x8_Mapped_Rot(&GFX_BG[ta<<6], x, y, map); } } END_SCROLL_512x256_2_8(); } // OBJECT // ------ if(check_layer_enabled(layer_id_data[3])) { if((TileBank[4]&0x08)==0){ ta = 8; } else{ ta = 16; } p = &RAM_BG0[0x33F0]; w = 0x7E; do { p -= 8; code = ReadWord(p) & spr_mask; if(code!=0){ if((colour = ((*(p+2)) & 15))<ta){ x = (ReadWord(p+4)+32)&0x1FF; y = (ReadWord(p+6)+16)&0x0FF; if((x>16)&&(y>16)&&(x<320+32)&&(y<224+32)){ MAP_PAL(colour, 16, map); code <<= 8; switch((*(p+3)) & 3){ case 0x00: Draw8x8_Trans_Mapped_Rot(&GFX_BG[code+0x00], x, y, map); Draw8x8_Trans_Mapped_Rot(&GFX_BG[code+0x40], x+8, y, map); Draw8x8_Trans_Mapped_Rot(&GFX_BG[code+0x80], x, y+8, map); Draw8x8_Trans_Mapped_Rot(&GFX_BG[code+0xC0], x+8, y+8, map); break; case 0x01: Draw8x8_Trans_Mapped_FlipY_Rot(&GFX_BG[code+0x00], x+8, y, map); Draw8x8_Trans_Mapped_FlipY_Rot(&GFX_BG[code+0x40], x, y, map); Draw8x8_Trans_Mapped_FlipY_Rot(&GFX_BG[code+0x80], x+8, y+8, map); Draw8x8_Trans_Mapped_FlipY_Rot(&GFX_BG[code+0xC0], x, y+8, map); break; case 0x02: Draw8x8_Trans_Mapped_FlipX_Rot(&GFX_BG[code+0x00], x, y+8, map); Draw8x8_Trans_Mapped_FlipX_Rot(&GFX_BG[code+0x40], x+8, y+8, map); Draw8x8_Trans_Mapped_FlipX_Rot(&GFX_BG[code+0x80], x, y, map); Draw8x8_Trans_Mapped_FlipX_Rot(&GFX_BG[code+0xC0], x+8, y, map); break; case 0x03: Draw8x8_Trans_Mapped_FlipXY_Rot(&GFX_BG[code+0x00], x+8, y+8, map); Draw8x8_Trans_Mapped_FlipXY_Rot(&GFX_BG[code+0x40], x, y+8, map); Draw8x8_Trans_Mapped_FlipXY_Rot(&GFX_BG[code+0x80], x+8, y, map); Draw8x8_Trans_Mapped_FlipXY_Rot(&GFX_BG[code+0xC0], x, y, map); break; } } }} } while(--w); } // FG0 // --- if(check_layer_enabled(layer_id_data[4])) { update_gfx_fg0(); MAKE_SCROLL_512x256_2_8( 8, 16 ); START_SCROLL_512x256_2_8(32,32,320,224); code = ReadWord(&RAM_BG0[0x2000+zz]); ta = (code&0x1FF)|((code&0x400)>>1); MAP_PAL((UINT8) ((code>>8)&0xF0)>>4, 16, map); if(GFX_FG0_SOLID[ta]){ // No pixels; skip if(GFX_FG0_SOLID[ta]==1){ // Some pixels; trans Draw8x8_Trans_Mapped_Rot(&GFX_FG0[ta<<6], x, y, map); } else{ // all pixels; solid Draw8x8_Mapped_Rot(&GFX_FG0[ta<<6], x, y, map); } } END_SCROLL_512x256_2_8(); } } static struct VIDEO_INFO video_champwr = { DrawLSystem, 320, 224, 32, VIDEO_ROTATE_NORMAL | VIDEO_ROTATABLE, gfxdecodeinfo2 }; static struct VIDEO_INFO video_fhawk = { DrawLSystem, 320, 224, 32, VIDEO_ROTATE_270 | VIDEO_ROTATABLE, }; static struct VIDEO_INFO video_kurikint = { DrawLSystem, 320, 224, 32, VIDEO_ROTATE_NORMAL | VIDEO_ROTATABLE, gfxdecodeinfo }; static struct DIR_INFO dir_horshoes[] = { { "american_horseshoes", }, { "amhorse", }, { "horshoes", }, { NULL, }, }; GAME( horshoes, "American Horseshoes", TAITO, 1990, GAME_SPORTS | GAME_NOT_WORKING, .input = input_horshoes, .dsw = dsw_horshoes, .video = &video_fhawk, .long_name_jpn = "ƒAƒƒŠƒJƒ“ƒz[ƒXƒVƒ…[", .board = "C47", ); static struct DIR_INFO dir_cachat[] = { { "cachat", }, { NULL, }, }; GAME( cachat, "Cachat", TAITO, 1993, GAME_PUZZLE, .input = input_cachat, .dsw = dsw_cachat, ); static struct DIR_INFO dir_champwr[] = { { "champion_wrestler", }, { "champwr", }, { NULL, }, }; GME( champwr, "Champion Wrestler", TAITO, 1989, GAME_SPORTS, .romsw = romsw_champwr, .video = &video_champwr, .long_name_jpn = "ƒ`ƒƒƒ“ƒsƒIƒ“ƒŒƒXƒ‰[", .board = "C01", ); static struct DIR_INFO dir_champwrj[] = { { "champion_wrestler_jp", }, { "champwrj", }, { ROMOF("champwr"), }, { CLONEOF("champwr"), }, { NULL, }, }; CLNE( champwrj, champwr, "Champion Wrestler (Japan)", TAITO, 1989, GAME_SPORTS, .dsw = dsw_champwrj, .video = &video_champwr, .long_name_jpn = "β`βββτβsβIβτβξβXβλό[ (Japan)", .board = "C01", ); static struct DIR_INFO dir_champwru[] = { { "champion_wrestler_us", }, { "champwru", }, { ROMOF("champwr"), }, { CLONEOF("champwr"), }, { NULL, }, }; CLNE( champwru, champwr, "Champion Wrestler (US)", TAITO, 1989, GAME_SPORTS, .dsw = dsw_champwru, .video = &video_champwr, .long_name_jpn = "β`βββτβsβIβτβξβXβλό[ (US)", .board = "C01", ); static struct DIR_INFO dir_cubybop[] = { { "cuby_bop", }, { "cubybop", }, { NULL, }, }; GAME( cubybop, "Cuby Bop", TAITO, 1990, GAME_PUZZLE, .input = input_cubybop, .dsw = dsw_cubybop, ); static struct DIR_INFO dir_fhawk[] = { { "fighting_hawk", }, { "fhawk", }, { "fhawkj", }, { NULL, }, }; GAME( fhawk, "Fighting Hawk", TAITO, 1988, GAME_SHOOT, .input = input_fhawk, .dsw = dsw_fhawk, .romsw = romsw_fhawk, .video = &video_fhawk, .long_name_jpn = "ƒtƒ@ƒCƒeƒBƒ“ƒOƒz[ƒN", .board = "B70", ); static struct DIR_INFO dir_kurikina[] = { { "kuri_kinton_alt", }, { "kurikina", }, { ROMOF("kurikint"), }, { CLONEOF("kurikint"), }, { NULL, }, }; CLNE( kurikina,kurikint, "Kuri Kinton (Alternate)", TAITO, 1988, GAME_BEAT, .dsw = dsw_kurikina, .romsw = romsw_kurikint, .long_name_jpn = "Œφ—›‹ΰ’c (Alternate)", .board = "B42", ); static struct DIR_INFO dir_kurikint[] = { { "kuri_kinton", }, { "kurikint", }, { NULL, }, }; GME( kurikint, "Kuri Kinton", TAITO, 1988, GAME_BEAT, .romsw = romsw_kurikint, .long_name_jpn = "Œφ—›‹ΰ’c", .board = "B42", ); static struct DIR_INFO dir_kurikinj[] = { { "kuri_kinton_jap", }, { "kurikinj", }, { "kurikina", }, { ROMOF("kurikint"), }, { CLONEOF("kurikint"), }, { NULL, }, }; CLNE( kurikinj,kurikint, "Kuri Kinton (JPN Ver.)", TAITO, 1988, GAME_BEAT, .long_name_jpn = "Œφ—›‹ΰ’c (alternate)", .romsw = romsw_kurikint, .board = "B42", ); static struct DIR_INFO dir_palamed[] = { { "palamedes", }, { "palamed", }, { NULL, }, }; GAME( palamed, "Palamedes", TAITO, 1990, GAME_PUZZLE, .input = input_palamed, .dsw = dsw_palamed, .romsw = romsw_palamed, .long_name_jpn = "ƒpƒ‰ƒƒfƒX", .board = "C63", ); static struct DIR_INFO dir_plgirls[] = { { "plgirls", }, { NULL, }, }; GAME( plgirls, "Play Girls", HOT_B, 1992, GAME_BREAKOUT | GAME_ADULT, .input = input_plgirls, .dsw = dsw_plgirls, .video = &video_fhawk, .long_name_jpn = "Play Girls", .board = "???", ); static struct DIR_INFO dir_plgirls2[] = { { "plgirls2", }, { NULL, }, }; GAME( plgirls2, "Play Girls 2", HOT_B, 1993, GAME_SHOOT | GAME_ADULT, .input = input_plgirls2, .dsw = dsw_plgirls2, .video = &video_fhawk, ); static struct DIR_INFO dir_puzznic[] = { { "puzznic", }, { "puzznicj", }, { NULL, }, }; GAME( puzznic, "Puzznic", TAITO, 1989, GAME_PUZZLE | GAME_ADULT, .input = input_puzznic, .dsw = dsw_puzznic, .romsw = romsw_puzznic, .long_name_jpn = "ƒpƒYƒjƒbƒN", .board = "C20", ); static struct DIR_INFO dir_raimais[] = { { "raimais", }, { "raimaisj", }, { NULL, }, }; GAME( raimais, "Raimais", TAITO, 1988, GAME_MISC, .input = input_raimais, .dsw = dsw_raimais, .long_name_jpn = "ƒŒƒCƒƒCƒY", .board = "B36", .sound = taito_ym2610_sound, ); static struct DIR_INFO dir_tubeit[] = { { "tube_it", }, { "tubeit", }, { ROMOF("cachat"), }, { CLONEOF("cachat"), }, { NULL, }, }; GAME( tubeit, "Tube It", TAITO, 1990, GAME_PUZZLE, .input = input_cachat, .dsw = dsw_cachat, ); GMEI( plotting ,"Plotting",TAITO,1989,GAME_PUZZLE, .romsw = plotting_romsw); CLNEI( plottinga,plotting,"Plotting (World set 2, protected)",TAITO,1989,GAME_PUZZLE, .romsw = plotting_romsw); CLNEI( plottingb,plotting,"Plotting (World set 3, earliest version)",TAITO,1989,GAME_PUZZLE, .romsw = plotting_romsw);
1fd832196d2c67acd01903f593968395465afaba
5ab69c8644a936a3d9dec1669a86c7369c911bf8
/arch/platform/simplelink/cc13xx-cc26xx/sensortag/cc1350/Board.h
92d01d76a84dd9822f921eb649ffca6361dbec42
[ "BSD-3-Clause" ]
permissive
contiki-ng/contiki-ng
393d36f68b98f5ee3544ea32502cf662ffb2fe9f
31fcaadf7a0dc8ceea07f438cd69db73174879e6
refs/heads/develop
2023-09-01T20:10:30.000765
2023-09-01T14:37:12
2023-09-01T14:37:12
91,191,972
1,242
788
BSD-3-Clause
2023-09-14T19:08:35
2017-05-13T17:37:59
C
UTF-8
C
false
false
7,321
h
Board.h
/* * Copyright (c) 2015-2019, Texas Instruments Incorporated * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of Texas Instruments Incorporated nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __BOARD_H #define __BOARD_H #ifdef __cplusplus extern "C" { #endif #include <ti/drivers/Board.h> #include "CC1350STK.h" #define Board_CC1350STK #define BOARD_STRING "TI CC1350 SensorTag" #define Board_initGeneral() Board_init() /* deprecated */ #define Board_shutDownExtFlash() CC1350STK_shutDownExtFlash() #define Board_wakeUpExtFlash() CC1350STK_wakeUpExtFlash() /* These #defines allow us to reuse TI-RTOS across other device families */ #define Board_ADC0 CC1350STK_ADC0 #define Board_ADC1 CC1350STK_ADC1 #define Board_ADCBUF0 CC1350STK_ADCBUF0 #define Board_ADCBUF0CHANNEL0 CC1350STK_ADCBUF0CHANNEL0 #define Board_ADCBUF0CHANNEL1 CC1350STK_ADCBUF0CHANNEL1 #define Board_CRYPTO0 CC1350STK_CRYPTO0 #define Board_AESCCM0 CC1350STK_AESCCM0 #define Board_AESGCM0 CC1350STK_AESGCM0 #define Board_AESCBC0 CC1350STK_AESCBC0 #define Board_AESCTR0 CC1350STK_AESCTR0 #define Board_AESECB0 CC1350STK_AESECB0 #define Board_AESCTRDRBG0 CC1350STK_AESCTRDRBG0 #define Board_TRNG0 CC1350STK_TRNG0 #define Board_DIO16_TDO CC1350STK_DIO16_TDO #define Board_DIO17_TDI CC1350STK_DIO17_TDI #define Board_DIO22 CC1350STK_DIO22 #define Board_DIO23_ANALOG CC1350STK_DIO23_ANALOG #define Board_DIO24_ANALOG CC1350STK_DIO24_ANALOG #define Board_DIO25_ANALOG CC1350STK_DIO25_ANALOG #define Board_DIO26_ANALOG CC1350STK_DIO26_ANALOG #define Board_DIO27_ANALOG CC1350STK_DIO27_ANALOG #define Board_DIO28_ANALOG CC1350STK_DIO28_ANALOG #define Board_DIO29_ANALOG CC1350STK_DIO29_ANALOG #define Board_DIO30_ANALOG CC1350STK_DIO30_ANALOG #define Board_GPIO_BUTTON0 CC1350STK_GPIO_S1 #define Board_GPIO_BUTTON1 CC1350STK_GPIO_S2 #define Board_GPIO_BTN1 CC1350STK_GPIO_S1 #define Board_GPIO_BTN2 CC1350STK_GPIO_S2 #define Board_GPIO_LED0 CC1350STK_GPIO_LED_RED #define Board_GPIO_LED1 CC1350STK_GPIO_LED_RED #define Board_GPIO_RLED CC1350STK_GPIO_LED_RED #define Board_GPIO_LED_ON CC1350STK_GPIO_LED_ON #define Board_GPIO_LED_OFF CC1350STK_GPIO_LED_OFF #define Board_GPTIMER0A CC1350STK_GPTIMER0A #define Board_GPTIMER0B CC1350STK_GPTIMER0B #define Board_GPTIMER1A CC1350STK_GPTIMER1A #define Board_GPTIMER1B CC1350STK_GPTIMER1B #define Board_GPTIMER2A CC1350STK_GPTIMER2A #define Board_GPTIMER2B CC1350STK_GPTIMER2B #define Board_GPTIMER3A CC1350STK_GPTIMER3A #define Board_GPTIMER3B CC1350STK_GPTIMER3B #define Board_NVSINTERNAL CC1350STK_NVSCC26XX0 #define Board_NVSEXTERNAL CC1350STK_NVSSPI25X0 #define Board_I2C0 CC1350STK_I2C0 #define Board_I2C1 CC1350STK_I2C1 #define Board_PIN_BUTTON0 CC1350STK_PIN_BTN1 #define Board_PIN_BUTTON1 CC1350STK_PIN_BTN2 #define Board_PIN_BTN1 CC1350STK_PIN_BTN1 #define Board_PIN_BTN2 CC1350STK_PIN_BTN2 #define Board_PIN_LED0 CC1350STK_PIN_RLED #define Board_PIN_LED1 CC1350STK_PIN_RLED #define Board_PIN_LED2 CC1350STK_PIN_RLED #define Board_PIN_RLED CC1350STK_PIN_RLED #define Board_KEY_LEFT CC1350STK_KEY_LEFT #define Board_KEY_RIGHT CC1350STK_KEY_RIGHT #define Board_RELAY CC1350STK_RELAY #define Board_BUZZER CC1350STK_BUZZER #define Board_BUZZER_ON CC1350STK_LED_ON #define Board_BUZZER_OFF CC1350STK_LED_OFF #define Board_MIC_POWER CC1350STK_MIC_POWER #define Board_MIC_POWER_OM CC1350STK_MIC_POWER_ON #define Board_MIC_POWER_OFF CC1350STK_MIC_POWER_OFF #define Board_MPU_INT CC1350STK_MPU_INT #define Board_MPU_POWER CC1350STK_MPU_POWER #define Board_MPU_POWER_OFF CC1350STK_MPU_POWER_OFF #define Board_MPU_POWER_ON CC1350STK_MPU_POWER_ON #define Board_TMP_RDY CC1350STK_TMP_RDY #define Board_I2S0 CC1350STK_I2S0 #define Board_I2S_ADO CC1350STK_I2S_ADO #define Board_I2S_ADI CC1350STK_I2S_ADI #define Board_I2S_BCLK CC1350STK_I2S_BCLK #define Board_I2S_MCLK CC1350STK_I2S_MCLK #define Board_I2S_WCLK CC1350STK_I2S_WCLK #define Board_PWM0 CC1350STK_PWM0 #define Board_PWM1 CC1350STK_PWM0 #define Board_PWM2 CC1350STK_PWM2 #define Board_PWM3 CC1350STK_PWM3 #define Board_PWM4 CC1350STK_PWM4 #define Board_PWM5 CC1350STK_PWM5 #define Board_PWM6 CC1350STK_PWM6 #define Board_PWM7 CC1350STK_PWM7 #define Board_SPI0 CC1350STK_SPI0 #define Board_SPI0_MISO CC1350STK_SPI0_MISO #define Board_SPI0_MOSI CC1350STK_SPI0_MOSI #define Board_SPI0_CLK CC1350STK_SPI0_CLK #define Board_SPI0_CSN CC1350STK_SPI0_CSN #define Board_SPI1 CC1350STK_SPI1 #define Board_SPI1_MISO CC1350STK_SPI1_MISO #define Board_SPI1_MOSI CC1350STK_SPI1_MOSI #define Board_SPI1_CLK CC1350STK_SPI1_CLK #define Board_SPI1_CSN CC1350STK_SPI1_CSN #define Board_SPI_FLASH_CS CC1350STK_SPI_FLASH_CS #define Board_FLASH_CS_ON (0) #define Board_FLASH_CS_OFF (1) #define Board_UART0 CC1350STK_UART0 #define Board_WATCHDOG0 CC1350STK_WATCHDOG0 /* Board specific I2C addresses */ #define Board_BMP280_ADDR (0x77) #define Board_HDC1000_ADDR (0x43) #define Board_MPU9250_ADDR (0x68) #define Board_MPU9250_MAG_ADDR (0x0C) #define Board_OPT3001_ADDR (0x45) #define Board_TMP_ADDR (0x44) #ifdef __cplusplus } #endif #endif /* __BOARD_H */
84a559b917aab438c164b1fe05270d244b7eba45
c8abb7c0a610348eb0b8474ce66463584ec5bc98
/Public/Src/Sandbox/Windows/DetoursServices/DetouredFunctionTypes.h
cd1de7220abd7a0cae8f1354ea903e573ddc4629
[ "MIT" ]
permissive
microsoft/BuildXL
d31b74ba23057dd251bcd9040390a7e751f04fae
f884dd1e34ed50f76d27d3fb1b8679235995653d
refs/heads/main
2023-08-31T21:19:44.385093
2023-08-30T23:36:57
2023-08-30T23:36:57
152,813,045
436
114
MIT
2023-09-13T09:49:08
2018-10-12T22:16:45
C#
UTF-8
C
false
false
15,019
h
DetouredFunctionTypes.h
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #pragma once #include <windows.h> #include <winternl.h> // ---------------------------------------------------------------------------- // TYPE DEFINITIONS // ---------------------------------------------------------------------------- // // Function signatures for detoured functions // typedef BOOL (WINAPI *CreateProcessA_t)( __in_opt LPCSTR lpApplicationName, __inout_opt LPSTR lpCommandLine, __in_opt LPSECURITY_ATTRIBUTES lpProcessAttributes, __in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes, __in BOOL bInheritHandles, __in DWORD dwCreationFlags, __in_opt LPVOID lpEnvironment, __in_opt LPCSTR lpCurrentDirectory, __in LPSTARTUPINFOA lpStartupInfo, __out LPPROCESS_INFORMATION lpProcessInformation ); typedef BOOL (WINAPI *CreateProcessW_t)( __in_opt LPCWSTR lpApplicationName, __inout_opt LPWSTR lpCommandLine, __in_opt LPSECURITY_ATTRIBUTES lpProcessAttributes, __in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes, __in BOOL bInheritHandles, __in DWORD dwCreationFlags, __in_opt LPVOID lpEnvironment, __in_opt LPCWSTR lpCurrentDirectory, __in LPSTARTUPINFOW lpStartupInfo, __out LPPROCESS_INFORMATION lpProcessInformation ); typedef HANDLE (WINAPI *CreateFileW_t)( __in LPCWSTR lpFileName, __in DWORD dwDesiredAccess, __in DWORD dwShareMode, __in_opt LPSECURITY_ATTRIBUTES lpSecurityAttributes, __in DWORD dwCreationDisposition, __in DWORD dwFlagsAndAttributes, __in_opt HANDLE hTemplateFile ); typedef BOOLEAN (NTAPI *RtlFreeHeap_t)( _In_ PVOID HeapHandle, _In_opt_ ULONG Flags, _In_ PVOID HeapBase); typedef PVOID(NTAPI *RtlAllocateHeap_t)( _In_ PVOID HeapHandle, _In_opt_ ULONG Flags, _In_ SIZE_T Size); typedef PVOID(NTAPI *RtlReAllocateHeap_t)( _In_ PVOID HeapHandle, _In_ ULONG Flags, _In_opt_ PVOID BaseAddress, _In_ SIZE_T Size); typedef LPVOID(NTAPI *VirtualAlloc_t)( _In_opt_ LPVOID lpAddress, _In_ SIZE_T dwSize, _In_ DWORD flAllocationType, _In_ DWORD flProtect); typedef HANDLE (WINAPI *CreateFileA_t)( __in LPCSTR lpFileName, __in DWORD dwDesiredAccess, __in DWORD dwShareMode, __in_opt LPSECURITY_ATTRIBUTES lpSecurityAttributes, __in DWORD dwCreationDisposition, __in DWORD dwFlagsAndAttributes, __in_opt HANDLE hTemplateFile ); typedef BOOL (WINAPI *CloseHandle_t)( __in HANDLE handle ); typedef BOOL (WINAPI *GetVolumePathNameW_t)( __in LPCWSTR lpszFileName, __out_ecount(cchBufferLength) LPWSTR lpszVolumePathName, __in DWORD cchBufferLength ); typedef DWORD (WINAPI *GetFileAttributesW_t)( __in LPCWSTR lpFileName ); typedef DWORD (WINAPI *GetFileAttributesA_t)( __in LPCSTR lpFileName ); typedef BOOL (WINAPI *GetFileAttributesExA_t)( __in LPCSTR lpFileName, __in GET_FILEEX_INFO_LEVELS fInfoLevelId, __out LPVOID lpFileInformation ); typedef BOOL (WINAPI *GetFileAttributesExW_t)( __in LPCWSTR lpFileName, __in GET_FILEEX_INFO_LEVELS fInfoLevelId, __out LPVOID lpFileInformation ); typedef BOOL (WINAPI *CopyFileW_t)( __in LPCWSTR lpExistingFileName, __in LPCWSTR lpNewFileName, __in BOOL bFailIfExists ); typedef BOOL (WINAPI *CopyFileA_t)( __in LPCSTR lpExistingFileName, __in LPCSTR lpNewFileName, __in BOOL bFailIfExists ); typedef BOOL (WINAPI *CopyFileExW_t)( __in LPCWSTR lpExistingFileName, __in LPCWSTR lpNewFileName, __in_opt LPPROGRESS_ROUTINE lpProgressRoutine, __in_opt LPVOID lpData, __in_opt LPBOOL pbCancel, __in DWORD dwCopyFlags ); typedef BOOL (WINAPI *CopyFileExA_t)( __in LPCSTR lpExistingFileName, __in LPCSTR lpNewFileName, __in_opt LPPROGRESS_ROUTINE lpProgressRoutine, __in_opt LPVOID lpData, __in_opt LPBOOL pbCancel, __in DWORD dwCopyFlags ); typedef BOOL (WINAPI *MoveFileW_t)( __in LPCWSTR lpExistingFileName, __in LPCWSTR lpNewFileName ); typedef BOOL (WINAPI *MoveFileA_t)( __in LPCSTR lpExistingFileName, __in LPCSTR lpNewFileName ); typedef BOOL (WINAPI *MoveFileExW_t)( __in LPCWSTR lpExistingFileName, __in_opt LPCWSTR lpNewFileName, __in DWORD dwFlags ); typedef BOOL (WINAPI *MoveFileExA_t)( __in LPCSTR lpExistingFileName, __in_opt LPCSTR lpNewFileName, __in DWORD dwFlags ); typedef BOOL (WINAPI *MoveFileWithProgressW_t)( __in LPCWSTR lpExistingFileName, __in_opt LPCWSTR lpNewFileName, __in_opt LPPROGRESS_ROUTINE lpProgressRoutine, __in_opt LPVOID lpData, __in DWORD dwFlags ); typedef BOOL (WINAPI *MoveFileWithProgressA_t)( __in LPCSTR lpExistingFileName, __in_opt LPCSTR lpNewFileName, __in_opt LPPROGRESS_ROUTINE lpProgressRoutine, __in_opt LPVOID lpData, __in DWORD dwFlags ); typedef BOOL (WINAPI *ReplaceFileW_t)( __in LPCWSTR lpReplacedFileName, __in LPCWSTR lpReplacementFileName, __in_opt LPCWSTR lpBackupFileName, __in DWORD dwReplaceFlags, __reserved LPVOID lpExclude, __reserved LPVOID lpReserved ); typedef BOOL (WINAPI *ReplaceFileA_t)( __in LPCSTR lpReplacedFileName, __in LPCSTR lpReplacementFileName, __in_opt LPCSTR lpBackupFileName, __in DWORD dwReplaceFlags, __reserved LPVOID lpExclude, __reserved LPVOID lpReserved ); typedef BOOL (WINAPI *DeleteFileW_t)( __in LPCWSTR lpFileName ); typedef BOOL (WINAPI *DeleteFileA_t)( __in LPCSTR lpFileName ); typedef BOOL (WINAPI *CreateHardLinkW_t)( __in LPCWSTR lpFileName, __in LPCWSTR lpExistingFileName, __reserved LPSECURITY_ATTRIBUTES lpSecurityAttributes ); typedef BOOL (WINAPI *CreateHardLinkA_t)( __in LPCSTR lpFileName, __in LPCSTR lpExistingFileName, __reserved LPSECURITY_ATTRIBUTES lpSecurityAttributes ); typedef BOOLEAN (WINAPI *CreateSymbolicLinkW_t)( __in LPCWSTR lpSymlinkFileName, __in LPCWSTR lpTargetFileName, __in DWORD dwFlags ); typedef BOOLEAN (WINAPI *CreateSymbolicLinkA_t)( __in LPCSTR lpSymlinkFileName, __in LPCSTR lpTargetFileName, __in DWORD dwFlags ); typedef HANDLE (WINAPI *FindFirstFileW_t)( __in LPCWSTR lpFileName, __out LPWIN32_FIND_DATAW lpFindFileData ); typedef HANDLE (WINAPI *FindFirstFileA_t)( __in LPCSTR lpFileName, __out LPWIN32_FIND_DATAA lpFindFileData ); typedef HANDLE (WINAPI *FindFirstFileExW_t)( __in LPCWSTR lpFileName, __in FINDEX_INFO_LEVELS fInfoLevelId, __out LPVOID lpFindFileData, __in FINDEX_SEARCH_OPS fSearchOp, __reserved LPVOID lpSearchFilter, __in DWORD dwAdditionalFlags ); typedef HANDLE (WINAPI *FindFirstFileExA_t)( __in LPCSTR lpFileName, __in FINDEX_INFO_LEVELS fInfoLevelId, __out LPVOID lpFindFileData, __in FINDEX_SEARCH_OPS fSearchOp, __reserved LPVOID lpSearchFilter, __in DWORD dwAdditionalFlags ); typedef BOOL (WINAPI *FindNextFileW_t)( __in HANDLE hFindFile, __out LPWIN32_FIND_DATAW lpFindFileData ); typedef BOOL (WINAPI *FindNextFileA_t)( __in HANDLE hFindFile, __out LPWIN32_FIND_DATAA lpFindFileData ); typedef BOOL(WINAPI *FindClose_t)( __in HANDLE hFindFile ); typedef BOOL (WINAPI *GetFileInformationByHandleEx_t)( __in HANDLE hFile, __in FILE_INFO_BY_HANDLE_CLASS FileInformationClass, __out LPVOID lpFileInformation, __in DWORD dwBufferSize ); typedef BOOL(WINAPI *GetFileInformationByHandle_t)( __in HANDLE hFile, __out LPBY_HANDLE_FILE_INFORMATION lpFileInformation ); typedef BOOL (WINAPI *SetFileInformationByHandle_t)( __in HANDLE hFile, __in FILE_INFO_BY_HANDLE_CLASS FileInformationClass, __in LPVOID lpFileInformation, __in DWORD dwBufferSize ); typedef HANDLE (WINAPI *OpenFileMappingW_t)( __in DWORD dwDesiredAccess, __in BOOL bInheritHandle, __in LPCWSTR lpName ); typedef HANDLE (WINAPI *OpenFileMappingA_t)( __in DWORD dwDesiredAccess, __in BOOL bInheritHandle, __in LPCSTR lpName ); typedef UINT (WINAPI *GetTempFileNameW_t)( __in LPCWSTR lpPathName, __in LPCWSTR lpPrefixString, __in UINT uUnique, __out LPWSTR lpTempFileName ); typedef UINT (WINAPI *GetTempFileNameA_t)( __in LPCSTR lpPathName, __in LPCSTR lpPrefixString, __in UINT uUnique, __out LPSTR lpTempFileName ); typedef BOOL (WINAPI *CreateDirectoryW_t)( __in LPCWSTR lpPathName, __in_opt LPSECURITY_ATTRIBUTES lpSecurityAttributes ); typedef BOOL (WINAPI *CreateDirectoryA_t)( __in LPCSTR lpPathName, __in_opt LPSECURITY_ATTRIBUTES lpSecurityAttributes ); typedef BOOL (WINAPI *CreateDirectoryExW_t)( __in LPCWSTR lpTemplateDirectory, __in LPCWSTR lpNewDirectory, __in_opt LPSECURITY_ATTRIBUTES lpSecurityAttributes ); typedef BOOL (WINAPI *CreateDirectoryExA_t)( __in LPCSTR lpTemplateDirectory, __in LPCSTR lpNewDirectory, __in_opt LPSECURITY_ATTRIBUTES lpSecurityAttributes ); typedef BOOL (WINAPI *RemoveDirectoryW_t)( __in LPCWSTR lpPathName ); typedef BOOL (WINAPI *RemoveDirectoryA_t)( __in LPCSTR lpPathName ); typedef BOOL (WINAPI *DecryptFileW_t)( __in LPCWSTR lpFileName, __reserved DWORD dwReserved ); typedef BOOL (WINAPI *DecryptFileA_t)( __in LPCSTR lpFileName, __reserved DWORD dwReserved ); typedef BOOL (WINAPI *EncryptFileW_t)( __in LPCWSTR lpFileName ); typedef BOOL (WINAPI *EncryptFileA_t)( __in LPCSTR lpFileName ); typedef DWORD (WINAPI *OpenEncryptedFileRawW_t)( __in LPCWSTR lpFileName, __in ULONG ulFlags, __out PVOID *pvContext ); typedef DWORD (WINAPI *OpenEncryptedFileRawA_t)( __in LPCSTR lpFileName, __in ULONG ulFlags, __out PVOID *pvContext ); typedef HANDLE (WINAPI *OpenFileById_t)( __in HANDLE hFile, __in LPFILE_ID_DESCRIPTOR lpFileID, __in DWORD dwDesiredAccess, __in DWORD dwShareMode, __in_opt LPSECURITY_ATTRIBUTES lpSecurityAttributes, __in DWORD dwFlags ); typedef DWORD(WINAPI *GetFinalPathNameByHandleW_t)( __in HANDLE hFile, __out LPTSTR lpszFilePath, __in DWORD cchFilePath, __in DWORD dwFlags ); typedef DWORD(WINAPI *GetFinalPathNameByHandleA_t)( __in HANDLE hFile, __out LPSTR lpszFilePath, __in DWORD cchFilePath, __in DWORD dwFlags ); typedef NTSTATUS (NTAPI *NtQueryDirectoryFile_t)( __in HANDLE FileHandle, __in_opt HANDLE Event, __in_opt PIO_APC_ROUTINE ApcRoutine, __in_opt PVOID ApcContext, __out PIO_STATUS_BLOCK IoStatusBlock, __out_bcount(Length) PVOID FileInformation, __in ULONG Length, __in FILE_INFORMATION_CLASS FileInformationClass, __in BOOLEAN ReturnSingleEntry, __in_opt PUNICODE_STRING FileName, __in BOOLEAN RestartScan ); typedef NTSTATUS(NTAPI *ZwQueryDirectoryFile_t)( __in HANDLE FileHandle, __in_opt HANDLE Event, __in_opt PIO_APC_ROUTINE ApcRoutine, __in_opt PVOID ApcContext, __out PIO_STATUS_BLOCK IoStatusBlock, __out_bcount(Length) PVOID FileInformation, __in ULONG Length, __in FILE_INFORMATION_CLASS FileInformationClass, __in BOOLEAN ReturnSingleEntry, __in_opt PUNICODE_STRING FileName, __in BOOLEAN RestartScan ); typedef NTSTATUS(NTAPI *NtCreateFile_t)( __out PHANDLE FileHandle, __in ACCESS_MASK DesiredAccess, __in POBJECT_ATTRIBUTES ObjectAttributes, __out PIO_STATUS_BLOCK IoStatusBlock, __in_opt PLARGE_INTEGER AllocationSize, __in ULONG FileAttributes, __in ULONG ShareAccess, __in ULONG CreateDisposition, __in ULONG CreateOptions, __in_opt PVOID EaBuffer, __in ULONG EaLength ); typedef NTSTATUS(NTAPI *NtOpenFile_t)( __out PHANDLE FileHandle, __in ACCESS_MASK DesiredAccess, __in POBJECT_ATTRIBUTES ObjectAttributes, __out PIO_STATUS_BLOCK IoStatusBlock, __in ULONG ShareAccess, __in ULONG OpenOptions ); typedef NTSTATUS(NTAPI *ZwCreateFile_t)( __out PHANDLE FileHandle, __in ACCESS_MASK DesiredAccess, __in POBJECT_ATTRIBUTES ObjectAttributes, __out PIO_STATUS_BLOCK IoStatusBlock, __in_opt PLARGE_INTEGER AllocationSize, __in ULONG FileAttributes, __in ULONG ShareAccess, __in ULONG CreateDisposition, __in ULONG CreateOptions, __in_opt PVOID EaBuffer, __in ULONG EaLength ); typedef NTSTATUS(NTAPI *ZwOpenFile_t)( __out PHANDLE FileHandle, __in ACCESS_MASK DesiredAccess, __in POBJECT_ATTRIBUTES ObjectAttributes, __out PIO_STATUS_BLOCK IoStatusBlock, __in ULONG ShareAccess, __in ULONG OpenOptions ); typedef NTSTATUS(NTAPI *ZwSetInformationFile_t)( _In_ HANDLE FileHandle, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _In_ PVOID FileInformation, _In_ ULONG Length, _In_ FILE_INFORMATION_CLASS FileInformationClass ); typedef NTSTATUS(NTAPI *NtClose_t)( __in HANDLE Handle ); typedef BOOL(WINAPI* CreatePipe_t)( _Out_ PHANDLE hReadPipe, _Out_ PHANDLE hWritePipe, _In_opt_ LPSECURITY_ATTRIBUTES lpPipeAttributes, _In_ DWORD nSize ); typedef BOOL(WINAPI* DeviceIoControl_t)( _In_ HANDLE hDevice, _In_ DWORD dwIoControlCode, _In_opt_ LPVOID lpInBuffer, _In_ DWORD nInBufferSize, _Out_ LPVOID lpOutBuffer, _In_ DWORD nOutBufferSize, _Out_ LPDWORD lpBytesReturned, _Out_ LPOVERLAPPED lpOverlapped );
786878ff609441e11ac5c116556683880de52ef2
6f8bf483b372d8bd526698a083309edb50b0bd90
/libs/sokol/sokol-noentry.c
65abd7605d43359c8423e3d47fe5e90d849990dc
[ "MIT" ]
permissive
floooh/sokol-samples
d48466f0da1b07c57b98733827074289faa335c9
578d71daed073dbeb2e5e3d74a3485cf46733cd7
refs/heads/master
2023-08-31T04:06:28.791638
2023-07-26T19:31:00
2023-07-26T19:31:00
97,253,410
496
100
MIT
2023-07-26T19:31:01
2017-07-14T16:29:50
C
UTF-8
C
false
false
241
c
sokol-noentry.c
#define SOKOL_IMPL #define SOKOL_NO_ENTRY /* sokol 3D-API defines are provided by build options */ #include "sokol_app.h" #include "sokol_gfx.h" #include "sokol_time.h" #include "sokol_audio.h" #include "sokol_log.h" #include "sokol_glue.h"
fb78cc472c5db1ea433744bee12a7fc2ca727ede
99bdb3251fecee538e0630f15f6574054dfc1468
/bsp/imxrt/libraries/MIMXRT1170/MIMXRT1176/drivers/fsl_enet_qos.c
37c09c764a8f1f0bbe4c605dc1fbce52ac22903c
[ "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
137,754
c
fsl_enet_qos.c
/* * Copyright 2019-2022 NXP * All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #include "fsl_enet_qos.h" /******************************************************************************* * Definitions ******************************************************************************/ /* Component ID definition, used by tools. */ #ifndef FSL_COMPONENT_ID #define FSL_COMPONENT_ID "platform.drivers.enet_qos" #endif /*! @brief Defines 10^9 nanosecond. */ #define ENET_QOS_NANOSECS_ONESECOND (1000000000U) /*! @brief Defines 10^6 microsecond.*/ #define ENET_QOS_MICRSECS_ONESECOND (1000000U) /*! @brief Rx buffer LSB ignore bits. */ #define ENET_QOS_RXBUFF_IGNORELSB_BITS (3U) /*! @brief ENET FIFO size unit. */ #define ENET_QOS_FIFOSIZE_UNIT (256U) /*! @brief ENET half-dulpex default IPG. */ #define ENET_QOS_HALFDUPLEX_DEFAULTIPG (4U) /*! @breif ENET miminum ring length. */ #define ENET_QOS_MIN_RINGLEN (4U) /*! @breif ENET wakeup filter numbers. */ #define ENET_QOS_WAKEUPFILTER_NUM (8U) /*! @breif Requried systime timer frequency. */ #define ENET_QOS_SYSTIME_REQUIRED_CLK_MHZ (50U) /*! @brief Ethernet VLAN tag length. */ #define ENET_QOS_FRAME_VLAN_TAGLEN 4U /*! @brief AVB TYPE */ #define ENET_QOS_AVBTYPE 0x22F0U #define ENET_QOS_HEAD_TYPE_OFFSET (12) #define ENET_QOS_HEAD_AVBTYPE_OFFSET (16) /*! @brief Defines the macro for converting constants from host byte order to network byte order. */ #define ENET_QOS_HTONS(n) __REV16(n) #define ENET_QOS_HTONL(n) __REV(n) #define ENET_QOS_NTOHS(n) __REV16(n) #define ENET_QOS_NTOHL(n) __REV(n) #define ENET_QOS_DMA_CHX_RX_CTRL_RBSZ /******************************************************************************* * Prototypes ******************************************************************************/ /*! @brief Mask the cache management code if cache control is disabled. */ #if !defined(FSL_ETH_ENABLE_CACHE_CONTROL) #define ENET_QOS_DcacheInvalidateByRange(address, sizeByte) #else #define ENET_QOS_DcacheInvalidateByRange(address, sizeByte) DCACHE_InvalidateByRange(address, sizeByte) #endif /*! * @brief Increase the index in the ring. * * @param index The current index. * @param max The size. * @return the increased index. */ static uint16_t ENET_QOS_IncreaseIndex(uint16_t index, uint16_t max); /*! * @brief Poll status flag. * * @param regAddr The register address to read out status * @param mask The mask to operate the register value. * @param readyStatus Indicate readyStatus for the field * @retval kStatus_Success Poll readyStatus Success. * @retval kStatus_ENET_QOS_Timeout Poll readyStatus timeout. */ static status_t ENET_QOS_PollStatusFlag(volatile uint32_t *regAddr, uint32_t mask, uint32_t readyStatus); /*! * @brief Set ENET DMA controller with the configuration. * * @param base ENET peripheral base address. * @param config ENET Mac configuration. */ static void ENET_QOS_SetDMAControl(ENET_QOS_Type *base, const enet_qos_config_t *config); /*! * @brief Set ENET MAC controller with the configuration. * * @param base ENET peripheral base address. * @param config ENET Mac configuration. * @param macAddr ENET six-byte mac address. */ static void ENET_QOS_SetMacControl(ENET_QOS_Type *base, const enet_qos_config_t *config, uint8_t *macAddr, uint8_t macCount); /*! * @brief Set ENET MTL with the configuration. * * @param base ENET peripheral base address. * @param config ENET Mac configuration. */ static void ENET_QOS_SetMTL(ENET_QOS_Type *base, const enet_qos_config_t *config); /*! * @brief Set ENET DMA transmit buffer descriptors for one channel. * * @param base ENET peripheral base address. * @param bufferConfig ENET buffer configuration. * @param intTxEnable tx interrupt enable. * @param channel The channel number, 0 , 1. */ static status_t ENET_QOS_TxDescriptorsInit(ENET_QOS_Type *base, const enet_qos_buffer_config_t *bufferConfig, bool intTxEnable, uint8_t channel); /*! * @brief Set ENET DMA receive buffer descriptors for one channel. * * @param base ENET peripheral base address. * @param bufferConfig ENET buffer configuration. * @param intRxEnable tx interrupt enable. * @param channel The channel number, 0, 1. */ static status_t ENET_QOS_RxDescriptorsInit(ENET_QOS_Type *base, enet_qos_config_t *config, const enet_qos_buffer_config_t *bufferConfig, bool intRxEnable, uint8_t channel); /*! * @brief Sets the ENET 1588 feature. * * Enable the enhacement 1588 buffer descriptor mode and start * the 1588 timer. * * @param base ENET peripheral base address. * @param config The ENET configuration. * @param refClk_Hz The reference clock for ptp 1588. */ static status_t ENET_QOS_SetPtp1588(ENET_QOS_Type *base, const enet_qos_config_t *config, uint32_t refClk_Hz); /*! * @brief Store the receive time-stamp for event PTP frame in the time-stamp buffer ring. * * @param base ENET peripheral base address. * @param handle ENET handler. * @param rxDesc The ENET receive descriptor pointer. * @param channel The rx channel. * @param ts The timestamp structure pointer. */ static void ENET_QOS_StoreRxFrameTime(ENET_QOS_Type *base, enet_qos_handle_t *handle, enet_qos_rx_bd_struct_t *rxDesc, // uint8_t channel, enet_qos_ptp_time_t *ts); /*! * @brief Check if txDirtyRing available. * * @param txDirtyRing pointer to txDirtyRing * @retval txDirty available status. */ static inline bool ENET_QOS_TxDirtyRingAvailable(enet_qos_tx_dirty_ring_t *txDirtyRing); /******************************************************************************* * Variables ******************************************************************************/ /*! @brief Pointers to enet bases for each instance. */ static ENET_QOS_Type *const s_enetqosBases[] = ENET_QOS_BASE_PTRS; /*! @brief Pointers to enet IRQ number for each instance. */ static const IRQn_Type s_enetqosIrqId[] = ENET_QOS_IRQS; /* ENET ISR for transactional APIs. */ static enet_qos_isr_t s_enetqosIsr; /*! @brief Pointers to enet handles for each instance. */ static enet_qos_handle_t *s_ENETHandle[ARRAY_SIZE(s_enetqosBases)] = {NULL}; #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) /*! @brief Pointers to enet clocks for each instance. */ const clock_ip_name_t s_enetqosClock[ARRAY_SIZE(s_enetqosBases)] = ENETQOS_CLOCKS; #endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ /******************************************************************************* * Code ******************************************************************************/ static status_t ENET_QOS_PollStatusFlag(volatile uint32_t *regAddr, uint32_t mask, uint32_t readyStatus) { uint8_t retryTimes = 10U; status_t result = kStatus_Success; while ((readyStatus != (*regAddr & mask)) && (0U != retryTimes)) { retryTimes--; SDK_DelayAtLeastUs(1U, SDK_DEVICE_MAXIMUM_CPU_CLOCK_FREQUENCY); } if (retryTimes == 0U) { result = kStatus_ENET_QOS_Timeout; } return result; } /*! * brief Sets the ENET AVB feature. * * ENET_QOS AVB feature configuration, set transmit bandwidth. * This API is called when the AVB feature is required. * * param base ENET_QOS peripheral base address. * param config The ENET_QOS AVB feature configuration structure. * param queueIndex ENET_QOS queue index. */ void ENET_QOS_AVBConfigure(ENET_QOS_Type *base, const enet_qos_cbs_config_t *config, uint8_t queueIndex) { assert(config != NULL); /* Enable AV algorithm */ base->MTL_QUEUE[queueIndex].MTL_TXQX_ETS_CTRL |= ENET_QOS_MTL_TXQX_ETS_CTRL_AVALG_MASK; /* Configure send slope */ base->MTL_QUEUE[queueIndex].MTL_TXQX_SNDSLP_CRDT = config->sendSlope; /* Configure idle slope (same register as tx weight) */ base->MTL_QUEUE[queueIndex].MTL_TXQX_QNTM_WGHT = config->idleSlope; /* Configure high credit */ base->MTL_QUEUE[queueIndex].MTL_TXQX_HI_CRDT = config->highCredit; /* Configure high credit */ base->MTL_QUEUE[queueIndex].MTL_TXQX_LO_CRDT = config->lowCredit; } static uint16_t ENET_QOS_IncreaseIndex(uint16_t index, uint16_t max) { /* Increase the index. */ index++; if (index >= max) { index = 0; } return index; } static uint32_t ENET_QOS_ReverseBits(uint32_t value) { value = ((value & 0x55555555UL) << 1U) | ((value >> 1U) & 0x55555555UL); value = ((value & 0x33333333UL) << 2U) | ((value >> 2U) & 0x33333333UL); value = ((value & 0x0F0F0F0FUL) << 4U) | ((value >> 4U) & 0x0F0F0F0FUL); return (value >> 24U) | ((value >> 8U) & 0xFF00UL) | ((value & 0xFF00UL) << 8U) | (value << 24U); } static void ENET_QOS_SetDMAControl(ENET_QOS_Type *base, const enet_qos_config_t *config) { assert(config != NULL); uint8_t index; uint32_t reg; uint32_t burstLen; /* Reset first and wait for the complete * The reset bit will automatically be cleared after complete. */ base->DMA_MODE |= ENET_QOS_DMA_MODE_SWR_MASK; while ((base->DMA_MODE & ENET_QOS_DMA_MODE_SWR_MASK) != 0U) { } /* Set the burst length. */ for (index = 0; index < ENET_QOS_RING_NUM_MAX; index++) { burstLen = (uint32_t)kENET_QOS_BurstLen1; if (config->multiqueueCfg != NULL) { burstLen = (uint32_t)config->multiqueueCfg->burstLen; } base->DMA_CH[index].DMA_CHX_CTRL = burstLen & ENET_QOS_DMA_CHX_CTRL_PBLx8_MASK; reg = base->DMA_CH[index].DMA_CHX_TX_CTRL & ~ENET_QOS_DMA_CHX_TX_CTRL_TxPBL_MASK; base->DMA_CH[index].DMA_CHX_TX_CTRL = reg | ENET_QOS_DMA_CHX_TX_CTRL_TxPBL(burstLen & 0x3FU); reg = base->DMA_CH[index].DMA_CHX_RX_CTRL & ~ENET_QOS_DMA_CHX_RX_CTRL_RxPBL_MASK; base->DMA_CH[index].DMA_CHX_RX_CTRL = reg | ENET_QOS_DMA_CHX_RX_CTRL_RxPBL(burstLen & 0x3FU); } } static void ENET_QOS_SetMTL(ENET_QOS_Type *base, const enet_qos_config_t *config) { assert(config != NULL); uint32_t txqOpreg = 0; uint32_t rxqOpReg = 0; enet_qos_multiqueue_config_t *multiqCfg = config->multiqueueCfg; uint8_t index; /* Set transmit operation mode. */ if ((config->specialControl & (uint32_t)kENET_QOS_StoreAndForward) != 0U) { txqOpreg = ENET_QOS_MTL_TXQX_OP_MODE_TSF_MASK; rxqOpReg = ENET_QOS_MTL_RXQX_OP_MODE_RSF_MASK; } /* Set transmit operation mode. */ txqOpreg |= ENET_QOS_MTL_TXQX_OP_MODE_FTQ_MASK; /* Set receive operation mode. */ rxqOpReg |= ENET_QOS_MTL_RXQX_OP_MODE_FUP_MASK | ENET_QOS_MTL_RXQX_OP_MODE_RFD(3U) | ENET_QOS_MTL_RXQX_OP_MODE_RFA(1U) | ENET_QOS_MTL_RXQX_OP_MODE_EHFC_MASK; if (multiqCfg == NULL) { txqOpreg |= ENET_QOS_MTL_TXQX_OP_MODE_TQS(((uint32_t)ENET_QOS_MTL_TXFIFOSIZE / (uint32_t)ENET_QOS_FIFOSIZE_UNIT - 1U)); rxqOpReg |= ENET_QOS_MTL_RXQX_OP_MODE_RQS(((uint32_t)ENET_QOS_MTL_RXFIFOSIZE / (uint32_t)ENET_QOS_FIFOSIZE_UNIT - 1U)); base->MTL_QUEUE[0].MTL_TXQX_OP_MODE = txqOpreg | ENET_QOS_MTL_TXQX_OP_MODE_TXQEN((uint32_t)kENET_QOS_DCB_Mode); base->MTL_QUEUE[0].MTL_RXQX_OP_MODE = rxqOpReg; } else { /* Set the schedule/arbitration(set for multiple queues). */ base->MTL_OPERATION_MODE = ENET_QOS_MTL_OPERATION_MODE_SCHALG(multiqCfg->mtltxSche) | ENET_QOS_MTL_OPERATION_MODE_RAA(multiqCfg->mtlrxSche); for (index = 0; index < multiqCfg->txQueueUse; index++) { txqOpreg |= ENET_QOS_MTL_TXQX_OP_MODE_TQS( ((uint32_t)ENET_QOS_MTL_TXFIFOSIZE / ((uint32_t)multiqCfg->txQueueUse * ENET_QOS_FIFOSIZE_UNIT)) - 1U); base->MTL_QUEUE[index].MTL_TXQX_OP_MODE = txqOpreg | ENET_QOS_MTL_TXQX_OP_MODE_TXQEN((uint32_t)multiqCfg->txQueueConfig[index].mode); if (multiqCfg->txQueueConfig[index].mode == kENET_QOS_AVB_Mode) { ENET_QOS_AVBConfigure(base, multiqCfg->txQueueConfig[index].cbsConfig, index); } else { base->MTL_QUEUE[index].MTL_TXQX_QNTM_WGHT = multiqCfg->txQueueConfig[index].weight; } } volatile uint32_t *mtlrxQuemapReg; uint8_t configIndex; for (index = 0; index < multiqCfg->rxQueueUse; index++) { rxqOpReg |= ENET_QOS_MTL_RXQX_OP_MODE_RQS( ((uint32_t)ENET_QOS_MTL_RXFIFOSIZE / ((uint32_t)multiqCfg->rxQueueUse * ENET_QOS_FIFOSIZE_UNIT)) - 1U); base->MTL_QUEUE[index].MTL_RXQX_OP_MODE = rxqOpReg; mtlrxQuemapReg = (index < 4U) ? &base->MTL_RXQ_DMA_MAP0 : &base->MTL_RXQ_DMA_MAP1; configIndex = (index & 0x3U); *mtlrxQuemapReg &= ~((uint32_t)ENET_QOS_MTL_RXQ_DMA_MAP0_Q0MDMACH_MASK << (8U * configIndex)); *mtlrxQuemapReg |= (uint32_t)ENET_QOS_MTL_RXQ_DMA_MAP0_Q0MDMACH(multiqCfg->rxQueueConfig[index].mapChannel) << (8U * configIndex); } } } static void ENET_QOS_SetMacControl(ENET_QOS_Type *base, const enet_qos_config_t *config, uint8_t *macAddr, uint8_t macCount) { assert(config != NULL); uint32_t reg = 0; /* Set Macaddr */ /* The dma channel 0 is set as to which the rx packet * whose DA matches the MAC address content is routed. */ if (macAddr != NULL) { for (uint8_t i = 0; i < macCount; i++) { ENET_QOS_SetMacAddr(base, macAddr, i); } } /* Set the receive filter. */ reg = ENET_QOS_MAC_PACKET_FILTER_PR(((config->specialControl & (uint32_t)kENET_QOS_PromiscuousEnable) != 0U) ? 1U : 0U) | ENET_QOS_MAC_PACKET_FILTER_DBF(((config->specialControl & (uint32_t)kENET_QOS_BroadCastRxDisable) != 0U) ? 1U : 0U) | ENET_QOS_MAC_PACKET_FILTER_PM(((config->specialControl & (uint32_t)kENET_QOS_MulticastAllEnable) != 0U) ? 1U : 0U) | ENET_QOS_MAC_PACKET_FILTER_HMC(((config->specialControl & (uint32_t)kENET_QOS_HashMulticastEnable) != 0U) ? 1U : 0U); base->MAC_PACKET_FILTER = reg; /* Flow control. */ if ((config->specialControl & (uint32_t)kENET_QOS_FlowControlEnable) != 0U) { base->MAC_RX_FLOW_CTRL = ENET_QOS_MAC_RX_FLOW_CTRL_RFE_MASK | ENET_QOS_MAC_RX_FLOW_CTRL_UP_MASK; base->MAC_TX_FLOW_CTRL_Q[0] = ENET_QOS_MAC_TX_FLOW_CTRL_Q_PT(config->pauseDuration); } /* Set the 1us ticket. */ reg = config->csrClock_Hz / ENET_QOS_MICRSECS_ONESECOND - 1U; base->MAC_ONEUS_TIC_COUNTER = ENET_QOS_MAC_ONEUS_TIC_COUNTER_TIC_1US_CNTR(reg); /* Set the speed and duplex. */ reg = ENET_QOS_MAC_CONFIGURATION_DM(config->miiDuplex) | (uint32_t)config->miiSpeed | ENET_QOS_MAC_CONFIGURATION_S2KP(((config->specialControl & (uint32_t)kENET_QOS_8023AS2KPacket) != 0U) ? 1U : 0U); if (config->miiDuplex == kENET_QOS_MiiHalfDuplex) { reg |= ENET_QOS_MAC_CONFIGURATION_IPG(ENET_QOS_HALFDUPLEX_DEFAULTIPG); } base->MAC_CONFIGURATION = reg; if (config->multiqueueCfg != NULL) { reg = 0U; uint8_t configIndex; enet_qos_multiqueue_config_t *multiqCfg = config->multiqueueCfg; uint32_t txQueuePrioMap0 = base->MAC_TXQ_PRTY_MAP0; uint32_t txQueuePrioMap1 = base->MAC_TXQ_PRTY_MAP1; uint32_t rxQueuePrioMap0 = base->MAC_RXQ_CTRL[2]; uint32_t rxQueuePrioMap1 = base->MAC_RXQ_CTRL[3]; uint32_t rxCtrlReg1 = base->MAC_RXQ_CTRL[1]; for (uint8_t index = 0U; index < multiqCfg->txQueueUse; index++) { configIndex = index & 0x3U; /* Configure tx queue priority. */ if (index < 4U) { txQueuePrioMap0 &= ~((uint32_t)ENET_QOS_MAC_TXQ_PRTY_MAP0_PSTQ0_MASK << (8U * configIndex)); txQueuePrioMap0 |= (uint32_t)ENET_QOS_MAC_TXQ_PRTY_MAP0_PSTQ0(multiqCfg->txQueueConfig[index].priority) << (8U * configIndex); } else { txQueuePrioMap1 &= ~((uint32_t)ENET_QOS_MAC_TXQ_PRTY_MAP0_PSTQ0_MASK << (8U * configIndex)); txQueuePrioMap1 |= (uint32_t)ENET_QOS_MAC_TXQ_PRTY_MAP0_PSTQ0(multiqCfg->txQueueConfig[index].priority) << (8U * configIndex); } } for (uint8_t index = 0U; index < multiqCfg->rxQueueUse; index++) { configIndex = index & 0x3U; /* Configure rx queue priority. */ if (index < 4U) { rxQueuePrioMap0 &= ~((uint32_t)ENET_QOS_MAC_RXQ_CTRL_PSRQ0_MASK << (8U * configIndex)); rxQueuePrioMap0 |= (uint32_t)ENET_QOS_MAC_RXQ_CTRL_PSRQ0(multiqCfg->rxQueueConfig[index].priority) << (8U * configIndex); } else { rxQueuePrioMap1 &= ~((uint32_t)ENET_QOS_MAC_RXQ_CTRL_PSRQ0_MASK << (8U * configIndex)); rxQueuePrioMap1 |= (uint32_t)ENET_QOS_MAC_RXQ_CTRL_PSRQ0(multiqCfg->rxQueueConfig[index].priority) << (8U * configIndex); } /* Configure queue enable mode. */ reg |= ENET_QOS_MAC_RXQ_CTRL_RXQ0EN((uint32_t)multiqCfg->rxQueueConfig[index].mode) << (2U * index); /* Configure rx queue routing */ if (((uint8_t)multiqCfg->rxQueueConfig[index].packetRoute & (uint8_t)kENET_QOS_PacketAVCPQ) != 0U) { rxCtrlReg1 &= ~ENET_QOS_MAC_RXQ_CTRL_AVCPQ_MASK; rxCtrlReg1 |= (ENET_QOS_MAC_RXQ_CTRL_AVCPQ(index) | ENET_QOS_MAC_RXQ_CTRL_TACPQE_MASK); } if (((uint8_t)multiqCfg->rxQueueConfig[index].packetRoute & (uint8_t)kENET_QOS_PacketPTPQ) != 0U) { rxCtrlReg1 &= ~ENET_QOS_MAC_RXQ_CTRL_PTPQ_MASK; rxCtrlReg1 |= ENET_QOS_MAC_RXQ_CTRL_PTPQ(index); } if (((uint8_t)multiqCfg->rxQueueConfig[index].packetRoute & (uint8_t)kENET_QOS_PacketDCBCPQ) != 0U) { rxCtrlReg1 &= ~ENET_QOS_MAC_RXQ_CTRL_DCBCPQ_MASK; rxCtrlReg1 |= ENET_QOS_MAC_RXQ_CTRL_DCBCPQ(index); } if (((uint8_t)multiqCfg->rxQueueConfig[index].packetRoute & (uint8_t)kENET_QOS_PacketUPQ) != 0U) { rxCtrlReg1 &= ~ENET_QOS_MAC_RXQ_CTRL_UPQ_MASK; rxCtrlReg1 |= ENET_QOS_MAC_RXQ_CTRL_UPQ(index); } if (((uint8_t)multiqCfg->rxQueueConfig[index].packetRoute & (uint8_t)kENET_QOS_PacketMCBCQ) != 0U) { rxCtrlReg1 &= ~ENET_QOS_MAC_RXQ_CTRL_MCBCQ_MASK; rxCtrlReg1 |= (ENET_QOS_MAC_RXQ_CTRL_MCBCQ(index) | ENET_QOS_MAC_RXQ_CTRL_MCBCQEN_MASK); } } base->MAC_TXQ_PRTY_MAP0 = txQueuePrioMap0; base->MAC_TXQ_PRTY_MAP1 = txQueuePrioMap1; base->MAC_RXQ_CTRL[2] = rxQueuePrioMap0; base->MAC_RXQ_CTRL[3] = rxQueuePrioMap1; base->MAC_RXQ_CTRL[1] = rxCtrlReg1; } else { /* Configure queue enable mode. */ reg = ENET_QOS_MAC_RXQ_CTRL_RXQ0EN((uint32_t)kENET_QOS_DCB_Mode); } /* Enable queue. */ base->MAC_RXQ_CTRL[0] = reg; /* Mask MMC counters interrupts as we don't handle * them in the interrupt handler. */ base->MAC_MMC_RX_INTERRUPT_MASK = 0xFFFFFFFFU; base->MAC_MMC_TX_INTERRUPT_MASK = 0xFFFFFFFFU; base->MAC_MMC_IPC_RX_INTERRUPT_MASK = 0xFFFFFFFFU; base->MAC_MMC_FPE_RX_INTERRUPT_MASK = 0xFFFFFFFFU; base->MAC_MMC_FPE_TX_INTERRUPT_MASK = 0xFFFFFFFFU; } static status_t ENET_QOS_TxDescriptorsInit(ENET_QOS_Type *base, const enet_qos_buffer_config_t *bufferConfig, bool intTxEnable, uint8_t channel) { uint16_t j; enet_qos_tx_bd_struct_t *txbdPtr; uint32_t control = intTxEnable ? ENET_QOS_TXDESCRIP_RD_IOC_MASK : 0U; const enet_qos_buffer_config_t *buffCfg = bufferConfig; uint32_t txDescAddr, txDescTail; if (buffCfg == NULL) { return kStatus_InvalidArgument; } /* Check the ring length. */ if (buffCfg->txRingLen < ENET_QOS_MIN_RINGLEN) { return kStatus_InvalidArgument; } /* Set the tx descriptor start/tail pointer, shall be word aligned. */ txDescAddr = (uint32_t)(uintptr_t)buffCfg->txDescStartAddrAlign & ENET_QOS_DMA_CHX_TXDESC_LIST_ADDR_TDESLA_MASK; txDescTail = (uint32_t)(uintptr_t)buffCfg->txDescTailAddrAlign & ENET_QOS_DMA_CHX_TXDESC_TAIL_PTR_TDTP_MASK; #if defined(FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET) && FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET txDescAddr = MEMORY_ConvertMemoryMapAddress(txDescAddr, kMEMORY_Local2DMA); txDescTail = MEMORY_ConvertMemoryMapAddress(txDescTail, kMEMORY_Local2DMA); #endif base->DMA_CH[channel].DMA_CHX_TXDESC_LIST_ADDR = txDescAddr; base->DMA_CH[channel].DMA_CHX_TXDESC_TAIL_PTR = txDescTail; /* Set the tx ring length. */ base->DMA_CH[channel].DMA_CHX_TXDESC_RING_LENGTH = ((uint32_t)buffCfg->txRingLen - 1U) & ENET_QOS_DMA_CHX_TXDESC_RING_LENGTH_TDRL_MASK; /* Init the txbdPtr to the transmit descriptor start address. */ txbdPtr = (enet_qos_tx_bd_struct_t *)(buffCfg->txDescStartAddrAlign); for (j = 0; j < buffCfg->txRingLen; j++) { txbdPtr->buff1Addr = 0; txbdPtr->buff2Addr = 0; txbdPtr->buffLen = control; txbdPtr->controlStat = 0; txbdPtr++; } return kStatus_Success; } static status_t ENET_QOS_RxDescriptorsInit(ENET_QOS_Type *base, enet_qos_config_t *config, const enet_qos_buffer_config_t *bufferConfig, bool intRxEnable, uint8_t channel) { uint16_t j; uint32_t reg; enet_qos_rx_bd_struct_t *rxbdPtr; uint16_t index; bool doubleBuffEnable = ((config->specialControl & (uint32_t)kENET_QOS_DescDoubleBuffer) != 0U) ? true : false; const enet_qos_buffer_config_t *buffCfg = bufferConfig; uint32_t control = ENET_QOS_RXDESCRIP_RD_BUFF1VALID_MASK; uint32_t rxDescAddr, rxDescTail; if (buffCfg == NULL) { return kStatus_InvalidArgument; } if (intRxEnable) { control |= ENET_QOS_RXDESCRIP_RD_IOC_MASK; } if (doubleBuffEnable) { control |= ENET_QOS_RXDESCRIP_RD_BUFF2VALID_MASK; } /* Not give ownership to DMA before Rx buffer is ready */ if ((config->rxBuffAlloc == NULL) || (config->rxBuffFree == NULL)) { control |= ENET_QOS_RXDESCRIP_WR_OWN_MASK; } /* Check the ring length. */ if (buffCfg->rxRingLen < ENET_QOS_MIN_RINGLEN) { return kStatus_InvalidArgument; } /* Set the rx descriptor start/tail pointer, shall be word aligned. */ rxDescAddr = (uint32_t)(uintptr_t)buffCfg->rxDescStartAddrAlign & ENET_QOS_DMA_CHX_RXDESC_LIST_ADDR_RDESLA_MASK; rxDescTail = (uint32_t)(uintptr_t)buffCfg->rxDescTailAddrAlign & ENET_QOS_DMA_CHX_RXDESC_TAIL_PTR_RDTP_MASK; #if defined(FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET) && FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET rxDescAddr = MEMORY_ConvertMemoryMapAddress(rxDescAddr, kMEMORY_Local2DMA); rxDescTail = MEMORY_ConvertMemoryMapAddress(rxDescTail, kMEMORY_Local2DMA); #endif base->DMA_CH[channel].DMA_CHX_RXDESC_LIST_ADDR = rxDescAddr; base->DMA_CH[channel].DMA_CHX_RXDESC_TAIL_PTR = rxDescTail; /* Register DMA_CHX_RXDESC_RING_LENGTH renamed to DMA_CHX_RX_CONTROL2 */ #if defined(ENET_QOS_DMA_CHX_RX_CONTROL2_COUNT) && ENET_QOS_DMA_CHX_RX_CONTROL2_COUNT base->DMA_CH[channel].DMA_CHX_RX_CONTROL2 = ((uint32_t)buffCfg->rxRingLen - 1U) & ENET_QOS_DMA_CHX_RX_CONTROL2_RDRL_MASK; #else base->DMA_CH[channel].DMA_CHX_RXDESC_RING_LENGTH = ((uint32_t)buffCfg->rxRingLen - 1U) & ENET_QOS_DMA_CHX_RXDESC_RING_LENGTH_RDRL_MASK; #endif reg = base->DMA_CH[channel].DMA_CHX_RX_CTRL & ~ENET_QOS_DMA_CHX_RX_CTRL_RBSZ_13_y_MASK; reg |= ENET_QOS_DMA_CHX_RX_CTRL_RBSZ_13_y(buffCfg->rxBuffSizeAlign >> ENET_QOS_RXBUFF_IGNORELSB_BITS); base->DMA_CH[channel].DMA_CHX_RX_CTRL = reg; /* Init the rxbdPtr to the receive descriptor start address. */ rxbdPtr = (enet_qos_rx_bd_struct_t *)(buffCfg->rxDescStartAddrAlign); for (j = 0U; j < buffCfg->rxRingLen; j++) { if ((config->rxBuffAlloc == NULL) || (config->rxBuffFree == NULL)) { if (doubleBuffEnable) { index = 2U * j; } else { index = j; } #if defined(FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET) && FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET buffCfg->rxBufferStartAddr[index] = MEMORY_ConvertMemoryMapAddress((uintptr_t)buffCfg->rxBufferStartAddr[index], kMEMORY_Local2DMA); #endif rxbdPtr->buff1Addr = buffCfg->rxBufferStartAddr[index]; /* The second buffer is set with 0 because it is not required for normal case. */ if (doubleBuffEnable) { #if defined(FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET) && FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET buffCfg->rxBufferStartAddr[index + 1U] = MEMORY_ConvertMemoryMapAddress( (uintptr_t)buffCfg->rxBufferStartAddr[index + 1U], kMEMORY_Local2DMA); #endif rxbdPtr->buff2Addr = buffCfg->rxBufferStartAddr[index + 1U]; } else { rxbdPtr->buff2Addr = 0; } } /* Set the valid and DMA own flag.*/ rxbdPtr->control = control; rxbdPtr++; } return kStatus_Success; } static status_t ENET_QOS_SetPtp1588(ENET_QOS_Type *base, const enet_qos_config_t *config, uint32_t refClk_Hz) { assert(config != NULL); assert(config->ptpConfig != NULL); assert(refClk_Hz != 0U); uint32_t control = 0U; status_t result = kStatus_Success; enet_qos_ptp_config_t *ptpConfig = config->ptpConfig; uint32_t ptpClk_Hz = refClk_Hz; uint32_t ssInc, snsSinc; /* Clear the timestamp interrupt first. */ base->MAC_INTERRUPT_ENABLE &= ~ENET_QOS_MAC_INTERRUPT_ENABLE_TSIE_MASK; if (ptpConfig->fineUpdateEnable) { control |= ENET_QOS_MAC_TIMESTAMP_CONTROL_TSCFUPDT_MASK; ptpClk_Hz = ptpConfig->systemTimeClock_Hz; /* PTP clock 50MHz. */ } /* Enable the IEEE 1588 timestamping and snapshot for event message. */ control |= ENET_QOS_MAC_TIMESTAMP_CONTROL_TSENA_MASK | ENET_QOS_MAC_TIMESTAMP_CONTROL_TSIPV4ENA_MASK | ENET_QOS_MAC_TIMESTAMP_CONTROL_TSIPV6ENA_MASK | ENET_QOS_MAC_TIMESTAMP_CONTROL_TSENALL_MASK | ENET_QOS_MAC_TIMESTAMP_CONTROL_TSEVNTENA_MASK | ENET_QOS_MAC_TIMESTAMP_CONTROL_SNAPTYPSEL_MASK | ENET_QOS_MAC_TIMESTAMP_CONTROL_TSCTRLSSR(ptpConfig->tsRollover); if (ptpConfig->ptp1588V2Enable) { control |= ENET_QOS_MAC_TIMESTAMP_CONTROL_TSVER2ENA_MASK | ENET_QOS_MAC_TIMESTAMP_CONTROL_TSIPENA_MASK; } /* Initialize the sub-second increment register. */ if (ptpConfig->tsRollover == kENET_QOS_DigitalRollover) { ssInc = (uint32_t)(((uint64_t)ENET_QOS_NANOSECS_ONESECOND << 8U) / ptpClk_Hz); } else { ssInc = (uint32_t)((((uint64_t)ENET_QOS_MAC_SYSTEM_TIME_NANOSECONDS_TSSS_MASK + 1U) << 8U) / ptpClk_Hz); } snsSinc = ssInc & 0xFFU; ssInc = (ssInc >> 8U) & 0xFFU; base->MAC_TIMESTAMP_CONTROL = control; /* Initialize the system timer. */ base->MAC_SYSTEM_TIME_NANOSECONDS_UPDATE = 0; /* Set the second.*/ base->MAC_SYSTEM_TIME_SECONDS_UPDATE = 0; base->MAC_SYSTEM_TIME_HIGHER_WORD_SECONDS = 0; /* Initialize the system timer. */ base->MAC_TIMESTAMP_CONTROL |= ENET_QOS_MAC_TIMESTAMP_CONTROL_TSINIT_MASK; while ((base->MAC_TIMESTAMP_CONTROL & ENET_QOS_MAC_TIMESTAMP_CONTROL_TSINIT_MASK) != 0U) { } base->MAC_SUB_SECOND_INCREMENT = ENET_QOS_MAC_SUB_SECOND_INCREMENT_SSINC(ssInc) | ENET_QOS_MAC_SUB_SECOND_INCREMENT_SNSINC(snsSinc); /* Set the initial added value for the fine update. */ if (ptpConfig->fineUpdateEnable) { result = ENET_QOS_Ptp1588CorrectTimerInFine(base, ptpConfig->defaultAddend); } return result; } static inline bool ENET_QOS_TxDirtyRingAvailable(enet_qos_tx_dirty_ring_t *txDirtyRing) { return !txDirtyRing->isFull; } static void ENET_QOS_StoreRxFrameTime(ENET_QOS_Type *base, enet_qos_handle_t *handle, enet_qos_rx_bd_struct_t *rxDesc, enet_qos_ptp_time_t *ts) { assert(ts != NULL); uint32_t nanosecond; /* Get transmit time stamp second. */ nanosecond = rxDesc->buff1Addr; if ((base->MAC_TIMESTAMP_CONTROL & ENET_QOS_MAC_TIMESTAMP_CONTROL_TSCTRLSSR_MASK) == 0U) { /* Binary rollover, 0.465ns accuracy. */ nanosecond = (uint32_t)(((uint64_t)nanosecond * 465U) / 1000U); } ts->second = rxDesc->reserved; ts->nanosecond = nanosecond; } uint32_t ENET_QOS_GetInstance(ENET_QOS_Type *base) { uint32_t instance; /* Find the instance index from base address mappings. */ for (instance = 0; instance < ARRAY_SIZE(s_enetqosBases); instance++) { if (s_enetqosBases[instance] == base) { break; } } assert(instance < ARRAY_SIZE(s_enetqosBases)); return instance; } /*! * brief Gets the ENET default configuration structure. * * The purpose of this API is to get the default ENET configure * structure for ENET_QOS_Init(). User may use the initialized * structure unchanged in ENET_QOS_Init(), or modify some fields of the * structure before calling ENET_QOS_Init(). * Example: code enet_qos_config_t config; ENET_QOS_GetDefaultConfig(&config); endcode * param config The ENET mac controller configuration structure pointer. */ void ENET_QOS_GetDefaultConfig(enet_qos_config_t *config) { /* Checks input parameter. */ assert(config != NULL); /* Initializes the configure structure to zero. */ (void)memset(config, 0, sizeof(*config)); /* Sets RGMII mode, full duplex, 1000Mbps for MAC and PHY data interface. */ config->miiMode = kENET_QOS_RgmiiMode; config->miiSpeed = kENET_QOS_MiiSpeed1000M; config->miiDuplex = kENET_QOS_MiiFullDuplex; /* Sets default configuration for other options. */ config->specialControl = 0; config->multiqueueCfg = NULL; config->pauseDuration = 0; config->ptpConfig = NULL; } /*! * brief Initializes the ENET module. * * This function set up the with ENET basic configuration. * * param base ENET peripheral base address. * param config ENET mac configuration structure pointer. * The "enet_qos_config_t" type mac configuration return from ENET_QOS_GetDefaultConfig * can be used directly. It is also possible to verify the Mac configuration using other methods. * param macAddr ENET mac address of Ethernet device. This MAC address should be * provided. * param refclkSrc_Hz ENET input reference clock. */ status_t ENET_QOS_Up( ENET_QOS_Type *base, const enet_qos_config_t *config, uint8_t *macAddr, uint8_t macCount, uint32_t refclkSrc_Hz) { assert(config != NULL); status_t result = kStatus_Success; /* Initializes the ENET MTL with basic function. */ ENET_QOS_SetMTL(base, config); /* Initializes the ENET MAC with basic function. */ ENET_QOS_SetMacControl(base, config, macAddr, macCount); return result; } /*! * brief Initializes the ENET module. * * This function ungates the module clock and initializes it with the ENET basic * configuration. * * param base ENET peripheral base address. * param config ENET mac configuration structure pointer. * The "enet_qos_config_t" type mac configuration return from ENET_QOS_GetDefaultConfig * can be used directly. It is also possible to verify the Mac configuration using other methods. * param macAddr ENET mac address of Ethernet device. This MAC address should be * provided. * param refclkSrc_Hz ENET input reference clock. */ status_t ENET_QOS_Init( ENET_QOS_Type *base, const enet_qos_config_t *config, uint8_t *macAddr, uint8_t macCount, uint32_t refclkSrc_Hz) { assert(config != NULL); status_t result = kStatus_Success; #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) uint32_t instance = ENET_QOS_GetInstance(base); /* Ungate ENET clock. */ (void)CLOCK_EnableClock(s_enetqosClock[instance]); #endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ /* System configure fistly. */ ENET_QOS_SetSYSControl(config->miiMode); /* Initializes the ENET DMA with basic function. */ ENET_QOS_SetDMAControl(base, config); (void)ENET_QOS_Up(base, config, macAddr, macCount, refclkSrc_Hz); if (config->ptpConfig != NULL) { result = ENET_QOS_SetPtp1588(base, config, refclkSrc_Hz); } return result; } /*! * brief Stops the ENET module. * This function disables the ENET module. * * param base ENET peripheral base address. */ void ENET_QOS_Down(ENET_QOS_Type *base) { enet_qos_handle_t *handle = s_ENETHandle[ENET_QOS_GetInstance(base)]; enet_qos_tx_bd_struct_t *txbdPtr; uint8_t index; uint32_t primask, j; uint32_t txDescAddr; /* Disable all interrupts */ ENET_QOS_DisableInterrupts(base, 0xFF); for (index = 0; index < handle->txQueueUse; index++) { enet_qos_tx_bd_ring_t *txBdRing = &handle->txBdRing[index]; enet_qos_tx_dirty_ring_t *txDirtyRing = (enet_qos_tx_dirty_ring_t *)&handle->txDirtyRing[index]; /* Clear pending descriptors */ if (handle->callback != NULL) { while (txBdRing->txDescUsed > 0U) { enet_qos_frame_info_t *txDirty = &txDirtyRing->txDirtyBase[txDirtyRing->txConsumIdx]; txDirty->isTsAvail = false; handle->callback(base, handle, kENET_QOS_TxIntEvent, index, handle->userData); primask = DisableGlobalIRQ(); txBdRing->txDescUsed--; EnableGlobalIRQ(primask); } } /* Disable Tx DMA */ base->DMA_CH[index].DMA_CHX_TX_CTRL &= ~ENET_QOS_DMA_CHX_TX_CTRL_ST_MASK; /* Flush Tx Queue */ base->MTL_QUEUE[index].MTL_TXQX_OP_MODE |= ENET_QOS_MTL_TXQX_OP_MODE_FTQ_MASK; /* Wait until Tx Queue is empty */ while ((base->MTL_QUEUE[index].MTL_TXQX_DBG & (ENET_QOS_MTL_TXQX_DBG_TXQSTS_MASK | ENET_QOS_MTL_TXQX_DBG_PTXQ_MASK)) != 0U) { } /* Reset hardware ring buffer */ txDescAddr = (uint32_t)(uintptr_t)handle->txBdRing[index].txBdBase & ENET_QOS_DMA_CHX_TXDESC_LIST_ADDR_TDESLA_MASK; #if defined(FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET) && FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET txDescAddr = MEMORY_ConvertMemoryMapAddress(txDescAddr, kMEMORY_Local2DMA); #endif base->DMA_CH[index].DMA_CHX_TXDESC_LIST_ADDR = txDescAddr; /* Reset software ring buffer */ handle->txBdRing[index].txGenIdx = 0; handle->txBdRing[index].txConsumIdx = 0; handle->txBdRing[index].txDescUsed = 0; handle->txDirtyRing[index].txGenIdx = 0; handle->txDirtyRing[index].txConsumIdx = 0; handle->txDirtyRing[index].isFull = false; txbdPtr = (enet_qos_tx_bd_struct_t *)(handle->txBdRing[index].txBdBase); for (j = 0; j < handle->txBdRing[index].txRingLen; j++) { txbdPtr->buff1Addr = 0; txbdPtr->buff2Addr = 0; txbdPtr->buffLen = 0; txbdPtr->controlStat = 0; txbdPtr++; } } /* Disable MAC Rx/Tx */ base->MAC_CONFIGURATION &= ~(ENET_QOS_MAC_CONFIGURATION_TE_MASK | ENET_QOS_MAC_CONFIGURATION_RE_MASK); /* Disable Rx DMA */ for (index = 0; index < handle->rxQueueUse; index++) { base->DMA_CH[index].DMA_CHX_RX_CTRL &= ~ENET_QOS_DMA_CHX_RX_CTRL_SR_MASK; } } /*! * brief Deinitializes the ENET module. * This function gates the module clock and disables the ENET module. * * param base ENET peripheral base address. */ void ENET_QOS_Deinit(ENET_QOS_Type *base) { /* Reset first and wait for the complete * The reset bit will automatically be cleared after complete. */ base->DMA_MODE |= ENET_QOS_DMA_MODE_SWR_MASK; while ((base->DMA_MODE & ENET_QOS_DMA_MODE_SWR_MASK) != 0U) { } #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) /* Disables the clock source. */ (void)CLOCK_DisableClock(s_enetqosClock[ENET_QOS_GetInstance(base)]); #endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ } /*! * brief Initialize for all ENET descriptors. * * note This function is do all tx/rx descriptors initialization. Because this API * read all interrupt registers first and then set the interrupt flag for all descriptos, * if the interrupt register is set. so the descriptor initialization should be called * after ENET_QOS_Init(), ENET_QOS_EnableInterrupts() and ENET_QOS_CreateHandle()(if transactional APIs * are used). * * param base ENET peripheral base address. * param config The configuration for ENET. * param bufferConfig All buffers configuration. */ status_t ENET_QOS_DescriptorInit(ENET_QOS_Type *base, enet_qos_config_t *config, enet_qos_buffer_config_t *bufferConfig) { assert(config != NULL); assert(bufferConfig != NULL); bool intTxEnable = false; bool intRxEnable = false; uint8_t ringNum = 1; uint8_t txQueueUse = 1; uint8_t rxQueueUse = 1; uint8_t channel; if (config->multiqueueCfg != NULL) { ringNum = MAX(config->multiqueueCfg->txQueueUse, config->multiqueueCfg->rxQueueUse); txQueueUse = config->multiqueueCfg->txQueueUse; rxQueueUse = config->multiqueueCfg->rxQueueUse; } for (channel = 0; channel < ringNum; channel++) { intRxEnable = ((base->DMA_CH[channel].DMA_CHX_INT_EN & ENET_QOS_DMA_CHX_INT_EN_RIE_MASK) != 0U) ? true : false; intTxEnable = ((base->DMA_CH[channel].DMA_CHX_INT_EN & ENET_QOS_DMA_CHX_INT_EN_TIE_MASK) != 0U) ? true : false; if (channel < txQueueUse) { if ((ENET_QOS_TxDescriptorsInit(base, bufferConfig, intTxEnable, channel) != kStatus_Success)) { return kStatus_Fail; } } if (channel < rxQueueUse) { if ((ENET_QOS_RxDescriptorsInit(base, config, bufferConfig, intRxEnable, channel) != kStatus_Success)) { return kStatus_Fail; } } bufferConfig++; } return kStatus_Success; } /*! * brief Allocates Rx buffers for all BDs. * It's used for zero copy Rx. In zero copy Rx case, Rx buffers are dynamic. This function * will populate initial buffers in all BDs for receiving. Then ENET_QOS_GetRxFrame() is used * to get Rx frame with zero copy, it will allocate new buffer to replace the buffer in BD taken * by application application should free those buffers after they're used. * * note This function should be called after ENET_QOS_CreateHandler() and buffer allocating callback * function should be ready. * * param base ENET_QOS peripheral base address. * param handle The ENET_QOS handler structure. This is the same handler pointer used in the ENET_QOS_Init. */ status_t ENET_QOS_RxBufferAllocAll(ENET_QOS_Type *base, enet_qos_handle_t *handle) { status_t result = kStatus_Success; enet_qos_rx_bd_struct_t *rxbdPtr; uint32_t buffAddr; uint8_t channel; uint16_t index; uint16_t j; if ((handle->rxBuffAlloc == NULL) || (handle->rxBuffFree == NULL)) { return kStatus_ENET_QOS_InitMemoryFail; } for (channel = 0; channel < handle->rxQueueUse; channel++) { /* Init the rxbdPtr to the receive descriptor start address. */ rxbdPtr = handle->rxBdRing[channel].rxBdBase; for (j = 0U; j < handle->rxBdRing[channel].rxRingLen; j++) { if (handle->doubleBuffEnable) { index = 2U * j; } else { index = j; } buffAddr = (uint32_t)(uintptr_t)(uint8_t *)handle->rxBuffAlloc(base, handle->userData, channel); if (buffAddr == 0U) { result = kStatus_ENET_QOS_InitMemoryFail; break; } #if defined(FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET) && FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET buffAddr = (uint32_t)MEMORY_ConvertMemoryMapAddress(buffAddr, kMEMORY_Local2DMA); #endif rxbdPtr->buff1Addr = buffAddr; handle->rxBufferStartAddr[channel][index] = buffAddr; /* The second buffer is set with 0 because it is not required for normal case. */ if (handle->doubleBuffEnable) { buffAddr = (uint32_t)(uintptr_t)(uint8_t *)handle->rxBuffAlloc(base, handle->userData, channel); if (buffAddr == 0U) { result = kStatus_ENET_QOS_InitMemoryFail; break; } #if defined(FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET) && FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET buffAddr = (uint32_t)MEMORY_ConvertMemoryMapAddress(buffAddr, kMEMORY_Local2DMA); #endif rxbdPtr->buff2Addr = buffAddr; handle->rxBufferStartAddr[channel][index + 1U] = buffAddr; } else { rxbdPtr->buff2Addr = 0; } /* Set the valid and DMA own flag.*/ rxbdPtr->control |= ENET_QOS_RXDESCRIP_WR_OWN_MASK; rxbdPtr++; } } if (result == kStatus_ENET_QOS_InitMemoryFail) { ENET_QOS_RxBufferFreeAll(base, handle); } return result; } /*! * brief Frees Rx buffers in all BDs. * It's used for zero copy Rx. In zero copy Rx case, Rx buffers are dynamic. This function * will free left buffers in all BDs. * * param base ENET_QOS peripheral base address. * param handle The ENET_QOS handler structure. This is the same handler pointer used in the ENET_QOS_Init. */ void ENET_QOS_RxBufferFreeAll(ENET_QOS_Type *base, enet_qos_handle_t *handle) { uint32_t buffAddr; uint8_t channel; uint16_t index; uint16_t j; if (handle->rxBuffFree != NULL) { for (channel = 0; channel < handle->rxQueueUse; channel++) { for (j = 0U; j < handle->rxBdRing[channel].rxRingLen; j++) { if (handle->doubleBuffEnable) { index = 2U * j; } else { index = j; } #if defined(FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET) && FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET buffAddr = MEMORY_ConvertMemoryMapAddress((uintptr_t)handle->rxBufferStartAddr[channel][index], kMEMORY_DMA2Local); #else buffAddr = (uint32_t)handle->rxBufferStartAddr[channel][index]; #endif if (buffAddr != 0U) { handle->rxBuffFree(base, (void *)(uint8_t *)(uintptr_t)buffAddr, handle->userData, channel); } /* The second buffer is set with 0 because it is not required for normal case. */ if (handle->doubleBuffEnable) { #if defined(FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET) && FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET buffAddr = MEMORY_ConvertMemoryMapAddress((uintptr_t)handle->rxBufferStartAddr[channel][index + 1U], kMEMORY_DMA2Local); #else buffAddr = (uint32_t)handle->rxBufferStartAddr[channel][index + 1U]; #endif if (buffAddr != 0U) { handle->rxBuffFree(base, (void *)(uint8_t *)(uintptr_t)buffAddr, handle->userData, channel); } } } } } } /*! * brief Starts the ENET rx/tx. * This function enable the tx/rx and starts the rx/tx DMA. * This shall be set after ENET initialization and before * starting to receive the data. * * param base ENET peripheral base address. * param rxRingNum The number of the used rx rings. It shall not be * larger than the ENET_QOS_RING_NUM_MAX(2). If the ringNum is set with * 1, the ring 0 will be used. * param txRingNum The number of the used tx rings. It shall not be * larger than the ENET_QOS_RING_NUM_MAX(2). If the ringNum is set with * 1, the ring 0 will be used. * * note This must be called after all the ENET initilization. * And should be called when the ENET receive/transmit is required. */ void ENET_QOS_StartRxTx(ENET_QOS_Type *base, uint8_t txRingNum, uint8_t rxRingNum) { assert(txRingNum != 0U); assert(rxRingNum != 0U); uint8_t index; if (txRingNum > ENET_QOS_RING_NUM_MAX) { txRingNum = ENET_QOS_RING_NUM_MAX; } if (rxRingNum > ENET_QOS_RING_NUM_MAX) { rxRingNum = ENET_QOS_RING_NUM_MAX; } /* Start/Acive the DMA first. */ for (index = 0; index < rxRingNum; index++) { base->DMA_CH[index].DMA_CHX_RX_CTRL |= ENET_QOS_DMA_CHX_RX_CTRL_SR_MASK; } for (index = 0; index < txRingNum; index++) { base->DMA_CH[index].DMA_CHX_TX_CTRL |= ENET_QOS_DMA_CHX_TX_CTRL_ST_MASK; } /* Enable the RX and TX at same time. */ base->MAC_CONFIGURATION |= (ENET_QOS_MAC_CONFIGURATION_TE_MASK | ENET_QOS_MAC_CONFIGURATION_RE_MASK); } /*! * brief Enables the ENET DMA and MAC interrupts. * * This function enables the ENET interrupt according to the provided mask. The mask * is a logical OR of enet_qos_dma_interrupt_enable_t and enet_qos_mac_interrupt_enable_t. * For example, to enable the dma and mac interrupt, do the following. * code * ENET_QOS_EnableInterrupts(ENET, kENET_QOS_DmaRx | kENET_QOS_DmaTx | kENET_QOS_MacPmt); * endcode * * param base ENET peripheral base address. * param mask ENET interrupts to enable. This is a logical OR of both * enumeration :: enet_qos_dma_interrupt_enable_t and enet_qos_mac_interrupt_enable_t. */ void ENET_QOS_EnableInterrupts(ENET_QOS_Type *base, uint32_t mask) { uint32_t interrupt = mask & 0xFFFFU; uint8_t index; /* For dma interrupt. */ if (interrupt != 0U) { for (index = 0; index < ENET_QOS_RING_NUM_MAX; index++) { /* Set for all abnormal interrupts. */ if ((ENET_QOS_ABNORM_INT_MASK & interrupt) != 0U) { interrupt |= ENET_QOS_DMA_CHX_INT_EN_AIE_MASK; } /* Set for all normal interrupts. */ if ((ENET_QOS_NORM_INT_MASK & interrupt) != 0U) { interrupt |= ENET_QOS_DMA_CHX_INT_EN_NIE_MASK; } base->DMA_CH[index].DMA_CHX_INT_EN = interrupt; } } interrupt = mask >> ENET_QOS_MACINT_ENUM_OFFSET; if (interrupt != 0U) { /* MAC interrupt */ base->MAC_INTERRUPT_ENABLE |= interrupt; } } /*! * brief Clears the ENET mac interrupt events status flag. * * This function clears enabled ENET interrupts according to the provided mask. The mask * is a logical OR of enumeration members. See the ref enet_qos_mac_interrupt_enable_t. * For example, to clear the TX frame interrupt and RX frame interrupt, do the following. * code * ENET_QOS_ClearMacInterruptStatus(ENET, kENET_QOS_MacPmt); * endcode * * param base ENET peripheral base address. * param mask ENET interrupt source to be cleared. * This is the logical OR of members of the enumeration :: enet_qos_mac_interrupt_enable_t. */ void ENET_QOS_ClearMacInterruptStatus(ENET_QOS_Type *base, uint32_t mask) { volatile uint32_t dummy; if ((mask & (uint32_t)kENET_QOS_MacTimestamp) != 0U) { dummy = base->MAC_TIMESTAMP_STATUS; } else if ((mask & (uint32_t)kENET_QOS_MacPmt) != 0U) { dummy = base->MAC_PMT_CONTROL_STATUS; } else { /* Add for avoid the misra 2004 rule 14.10 */ } (void)dummy; } /*! * brief Disables the ENET DMA and MAC interrupts. * * This function disables the ENET interrupt according to the provided mask. The mask * is a logical OR of enet_qos_dma_interrupt_enable_t and enet_qos_mac_interrupt_enable_t. * For example, to disable the dma and mac interrupt, do the following. * code * ENET_QOS_DisableInterrupts(ENET, kENET_QOS_DmaRx | kENET_QOS_DmaTx | kENET_QOS_MacPmt); * endcode * * param base ENET peripheral base address. * param mask ENET interrupts to disables. This is a logical OR of both * enumeration :: enet_qos_dma_interrupt_enable_t and enet_qos_mac_interrupt_enable_t. */ void ENET_QOS_DisableInterrupts(ENET_QOS_Type *base, uint32_t mask) { uint32_t interrupt = mask & 0xFFFFU; uint8_t index; /* For dma interrupt. */ if (interrupt != 0U) { for (index = 0; index < ENET_QOS_RING_NUM_MAX; index++) { /* Set for all abnormal interrupts. */ if ((ENET_QOS_ABNORM_INT_MASK & interrupt) != 0U) { interrupt |= ENET_QOS_DMA_CHX_INT_EN_AIE_MASK; } /* Set for all normal interrupts. */ if ((ENET_QOS_NORM_INT_MASK & interrupt) != 0U) { interrupt |= ENET_QOS_DMA_CHX_INT_EN_NIE_MASK; } base->DMA_CH[index].DMA_CHX_INT_EN &= ~interrupt; } } interrupt = mask >> ENET_QOS_MACINT_ENUM_OFFSET; if (interrupt != 0U) { /* MAC interrupt */ base->MAC_INTERRUPT_ENABLE &= ~interrupt; } } /*! * @brief Set the second level IRQ handler, allow user to overwrite the default * second level weak IRQ handler. * * @param ISRHandler he handler to install. */ void ENET_QOS_SetISRHandler(ENET_QOS_Type *base, enet_qos_isr_t ISRHandler) { /* Update IRQ entry. */ s_enetqosIsr = ISRHandler; /* Enable NVIC. */ (void)EnableIRQ(s_enetqosIrqId[ENET_QOS_GetInstance(base)]); } /*! * brief Create ENET Handler * * This is a transactional API and it's provided to store all datas which are needed * during the whole transactional process. This API should not be used when you use * functional APIs to do data tx/rx. This is funtion will store many data/flag for * transactional use, so all configure API such as ENET_QOS_Init(), ENET_QOS_DescriptorInit(), * ENET_QOS_EnableInterrupts() etc. * * note as our transactional transmit API use the zero-copy transmit buffer. * so there are two thing we emphasize here: * 1. tx buffer free/requeue for application should be done in the tx * interrupt handler. Please set callback: kENET_QOS_TxIntEvent with tx buffer free/requeue * process APIs. * 2. the tx interrupt is forced to open. * * param base ENET peripheral base address. * param handle ENET handler. * param config ENET configuration. * param bufferConfig ENET buffer configuration. * param callback The callback function. * param userData The application data. */ void ENET_QOS_CreateHandler(ENET_QOS_Type *base, enet_qos_handle_t *handle, enet_qos_config_t *config, enet_qos_buffer_config_t *bufferConfig, enet_qos_callback_t callback, void *userData) { assert(config != NULL); assert(bufferConfig != NULL); assert(callback != NULL); uint8_t ringNum = 1; uint8_t count = 0; uint32_t rxIntEnable = 0; uint8_t txQueueUse = 1; uint8_t rxQueueUse = 1; enet_qos_buffer_config_t *buffConfig = bufferConfig; /* Store transfer parameters in handle pointer. */ (void)memset(handle, 0, sizeof(enet_qos_handle_t)); if (config->multiqueueCfg != NULL) { txQueueUse = config->multiqueueCfg->txQueueUse; rxQueueUse = config->multiqueueCfg->rxQueueUse; ringNum = MAX(txQueueUse, rxQueueUse); } handle->txQueueUse = txQueueUse; handle->rxQueueUse = rxQueueUse; if ((config->specialControl & (uint32_t)kENET_QOS_DescDoubleBuffer) != 0U) { handle->doubleBuffEnable = true; } for (count = 0; count < ringNum; count++) { if (count < txQueueUse) { handle->txBdRing[count].txBdBase = buffConfig->txDescStartAddrAlign; handle->txBdRing[count].txRingLen = buffConfig->txRingLen; handle->txBdRing[count].txGenIdx = 0; handle->txBdRing[count].txConsumIdx = 0; handle->txBdRing[count].txDescUsed = 0; handle->txDirtyRing[count].txDirtyBase = buffConfig->txDirtyStartAddr; handle->txDirtyRing[count].txRingLen = buffConfig->txRingLen; handle->txDirtyRing[count].txGenIdx = 0; handle->txDirtyRing[count].txConsumIdx = 0; /* Enable tx interrupt for use transactional API to do tx buffer free/requeue. */ base->DMA_CH[count].DMA_CHX_INT_EN |= ENET_QOS_DMA_CHX_INT_EN_TIE_MASK | ENET_QOS_DMA_CHX_INT_EN_NIE_MASK; } if (count < rxQueueUse) { handle->rxBdRing[count].rxBdBase = buffConfig->rxDescStartAddrAlign; handle->rxBdRing[count].rxGenIdx = 0; handle->rxBdRing[count].rxRingLen = buffConfig->rxRingLen; handle->rxBdRing[count].rxBuffSizeAlign = buffConfig->rxBuffSizeAlign; /* Record rx buffer address for re-init Rx buffer descriptor */ handle->rxBufferStartAddr[count] = buffConfig->rxBufferStartAddr; /* Record rx buffer need cache maintain */ handle->rxMaintainEnable[count] = buffConfig->rxBuffNeedMaintain; /* Check if the rx interrrupt is enabled. */ rxIntEnable |= (base->DMA_CH[count].DMA_CHX_INT_EN & ENET_QOS_DMA_CHX_INT_EN_RIE_MASK); } buffConfig++; } handle->rxintEnable = (rxIntEnable != 0U) ? true : false; /* Save the handle pointer in the global variables. */ s_ENETHandle[ENET_QOS_GetInstance(base)] = handle; /* Set Rx alloc/free callback. */ handle->rxBuffAlloc = config->rxBuffAlloc; handle->rxBuffFree = config->rxBuffFree; /* Set callback and userData. */ handle->callback = callback; handle->userData = userData; /* Use default ENET_QOS_CommonIRQHandler as default weak IRQ handler. */ ENET_QOS_SetISRHandler(base, ENET_QOS_CommonIRQHandler); } /*! * brief Gets the ENET module Mac address. * * param base ENET peripheral base address. * param macAddr The six-byte Mac address pointer. * The pointer is allocated by application and input into the API. */ void ENET_QOS_GetMacAddr(ENET_QOS_Type *base, uint8_t *macAddr, uint8_t index) { assert(macAddr != NULL); uint32_t address = base->MAC_ADDRESS[index].LOW; /* Get from physical address lower register. */ macAddr[2] = (uint8_t)(0xFFU & (address >> 24U)); macAddr[3] = (uint8_t)(0xFFU & (address >> 16U)); macAddr[4] = (uint8_t)(0xFFU & (address >> 8U)); macAddr[5] = (uint8_t)(0xFFU & address); /* Get from physical address high register. */ address = base->MAC_ADDRESS[index].HIGH; macAddr[0] = (uint8_t)(0xFFU & (address >> 8U)); macAddr[1] = (uint8_t)(0xFFU & address); } /*! * brief Adds the ENET_QOS device to a multicast group. * * param base ENET_QOS peripheral base address. * param address The six-byte multicast group address which is provided by application. */ void ENET_QOS_AddMulticastGroup(ENET_QOS_Type *base, uint8_t *address) { assert(address != NULL); enet_qos_handle_t *handle = s_ENETHandle[ENET_QOS_GetInstance(base)]; uint32_t crc = 0xFFFFFFFFU; uint32_t count1 = 0; uint32_t count2 = 0; /* Calculates the CRC-32 polynomial on the multicast group address. */ for (count1 = 0; count1 < 6U; count1++) { uint8_t c = address[count1]; for (count2 = 0; count2 < 0x08U; count2++) { if (((c ^ crc) & 1U) != 0U) { crc >>= 1U; c >>= 1U; crc ^= 0xEDB88320U; } else { crc >>= 1U; c >>= 1U; } } } /* Calculate bitwise reverse value. */ crc = ENET_QOS_ReverseBits(~crc); /* Get highest 6 bits*/ crc = crc >> 26U; handle->multicastCount[crc]++; if (0U != (crc & 0x20U)) { base->MAC_HASH_TABLE_REG1 |= (1UL << (crc & 0x1FU)); } else { base->MAC_HASH_TABLE_REG0 |= (1UL << (crc & 0x1FU)); } } /*! * brief Moves the ENET_QOS device from a multicast group. * * param base ENET_QOS peripheral base address. * param address The six-byte multicast group address which is provided by application. */ void ENET_QOS_LeaveMulticastGroup(ENET_QOS_Type *base, uint8_t *address) { assert(address != NULL); enet_qos_handle_t *handle = s_ENETHandle[ENET_QOS_GetInstance(base)]; uint32_t crc = 0xFFFFFFFFU; uint32_t count1 = 0; uint32_t count2 = 0; /* Calculates the CRC-32 polynomial on the multicast group address. */ for (count1 = 0; count1 < 6U; count1++) { uint8_t c = address[count1]; for (count2 = 0; count2 < 0x08U; count2++) { if (((c ^ crc) & 1U) != 0U) { crc >>= 1U; c >>= 1U; crc ^= 0xEDB88320U; } else { crc >>= 1U; c >>= 1U; } } } /* Calculate bitwise reverse value. */ crc = ENET_QOS_ReverseBits(~crc); /* Get highest 6 bits*/ crc = crc >> 26U; handle->multicastCount[crc]--; /* Set the hash table if no collisions */ if (0U == handle->multicastCount[crc]) { if (0U != (crc & 0x20U)) { base->MAC_HASH_TABLE_REG1 &= ~((1UL << (crc & 0x1FU))); } else { base->MAC_HASH_TABLE_REG0 &= ~((1UL << (crc & 0x1FU))); } } } /*! * brief Sets the ENET SMI(serial management interface)- MII management interface. * * param base ENET peripheral base address. */ void ENET_QOS_SetSMI(ENET_QOS_Type *base, uint32_t csrClock_Hz) { uint32_t crDiv = 0; uint32_t srcClock_Hz = csrClock_Hz / 1000000U; assert((srcClock_Hz >= 20U) && (srcClock_Hz < 800U)); if (srcClock_Hz < 35U) { crDiv = 2; } else if (srcClock_Hz < 60U) { crDiv = 3; } else if (srcClock_Hz < 100U) { crDiv = 0; } else if (srcClock_Hz < 150U) { crDiv = 1; } else if (srcClock_Hz < 250U) { crDiv = 4; } else if (srcClock_Hz < 300U) { crDiv = 5; } else if (srcClock_Hz < 500U) { crDiv = 6; } else if (srcClock_Hz < 800U) { crDiv = 7; } else { /* Empty else */ } base->MAC_MDIO_ADDRESS = ENET_QOS_MAC_MDIO_ADDRESS_CR(crDiv); } /*! * brief Starts a SMI write command. * It supports MDIO IEEE802.3 Clause 22. * After send command, user needs to check whether the transmission is over * with ENET_QOS_IsSMIBusy(). * * param base ENET peripheral base address. * param phyAddr The PHY address. * param phyReg The PHY register. * param data The data written to PHY. */ void ENET_QOS_StartSMIWrite(ENET_QOS_Type *base, uint32_t phyAddr, uint32_t phyReg, uint32_t data) { uint32_t reg = base->MAC_MDIO_ADDRESS & ENET_QOS_MAC_MDIO_ADDRESS_CR_MASK; /* Build MII write command. */ base->MAC_MDIO_ADDRESS = reg | (uint32_t)kENET_QOS_MiiWriteFrame | ENET_QOS_MAC_MDIO_ADDRESS_PA(phyAddr) | ENET_QOS_MAC_MDIO_ADDRESS_RDA(phyReg); base->MAC_MDIO_DATA = data; base->MAC_MDIO_ADDRESS |= ENET_QOS_MAC_MDIO_ADDRESS_GB_MASK; } /*! * brief Starts an SMI read command. * It supports MDIO IEEE802.3 Clause 22. * After send command, user needs to check whether the transmission is over * with ENET_QOS_IsSMIBusy(). * * param base ENET peripheral base address. * param phyAddr The PHY address. * param phyReg The PHY register. */ void ENET_QOS_StartSMIRead(ENET_QOS_Type *base, uint32_t phyAddr, uint32_t phyReg) { uint32_t reg = base->MAC_MDIO_ADDRESS & ENET_QOS_MAC_MDIO_ADDRESS_CR_MASK; /* Build MII read command. */ base->MAC_MDIO_ADDRESS = reg | (uint32_t)kENET_QOS_MiiReadFrame | ENET_QOS_MAC_MDIO_ADDRESS_PA(phyAddr) | ENET_QOS_MAC_MDIO_ADDRESS_RDA(phyReg); base->MAC_MDIO_ADDRESS |= ENET_QOS_MAC_MDIO_ADDRESS_GB_MASK; } /*! * brief Starts a SMI write command. * It supports MDIO IEEE802.3 Clause 45. * After send command, user needs to check whether the transmission is over * with ENET_QOS_IsSMIBusy(). * * param base ENET peripheral base address. * param phyAddr The PHY address. * param device The PHY device type. * param phyReg The PHY register address. * param data The data written to PHY. */ void ENET_QOS_StartExtC45SMIWrite( ENET_QOS_Type *base, uint32_t phyAddr, uint32_t device, uint32_t phyReg, uint32_t data) { uint32_t reg = base->MAC_MDIO_ADDRESS & ENET_QOS_MAC_MDIO_ADDRESS_CR_MASK; /* Build MII write command. */ base->MAC_MDIO_ADDRESS = reg | ENET_QOS_MAC_MDIO_ADDRESS_C45E_MASK | (uint32_t)kENET_QOS_MiiWriteFrame | ENET_QOS_MAC_MDIO_ADDRESS_PA(phyAddr) | ENET_QOS_MAC_MDIO_ADDRESS_RDA(device); base->MAC_MDIO_DATA = data | ENET_QOS_MAC_MDIO_DATA_RA(phyReg); base->MAC_MDIO_ADDRESS |= ENET_QOS_MAC_MDIO_ADDRESS_GB_MASK; } /*! * brief Starts a SMI write command. * It supports MDIO IEEE802.3 Clause 45. * After send command, user needs to check whether the transmission is over * with ENET_QOS_IsSMIBusy(). * * param base ENET peripheral base address. * param phyAddr The PHY address. * param device The PHY device type. * param phyReg The PHY register address. */ void ENET_QOS_StartExtC45SMIRead(ENET_QOS_Type *base, uint32_t phyAddr, uint32_t device, uint32_t phyReg) { uint32_t reg = base->MAC_MDIO_ADDRESS & ENET_QOS_MAC_MDIO_ADDRESS_CR_MASK; /* Build MII read command. */ base->MAC_MDIO_ADDRESS = reg | ENET_QOS_MAC_MDIO_ADDRESS_C45E_MASK | (uint32_t)kENET_QOS_MiiReadFrame | ENET_QOS_MAC_MDIO_ADDRESS_PA(phyAddr) | ENET_QOS_MAC_MDIO_ADDRESS_RDA(device); base->MAC_MDIO_DATA = ENET_QOS_MAC_MDIO_DATA_RA(phyReg); base->MAC_MDIO_ADDRESS |= ENET_QOS_MAC_MDIO_ADDRESS_GB_MASK; } /*! * brief Set the MAC to enter into power down mode. * the remote power wake up frame and magic frame can wake up * the ENET from the power down mode. * * param base ENET peripheral base address. * param wakeFilter The wakeFilter provided to configure the wake up frame fitlter. * Set the wakeFilter to NULL is not required. But if you have the filter requirement, * please make sure the wakeFilter pointer shall be eight continous * 32-bits configuration. */ void ENET_QOS_EnterPowerDown(ENET_QOS_Type *base, uint32_t *wakeFilter) { uint8_t index; uint32_t *reg = wakeFilter; /* Disable the tx dma. */ base->DMA_CH[0].DMA_CHX_TX_CTRL &= ~ENET_QOS_DMA_CHX_TX_CTRL_ST_MASK; base->DMA_CH[1].DMA_CHX_TX_CTRL &= ~ENET_QOS_DMA_CHX_TX_CTRL_ST_MASK; /* Disable the mac tx/rx. */ base->MAC_CONFIGURATION &= ~(ENET_QOS_MAC_CONFIGURATION_RE_MASK | ENET_QOS_MAC_CONFIGURATION_TE_MASK); /* Enable the remote wakeup packet and enable the power down mode. */ if (wakeFilter != NULL) { for (index = 0; index < ENET_QOS_WAKEUPFILTER_NUM; index++) { base->MAC_RWK_PACKET_FILTER = *reg; reg++; } } base->MAC_PMT_CONTROL_STATUS = ENET_QOS_MAC_PMT_CONTROL_STATUS_MGKPKTEN_MASK | ENET_QOS_MAC_PMT_CONTROL_STATUS_RWKPKTEN_MASK | ENET_QOS_MAC_PMT_CONTROL_STATUS_PWRDWN_MASK; /* Enable the MAC rx. */ base->MAC_CONFIGURATION |= ENET_QOS_MAC_CONFIGURATION_RE_MASK; } /*! * brief Enable/Disable Rx parser, please notice that for enable/disable Rx Parser, * should better disable Receive first. * * param base ENET_QOS peripheral base address. * param enable Enable/Disable Rx parser function */ status_t ENET_QOS_EnableRxParser(ENET_QOS_Type *base, bool enable) { status_t result = kStatus_Success; if (enable) { base->MTL_OPERATION_MODE |= ENET_QOS_MTL_OPERATION_MODE_FRPE_MASK; } else { base->MTL_OPERATION_MODE &= ~ENET_QOS_MTL_OPERATION_MODE_FRPE_MASK; result = ENET_QOS_PollStatusFlag(&(base->MTL_RXP_CONTROL_STATUS), ENET_QOS_MTL_RXP_CONTROL_STATUS_RXPI_MASK, ENET_QOS_MTL_RXP_CONTROL_STATUS_RXPI_MASK); } return result; } /*! * brief Gets the size of the read frame. * This function gets a received frame size from the ENET buffer descriptors. * note The FCS of the frame is automatically removed by MAC and the size is the length without the FCS. * After calling ENET_QOS_GetRxFrameSize, ENET_QOS_ReadFrame() should be called to update the * receive buffers If the result is not "kStatus_ENET_QOS_RxFrameEmpty". * * param handle The ENET handler structure. This is the same handler pointer used in the ENET_QOS_Init. * param length The length of the valid frame received. * param channel The DMAC channel for the rx. * retval kStatus_ENET_QOS_RxFrameEmpty No frame received. Should not call ENET_QOS_ReadFrame to read frame. * retval kStatus_ENET_QOS_RxFrameError Data error happens. ENET_QOS_ReadFrame should be called with NULL data * and NULL length to update the receive buffers. * retval kStatus_Success Receive a frame Successfully then the ENET_QOS_ReadFrame * should be called with the right data buffer and the captured data length input. */ status_t ENET_QOS_GetRxFrameSize(ENET_QOS_Type *base, enet_qos_handle_t *handle, uint32_t *length, uint8_t channel) { assert(handle != NULL); assert(length != NULL); enet_qos_rx_bd_ring_t *rxBdRing = (enet_qos_rx_bd_ring_t *)&handle->rxBdRing[channel]; enet_qos_rx_bd_struct_t *rxDesc = &rxBdRing->rxBdBase[rxBdRing->rxGenIdx]; uint16_t index = rxBdRing->rxGenIdx; uint32_t control = rxDesc->control; /* Reset the length to zero. */ *length = 0; if ((control & ENET_QOS_RXDESCRIP_WR_OWN_MASK) != 0U) { return kStatus_ENET_QOS_RxFrameEmpty; } else { do { /* Application owns the buffer descriptor, get the length. */ if ((control & ENET_QOS_RXDESCRIP_WR_LD_MASK) != 0U) { if ((control & ENET_QOS_RXDESCRIP_WR_ERRSUM_MASK) != 0U) { return kStatus_ENET_QOS_RxFrameError; } *length = (control & ENET_QOS_RXDESCRIP_WR_PACKETLEN_MASK) - ENET_QOS_FCS_LEN; return kStatus_Success; } index = ENET_QOS_IncreaseIndex(index, rxBdRing->rxRingLen); rxDesc = &rxBdRing->rxBdBase[index]; control = rxDesc->control; } while (index != rxBdRing->rxGenIdx); return kStatus_ENET_QOS_RxFrameError; } } static void ENET_QOS_DropFrame(ENET_QOS_Type *base, enet_qos_handle_t *handle, uint8_t channel) { enet_qos_rx_bd_ring_t *rxBdRing = (enet_qos_rx_bd_ring_t *)&handle->rxBdRing[channel]; enet_qos_rx_bd_struct_t *rxDesc; uint16_t index = rxBdRing->rxGenIdx; bool tsAvailable = false; uintptr_t buff1Addr = 0; uintptr_t buff2Addr = 0; uint32_t rxDescTail; uint32_t rdesc1; uint32_t rdesc3; /* Not check DMA ownership here, assume there's at least one valid frame left in BD ring */ do { /* Get the control flag. */ rxDesc = &rxBdRing->rxBdBase[rxBdRing->rxGenIdx]; rdesc1 = rxDesc->reserved; rdesc3 = rxDesc->control; if (!handle->doubleBuffEnable) { buff1Addr = handle->rxBufferStartAddr[channel][rxBdRing->rxGenIdx]; ENET_QOS_UpdateRxDescriptor(rxDesc, (void *)(uint8_t *)buff1Addr, NULL, handle->rxintEnable, handle->doubleBuffEnable); } else { buff1Addr = handle->rxBufferStartAddr[channel][2U * rxBdRing->rxGenIdx]; buff2Addr = handle->rxBufferStartAddr[channel][2U * rxBdRing->rxGenIdx + 1U]; ENET_QOS_UpdateRxDescriptor(rxDesc, (void *)(uint8_t *)buff1Addr, (void *)(uint8_t *)buff2Addr, handle->rxintEnable, handle->doubleBuffEnable); } rxBdRing->rxGenIdx = ENET_QOS_IncreaseIndex(rxBdRing->rxGenIdx, rxBdRing->rxRingLen); /* Find the last buffer descriptor for the frame. */ if ((rdesc3 & ENET_QOS_RXDESCRIP_WR_LD_MASK) != 0U) { if ((rdesc3 & ENET_QOS_RXDESCRIP_WR_RS1V_MASK) != 0U) { if ((rdesc1 & ENET_QOS_RXDESCRIP_WR_PTPTSA_MASK) != 0U) { tsAvailable = true; } } /* Reinit for the context descriptor which has been updated by DMA. */ rxDesc = &rxBdRing->rxBdBase[rxBdRing->rxGenIdx]; if (tsAvailable && ((rxDesc->control & ENET_QOS_RXDESCRIP_WR_CTXT_MASK) != 0U)) { if (!handle->doubleBuffEnable) { buff1Addr = handle->rxBufferStartAddr[channel][rxBdRing->rxGenIdx]; ENET_QOS_UpdateRxDescriptor(rxDesc, (void *)(uint8_t *)buff1Addr, NULL, handle->rxintEnable, handle->doubleBuffEnable); } else { buff1Addr = handle->rxBufferStartAddr[channel][2U * rxBdRing->rxGenIdx]; buff2Addr = handle->rxBufferStartAddr[channel][2U * rxBdRing->rxGenIdx + 1U]; ENET_QOS_UpdateRxDescriptor(rxDesc, (void *)(uint8_t *)buff1Addr, (void *)(uint8_t *)buff2Addr, handle->rxintEnable, handle->doubleBuffEnable); } rxBdRing->rxGenIdx = ENET_QOS_IncreaseIndex(rxBdRing->rxGenIdx, rxBdRing->rxRingLen); } break; } } while (rxBdRing->rxGenIdx != index); /* Always try to start receive, in case it had stopped */ rxDescTail = (uint32_t)(uintptr_t)&rxBdRing->rxBdBase[rxBdRing->rxRingLen]; #if defined(FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET) && FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET rxDescTail = MEMORY_ConvertMemoryMapAddress(rxDescTail, kMEMORY_Local2DMA); #endif base->DMA_CH[channel].DMA_CHX_RXDESC_TAIL_PTR = rxDescTail; } /*! * brief Reads a frame from the ENET device. * This function reads a frame from the ENET DMA descriptors. * The ENET_QOS_GetRxFrameSize should be used to get the size of the prepared data buffer. * For example use rx dma channel 0: * code * uint32_t length; * enet_qos_handle_t g_handle; * enet_qos_ptp_time_t ts; * status = ENET_QOS_GetRxFrameSize(&g_handle, &length, 0); * if (length != 0) * { * uint8_t *data = memory allocate interface; * if (!data) * { * ENET_QOS_ReadFrame(ENET, &g_handle, NULL, 0, 0, &ts); * } * else * { * status = ENET_QOS_ReadFrame(ENET, &g_handle, data, length, 0, &ts); * } * } * else if (status == kStatus_ENET_QOS_RxFrameError) * { * ENET_QOS_ReadFrame(ENET, &g_handle, NULL, 0, 0, &ts); * } * endcode * param base ENET peripheral base address. * param handle The ENET handler structure. This is the same handler pointer used in the ENET_QOS_Init. * param data The data buffer provided by user to store the frame which memory size should be at least "length". * param length The size of the data buffer which is still the length of the received frame. * param channel The rx DMA channel. shall not be larger than 2. * return The execute status, successful or failure. */ status_t ENET_QOS_ReadFrame(ENET_QOS_Type *base, enet_qos_handle_t *handle, uint8_t *data, uint32_t length, uint8_t channel, enet_qos_ptp_time_t *ts) { assert(handle != NULL); assert(channel < handle->rxQueueUse); uint32_t len = 0; uint32_t offset = 0; uint32_t control; bool isLastBuff = false; enet_qos_rx_bd_ring_t *rxBdRing = (enet_qos_rx_bd_ring_t *)&handle->rxBdRing[channel]; enet_qos_rx_bd_struct_t *rxDesc; status_t result = kStatus_Fail; uintptr_t buff1Addr = 0; /*!< Buffer 1 address */ uintptr_t buff2Addr = 0; /*!< Buffer 2 or next descriptor address */ uint32_t rxDescTail; bool tsAvailable = false; /* For data-NULL input, only update the buffer descriptor. */ if (data == NULL) { ENET_QOS_DropFrame(base, handle, channel); result = kStatus_Success; } else { while (!isLastBuff) { /* The last buffer descriptor of a frame. */ rxDesc = &rxBdRing->rxBdBase[rxBdRing->rxGenIdx]; control = rxDesc->control; if (!handle->doubleBuffEnable) { buff1Addr = handle->rxBufferStartAddr[channel][rxBdRing->rxGenIdx]; if (handle->rxMaintainEnable[channel]) { #if defined(FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET) && FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET /* Add the cache invalidate maintain. */ ENET_QOS_DcacheInvalidateByRange(MEMORY_ConvertMemoryMapAddress(buff1Addr, kMEMORY_DMA2Local), rxBdRing->rxBuffSizeAlign); #else /* Add the cache invalidate maintain. */ ENET_QOS_DcacheInvalidateByRange(buff1Addr, rxBdRing->rxBuffSizeAlign); #endif } } else { buff1Addr = handle->rxBufferStartAddr[channel][2U * rxBdRing->rxGenIdx]; buff2Addr = handle->rxBufferStartAddr[channel][2U * rxBdRing->rxGenIdx + 1U]; if (handle->rxMaintainEnable[channel]) { #if defined(FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET) && FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET /* Add the cache invalidate maintain. */ ENET_QOS_DcacheInvalidateByRange(MEMORY_ConvertMemoryMapAddress(buff1Addr, kMEMORY_DMA2Local), rxBdRing->rxBuffSizeAlign); /* Add the cache invalidate maintain. */ ENET_QOS_DcacheInvalidateByRange(MEMORY_ConvertMemoryMapAddress(buff2Addr, kMEMORY_DMA2Local), rxBdRing->rxBuffSizeAlign); #else /* Add the cache invalidate maintain. */ ENET_QOS_DcacheInvalidateByRange(buff1Addr, rxBdRing->rxBuffSizeAlign); /* Add the cache invalidate maintain. */ ENET_QOS_DcacheInvalidateByRange(buff2Addr, rxBdRing->rxBuffSizeAlign); #endif } } rxBdRing->rxGenIdx = ENET_QOS_IncreaseIndex(rxBdRing->rxGenIdx, rxBdRing->rxRingLen); if ((control & ENET_QOS_RXDESCRIP_WR_LD_MASK) != 0U) { /* This is a valid frame. */ isLastBuff = true; /* Remove FCS */ len = (control & ENET_QOS_RXDESCRIP_WR_PACKETLEN_MASK) - ENET_QOS_FCS_LEN; if (length == len) { /* Copy the frame to user's buffer. */ len -= offset; if (len > rxBdRing->rxBuffSizeAlign) { #if defined(FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET) && FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET (void)memcpy((void *)&data[offset], (void *)(uint8_t *)MEMORY_ConvertMemoryMapAddress(buff1Addr, kMEMORY_DMA2Local), rxBdRing->rxBuffSizeAlign); #else (void)memcpy((void *)&data[offset], (void *)(uint8_t *)buff1Addr, rxBdRing->rxBuffSizeAlign); #endif offset += rxBdRing->rxBuffSizeAlign; #if defined(FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET) && FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET (void)memcpy((void *)&data[offset], (void *)(uint8_t *)MEMORY_ConvertMemoryMapAddress(buff2Addr, kMEMORY_DMA2Local), len - rxBdRing->rxBuffSizeAlign); #else (void)memcpy((void *)&data[offset], (void *)(uint8_t *)buff2Addr, len - rxBdRing->rxBuffSizeAlign); #endif } else { #if defined(FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET) && FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET (void)memcpy((void *)&data[offset], (void *)(uint8_t *)MEMORY_ConvertMemoryMapAddress(buff1Addr, kMEMORY_DMA2Local), len); #else (void)memcpy((void *)&data[offset], (void *)(uint8_t *)buff1Addr, len); #endif } result = kStatus_Success; } if ((rxDesc->reserved & ENET_QOS_RXDESCRIP_WR_PTPTSA_MASK) != 0U) { tsAvailable = true; } /* Updates the receive buffer descriptors. */ ENET_QOS_UpdateRxDescriptor(rxDesc, (void *)(uint8_t *)buff1Addr, (void *)(uint8_t *)buff2Addr, handle->rxintEnable, handle->doubleBuffEnable); /* Store the rx timestamp which is in the next buffer descriptor of the last * descriptor of a frame. */ rxDesc = &rxBdRing->rxBdBase[rxBdRing->rxGenIdx]; control = rxDesc->control; /* If tsAvailable is true, a context descriptor is expected but might not be yet * available. */ if (tsAvailable) { uint8_t retryTimes = 10; while (((control & ENET_QOS_RXDESCRIP_WR_OWN_MASK) != 0U) || ((control & ENET_QOS_RXDESCRIP_WR_CTXT_MASK) == 0U)) { SDK_DelayAtLeastUs(1U, SDK_DEVICE_MAXIMUM_CPU_CLOCK_FREQUENCY); if (0U == retryTimes--) { assert(false); } control = rxDesc->control; } } /* Reinit for the context descritor which has been updated by DMA. */ if ((control & ENET_QOS_RXDESCRIP_WR_CTXT_MASK) != 0U) { if (tsAvailable && (NULL != ts)) { ENET_QOS_StoreRxFrameTime(base, handle, rxDesc, ts); } if (!handle->doubleBuffEnable) { buff1Addr = handle->rxBufferStartAddr[channel][rxBdRing->rxGenIdx]; ENET_QOS_UpdateRxDescriptor(rxDesc, (void *)(uint8_t *)buff1Addr, NULL, handle->rxintEnable, handle->doubleBuffEnable); } else { buff1Addr = handle->rxBufferStartAddr[channel][2U * rxBdRing->rxGenIdx]; buff2Addr = handle->rxBufferStartAddr[channel][2U * rxBdRing->rxGenIdx + 1U]; ENET_QOS_UpdateRxDescriptor(rxDesc, (void *)(uint8_t *)buff1Addr, (void *)(uint8_t *)buff2Addr, handle->rxintEnable, handle->doubleBuffEnable); } rxBdRing->rxGenIdx = ENET_QOS_IncreaseIndex(rxBdRing->rxGenIdx, rxBdRing->rxRingLen); } } else { /* Store a frame on several buffer descriptors. */ isLastBuff = false; /* Length check. */ if (offset >= length) { /* Updates the receive buffer descriptors. */ ENET_QOS_UpdateRxDescriptor(rxDesc, (void *)(uint8_t *)buff1Addr, (void *)(uint8_t *)buff2Addr, handle->rxintEnable, handle->doubleBuffEnable); break; } #if defined(FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET) && FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET (void)memcpy((void *)&data[offset], (void *)(uint8_t *)MEMORY_ConvertMemoryMapAddress(buff1Addr, kMEMORY_DMA2Local), rxBdRing->rxBuffSizeAlign); #else (void)memcpy((void *)&data[offset], (void *)(uint8_t *)buff1Addr, rxBdRing->rxBuffSizeAlign); #endif offset += rxBdRing->rxBuffSizeAlign; if (buff2Addr != 0U) { #if defined(FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET) && FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET (void)memcpy((void *)&data[offset], (void *)(uint8_t *)MEMORY_ConvertMemoryMapAddress(buff2Addr, kMEMORY_DMA2Local), rxBdRing->rxBuffSizeAlign); #else (void)memcpy((void *)&data[offset], (void *)(uint8_t *)buff2Addr, rxBdRing->rxBuffSizeAlign); #endif offset += rxBdRing->rxBuffSizeAlign; } ENET_QOS_UpdateRxDescriptor(rxDesc, (void *)(uint8_t *)buff1Addr, (void *)(uint8_t *)buff2Addr, handle->rxintEnable, handle->doubleBuffEnable); } } /* Always try to start receive, in case it had stopped */ rxDescTail = (uint32_t)(uintptr_t)&rxBdRing->rxBdBase[rxBdRing->rxRingLen]; #if defined(FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET) && FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET rxDescTail = MEMORY_ConvertMemoryMapAddress(rxDescTail, kMEMORY_Local2DMA); #endif base->DMA_CH[channel].DMA_CHX_RXDESC_TAIL_PTR = rxDescTail; } return result; } /*! * brief Updates the buffers and the own status for a given rx descriptor. * This function is a low level functional API to Updates the * buffers and the own status for a given rx descriptor. * * param rxDesc The given rx descriptor. * param buffer1 The first buffer address in the descriptor. * param buffer2 The second buffer address in the descriptor. * param intEnable Interrupt enable flag. * param doubleBuffEnable The double buffer enable flag. * * note This must be called after all the ENET initilization. * And should be called when the ENET receive/transmit is required. */ void ENET_QOS_UpdateRxDescriptor( enet_qos_rx_bd_struct_t *rxDesc, void *buffer1, void *buffer2, bool intEnable, bool doubleBuffEnable) { assert(rxDesc != NULL); uint32_t control = ENET_QOS_RXDESCRIP_RD_OWN_MASK | ENET_QOS_RXDESCRIP_RD_BUFF1VALID_MASK; if (intEnable) { control |= ENET_QOS_RXDESCRIP_RD_IOC_MASK; } if (doubleBuffEnable) { control |= ENET_QOS_RXDESCRIP_RD_BUFF2VALID_MASK; } /* Update the buffer if needed. */ if (buffer1 != NULL) { rxDesc->buff1Addr = (uint32_t)(uintptr_t)(uint8_t *)buffer1; } if (buffer2 != NULL) { rxDesc->buff2Addr = (uint32_t)(uintptr_t)(uint8_t *)buffer2; } else { rxDesc->buff2Addr = 0; } rxDesc->reserved = 0; /* Add a data barrier to be sure that the address is written before the ownership bit status. */ __DMB(); rxDesc->control = control; } /*! * brief Setup a given tx descriptor. * This function is a low level functional API to setup or prepare * a given tx descriptor. * * param txDesc The given tx descriptor. * param buffer1 The first buffer address in the descriptor. * param bytes1 The bytes in the fist buffer. * param buffer2 The second buffer address in the descriptor. * param bytes1 The bytes in the second buffer. * param framelen The length of the frame to be transmitted. * param intEnable Interrupt enable flag. * param tsEnable The timestamp enable. * param flag The flag of this tx desciriptor, see "enet_qos_desc_flag" . * param slotNum The slot num used for AV only. * * note This must be called after all the ENET initilization. * And should be called when the ENET receive/transmit is required. * Transmit buffers are 'zero-copy' buffers, so the buffer must remain in * memory until the packet has been fully transmitted. The buffers * should be free or requeued in the transmit interrupt irq handler. */ void ENET_QOS_SetupTxDescriptor(enet_qos_tx_bd_struct_t *txDesc, void *buffer1, uint32_t bytes1, void *buffer2, uint32_t bytes2, uint32_t framelen, bool intEnable, bool tsEnable, enet_qos_desc_flag flag, uint8_t slotNum) { uint32_t control = ENET_QOS_TXDESCRIP_RD_BL1(bytes1) | ENET_QOS_TXDESCRIP_RD_BL2(bytes2); if (tsEnable) { control |= ENET_QOS_TXDESCRIP_RD_TTSE_MASK; } else { control &= ~ENET_QOS_TXDESCRIP_RD_TTSE_MASK; } if (intEnable) { control |= ENET_QOS_TXDESCRIP_RD_IOC_MASK; } else { control &= ~ENET_QOS_TXDESCRIP_RD_IOC_MASK; } #if defined(FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET) && FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET buffer1 = (void *)(uint8_t *)MEMORY_ConvertMemoryMapAddress((uintptr_t)(uint8_t *)buffer1, kMEMORY_Local2DMA); buffer2 = (void *)(uint8_t *)MEMORY_ConvertMemoryMapAddress((uintptr_t)(uint8_t *)buffer2, kMEMORY_Local2DMA); #endif /* FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET */ /* Preare the descriptor for transmit. */ txDesc->buff1Addr = (uint32_t)(uintptr_t)(uint8_t *)buffer1; txDesc->buff2Addr = (uint32_t)(uintptr_t)(uint8_t *)buffer2; txDesc->buffLen = control; /* Make sure all fields of descriptor are written before setting ownership */ __DMB(); control = ENET_QOS_TXDESCRIP_RD_FL(framelen) | ENET_QOS_TXDESCRIP_RD_LDFD(flag) | ENET_QOS_TXDESCRIP_RD_OWN_MASK; txDesc->controlStat = control; /* Make sure the descriptor is written in memory (before MAC starts checking it) */ __DSB(); } /*! * brief Reclaim tx descriptors. * This function is used to update the tx descriptor status and * store the tx timestamp when the 1588 feature is enabled. * This is called by the transmit interupt IRQ handler after the * complete of a frame transmission. * * param base ENET peripheral base address. * param handle The ENET handler pointer. This is the same handler pointer used in the ENET_QOS_Init. * param channel The tx DMA channnel. * */ void ENET_QOS_ReclaimTxDescriptor(ENET_QOS_Type *base, enet_qos_handle_t *handle, uint8_t channel) { enet_qos_tx_bd_ring_t *txBdRing = &handle->txBdRing[channel]; enet_qos_tx_bd_struct_t *txDesc = &txBdRing->txBdBase[txBdRing->txConsumIdx]; enet_qos_tx_dirty_ring_t *txDirtyRing = (enet_qos_tx_dirty_ring_t *)&handle->txDirtyRing[channel]; enet_qos_frame_info_t *txDirty = NULL; uint32_t control, primask; control = txDesc->controlStat; /* Need to update the first index for transmit buffer free. */ while ((txBdRing->txDescUsed > 0U) && (0U == (control & ENET_QOS_TXDESCRIP_RD_OWN_MASK))) { if ((control & ENET_QOS_TXDESCRIP_RD_LD_MASK) != 0U) { if (ENET_QOS_TxDirtyRingAvailable(txDirtyRing)) { txDirty = &txDirtyRing->txDirtyBase[txBdRing->txConsumIdx]; txDirtyRing->txGenIdx = ENET_QOS_IncreaseIndex(txDirtyRing->txGenIdx, txDirtyRing->txRingLen); if (txDirtyRing->txGenIdx == txDirtyRing->txConsumIdx) { txDirtyRing->isFull = true; } if ((control & ENET_QOS_TXDESCRIP_WB_TTSS_MASK) != 0U) { enet_qos_ptp_time_t *ts = &txDirty->timeStamp; uint32_t nanosecond; /* Get transmit time stamp second. */ nanosecond = txDesc->buff1Addr; txDirty->isTsAvail = true; if (0U == (base->MAC_TIMESTAMP_CONTROL & ENET_QOS_MAC_TIMESTAMP_CONTROL_TSCTRLSSR_MASK)) { /* Binary rollover, 0.465ns accuracy. */ nanosecond = (nanosecond * 465U) / 1000U; } ts->second = txDesc->buff2Addr; ts->nanosecond = nanosecond; } else { txDirty->isTsAvail = false; } } } /* For tx buffer free or requeue for each descriptor. * The tx interrupt callback should free/requeue the tx buffer. */ if (handle->callback != NULL) { handle->callback(base, handle, kENET_QOS_TxIntEvent, channel, handle->userData); } primask = DisableGlobalIRQ(); txBdRing->txDescUsed--; EnableGlobalIRQ(primask); /* Update the txConsumIdx/txDesc. */ txBdRing->txConsumIdx = ENET_QOS_IncreaseIndex(txBdRing->txConsumIdx, txBdRing->txRingLen); txDesc = &txBdRing->txBdBase[txBdRing->txConsumIdx]; control = txDesc->controlStat; } } /*! * brief Transmits an ENET frame. * note The CRC is automatically appended to the data. Input the data * to send without the CRC. * * param base ENET peripheral base address. * param handle The ENET handler pointer. This is the same handler pointer used in the ENET_QOS_Init. * param data The data buffer provided by user to be send. * param length The length of the data to be send. * param channel Channel to send the frame, same with queue index. * param isNeedTs True means save timestamp * param context pointer to user context to be kept in the tx dirty frame information. * retval kStatus_Success Send frame succeed. * retval kStatus_ENET_QOS_TxFrameBusy Transmit buffer descriptor is busy under transmission. * The transmit busy happens when the data send rate is over the MAC capacity. * The waiting mechanism is recommended to be added after each call return with * kStatus_ENET_QOS_TxFrameBusy. */ status_t ENET_QOS_SendFrame(ENET_QOS_Type *base, enet_qos_handle_t *handle, uint8_t *data, uint32_t length, uint8_t channel, bool isNeedTs, void *context) { assert(handle != NULL); assert(data != NULL); assert(channel < handle->txQueueUse); enet_qos_tx_bd_ring_t *txBdRing; enet_qos_tx_bd_struct_t *txDesc; enet_qos_tx_dirty_ring_t *txDirtyRing; enet_qos_frame_info_t *txDirty; uint32_t primask; uint32_t txDescTail; if (length > 2U * ENET_QOS_TXDESCRIP_RD_BL1_MASK) { return kStatus_ENET_QOS_TxFrameOverLen; } /* Check if the DMA owns the descriptor. */ txBdRing = (enet_qos_tx_bd_ring_t *)&handle->txBdRing[channel]; txDesc = &txBdRing->txBdBase[txBdRing->txGenIdx]; if (txBdRing->txRingLen == txBdRing->txDescUsed) { return kStatus_ENET_QOS_TxFrameBusy; } txDirtyRing = (enet_qos_tx_dirty_ring_t *)&handle->txDirtyRing[channel]; txDirty = &txDirtyRing->txDirtyBase[txBdRing->txGenIdx]; txDirty->context = context; /* Fill the descriptor. */ if (length <= ENET_QOS_TXDESCRIP_RD_BL1_MASK) { ENET_QOS_SetupTxDescriptor(txDesc, data, length, NULL, 0, length, true, isNeedTs, kENET_QOS_FirstLastFlag, 0); } else { ENET_QOS_SetupTxDescriptor(txDesc, data, ENET_QOS_TXDESCRIP_RD_BL1_MASK, &data[ENET_QOS_TXDESCRIP_RD_BL1_MASK], (length - ENET_QOS_TXDESCRIP_RD_BL1_MASK), length, true, isNeedTs, kENET_QOS_FirstLastFlag, 0); } /* Increase the index. */ txBdRing->txGenIdx = ENET_QOS_IncreaseIndex(txBdRing->txGenIdx, txBdRing->txRingLen); /* Disable interrupt first and then enable interrupt to avoid the race condition. */ primask = DisableGlobalIRQ(); txBdRing->txDescUsed++; EnableGlobalIRQ(primask); /* Update the transmit tail address. */ txDesc = &txBdRing->txBdBase[txBdRing->txGenIdx]; if (txBdRing->txGenIdx == 0U) { txDesc = &txBdRing->txBdBase[txBdRing->txRingLen]; } txDescTail = (uint32_t)(uintptr_t)txDesc & ~ENET_QOS_ADDR_ALIGNMENT; #if defined(FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET) && FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET txDescTail = MEMORY_ConvertMemoryMapAddress(txDescTail, kMEMORY_Local2DMA); #endif base->DMA_CH[channel].DMA_CHX_TXDESC_TAIL_PTR = txDescTail; return kStatus_Success; } /*! * brief Gets the sent frame. * * This function is used to get the sent frame for timestamp and buffer clean operation. * * param handle The ENET handler pointer.This is the same state pointer used in * ENET_QOS_Init. * param txFrame Input parameter, pointer to enet_qos_frame_info_t for saving read out frame information. * param channel Read out frame from specified channel. */ void ENET_QOS_GetTxFrame(enet_qos_handle_t *handle, enet_qos_frame_info_t *txFrame, uint8_t channel) { assert(handle != NULL); assert(channel < handle->txQueueUse); enet_qos_tx_dirty_ring_t *txDirtyRing = (enet_qos_tx_dirty_ring_t *)&handle->txDirtyRing[channel]; enet_qos_frame_info_t *txDirty = &txDirtyRing->txDirtyBase[txDirtyRing->txConsumIdx]; (void)memcpy(txFrame, txDirty, sizeof(enet_qos_frame_info_t)); txDirtyRing->isFull = false; txDirtyRing->txConsumIdx = ENET_QOS_IncreaseIndex(txDirtyRing->txConsumIdx, txDirtyRing->txRingLen); } static inline void ENET_QOS_GetRxFrameErr(enet_qos_rx_bd_struct_t *rxDesc, enet_qos_rx_frame_error_t *rxFrameError) { uint32_t rdes2 = rxDesc->buff2Addr; uint32_t rdes3 = rxDesc->control; (void)memset(rxFrameError, 0, sizeof(enet_qos_rx_frame_error_t)); if ((rdes2 & ENET_QOS_RXDESCRIP_WR_SA_FAILURE_MASK) != 0U) { rxFrameError->rxSrcAddrFilterErr = true; } if ((rdes2 & ENET_QOS_RXDESCRIP_WR_DA_FAILURE_MASK) != 0U) { rxFrameError->rxDstAddrFilterErr = true; } if ((rdes3 & ENET_QOS_RXDESCRIP_WR_DE_MASK) != 0U) { rxFrameError->rxDstAddrFilterErr = true; } if ((rdes3 & ENET_QOS_RXDESCRIP_WR_RE_MASK) != 0U) { rxFrameError->rxReceiveErr = true; } if ((rdes3 & ENET_QOS_RXDESCRIP_WR_OE_MASK) != 0U) { rxFrameError->rxOverFlowErr = true; } if ((rdes3 & ENET_QOS_RXDESCRIP_WR_RWT_MASK) != 0U) { rxFrameError->rxWatchDogErr = true; } if ((rdes3 & ENET_QOS_RXDESCRIP_WR_GP_MASK) != 0U) { rxFrameError->rxGaintPacketErr = true; } if ((rdes3 & ENET_QOS_RXDESCRIP_WR_CRC_MASK) != 0U) { rxFrameError->rxCrcErr = true; } } /*! * brief Receives one frame in specified BD ring with zero copy. * * This function will use the user-defined allocate and free callback. Every time application gets one frame through * this function, driver will allocate new buffers for the BDs whose buffers have been taken by application. * note This function will drop current frame and update related BDs as available for DMA if new buffers allocating * fails. Application must provide a memory pool including at least BD number + 1 buffers(+2 if enable double buffer) * to make this function work normally. If user calls this function in Rx interrupt handler, be careful that this * function makes Rx BD ready with allocating new buffer(normal) or updating current BD(out of memory). If there's * always new Rx frame input, Rx interrupt will be triggered forever. Application need to disable Rx interrupt according * to specific design in this case. * * param base ENET peripheral base address. * param handle The ENET handler pointer. This is the same handler pointer used in the ENET_Init. * param rxFrame The received frame information structure provided by user. * param ringId The ring index or ring number. * retval kStatus_Success Succeed to get one frame and allocate new memory for Rx buffer. * retval kStatus_ENET_QOS_RxFrameEmpty There's no Rx frame in the BD. * retval kStatus_ENET_QOS_RxFrameError There's issue in this receiving. * retval kStatus_ENET_QOS_RxFrameDrop There's no new buffer memory for BD, drop this frame. */ status_t ENET_QOS_GetRxFrame(ENET_QOS_Type *base, enet_qos_handle_t *handle, enet_qos_rx_frame_struct_t *rxFrame, uint8_t channel) { assert(handle != NULL); assert(channel < handle->rxQueueUse); enet_qos_rx_bd_ring_t *rxBdRing = (enet_qos_rx_bd_ring_t *)&handle->rxBdRing[channel]; enet_qos_rx_bd_struct_t *rxDesc = &rxBdRing->rxBdBase[rxBdRing->rxGenIdx]; uint16_t index = rxBdRing->rxGenIdx; status_t result = kStatus_Success; uintptr_t buff1Addr = 0; uintptr_t buff2Addr = 0; uint16_t buff1Len = 0; uint16_t buff2Len = 0; uint16_t offset = 0; void *newBuff1 = NULL; void *newBuff2 = NULL; bool isDrop = false; bool isLastBuff = false; bool tsAvailable = false; uint32_t rxDescTail; /* Check the frame status. */ do { if ((rxDesc->control & ENET_QOS_RXDESCRIP_WR_OWN_MASK) != 0U) { result = kStatus_ENET_QOS_RxFrameEmpty; break; } /* Check timestamp and error. */ if ((rxDesc->control & ENET_QOS_RXDESCRIP_WR_LD_MASK) != 0U) { if ((rxDesc->control & ENET_QOS_RXDESCRIP_WR_RS1V_MASK) != 0U) { if ((rxDesc->reserved & ENET_QOS_RXDESCRIP_WR_PTPTSA_MASK) != 0U) { /* Context descriptor is expected but might not be yet available. */ uint8_t retryTimes = 10; while (((rxDesc->control & ENET_QOS_RXDESCRIP_WR_OWN_MASK) != 0U) || ((rxDesc->control & ENET_QOS_RXDESCRIP_WR_CTXT_MASK) == 0U)) { /* Timsstamp value is not corrupted. */ if ((rxDesc->buff1Addr != 0xFFFFFFFFU) && (rxDesc->buff2Addr != 0xFFFFFFFFU)) { break; } if (retryTimes-- == 0U) { break; } } if (retryTimes != 0U) { tsAvailable = true; } else { result = kStatus_ENET_QOS_RxFrameEmpty; break; } } } /* Get the frame error if there is. */ if ((rxDesc->control & ENET_QOS_RXDESCRIP_WR_ERRSUM_MASK) != 0U) { ENET_QOS_GetRxFrameErr(rxDesc, &rxFrame->rxFrameError); result = kStatus_ENET_QOS_RxFrameError; } else if ((rxDesc->control & ENET_QOS_RXDESCRIP_WR_PACKETLEN_MASK) == 0U) { result = kStatus_ENET_QOS_RxFrameEmpty; } else { /* Intentional empty */ } break; } index = ENET_QOS_IncreaseIndex(index, rxBdRing->rxRingLen); if (index == rxBdRing->rxGenIdx) { result = kStatus_ENET_QOS_RxFrameEmpty; break; } rxDesc = &rxBdRing->rxBdBase[index]; } while (index != rxBdRing->rxGenIdx); /* Drop the error frame and return error. */ if (result != kStatus_Success) { if (result == kStatus_ENET_QOS_RxFrameError) { ENET_QOS_DropFrame(base, handle, channel); } return result; } /* Get the valid frame */ index = 0; do { rxDesc = &rxBdRing->rxBdBase[rxBdRing->rxGenIdx]; /* Caculate the buffer and frame length. */ if ((rxDesc->control & ENET_QOS_RXDESCRIP_WR_LD_MASK) != 0U) { isLastBuff = true; rxFrame->totLen = (uint16_t)(rxDesc->control & ENET_QOS_RXDESCRIP_WR_PACKETLEN_MASK); if (rxFrame->totLen - offset > (uint16_t)rxBdRing->rxBuffSizeAlign) { buff1Len = (uint16_t)rxBdRing->rxBuffSizeAlign; if (handle->doubleBuffEnable) { buff2Len = rxFrame->totLen - offset - (uint16_t)rxBdRing->rxBuffSizeAlign - ENET_QOS_FCS_LEN; } } else { buff1Len = rxFrame->totLen - offset - ENET_QOS_FCS_LEN; } rxFrame->totLen -= ENET_QOS_FCS_LEN; } else { if (!handle->doubleBuffEnable) { buff1Len = (uint16_t)rxBdRing->rxBuffSizeAlign; offset += buff1Len; } else { buff1Len = (uint16_t)rxBdRing->rxBuffSizeAlign; buff2Len = (uint16_t)rxBdRing->rxBuffSizeAlign; offset += buff1Len + buff2Len; } } /* Allocate new buffer to replace the buffer taken by application */ newBuff1 = handle->rxBuffAlloc(base, handle->userData, channel); if (newBuff1 == NULL) { isDrop = true; } else if (handle->doubleBuffEnable && (buff2Len != 0U)) { newBuff2 = handle->rxBuffAlloc(base, handle->userData, channel); if (newBuff2 == NULL) { handle->rxBuffFree(base, newBuff1, handle->userData, channel); isDrop = true; } } else { /* Intentional empty */ } if (!isDrop) { /* Get the frame data information into Rx frame structure. */ if (!handle->doubleBuffEnable) { buff1Addr = handle->rxBufferStartAddr[channel][rxBdRing->rxGenIdx]; #if defined(FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET) && FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET buff1Addr = MEMORY_ConvertMemoryMapAddress(buff1Addr, kMEMORY_DMA2Local); #endif /* FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET */ if (handle->rxMaintainEnable[channel]) { ENET_QOS_DcacheInvalidateByRange(buff1Addr, rxBdRing->rxBuffSizeAlign); } rxFrame->rxBuffArray[index].buffer = (void *)(uint8_t *)buff1Addr; rxFrame->rxBuffArray[index].length = buff1Len; index++; } else { buff1Addr = handle->rxBufferStartAddr[channel][2U * rxBdRing->rxGenIdx]; #if defined(FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET) && FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET buff1Addr = MEMORY_ConvertMemoryMapAddress(buff1Addr, kMEMORY_DMA2Local); #endif /* FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET */ if (handle->rxMaintainEnable[channel]) { ENET_QOS_DcacheInvalidateByRange(buff1Addr, rxBdRing->rxBuffSizeAlign); } rxFrame->rxBuffArray[index].buffer = (void *)(uint8_t *)buff1Addr; rxFrame->rxBuffArray[index].length = buff1Len; index++; /* If there's no data in buffer2, not add it into rxFrame */ if (buff2Len != 0U) { buff2Addr = handle->rxBufferStartAddr[channel][2U * rxBdRing->rxGenIdx + 1U]; #if defined(FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET) && FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET buff2Addr = MEMORY_ConvertMemoryMapAddress(buff2Addr, kMEMORY_DMA2Local); #endif /* FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET */ if (handle->rxMaintainEnable[channel]) { ENET_QOS_DcacheInvalidateByRange(buff2Addr, rxBdRing->rxBuffSizeAlign); } rxFrame->rxBuffArray[index].buffer = (void *)(uint8_t *)buff2Addr; rxFrame->rxBuffArray[index].length = buff2Len; index++; } } /* Give new buffer from application to BD */ if (!handle->doubleBuffEnable) { if (handle->rxMaintainEnable[channel]) { ENET_QOS_DcacheInvalidateByRange((uintptr_t)(uint8_t *)newBuff1, rxBdRing->rxBuffSizeAlign); } #if defined(FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET) && FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET buff1Addr = MEMORY_ConvertMemoryMapAddress((uintptr_t)(uint8_t *)newBuff1, kMEMORY_Local2DMA); #else buff1Addr = (uintptr_t)(uint8_t *)newBuff1; #endif handle->rxBufferStartAddr[channel][rxBdRing->rxGenIdx] = buff1Addr; ENET_QOS_UpdateRxDescriptor(rxDesc, (void *)(uint8_t *)buff1Addr, NULL, handle->rxintEnable, handle->doubleBuffEnable); } else { if (handle->rxMaintainEnable[channel]) { ENET_QOS_DcacheInvalidateByRange((uintptr_t)(uint8_t *)newBuff1, rxBdRing->rxBuffSizeAlign); } #if defined(FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET) && FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET buff1Addr = MEMORY_ConvertMemoryMapAddress((uintptr_t)(uint8_t *)newBuff1, kMEMORY_Local2DMA); #else buff1Addr = (uintptr_t)(uint8_t *)newBuff1; #endif handle->rxBufferStartAddr[channel][2U * rxBdRing->rxGenIdx] = buff1Addr; if (buff2Len != 0U) { if (handle->rxMaintainEnable[channel]) { ENET_QOS_DcacheInvalidateByRange((uintptr_t)(uint8_t *)newBuff2, rxBdRing->rxBuffSizeAlign); } #if defined(FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET) && FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET buff2Addr = (uint32_t)MEMORY_ConvertMemoryMapAddress((uintptr_t)(uint8_t *)newBuff2, kMEMORY_Local2DMA); #else buff2Addr = (uintptr_t)(uint8_t *)newBuff2; #endif handle->rxBufferStartAddr[channel][2U * rxBdRing->rxGenIdx + 1U] = buff2Addr; } else { /* If there's no data in buffer2, keep it */ buff2Addr = handle->rxBufferStartAddr[channel][2U * rxBdRing->rxGenIdx + 1U]; } ENET_QOS_UpdateRxDescriptor(rxDesc, (void *)(uint8_t *)buff1Addr, (void *)(uint8_t *)buff2Addr, handle->rxintEnable, handle->doubleBuffEnable); } rxBdRing->rxGenIdx = ENET_QOS_IncreaseIndex(rxBdRing->rxGenIdx, rxBdRing->rxRingLen); /* Update context BD if there is */ if (isLastBuff && tsAvailable) { rxDesc = &rxBdRing->rxBdBase[rxBdRing->rxGenIdx]; if ((rxDesc->control & ENET_QOS_RXDESCRIP_WR_CTXT_MASK) != 0U) { ENET_QOS_StoreRxFrameTime(base, handle, rxDesc, &rxFrame->rxAttribute.timestamp); rxFrame->rxAttribute.isTsAvail = true; if (!handle->doubleBuffEnable) { buff1Addr = handle->rxBufferStartAddr[channel][rxBdRing->rxGenIdx]; ENET_QOS_UpdateRxDescriptor(rxDesc, (void *)(uint8_t *)buff1Addr, NULL, handle->rxintEnable, handle->doubleBuffEnable); } else { buff1Addr = handle->rxBufferStartAddr[channel][2U * rxBdRing->rxGenIdx]; buff2Addr = handle->rxBufferStartAddr[channel][2U * rxBdRing->rxGenIdx + 1U]; ENET_QOS_UpdateRxDescriptor(rxDesc, (void *)(uint8_t *)buff1Addr, (void *)(uint8_t *)buff2Addr, handle->rxintEnable, handle->doubleBuffEnable); } rxBdRing->rxGenIdx = ENET_QOS_IncreaseIndex(rxBdRing->rxGenIdx, rxBdRing->rxRingLen); } } /* Always try to start receive, in case it had stopped */ rxDescTail = (uint32_t)(uintptr_t)&rxBdRing->rxBdBase[rxBdRing->rxRingLen]; #if defined(FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET) && FSL_FEATURE_MEMORY_HAS_ADDRESS_OFFSET rxDescTail = MEMORY_ConvertMemoryMapAddress(rxDescTail, kMEMORY_Local2DMA); #endif base->DMA_CH[channel].DMA_CHX_RXDESC_TAIL_PTR = rxDescTail; } else { /* Drop frame if there's no new buffer memory */ /* Free the incomplete frame buffers. */ while (index-- != 0U) { handle->rxBuffFree(base, &rxFrame->rxBuffArray[index].buffer, handle->userData, channel); } /* Update all left BDs of this frame from current index. */ ENET_QOS_DropFrame(base, handle, channel); result = kStatus_ENET_QOS_RxFrameDrop; break; } } while (!isLastBuff); return result; } /*! * brief Gets the current ENET time from the PTP 1588 timer without IRQ disable. * * param base ENET peripheral base address. * param second The PTP 1588 system timer second. * param nanosecond The PTP 1588 system timer nanosecond. * For the unit of the nanosecond is 1ns. so the nanosecond is the real nanosecond. */ void ENET_QOS_Ptp1588GetTimerNoIRQDisable(ENET_QOS_Type *base, uint64_t *second, uint32_t *nanosecond) { assert(second != NULL); assert(nanosecond != NULL); uint32_t high_sec[2]; uint32_t sec[2]; /* Get the current PTP time. */ /* Since register reads are not atomic, we need to check for wraps during the read */ high_sec[1] = base->MAC_SYSTEM_TIME_HIGHER_WORD_SECONDS & ENET_QOS_MAC_SYSTEM_TIME_HIGHER_WORD_SECONDS_TSHWR_MASK; do { high_sec[0] = high_sec[1]; sec[1] = base->MAC_SYSTEM_TIME_SECONDS; do { sec[0] = sec[1]; *nanosecond = base->MAC_SYSTEM_TIME_NANOSECONDS & ENET_QOS_MAC_SYSTEM_TIME_NANOSECONDS_TSSS_MASK; sec[1] = base->MAC_SYSTEM_TIME_SECONDS; } while (sec[1] != sec[0]); high_sec[1] = base->MAC_SYSTEM_TIME_HIGHER_WORD_SECONDS & ENET_QOS_MAC_SYSTEM_TIME_HIGHER_WORD_SECONDS_TSHWR_MASK; } while (high_sec[1] != high_sec[0]); *second = ((uint64_t)high_sec[1] << 32U) | sec[1]; if ((base->MAC_TIMESTAMP_CONTROL & ENET_QOS_MAC_TIMESTAMP_CONTROL_TSCTRLSSR_MASK) == 0U) { /* Binary rollover, the unit of the increment is ~ 0.465 ns. */ *nanosecond = (*nanosecond * 465U) / 1000U; } } /*! * brief Gets the current ENET time from the PTP 1588 timer, get a more accurate value * with IRQ disabled during get timer. * * param base ENET peripheral base address. * param second The PTP 1588 system timer second. * param nanosecond The PTP 1588 system timer nanosecond. * For the unit of the nanosecond is 1ns. so the nanosecond is the real nanosecond. */ void ENET_QOS_Ptp1588GetTimer(ENET_QOS_Type *base, uint64_t *second, uint32_t *nanosecond) { uint32_t primask; /* Disables the interrupt. */ primask = DisableGlobalIRQ(); ENET_QOS_Ptp1588GetTimerNoIRQDisable(base, second, nanosecond); /* Enables the interrupt. */ EnableGlobalIRQ(primask); } /*! * brief Coreect the ENET PTP 1588 timer in coarse method. * * param base ENET peripheral base address. * param operation The system time operation, refer to "enet_qos_systime_op" * param second The correction second. * param nanosecond The correction nanosecond. */ status_t ENET_QOS_Ptp1588CorrectTimerInCoarse(ENET_QOS_Type *base, enet_qos_systime_op operation, uint32_t second, uint32_t nanosecond) { uint32_t corrSecond = second; uint32_t corrNanosecond; status_t result = kStatus_Success; /* Set the system timer. */ if ((base->MAC_TIMESTAMP_CONTROL & ENET_QOS_MAC_TIMESTAMP_CONTROL_TSCTRLSSR_MASK) != 0U) { if (operation == kENET_QOS_SystimeSubtract) { /* Set with the complement of the sub-second. */ corrSecond = ENET_QOS_MAC_SYSTEM_TIME_SECONDS_UPDATE_TSS_MASK - (second - 1U); corrNanosecond = ENET_QOS_MAC_SYSTEM_TIME_NANOSECONDS_UPDATE_ADDSUB_MASK | ENET_QOS_MAC_SYSTEM_TIME_NANOSECONDS_UPDATE_TSSS(ENET_QOS_NANOSECS_ONESECOND - nanosecond); } else { corrNanosecond = ENET_QOS_MAC_SYSTEM_TIME_NANOSECONDS_UPDATE_TSSS(nanosecond); } } else { nanosecond = ENET_QOS_MAC_SYSTEM_TIME_NANOSECONDS_UPDATE_TSSS_MASK / ENET_QOS_NANOSECS_ONESECOND * nanosecond; if (operation == kENET_QOS_SystimeSubtract) { /* Set with the complement of the sub-second. */ corrSecond = ENET_QOS_MAC_SYSTEM_TIME_SECONDS_UPDATE_TSS_MASK - (second - 1U); corrNanosecond = ENET_QOS_MAC_SYSTEM_TIME_NANOSECONDS_UPDATE_ADDSUB_MASK | ENET_QOS_MAC_SYSTEM_TIME_NANOSECONDS_UPDATE_TSSS( ENET_QOS_MAC_SYSTEM_TIME_NANOSECONDS_UPDATE_TSSS_MASK + 1U - nanosecond); } else { corrNanosecond = ENET_QOS_MAC_SYSTEM_TIME_NANOSECONDS_UPDATE_TSSS(nanosecond); } } base->MAC_SYSTEM_TIME_SECONDS_UPDATE = corrSecond; base->MAC_SYSTEM_TIME_NANOSECONDS_UPDATE = corrNanosecond; /* Update the timer. */ base->MAC_TIMESTAMP_CONTROL |= ENET_QOS_MAC_TIMESTAMP_CONTROL_TSUPDT_MASK; /* Wait for update finish */ result = ENET_QOS_PollStatusFlag(&(base->MAC_TIMESTAMP_CONTROL), ENET_QOS_MAC_TIMESTAMP_CONTROL_TSUPDT_MASK, 0U); return result; } /*! * brief Correct the ENET PTP 1588 timer in fine method. * * * param base ENET peripheral base address. * param addend The addend value to be set in the fine method * note Should take refer to the chapter "System time correction" and * see the description for the "fine correction method". */ status_t ENET_QOS_Ptp1588CorrectTimerInFine(ENET_QOS_Type *base, uint32_t addend) { status_t result = kStatus_Success; base->MAC_TIMESTAMP_ADDEND = addend; base->MAC_TIMESTAMP_CONTROL |= ENET_QOS_MAC_TIMESTAMP_CONTROL_TSADDREG_MASK; result = ENET_QOS_PollStatusFlag(&(base->MAC_TIMESTAMP_CONTROL), ENET_QOS_MAC_TIMESTAMP_CONTROL_TSADDREG_MASK, 0U); return result; } /*! * @brief Sets the ENET OQS PTP 1588 PPS target time registers. * * param base ENET QOS peripheral base address. * param instance The ENET QOS PTP PPS instance. * param seconds The target seconds. * param nanoseconds The target nanoseconds. */ status_t ENET_QOS_Ptp1588PpsSetTrgtTime(ENET_QOS_Type *base, enet_qos_ptp_pps_instance_t instance, uint32_t seconds, uint32_t nanoseconds) { uint32_t *mac_pps_trgt_ns; uint32_t *mac_pps_trgt_s; mac_pps_trgt_ns = (uint32_t *)((uintptr_t)&base->MAC_PPS0_TARGET_TIME_NANOSECONDS + 0x10U * (uint32_t)instance); mac_pps_trgt_s = (uint32_t *)((uintptr_t)&base->MAC_PPS0_TARGET_TIME_SECONDS + 0x10U * (uint32_t)instance); if ((*mac_pps_trgt_ns & ENET_QOS_MAC_PPS0_TARGET_TIME_NANOSECONDS_TRGTBUSY0_MASK) != 0U) { return kStatus_ENET_QOS_TrgtBusy; } *mac_pps_trgt_ns = ENET_QOS_MAC_PPS0_TARGET_TIME_NANOSECONDS_TTSL0(nanoseconds); *mac_pps_trgt_s = ENET_QOS_MAC_PPS0_TARGET_TIME_SECONDS_TSTRH0(seconds); return kStatus_Success; } static status_t ENET_QOS_EstReadWriteWord( ENET_QOS_Type *base, uint32_t addr, uint32_t *data, uint8_t gcrr, uint8_t read, uint8_t dbgm) { uint32_t ctrl; int retry = 10; ctrl = ENET_QOS_MTL_EST_GCL_CONTROL_ADDR(addr) | ENET_QOS_MTL_EST_GCL_CONTROL_SRWO(1) | ENET_QOS_MTL_EST_GCL_CONTROL_DBGM(dbgm) | ENET_QOS_MTL_EST_GCL_CONTROL_GCRR(gcrr); if (read != 0U) { ctrl |= ENET_QOS_MTL_EST_GCL_CONTROL_R1W0(1); } else { base->MTL_EST_GCL_DATA = *data; } base->MTL_EST_GCL_CONTROL = ctrl; while ((base->MTL_EST_GCL_CONTROL & ENET_QOS_MTL_EST_GCL_CONTROL_SRWO_MASK) != 0U) { if (retry-- < 0) { return kStatus_Timeout; } SDK_DelayAtLeastUs(1, SDK_DEVICE_MAXIMUM_CPU_CLOCK_FREQUENCY); } if (read != 0U) { *data = base->MTL_EST_GCL_DATA; } if ((base->MTL_EST_GCL_CONTROL & ENET_QOS_MTL_EST_GCL_CONTROL_ERR0_MASK) != 0U) { return kStatus_ENET_QOS_Est_SwListWriteAbort; } return kStatus_Success; } static status_t ENET_QOS_EstProgramWord(ENET_QOS_Type *base, uint32_t addr, uint32_t *data, uint8_t gcrr) { return ENET_QOS_EstReadWriteWord(base, addr, data, gcrr, 0, 0); } static status_t ENET_QOS_EstReadWord(ENET_QOS_Type *base, uint32_t addr, uint32_t *data, uint8_t gcrr, uint8_t dbgm) { return ENET_QOS_EstReadWriteWord(base, addr, data, gcrr, 1, dbgm); } /*! * @brief Program Gate Control List. * * This function is used to program the Enhanced Scheduled Transmisson. (IEEE802.1Qbv) * * @param base ENET peripheral base address.. * @param gcl Pointer to the Gate Control List structure. * @param ptpClk_Hz frequency of the PTP clock. */ status_t ENET_QOS_EstProgramGcl(ENET_QOS_Type *base, enet_qos_est_gcl_t *gcl, uint32_t ptpClk_Hz) { assert(gcl != NULL); uint32_t i, control, data; enet_qos_est_gate_op_t *gateOp; status_t rc; #define EST_MAX_INTERVAL ((1UL << ENET_QOS_EST_WID) - 1U) #define EST_MAX_GATE ((1UL << (32U - ENET_QOS_EST_WID)) - 1U) if (!gcl->enable) { goto exit; } /* Sanity checks */ if (gcl->numEntries > ENET_QOS_EST_DEP) { return kStatus_ENET_QOS_Est_InvalidParameter; } if (gcl->opList == NULL) { return kStatus_ENET_QOS_Est_InvalidParameter; } gateOp = gcl->opList; for (i = 0; i < gcl->numEntries; i++) { if (gateOp->interval > EST_MAX_INTERVAL) { return kStatus_ENET_QOS_Est_InvalidParameter; } if (gateOp->gate > EST_MAX_GATE) { return kStatus_ENET_QOS_Est_InvalidParameter; } gateOp++; } /* Check if sw list is busy */ if ((base->MTL_EST_CONTROL & ENET_QOS_MTL_EST_CONTROL_SSWL_MASK) != 0U) { return kStatus_ENET_QOS_Est_SwListBusy; } gateOp = gcl->opList; for (i = 0; i < gcl->numEntries; i++) { data = gateOp->interval | (gateOp->gate << ENET_QOS_EST_WID); rc = ENET_QOS_EstProgramWord(base, i, &data, 0); if (rc != kStatus_Success) { return rc; } gateOp++; } /* BTR High */ data = (uint32_t)(gcl->baseTime >> 32U); rc = ENET_QOS_EstProgramWord(base, (uint32_t)kENET_QOS_Ets_btr_high, &data, 1U); if (rc != kStatus_Success) { return rc; } /* BTR Low */ data = (uint32_t)gcl->baseTime; rc = ENET_QOS_EstProgramWord(base, (uint32_t)kENET_QOS_Ets_btr_low, &data, 1); if (rc != kStatus_Success) { return rc; } /* CTR High */ data = (uint32_t)(gcl->cycleTime >> 32U); rc = ENET_QOS_EstProgramWord(base, (uint32_t)kENET_QOS_Ets_ctr_high, &data, 1); if (rc != kStatus_Success) { return rc; } /* CTR Low */ data = (uint32_t)gcl->cycleTime; rc = ENET_QOS_EstProgramWord(base, (uint32_t)kENET_QOS_Ets_ctr_low, &data, 1); if (rc != kStatus_Success) { return rc; } /* TER */ data = gcl->extTime; rc = ENET_QOS_EstProgramWord(base, (uint32_t)kENET_QOS_Ets_ter, &data, 1); if (rc != kStatus_Success) { return rc; } /* LLR */ data = gcl->numEntries; rc = ENET_QOS_EstProgramWord(base, (uint32_t)kENET_QOS_Ets_llr, &data, 1); if (rc != kStatus_Success) { return rc; } exit: control = base->MTL_EST_CONTROL; if (gcl->enable) { control &= ~ENET_QOS_MTL_EST_CONTROL_PTOV_MASK; control |= ENET_QOS_MTL_EST_CONTROL_SSWL_MASK | ENET_QOS_MTL_EST_CONTROL_EEST_MASK | ENET_QOS_MTL_EST_CONTROL_PTOV((1000000000U / ptpClk_Hz) * 6U); } else { control &= ~ENET_QOS_MTL_EST_CONTROL_EEST_MASK; } base->MTL_EST_CONTROL = control; return kStatus_Success; } /*! * @brief Read Gate Control List. * * This function is used to read the Enhanced Scheduled Transmisson list. (IEEE802.1Qbv) * * @param base ENET peripheral base address.. * @param gcl Pointer to the Gate Control List structure. * @param listLen length of the provided opList array in gcl structure. * @param hwList Boolean if True read HW list, false read SW list. */ status_t ENET_QOS_EstReadGcl(ENET_QOS_Type *base, enet_qos_est_gcl_t *gcl, uint32_t listLen, bool hwList) { assert(gcl != NULL); assert(gcl->opList != NULL); uint8_t dbgm = 0; uint32_t data, i; enet_qos_est_gate_op_t *gateOp; status_t rc; if (hwList == true) { dbgm = 1; } /* LLR */ rc = ENET_QOS_EstReadWord(base, (uint32_t)kENET_QOS_Ets_llr, &data, 1, dbgm); if (rc != kStatus_Success) { return rc; } gcl->numEntries = data; if (gcl->numEntries > listLen) { return kStatus_ENET_QOS_Est_InvalidParameter; } /* BTR High */ rc = ENET_QOS_EstReadWord(base, (uint32_t)kENET_QOS_Ets_btr_high, &data, 1, dbgm); if (rc != kStatus_Success) { return rc; } gcl->baseTime = (uint64_t)data << 32U; /* BTR Low */ rc = ENET_QOS_EstReadWord(base, (uint32_t)kENET_QOS_Ets_btr_low, &data, 1, dbgm); if (rc != kStatus_Success) { return rc; } gcl->baseTime |= data; /* CTR High */ rc = ENET_QOS_EstReadWord(base, (uint32_t)kENET_QOS_Ets_ctr_high, &data, 1, dbgm); if (rc != kStatus_Success) { return rc; } gcl->cycleTime = (uint64_t)data << 32U; /* CTR Low */ rc = ENET_QOS_EstReadWord(base, (uint32_t)kENET_QOS_Ets_ctr_low, &data, 1, dbgm); if (rc != kStatus_Success) { return rc; } gcl->cycleTime |= data; /* TER */ rc = ENET_QOS_EstReadWord(base, (uint32_t)kENET_QOS_Ets_ter, &data, 1, dbgm); if (rc != kStatus_Success) { return rc; } gcl->extTime = data; gateOp = gcl->opList; for (i = 0; i < gcl->numEntries; i++) { rc = ENET_QOS_EstReadWord(base, i, &data, 0, dbgm); if (rc != kStatus_Success) { return rc; } gateOp->interval = data & (EST_MAX_INTERVAL); gateOp->gate = data >> ENET_QOS_EST_WID; gateOp++; } return kStatus_Success; } /*! * brief Read flexible rx parser configuration at specified index. * * This function is used to read flexible rx parser configuration at specified index. * * param base ENET peripheral base address.. * param rxpConfig The rx parser configuration pointer. * param entryIndex The rx parser entry index to read, start from 0. * retval kStatus_Success Configure rx parser success. * retval kStatus_ENET_QOS_Timeout Poll status flag timeout. */ status_t ENET_QOS_ReadRxParser(ENET_QOS_Type *base, enet_qos_rxp_config_t *rxpConfig, uint16_t entryIndex) { assert(rxpConfig != NULL); assert(entryIndex < ENET_QOS_RXP_ENTRY_COUNT); uint32_t *dataPtr; uint8_t entrySize = sizeof(enet_qos_rxp_config_t) / sizeof(uint32_t); uint32_t value = 0U; status_t result = kStatus_Success; /* Wait hardware not busy */ result = ENET_QOS_PollStatusFlag(&(base->MTL_RXP_INDIRECT_ACC_CONTROL_STATUS), ENET_QOS_MTL_RXP_INDIRECT_ACC_CONTROL_STATUS_STARTBUSY_MASK, 0U); if (kStatus_Success != result) { return result; } for (uint8_t i = 0; i < entrySize; i++) { /* Read address. */ value = ENET_QOS_MTL_RXP_INDIRECT_ACC_CONTROL_STATUS_ADDR((uint32_t)entrySize * entryIndex + i); /* Issue read command. */ value &= ~ENET_QOS_MTL_RXP_INDIRECT_ACC_CONTROL_STATUS_WRRDN_MASK; base->MTL_RXP_INDIRECT_ACC_CONTROL_STATUS = value; /* Start Read */ value |= ENET_QOS_MTL_RXP_INDIRECT_ACC_CONTROL_STATUS_STARTBUSY_MASK; base->MTL_RXP_INDIRECT_ACC_CONTROL_STATUS = value; /* Wait hardware not busy */ result = ENET_QOS_PollStatusFlag(&base->MTL_RXP_INDIRECT_ACC_CONTROL_STATUS, ENET_QOS_MTL_RXP_INDIRECT_ACC_CONTROL_STATUS_STARTBUSY_MASK, 0U); if (kStatus_Success != result) { return result; } dataPtr = (uint32_t *)(void *)&rxpConfig[entryIndex]; dataPtr = &dataPtr[i]; /* Read data */ *dataPtr = base->MTL_RXP_INDIRECT_ACC_DATA; } return result; } /*! * brief Configure flexible rx parser. * * This function is used to configure the flexible rx parser table. * * param base ENET peripheral base address.. * param rxpConfig The rx parser configuration pointer. * param entryCount The rx parser entry count. * retval kStatus_Success Configure rx parser success. * retval kStatus_ENET_QOS_Timeout Poll status flag timeout. */ status_t ENET_QOS_ConfigureRxParser(ENET_QOS_Type *base, enet_qos_rxp_config_t *rxpConfig, uint16_t entryCount) { assert(rxpConfig != NULL); assert(entryCount <= ENET_QOS_RXP_ENTRY_COUNT); uint32_t *dataPtr; uint32_t entrySize = sizeof(enet_qos_rxp_config_t) / sizeof(uint32_t); uint32_t value = 0U; status_t result = kStatus_Success; bool enableRx = false; /* Disable the MAC rx. */ if (0U != (base->MAC_CONFIGURATION & ENET_QOS_MAC_CONFIGURATION_RE_MASK)) { base->MAC_CONFIGURATION &= ~ENET_QOS_MAC_CONFIGURATION_RE_MASK; enableRx = true; } /* Disable frame parser. */ result = ENET_QOS_EnableRxParser(base, false); if (kStatus_Success != result) { return result; } for (uint8_t count = 0; count < entryCount; count++) { for (uint8_t i = 0; i < entrySize; i++) { /* Wait hardware not busy */ result = ENET_QOS_PollStatusFlag(&base->MTL_RXP_INDIRECT_ACC_CONTROL_STATUS, ENET_QOS_MTL_RXP_INDIRECT_ACC_CONTROL_STATUS_STARTBUSY_MASK, 0U); if (kStatus_Success != result) { return result; } dataPtr = (uint32_t *)(void *)&rxpConfig[count]; dataPtr = &dataPtr[i]; /* Write data before issue write command */ base->MTL_RXP_INDIRECT_ACC_DATA = *dataPtr; /* Write address and issue write command */ value = ENET_QOS_MTL_RXP_INDIRECT_ACC_CONTROL_STATUS_ADDR(entrySize * count + i); // base->MTL_RXP_INDIRECT_ACC_CONTROL_STATUS = value; value |= ENET_QOS_MTL_RXP_INDIRECT_ACC_CONTROL_STATUS_WRRDN_MASK; base->MTL_RXP_INDIRECT_ACC_CONTROL_STATUS = value; /* Start write */ value |= ENET_QOS_MTL_RXP_INDIRECT_ACC_CONTROL_STATUS_STARTBUSY_MASK; base->MTL_RXP_INDIRECT_ACC_CONTROL_STATUS = value; } } /* Wait hardware not busy */ result = ENET_QOS_PollStatusFlag(&(base->MTL_RXP_INDIRECT_ACC_CONTROL_STATUS), ENET_QOS_MTL_RXP_INDIRECT_ACC_CONTROL_STATUS_STARTBUSY_MASK, 0U); if (kStatus_Success != result) { return result; } /* Program NVE and NPE. */ value = base->MTL_RXP_CONTROL_STATUS; value &= ~(ENET_QOS_MTL_RXP_CONTROL_STATUS_NVE_MASK | ENET_QOS_MTL_RXP_CONTROL_STATUS_NPE_MASK); value |= ENET_QOS_MTL_RXP_CONTROL_STATUS_NPE((uint32_t)entryCount - 1U); if (entryCount < 3U) { value |= ENET_QOS_MTL_RXP_CONTROL_STATUS_NVE(2U); } else { value |= ENET_QOS_MTL_RXP_CONTROL_STATUS_NVE((uint32_t)entryCount - 1U); } base->MTL_RXP_CONTROL_STATUS = value; /* Enable frame parser. */ result = ENET_QOS_EnableRxParser(base, true); /* Enable Receive */ if (enableRx) { base->MAC_CONFIGURATION |= ENET_QOS_MAC_CONFIGURATION_RE_MASK; } return result; } /*! * brief Gets statistical data in transfer. * * param base ENET_QOS peripheral base address. * param statistics The statistics structure pointer. */ void ENET_QOS_GetStatistics(ENET_QOS_Type *base, enet_qos_transfer_stats_t *statistics) { /* Rx statistics */ statistics->statsRxFrameCount = base->MAC_RX_PACKETS_COUNT_GOOD_BAD; statistics->statsRxCrcErr = base->MAC_RX_CRC_ERROR_PACKETS; statistics->statsRxAlignErr = base->MAC_RX_ALIGNMENT_ERROR_PACKETS; statistics->statsRxLengthErr = base->MAC_RX_LENGTH_ERROR_PACKETS; statistics->statsRxFifoOverflowErr = base->MAC_RX_FIFO_OVERFLOW_PACKETS; /* Tx statistics */ statistics->statsTxFrameCount = base->MAC_TX_PACKET_COUNT_GOOD_BAD; statistics->statsTxFifoUnderRunErr = base->MAC_TX_UNDERFLOW_ERROR_PACKETS; } /*! * brief The ENET IRQ handler. * * param base ENET peripheral base address. * param handle The ENET handler pointer. */ void ENET_QOS_CommonIRQHandler(ENET_QOS_Type *base, enet_qos_handle_t *handle) { /* Check for the interrupt source type. */ /* DMA CHANNEL 0. */ if ((base->DMA_INTERRUPT_STATUS & ENET_QOS_DMA_INTERRUPT_STATUS_DC0IS_MASK) != 0U) { uint32_t flag = base->DMA_CH[0].DMA_CHX_STAT; if ((flag & ENET_QOS_DMA_CHX_STAT_RI_MASK) != 0U) { base->DMA_CH[0].DMA_CHX_STAT = ENET_QOS_DMA_CHX_STAT_RI_MASK | ENET_QOS_DMA_CHX_STAT_NIS_MASK; if (handle->callback != NULL) { handle->callback(base, handle, kENET_QOS_RxIntEvent, 0, handle->userData); } } if ((flag & ENET_QOS_DMA_CHX_STAT_TI_MASK) != 0U) { base->DMA_CH[0].DMA_CHX_STAT = ENET_QOS_DMA_CHX_STAT_TI_MASK | ENET_QOS_DMA_CHX_STAT_NIS_MASK; ENET_QOS_ReclaimTxDescriptor(base, handle, 0); } } /* DMA CHANNEL 1. */ if ((base->DMA_INTERRUPT_STATUS & ENET_QOS_DMA_INTERRUPT_STATUS_DC1IS_MASK) != 0U) { uint32_t flag = base->DMA_CH[1].DMA_CHX_STAT; if ((flag & ENET_QOS_DMA_CHX_STAT_RI_MASK) != 0U) { base->DMA_CH[1].DMA_CHX_STAT = ENET_QOS_DMA_CHX_STAT_RI_MASK | ENET_QOS_DMA_CHX_STAT_NIS_MASK; if (handle->callback != NULL) { handle->callback(base, handle, kENET_QOS_RxIntEvent, 1, handle->userData); } } if ((flag & ENET_QOS_DMA_CHX_STAT_TI_MASK) != 0U) { base->DMA_CH[1].DMA_CHX_STAT = ENET_QOS_DMA_CHX_STAT_TI_MASK | ENET_QOS_DMA_CHX_STAT_NIS_MASK; ENET_QOS_ReclaimTxDescriptor(base, handle, 1); } } /* DMA CHANNEL 2. */ if ((base->DMA_INTERRUPT_STATUS & ENET_QOS_DMA_INTERRUPT_STATUS_DC2IS_MASK) != 0U) { uint32_t flag = base->DMA_CH[2].DMA_CHX_STAT; if ((flag & ENET_QOS_DMA_CHX_STAT_RI_MASK) != 0U) { base->DMA_CH[2].DMA_CHX_STAT = ENET_QOS_DMA_CHX_STAT_RI_MASK | ENET_QOS_DMA_CHX_STAT_NIS_MASK; if (handle->callback != NULL) { handle->callback(base, handle, kENET_QOS_RxIntEvent, 2, handle->userData); } } if ((flag & ENET_QOS_DMA_CHX_STAT_TI_MASK) != 0U) { base->DMA_CH[2].DMA_CHX_STAT = ENET_QOS_DMA_CHX_STAT_TI_MASK | ENET_QOS_DMA_CHX_STAT_NIS_MASK; ENET_QOS_ReclaimTxDescriptor(base, handle, 2); } } /* DMA CHANNEL 3. */ if ((base->DMA_INTERRUPT_STATUS & ENET_QOS_DMA_INTERRUPT_STATUS_DC3IS_MASK) != 0U) { uint32_t flag = base->DMA_CH[3].DMA_CHX_STAT; if ((flag & ENET_QOS_DMA_CHX_STAT_RI_MASK) != 0U) { base->DMA_CH[3].DMA_CHX_STAT = ENET_QOS_DMA_CHX_STAT_RI_MASK | ENET_QOS_DMA_CHX_STAT_NIS_MASK; if (handle->callback != NULL) { handle->callback(base, handle, kENET_QOS_RxIntEvent, 3, handle->userData); } } if ((flag & ENET_QOS_DMA_CHX_STAT_TI_MASK) != 0U) { base->DMA_CH[3].DMA_CHX_STAT = ENET_QOS_DMA_CHX_STAT_TI_MASK | ENET_QOS_DMA_CHX_STAT_NIS_MASK; ENET_QOS_ReclaimTxDescriptor(base, handle, 3); } } /* MAC TIMESTAMP. */ if ((base->DMA_INTERRUPT_STATUS & ENET_QOS_DMA_INTERRUPT_STATUS_MACIS_MASK) != 0U) { if ((base->MAC_INTERRUPT_STATUS & ENET_QOS_MAC_INTERRUPT_STATUS_TSIS_MASK) != 0U) { if (handle->callback != NULL) { handle->callback(base, handle, kENET_QOS_TimeStampIntEvent, 0, handle->userData); } } } SDK_ISR_EXIT_BARRIER; } #if defined(ENET_QOS) void ENET_QOS_DriverIRQHandler(void); void ENET_QOS_DriverIRQHandler(void) { s_enetqosIsr(ENET_QOS, s_ENETHandle[0]); } #endif #if defined(CONNECTIVITY__ENET_QOS) void CONNECTIVITY_EQOS_INT_DriverIRQHandler(void); void CONNECTIVITY_EQOS_INT_DriverIRQHandler(void) { s_enetqosIsr(CONNECTIVITY__ENET_QOS, s_ENETHandle[0]); } #endif
1360a0fbec476a265b1dd3e48c59d68f19508c22
086cfcedd5742ff9377d3d235ddc3c3664fa0d94
/c/network/ex1/server.c
35703838a30d656b970a977b2737d89ca153184d
[ "MIT" ]
permissive
honux77/practice
27a6acb20ed55653455ee8dec393b898db08ed7b
e1f393e0f5d271b94a677d44b6a991845f8b0db8
refs/heads/master
2023-08-17T11:15:12.106266
2023-08-09T12:48:26
2023-08-09T12:48:26
18,316,426
161
33
MIT
2023-03-04T07:56:20
2014-04-01T03:23:15
JavaScript
UTF-8
C
false
false
446
c
server.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/socket.h> #include <sys/types.h> int main(int argc, char *argv[]) { int serv_socket; int clnt_socket; struct sockaddr_in serv_addr; struct sockaddr_in clnt_addr; socklen_t clnt_addr_size; if (argc != 2) { printf("Usage :% <port>\n", argv[0]); exit(1); } serv_socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
02e795df7281287f6bc6e2829fe847e1bc700b72
9746c6821b6c13e9089f1eeee1b53efcafb4a84f
/src/signal.c
b3e2f7686f6bb3d834ad0de662e91dc10f7512b1
[ "MIT" ]
permissive
intel/kernel-fuzzer-for-xen-project
3c953d3e2ff8d497435b3eddd2b3bcce570f705c
3458cf6ecdddf4aa3d85484915eb4fa7d2f378e4
refs/heads/master
2023-08-20T22:14:24.086023
2023-05-26T18:56:48
2023-05-26T18:56:48
261,611,628
457
80
MIT
2023-05-26T18:56:49
2020-05-06T00:14:07
C
UTF-8
C
false
false
914
c
signal.c
/* * Copyright (C) 2020 Intel Corporation * SPDX-License-Identifier: MIT */ #include "vmi.h" #include "signal.h" #include "tracer.h" static struct sigaction act; extern int interrupted; extern bool loopmode; extern vmi_instance_t vmi; #ifdef CODECOV_SIGNAL static struct sigaction act2; #endif static void close_handler(int sig) { interrupted = sig; loopmode = false; if ( vmi ) vmi_pause_vm(vmi); } #ifdef CODECOV_SIGNAL static void user_handler(int sig) { (void)sig; do_record_codecov(); } #endif void setup_handlers(void) { act.sa_handler = close_handler; sigemptyset(&act.sa_mask); sigaction(SIGHUP, &act, NULL); sigaction(SIGTERM, &act, NULL); sigaction(SIGINT, &act, NULL); sigaction(SIGALRM, &act, NULL); #ifdef CODECOV_SIGNAL act2.sa_handler = user_handler; sigemptyset(&act2.sa_mask); sigaction(SIGUSR1, &act2, NULL); #endif }
18a6135406afcb119a8581e0f89d3ec155249e39
59864cbd213b5da6f50d6255b0a021564b3d5bd4
/challenges/Movie_Rental_Service_Redux/src/cgc_admin.h
68e916cf5df81f143447cddb19a638afb4f1f9cc
[ "MIT", "BSD-3-Clause", "LicenseRef-scancode-unknown", "BSD-2-Clause" ]
permissive
trailofbits/cb-multios
8af96a4fbc3b34644367faa135347f88e0e0d0a3
810d7b24b1f62f56ef49b148fe155b0d0629cad2
refs/heads/master
2023-09-05T03:56:20.229403
2022-12-27T15:47:54
2022-12-27T15:47:54
41,688,943
522
133
MIT
2023-06-29T02:47:13
2015-08-31T17:04:31
C
UTF-8
C
false
false
78
h
cgc_admin.h
#ifndef ADMIN_H_ #define ADMIN_H_ int cgc_run_admin_mode(int *user); #endif
54c8649592602c2c524eee2cc94b9184cc2c9f0a
9ceacf33fd96913cac7ef15492c126d96cae6911
/sys/dev/pci/drm/amd/amdgpu/amdgpu_pmu.c
ec905b0888f5977a98ec8ec05c7ced7c46c43aa5
[]
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
18,389
c
amdgpu_pmu.c
/* * Copyright 2019 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * */ #include <linux/perf_event.h> #include <linux/init.h> #include "amdgpu.h" #include "amdgpu_pmu.h" #define PMU_NAME_SIZE 32 #define NUM_FORMATS_AMDGPU_PMU 4 #define NUM_FORMATS_DF_VEGA20 3 #define NUM_EVENTS_DF_VEGA20 8 #define NUM_EVENT_TYPES_VEGA20 1 #define NUM_EVENTS_VEGA20_XGMI 2 #define NUM_EVENTS_VEGA20_MAX NUM_EVENTS_VEGA20_XGMI #define NUM_EVENT_TYPES_ARCTURUS 1 #define NUM_EVENTS_ARCTURUS_XGMI 6 #define NUM_EVENTS_ARCTURUS_MAX NUM_EVENTS_ARCTURUS_XGMI struct amdgpu_pmu_event_attribute { struct device_attribute attr; const char *event_str; unsigned int type; }; /* record to keep track of pmu entry per pmu type per device */ struct amdgpu_pmu_entry { struct list_head entry; struct amdgpu_device *adev; struct pmu pmu; unsigned int pmu_perf_type; char *pmu_type_name; char *pmu_file_prefix; struct attribute_group fmt_attr_group; struct amdgpu_pmu_event_attribute *fmt_attr; struct attribute_group evt_attr_group; struct amdgpu_pmu_event_attribute *evt_attr; }; static ssize_t amdgpu_pmu_event_show(struct device *dev, struct device_attribute *attr, char *buf) { struct amdgpu_pmu_event_attribute *amdgpu_pmu_attr; amdgpu_pmu_attr = container_of(attr, struct amdgpu_pmu_event_attribute, attr); if (!amdgpu_pmu_attr->type) return sprintf(buf, "%s\n", amdgpu_pmu_attr->event_str); return sprintf(buf, "%s,type=0x%x\n", amdgpu_pmu_attr->event_str, amdgpu_pmu_attr->type); } static DRM_LIST_HEAD(amdgpu_pmu_list); struct amdgpu_pmu_attr { const char *name; const char *config; }; struct amdgpu_pmu_type { const unsigned int type; const unsigned int num_of_type; }; struct amdgpu_pmu_config { struct amdgpu_pmu_attr *formats; unsigned int num_formats; struct amdgpu_pmu_attr *events; unsigned int num_events; struct amdgpu_pmu_type *types; unsigned int num_types; }; /* * Events fall under two categories: * - PMU typed * Events in /sys/bus/event_source/devices/amdgpu_<pmu_type>_<dev_num> have * performance counter operations handled by one IP <pmu_type>. Formats and * events should be defined by <pmu_type>_<asic_type>_formats and * <pmu_type>_<asic_type>_events respectively. * * - Event config typed * Events in /sys/bus/event_source/devices/amdgpu_<dev_num> have performance * counter operations that can be handled by multiple IPs dictated by their * "type" format field. Formats and events should be defined by * amdgpu_pmu_formats and <asic_type>_events respectively. Format field * "type" is generated in amdgpu_pmu_event_show and defined in * <asic_type>_event_config_types. */ static struct amdgpu_pmu_attr amdgpu_pmu_formats[NUM_FORMATS_AMDGPU_PMU] = { { .name = "event", .config = "config:0-7" }, { .name = "instance", .config = "config:8-15" }, { .name = "umask", .config = "config:16-23"}, { .name = "type", .config = "config:56-63"} }; /* Vega20 events */ static struct amdgpu_pmu_attr vega20_events[NUM_EVENTS_VEGA20_MAX] = { { .name = "xgmi_link0_data_outbound", .config = "event=0x7,instance=0x46,umask=0x2" }, { .name = "xgmi_link1_data_outbound", .config = "event=0x7,instance=0x47,umask=0x2" } }; static struct amdgpu_pmu_type vega20_types[NUM_EVENT_TYPES_VEGA20] = { { .type = AMDGPU_PMU_EVENT_CONFIG_TYPE_XGMI, .num_of_type = NUM_EVENTS_VEGA20_XGMI } }; static struct amdgpu_pmu_config vega20_config = { .formats = amdgpu_pmu_formats, .num_formats = ARRAY_SIZE(amdgpu_pmu_formats), .events = vega20_events, .num_events = ARRAY_SIZE(vega20_events), .types = vega20_types, .num_types = ARRAY_SIZE(vega20_types) }; /* Vega20 data fabric (DF) events */ static struct amdgpu_pmu_attr df_vega20_formats[NUM_FORMATS_DF_VEGA20] = { { .name = "event", .config = "config:0-7" }, { .name = "instance", .config = "config:8-15" }, { .name = "umask", .config = "config:16-23"} }; static struct amdgpu_pmu_attr df_vega20_events[NUM_EVENTS_DF_VEGA20] = { { .name = "cake0_pcsout_txdata", .config = "event=0x7,instance=0x46,umask=0x2" }, { .name = "cake1_pcsout_txdata", .config = "event=0x7,instance=0x47,umask=0x2" }, { .name = "cake0_pcsout_txmeta", .config = "event=0x7,instance=0x46,umask=0x4" }, { .name = "cake1_pcsout_txmeta", .config = "event=0x7,instance=0x47,umask=0x4" }, { .name = "cake0_ftiinstat_reqalloc", .config = "event=0xb,instance=0x46,umask=0x4" }, { .name = "cake1_ftiinstat_reqalloc", .config = "event=0xb,instance=0x47,umask=0x4" }, { .name = "cake0_ftiinstat_rspalloc", .config = "event=0xb,instance=0x46,umask=0x8" }, { .name = "cake1_ftiinstat_rspalloc", .config = "event=0xb,instance=0x47,umask=0x8" } }; static struct amdgpu_pmu_config df_vega20_config = { .formats = df_vega20_formats, .num_formats = ARRAY_SIZE(df_vega20_formats), .events = df_vega20_events, .num_events = ARRAY_SIZE(df_vega20_events), .types = NULL, .num_types = 0 }; /* Arcturus events */ static struct amdgpu_pmu_attr arcturus_events[NUM_EVENTS_ARCTURUS_MAX] = { { .name = "xgmi_link0_data_outbound", .config = "event=0x7,instance=0x4b,umask=0x2" }, { .name = "xgmi_link1_data_outbound", .config = "event=0x7,instance=0x4c,umask=0x2" }, { .name = "xgmi_link2_data_outbound", .config = "event=0x7,instance=0x4d,umask=0x2" }, { .name = "xgmi_link3_data_outbound", .config = "event=0x7,instance=0x4e,umask=0x2" }, { .name = "xgmi_link4_data_outbound", .config = "event=0x7,instance=0x4f,umask=0x2" }, { .name = "xgmi_link5_data_outbound", .config = "event=0x7,instance=0x50,umask=0x2" } }; static struct amdgpu_pmu_type arcturus_types[NUM_EVENT_TYPES_ARCTURUS] = { { .type = AMDGPU_PMU_EVENT_CONFIG_TYPE_XGMI, .num_of_type = NUM_EVENTS_ARCTURUS_XGMI } }; static struct amdgpu_pmu_config arcturus_config = { .formats = amdgpu_pmu_formats, .num_formats = ARRAY_SIZE(amdgpu_pmu_formats), .events = arcturus_events, .num_events = ARRAY_SIZE(arcturus_events), .types = arcturus_types, .num_types = ARRAY_SIZE(arcturus_types) }; /* initialize perf counter */ static int amdgpu_perf_event_init(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; /* test the event attr type check for PMU enumeration */ if (event->attr.type != event->pmu->type) return -ENOENT; /* update the hw_perf_event struct with config data */ hwc->config = event->attr.config; hwc->config_base = AMDGPU_PMU_PERF_TYPE_NONE; return 0; } /* start perf counter */ static void amdgpu_perf_start(struct perf_event *event, int flags) { struct hw_perf_event *hwc = &event->hw; struct amdgpu_pmu_entry *pe = container_of(event->pmu, struct amdgpu_pmu_entry, pmu); int target_cntr = 0; if (WARN_ON_ONCE(!(hwc->state & PERF_HES_STOPPED))) return; if ((!pe->adev->df.funcs) || (!pe->adev->df.funcs->pmc_start)) return; WARN_ON_ONCE(!(hwc->state & PERF_HES_UPTODATE)); hwc->state = 0; switch (hwc->config_base) { case AMDGPU_PMU_EVENT_CONFIG_TYPE_DF: case AMDGPU_PMU_EVENT_CONFIG_TYPE_XGMI: if (!(flags & PERF_EF_RELOAD)) { target_cntr = pe->adev->df.funcs->pmc_start(pe->adev, hwc->config, 0 /* unused */, 1 /* add counter */); if (target_cntr < 0) break; hwc->idx = target_cntr; } pe->adev->df.funcs->pmc_start(pe->adev, hwc->config, hwc->idx, 0); break; default: break; } perf_event_update_userpage(event); } /* read perf counter */ static void amdgpu_perf_read(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; struct amdgpu_pmu_entry *pe = container_of(event->pmu, struct amdgpu_pmu_entry, pmu); u64 count, prev; if ((!pe->adev->df.funcs) || (!pe->adev->df.funcs->pmc_get_count)) return; do { prev = local64_read(&hwc->prev_count); switch (hwc->config_base) { case AMDGPU_PMU_EVENT_CONFIG_TYPE_DF: case AMDGPU_PMU_EVENT_CONFIG_TYPE_XGMI: pe->adev->df.funcs->pmc_get_count(pe->adev, hwc->config, hwc->idx, &count); break; default: count = 0; break; } } while (local64_cmpxchg(&hwc->prev_count, prev, count) != prev); local64_add(count - prev, &event->count); } /* stop perf counter */ static void amdgpu_perf_stop(struct perf_event *event, int flags) { struct hw_perf_event *hwc = &event->hw; struct amdgpu_pmu_entry *pe = container_of(event->pmu, struct amdgpu_pmu_entry, pmu); if (hwc->state & PERF_HES_UPTODATE) return; if ((!pe->adev->df.funcs) || (!pe->adev->df.funcs->pmc_stop)) return; switch (hwc->config_base) { case AMDGPU_PMU_EVENT_CONFIG_TYPE_DF: case AMDGPU_PMU_EVENT_CONFIG_TYPE_XGMI: pe->adev->df.funcs->pmc_stop(pe->adev, hwc->config, hwc->idx, 0); break; default: break; } WARN_ON_ONCE(hwc->state & PERF_HES_STOPPED); hwc->state |= PERF_HES_STOPPED; if (hwc->state & PERF_HES_UPTODATE) return; amdgpu_perf_read(event); hwc->state |= PERF_HES_UPTODATE; } /* add perf counter */ static int amdgpu_perf_add(struct perf_event *event, int flags) { struct hw_perf_event *hwc = &event->hw; int retval = 0, target_cntr; struct amdgpu_pmu_entry *pe = container_of(event->pmu, struct amdgpu_pmu_entry, pmu); if ((!pe->adev->df.funcs) || (!pe->adev->df.funcs->pmc_start)) return -EINVAL; switch (pe->pmu_perf_type) { case AMDGPU_PMU_PERF_TYPE_DF: hwc->config_base = AMDGPU_PMU_EVENT_CONFIG_TYPE_DF; break; case AMDGPU_PMU_PERF_TYPE_ALL: hwc->config_base = (hwc->config >> AMDGPU_PMU_EVENT_CONFIG_TYPE_SHIFT) & AMDGPU_PMU_EVENT_CONFIG_TYPE_MASK; break; } event->hw.state = PERF_HES_UPTODATE | PERF_HES_STOPPED; switch (hwc->config_base) { case AMDGPU_PMU_EVENT_CONFIG_TYPE_DF: case AMDGPU_PMU_EVENT_CONFIG_TYPE_XGMI: target_cntr = pe->adev->df.funcs->pmc_start(pe->adev, hwc->config, 0 /* unused */, 1 /* add counter */); if (target_cntr < 0) retval = target_cntr; else hwc->idx = target_cntr; break; default: return 0; } if (retval) return retval; if (flags & PERF_EF_START) amdgpu_perf_start(event, PERF_EF_RELOAD); return retval; } /* delete perf counter */ static void amdgpu_perf_del(struct perf_event *event, int flags) { struct hw_perf_event *hwc = &event->hw; struct amdgpu_pmu_entry *pe = container_of(event->pmu, struct amdgpu_pmu_entry, pmu); if ((!pe->adev->df.funcs) || (!pe->adev->df.funcs->pmc_stop)) return; amdgpu_perf_stop(event, PERF_EF_UPDATE); switch (hwc->config_base) { case AMDGPU_PMU_EVENT_CONFIG_TYPE_DF: case AMDGPU_PMU_EVENT_CONFIG_TYPE_XGMI: pe->adev->df.funcs->pmc_stop(pe->adev, hwc->config, hwc->idx, 1); break; default: break; } perf_event_update_userpage(event); } static void amdgpu_pmu_create_event_attrs_by_type( struct attribute_group *attr_group, struct amdgpu_pmu_event_attribute *pmu_attr, struct amdgpu_pmu_attr events[], int s_offset, int e_offset, unsigned int type) { int i; pmu_attr += s_offset; for (i = s_offset; i < e_offset; i++) { attr_group->attrs[i] = &pmu_attr->attr.attr; sysfs_attr_init(&pmu_attr->attr.attr); pmu_attr->attr.attr.name = events[i].name; pmu_attr->attr.attr.mode = 0444; pmu_attr->attr.show = amdgpu_pmu_event_show; pmu_attr->event_str = events[i].config; pmu_attr->type = type; pmu_attr++; } } static void amdgpu_pmu_create_attrs(struct attribute_group *attr_group, struct amdgpu_pmu_event_attribute *pmu_attr, struct amdgpu_pmu_attr events[], int num_events) { amdgpu_pmu_create_event_attrs_by_type(attr_group, pmu_attr, events, 0, num_events, AMDGPU_PMU_EVENT_CONFIG_TYPE_NONE); } static int amdgpu_pmu_alloc_pmu_attrs( struct attribute_group *fmt_attr_group, struct amdgpu_pmu_event_attribute **fmt_attr, struct attribute_group *evt_attr_group, struct amdgpu_pmu_event_attribute **evt_attr, struct amdgpu_pmu_config *config) { *fmt_attr = kcalloc(config->num_formats, sizeof(**fmt_attr), GFP_KERNEL); if (!(*fmt_attr)) return -ENOMEM; fmt_attr_group->attrs = kcalloc(config->num_formats + 1, sizeof(*fmt_attr_group->attrs), GFP_KERNEL); if (!fmt_attr_group->attrs) goto err_fmt_attr_grp; *evt_attr = kcalloc(config->num_events, sizeof(**evt_attr), GFP_KERNEL); if (!(*evt_attr)) goto err_evt_attr; evt_attr_group->attrs = kcalloc(config->num_events + 1, sizeof(*evt_attr_group->attrs), GFP_KERNEL); if (!evt_attr_group->attrs) goto err_evt_attr_grp; return 0; err_evt_attr_grp: kfree(*evt_attr); err_evt_attr: kfree(fmt_attr_group->attrs); err_fmt_attr_grp: kfree(*fmt_attr); return -ENOMEM; } /* init pmu tracking per pmu type */ static int init_pmu_entry_by_type_and_add(struct amdgpu_pmu_entry *pmu_entry, struct amdgpu_pmu_config *config) { const struct attribute_group *attr_groups[] = { &pmu_entry->fmt_attr_group, &pmu_entry->evt_attr_group, NULL }; char pmu_name[PMU_NAME_SIZE]; int ret = 0, total_num_events = 0; pmu_entry->pmu = (struct pmu){ .event_init = amdgpu_perf_event_init, .add = amdgpu_perf_add, .del = amdgpu_perf_del, .start = amdgpu_perf_start, .stop = amdgpu_perf_stop, .read = amdgpu_perf_read, .task_ctx_nr = perf_invalid_context, }; ret = amdgpu_pmu_alloc_pmu_attrs(&pmu_entry->fmt_attr_group, &pmu_entry->fmt_attr, &pmu_entry->evt_attr_group, &pmu_entry->evt_attr, config); if (ret) goto err_out; amdgpu_pmu_create_attrs(&pmu_entry->fmt_attr_group, pmu_entry->fmt_attr, config->formats, config->num_formats); if (pmu_entry->pmu_perf_type == AMDGPU_PMU_PERF_TYPE_ALL) { int i; for (i = 0; i < config->num_types; i++) { amdgpu_pmu_create_event_attrs_by_type( &pmu_entry->evt_attr_group, pmu_entry->evt_attr, config->events, total_num_events, total_num_events + config->types[i].num_of_type, config->types[i].type); total_num_events += config->types[i].num_of_type; } } else { amdgpu_pmu_create_attrs(&pmu_entry->evt_attr_group, pmu_entry->evt_attr, config->events, config->num_events); total_num_events = config->num_events; } pmu_entry->pmu.attr_groups = kmemdup(attr_groups, sizeof(attr_groups), GFP_KERNEL); if (!pmu_entry->pmu.attr_groups) { ret = -ENOMEM; goto err_attr_group; } snprintf(pmu_name, PMU_NAME_SIZE, "%s_%d", pmu_entry->pmu_file_prefix, adev_to_drm(pmu_entry->adev)->primary->index); ret = perf_pmu_register(&pmu_entry->pmu, pmu_name, -1); if (ret) goto err_register; if (pmu_entry->pmu_perf_type != AMDGPU_PMU_PERF_TYPE_ALL) pr_info("Detected AMDGPU %s Counters. # of Counters = %d.\n", pmu_entry->pmu_type_name, total_num_events); else pr_info("Detected AMDGPU %d Perf Events.\n", total_num_events); list_add_tail(&pmu_entry->entry, &amdgpu_pmu_list); return 0; err_register: kfree(pmu_entry->pmu.attr_groups); err_attr_group: kfree(pmu_entry->fmt_attr_group.attrs); kfree(pmu_entry->fmt_attr); kfree(pmu_entry->evt_attr_group.attrs); kfree(pmu_entry->evt_attr); err_out: pr_warn("Error initializing AMDGPU %s PMUs.\n", pmu_entry->pmu_type_name); return ret; } /* destroy all pmu data associated with target device */ void amdgpu_pmu_fini(struct amdgpu_device *adev) { struct amdgpu_pmu_entry *pe, *temp; list_for_each_entry_safe(pe, temp, &amdgpu_pmu_list, entry) { if (pe->adev != adev) continue; list_del(&pe->entry); perf_pmu_unregister(&pe->pmu); kfree(pe->pmu.attr_groups); kfree(pe->fmt_attr_group.attrs); kfree(pe->fmt_attr); kfree(pe->evt_attr_group.attrs); kfree(pe->evt_attr); kfree(pe); } } static struct amdgpu_pmu_entry *create_pmu_entry(struct amdgpu_device *adev, unsigned int pmu_type, char *pmu_type_name, char *pmu_file_prefix) { struct amdgpu_pmu_entry *pmu_entry; pmu_entry = kzalloc(sizeof(struct amdgpu_pmu_entry), GFP_KERNEL); if (!pmu_entry) return pmu_entry; pmu_entry->adev = adev; pmu_entry->fmt_attr_group.name = "format"; pmu_entry->fmt_attr_group.attrs = NULL; pmu_entry->evt_attr_group.name = "events"; pmu_entry->evt_attr_group.attrs = NULL; pmu_entry->pmu_perf_type = pmu_type; pmu_entry->pmu_type_name = pmu_type_name; pmu_entry->pmu_file_prefix = pmu_file_prefix; return pmu_entry; } /* init amdgpu_pmu */ int amdgpu_pmu_init(struct amdgpu_device *adev) { int ret = 0; struct amdgpu_pmu_entry *pmu_entry, *pmu_entry_df; switch (adev->asic_type) { case CHIP_VEGA20: pmu_entry_df = create_pmu_entry(adev, AMDGPU_PMU_PERF_TYPE_DF, "DF", "amdgpu_df"); if (!pmu_entry_df) return -ENOMEM; ret = init_pmu_entry_by_type_and_add(pmu_entry_df, &df_vega20_config); if (ret) { kfree(pmu_entry_df); return ret; } pmu_entry = create_pmu_entry(adev, AMDGPU_PMU_PERF_TYPE_ALL, "", "amdgpu"); if (!pmu_entry) { amdgpu_pmu_fini(adev); return -ENOMEM; } ret = init_pmu_entry_by_type_and_add(pmu_entry, &vega20_config); if (ret) { kfree(pmu_entry); amdgpu_pmu_fini(adev); return ret; } break; case CHIP_ARCTURUS: pmu_entry = create_pmu_entry(adev, AMDGPU_PMU_PERF_TYPE_ALL, "", "amdgpu"); if (!pmu_entry) return -ENOMEM; ret = init_pmu_entry_by_type_and_add(pmu_entry, &arcturus_config); if (ret) { kfree(pmu_entry); return -ENOMEM; } break; default: return 0; } return ret; }
b9c124c7f5bfd2e88545c9d2aa6971f1f8e38da7
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
/devel/electron23/files/patch-ui_ozone_public_ozone__platform.h
ee5b94eacbe0a77302de65d40e9005b9d46b4290
[ "BSD-2-Clause", "BSD-3-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
559
h
patch-ui_ozone_public_ozone__platform.h
--- ui/ozone/public/ozone_platform.h.orig 2023-01-30 07:58:59 UTC +++ ui/ozone/public/ozone_platform.h @@ -148,7 +148,7 @@ class COMPONENT_EXPORT(OZONE) OzonePlatform { // back via gpu extra info. bool fetch_buffer_formats_for_gmb_on_gpu = false; -#if BUILDFLAG(IS_LINUX) +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_BSD) // TODO(crbug.com/1116701): add vaapi support for other Ozone platforms on // Linux. At the moment, VA-API Linux implementation supports only X11 // backend. This implementation must be refactored to support Ozone
c91383228add5f8cef6c24f801580cfdc7560dda
69db0de8c61c7cba691193edd3f087fdb54351c2
/src/field_message_box.c
74f441c889d59775f0a4bb16567685b5f78a9ef2
[]
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
3,461
c
field_message_box.c
#include "global.h" #include "field_message_box.h" #include "gflib.h" #include "new_menu_helpers.h" #include "quest_log.h" #include "script.h" #include "text_window.h" static EWRAM_DATA u8 sMessageBoxType = 0; static void ExpandStringAndStartDrawFieldMessageBox(const u8 *str); static void StartDrawFieldMessageBox(void); void InitFieldMessageBox(void) { sMessageBoxType = FIELD_MESSAGE_BOX_HIDDEN; gTextFlags.canABSpeedUpPrint = FALSE; gTextFlags.useAlternateDownArrow = FALSE; gTextFlags.autoScroll = FALSE; } static void Task_DrawFieldMessageBox(u8 taskId) { struct Task *task = &gTasks[taskId]; switch (task->data[0]) { case 0: if (gQuestLogState == QL_STATE_PLAYBACK) { gTextFlags.autoScroll = TRUE; LoadQuestLogWindowTiles(0, 0x200); } else if (!IsMsgSignpost()) LoadStdWindowFrameGfx(); else LoadSignpostWindowFrameGfx(); task->data[0]++; break; case 1: DrawDialogueFrame(0, TRUE); task->data[0]++; break; case 2: if (RunTextPrinters_CheckPrinter0Active() != TRUE) { sMessageBoxType = FIELD_MESSAGE_BOX_HIDDEN; DestroyTask(taskId); } break; } } static void CreateTask_DrawFieldMessageBox(void) { CreateTask(Task_DrawFieldMessageBox, 80); } static void DestroyTask_DrawFieldMessageBox(void) { u8 taskId = FindTaskIdByFunc(Task_DrawFieldMessageBox); if (taskId != 0xFF) DestroyTask(taskId); } bool8 ShowFieldMessage(const u8 *str) { if (sMessageBoxType != FIELD_MESSAGE_BOX_HIDDEN) return FALSE; ExpandStringAndStartDrawFieldMessageBox(str); sMessageBoxType = FIELD_MESSAGE_BOX_NORMAL; return TRUE; } bool8 ShowFieldAutoScrollMessage(const u8 *str) { if (sMessageBoxType != FIELD_MESSAGE_BOX_HIDDEN) return FALSE; sMessageBoxType = FIELD_MESSAGE_BOX_AUTO_SCROLL; ExpandStringAndStartDrawFieldMessageBox(str); return TRUE; } // Unused static bool8 ForceShowFieldAutoScrollMessage(const u8 *str) { sMessageBoxType = FIELD_MESSAGE_BOX_AUTO_SCROLL; ExpandStringAndStartDrawFieldMessageBox(str); return TRUE; } // Unused // Same as ShowFieldMessage, but instead of accepting a string argument, // it just prints whatever that's already in gStringVar4 static bool8 ShowFieldMessageFromBuffer(void) { if (sMessageBoxType != FIELD_MESSAGE_BOX_HIDDEN) return FALSE; sMessageBoxType = FIELD_MESSAGE_BOX_NORMAL; StartDrawFieldMessageBox(); return TRUE; } static void ExpandStringAndStartDrawFieldMessageBox(const u8 *str) { StringExpandPlaceholders(gStringVar4, str); AddTextPrinterDiffStyle(TRUE); CreateTask_DrawFieldMessageBox(); } static void StartDrawFieldMessageBox(void) { AddTextPrinterDiffStyle(TRUE); CreateTask_DrawFieldMessageBox(); } void HideFieldMessageBox(void) { DestroyTask_DrawFieldMessageBox(); ClearDialogWindowAndFrame(0, TRUE); sMessageBoxType = FIELD_MESSAGE_BOX_HIDDEN; } u8 GetFieldMessageBoxType(void) { return sMessageBoxType; } bool8 IsFieldMessageBoxHidden(void) { if (sMessageBoxType == FIELD_MESSAGE_BOX_HIDDEN) return TRUE; else return FALSE; } // Unused static void ReplaceFieldMessageWithFrame(void) { DestroyTask_DrawFieldMessageBox(); DrawStdWindowFrame(0, TRUE); sMessageBoxType = FIELD_MESSAGE_BOX_HIDDEN; }
4afd7d523d6511f3830e831297aa12d8173a484a
56d1226dfefc93768a5f60ce15d1d7ca9bd58a08
/Wrappers/d3d8.h
95292d8a41b3e312c80580e5c036cb5cc67ad6fb
[ "Zlib", "GPL-1.0-or-later" ]
permissive
elishacloud/dxwrapper
ef6e047a6c49b98b74bf0adcff80740e8c0fff42
258bc970a72c7a4bd89449527a537e6912acbfb3
refs/heads/master
2023-08-17T06:13:06.649077
2023-08-16T21:17:18
2023-08-16T21:17:18
81,271,358
968
83
Zlib
2023-08-22T19:56:05
2017-02-08T00:58:26
C
UTF-8
C
false
false
245
h
d3d8.h
#pragma once #define VISIT_PROCS_D3D8(visit) \ visit(ValidateVertexShader, jmpaddr) \ visit(ValidatePixelShader, jmpaddr) \ visit(Direct3DCreate8, jmpaddr) #ifdef PROC_CLASS PROC_CLASS(d3d8, dll, VISIT_PROCS_D3D8, VISIT_PROCS_BLANK) #endif
7ef48254bd7edca557c8743b56ebb9a181f62710
d61b532db0d3e08818338cfaac530a1ced1ffe3b
/plat/osx/include/ack/plat.h
f0ad12797d2fbd3ba156d70747f0f2539df74810
[ "LicenseRef-scancode-other-permissive" ]
permissive
davidgiven/ack
61049c7a8e95ff61a77b1edd3c22bb290720e276
db5a32c68c4a60ca26a3927a799ea662b5b2b0e5
refs/heads/default
2023-08-29T07:33:12.771205
2023-07-08T20:17:27
2023-07-08T20:17:27
37,686,316
376
74
NOASSERTION
2023-07-08T20:17:28
2015-06-18T21:33:42
C
UTF-8
C
false
false
165
h
plat.h
/* $Source$ * $State$ * $Revision$ */ #ifndef _ACK_PLAT_H #define _ACK_PLAT_H #define ACKCONF_WANT_STANDARD_O 0 #define ACKCONF_WANT_STANDARD_SIGNALS 0 #endif