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
4f8414a4cdd8ee8dd45204b710bf9413fe591565
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
/comms/libfec/files/patch-sumsq__av.c
f65c0b1f33a3682a90f1f80c0197c04b086c284c
[ "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,908
c
patch-sumsq__av.c
--- sumsq_av.c.orig 2019-02-05 19:36:10 UTC +++ sumsq_av.c @@ -8,6 +8,7 @@ * May be used under the terms of the GNU Lesser General Public License (LGPL) */ +#include <altivec.h> #include "fec.h" unsigned long long sumsq_av(signed short *in,int cnt){ @@ -17,15 +18,15 @@ unsigned long long sumsq_av(signed short *in,int cnt){ int pad; union { vector unsigned char cv; vector unsigned int iv; unsigned int w[4]; unsigned char c[16];} s; - carries = sums = (vector unsigned int)(0); + carries = sums = (vector unsigned int){0}; if((pad = (int)in & 15)!=0){ /* Load unaligned leading word */ - x = vec_perm(vec_ld(0,in),(vector signed short)(0),vec_lvsl(0,in)); + x = vec_perm(vec_ld(0,in),(vector signed short){0},vec_lvsl(0,in)); if(cnt < 8){ /* Shift right to chop stuff beyond end of short block */ s.c[15] = (8-cnt)<<4; x = vec_sro(x,s.cv); } - sums = (vector unsigned int)vec_msum(x,x,(vector signed int)(0)); + sums = (vector unsigned int)vec_msum(x,x,(vector signed int){0}); in += 8-pad/2; cnt -= 8-pad/2; } @@ -36,7 +37,7 @@ unsigned long long sumsq_av(signed short *in,int cnt){ * the earlier terms separately to handle the carries * The cast to unsigned is OK because squares are always positive */ - s1 = (vector unsigned int)vec_msum(x,x,(vector signed int)(0)); + s1 = (vector unsigned int)vec_msum(x,x,(vector signed int){0}); carries = vec_add(carries,vec_addc(sums,s1)); sums = vec_add(sums,s1); in += 8; @@ -47,7 +48,7 @@ unsigned long long sumsq_av(signed short *in,int cnt){ x = vec_ld(0,in); s.c[15] = (8-cnt)<<4; x = vec_sro(x,s.cv); - s1 = (vector unsigned int)vec_msum(x,x,(vector signed int)(0)); + s1 = (vector unsigned int)vec_msum(x,x,(vector signed int){0}); carries = vec_add(carries,vec_addc(sums,s1)); sums = vec_add(sums,s1); }
5c7091446324c239818c2f1ae8df4f04bb950a2d
0b1f18c37bfbf6901749916a5935c49b1afe17e3
/core/lib/experimental/gtk/win/include/glib-2.0/glibconfig.h
6820f7fecb1ba1fb08159d2c8c6f8284b1900692
[ "OpenSSL", "Zlib", "BSD-3-Clause" ]
permissive
objeck/objeck-lang
2e97ff6c070492e53d4a5f1bec88e07dda4b4296
627482005da67618fd46133d18ade2d66e515284
refs/heads/master
2023-08-24T05:38:15.489677
2023-08-22T20:06:43
2023-08-22T20:06:43
20,608,381
240
33
NOASSERTION
2023-09-06T20:13:02
2014-06-08T03:25:12
C
UTF-8
C
false
false
5,750
h
glibconfig.h
/* glibconfig.h * * This is a generated file. Please modify 'glibconfig.h.in' */ #ifndef __GLIBCONFIG_H__ #define __GLIBCONFIG_H__ #include <glib/gmacros.h> #include <limits.h> #include <float.h> /* #undef GLIB_HAVE_ALLOCA_H */ /* Specifies that GLib's g_print*() functions wrap the * system printf functions. This is useful to know, for example, * when using glibc's register_printf_function(). */ #undef GLIB_USING_SYSTEM_PRINTF /* #undef GLIB_STATIC_COMPILATION */ /* #undef GOBJECT_STATIC_COMPILATION */ /* #undef G_INTL_STATIC_COMPILATION */ /* #undef FFI_STATIC_BUILD */ G_BEGIN_DECLS #define G_MINFLOAT FLT_MIN #define G_MAXFLOAT FLT_MAX #define G_MINDOUBLE DBL_MIN #define G_MAXDOUBLE DBL_MAX #define G_MINSHORT SHRT_MIN #define G_MAXSHORT SHRT_MAX #define G_MAXUSHORT USHRT_MAX #define G_MININT INT_MIN #define G_MAXINT INT_MAX #define G_MAXUINT UINT_MAX #define G_MINLONG LONG_MIN #define G_MAXLONG LONG_MAX #define G_MAXULONG ULONG_MAX typedef signed char gint8; typedef unsigned char guint8; typedef signed short gint16; typedef unsigned short guint16; #define G_GINT16_MODIFIER "h" #define G_GINT16_FORMAT "hi" #define G_GUINT16_FORMAT "hu" typedef signed int gint32; typedef unsigned int guint32; #define G_GINT32_MODIFIER "" #define G_GINT32_FORMAT "i" #define G_GUINT32_FORMAT "u" #define G_HAVE_GINT64 1 /* deprecated, always true */ G_GNUC_EXTENSION typedef signed long long gint64; G_GNUC_EXTENSION typedef unsigned long long guint64; #define G_GINT64_CONSTANT(val) (G_GNUC_EXTENSION (val##LL)) #define G_GUINT64_CONSTANT(val) (G_GNUC_EXTENSION (val##ULL)) #define G_GINT64_MODIFIER "ll" #define G_GINT64_FORMAT "lli" #define G_GUINT64_FORMAT "llu" #define GLIB_SIZEOF_VOID_P 8 #define GLIB_SIZEOF_LONG 4 #define GLIB_SIZEOF_SIZE_T 8 #define GLIB_SIZEOF_SSIZE_T 8 typedef signed long long gssize; typedef unsigned long long gsize; #define G_GSIZE_MODIFIER "ll" #define G_GSSIZE_MODIFIER "ll" #define G_GSIZE_FORMAT "llu" #define G_GSSIZE_FORMAT "lli" #define G_MAXSIZE G_MAXUINT64 #define G_MINSSIZE G_MININT64 #define G_MAXSSIZE G_MAXINT64 typedef gint64 goffset; #define G_MINOFFSET G_MININT64 #define G_MAXOFFSET G_MAXINT64 #define G_GOFFSET_MODIFIER G_GINT64_MODIFIER #define G_GOFFSET_FORMAT G_GINT64_FORMAT #define G_GOFFSET_CONSTANT(val) G_GINT64_CONSTANT(val) #define G_POLLFD_FORMAT "%#llx" #define GPOINTER_TO_INT(p) ((gint) (gint64) (p)) #define GPOINTER_TO_UINT(p) ((guint) (guint64) (p)) #define GINT_TO_POINTER(i) ((gpointer) (gint64) (i)) #define GUINT_TO_POINTER(u) ((gpointer) (guint64) (u)) typedef signed long long gintptr; typedef unsigned long long guintptr; #define G_GINTPTR_MODIFIER "ll" #define G_GINTPTR_FORMAT "lli" #define G_GUINTPTR_FORMAT "llu" #define GLIB_MAJOR_VERSION 2 #define GLIB_MINOR_VERSION 74 #define GLIB_MICRO_VERSION 1 #define G_OS_WIN32 #define G_PLATFORM_WIN32 /* #undef G_VA_COPY */ #define G_HAVE_ISO_VARARGS 1 /* gcc-2.95.x supports both gnu style and ISO varargs, but if -ansi * is passed ISO vararg support is turned off, and there is no work * around to turn it on, so we unconditionally turn it off. */ #if __GNUC__ == 2 && __GNUC_MINOR__ == 95 # undef G_HAVE_ISO_VARARGS #endif #define G_HAVE_GROWING_STACK 0 /* #undef G_HAVE_GNUC_VISIBILITY */ #ifndef _MSC_VER # define G_HAVE_GNUC_VARARGS 1 #endif #if defined(__SUNPRO_C) && (__SUNPRO_C >= 0x590) #define G_GNUC_INTERNAL __attribute__((visibility("hidden"))) #elif defined(__SUNPRO_C) && (__SUNPRO_C >= 0x550) #define G_GNUC_INTERNAL __hidden #elif defined (__GNUC__) && defined (G_HAVE_GNUC_VISIBILITY) #define G_GNUC_INTERNAL __attribute__((visibility("hidden"))) #else #define G_GNUC_INTERNAL #endif #define G_THREADS_ENABLED #define G_THREADS_IMPL_WIN32 #define G_ATOMIC_LOCK_FREE #define GINT16_TO_LE(val) ((gint16) (val)) #define GUINT16_TO_LE(val) ((guint16) (val)) #define GINT16_TO_BE(val) ((gint16) GUINT16_SWAP_LE_BE (val)) #define GUINT16_TO_BE(val) (GUINT16_SWAP_LE_BE (val)) #define GINT32_TO_LE(val) ((gint32) (val)) #define GUINT32_TO_LE(val) ((guint32) (val)) #define GINT32_TO_BE(val) ((gint32) GUINT32_SWAP_LE_BE (val)) #define GUINT32_TO_BE(val) (GUINT32_SWAP_LE_BE (val)) #define GINT64_TO_LE(val) ((gint64) (val)) #define GUINT64_TO_LE(val) ((guint64) (val)) #define GINT64_TO_BE(val) ((gint64) GUINT64_SWAP_LE_BE (val)) #define GUINT64_TO_BE(val) (GUINT64_SWAP_LE_BE (val)) #define GLONG_TO_LE(val) ((glong) GINT32_TO_LE (val)) #define GULONG_TO_LE(val) ((gulong) GUINT32_TO_LE (val)) #define GLONG_TO_BE(val) ((glong) GINT32_TO_BE (val)) #define GULONG_TO_BE(val) ((gulong) GUINT32_TO_BE (val)) #define GINT_TO_LE(val) ((gint) GINT32_TO_LE (val)) #define GUINT_TO_LE(val) ((guint) GUINT32_TO_LE (val)) #define GINT_TO_BE(val) ((gint) GINT32_TO_BE (val)) #define GUINT_TO_BE(val) ((guint) GUINT32_TO_BE (val)) #define GSIZE_TO_LE(val) ((gsize) GUINT64_TO_LE (val)) #define GSSIZE_TO_LE(val) ((gssize) GINT64_TO_LE (val)) #define GSIZE_TO_BE(val) ((gsize) GUINT64_TO_BE (val)) #define GSSIZE_TO_BE(val) ((gssize) GINT64_TO_BE (val)) #define G_BYTE_ORDER G_LITTLE_ENDIAN #define GLIB_SYSDEF_POLLIN =1 #define GLIB_SYSDEF_POLLOUT =4 #define GLIB_SYSDEF_POLLPRI =2 #define GLIB_SYSDEF_POLLHUP =16 #define GLIB_SYSDEF_POLLERR =8 #define GLIB_SYSDEF_POLLNVAL =32 #define G_MODULE_SUFFIX "dll" typedef void* GPid; #define G_PID_FORMAT "p" #define GLIB_SYSDEF_AF_UNIX 1 #define GLIB_SYSDEF_AF_INET 2 #define GLIB_SYSDEF_AF_INET6 23 #define GLIB_SYSDEF_MSG_OOB 1 #define GLIB_SYSDEF_MSG_PEEK 2 #define GLIB_SYSDEF_MSG_DONTROUTE 4 #define G_DIR_SEPARATOR '\\' #define G_DIR_SEPARATOR_S "\\" #define G_SEARCHPATH_SEPARATOR ';' #define G_SEARCHPATH_SEPARATOR_S ";" G_END_DECLS #endif /* __GLIBCONFIG_H__ */
8d2963435c287e9907916fa8c769e8611a8aaca7
99220be0d4710b2ace7d9d455c5ab6d4b3082296
/Src/pangen2.h
491289849839dfe4f8ca16eb601b0a9eb99a0032
[ "BSD-3-Clause" ]
permissive
nimble-code/Spin
024303c55fde5730497b5b2cf5a3550fe55858b4
c400fb339f505e0c9defc695604ede9cfe777f77
refs/heads/master
2023-06-09T00:51:20.421697
2023-05-30T22:20:31
2023-05-30T22:20:31
162,628,208
326
153
NOASSERTION
2023-06-05T16:42:59
2018-12-20T20:29:19
C
UTF-8
C
false
false
37,415
h
pangen2.h
/***** spin: pangen2.h *****/ /* * This file is part of the public release of Spin. It is subject to the * terms in the LICENSE file that is included in this source directory. * Tool documentation is available at http://spinroot.com */ static const char *Pre0[] = { "#ifdef SC", " #define _FILE_OFFSET_BITS 64", /* allows file sizes greater than 2Gb */ "#endif", "#include <stdio.h>", "#include <signal.h>", "#include <stdlib.h>", "#include <stdarg.h>", "#include <string.h>", "#include <ctype.h>", "#include <errno.h>", "#if defined(WIN32) || defined(WIN64)", "#include <time.h>", "#else", "#include <unistd.h>", "#include <sys/times.h>", "#endif", "#include <sys/types.h>", /* defines off_t */ "#include <sys/stat.h>", "#include <limits.h>", "#include <fcntl.h>", "#define Offsetof(X, Y) ((ulong)(&(((X *)0)->Y)))", "#ifndef max", "#define max(a,b) (((a)<(b)) ? (b) : (a))", "#endif", "#ifndef PRINTF", "int Printf(const char *fmt, ...); /* prototype only */", "#endif", 0, }; static const char *Separate[] = { "#ifdef COLLAPSE", " #if (NCORE>1 && !defined(SEP_STATE)) || defined(BFS_PAR)", " volatile ulong *ncomps; /* in shared memory */", " #else", " ulong ncomps[256+2];", " #endif", "#endif", "Trans ***trans; /* 1 ptr per state per proctype */\n", "", "#if VECTORSZ>32000", " int P_o[MAXPROC], P_o_tmp[MAXPROC+1];", " int Q_o[MAXQ], Q_o_tmp[MAXPROC+1];", "", " int *proc_offset = (int *) P_o;", " int *q_offset = (int *) Q_o;", "#else", " short P_o[MAXPROC], P_o_tmp[MAXPROC+1];", " short Q_o[MAXQ], Q_o_tmp[MAXPROC+1];", "", " short *proc_offset = (short *) P_o;", " short *q_offset = (short *) Q_o;", "#endif", "uchar P_s[MAXPROC+1], P_s_tmp[MAXPROC+1];", "uchar Q_s[MAXQ+1], Q_s_tmp[MAXQ+1];", "uchar *proc_skip = (uchar *) P_s;", "uchar *q_skip = (uchar *) Q_s;", "", "#ifdef TRIX", " TRIX_v6 *freebodies;", " TRIX_v6 *processes[MAXPROC+1];", " TRIX_v6 *channels[MAXQ+1];", " long _p_count[MAXPROC];", " long _c_count[MAXPROC];", "#endif\n", "ulong vsize; /* vector size in bytes */", "#ifdef SVDUMP", " int vprefix=0, svfd; /* runtime option -pN */", "#endif", "char *tprefix = \"trail\"; /* runtime option -tsuffix */", "short boq = -1; /* blocked_on_queue status */", "int _; /* predefined write-only variable */", "#ifdef PEG", " long peg[NTRANS];", "#endif", 0, }; static const char *Preamble[] = { "#ifdef RANDOMIZE", " #define T_RAND RANDOMIZE", "#endif", "#ifdef CNTRSTACK", " #define onstack_now() (LL[trpt->j6] && LL[trpt->j7])", " #define onstack_put() LL[trpt->j6]++; LL[trpt->j7]++", " #define onstack_zap() LL[trpt->j6]--; LL[trpt->j7]--", "#endif", "#if !defined(SAFETY) && !defined(NOCOMP)", /* * V_A identifies states in the current statespace * A_V identifies states in the 'other' statespace * S_A remembers how many leading bytes in the sv * are used for these markers + fairness bits */ " #define V_A (((now._a_t&1)?2:1) << (now._a_t&2))", " #define A_V (((now._a_t&1)?1:2) << (now._a_t&2))", " int S_A = 0;", "#else", " #define V_A 0", " #define A_V 0", " #define S_A 0", "#endif", "#ifdef MA", "#undef onstack_now", "#undef onstack_put", "#undef onstack_zap", "#define onstack_put() ;", "#define onstack_zap() g_store((char *) &now, vsize, 4)", "#else", "#if defined(FULLSTACK) && !defined(BITSTATE)", "#define onstack_put() trpt->ostate = Lstate", "#define onstack_zap() { \\", " if (trpt->ostate) \\", " trpt->ostate->tagged = \\", " (S_A)? (trpt->ostate->tagged&~V_A) : 0; \\", " }", "#endif", "#endif", "H_el **H_tab, **S_Tab;", "/* #ifndef BFS_PAR */", " H_el *Lstate;", "/* #endif */", "Trail *trail, *trpt;", "FILE *efd;", "uchar *_this;", "long maxdepth=10000;", "long omaxdepth=10000;", "#ifdef BCS", " /* bitflags in trpt->bcs */", " #define B_PHASE1 1", " #define B_PHASE2 2", " #define B_FORCED 4", "int sched_max = 0;", "#endif", "", "double quota; /* time limit */", "#if NCORE>1", " long z_handoff = -1;", "#endif", "#ifdef SC", /* stack cycling */ " char *stackfile;", "#endif", "uchar *SS, *LL;", "", "uchar reversing = 0;", "uchar HASH_NR = 0;", "", "double memcnt = (double) 0;", "double memlim = (double) (1<<30); /* 1 GB */", "#if NCORE>1", "double mem_reserved = (double) 0;", "#endif", "", "/* for emalloc: */", "static char *have;", "static long left = 0L;", "static double fragment = (double) 0;", "static ulong grow;", "", #if 1 "unsigned int HASH_CONST[] = {", " /* generated by hashgen 421 -- assumes 4 bytes per int */", " 0x100d4e63, 0x0fc22f87, 0xa7155c77, 0x78f2c3b9,", " 0xde32d207, 0xc27d305b, 0x1bb3fb2b, 0x2798c7a5,", " 0x9c675ffd, 0x777d9081, 0x07aef2f1, 0xae08922f,", " 0x5bd365b7, 0xed51c47b, 0x9b5aeea1, 0xbcc9d431,", " 0x396d8fff, 0xa2fd1367, 0x08616521, 0x5e84991f,", " 0x87495bc5, 0x2930039b, 0xceb6a593, 0xfe522d63,", " 0x7ff60baf, 0xf89b1fbf, 0x74c01755, 0xe0c559bf,", " 0x3669fc47, 0x8756d3bf, 0x14f78445, 0x24c41779,", " 0x0af7b129, 0xde22368d, 0x3e1c01e3, 0xaf773e49,", " 0x5b762459, 0x86d12911, 0x0953a3af, 0xb66dc23d,", " 0x96b3bd4f, 0x19b1dd51, 0xd886fbc3, 0xa7f3a025,", " 0xccb48e63, 0x87d8f027, 0x2bea270d, 0xdb0e9379,", " 0x78c09f21, 0x0cbbfe07, 0xea4bc7c3, 0x5bfbc3c9,", " 0x3c6e53fd, 0xab320cdd, 0x31041409, 0x416e7485,", " 0xe41d75fd, 0xc3c5060f, 0x201a9dc1, 0x93dee72b,", " 0x6461305f, 0xc571dec5, 0xa1fd21c5, 0xfb421ce1,", " 0x7f024b05, 0xfa518819, 0x6c9777fb, 0x0d4d9351,", " 0x08b33861, 0xccb9d0f3, 0x34112791, 0xe962d7c9,", " 0x8d742211, 0xcd9c47a1, 0x64437b69, 0x5fe40feb,", " 0x806113cb, 0x10e1d593, 0x821851b3, 0x057a1ff3,", " 0x8ededc0b, 0x90dd5b31, 0x635ff359, 0x68dbcd35,", " 0x1050ff4f, 0xdbb07257, 0x486336db, 0x83af1e75,", " 0x432f1799, 0xc1d0e7e7, 0x21f4eb5b, 0x881ec2c1,", " 0x23f3b539, 0x6cdfb80d, 0x71d474cf, 0x97d5d4a9,", " 0xf721d2e5, 0xb5ff3711, 0x3f2e58cd, 0x4e06e3d9,", " 0x7d711739, 0x927887df, 0x7d57ad71, 0x232eb767,", " 0xe3f5cc51, 0x6576b443, 0xed17bf1f, 0x8828b637,", " 0xc940f6ab, 0xc7b830ef, 0x11ed8a13, 0xaff20949,", " 0xf28a8465, 0x0da10cf9, 0xb512497d, 0x44accae1,", " 0x95e0929f, 0xe08c8901, 0xfd22d6c9, 0xb6a5c029,", " 0xaadb428d, 0x6e8a453d, 0x3d5c0195, 0x8bf4ae39,", " 0xbf83ab19, 0x3e9dac33, 0xc4df075d, 0x39472d71,", " 0xb8647725, 0x1a6d4887, 0x78a03577, 0xafd76ef7,", " 0xc1a1d6b3, 0x1afb33c5, 0x87896299, 0x5cc992ef,", " 0x7f805d0d, 0x089a039b, 0xa353cc27, 0x57b296b3,", " 0x52badec9, 0xc916e431, 0x09171957, 0x14996d51,", " 0xe87e32c7, 0xb4fdbb5d, 0xdd216a03, 0x4ddd3fff,", " 0x767d5c57, 0x79c97509, 0xab70543b, 0xc5feca4f,", " 0x8eb37b89, 0x20a2cefd, 0xf4b00b91, 0xf166593d,", " 0x7bf50f65, 0x753e6c8b, 0xfb5b81dd, 0xf2d45ef5,", " 0x9741c04f, 0x300da48d, 0x01dc4121, 0xa112cd47,", " 0x0223b24b, 0xa89fbce7, 0x681e1f7b, 0xe7c6aedf,", " 0x1fd3d523, 0x561ba723, 0xf54042fb, 0x1a516751,", " 0xcd085bd5, 0xe74246d5, 0x8b170b5d, 0x249985e9,", " 0x5b4d9cf7, 0xe9912323, 0x5fc0f339, 0x41f8f051,", " 0x8a296fb1, 0x62909f51, 0x2c05d695, 0x095efccb,", " 0xa91574f1, 0x0f5cc6c3, 0x23a2ca2b, 0xc6053ec1,", " 0xeb19e081, 0x3d1b3997, 0xb0c5f3cd, 0xe5d85b35,", " 0x1cb1bdf1, 0x0c8f278f, 0x518249c3, 0x9f61b68d,", " 0xade0919d, 0x779e29c3, 0xdbac9485, 0x2ce149a9,", " 0x254c2409, 0x205b34fb, 0xc8ab1a89, 0x6b4a2585,", " 0x2303d94b, 0x8fa186b9, 0x49826da5, 0xd23a37ad,", " 0x680b18c9, 0xa46fbd7f, 0xe42c2cf9, 0xf7cfcb5f,", " 0xb4842b8b, 0xe483780d, 0x66cf756b, 0x3eb73781,", " 0x41ca17a5, 0x59f91b0f, 0x92fb67d9, 0x0a5c330f,", " 0x46013fdb, 0x3b0634af, 0x9024f533, 0x96a001a7,", " 0x15bcd793, 0x3a311fb1, 0x78913b8b, 0x9d4a5ddf,", " 0x33189b31, 0xa99e8283, 0xf7cb29e9, 0x12d64a27,", " 0xeda770ff, 0xa7320297, 0xbd3c14a5, 0x96d0156f,", " 0x0115db95, 0x7f79f52b, 0xa6d52521, 0xa063d4bd,", " 0x9cb5e039, 0x42cf8195, 0xcb716835, 0x1bc21273,", " 0x5a67ad27, 0x4b3b0545, 0x162cda67, 0x0489166b,", " 0x85fd06a9, 0x562b037d, 0x995bc1f3, 0xe144e78b,", " 0x1e749f69, 0xa36df057, 0xcfee1667, 0x8c4116b7,", " 0x94647fe3, 0xe6899df7, 0x6d218981, 0xf1069079,", " 0xd1851a33, 0xf424fc83, 0x24467005, 0xad8caf59,", " 0x1ae5da13, 0x497612f9, 0x10f6d1ef, 0xeaf4ff05,", " 0x405f030b, 0x693b041d, 0x2065a645, 0x9fec71b3,", " 0xc3bd1b0f, 0xf29217a3, 0x0f25e15d, 0xd48c2b97,", " 0xce8acf2d, 0x0629489b, 0x1a5b0e01, 0x32d0c059,", " 0x2d3664bf, 0xc45f3833, 0xd57f551b, 0xbdd991c5,", " 0x9f97da9f, 0xa029c2a9, 0x5dd0cbdf, 0xe237ba41,", " 0x62bb0b59, 0x93e7d037, 0x7e495619, 0x51b8282f,", " 0x853e8ef3, 0x9b8abbeb, 0x055f66f9, 0x2736f7e5,", " 0x8d7e6353, 0x143abb65, 0x4e2bb5b3, 0x872e1adf,", " 0x8fcac853, 0xb7cf6e57, 0x12177f3d, 0x1d2da641,", " 0x07856425, 0xc0ed53dd, 0x252271d9, 0x79874843,", " 0x0aa8c9b5, 0x7e804f93, 0x2d080e09, 0x3929ddfd,", " 0x36433dbd, 0xd6568c17, 0xe624e939, 0xb33189ef,", " 0x29e68bff, 0x8aae2433, 0xe6335499, 0xc5facd9d,", " 0xbd5afc65, 0x7a584fa7, 0xab191435, 0x64bbdeef,", " 0x9f5cd8e1, 0xb3a1be05, 0xbd0c1753, 0xb00e2c7f,", " 0x6a96e315, 0x96a31589, 0x660af5af, 0xc0438d43,", " 0x17637373, 0x6460e8df, 0x7d458de9, 0xd76b923f,", " 0x316f045f, 0x3ccbd035, 0x63f64d81, 0xd990d969,", " 0x7c860a93, 0x99269ff7, 0x6fbcac8f, 0xd8cc562b,", " 0x67141071, 0x09f85ea3, 0x1298f2dd, 0x41fa86e5,", " 0xce1d7cf5, 0x6b232c9d, 0x8f093d4b, 0x3203ad4b,", " 0x07d70d5f, 0x38c44c75, 0x0887c9ef, 0x1833acf5,", " 0xa3607f85, 0x7d367573, 0x0ea4ffc3, 0xad2d09c1,", " 0x7a1e664f, 0xef41dff5, 0x03563491, 0x67f30a1f,", " 0x5ce5f9ef, 0xa2487a27, 0xe5077957, 0x9beb36fd,", " 0x16e41251, 0x216799ef, 0x07181f8d, 0xc191c3cf,", " 0xba21cab5, 0x73944eb7, 0xdf9eb69d, 0x5fef6cfd,", " 0xd750a6f5, 0x04f3fa43, 0x7cb2d063, 0xd3bdb369,", " 0x35f35981, 0x9f294633, 0x5e293517, 0x70e51d05,", " 0xf8db618d, 0x66ee05db, 0x835eaa77, 0x166a02c3,", " 0xb516f283, 0x94102293, 0x1ace50a5, 0x64072651,", " 0x66df7b75, 0x02e1b261, 0x8e6a73b9, 0x19dddfe7,", " 0xd551cf39, 0x391c17cb, 0xf4304de5, 0xcd67b8d1,", " 0x25873e8d, 0x115b4c71, 0x36e062f3, 0xaec0c7c9,", " 0xd929f79d, 0x935a661b, 0xda762b47, 0x170bd76b,", " 0x1a955cb5, 0x341fb0ef, 0x7f366cef, 0xc98f60c7,", " 0xa4181af3, 0xa94a8837, 0x5fa3bc43, 0x11c638c1,", " 0x4e66fabb, 0x30ab85cf, 0x250704ef, 0x8bf3bc07,", " 0x6d2cd5ab, 0x613ef9c3, 0xb8e62149, 0x0404fd91,", " 0xa04fd9b1, 0xa5e389eb, 0x9543bd23, 0xad6ca1f9,", " 0x210c49ab, 0xf8e9532b, 0x854fba89, 0xdc7fc6bb,", " 0x48a051a7, 0x6b2f383b, 0x61a4b433, 0xd3af231b,", " 0xc5023fc7, 0xa5aa85df, 0xa0cd1157, 0x4206f64d,", " 0x3fea31c3, 0x62d510a1, 0x13988957, 0x6a11a033,", " 0x46f2a3b7, 0x2784ef85, 0x229eb9eb, 0x9c0c3053,", " 0x5b7ead39, 0x82ae9afb, 0xf99e9fb3, 0x914b6459,", " 0xaf05edd7, 0xc82710dd, 0x8fc1ea1f, 0x7e0d7a8d,", " 0x7c7592e9, 0x65321017, 0xea57553f, 0x4aeb49ff,", " 0x5239ae4d, 0x4b4b4585, 0x94091c21, 0x7eaaf4cb,", " 0x6b489d6f, 0xecb9c0c3, 0x29a7af63, 0xaf117a0d,", " 0x969ea6cd, 0x7658a34d, 0x5fc0bba9, 0x26e99b7f,", " 0x7a6f260f, 0xe37c34f1, 0x1a1569bb, 0xc3bc7371,", " 0x8567543d, 0xad0c46a9, 0xa1264fd9, 0x16f10b29,", " 0x5e00dd3b, 0xf85b6bcd, 0xa2d32d8b, 0x4a3c8d43,", " 0x6b33b959, 0x4fd1e6c9, 0x7938b8a9, 0x1ec795c7,", " 0xe2ef3409, 0x83c16b9d, 0x0d3fd9eb, 0xeb461ad7,", " 0xb09c831d, 0xaf052001, 0x7911164d, 0x1a9dc191,", " 0xb52a0815, 0x0f732157, 0xc68c4831, 0x12cf3cbb };", #else "unsigned int HASH_CONST[] = {", " /* asuming 4 bytes per int */", " 0x100d4e63, 0x0fc22f87,", " 0x3ff0c3ff, 0x38e84cd7,", " 0x02b148e9, 0x98b2e49d,", " 0xb616d379, 0xa5247fd9,", " 0xbae92a15, 0xb91c8bc5,", " 0x8e5880f3, 0xacd7c069,", " 0xb4c44bb3, 0x2ead1fb7,", " 0x8e428171, 0xdbebd459,", " 0x00400007, 0x04c11db7,", " 0x828ae611, 0x6cb25933,", " 0x86cdd651, 0x9e8f5f21,", " 0xd5f8d8e7, 0x9c4e956f,", " 0xb5cf2c71, 0x2e805a6d,", " 0x33fc3a55, 0xaf203ed1,", " 0xe31f5909, 0x5276db35,", " 0x0c565ef7, 0x273d1aa5,", " 0x8923b1dd, 0xa9acaac5,", " 0xd1f69207, 0xedfd944b,", " 0x9a68e46b, 0x5355e13f,", " 0x7eeb44f9, 0x932beea9,", " 0x330c4cd3, 0x87f34e5f,", " 0x1b5851b7, 0xb9ca6447,", " 0x58f96a8f, 0x1b3b5307,", " 0x31c387b3, 0xf35f0f35,", " 0xa0acc4df, 0xf3140303,", " 0x2446245d, 0xe4b8f4ef,", " 0x5c007383, 0x68e648af,", " 0x1814fba7, 0xcdf731b5,", " 0xd09ccb4b, 0xb92d0eff,", " 0xcc3c6b67, 0xd3af6a57,", " 0xf44fc3f5, 0x5bb67623,", " 0xaeb9c953, 0x5e0ac739,", " 0x3a7fda09, 0x5edf39eb,", " 0x661eefd9, 0x6423f0d1,", " 0x910fe413, 0x9ec92297,", " 0x4bd8159d, 0xa7b16ee1,", " 0x89d484e9, 0x7f305cb3,", " 0xc5f303e7, 0x415deeef,", " 0x09986f89, 0x7e9c4117,", " 0x0b7cbedb, 0xf9ed7561,", " 0x7a20ac99, 0xf05adef3,", " 0x5893d75b, 0x44d73327,", " 0xb583c873, 0x324d2145,", " 0x7fa3829b, 0xe4b47a23,", " 0xe256d94f, 0xb1fd8959,", " 0xe561a321, 0x1435ac09,", " 0xdd62408b, 0x02ec0bcb,", " 0x5469b785, 0x2f4f50bb,", " 0x20f19395, 0xf96ba085,", " 0x2381f937, 0x768e2a11 };", #endif "", "#if NCORE>1", "extern int core_id;", "#endif", "long mreached=0;", "ulong errors=0;", "int done=0, Nrun=1;", "int c_init_done=0;", "char *c_stack_start = (char *) 0;", "double nstates=0, nlinks=0, truncs=0, truncs2=0;", "double nlost=0, nShadow=0, hcmp=0, ngrabs=0;", "#ifdef BFS_PAR", "extern ulong bfs_punt;", "#endif", "#ifdef PUTPID", "char *progname;", "#endif", "#if defined(ZAPH) && defined(BITSTATE)", "double zstates = 0;", "#endif", "/* int c_init_run; */", "#ifdef REVERSE", " #define P_REVERSE", "#endif", "#ifdef T_REVERSE", " int t_reverse = 1;", /* can be modified with a parameter */ "#else", " int t_reverse = 0;", "#endif", "#ifdef BFS", "double midrv=0, failedrv=0, revrv=0;", "#endif", "ulong nr_states=0; /* nodes in DFA */", "long Fa=0, Fh=0, Zh=0, Zn=0;", "long PUT=0, PROBE=0, ZAPS=0;", "long Ccheck=0, Cholds=0;", "int a_cycles=0, upto=1, strict=0, verbose = 0, signoff = 0;", "#ifdef HAS_CODE", "int gui = 0, coltrace = 0, readtrail = 0;", "int whichtrail = 0, whichclaim = -1, onlyproc = -1, silent = 0;", "char *claimname;", "#endif", "int state_tables=0, fairness=0, no_rck=0, Nr_Trails=0, dodot=0;", "char simvals[256];", "#ifndef INLINE", "int TstOnly=0;", "#endif", "ulong mask, nmask;", "#ifdef BITSTATE", "int ssize=27; /* 16 Mb */", "#else", "int ssize=24; /* 16M slots */", "#endif", "int hmax=0, svmax=0, smax=0;", "int Maxbody=0, XX;", "uchar *noptr, *noqptr; /* used by Pptr(x) and Qptr(x) */", "#ifdef VAR_RANGES", "void logval(char *, int);", "void dumpranges(void);", "#endif", "#ifdef MA", "#define INLINE_REV", "extern void dfa_init(unsigned short);", "extern int dfa_member(ulong);", "extern int dfa_store(uchar *);", "unsigned int maxgs = 0;", "#endif", "", "#ifdef ALIGNED", " State comp_now __attribute__ ((aligned (8)));", " /* gcc 64-bit aligned for Itanium2 systems */", " /* MAJOR runtime penalty if not used on those systems */", "#else", " State comp_now; /* compressed state vector */", "#endif", "", "#ifndef HC", " #ifdef BFS_PAR", " State tmp_msk;", " #endif", " State comp_msk;", " uchar *Mask = (uchar *) &comp_msk;", "#endif", "#ifdef COLLAPSE", " State comp_tmp;", " static char *scratch = (char *) &comp_tmp;", "#endif", "", "_Stack *stack; /* for queues, processes */", "Svtack *svtack; /* for old state vectors */", "#ifdef BITSTATE", "static unsigned int hfns = 3; /* new default */", "#endif", "static ulong j1_spin, j2_spin; /* 5.2.1: avoid nameclash with math.h */", "static ulong j3_spin, j4_spin;", "ulong K1, K2;", "#ifdef BITSTATE", "long udmem;", "#endif", "#ifndef BFS_PAR", "static long A_depth = 0;", "#endif", "long depth = 0;", "long depthfound = -1; /* loop detection */", /* depth: not static to support -S2, but possible clash with embedded code */ "#if NCORE>1", "long nr_handoffs = 0;", "#endif", "uchar warned = 0, iterative = 0, exclusive = 0, like_java = 0, every_error = 0;", "uchar noasserts = 0, noends = 0, bounded = 0;", "uint s_rand = 12345; /* default seed */", "#if SYNC>0 && ASYNC==0", "void set_recvs(void);", "int no_recvs(int);", "#endif", "#if SYNC", "#define IfNotBlocked if (boq != -1) continue;", "#define UnBlock boq = -1", "#else", "#define IfNotBlocked /* cannot block */", "#define UnBlock /* don't bother */", "#endif\n", "#ifdef BITSTATE", "int (*b_store)(char *, int);", "int bstore_reg(char *, int);", "int bstore_mod(char *, int);", "#endif", "", "void dfs_uerror(char *);", "void dfs_Uerror(char *);", "#ifdef BFS_PAR", "void bfs_uerror(char *);", "void bfs_Uerror(char *);", "#endif", "void (*uerror)(char *);", "void (*Uerror)(char *);", "void (*hasher)(uchar *, int);", "void (*o_hash)(uchar *, int, int);", "void d_hash(uchar *, int);", "void m_hash(uchar *, int);", "void d_sfh(uchar *, int);", "void o_hash32(uchar *, int, int);", "void o_hash64(uchar *, int, int);", "", "void active_procs(void);", "void cleanup(void);", "void do_the_search(void);", "void find_shorter(int);", "void iniglobals(int);", "void stopped(int);", "void wrapup(void);", "int *grab_ints(int);", "void ungrab_ints(int *, int);", 0, }; static const char *Tail[] = { "Trans *", "settr( int t_id, int a, int b, int c, int d,", " char *t, int g, int tpe0, int tpe1)", "{ Trans *tmp = (Trans *) emalloc(sizeof(Trans));\n", " tmp->atom = a&(6|32); /* only (2|8|32) have meaning */", " if (!g) tmp->atom |= 8; /* no global references */", " tmp->st = b;", " tmp->tpe[0] = tpe0;", " tmp->tpe[1] = tpe1;", " tmp->tp = t;", " tmp->t_id = t_id;", " tmp->forw = c;", " tmp->back = d;", " return tmp;", "}\n", "Trans *", "cpytr(Trans *a)", "{ Trans *tmp = (Trans *) emalloc(sizeof(Trans));\n", " int i;", " tmp->atom = a->atom;", " tmp->st = a->st;", "#ifdef HAS_UNLESS", " tmp->e_trans = a->e_trans;", " for (i = 0; i < HAS_UNLESS; i++)", " tmp->escp[i] = a->escp[i];", "#endif", " tmp->tpe[0] = a->tpe[0];", " tmp->tpe[1] = a->tpe[1];", " for (i = 0; i < 6; i++)", " { tmp->qu[i] = a->qu[i];", " tmp->ty[i] = a->ty[i];", " }", " tmp->tp = (char *) emalloc(strlen(a->tp)+1);", " strcpy(tmp->tp, a->tp);", " tmp->t_id = a->t_id;", " tmp->forw = a->forw;", " tmp->back = a->back;", " return tmp;", "}\n", "#ifndef NOREDUCE", "int", "srinc_set(int n)", "{ if (n <= 2) return LOCAL;", " if (n <= 2+ DELTA) return Q_FULL_F; /* 's' or nfull */", " if (n <= 2+2*DELTA) return Q_EMPT_F; /* 'r' or nempty */", " if (n <= 2+3*DELTA) return Q_EMPT_T; /* empty */", " if (n <= 2+4*DELTA) return Q_FULL_T; /* full */", " if (n == 5*DELTA) return GLOBAL;", " if (n == 6*DELTA) return TIMEOUT_F;", " if (n == 7*DELTA) return ALPHA_F;", " Uerror(\"cannot happen srinc_class\");", " return BAD;", "}", "int", "srunc(int n, int m)", "{ switch(m) {", " case Q_FULL_F: return n-2;", " case Q_EMPT_F: return n-2-DELTA;", " case Q_EMPT_T: return n-2-2*DELTA;", " case Q_FULL_T: return n-2-3*DELTA;", " case ALPHA_F:", " case TIMEOUT_F: return 257; /* non-zero, and > MAXQ */", " }", " Uerror(\"cannot happen srunc\");", " return 0;", "}", "#endif", "int cnt;", "#ifdef HAS_UNLESS", "int", "isthere(Trans *a, int b)", /* is b already in a's list? */ "{ Trans *t;", " for (t = a; t; t = t->nxt)", " if (t->t_id == b)", " return 1;", " return 0;", "}", "#endif", "#ifndef NOREDUCE", "int", "mark_safety(Trans *t) /* for conditional safety */", "{ int g = 0, i, j, k;", "", " if (!t) return 0;", " if (t->qu[0])", " return (t->qu[1])?2:1; /* marked */", "", " for (i = 0; i < 2; i++)", " { j = srinc_set(t->tpe[i]);", " if (j >= GLOBAL && j != ALPHA_F)", " return -1;", " if (j != LOCAL)", " { k = srunc(t->tpe[i], j);", " if (g == 0", " || t->qu[0] != k", " || t->ty[0] != j)", " { t->qu[g] = k;", " t->ty[g] = j;", " g++;", " } } }", " return g;", "}", "#endif", "void", "retrans(int n, int m, int is, short srcln[], uchar reach[], uchar lpstate[])", " /* process n, with m states, is=initial state */", "{ Trans *T0, *T1, *T2, *T3;", " Trans *T4, *T5; /* t_reverse or has_unless */", " int i;", "#if defined(HAS_UNLESS) || !defined(NOREDUCE)", " int k;", "#endif", "#ifndef NOREDUCE", " int g, h, j, aa;", "#endif", "#ifdef HAS_UNLESS", " int p;", "#endif", " if (state_tables >= 4)", " { printf(\"STEP 1 %%s\\n\", ", " procname[n]);", " for (i = 1; i < m; i++)", " for (T0 = trans[n][i]; T0; T0 = T0->nxt)", " crack(n, i, T0, srcln);", " return;", " }", " do {", " for (i = 1, cnt = 0; i < m; i++)", " { T2 = trans[n][i];", " T1 = T2?T2->nxt:(Trans *)0;", "/* prescan: */ for (T0 = T1; T0; T0 = T0->nxt)", "/* choice in choice */ { if (T0->st && trans[n][T0->st]", " && trans[n][T0->st]->nxt)", " break;", " }", "#if 0", " if (T0)", " printf(\"\\tstate %%d / %%d: choice in choice\\n\",", " i, T0->st);", "#endif", " if (T0)", " for (T0 = T1; T0; T0 = T0->nxt)", " { T3 = trans[n][T0->st];", " if (!T3->nxt)", " { T2->nxt = cpytr(T0);", " T2 = T2->nxt;", " imed(T2, T0->st, n, i);", " continue;", " }", " do { T3 = T3->nxt;", " T2->nxt = cpytr(T3);", " T2 = T2->nxt;", " imed(T2, T0->st, n, i);", " } while (T3->nxt);", " cnt++;", " }", " }", " } while (cnt);", " if (state_tables >= 3)", " { printf(\"STEP 2 %%s\\n\", ", " procname[n]);", " for (i = 1; i < m; i++)", " for (T0 = trans[n][i]; T0; T0 = T0->nxt)", " crack(n, i, T0, srcln);", " return;", " }", " for (i = 1; i < m; i++)", " { if (trans[n][i] && trans[n][i]->nxt) /* optimize */", " { T1 = trans[n][i]->nxt;", "#if 0", " printf(\"\\t\\tpull %%d (%%d) to %%d\\n\",", " T1->st, T1->forw, i);", "#endif", /* pull linenumber ref as well: */ " srcln[i] = srcln[T1->st]; /* Oyvind Teig, 5.2.0 */", "", " if (!trans[n][T1->st]) continue;", " T0 = cpytr(trans[n][T1->st]);", " trans[n][i] = T0;", " reach[T1->st] = 1;", " imed(T0, T1->st, n, i);", " for (T1 = T1->nxt; T1; T1 = T1->nxt)", " {", "#if 0", " printf(\"\\t\\tpull %%d (%%d) to %%d\\n\",", " T1->st, T1->forw, i);", "#endif", " /* srcln[i] = srcln[T1->st]; gh: not useful */", " if (!trans[n][T1->st]) continue;", " T0->nxt = cpytr(trans[n][T1->st]);", " T0 = T0->nxt;", " reach[T1->st] = 1;", " imed(T0, T1->st, n, i);", " } } }", " if (state_tables >= 2)", " { printf(\"STEP 3 %%s\\n\", ", " procname[n]);", " for (i = 1; i < m; i++)", " for (T0 = trans[n][i]; T0; T0 = T0->nxt)", " crack(n, i, T0, srcln);", " return;", " }", "#ifdef HAS_UNLESS", " for (i = 1; i < m; i++)", " { if (!trans[n][i]) continue;", " /* check for each state i if an", " * escape to some state p is defined", " * if so, copy and mark p's transitions", " * and prepend them to the transition-", " * list of state i", " */", " if (!like_java) /* the default */", " { for (T0 = trans[n][i]; T0; T0 = T0->nxt)", " for (k = HAS_UNLESS-1; k >= 0; k--)", " { if (p = T0->escp[k])", " for (T1 = trans[n][p]; T1; T1 = T1->nxt)", " { if (isthere(trans[n][i], T1->t_id))", " continue;", " T2 = cpytr(T1);", " T2->e_trans = p;", " T2->nxt = trans[n][i];", " trans[n][i] = T2;", " } }", " } else /* outermost unless checked first */", " { T4 = T3 = (Trans *) 0;", " for (T0 = trans[n][i]; T0; T0 = T0->nxt)", " for (k = HAS_UNLESS-1; k >= 0; k--)", " { if (p = T0->escp[k])", " for (T1 = trans[n][p]; T1; T1 = T1->nxt)", " { if (isthere(trans[n][i], T1->t_id))", " continue;", " T2 = cpytr(T1);", " T2->nxt = (Trans *) 0;", " T2->e_trans = p;", " if (T3) T3->nxt = T2;", " else T4 = T2;", " T3 = T2;", " } }", " if (T4)", " { T3->nxt = trans[n][i];", " trans[n][i] = T4;", " }", " }", " }", "#endif", "#ifndef NOREDUCE", " for (i = 1; i < m; i++)", " { if (a_cycles)", " { /* moves through these states are visible */", " #if PROG_LAB>0 && defined(HAS_NP)", " if (progstate[n][i])", " goto degrade;", " for (T1 = trans[n][i]; T1; T1 = T1->nxt)", " if (progstate[n][T1->st])", " goto degrade;", " #endif", " if (accpstate[n][i] || visstate[n][i])", " goto degrade;", " for (T1 = trans[n][i]; T1; T1 = T1->nxt)", " if (accpstate[n][T1->st])", " goto degrade;", " }", " T1 = trans[n][i];", " if (!T1) continue;", " g = mark_safety(T1); /* V3.3.1 */", " if (g < 0) goto degrade; /* global */", " /* check if mixing of guards preserves reduction */", " if (T1->nxt)", " { k = 0;", " for (T0 = T1; T0; T0 = T0->nxt)", " { if (!(T0->atom&8))", " goto degrade;", " for (aa = 0; aa < 2; aa++)", " { j = srinc_set(T0->tpe[aa]);", " if (j >= GLOBAL && j != ALPHA_F)", " goto degrade;", " if (T0->tpe[aa]", " && T0->tpe[aa]", " != T1->tpe[0])", " k = 1;", " } }", " /* g = 0; V3.3.1 */", " if (k) /* non-uniform selection */", " for (T0 = T1; T0; T0 = T0->nxt)", " for (aa = 0; aa < 2; aa++)", " { j = srinc_set(T0->tpe[aa]);", " if (j != LOCAL)", " { k = srunc(T0->tpe[aa], j);", " for (h = 0; h < 6; h++)", " if (T1->qu[h] == k", " && T1->ty[h] == j)", " break;", " if (h >= 6)", " { T1->qu[g%%6] = k;", " T1->ty[g%%6] = j;", " g++;", " } } }", " if (g > 6)", " { T1->qu[0] = 0; /* turn it off */", " printf(\"pan: warning, line %%d, \",", " srcln[i]);", " printf(\"too many stmnt types (%%d)\",", " g);", " printf(\" in selection\\n\");", " goto degrade;", " }", " }", " /* mark all options global if >=1 is global */", " for (T1 = trans[n][i]; T1; T1 = T1->nxt)", " if (!(T1->atom&8)) break;", " if (T1)", "degrade: for (T1 = trans[n][i]; T1; T1 = T1->nxt)", " T1->atom &= ~8; /* mark as unsafe */", " /* can only mix 'r's or 's's if on same chan */", " /* and not mixed with other local operations */", " T1 = trans[n][i];", " if (!T1 || T1->qu[0]) continue;", " j = T1->tpe[0];", " if (T1->nxt && T1->atom&8)", " { if (j == 5*DELTA)", " { printf(\"warning: line %%d \", srcln[i]);", " printf(\"mixed condition \");", " printf(\"(defeats reduction)\\n\");", " goto degrade;", " }", " for (T0 = T1; T0; T0 = T0->nxt)", " for (aa = 0; aa < 2; aa++)", " if (T0->tpe[aa] && T0->tpe[aa] != j)", " { printf(\"warning: line %%d \", srcln[i]);", " printf(\"[%%d-%%d] mixed %%stion \",", " T0->tpe[aa], j, ", " (j==5*DELTA)?\"condi\":\"selec\");", " printf(\"(defeats reduction)\\n\");", " printf(\" '%%s' <-> '%%s'\\n\",", " T1->tp, T0->tp);", " goto degrade;", " } }", " }", "#endif", " for (i = 1; i < m; i++)", /* R */ " { T2 = trans[n][i];", " if (!T2", " || T2->nxt", " || strncmp(T2->tp, \".(goto)\", 7)", " || !stopstate[n][i])", " continue;", " stopstate[n][T2->st] = 1;", " }", " if (state_tables && !verbose)", " { if (dodot)", " { char buf[256], *q = buf, *p = procname[n];", " while (*p != '\\0')", " { if (*p != ':')", " { *q++ = *p;", " }", " p++;", " }", " *q = '\\0';", " printf(\"digraph \");", " switch (Btypes[n]) {", " case I_PROC: printf(\"init {\\n\"); break;", " case N_CLAIM: printf(\"claim_%%s {\\n\", buf); break;", " case E_TRACE: printf(\"notrace {\\n\"); break;", " case N_TRACE: printf(\"trace {\\n\"); break;", " default: printf(\"p_%%s {\\n\", buf); break;", " }", " printf(\"size=\\\"8,10\\\";\\n\");", " printf(\" GT [shape=box,style=dotted,label=\\\"%%s\\\"];\\n\", buf);", " printf(\" GT -> S%%d;\\n\", is);", " } else", " { switch (Btypes[n]) {", " case I_PROC: printf(\"init\\n\"); break;", " case N_CLAIM: printf(\"claim %%s\\n\", procname[n]); break;", " case E_TRACE: printf(\"notrace assertion\\n\"); break;", " case N_TRACE: printf(\"trace assertion\\n\"); break;", " default: printf(\"proctype %%s\\n\", procname[n]); break;", " } }", " for (i = 1; i < m; i++)", " { reach[i] = 1;", " }", " tagtable(n, m, is, srcln, reach);", " if (dodot) printf(\"}\\n\");", " } else", " for (i = 1; i < m; i++)", " { int nrelse;", " if (Btypes[n] != N_CLAIM)", " { for (T0 = trans[n][i]; T0; T0 = T0->nxt)", " { if (T0->st == i", " && strcmp(T0->tp, \"(1)\") == 0)", " { printf(\"error: proctype '%%s' \",", " procname[n]);", " printf(\"line %%d, state %%d: has un\",", " srcln[i], i);", " printf(\"conditional self-loop\\n\");", " pan_exit(1);", " } } }", " nrelse = 0;", " for (T0 = trans[n][i]; T0; T0 = T0->nxt)", " { if (strcmp(T0->tp, \"else\") == 0)", " nrelse++;", " }", " if (nrelse > 1)", " { printf(\"error: proctype '%%s' state\",", " procname[n]);", " printf(\" %%d, inherits %%d\", i, nrelse);", " printf(\" 'else' stmnts\\n\");", " pan_exit(1);", " } }", "#if !defined(LOOPSTATE) && !defined(BFS_PAR)", " if (state_tables)", "#endif", " do_dfs(n, m, is, srcln, reach, lpstate);", "", " if (!t_reverse)", " { return;", " }", " /* process n, with m states, is=initial state -- reverse list */", " if (!state_tables && Btypes[n] != N_CLAIM)", " { for (i = 1; i < m; i++)", /* for each state */ " { Trans *Tx = (Trans *) 0; /* list of escapes */", " Trans *Ty = (Trans *) 0; /* its tail element */", " T1 = (Trans *) 0; /* reversed list */", " T2 = (Trans *) 0; /* its tail */", " T3 = (Trans *) 0; /* remembers possible 'else' */", "", " /* find unless-escapes, they should go first */", " T4 = T5 = T0 = trans[n][i];", " #ifdef HAS_UNLESS", " while (T4 && T4->e_trans) /* escapes are first in orig list */", " { T5 = T4; /* remember predecessor */", " T4 = T4->nxt;", " }", " #endif", " /* T4 points to first non-escape, T5 to its parent, T0 to original list */", " if (T4 != T0) /* there was at least one escape */", " { T3 = T5->nxt; /* start of non-escapes */", " T5->nxt = (Trans *) 0; /* separate */", " Tx = T0; /* start of the escapes */", " Ty = T5; /* its tail */", " T0 = T3; /* the rest, to be reversed */", " }", " /* T0 points to first non-escape, Tx to the list of escapes, Ty to its tail */", "", " /* first tail-add non-escape transitions, reversed */", " T3 = (Trans *) 0;", /* remember a possible 'else' */ " for (T5 = T0; T5; T5 = T4)", " { T4 = T5->nxt;", " #ifdef HAS_UNLESS", " if (T5->e_trans)", " { printf(\"error: cannot happen!\\n\");", " continue;", " }", " #endif", " if (strcmp(T5->tp, \"else\") == 0)", " { T3 = T5;", " T5->nxt = (Trans *) 0;", " } else", " { T5->nxt = T1;", " if (!T1) { T2 = T5; }", " T1 = T5;", " } }", " /* T3 points to a possible else, which is removed from the list */", " /* T1 points to the reversed list so far (without escapes) */", " /* T2 points to the tail element -- where the else should go */", " if (T2 && T3)", " { T2->nxt = T3; /* add else */", " } else", " { if (T3) /* there was an else, but there's no tail */", " { if (!T1) /* and no reversed list */", " { T1 = T3; /* odd, but possible */", " } else /* even stranger */", " { T1->nxt = T3;", " } } }", "", " /* add in the escapes, to that they appear at the front */", " if (Tx && Ty) { Ty->nxt = T1; T1 = Tx; }", "", " trans[n][i] = T1;", " /* reversed, with escapes first and else last */", " } }", " if (state_tables && verbose)", " { printf(\"FINAL proctype %%s\\n\", ", " procname[n]);", " for (i = 1; i < m; i++)", " for (T0 = trans[n][i]; T0; T0 = T0->nxt)", " crack(n, i, T0, srcln);", " }", "}", "void", "imed(Trans *T, int v, int n, int j) /* set intermediate state */", "{ progstate[n][T->st] |= progstate[n][v];", " accpstate[n][T->st] |= accpstate[n][v];", " stopstate[n][T->st] |= stopstate[n][v];", " mapstate[n][j] = T->st;", "}", "void", "tagtable(int n, int m, int is, short srcln[], uchar reach[])", "{ Trans *z;\n", " if (is >= m || !trans[n][is]", " || is <= 0 || reach[is] == 0)", " return;", " reach[is] = 0;", " if (state_tables)", " for (z = trans[n][is]; z; z = z->nxt)", " { if (dodot)", " dot_crack(n, is, z);", " else", " crack(n, is, z, srcln);", " }", "", " for (z = trans[n][is]; z; z = z->nxt)", " {", "#ifdef HAS_UNLESS", " int i, j;", "#endif", " tagtable(n, m, z->st, srcln, reach);", "#ifdef HAS_UNLESS", " for (i = 0; i < HAS_UNLESS; i++)", " { j = trans[n][is]->escp[i];", " if (!j) break;", " tagtable(n, m, j, srcln, reach);", " }", "#endif", " }", "}", "", "extern Trans *t_id_lkup[];", /* needed by BFS_PAR */ "", "void", "dfs_table(int n, int m, int is, short srcln[], uchar reach[], uchar lpstate[])", "{ Trans *z;\n", " if (is >= m || is <= 0 || !trans[n][is])", " return;", " if ((reach[is] & (4|8|16)) != 0)", " { if ((reach[is] & (8|16)) == 16) /* on stack, not yet recorded */", " { lpstate[is] = 1;", " reach[is] |= 8; /* recorded */", " if (state_tables && verbose)", " { printf(\"state %%d line %%d is a loopstate\\n\", is, srcln[is]);", " } }", " return;", " }", " reach[is] |= (4|16); /* visited | onstack */", " for (z = trans[n][is]; z; z = z->nxt)", " { t_id_lkup[z->t_id] = z;", /* needed by BFS_PAR */ "#ifdef HAS_UNLESS", " int i, j;", "#endif", " dfs_table(n, m, z->st, srcln, reach, lpstate);", "#ifdef HAS_UNLESS", " for (i = 0; i < HAS_UNLESS; i++)", " { j = trans[n][is]->escp[i];", " if (!j) break;", " dfs_table(n, m, j, srcln, reach, lpstate);", " }", "#endif", " }", " reach[is] &= ~16; /* no longer on stack */", "}", "void", "do_dfs(int n, int m, int is, short srcln[], uchar reach[], uchar lpstate[])", "{ int i;", " dfs_table(n, m, is, srcln, reach, lpstate);", " for (i = 0; i < m; i++)", " reach[i] &= ~(4|8|16);", "}", "void", "crack(int n, int j, Trans *z, short srcln[])", "{ int i;\n", " if (!z) return;", " printf(\"\tstate %%3d -(tr %%3d)-> state %%3d \",", " j, z->forw, z->st);", " printf(\"[id %%3d tp %%3d\", z->t_id, z->tpe[0]);", " if (z->tpe[1]) printf(\",%%d\", z->tpe[1]);", "#ifdef HAS_UNLESS", " if (z->e_trans)", " printf(\" org %%3d\", z->e_trans);", " else if (state_tables >= 2)", " for (i = 0; i < HAS_UNLESS; i++)", " { if (!z->escp[i]) break;", " printf(\" esc %%d\", z->escp[i]);", " }", "#endif", " printf(\"]\");", " printf(\" [%%s%%s%%s%%s%%s] %%s:%%d => \",", " z->atom&6?\"A\":z->atom&32?\"D\":\"-\",", " accpstate[n][j]?\"a\" :\"-\",", " stopstate[n][j]?\"e\" : \"-\",", " progstate[n][j]?\"p\" : \"-\",", " z->atom & 8 ?\"L\":\"G\",", " PanSource, srcln[j]);", " for (i = 0; z->tp[i]; i++)", " if (z->tp[i] == \'\\n\')", " printf(\"\\\\n\");", " else", " putchar(z->tp[i]);", " if (verbose && z->qu[0])", " { printf(\"\\t[\");", " for (i = 0; i < 6; i++)", " if (z->qu[i])", " printf(\"(%%d,%%d)\",", " z->qu[i], z->ty[i]);", " printf(\"]\");", " }", " printf(\"\\n\");", " fflush(stdout);", "}", "/* spin -a m.pml; cc -o pan pan.c; ./pan -D | dot -Tps > foo.ps; ps2pdf foo.ps */", "void", "dot_crack(int n, int j, Trans *z)", "{ int i;\n", " if (!z) return;", " printf(\"\tS%%d -> S%%d [color=black\", j, z->st);", "", " if (z->atom&6) printf(\",style=dashed\");", /* A */ " else if (z->atom&32) printf(\",style=dotted\");", /* D */ " else if (z->atom&8) printf(\",style=solid\");", /* L */ " else printf(\",style=bold\");", /* G */ /* other styles: filled dotted */ "", " printf(\",label=\\\"\");", " for (i = 0; z->tp[i]; i++)", " { if (z->tp[i] == \'\\\\\'", " && z->tp[i+1] == \'n\')", " { i++; printf(\" \");", " } else", " { putchar(z->tp[i]);", " } }", " printf(\"\\\"];\\n\");", " if (accpstate[n][j]) printf(\" S%%d [color=red,style=bold];\\n\", j);", " else if (progstate[n][j]) printf(\" S%%d [color=green,style=bold];\\n\", j);", " if (stopstate[n][j]) printf(\" S%%d [color=blue,style=bold,shape=box];\\n\", j);", "}", "", "#ifdef VAR_RANGES", "#define BYTESIZE 32 /* 2^8 : 2^3 = 256:8 = 32 */", "", "typedef struct Vr_Ptr {", " char *nm;", " uchar vals[BYTESIZE];", " struct Vr_Ptr *nxt;", "} Vr_Ptr;", "Vr_Ptr *ranges = (Vr_Ptr *) 0;", "", "void", "logval(char *s, int v)", "{ Vr_Ptr *tmp;", "", " if (v<0 || v > 255) return;", " for (tmp = ranges; tmp; tmp = tmp->nxt)", " if (!strcmp(tmp->nm, s))", " goto found;", " tmp = (Vr_Ptr *) emalloc(sizeof(Vr_Ptr));", " tmp->nxt = ranges;", " ranges = tmp;", " tmp->nm = s;", "found:", " tmp->vals[(v)/8] |= 1<<((v)%%8);", "}", "", "void", "dumpval(uchar X[], int range)", "{ int w, x, i, j = -1;", "", " for (w = i = 0; w < range; w++)", " for (x = 0; x < 8; x++, i++)", " {", "from: if ((X[w] & (1<<x)))", " { printf(\"%%d\", i);", " j = i;", " goto upto;", " } }", " return;", " for (w = 0; w < range; w++)", " for (x = 0; x < 8; x++, i++)", " {", "upto: if (!(X[w] & (1<<x)))", " { if (i-1 == j)", " printf(\", \");", " else", " printf(\"-%%d, \", i-1);", " goto from;", " } }", " if (j >= 0 && j != 255)", " printf(\"-255\");", "}", "", "void", "dumpranges(void)", "{ Vr_Ptr *tmp;", " printf(\"\\nValues assigned within \");", " printf(\"interval [0..255]:\\n\");", " for (tmp = ranges; tmp; tmp = tmp->nxt)", " { printf(\"\\t%%s\\t: \", tmp->nm);", " dumpval(tmp->vals, BYTESIZE);", " printf(\"\\n\");", " }", "}", "#endif", 0, };
05ac69d5bd22991dd603d9a216cdfc094c249aec
7664f318ed04bd0680f3d82321c18896e3ef6ad5
/src/overlays/actors/ovl_En_Wallmas/z_en_wallmas.h
8b2f8d7ba9f87ae0ee4a06dfe7759c47ca5ddb3a
[]
no_license
zeldaret/oot
9c80ce17f2d8fd61514b375f92ee4739b5ce9d4e
2875ab4fcf5c5f81d76353d1ee0024c9ea8d0b23
refs/heads/master
2023-08-29T05:29:31.356427
2023-08-28T22:48:52
2023-08-28T22:48:52
247,875,738
4,401
802
null
2023-09-14T13:34:38
2020-03-17T04:02:19
C
UTF-8
C
false
false
683
h
z_en_wallmas.h
#ifndef Z_EN_WALLMAS_H #define Z_EN_WALLMAS_H #include "ultra64.h" #include "global.h" typedef enum { /* 0x00 */ WMT_TIMER, /* 0x01 */ WMT_PROXIMITY, /* 0x02 */ WMT_FLAG } WallmasType; struct EnWallmas; typedef void (*EnWallmasActionFunc)(struct EnWallmas*, PlayState*); typedef struct EnWallmas { /* 0x0000 */ Actor actor; /* 0x014C */ SkelAnime skelAnime; /* 0x0190 */ EnWallmasActionFunc actionFunc; /* 0x0194 */ s16 timer; /* 0x0196 */ s16 switchFlag; /* 0x0198 */ Vec3s jointTable[25]; /* 0x022E */ Vec3s morphTable[25]; /* 0x02C4 */ f32 yTarget; /* 0x02C8 */ ColliderCylinder collider; } EnWallmas; // size = 0x0314 #endif
428b90264b81d0c42c7e221806e364ae5e807568
971b2cea2d1c3001aadc8ca1a48110b7db1ed5f2
/deps/abc/src/map/if/ifDelay.c
cb25e767ea9360505a91286e8f0fbd06800da9a0
[ "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
16,308
c
ifDelay.c
/**CFile**************************************************************** FileName [ifDelay.c] SystemName [ABC: Logic synthesis and verification system.] PackageName [FPGA mapping based on priority cuts.] Synopsis [Delay balancing for cut functions.] Author [Alan Mishchenko] Affiliation [UC Berkeley] Date [Ver. 1.0. Started - November 21, 2006.] Revision [$Id: ifDelay.c,v 1.00 2006/11/21 00:00:00 alanmi Exp $] ***********************************************************************/ #include "if.h" #include "ifCount.h" #include "bool/kit/kit.h" ABC_NAMESPACE_IMPL_START //////////////////////////////////////////////////////////////////////// /// DECLARATIONS /// //////////////////////////////////////////////////////////////////////// #define IF_MAX_CUBES 70 //////////////////////////////////////////////////////////////////////// /// FUNCTION DEFINITIONS /// //////////////////////////////////////////////////////////////////////// /**Function************************************************************* Synopsis [Computes the SOP delay using balanced AND decomposition.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ static inline int If_CutMaxCubeSize( Vec_Int_t * vCover, int nVars ) { int i, k, Entry, Literal, Count, CountMax = 0; Vec_IntForEachEntry( vCover, Entry, i ) { Count = 0; for ( k = 0; k < nVars; k++ ) { Literal = (3 & (Entry >> (k << 1))); if ( Literal == 1 || Literal == 2 ) Count++; } CountMax = Abc_MaxInt( CountMax, Count ); } return CountMax; } int If_CutDelaySop( If_Man_t * p, If_Cut_t * pCut ) { char * pPerm = If_CutPerm( pCut ); // delay is calculated using 1+log2(NumFanins) static double GateDelays[20] = { 1.00, 1.00, 2.00, 2.58, 3.00, 3.32, 3.58, 3.81, 4.00, 4.17, 4.32, 4.46, 4.58, 4.70, 4.81, 4.91, 5.00, 5.09, 5.17, 5.25 }; Vec_Int_t * vCover; If_Obj_t * pLeaf; int i, nLitMax, Delay, DelayMax; // mark cut as a user cut pCut->fUser = 1; if ( pCut->nLeaves == 0 ) return 0; if ( pCut->nLeaves == 1 ) return (int)If_ObjCutBest(If_CutLeaf(p, pCut, 0))->Delay; vCover = Vec_WecEntry( p->vTtIsops[pCut->nLeaves], Abc_Lit2Var(If_CutTruthLit(pCut)) ); if ( Vec_IntSize(vCover) == 0 ) return -1; // mark the output as complemented // vAnds = If_CutDelaySopAnds( p, pCut, vCover, RetValue ^ pCut->fCompl ); if ( Vec_IntSize(vCover) > p->pPars->nGateSize ) return -1; // set the area cost assert( If_CutLeaveNum(pCut) >= 0 && If_CutLeaveNum(pCut) <= 16 ); // compute the gate delay nLitMax = If_CutMaxCubeSize( vCover, If_CutLeaveNum(pCut) ); if ( Vec_IntSize(vCover) < 2 ) { pCut->Cost = Vec_IntSize(vCover); Delay = (int)(GateDelays[If_CutLeaveNum(pCut)] + 0.5); DelayMax = 0; If_CutForEachLeaf( p, pCut, pLeaf, i ) DelayMax = Abc_MaxInt( DelayMax, If_ObjCutBest(pLeaf)->Delay + (pPerm[i] = (char)Delay) ); } else { pCut->Cost = Vec_IntSize(vCover) + 1; Delay = (int)(GateDelays[If_CutLeaveNum(pCut)] + GateDelays[nLitMax] + 0.5); DelayMax = 0; If_CutForEachLeaf( p, pCut, pLeaf, i ) DelayMax = Abc_MaxInt( DelayMax, If_ObjCutBest(pLeaf)->Delay + (pPerm[i] = (char)Delay) ); } return DelayMax; } /**Function************************************************************* Synopsis [Compute pin delays.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int If_CutSopBalancePinDelaysInt( Vec_Int_t * vCover, int * pTimes, word * pFaninRes, int nSuppAll, word * pRes ) { word pPinDelsAnd[IF_MAX_FUNC_LUTSIZE], pPinDelsOr[IF_MAX_CUBES]; int nCounterAnd, pCounterAnd[IF_MAX_FUNC_LUTSIZE]; int nCounterOr, pCounterOr[IF_MAX_CUBES]; int i, k, Entry, Literal, Delay = 0; word ResAnd; if ( Vec_IntSize(vCover) > IF_MAX_CUBES ) return -1; nCounterOr = 0; Vec_IntForEachEntry( vCover, Entry, i ) { nCounterAnd = 0; for ( k = 0; k < nSuppAll; k++ ) { Literal = 3 & (Entry >> (k << 1)); if ( Literal == 1 || Literal == 2 ) // neg or pos literal Delay = If_LogCounterPinDelays( pCounterAnd, &nCounterAnd, pPinDelsAnd, pTimes[k], pFaninRes[k], nSuppAll, 0 ); else if ( Literal != 0 ) assert( 0 ); } assert( nCounterAnd > 0 ); ResAnd = If_LogPinDelaysMulti( pPinDelsAnd, nCounterAnd, nSuppAll, 0 ); Delay = If_LogCounterPinDelays( pCounterOr, &nCounterOr, pPinDelsOr, Delay, ResAnd, nSuppAll, 0 ); } assert( nCounterOr > 0 ); *pRes = If_LogPinDelaysMulti( pPinDelsOr, nCounterOr, nSuppAll, 0 ); return Delay; } int If_CutSopBalancePinDelaysIntInt( Vec_Int_t * vCover, int * pTimes, int nSuppAll, char * pPerm ) { int i, Delay; word Res, FaninRes[IF_MAX_FUNC_LUTSIZE]; for ( i = 0; i < nSuppAll; i++ ) FaninRes[i] = If_CutPinDelayInit(i); Delay = If_CutSopBalancePinDelaysInt( vCover, pTimes, FaninRes, nSuppAll, &Res ); If_CutPinDelayTranslate( Res, nSuppAll, pPerm ); return Delay; } int If_CutSopBalancePinDelays( If_Man_t * p, If_Cut_t * pCut, char * pPerm ) { if ( pCut->nLeaves == 0 ) // const return 0; if ( pCut->nLeaves == 1 ) // variable { pPerm[0] = 0; return (int)If_ObjCutBest(If_CutLeaf(p, pCut, 0))->Delay; } else { Vec_Int_t * vCover; int i, pTimes[IF_MAX_FUNC_LUTSIZE]; vCover = Vec_WecEntry( p->vTtIsops[pCut->nLeaves], Abc_Lit2Var(If_CutTruthLit(pCut)) ); if ( Vec_IntSize(vCover) == 0 ) return -1; for ( i = 0; i < If_CutLeaveNum(pCut); i++ ) pTimes[i] = (int)If_ObjCutBest(If_CutLeaf(p, pCut, i))->Delay; return If_CutSopBalancePinDelaysIntInt( vCover, pTimes, If_CutLeaveNum(pCut), pPerm ); } } /**Function************************************************************* Synopsis [Evaluate delay using SOP balancing.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int If_CutSopBalanceEvalInt( Vec_Int_t * vCover, int * pTimes, int * pFaninLits, Vec_Int_t * vAig, int * piRes, int nSuppAll, int * pArea ) { int nCounterAnd, pCounterAnd[IF_MAX_FUNC_LUTSIZE], pFaninLitsAnd[IF_MAX_FUNC_LUTSIZE]; int nCounterOr, pCounterOr[IF_MAX_CUBES], pFaninLitsOr[IF_MAX_CUBES]; int i, k, Entry, Literal, nLits, Delay = 0, iRes = 0; if ( Vec_IntSize(vCover) > IF_MAX_CUBES ) return -1; nCounterOr = 0; Vec_IntForEachEntry( vCover, Entry, i ) { nCounterAnd = nLits = 0; for ( k = 0; k < nSuppAll; k++ ) { Literal = 3 & (Entry >> (k << 1)); if ( Literal == 1 ) // neg literal nLits++, Delay = If_LogCounterAddAig( pCounterAnd, &nCounterAnd, pFaninLitsAnd, pTimes[k], vAig ? Abc_LitNot(pFaninLits[k]) : -1, vAig, nSuppAll, 0, 0 ); else if ( Literal == 2 ) // pos literal nLits++, Delay = If_LogCounterAddAig( pCounterAnd, &nCounterAnd, pFaninLitsAnd, pTimes[k], vAig ? pFaninLits[k] : -1, vAig, nSuppAll, 0, 0 ); else if ( Literal != 0 ) assert( 0 ); } assert( nCounterAnd > 0 ); assert( nLits > 0 ); if ( vAig ) iRes = If_LogCreateAndXorMulti( vAig, pFaninLitsAnd, nCounterAnd, nSuppAll, 0 ); else *pArea += nLits == 1 ? 0 : nLits - 1; Delay = If_LogCounterAddAig( pCounterOr, &nCounterOr, pFaninLitsOr, Delay, vAig ? Abc_LitNot(iRes) : -1, vAig, nSuppAll, 0, 0 ); } assert( nCounterOr > 0 ); if ( vAig ) { *piRes = Abc_LitNot( If_LogCreateAndXorMulti( vAig, pFaninLitsOr, nCounterOr, nSuppAll, 0 ) ); if ( ((vCover->nCap >> 16) & 1) ) // hack to remember complemented attribute *piRes = Abc_LitNot( *piRes ); } else *pArea += Vec_IntSize(vCover) == 1 ? 0 : Vec_IntSize(vCover) - 1; return Delay; } int If_CutSopBalanceEvalIntInt( Vec_Int_t * vCover, int nLeaves, int * pTimes, Vec_Int_t * vAig, int fCompl, int * pArea ) { int pFaninLits[IF_MAX_FUNC_LUTSIZE]; int iRes = 0, Res, k; if ( vAig ) for ( k = 0; k < nLeaves; k++ ) pFaninLits[k] = Abc_Var2Lit(k, 0); Res = If_CutSopBalanceEvalInt( vCover, pTimes, pFaninLits, vAig, &iRes, nLeaves, pArea ); if ( Res == -1 ) return -1; assert( vAig == NULL || Abc_Lit2Var(iRes) == nLeaves + Abc_Lit2Var(Vec_IntSize(vAig)) - 1 ); if ( vAig ) Vec_IntPush( vAig, Abc_LitIsCompl(iRes) ^ fCompl ); assert( vAig == NULL || (Vec_IntSize(vAig) & 1) ); return Res; } int If_CutSopBalanceEval( If_Man_t * p, If_Cut_t * pCut, Vec_Int_t * vAig ) { pCut->fUser = 1; if ( vAig ) Vec_IntClear( vAig ); if ( pCut->nLeaves == 0 ) // const { assert( Abc_Lit2Var(If_CutTruthLit(pCut)) == 0 ); if ( vAig ) Vec_IntPush( vAig, Abc_LitIsCompl(If_CutTruthLit(pCut)) ); pCut->Cost = 0; return 0; } if ( pCut->nLeaves == 1 ) // variable { assert( Abc_Lit2Var(If_CutTruthLit(pCut)) == 1 ); if ( vAig ) Vec_IntPush( vAig, 0 ); if ( vAig ) Vec_IntPush( vAig, Abc_LitIsCompl(If_CutTruthLit(pCut)) ); pCut->Cost = 0; return (int)If_ObjCutBest(If_CutLeaf(p, pCut, 0))->Delay; } else { int fVerbose = 0; Vec_Int_t * vCover = Vec_WecEntry( p->vTtIsops[pCut->nLeaves], Abc_Lit2Var(If_CutTruthLit(pCut)) ); int Delay, Area = 0; int i, pTimes[IF_MAX_FUNC_LUTSIZE]; if ( vCover == NULL ) return -1; assert( Vec_IntSize(vCover) > 0 ); for ( i = 0; i < If_CutLeaveNum(pCut); i++ ) pTimes[i] = (int)If_ObjCutBest(If_CutLeaf(p, pCut, i))->Delay; Delay = If_CutSopBalanceEvalIntInt( vCover, If_CutLeaveNum(pCut), pTimes, vAig, Abc_LitIsCompl(If_CutTruthLit(pCut)) ^ pCut->fCompl, &Area ); pCut->Cost = Area; if ( fVerbose ) { int Max = 0, Two = 0; for ( i = 0; i < If_CutLeaveNum(pCut); i++ ) Max = Abc_MaxInt( Max, pTimes[i] ); for ( i = 0; i < If_CutLeaveNum(pCut); i++ ) if ( pTimes[i] != Max ) Two = Abc_MaxInt( Two, pTimes[i] ); if ( Two + 2 < Max && Max + 3 < Delay ) { for ( i = 0; i < If_CutLeaveNum(pCut); i++ ) printf( "%3d ", pTimes[i] ); for ( ; i < p->pPars->nLutSize; i++ ) printf( " " ); printf( "-> %3d ", Delay ); Dau_DsdPrintFromTruth( If_CutTruthW(p, pCut), If_CutLeaveNum(pCut) ); Kit_TruthIsopPrintCover( vCover, If_CutLeaveNum(pCut), Abc_LitIsCompl(If_CutTruthLit(pCut)) ^ pCut->fCompl ); { Vec_Int_t vIsop; int pIsop[64]; vIsop.nCap = vIsop.nSize = Abc_Tt6Esop( *If_CutTruthW(p, pCut), pCut->nLeaves, pIsop ); vIsop.pArray = pIsop; printf( "ESOP (%d -> %d)\n", Vec_IntSize(vCover), vIsop.nSize ); Kit_TruthIsopPrintCover( &vIsop, If_CutLeaveNum(pCut), 0 ); } printf( "\n" ); } } return Delay; } } /**Function************************************************************* Synopsis [Evaluate delay using SOP balancing.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int If_CutLutBalancePinDelays( If_Man_t * p, If_Cut_t * pCut, char * pPerm ) { if ( pCut->nLeaves == 0 ) // const return 0; if ( pCut->nLeaves == 1 ) // variable { pPerm[0] = 0; return (int)If_ObjCutBest(If_CutLeaf(p, pCut, 0))->Delay; } else { char * pCutPerm = If_CutDsdPerm( p, pCut ); int LutSize = p->pPars->pLutStruct[0] - '0'; int i, Delay, DelayMax = -1; assert( (If_CutLeaveNum(pCut) > LutSize) == (pCut->uMaskFunc > 0) ); for ( i = 0; i < If_CutLeaveNum(pCut); i++ ) { if ( If_CutLeaveNum(pCut) > LutSize && ((pCut->uMaskFunc >> (i << 1)) & 1) ) pPerm[Abc_Lit2Var((int)pCutPerm[i])] = 2; else pPerm[Abc_Lit2Var((int)pCutPerm[i])] = 1; } for ( i = 0; i < If_CutLeaveNum(pCut); i++ ) { Delay = (int)If_ObjCutBest(If_CutLeaf(p, pCut, i))->Delay; DelayMax = Abc_MaxInt( DelayMax, Delay + (int)pPerm[i] ); } return DelayMax; } } /**Function************************************************************* Synopsis [Evaluate delay using SOP balancing.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int If_CutLutBalanceEval( If_Man_t * p, If_Cut_t * pCut ) { pCut->fUser = 1; pCut->Cost = pCut->nLeaves > 1 ? 1 : 0; pCut->uMaskFunc = 0; if ( pCut->nLeaves == 0 ) // const { assert( Abc_Lit2Var(If_CutTruthLit(pCut)) == 0 ); return 0; } if ( pCut->nLeaves == 1 ) // variable { assert( Abc_Lit2Var(If_CutTruthLit(pCut)) == 1 ); return (int)If_ObjCutBest(If_CutLeaf(p, pCut, 0))->Delay; } else { char * pCutPerm = If_CutDsdPerm( p, pCut ); int LutSize = p->pPars->pLutStruct[0] - '0'; int i, pTimes[IF_MAX_FUNC_LUTSIZE]; int DelayMax = -1, nLeafMax = 0; unsigned uLeafMask = 0; for ( i = 0; i < If_CutLeaveNum(pCut); i++ ) { pTimes[i] = (int)If_ObjCutBest(If_CutLeaf(p, pCut, Abc_Lit2Var((int)pCutPerm[i])))->Delay; if ( DelayMax < pTimes[i] ) DelayMax = pTimes[i], nLeafMax = 1, uLeafMask = (1 << (i << 1)); else if ( DelayMax == pTimes[i] ) nLeafMax++, uLeafMask |= (1 << (i << 1)); } if ( If_CutLeaveNum(pCut) <= LutSize ) return DelayMax + 1; pCut->Cost = 2; if ( nLeafMax <= LutSize - 1 ) { pCut->uMaskFunc = If_DsdManCheckXY( p->pIfDsdMan, If_CutDsdLit(p, pCut), LutSize, 1, uLeafMask, 0, 0 ); if ( pCut->uMaskFunc > 0 ) return DelayMax + 1; } pCut->uMaskFunc = If_DsdManCheckXY( p->pIfDsdMan, If_CutDsdLit(p, pCut), LutSize, 1, 0, 0, 0 ); if ( pCut->uMaskFunc == 0 ) return -1; return DelayMax + 2; } } /* int If_CutLutBalanceEval( If_Man_t * p, If_Cut_t * pCut ) { char pPerm[16]; int Delay2, Delay = If_CutLutBalanceEvalInt( p, pCut ); if ( Delay == -1 ) return -1; Delay2 = If_CutLutBalancePinDelays( p, pCut, pPerm ); if ( Delay2 != Delay ) { int s = 0; char * pCutPerm = If_CutDsdPerm( p, pCut ); If_DsdManPrintNode( p->pIfDsdMan, If_CutDsdLit(p, pCut) ); Dau_DecPrintSet( pCut->uMaskFunc, pCut->nLeaves, 1 ); Kit_DsdPrintFromTruth( If_CutTruthUR(p, pCut), pCut->nLeaves ); printf( "\n" ); for ( s = 0; s < pCut->nLeaves; s++ ) // printf( "%d ", (int)If_ObjCutBest(If_CutLeaf(p, pCut, Abc_Lit2Var((int)pCutPerm[s])))->Delay ); printf( "%d ", (int)If_ObjCutBest(If_CutLeaf(p, pCut, s))->Delay ); printf( "\n" ); Delay = If_CutLutBalanceEvalInt( p, pCut ); Delay2 = If_CutLutBalancePinDelays( p, pCut, pPerm ); } return Delay; } */ //////////////////////////////////////////////////////////////////////// /// END OF FILE /// //////////////////////////////////////////////////////////////////////// ABC_NAMESPACE_IMPL_END
bf34e51831b231f64908f3c9105545d5c397183d
450916eee7580beb928ed8f387db4f0a8c1aa508
/src/amuse/community/simplex/src/plugins/HEALPix/src/libfftpack/fftpack.c
522afc5cc70f32464e4c1ac0aec8a52e6cbb9c0e
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
amusecode/amuse
42095545893f5a86ea79c2a52ce54d3ce8eb204f
b57c1e2fda1457d5025307be105c2aa59b19b574
refs/heads/main
2023-08-31T04:50:48.880044
2023-08-30T12:00:20
2023-08-30T12:00:20
18,516,331
158
118
Apache-2.0
2023-08-30T12:00:22
2014-04-07T12:35:07
AMPL
UTF-8
C
false
false
46,443
c
fftpack.c
/* * This file is part of libfftpack. * * libfftpack 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. * * libfftpack 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 libfftpack; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /* * libfftpack is being developed at the Max-Planck-Institut fuer Astrophysik * and financially supported by the Deutsches Zentrum fuer Luft- und Raumfahrt * (DLR). */ /* * This file was originally part of tela the Tensor Language. * Copyright (C) 1994-1995 Pekka Janhunen */ /* fftpack.c : A set of FFT routines in C. Algorithmically based on Fortran-77 FFTPACK by Paul N. Swarztrauber (Version 4, 1985). Pekka Janhunen 23.2.1995 (reformatted by joerg arndt) reformatted and slightly enhanced by Martin Reinecke (2004) */ #include <math.h> #include <stdlib.h> #include <string.h> #include "fftpack.h" static void passf2(int ido, int l1, const double *cc, double *ch, const double *wa1) { int i, k, ah, ac; double ti2, tr2; if(ido<=2) { for(k=0; k<l1; k++) { ah=k*ido; ac=2*k*ido; ch[ah]=cc[ac]+cc[ac+ido]; ch[ah+ido*l1]=cc[ac]-cc[ac+ido]; ch[ah+1]=cc[ac+1]+cc[ac+ido+1]; ch[ah+ido*l1+1]=cc[ac+1]-cc[ac+ido+1]; } } else { for(k=0; k<l1; k++) { for(i=0; i<ido-1; i+=2) { ah=i+k*ido; ac=i+2*k*ido; ch[ah]=cc[ac]+cc[ac+ido]; tr2=cc[ac]-cc[ac+ido]; ch[ah+1]=cc[ac+1]+cc[ac+1+ido]; ti2=cc[ac+1]-cc[ac+1+ido]; ch[ah+l1*ido+1]=wa1[i]*ti2-wa1[i+1]*tr2; ch[ah+l1*ido]=wa1[i]*tr2+wa1[i+1]*ti2; } } } } static void passb2(int ido, int l1, const double *cc, double *ch, const double *wa1) { int i, k, ah, ac; double ti2, tr2; if(ido<=2) { for(k=0; k<l1; k++) { ah=k*ido; ac=2*k*ido; ch[ah]=cc[ac]+cc[ac+ido]; ch[ah+ido*l1]=cc[ac]-cc[ac+ido]; ch[ah+1]=cc[ac+1]+cc[ac+ido+1]; ch[ah+ido*l1+1]=cc[ac+1]-cc[ac+ido+1]; } } else { for(k=0; k<l1; k++) { for(i=0; i<ido-1; i+=2) { ah=i+k*ido; ac=i+2*k*ido; ch[ah]=cc[ac]+cc[ac+ido]; tr2=cc[ac]-cc[ac+ido]; ch[ah+1]=cc[ac+1]+cc[ac+1+ido]; ti2=cc[ac+1]-cc[ac+1+ido]; ch[ah+l1*ido+1]=wa1[i]*ti2+wa1[i+1]*tr2; ch[ah+l1*ido]=wa1[i]*tr2-wa1[i+1]*ti2; } } } } static void passf3(int ido, int l1, const double *cc, double *ch, const double *wa1, const double *wa2) { static const double taur=-0.5, taui=0.86602540378443864676; int i, k, ac, ah; double ci2, ci3, di2, di3, cr2, cr3, dr2, dr3, ti2, tr2; if(ido==2) { for(k=1; k<=l1; k++) { ac=(3*k-2)*ido; tr2=cc[ac]+cc[ac+ido]; cr2=cc[ac-ido]+taur*tr2; ah=(k-1)*ido; ch[ah]=cc[ac-ido]+tr2; ti2=cc[ac+1]+cc[ac+ido+1]; ci2=cc[ac-ido+1]+taur*ti2; ch[ah+1]=cc[ac-ido+1]+ti2; cr3=-taui*(cc[ac]-cc[ac+ido]); ci3=-taui*(cc[ac+1]-cc[ac+ido+1]); ch[ah+l1*ido]=cr2-ci3; ch[ah+2*l1*ido]=cr2+ci3; ch[ah+l1*ido+1]=ci2+cr3; ch[ah+2*l1*ido+1]=ci2-cr3; } } else { for(k=1; k<=l1; k++) { for(i=0; i<ido-1; i+=2) { ac=i+(3*k-2)*ido; tr2=cc[ac]+cc[ac+ido]; cr2=cc[ac-ido]+taur*tr2; ah=i+(k-1)*ido; ch[ah]=cc[ac-ido]+tr2; ti2=cc[ac+1]+cc[ac+ido+1]; ci2=cc[ac-ido+1]+taur*ti2; ch[ah+1]=cc[ac-ido+1]+ti2; cr3=-taui*(cc[ac]-cc[ac+ido]); ci3=-taui*(cc[ac+1]-cc[ac+ido+1]); dr2=cr2-ci3; dr3=cr2+ci3; di2=ci2+cr3; di3=ci2-cr3; ch[ah+l1*ido+1]=wa1[i]*di2-wa1[i+1]*dr2; ch[ah+l1*ido]=wa1[i]*dr2+wa1[i+1]*di2; ch[ah+2*l1*ido+1]=wa2[i]*di3-wa2[i+1]*dr3; ch[ah+2*l1*ido]=wa2[i]*dr3+wa2[i+1]*di3; } } } } static void passb3(int ido, int l1, const double *cc, double *ch, const double *wa1, const double *wa2) { static const double taur=-0.5, taui=0.86602540378443864676; int i, k, ac, ah; double ci2, ci3, di2, di3, cr2, cr3, dr2, dr3, ti2, tr2; if(ido==2) { for(k=1; k<=l1; k++) { ac=(3*k-2)*ido; tr2=cc[ac]+cc[ac+ido]; cr2=cc[ac-ido]+taur*tr2; ah=(k-1)*ido; ch[ah]=cc[ac-ido]+tr2; ti2=cc[ac+1]+cc[ac+ido+1]; ci2=cc[ac-ido+1]+taur*ti2; ch[ah+1]=cc[ac-ido+1]+ti2; cr3=taui*(cc[ac]-cc[ac+ido]); ci3=taui*(cc[ac+1]-cc[ac+ido+1]); ch[ah+l1*ido]=cr2-ci3; ch[ah+2*l1*ido]=cr2+ci3; ch[ah+l1*ido+1]=ci2+cr3; ch[ah+2*l1*ido+1]=ci2-cr3; } } else { for(k=1; k<=l1; k++) { for(i=0; i<ido-1; i+=2) { ac=i+(3*k-2)*ido; tr2=cc[ac]+cc[ac+ido]; cr2=cc[ac-ido]+taur*tr2; ah=i+(k-1)*ido; ch[ah]=cc[ac-ido]+tr2; ti2=cc[ac+1]+cc[ac+ido+1]; ci2=cc[ac-ido+1]+taur*ti2; ch[ah+1]=cc[ac-ido+1]+ti2; cr3=taui*(cc[ac]-cc[ac+ido]); ci3=taui*(cc[ac+1]-cc[ac+ido+1]); dr2=cr2-ci3; dr3=cr2+ci3; di2=ci2+cr3; di3=ci2-cr3; ch[ah+l1*ido+1]=wa1[i]*di2+wa1[i+1]*dr2; ch[ah+l1*ido]=wa1[i]*dr2-wa1[i+1]*di2; ch[ah+2*l1*ido+1]=wa2[i]*di3+wa2[i+1]*dr3; ch[ah+2*l1*ido]=wa2[i]*dr3-wa2[i+1]*di3; } } } } static void passf4(int ido, int l1, const double *cc, double *ch, const double *wa1, const double *wa2, const double *wa3) { int i, k, ac, ah; double ci2, ci3, ci4, cr2, cr3, cr4, ti1, ti2, ti3, ti4, tr1, tr2, tr3, tr4; if(ido==2) { for(k=0; k<l1; k++) { ac=4*k*ido+1; ti1=cc[ac]-cc[ac+2*ido]; ti2=cc[ac]+cc[ac+2*ido]; tr4=cc[ac+3*ido]-cc[ac+ido]; ti3=cc[ac+ido]+cc[ac+3*ido]; tr1=cc[ac-1]-cc[ac+2*ido-1]; tr2=cc[ac-1]+cc[ac+2*ido-1]; ti4=cc[ac+ido-1]-cc[ac+3*ido-1]; tr3=cc[ac+ido-1]+cc[ac+3*ido-1]; ah=k*ido; ch[ah]=tr2+tr3; ch[ah+2*l1*ido]=tr2-tr3; ch[ah+1]=ti2+ti3; ch[ah+2*l1*ido+1]=ti2-ti3; ch[ah+l1*ido]=tr1-tr4; ch[ah+3*l1*ido]=tr1+tr4; ch[ah+l1*ido+1]=ti1-ti4; ch[ah+3*l1*ido+1]=ti1+ti4; } } else { for(k=0; k<l1; k++) { for(i=0; i<ido-1; i+=2) { ac=i+1+4*k*ido; ti1=cc[ac]-cc[ac+2*ido]; ti2=cc[ac]+cc[ac+2*ido]; ti3=cc[ac+ido]+cc[ac+3*ido]; tr4=cc[ac+3*ido]-cc[ac+ido]; tr1=cc[ac-1]-cc[ac+2*ido-1]; tr2=cc[ac-1]+cc[ac+2*ido-1]; ti4=cc[ac+ido-1]-cc[ac+3*ido-1]; tr3=cc[ac+ido-1]+cc[ac+3*ido-1]; ah=i+k*ido; ch[ah]=tr2+tr3; cr3=tr2-tr3; ch[ah+1]=ti2+ti3; ci3=ti2-ti3; cr2=tr1-tr4; cr4=tr1+tr4; ci2=ti1-ti4; ci4=ti1+ti4; ch[ah+l1*ido]=wa1[i]*cr2+wa1[i+1]*ci2; ch[ah+l1*ido+1]=wa1[i]*ci2-wa1[i+1]*cr2; ch[ah+2*l1*ido]=wa2[i]*cr3+wa2[i+1]*ci3; ch[ah+2*l1*ido+1]=wa2[i]*ci3-wa2[i+1]*cr3; ch[ah+3*l1*ido]=wa3[i]*cr4+wa3[i+1]*ci4; ch[ah+3*l1*ido+1]=wa3[i]*ci4-wa3[i+1]*cr4; } } } } static void passb4(int ido, int l1, const double *cc, double *ch, const double *wa1, const double *wa2, const double *wa3) { int i, k, ac, ah; double ci2, ci3, ci4, cr2, cr3, cr4, ti1, ti2, ti3, ti4, tr1, tr2, tr3, tr4; if(ido==2) { for(k=0; k<l1; k++) { ac=4*k*ido+1; ti1=cc[ac]-cc[ac+2*ido]; ti2=cc[ac]+cc[ac+2*ido]; tr4=cc[ac+3*ido]-cc[ac+ido]; ti3=cc[ac+ido]+cc[ac+3*ido]; tr1=cc[ac-1]-cc[ac+2*ido-1]; tr2=cc[ac-1]+cc[ac+2*ido-1]; ti4=cc[ac+ido-1]-cc[ac+3*ido-1]; tr3=cc[ac+ido-1]+cc[ac+3*ido-1]; ah=k*ido; ch[ah]=tr2+tr3; ch[ah+2*l1*ido]=tr2-tr3; ch[ah+1]=ti2+ti3; ch[ah+2*l1*ido+1]=ti2-ti3; ch[ah+l1*ido]=tr1+tr4; ch[ah+3*l1*ido]=tr1-tr4; ch[ah+l1*ido+1]=ti1+ti4; ch[ah+3*l1*ido+1]=ti1-ti4; } } else { for(k=0; k<l1; k++) { for(i=0; i<ido-1; i+=2) { ac=i+1+4*k*ido; ti1=cc[ac]-cc[ac+2*ido]; ti2=cc[ac]+cc[ac+2*ido]; ti3=cc[ac+ido]+cc[ac+3*ido]; tr4=cc[ac+3*ido]-cc[ac+ido]; tr1=cc[ac-1]-cc[ac+2*ido-1]; tr2=cc[ac-1]+cc[ac+2*ido-1]; ti4=cc[ac+ido-1]-cc[ac+3*ido-1]; tr3=cc[ac+ido-1]+cc[ac+3*ido-1]; ah=i+k*ido; ch[ah]=tr2+tr3; cr3=tr2-tr3; ch[ah+1]=ti2+ti3; ci3=ti2-ti3; cr2=tr1+tr4; cr4=tr1-tr4; ci2=ti1+ti4; ci4=ti1-ti4; ch[ah+l1*ido]=wa1[i]*cr2-wa1[i+1]*ci2; ch[ah+l1*ido+1]=wa1[i]*ci2+wa1[i+1]*cr2; ch[ah+2*l1*ido]=wa2[i]*cr3-wa2[i+1]*ci3; ch[ah+2*l1*ido+1]=wa2[i]*ci3+wa2[i+1]*cr3; ch[ah+3*l1*ido]=wa3[i]*cr4-wa3[i+1]*ci4; ch[ah+3*l1*ido+1]=wa3[i]*ci4+wa3[i+1]*cr4; } } } } static void passf5(int ido, int l1, const double *cc, double *ch, const double *wa1, const double *wa2, const double *wa3, const double *wa4) { static const double tr11= 0.3090169943749474241, ti11=0.95105651629515357212; static const double tr12=-0.8090169943749474241, ti12=0.58778525229247312917; int i, k, ac, ah; double ci2, ci3, ci4, ci5, di3, di4, di5, di2, cr2, cr3, cr5, cr4, ti2, ti3, ti4, ti5, dr3, dr4, dr5, dr2, tr2, tr3, tr4, tr5; if(ido==2) { for(k=1; k<=l1;++k) { ac=(5*k-4)*ido+1; ti5=cc[ac]-cc[ac+3*ido]; ti2=cc[ac]+cc[ac+3*ido]; ti4=cc[ac+ido]-cc[ac+2*ido]; ti3=cc[ac+ido]+cc[ac+2*ido]; tr5=cc[ac-1]-cc[ac+3*ido-1]; tr2=cc[ac-1]+cc[ac+3*ido-1]; tr4=cc[ac+ido-1]-cc[ac+2*ido-1]; tr3=cc[ac+ido-1]+cc[ac+2*ido-1]; ah=(k-1)*ido; ch[ah]=cc[ac-ido-1]+tr2+tr3; ch[ah+1]=cc[ac-ido]+ti2+ti3; cr2=cc[ac-ido-1]+tr11*tr2+tr12*tr3; ci2=cc[ac-ido]+tr11*ti2+tr12*ti3; cr3=cc[ac-ido-1]+tr12*tr2+tr11*tr3; ci3=cc[ac-ido]+tr12*ti2+tr11*ti3; cr5=-(ti11*tr5+ti12*tr4); ci5=-(ti11*ti5+ti12*ti4); cr4=-(ti12*tr5-ti11*tr4); ci4=-(ti12*ti5-ti11*ti4); ch[ah+l1*ido]=cr2-ci5; ch[ah+4*l1*ido]=cr2+ci5; ch[ah+l1*ido+1]=ci2+cr5; ch[ah+2*l1*ido+1]=ci3+cr4; ch[ah+2*l1*ido]=cr3-ci4; ch[ah+3*l1*ido]=cr3+ci4; ch[ah+3*l1*ido+1]=ci3-cr4; ch[ah+4*l1*ido+1]=ci2-cr5; } } else { for(k=1; k<=l1; k++) { for(i=0; i<ido-1; i+=2) { ac=i+1+(k*5-4)*ido; ti5=cc[ac]-cc[ac+3*ido]; ti2=cc[ac]+cc[ac+3*ido]; ti4=cc[ac+ido]-cc[ac+2*ido]; ti3=cc[ac+ido]+cc[ac+2*ido]; tr5=cc[ac-1]-cc[ac+3*ido-1]; tr2=cc[ac-1]+cc[ac+3*ido-1]; tr4=cc[ac+ido-1]-cc[ac+2*ido-1]; tr3=cc[ac+ido-1]+cc[ac+2*ido-1]; ah=i+(k-1)*ido; ch[ah]=cc[ac-ido-1]+tr2+tr3; ch[ah+1]=cc[ac-ido]+ti2+ti3; cr2=cc[ac-ido-1]+tr11*tr2+tr12*tr3; ci2=cc[ac-ido]+tr11*ti2+tr12*ti3; cr3=cc[ac-ido-1]+tr12*tr2+tr11*tr3; ci3=cc[ac-ido]+tr12*ti2+tr11*ti3; cr5=-(ti11*tr5+ti12*tr4); ci5=-(ti11*ti5+ti12*ti4); cr4=-(ti12*tr5-ti11*tr4); ci4=-(ti12*ti5-ti11*ti4); dr3=cr3-ci4; dr4=cr3+ci4; di3=ci3+cr4; di4=ci3-cr4; dr5=cr2+ci5; dr2=cr2-ci5; di5=ci2-cr5; di2=ci2+cr5; ch[ah+l1*ido]=wa1[i]*dr2+wa1[i+1]*di2; ch[ah+l1*ido+1]=wa1[i]*di2-wa1[i+1]*dr2; ch[ah+2*l1*ido]=wa2[i]*dr3+wa2[i+1]*di3; ch[ah+2*l1*ido+1]=wa2[i]*di3-wa2[i+1]*dr3; ch[ah+3*l1*ido]=wa3[i]*dr4+wa3[i+1]*di4; ch[ah+3*l1*ido+1]=wa3[i]*di4-wa3[i+1]*dr4; ch[ah+4*l1*ido]=wa4[i]*dr5+wa4[i+1]*di5; ch[ah+4*l1*ido+1]=wa4[i]*di5-wa4[i+1]*dr5; } } } } static void passb5(int ido, int l1, const double *cc, double *ch, const double *wa1, const double *wa2, const double *wa3, const double *wa4) { static const double tr11= 0.3090169943749474241, ti11=0.95105651629515357212; static const double tr12=-0.8090169943749474241, ti12=0.58778525229247312917; int i, k, ac, ah; double ci2, ci3, ci4, ci5, di3, di4, di5, di2, cr2, cr3, cr5, cr4, ti2, ti3, ti4, ti5, dr3, dr4, dr5, dr2, tr2, tr3, tr4, tr5; if(ido==2) { for(k=1; k<=l1;++k) { ac=(5*k-4)*ido+1; ti5=cc[ac]-cc[ac+3*ido]; ti2=cc[ac]+cc[ac+3*ido]; ti4=cc[ac+ido]-cc[ac+2*ido]; ti3=cc[ac+ido]+cc[ac+2*ido]; tr5=cc[ac-1]-cc[ac+3*ido-1]; tr2=cc[ac-1]+cc[ac+3*ido-1]; tr4=cc[ac+ido-1]-cc[ac+2*ido-1]; tr3=cc[ac+ido-1]+cc[ac+2*ido-1]; ah=(k-1)*ido; ch[ah]=cc[ac-ido-1]+tr2+tr3; ch[ah+1]=cc[ac-ido]+ti2+ti3; cr2=cc[ac-ido-1]+tr11*tr2+tr12*tr3; ci2=cc[ac-ido]+tr11*ti2+tr12*ti3; cr3=cc[ac-ido-1]+tr12*tr2+tr11*tr3; ci3=cc[ac-ido]+tr12*ti2+tr11*ti3; cr5=ti11*tr5+ti12*tr4; ci5=ti11*ti5+ti12*ti4; cr4=ti12*tr5-ti11*tr4; ci4=ti12*ti5-ti11*ti4; ch[ah+l1*ido]=cr2-ci5; ch[ah+4*l1*ido]=cr2+ci5; ch[ah+l1*ido+1]=ci2+cr5; ch[ah+2*l1*ido+1]=ci3+cr4; ch[ah+2*l1*ido]=cr3-ci4; ch[ah+3*l1*ido]=cr3+ci4; ch[ah+3*l1*ido+1]=ci3-cr4; ch[ah+4*l1*ido+1]=ci2-cr5; } } else { for(k=1; k<=l1; k++) { for(i=0; i<ido-1; i+=2) { ac=i+1+(k*5-4)*ido; ti5=cc[ac]-cc[ac+3*ido]; ti2=cc[ac]+cc[ac+3*ido]; ti4=cc[ac+ido]-cc[ac+2*ido]; ti3=cc[ac+ido]+cc[ac+2*ido]; tr5=cc[ac-1]-cc[ac+3*ido-1]; tr2=cc[ac-1]+cc[ac+3*ido-1]; tr4=cc[ac+ido-1]-cc[ac+2*ido-1]; tr3=cc[ac+ido-1]+cc[ac+2*ido-1]; ah=i+(k-1)*ido; ch[ah]=cc[ac-ido-1]+tr2+tr3; ch[ah+1]=cc[ac-ido]+ti2+ti3; cr2=cc[ac-ido-1]+tr11*tr2+tr12*tr3; ci2=cc[ac-ido]+tr11*ti2+tr12*ti3; cr3=cc[ac-ido-1]+tr12*tr2+tr11*tr3; ci3=cc[ac-ido]+tr12*ti2+tr11*ti3; cr5=ti11*tr5+ti12*tr4; ci5=ti11*ti5+ti12*ti4; cr4=ti12*tr5-ti11*tr4; ci4=ti12*ti5-ti11*ti4; dr3=cr3-ci4; dr4=cr3+ci4; di3=ci3+cr4; di4=ci3-cr4; dr5=cr2+ci5; dr2=cr2-ci5; di5=ci2-cr5; di2=ci2+cr5; ch[ah+l1*ido]=wa1[i]*dr2-wa1[i+1]*di2; ch[ah+l1*ido+1]=wa1[i]*di2+wa1[i+1]*dr2; ch[ah+2*l1*ido]=wa2[i]*dr3-wa2[i+1]*di3; ch[ah+2*l1*ido+1]=wa2[i]*di3+wa2[i+1]*dr3; ch[ah+3*l1*ido]=wa3[i]*dr4-wa3[i+1]*di4; ch[ah+3*l1*ido+1]=wa3[i]*di4+wa3[i+1]*dr4; ch[ah+4*l1*ido]=wa4[i]*dr5-wa4[i+1]*di5; ch[ah+4*l1*ido+1]=wa4[i]*di5+wa4[i+1]*dr5; } } } } static void passfg(int *nac, int ido, int ip, int l1, int idl1, double *cc, double *ch, const double *wa) { int idij, idlj, ipph, i, j, k, l, jc, lc, ik, idj, idl, inc, idp, idx; double wai, war; ipph=(ip+1)/ 2; idp=ip*ido; for(j=1; j<ipph; j++) { jc=ip-j; for(k=0; k<l1; k++) { for(i=0; i<ido; i++) { ch[i+(k+j*l1)*ido] = cc[i+(j+k*ip)*ido]+cc[i+(jc+k*ip)*ido]; ch[i+(k+jc*l1)*ido]= cc[i+(j+k*ip)*ido]-cc[i+(jc+k*ip)*ido]; } } } for(k=0; k<l1; k++) memcpy (ch+k*ido, cc+k*ip*ido, ido*sizeof(double)); idl=2-ido; inc=0; for(l=1; l<ipph; l++) { lc=ip-l; idl+=ido; for(ik=0; ik<idl1; ik++) { cc[ik+l*idl1]=ch[ik]+wa[idl-2]*ch[ik+idl1]; cc[ik+lc*idl1]=-wa[idl-1]*ch[ik+(ip-1)*idl1]; } idlj=idl; inc+=ido; for(j=2; j<ipph; j++) { jc=ip-j; idlj+=inc; if(idlj>idp) idlj-=idp; war=wa[idlj-2]; wai=wa[idlj-1]; for(ik=0; ik<idl1; ik++) { cc[ik+l*idl1]+=war*ch[ik+j*idl1]; cc[ik+lc*idl1]-=wai*ch[ik+jc*idl1]; } } } for(j=1; j<ipph; j++) for(ik=0; ik<idl1; ik++) ch[ik]+=ch[ik+j*idl1]; for(j=1; j<ipph; j++) { jc=ip-j; for(ik=1; ik<idl1; ik+=2) { ch[ik-1+j *idl1]=cc[ik-1+j*idl1]-cc[ik +jc*idl1]; ch[ik-1+jc*idl1]=cc[ik-1+j*idl1]+cc[ik +jc*idl1]; ch[ik +j *idl1]=cc[ik +j*idl1]+cc[ik-1+jc*idl1]; ch[ik +jc*idl1]=cc[ik +j*idl1]-cc[ik-1+jc*idl1]; } } *nac=1; if(ido==2) return; *nac=0; for(ik=0; ik<idl1; ik++) cc[ik]=ch[ik]; for(j=1; j<ip; j++) { for(k=0; k<l1; k++) { cc[(k+j*l1)*ido ]=ch[(k+j*l1)*ido ]; cc[(k+j*l1)*ido+1]=ch[(k+j*l1)*ido+1]; } } idj=2-ido; for(j=1; j<ip; j++) { idj+=ido; for(k=0; k<l1; k++) { idij=idj; for(i=3; i<ido; i+=2) { idij+=2; idx = (k+j*l1)*ido; cc[i-1+idx] = wa[idij-2]*ch[i-1+idx]+wa[idij-1]*ch[i +idx]; cc[i +idx] = wa[idij-2]*ch[i +idx]-wa[idij-1]*ch[i-1+idx]; } } } } static void passbg(int *nac, int ido, int ip, int l1, int idl1, double *cc, double *ch, const double *wa) { int idij, idlj, ipph, i, j, k, l, jc, lc, ik, idj, idl, inc, idp, idx; double wai, war; ipph=(ip+1)/ 2; idp=ip*ido; for(j=1; j<ipph; j++) { jc=ip-j; for(k=0; k<l1; k++) { for(i=0; i<ido; i++) { ch[i+(k+j*l1)*ido] = cc[i+(j+k*ip)*ido]+cc[i+(jc+k*ip)*ido]; ch[i+(k+jc*l1)*ido]= cc[i+(j+k*ip)*ido]-cc[i+(jc+k*ip)*ido]; } } } for(k=0; k<l1; k++) memcpy (ch+k*ido, cc+k*ip*ido, ido*sizeof(double)); idl=2-ido; inc=0; for(l=1; l<ipph; l++) { lc=ip-l; idl+=ido; for(ik=0; ik<idl1; ik++) { cc[ik+l*idl1]=ch[ik]+wa[idl-2]*ch[ik+idl1]; cc[ik+lc*idl1]=wa[idl-1]*ch[ik+(ip-1)*idl1]; } idlj=idl; inc+=ido; for(j=2; j<ipph; j++) { jc=ip-j; idlj+=inc; if(idlj>idp) idlj-=idp; war=wa[idlj-2]; wai=wa[idlj-1]; for(ik=0; ik<idl1; ik++) { cc[ik+l*idl1]+=war*ch[ik+j*idl1]; cc[ik+lc*idl1]+=wai*ch[ik+jc*idl1]; } } } for(j=1; j<ipph; j++) for(ik=0; ik<idl1; ik++) ch[ik]+=ch[ik+j*idl1]; for(j=1; j<ipph; j++) { jc=ip-j; for(ik=1; ik<idl1; ik+=2) { ch[ik-1+j *idl1]=cc[ik-1+j*idl1]-cc[ik +jc*idl1]; ch[ik-1+jc*idl1]=cc[ik-1+j*idl1]+cc[ik +jc*idl1]; ch[ik +j *idl1]=cc[ik +j*idl1]+cc[ik-1+jc*idl1]; ch[ik +jc*idl1]=cc[ik +j*idl1]-cc[ik-1+jc*idl1]; } } *nac=1; if(ido==2) return; *nac=0; for(ik=0; ik<idl1; ik++) cc[ik]=ch[ik]; for(j=1; j<ip; j++) { for(k=0; k<l1; k++) { cc[(k+j*l1)*ido ]=ch[(k+j*l1)*ido ]; cc[(k+j*l1)*ido+1]=ch[(k+j*l1)*ido+1]; } } idj=2-ido; for(j=1; j<ip; j++) { idj+=ido; for(k=0; k<l1; k++) { idij=idj; for(i=3; i<ido; i+=2) { idij+=2; idx = (k+j*l1)*ido; cc[i-1+idx] = wa[idij-2]*ch[i-1+idx]-wa[idij-1]*ch[i +idx]; cc[i +idx] = wa[idij-2]*ch[i +idx]+wa[idij-1]*ch[i-1+idx]; } } } } static void radf2 (int ido, int l1, const double *cc, double *ch, const double *wa1) { int i, k, ic; double ti2, tr2; for(k=0; k<l1; k++) { ch[2*k*ido] = cc[k*ido]+cc[(k+l1)*ido]; ch[(2*k+1)*ido+ido-1] = cc[k*ido]-cc[(k+l1)*ido]; } if(ido<2) return; if(ido !=2) { for(k=0; k<l1; k++) { for(i=2; i<ido; i+=2) { ic=ido-i; tr2=wa1[i-2]*cc[i-1+(k+l1)*ido]+wa1[i-1]*cc[i+(k+l1)*ido]; ti2=wa1[i-2]*cc[i+(k+l1)*ido]-wa1[i-1]*cc[i-1+(k+l1)*ido]; ch[i+2*k*ido]=cc[i+k*ido]+ti2; ch[ic+(2*k+1)*ido]=ti2-cc[i+k*ido]; ch[i-1+2*k*ido]=cc[i-1+k*ido]+tr2; ch[ic-1+(2*k+1)*ido]=cc[i-1+k*ido]-tr2; } } if(ido%2==1) return; } for(k=0; k<l1; k++) { ch[(2*k+1)*ido] = -cc[ido-1+(k+l1)*ido]; ch[ido-1+2*k*ido] = cc[ido-1+k*ido]; } } static void radb2(int ido, int l1, const double *cc, double *ch, const double *wa1) { int i, k, ic; double ti2, tr2; for(k=0; k<l1; k++) { ch[k*ido] = cc[2*k*ido]+cc[ido-1+(2*k+1)*ido]; ch[(k+l1)*ido] = cc[2*k*ido]-cc[ido-1+(2*k+1)*ido]; } if(ido<2) return; if(ido !=2) { for(k=0; k<l1;++k) { for(i=2; i<ido; i+=2) { ic=ido-i; ch[i-1+k*ido] = cc[i-1+2*k*ido]+cc[ic-1+(2*k+1)*ido]; tr2 = cc[i-1+2*k*ido]-cc[ic-1+(2*k+1)*ido]; ch[i+k*ido] = cc[i+2*k*ido]-cc[ic+(2*k+1)*ido]; ti2 = cc[i+(2*k)*ido]+cc[ic+(2*k+1)*ido]; ch[i-1+(k+l1)*ido] = wa1[i-2]*tr2-wa1[i-1]*ti2; ch[i+(k+l1)*ido] = wa1[i-2]*ti2+wa1[i-1]*tr2; } } if(ido%2==1) return; } for(k=0; k<l1; k++) { ch[ido-1+k*ido]=2*cc[ido-1+2*k*ido]; ch[ido-1+(k+l1)*ido]=-2*cc[(2*k+1)*ido]; } } static void radf3(int ido, int l1, const double *cc, double *ch, const double *wa1, const double *wa2) { static const double taur=-0.5, taui=0.86602540378443864676; int i, k, ic; double ci2, di2, di3, cr2, dr2, dr3, ti2, ti3, tr2, tr3; for(k=0; k<l1; k++) { cr2=cc[(k+l1)*ido]+cc[(k+2*l1)*ido]; ch[3*k*ido]=cc[k*ido]+cr2; ch[(3*k+2)*ido]=taui*(cc[(k+l1*2)*ido]-cc[(k+l1)*ido]); ch[ido-1+(3*k+1)*ido]=cc[k*ido]+taur*cr2; } if(ido==1) return; for(k=0; k<l1; k++) { for(i=2; i<ido; i+=2) { ic=ido-i; dr2=wa1[i-2]*cc[i-1+(k+l1)*ido]+ wa1[i-1]*cc[i+(k+l1)*ido]; di2=wa1[i-2]*cc[i+(k+l1)*ido]-wa1[i-1]*cc[i-1+(k+l1)*ido]; dr3=wa2[i-2]*cc[i-1+(k+l1*2)*ido]+wa2[i-1]*cc[i+(k+l1*2)*ido]; di3=wa2[i-2]*cc[i+(k+l1*2)*ido]-wa2[i-1]*cc[i-1+(k+l1*2)*ido]; cr2=dr2+dr3; ci2=di2+di3; ch[i-1+3*k*ido]=cc[i-1+k*ido]+cr2; ch[i+3*k*ido]=cc[i+k*ido]+ci2; tr2=cc[i-1+k*ido]+taur*cr2; ti2=cc[i+k*ido]+taur*ci2; tr3=taui*(di2-di3); ti3=taui*(dr3-dr2); ch[i-1+(3*k+2)*ido]=tr2+tr3; ch[ic-1+(3*k+1)*ido]=tr2-tr3; ch[i+(3*k+2)*ido]=ti2+ti3; ch[ic+(3*k+1)*ido]=ti3-ti2; } } } static void radb3(int ido, int l1, const double *cc, double *ch, const double *wa1, const double *wa2) { static const double taur=-0.5, taui=0.86602540378443864676; int i, k, ic; double ci2, ci3, di2, di3, cr2, cr3, dr2, dr3, ti2, tr2; for(k=0; k<l1; k++) { tr2=2*cc[ido-1+(3*k+1)*ido]; cr2=cc[3*k*ido]+taur*tr2; ch[k*ido]=cc[3*k*ido]+tr2; ci3=2*taui*cc[(3*k+2)*ido]; ch[(k+l1)*ido]=cr2-ci3; ch[(k+2*l1)*ido]=cr2+ci3; } if(ido==1) return; for(k=0; k<l1; k++) { for(i=2; i<ido; i+=2) { ic=ido-i; tr2=cc[i-1+(3*k+2)*ido]+cc[ic-1+(3*k+1)*ido]; cr2=cc[i-1+3*k*ido]+taur*tr2; ch[i-1+k*ido]=cc[i-1+3*k*ido]+tr2; ti2=cc[i+(3*k+2)*ido]-cc[ic+(3*k+1)*ido]; ci2=cc[i+3*k*ido]+taur*ti2; ch[i+k*ido]=cc[i+3*k*ido]+ti2; cr3=taui*(cc[i-1+(3*k+2)*ido]-cc[ic-1+(3*k+1)*ido]); ci3=taui*(cc[i+(3*k+2)*ido]+cc[ic+(3*k+1)*ido]); dr2=cr2-ci3; dr3=cr2+ci3; di2=ci2+cr3; di3=ci2-cr3; ch[i-1+(k+l1)*ido]=wa1[i-2]*dr2-wa1[i-1]*di2; ch[i+(k+l1)*ido]=wa1[i-2]*di2+wa1[i-1]*dr2; ch[i-1+(k+2*l1)*ido]=wa2[i-2]*dr3-wa2[i-1]*di3; ch[i+(k+2*l1)*ido]=wa2[i-2]*di3+wa2[i-1]*dr3; } } } static void radf4(int ido, int l1, const double *cc, double *ch, const double *wa1, const double *wa2, const double *wa3) { static const double hsqt2=0.70710678118654752440; int i, k, ic; double ci2, ci3, ci4, cr2, cr3, cr4, ti1, ti2, ti3, ti4, tr1, tr2, tr3, tr4; for(k=0; k<l1; k++) { tr1=cc[(k+l1)*ido]+cc[(k+3*l1)*ido]; tr2=cc[k*ido]+cc[(k+2*l1)*ido]; ch[4*k*ido]=tr1+tr2; ch[ido-1+(4*k+3)*ido]=tr2-tr1; ch[ido-1+(4*k+1)*ido]=cc[k*ido]-cc[(k+2*l1)*ido]; ch[(4*k+2)*ido]=cc[(k+3*l1)*ido]-cc[(k+l1)*ido]; } if(ido<2) return; if(ido !=2) { for(k=0; k<l1; k++) { for(i=2; i<ido; i+=2) { ic=ido-i; cr2=wa1[i-2]*cc[i-1+(k+l1)*ido]+wa1[i-1]*cc[i+(k+l1)*ido]; ci2=wa1[i-2]*cc[i+(k+l1)*ido]-wa1[i-1]*cc[i-1+(k+l1)*ido]; cr3=wa2[i-2]*cc[i-1+(k+2*l1)*ido]+wa2[i-1]*cc[i+(k+2*l1)*ido]; ci3=wa2[i-2]*cc[i+(k+2*l1)*ido]-wa2[i-1]*cc[i-1+(k+2*l1)*ido]; cr4=wa3[i-2]*cc[i-1+(k+3*l1)*ido]+wa3[i-1]*cc[i+(k+3*l1)*ido]; ci4=wa3[i-2]*cc[i+(k+3*l1)*ido]-wa3[i-1]*cc[i-1+(k+3*l1)*ido]; tr1=cr2+cr4; tr4=cr4-cr2; ti1=ci2+ci4; ti4=ci2-ci4; ti2=cc[i+k*ido]+ci3; ti3=cc[i+k*ido]-ci3; tr2=cc[i-1+k*ido]+cr3; tr3=cc[i-1+k*ido]-cr3; ch[i-1+4*k*ido]=tr1+tr2; ch[ic-1+(4*k+3)*ido]=tr2-tr1; ch[i+4*k*ido]=ti1+ti2; ch[ic+(4*k+3)*ido]=ti1-ti2; ch[i-1+(4*k+2)*ido]=ti4+tr3; ch[ic-1+(4*k+1)*ido]=tr3-ti4; ch[i+(4*k+2)*ido]=tr4+ti3; ch[ic+(4*k+1)*ido]=tr4-ti3; } } if(ido%2==1) return; } for(k=0; k<l1; k++) { ti1=-hsqt2*(cc[ido-1+(k+l1)*ido]+cc[ido-1+(k+3*l1)*ido]); tr1=hsqt2*(cc[ido-1+(k+l1)*ido]-cc[ido-1+(k+3*l1)*ido]); ch[ido-1+4*k*ido]=tr1+cc[ido-1+k*ido]; ch[ido-1+(4*k+2)*ido]=cc[ido-1+k*ido]-tr1; ch[(4*k+1)*ido]=ti1-cc[ido-1+(k+2*l1)*ido]; ch[(4*k+3)*ido]=ti1+cc[ido-1+(k+2*l1)*ido]; } } static void radb4(int ido, int l1, const double *cc, double *ch, const double *wa1, const double *wa2, const double *wa3) { static const double sqrt2=1.41421356237309504880; int i, k, ic; double ci2, ci3, ci4, cr2, cr3, cr4, ti1, ti2, ti3, ti4, tr1, tr2, tr3, tr4; for(k=0; k<l1; k++) { tr1=cc[4*k*ido]-cc[ido-1+(4*k+3)*ido]; tr2=cc[4*k*ido]+cc[ido-1+(4*k+3)*ido]; tr3=cc[ido-1+(4*k+1)*ido]+cc[ido-1+(4*k+1)*ido]; tr4=cc[(4*k+2)*ido]+cc[(4*k+2)*ido]; ch[k*ido]=tr2+tr3; ch[(k+l1)*ido]=tr1-tr4; ch[(k+2*l1)*ido]=tr2-tr3; ch[(k+3*l1)*ido]=tr1+tr4; } if(ido<2) return; if(ido !=2) { for(k=0; k<l1;++k) { for(i=2; i<ido; i+=2) { ic=ido-i; ti1=cc[i+4*k*ido]+cc[ic+(4*k+3)*ido]; ti2=cc[i+4*k*ido]-cc[ic+(4*k+3)*ido]; ti3=cc[i+(4*k+2)*ido]-cc[ic+(4*k+1)*ido]; tr4=cc[i+(4*k+2)*ido]+cc[ic+(4*k+1)*ido]; tr1=cc[i-1+4*k*ido]-cc[ic-1+(4*k+3)*ido]; tr2=cc[i-1+4*k*ido]+cc[ic-1+(4*k+3)*ido]; ti4=cc[i-1+(4*k+2)*ido]-cc[ic-1+(4*k+1)*ido]; tr3=cc[i-1+(4*k+2)*ido]+cc[ic-1+(4*k+1)*ido]; ch[i-1+k*ido]=tr2+tr3; cr3=tr2-tr3; ch[i+k*ido]=ti2+ti3; ci3=ti2-ti3; cr2=tr1-tr4; cr4=tr1+tr4; ci2=ti1+ti4; ci4=ti1-ti4; ch[i-1+(k+l1)*ido]=wa1[i-2]*cr2-wa1[i-1]*ci2; ch[i+(k+l1)*ido]=wa1[i-2]*ci2+wa1[i-1]*cr2; ch[i-1+(k+2*l1)*ido]=wa2[i-2]*cr3-wa2[i-1]*ci3; ch[i+(k+2*l1)*ido]=wa2[i-2]*ci3+wa2[i-1]*cr3; ch[i-1+(k+3*l1)*ido]=wa3[i-2]*cr4-wa3[i-1]*ci4; ch[i+(k+3*l1)*ido]=wa3[i-2]*ci4+wa3[i-1]*cr4; } } if(ido%2==1) return; } for(k=0; k<l1; k++) { ti1=cc[(4*k+1)*ido]+cc[(4*k+3)*ido]; ti2=cc[(4*k+3)*ido]-cc[(4*k+1)*ido]; tr1=cc[ido-1+4*k*ido]-cc[ido-1+(4*k+2)*ido]; tr2=cc[ido-1+4*k*ido]+cc[ido-1+(4*k+2)*ido]; ch[ido-1+k*ido]=tr2+tr2; ch[ido-1+(k+l1)*ido]=sqrt2*(tr1-ti1); ch[ido-1+(k+2*l1)*ido]=ti2+ti2; ch[ido-1+(k+3*l1)*ido]=-sqrt2*(tr1+ti1); } } static void radf5(int ido, int l1, const double *cc, double *ch, const double *wa1, const double *wa2, const double *wa3, const double *wa4) { static const double tr11=0.3090169943749474241; static const double ti11=0.95105651629515357212; static const double tr12=-0.8090169943749474241; static const double ti12=0.58778525229247312917; int i, k, ic; double ci2, di2, ci4, ci5, di3, di4, di5, ci3, cr2, cr3, dr2, dr3, dr4, dr5, cr5, cr4, ti2, ti3, ti5, ti4, tr2, tr3, tr4, tr5; for(k=0; k<l1; k++) { cr2=cc[(k+4*l1)*ido]+cc[(k+l1)*ido]; ci5=cc[(k+4*l1)*ido]-cc[(k+l1)*ido]; cr3=cc[(k+3*l1)*ido]+cc[(k+2*l1)*ido]; ci4=cc[(k+3*l1)*ido]-cc[(k+2*l1)*ido]; ch[5*k*ido]=cc[k*ido]+cr2+cr3; ch[ido-1+(5*k+1)*ido]=cc[k*ido]+tr11*cr2+tr12*cr3; ch[(5*k+2)*ido]=ti11*ci5+ti12*ci4; ch[ido-1+(5*k+3)*ido]=cc[k*ido]+tr12*cr2+tr11*cr3; ch[(5*k+4)*ido]=ti12*ci5-ti11*ci4; } if(ido==1) return; for(k=0; k<l1;++k) { for(i=2; i<ido; i+=2) { ic=ido-i; dr2=wa1[i-2]*cc[i-1+(k+l1)*ido]+wa1[i-1]*cc[i+(k+l1)*ido]; di2=wa1[i-2]*cc[i+(k+l1)*ido]-wa1[i-1]*cc[i-1+(k+l1)*ido]; dr3=wa2[i-2]*cc[i-1+(k+2*l1)*ido]+wa2[i-1]*cc[i+(k+2*l1)*ido]; di3=wa2[i-2]*cc[i+(k+2*l1)*ido]-wa2[i-1]*cc[i-1+(k+2*l1)*ido]; dr4=wa3[i-2]*cc[i-1+(k+3*l1)*ido]+wa3[i-1]*cc[i+(k+3*l1)*ido]; di4=wa3[i-2]*cc[i+(k+3*l1)*ido]-wa3[i-1]*cc[i-1+(k+3*l1)*ido]; dr5=wa4[i-2]*cc[i-1+(k+4*l1)*ido]+wa4[i-1]*cc[i+(k+4*l1)*ido]; di5=wa4[i-2]*cc[i+(k+4*l1)*ido]-wa4[i-1]*cc[i-1+(k+4*l1)*ido]; cr2=dr2+dr5; ci5=dr5-dr2; cr5=di2-di5; ci2=di2+di5; cr3=dr3+dr4; ci4=dr4-dr3; cr4=di3-di4; ci3=di3+di4; ch[i-1+5*k*ido]=cc[i-1+k*ido]+cr2+cr3; ch[i+5*k*ido]=cc[i+k*ido]+ci2+ci3; tr2=cc[i-1+k*ido]+tr11*cr2+tr12*cr3; ti2=cc[i+k*ido]+tr11*ci2+tr12*ci3; tr3=cc[i-1+k*ido]+tr12*cr2+tr11*cr3; ti3=cc[i+k*ido]+tr12*ci2+tr11*ci3; tr5=ti11*cr5+ti12*cr4; ti5=ti11*ci5+ti12*ci4; tr4=ti12*cr5-ti11*cr4; ti4=ti12*ci5-ti11*ci4; ch[i-1+(5*k+2)*ido]=tr2+tr5; ch[ic-1+(5*k+1)*ido]=tr2-tr5; ch[i+(5*k+2)*ido]=ti2+ti5; ch[ic+(5*k+1)*ido]=ti5-ti2; ch[i-1+(5*k+4)*ido]=tr3+tr4; ch[ic-1+(5*k+3)*ido]=tr3-tr4; ch[i+(5*k+4)*ido]=ti3+ti4; ch[ic+(5*k+3)*ido]=ti4-ti3; } } } static void radb5(int ido, int l1, const double *cc, double *ch, const double *wa1, const double *wa2, const double *wa3, const double *wa4) { static const double tr11=0.3090169943749474241; static const double ti11=0.95105651629515357212; static const double tr12=-0.8090169943749474241; static const double ti12=0.58778525229247312917; int i, k, ic; double ci2, ci3, ci4, ci5, di3, di4, di5, di2, cr2, cr3, cr5, cr4, ti2, ti3, ti4, ti5, dr3, dr4, dr5, dr2, tr2, tr3, tr4, tr5; for(k=0; k<l1; k++) { ti5=2*cc[(5*k+2)*ido]; ti4=2*cc[(5*k+4)*ido]; tr2=2*cc[ido-1+(5*k+1)*ido]; tr3=2*cc[ido-1+(5*k+3)*ido]; ch[k*ido]=cc[5*k*ido]+tr2+tr3; cr2=cc[5*k*ido]+tr11*tr2+tr12*tr3; cr3=cc[5*k*ido]+tr12*tr2+tr11*tr3; ci5=ti11*ti5+ti12*ti4; ci4=ti12*ti5-ti11*ti4; ch[(k+l1)*ido]=cr2-ci5; ch[(k+2*l1)*ido]=cr3-ci4; ch[(k+3*l1)*ido]=cr3+ci4; ch[(k+4*l1)*ido]=cr2+ci5; } if(ido==1) return; for(k=0; k<l1;++k) { for(i=2; i<ido; i+=2) { ic=ido-i; ti5=cc[i+(5*k+2)*ido]+cc[ic+(5*k+1)*ido]; ti2=cc[i+(5*k+2)*ido]-cc[ic+(5*k+1)*ido]; ti4=cc[i+(5*k+4)*ido]+cc[ic+(5*k+3)*ido]; ti3=cc[i+(5*k+4)*ido]-cc[ic+(5*k+3)*ido]; tr5=cc[i-1+(5*k+2)*ido]-cc[ic-1+(5*k+1)*ido]; tr2=cc[i-1+(5*k+2)*ido]+cc[ic-1+(5*k+1)*ido]; tr4=cc[i-1+(5*k+4)*ido]-cc[ic-1+(5*k+3)*ido]; tr3=cc[i-1+(5*k+4)*ido]+cc[ic-1+(5*k+3)*ido]; ch[i-1+k*ido]=cc[i-1+5*k*ido]+tr2+tr3; ch[i+k*ido]=cc[i+5*k*ido]+ti2+ti3; cr2=cc[i-1+5*k*ido]+tr11*tr2+tr12*tr3; ci2=cc[i+5*k*ido]+tr11*ti2+tr12*ti3; cr3=cc[i-1+5*k*ido]+tr12*tr2+tr11*tr3; ci3=cc[i+5*k*ido]+tr12*ti2+tr11*ti3; cr5=ti11*tr5+ti12*tr4; ci5=ti11*ti5+ti12*ti4; cr4=ti12*tr5-ti11*tr4; ci4=ti12*ti5-ti11*ti4; dr3=cr3-ci4; dr4=cr3+ci4; di3=ci3+cr4; di4=ci3-cr4; dr5=cr2+ci5; dr2=cr2-ci5; di5=ci2-cr5; di2=ci2+cr5; ch[i-1+(k+l1)*ido]=wa1[i-2]*dr2-wa1[i-1]*di2; ch[i+(k+l1)*ido]=wa1[i-2]*di2+wa1[i-1]*dr2; ch[i-1+(k+2*l1)*ido]=wa2[i-2]*dr3-wa2[i-1]*di3; ch[i+(k+2*l1)*ido]=wa2[i-2]*di3+wa2[i-1]*dr3; ch[i-1+(k+3*l1)*ido]=wa3[i-2]*dr4-wa3[i-1]*di4; ch[i+(k+3*l1)*ido]=wa3[i-2]*di4+wa3[i-1]*dr4; ch[i-1+(k+4*l1)*ido]=wa4[i-2]*dr5-wa4[i-1]*di5; ch[i+(k+4*l1)*ido]=wa4[i-2]*di5+wa4[i-1]*dr5; } } } static void radfg(int ido, int ip, int l1, int idl1, double *cc, double *ch, const double *wa) { static const double twopi=6.28318530717958647692; int idij, ipph, i, j, k, l, j2, ic, jc, lc, ik, is; double ai1, ai2, ar1, ar2, arg; double *csarr; int aidx; ipph=(ip+1)/ 2; if(ido !=1) { for(ik=0; ik<idl1; ik++) ch[ik]=cc[ik]; for(j=1; j<ip; j++) for(k=0; k<l1; k++) ch[(k+j*l1)*ido]=cc[(k+j*l1)*ido]; is=-ido; for(j=1; j<ip; j++) { is+=ido; for(k=0; k<l1; k++) { idij=is-1; for(i=2; i<ido; i+=2) { idij+=2; ch[i-1+(k+j*l1)*ido]= wa[idij-1]*cc[i-1+(k+j*l1)*ido]+wa[idij]*cc[i+(k+j*l1)*ido]; ch[i+(k+j*l1)*ido]= wa[idij-1]*cc[i+(k+j*l1)*ido]-wa[idij]*cc[i-1+(k+j*l1)*ido]; } } } for(j=1; j<ipph; j++) { jc=ip-j; for(k=0; k<l1; k++) { for(i=2; i<ido; i+=2) { cc[i-1+(k+j*l1)*ido]=ch[i-1+(k+j*l1)*ido]+ch[i-1+(k+jc*l1)*ido]; cc[i-1+(k+jc*l1)*ido]=ch[i+(k+j*l1)*ido]-ch[i+(k+jc*l1)*ido]; cc[i+(k+j*l1)*ido]=ch[i+(k+j*l1)*ido]+ch[i+(k+jc*l1)*ido]; cc[i+(k+jc*l1)*ido]=ch[i-1+(k+jc*l1)*ido]-ch[i-1+(k+j*l1)*ido]; } } } } else { /*now ido==1*/ for(ik=0; ik<idl1; ik++) cc[ik]=ch[ik]; } for(j=1; j<ipph; j++) { jc=ip-j; for(k=0; k<l1; k++) { cc[(k+j*l1)*ido]=ch[(k+j*l1)*ido]+ch[(k+jc*l1)*ido]; cc[(k+jc*l1)*ido]=ch[(k+jc*l1)*ido]-ch[(k+j*l1)*ido]; } } csarr=(double *)malloc(2*ip*sizeof(double)); arg=twopi / ip; csarr[0]=1.; csarr[1]=0.; csarr[2]=csarr[2*ip-2]=cos(arg); csarr[3]=sin(arg); csarr[2*ip-1]=-csarr[3]; for (i=2; i<=ip/2; ++i) { csarr[2*i]=csarr[2*ip-2*i]=cos(i*arg); csarr[2*i+1]=sin(i*arg); csarr[2*ip-2*i+1]=-csarr[2*i+1]; } for(l=1; l<ipph; l++) { lc=ip-l; ar1=csarr[2*l]; ai1=csarr[2*l+1]; for(ik=0; ik<idl1; ik++) { ch[ik+l*idl1]=cc[ik]+ar1*cc[ik+idl1]; ch[ik+lc*idl1]=ai1*cc[ik+(ip-1)*idl1]; } aidx=2*l; for(j=2; j<ipph; j++) { jc=ip-j; aidx+=2*l; if (aidx>=2*ip) aidx-=2*ip; ar2=csarr[aidx]; ai2=csarr[aidx+1]; for(ik=0; ik<idl1; ik++) { ch[ik+l*idl1]+=ar2*cc[ik+j*idl1]; ch[ik+lc*idl1]+=ai2*cc[ik+jc*idl1]; } } } free(csarr); for(j=1; j<ipph; j++) for(ik=0; ik<idl1; ik++) ch[ik]+=cc[ik+j*idl1]; for(k=0; k<l1; k++) for(i=0; i<ido; i++) cc[i+k*ip*ido]=ch[i+k*ido]; for(j=1; j<ipph; j++) { jc=ip-j; j2=2*j; for(k=0; k<l1; k++) { cc[ido-1+(j2-1+k*ip)*ido] = ch[(k+j*l1)*ido]; cc[(j2+k*ip)*ido] = ch[(k+jc*l1)*ido]; } } if(ido==1) return; for(j=1; j<ipph; j++) { jc=ip-j; j2=2*j; for(k=0; k<l1; k++) { for(i=2; i<ido; i+=2) { ic=ido-i; cc[i-1+(j2+k*ip)*ido]=ch[i-1+(k+j*l1)*ido]+ch[i-1+(k+jc*l1)*ido]; cc[ic-1+(j2-1+k*ip)*ido]=ch[i-1+(k+j*l1)*ido]-ch[i-1+(k+jc*l1)*ido]; cc[i+(j2+k*ip)*ido]=ch[i+(k+j*l1)*ido]+ch[i+(k+jc*l1)*ido]; cc[ic+(j2-1+k*ip)*ido]=ch[i+(k+jc*l1)*ido]-ch[i+(k+j*l1)*ido]; } } } } static void radbg(int ido, int ip, int l1, int idl1, double *cc, double *ch, const double *wa) { static const double twopi=6.28318530717958647692; int idij, ipph, i, j, k, l, j2, ic, jc, lc, ik, is; double ai1, ai2, ar1, ar2, arg; double *csarr; int aidx; ipph=(ip+1)/ 2; for(k=0; k<l1; k++) for(i=0; i<ido; i++) ch[i+k*ido]=cc[i+k*ip*ido]; for(j=1; j<ipph; j++) { jc=ip-j; j2=2*j; for(k=0; k<l1; k++) { ch[(k+j*l1)*ido]=cc[ido-1+(j2-1+k*ip)*ido]+cc[ido-1+(j2-1+k*ip)*ido]; ch[(k+jc*l1)*ido]=cc[(j2+k*ip)*ido]+cc[(j2+k*ip)*ido]; } } if(ido !=1) { for(j=1; j<ipph; j++) { jc=ip-j; for(k=0; k<l1; k++) { for(i=2; i<ido; i+=2) { ic=ido-i; ch[i-1+(k+j*l1)*ido] = cc[i-1+(2*j+k*ip)*ido]+cc[ic-1+(2*j-1+k*ip)*ido]; ch[i-1+(k+jc*l1)*ido] = cc[i-1+(2*j+k*ip)*ido]-cc[ic-1+(2*j-1+k*ip)*ido]; ch[i+(k+j*l1)*ido]=cc[i+(2*j+k*ip)*ido]-cc[ic+(2*j-1+k*ip)*ido]; ch[i+(k+jc*l1)*ido]=cc[i+(2*j+k*ip)*ido]+cc[ic+(2*j-1+k*ip)*ido]; } } } } csarr=(double *)malloc(2*ip*sizeof(double)); arg=twopi / ip; csarr[0]=1.; csarr[1]=0.; csarr[2]=csarr[2*ip-2]=cos(arg); csarr[3]=sin(arg); csarr[2*ip-1]=-csarr[3]; for (i=2; i<=ip/2; ++i) { csarr[2*i]=csarr[2*ip-2*i]=cos(i*arg); csarr[2*i+1]=sin(i*arg); csarr[2*ip-2*i+1]=-csarr[2*i+1]; } for(l=1; l<ipph; l++) { lc=ip-l; ar1=csarr[2*l]; ai1=csarr[2*l+1]; for(ik=0; ik<idl1; ik++) { cc[ik+l*idl1]=ch[ik]+ar1*ch[ik+idl1]; cc[ik+lc*idl1]=ai1*ch[ik+(ip-1)*idl1]; } aidx=2*l; for(j=2; j<ipph; j++) { jc=ip-j; aidx+=2*l; if (aidx>=2*ip) aidx-=2*ip; ar2=csarr[aidx]; ai2=csarr[aidx+1]; for(ik=0; ik<idl1; ik++) { cc[ik+l*idl1]+=ar2*ch[ik+j*idl1]; cc[ik+lc*idl1]+=ai2*ch[ik+jc*idl1]; } } } free(csarr); for(j=1; j<ipph; j++) for(ik=0; ik<idl1; ik++) ch[ik]+=ch[ik+j*idl1]; for(j=1; j<ipph; j++) { jc=ip-j; for(k=0; k<l1; k++) { ch[(k+j*l1)*ido]=cc[(k+j*l1)*ido]-cc[(k+jc*l1)*ido]; ch[(k+jc*l1)*ido]=cc[(k+j*l1)*ido]+cc[(k+jc*l1)*ido]; } } if(ido==1) return; for(j=1; j<ipph; j++) { jc=ip-j; for(k=0; k<l1; k++) { for(i=2; i<ido; i+=2) { ch[i-1+(k+j*l1)*ido]=cc[i-1+(k+j*l1)*ido]-cc[i+(k+jc*l1)*ido]; ch[i-1+(k+jc*l1)*ido]=cc[i-1+(k+j*l1)*ido]+cc[i+(k+jc*l1)*ido]; ch[i+(k+j*l1)*ido]=cc[i+(k+j*l1)*ido]+cc[i-1+(k+jc*l1)*ido]; ch[i+(k+jc*l1)*ido]=cc[i+(k+j*l1)*ido]-cc[i-1+(k+jc*l1)*ido]; } } } for(ik=0; ik<idl1; ik++) cc[ik]=ch[ik]; for(j=1; j<ip; j++) for(k=0; k<l1; k++) cc[(k+j*l1)*ido]=ch[(k+j*l1)*ido]; is=-ido; for(j=1; j<ip; j++) { is+=ido; for(k=0; k<l1; k++) { idij=is-1; for(i=2; i<ido; i+=2) { idij+=2; cc[i-1+(k+j*l1)*ido]= wa[idij-1]*ch[i-1+(k+j*l1)*ido]-wa[idij]*ch[i+(k+j*l1)*ido]; cc[i+(k+j*l1)*ido]= wa[idij-1]*ch[i+(k+j*l1)*ido]+wa[idij]*ch[i-1+(k+j*l1)*ido]; } } } } /*---------------------------------------------------------------------- cfftf1, cfftb1, cfftf, cfftb, cffti1, cffti. Complex FFTs. ----------------------------------------------------------------------*/ static void cfftf1(int n, double c[], double ch[], const double wa[], const int ifac[]) { int idot, k1, l1, l2, na, nf, ip, iw, nac, ido, idl1; double *p1, *p2; nf=ifac[1]; na=0; l1=1; iw=0; for(k1=2; k1<=nf+1; k1++) { ip=ifac[k1]; l2=ip*l1; ido=n / l2; idot=ido+ido; idl1=idot*l1; p1 = (na==0) ? c : ch; p2 = (na==0) ? ch : c; if(ip==4) passf4(idot, l1, p1, p2, wa+iw, wa+iw+idot, wa+iw+2*idot); else if(ip==2) passf2(idot, l1, p1, p2, wa+iw); else if(ip==3) passf3(idot, l1, p1, p2, wa+iw, wa+iw+idot); else if(ip==5) passf5(idot, l1, p1, p2, wa+iw, wa+iw+idot, wa+iw+2*idot, wa+iw+3*idot); else { passfg(&nac, idot, ip, l1, idl1, p1, p2, &wa[iw]); if(nac==0) na=1-na; } na=1-na; l1=l2; iw+=(ip-1)*idot; } if(na!=0) memcpy (c,ch,2*n*sizeof(double)); } static void cfftb1(int n, double c[], double ch[], const double wa[], const int ifac[]) { int idot, k1, l1, l2, na, nf, ip, iw, nac, ido, idl1; double *p1, *p2; nf=ifac[1]; na=0; l1=1; iw=0; for(k1=2; k1<=nf+1; k1++) { ip=ifac[k1]; l2=ip*l1; ido=n / l2; idot=ido+ido; idl1=idot*l1; p1 = (na==0) ? c : ch; p2 = (na==0) ? ch : c; if(ip==4) passb4(idot, l1, p1, p2, wa+iw, wa+iw+idot, wa+iw+2*idot); else if(ip==2) passb2(idot, l1, p1, p2, wa+iw); else if(ip==3) passb3(idot, l1, p1, p2, wa+iw, wa+iw+idot); else if(ip==5) passb5(idot, l1, p1, p2, wa+iw, wa+iw+idot, wa+iw+2*idot, wa+iw+3*idot); else { passbg(&nac, idot, ip, l1, idl1, p1, p2, &wa[iw]); if(nac==0) na=1-na; } na=1-na; l1=l2; iw+=(ip-1)*idot; } if(na!=0) memcpy (c,ch,2*n*sizeof(double)); } void cfftf(int n, double c[], double wsave[]) { if(n!=1) cfftf1(n, c, wsave, wsave+2*n,(int*)(wsave+4*n)); } void cfftb(int n, double c[], double wsave[]) { if(n!=1) cfftb1(n, c, wsave, wsave+2*n,(int*)(wsave+4*n)); } static void cffti1(int n, double wa[], int ifac[]) { static const int ntryh[4]= {3, 4, 2, 5}; static const double twopi=6.28318530717958647692; double argh, argld, arg, fi; int idot, ntry=0, i, j, i1, k1, l1, l2, ib; int ld, ii, nf, ip, nl, nq, nr, ido, ipm; nl=n; nf=0; j=0; startloop: j++; if(j<=4) ntry=ntryh[j-1]; else ntry+=2; do { nq=nl / ntry; nr=nl-ntry*nq; if(nr !=0) goto startloop; nf++; ifac[nf+1]=ntry; nl=nq; if(ntry==2 && nf !=1) { for(i=2; i<=nf; i++) { ib=nf-i+2; ifac[ib+1]=ifac[ib]; } ifac[2]=2; } } while(nl !=1); ifac[0]=n; ifac[1]=nf; argh=twopi /(double)n; i=1; l1=1; for(k1=1; k1<=nf; k1++) { ip=ifac[k1+1]; ld=0; l2=l1*ip; ido=n / l2; idot=ido+ido+2; ipm=ip-1; for(j=1; j<=ipm; j++) { i1=i; wa[i-1]=1; wa[i]=0; ld+=l1; fi=0; argld=ld*argh; for(ii=4; ii<=idot; ii+=2) { i+=2; fi+=1; arg=fi*argld; wa[i-1]=cos(arg); wa[i]=sin(arg); } if(ip>5) { wa[i1-1]=wa[i-1]; wa[i1]=wa[i]; } } l1=l2; } } void cffti(int n, double wsave[]) { if (n!=1) cffti1(n, wsave+2*n,(int*)(wsave+4*n)); } /*---------------------------------------------------------------------- rfftf1, rfftb1, rfftf, rfftb, rffti1, rffti. Real FFTs. ----------------------------------------------------------------------*/ static void rfftf1(int n, double c[], double ch[], const double wa[], const int ifac[]) { int i, k1, l1, l2, na, kh, nf, ip, iw, ido, idl1; double *p1, *p2; nf=ifac[1]; na=1; l2=n; iw=n-1; for(k1=1; k1<=nf;++k1) { kh=nf-k1; ip=ifac[kh+2]; l1=l2 / ip; ido=n / l2; idl1=ido*l1; iw-=(ip-1)*ido; na=1-na; p1 = (na==0) ? c : ch; p2 = (na==0) ? ch : c; if(ip==4) radf4(ido, l1, p1, p2, wa+iw, wa+iw+ido, wa+iw+2*ido); else if(ip==2) radf2(ido, l1, p1, p2, wa+iw); else if(ip==3) radf3(ido, l1, p1, p2, wa+iw, wa+iw+ido); else if(ip==5) radf5(ido, l1, p1, p2, wa+iw, wa+iw+ido, wa+iw+2*ido, wa+iw+3*ido); else { if(ido==1) na=1-na; if(na==0) radfg(ido, ip, l1, idl1, c, ch, wa+iw); else radfg(ido, ip, l1, idl1, ch, c, wa+iw); na=1-na; } l2=l1; } if(na==1) return; for(i=0; i<n; i++) c[i]=ch[i]; } static void rfftb1(int n, double c[], double ch[], const double wa[], const int ifac[]) { int k1, l1, l2, na, nf, ip, iw, ido, idl1; double *p1, *p2; nf=ifac[1]; na=0; l1=1; iw=0; for(k1=1; k1<=nf; k1++) { ip=ifac[k1+1]; l2=ip*l1; ido=n / l2; idl1=ido*l1; p1 = (na==0) ? c : ch; p2 = (na==0) ? ch : c; if(ip==4) radb4(ido, l1, p1, p2, wa+iw, wa+iw+ido, wa+iw+2*ido); else if(ip==2) radb2(ido, l1, p1, p2, wa+iw); else if(ip==3) radb3(ido, l1, p1, p2, wa+iw, wa+iw+ido); else if(ip==5) radb5(ido, l1, p1, p2, wa+iw, wa+iw+ido, wa+iw+2*ido, wa+iw+3*ido); else { radbg(ido, ip, l1, idl1, p1, p2, wa+iw); if(ido!=1) na=1-na; } na=1-na; l1=l2; iw+=(ip-1)*ido; } if(na!=0) memcpy (c,ch,n*sizeof(double)); } void rfftf(int n, double r[], double wsave[]) { if(n!=1) rfftf1(n, r, wsave, wsave+n,(int*)(wsave+2*n)); } void rfftb(int n, double r[], double wsave[]) { if(n!=1) rfftb1(n, r, wsave, wsave+n,(int*)(wsave+2*n)); } static void rffti1(int n, double wa[], int ifac[]) { static const int ntryh[4]={4, 2, 3, 5}; static const double twopi=6.28318530717958647692; double argh, argld, arg, fi; int ntry=0, i, j, k1, l1, l2, ib, ld, ii, nf, ip, nl, is, nq, nr; int ido, ipm, nfm1; nl=n; nf=0; j=0; startloop: ++j; if(j<=4) ntry=ntryh[j-1]; else ntry+=2; do { nq=nl / ntry; nr=nl-ntry*nq; if(nr !=0) goto startloop; ++nf; ifac[nf+1]=ntry; nl=nq; if(ntry==2 && nf !=1) { for(i=2; i<=nf; i++) { ib=nf-i+2; ifac[ib+1]=ifac[ib]; } ifac[2]=2; } } while(nl !=1); ifac[0]=n; ifac[1]=nf; argh=twopi /(double)(n); is=0; nfm1=nf-1; l1=1; if(nfm1==0) return; for(k1=1; k1<=nfm1; k1++) { ip=ifac[k1+1]; ld=0; l2=l1*ip; ido=n / l2; ipm=ip-1; for(j=1; j<=ipm;++j) { ld+=l1; i=is; argld=(double)ld*argh; fi=0; for(ii=3; ii<=ido; ii+=2) { i+=2; fi+=1; arg=fi*argld; wa[i-2]=cos(arg); wa[i-1]=sin(arg); } is+=ido; } l1=l2; } } void rffti(int n, double wsave[]) { if (n!=1) rffti1(n, wsave+n,(int*)(wsave+2*n)); }
44726a597542bdc1d5968c9babcf351fbd08265e
7f6c235b0598353549959c18f69eefd20b766907
/libsrc/target/aquarius/fcntl/read.c
5d73f081cd320914378648fab39982170018b1d1
[ "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
1,074
c
read.c
#include <fcntl.h> ssize_t read(int fd,void * ptr,size_t len) __smallc __naked { #asm INCLUDE "fcntl.def" ld hl,6 add hl,sp ld a,ESPCMD_READ call __esp_send_cmd ld a,(hl) ;fd call __esp_send_byte dec hl ;sp+5 dec hl ;sp+4 dec hl ;sp+3 dec hl ;sp+2 ld a,(hl) ;length call __esp_send_byte inc hl ;sp+3 ld a,(hl) call __esp_send_byte ; Read result call __esp_read_byte and a jr z,not_failed ld hl,-1 ret not_failed: ; Read offered length call __esp_read_byte ld c,a call __esp_read_byte ld b,a push bc inc hl ;sp+4 ld a,(hl) ;ptr inc hl ld h,(hl) ld l,a ; And fill buffer for offered length loop: call __esp_read_byte ld (hl),a inc hl dec bc ld a,b or c jr nz,loop pop hl ;amount read ret #endasm }
2cbb8d3185ea6366f815230c8a46dac88da787ac
bdf358386d2669d01be07865051646135f6d4c64
/tst/test_queue.c
abda783c16729387a896f0f8303421516a07091c
[ "MIT" ]
permissive
bkthomps/Containers
591bbcc075b9484b4c9aa59ab0ecd879851edb00
5f222507b077b8e223cc56d0c57a6ef4ea29b5f5
refs/heads/master
2022-06-23T08:50:40.631232
2022-06-12T18:43:04
2022-06-12T18:43:04
106,978,489
201
23
MIT
2022-06-12T18:43:05
2017-10-15T02:43:17
C
UTF-8
C
false
false
4,262
c
test_queue.c
#include "test.h" #include "../src/include/queue.h" static void test_invalid_init(void) { assert(!queue_init(0)); } static void test_linear_operations(queue me) { int val[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int stuff; int get; int i; assert(queue_size(me) == 0); assert(queue_is_empty(me)); for (i = 0; i < 10; i++) { queue_push(me, &val[i]); get = 0; assert(queue_back(&get, me)); assert(get == val[i]); stuff = 0; assert(queue_front(&stuff, me)); assert(stuff == 1); } assert(queue_size(me) == 10); assert(!queue_is_empty(me)); } static void test_array_copy(queue me) { int get_arr[10] = {0}; int get; int i; queue_copy_to_array(get_arr, me); for (i = 0; i < 10; i++) { assert(get_arr[i] == i + 1); } for (i = 0; i < 9; i++) { get = 0; assert(queue_pop(&get, me)); assert(get == i + 1); } } static void test_array_trim(queue me) { int get; queue_trim(me); assert(queue_size(me) == 1); queue_clear(me); assert(queue_size(me) == 0); get = 0; assert(!queue_pop(&get, me)); assert(!queue_front(&get, me)); assert(!queue_back(&get, me)); } static void test_basic(void) { queue me = queue_init(sizeof(int)); assert(me); test_linear_operations(me); test_array_copy(me); test_array_trim(me); assert(!queue_destroy(me)); } static void test_large_alloc(void) { int old_size; int pop_count; int get; int i; queue me = queue_init(sizeof(int)); assert(me); for (i = 123; i < 123456; i++) { queue_push(me, &i); } old_size = queue_size(me); pop_count = 0; while (!queue_is_empty(me)) { queue_pop(&get, me); pop_count++; } assert(pop_count == old_size); assert(!queue_destroy(me)); } static void test_automated_trim(void) { queue me = queue_init(sizeof(int)); int get; int i; for (i = 0; i < 100; i++) { queue_push(me, &i); queue_pop(&get, me); } assert(!queue_destroy(me)); } struct pair { int cur_node; int cur_cost; }; static int test_puzzle(int start_node, int dest_node) { queue q = queue_init(sizeof(struct pair)); struct pair cur; cur.cur_node = start_node; cur.cur_cost = 0; assert(queue_is_empty(q)); queue_push(q, &cur); assert(queue_size(q) == 1); while (!queue_is_empty(q)) { int node; int cost; queue_pop(&cur, q); node = cur.cur_node; cost = cur.cur_cost; if (node > 2 * dest_node || node < 1) { continue; } if (node == dest_node) { queue_destroy(q); return cost; } cur.cur_cost = cost + 1; cur.cur_node = node - 1; queue_push(q, &cur); assert(cur.cur_cost == cost + 1); assert(cur.cur_node == node - 1); cur.cur_node = 2 * node; queue_push(q, &cur); assert(cur.cur_cost == cost + 1); assert(cur.cur_node == 2 * node); } queue_destroy(q); return -1; } struct big_object { int n; double d; signed char c[8]; }; static void test_big_object(void) { int i; queue me = queue_init(sizeof(struct big_object)); assert(me); for (i = 0; i < 16; i++) { int j; struct big_object b; b.n = INT_MIN + i; b.d = i + 0.5; for (j = 0; j < 8; j++) { b.c[j] = (signed char) (SCHAR_MIN + i + j); } assert(queue_push(me, &b) == 0); b.n = -1; b.d = -1; for (j = 0; j < 8; j++) { b.c[j] = -1; } } for (i = 0; i < 16; i++) { int j; struct big_object b; assert(queue_pop(&b, me) == 1); assert(b.n == INT_MIN + i); assert(b.d == i + 0.5); for (j = 0; j < 8; j++) { assert(b.c[j] == SCHAR_MIN + i + j); } } assert(!queue_destroy(me)); } void test_queue(void) { test_invalid_init(); test_basic(); test_large_alloc(); test_automated_trim(); assert(test_puzzle(2, 5) == 4); assert(test_puzzle(2, 10) == 5); test_big_object(); queue_destroy(NULL); }
935821ee7769d59b5846783ee7de2febdfdb2110
4d0300263d28fb461f285cc2c3dfd7c51621cb4d
/external/ALmixer/Isolated/SoundDecoder.h
e7d5711945a36aa33d34e7556866158e6ff6b74c
[ "MIT", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-free-unknown", "LGPL-2.0-or-later", "LGPL-2.1-only" ]
permissive
coronalabs/corona
6a108e8bfc8026e8c85e6768cdd8590b5a83bdc2
5e853b590f6857f43f4d1eb98ee2b842f67eef0d
refs/heads/master
2023-08-30T14:29:19.542726
2023-08-22T15:18:29
2023-08-22T15:18:29
163,527,358
2,487
326
MIT
2023-09-02T16:46:40
2018-12-29T17:05:15
C++
UTF-8
C
false
false
6,840
h
SoundDecoder.h
/* * This is a wrapper interface that tries to provide a similar * front-end interface to SDL_sound. */ #ifndef SOUNDDECODER_H #define SOUNDDECODER_H #ifdef __cplusplus extern "C" { #endif #if defined(_WIN32) || defined(WINAPI_FAMILY) #if defined(SOUND_DECODER_BUILD_LIBRARY) #define SOUND_DECODER_DECLSPEC __declspec(dllexport) #else #define SOUND_DECODER_DECLSPEC #endif #else #if defined(SOUND_DECODER_BUILD_LIBRARY) #if defined (__GNUC__) && __GNUC__ >= 4 #define SOUND_DECODER_DECLSPEC __attribute__((visibility("default"))) #else #define SOUND_DECODER_DECLSPEC #endif #else #define SOUND_DECODER_DECLSPEC #endif #endif /* * For some reason, the __cdecl triggers a compiler error for Windows Phone with the SoundDecoder_DecoderInfo struct below. * I don't know why. This is to be investigated later. */ // #if defined(_WIN32) || defined(WINAPI_FAMILY) // #define SOUND_DECODER_CALL __cdecl // #else #define SOUND_DECODER_CALL // #endif #include <stdint.h> #include <stddef.h> #include "al.h" /* OpenAL */ /* Compatibility defines for SDL */ #define AUDIO_U8 0x0008 #define AUDIO_S8 0x8008 #define AUDIO_U16LSB 0x0010 #define AUDIO_S16LSB 0x8010 #define AUDIO_U16MSB 0x1010 #define AUDIO_S16MSB 0x9010 #define AUDIO_U16 AUDIO_U16LSB #define AUDIO_S16 AUDIO_S16LSB /* Apple defines __BIG_ENDIAN__ and __LITTLE_ENDIAN__ appropriately. * Linux provides <endian.h> */ #if !defined(__BIG_ENDIAN__) && !defined(__LITTLE_ENDIAN__) #ifdef __linux__ #include <endian.h> #if _BYTE_ORDER == _BIG_ENDIAN #define __BIG_ENDIAN__ 1 #else #define __LITTLE_ENDIAN__ 1 #endif #else /* __linux __ */ #if defined(__hppa__) || \ defined(__m68k__) || defined(mc68000) || defined(_M_M68K) || \ (defined(__MIPS__) && defined(__MISPEB__)) || \ defined(__ppc__) || defined(__POWERPC__) || defined(_M_PPC) || \ defined(__sparc__) #define __BIG_ENDIAN__ 1 #else #define __LITTLE_ENDIAN__ 1 #endif #endif /* __linux __ */ #endif /* */ #if __BIG_ENDIAN__ /* #warning "Using __BIG_ENDIAN__" */ #define AUDIO_U16SYS AUDIO_U16MSB #define AUDIO_S16SYS AUDIO_S16MSB #elif __LITTLE_ENDIAN__ #define AUDIO_U16SYS AUDIO_U16LSB #define AUDIO_S16SYS AUDIO_S16LSB #else #warning "Using __LITTLE_ENDIAN__ as fallback" #define AUDIO_U16SYS AUDIO_U16LSB #define AUDIO_S16SYS AUDIO_S16LSB #endif struct ALmixer_RWops; typedef enum { SOUND_SAMPLEFLAG_NONE = 0, SOUND_SAMPLEFLAG_CANSEEK = 1, SOUND_SAMPLEFLAG_EOF = 1 << 29, SOUND_SAMPLEFLAG_ERROR = 1 << 30, SOUND_SAMPLEFLAG_EAGAIN = 1 << 31 } SoundDecoder_SampleFlags; #define Sound_SampleFlags SoundDecoder_SampleFlags; typedef struct SoundDecoder_AudioInfo { //uint16_t format; /**< Equivalent of SDL_AudioSpec.format. */ ALushort format; /**< Equivalent of SDL_AudioSpec.format. */ ALubyte channels; // uint8_t channels; //uint32_t rate; ALuint rate; } SoundDecoder_AudioInfo; //#define Sound_AudioInfo SoundDecoder_AudioInfo; typedef struct SoundDecoder_AudioInfo Sound_AudioInfo; typedef struct SoundDecoder_DecoderInfo { const char** extensions; const char* description; const char* author; const char* url; } SoundDecoder_DecoderInfo; //#define Sound_DecoderInfo SoundDecoder_DecoderInfo; typedef struct SoundDecoder_DecoderInfo Sound_DecoderInfo; typedef struct SoundDecoder_Sample { void* opaque; const SoundDecoder_DecoderInfo* decoder; SoundDecoder_AudioInfo desired; SoundDecoder_AudioInfo actual; void *buffer; size_t buffer_size; SoundDecoder_SampleFlags flags; } SoundDecoder_Sample; //#define Sound_Sample SoundDecoder_Sample; typedef struct SoundDecoder_Sample Sound_Sample; typedef struct SoundDecoder_Version { int major; int minor; int patch; } SoundDecoder_Version; //#define Sound_Version SoundDecoder_Version; typedef struct SoundDecoder_Version Sound_Version; #define SOUNDDECODER_VER_MAJOR 0 #define SOUNDDECODER_VER_MINOR 0 #define SOUNDDECODER_VER_PATCH 1 #define SOUNDDECODER_VERSION(x) \ { \ (x)->major = SOUNDDECODER_VER_MAJOR; \ (x)->minor = SOUNDDECODER_VER_MINOR; \ (x)->patch = SOUNDDECODER_VER_PATCH; \ } #define SOUND_VERSION SOUNDDECODER_VERSION extern SOUND_DECODER_DECLSPEC void SOUND_DECODER_CALL SoundDecoder_GetLinkedVersion(SoundDecoder_Version *ver); #define Sound_GetLinkedVersion SoundDecoder_GetLinkedVersion extern SOUND_DECODER_DECLSPEC int SOUND_DECODER_CALL SoundDecoder_Init(void); #define Sound_Init SoundDecoder_Init extern SOUND_DECODER_DECLSPEC void SOUND_DECODER_CALL SoundDecoder_Quit(void); #define Sound_Quit SoundDecoder_Quit extern SOUND_DECODER_DECLSPEC const SOUND_DECODER_CALL SoundDecoder_DecoderInfo** SoundDecoder_AvailableDecoders(void); #define Sound_AvailableDecoders SoundDecoder_AvailableDecoders extern SOUND_DECODER_DECLSPEC const char* SOUND_DECODER_CALL SoundDecoder_GetError(void); #define Sound_GetError SoundDecoder_GetError extern SOUND_DECODER_DECLSPEC void SOUND_DECODER_CALL SoundDecoder_ClearError(void); #define Sound_ClearError SoundDecoder_ClearError extern SOUND_DECODER_DECLSPEC SoundDecoder_Sample* SOUND_DECODER_CALL SoundDecoder_NewSample( struct ALmixer_RWops* rw_ops, const char* ext, SoundDecoder_AudioInfo* desired, size_t buffer_size); #define Sound_NewSample SoundDecoder_NewSample extern SOUND_DECODER_DECLSPEC SoundDecoder_Sample* SOUND_DECODER_CALL SoundDecoder_NewSampleFromFile(const char* file_name, SoundDecoder_AudioInfo* desired, size_t bufferSize); #define Sound_NewSampleFromFile SoundDecoder_NewSampleFromFile extern SOUND_DECODER_DECLSPEC void SOUND_DECODER_CALL SoundDecoder_FreeSample(SoundDecoder_Sample* sound_sample); #define Sound_FreeSample SoundDecoder_FreeSample extern SOUND_DECODER_DECLSPEC ptrdiff_t SOUND_DECODER_CALL SoundDecoder_GetDuration(SoundDecoder_Sample* sound_sample); #define Sound_GetDuration SoundDecoder_GetDuration extern SOUND_DECODER_DECLSPEC int SOUND_DECODER_CALL SoundDecoder_SetBufferSize(SoundDecoder_Sample* sound_sample, size_t new_buffer_size); #define Sound_SetBufferSize SoundDecoder_SetBufferSize extern SOUND_DECODER_DECLSPEC size_t SOUND_DECODER_CALL SoundDecoder_Decode(SoundDecoder_Sample* sound_sample); #define Sound_Decode SoundDecoder_Decode extern SOUND_DECODER_DECLSPEC size_t SOUND_DECODER_CALL SoundDecoder_DecodeAll(SoundDecoder_Sample* sound_sample); #define Sound_DecodeAll SoundDecoder_DecodeAll extern SOUND_DECODER_DECLSPEC int SOUND_DECODER_CALL SoundDecoder_Rewind(SoundDecoder_Sample* sound_sample); #define Sound_Rewind SoundDecoder_Rewind extern SOUND_DECODER_DECLSPEC int SOUND_DECODER_CALL SoundDecoder_Seek(SoundDecoder_Sample* sound_sample, size_t ms); #define Sound_Seek SoundDecoder_Seek /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #endif
ed3da0187890a98b86df27c4a77f9839000de9bb
ed7189bcb31973648dca4cb9f0d67cb4653d0e70
/tests/posix/pthread_rwlock.c
531637242dc8ace9fb2295ca98f4f1bfdd82a536
[ "MIT" ]
permissive
managarm/mlibc
6dedaa86ed74f26a52e300d97f6e5949bac0f93c
74efefb5e9e546adab60a5730d95165334d7ee15
refs/heads/master
2023-09-01T05:17:26.709378
2023-08-29T08:33:01
2023-08-29T08:33:01
63,353,495
717
173
MIT
2023-09-10T10:55:53
2016-07-14T16:46:51
C
UTF-8
C
false
false
2,744
c
pthread_rwlock.c
#include <assert.h> #include <errno.h> #include <pthread.h> static void test_write_lock_unlock() { int res; pthread_rwlock_t rw = PTHREAD_RWLOCK_INITIALIZER; res = pthread_rwlock_wrlock(&rw); assert(!res); res = pthread_rwlock_unlock(&rw); assert(!res); } static void test_read_lock_unlock() { int res; pthread_rwlock_t rw = PTHREAD_RWLOCK_INITIALIZER; res = pthread_rwlock_rdlock(&rw); assert(!res); res = pthread_rwlock_unlock(&rw); assert(!res); } static void test_write_trylock_unlock() { int res; pthread_rwlock_t rw = PTHREAD_RWLOCK_INITIALIZER; res = pthread_rwlock_trywrlock(&rw); assert(!res); res = pthread_rwlock_unlock(&rw); assert(!res); } static void test_read_trylock_unlock() { int res; pthread_rwlock_t rw = PTHREAD_RWLOCK_INITIALIZER; res = pthread_rwlock_tryrdlock(&rw); assert(!res); res = pthread_rwlock_unlock(&rw); assert(!res); } static void test_write_prevents_read() { int res; pthread_rwlock_t rw = PTHREAD_RWLOCK_INITIALIZER; res = pthread_rwlock_wrlock(&rw); assert(!res); res = pthread_rwlock_tryrdlock(&rw); assert(res == EBUSY); res = pthread_rwlock_unlock(&rw); assert(!res); } static void test_write_prevents_write() { int res; pthread_rwlock_t rw = PTHREAD_RWLOCK_INITIALIZER; res = pthread_rwlock_wrlock(&rw); assert(!res); res = pthread_rwlock_trywrlock(&rw); assert(res == EBUSY); res = pthread_rwlock_unlock(&rw); assert(!res); } static void test_read_prevents_write() { int res; pthread_rwlock_t rw = PTHREAD_RWLOCK_INITIALIZER; res = pthread_rwlock_rdlock(&rw); assert(!res); res = pthread_rwlock_trywrlock(&rw); assert(res == EBUSY); res = pthread_rwlock_unlock(&rw); assert(!res); } static void test_read_allows_read() { int res; pthread_rwlock_t rw = PTHREAD_RWLOCK_INITIALIZER; res = pthread_rwlock_rdlock(&rw); assert(!res); res = pthread_rwlock_tryrdlock(&rw); assert(!res); res = pthread_rwlock_unlock(&rw); assert(!res); } static void test_attr() { pthread_rwlockattr_t attr; pthread_rwlockattr_init(&attr); int pshared; pthread_rwlockattr_getpshared(&attr, &pshared); assert(pshared == PTHREAD_PROCESS_PRIVATE); pthread_rwlockattr_setpshared(&attr, PTHREAD_PROCESS_SHARED); pthread_rwlockattr_getpshared(&attr, &pshared); assert(pshared == PTHREAD_PROCESS_SHARED); pthread_rwlockattr_setpshared(&attr, PTHREAD_PROCESS_PRIVATE); pthread_rwlockattr_getpshared(&attr, &pshared); assert(pshared == PTHREAD_PROCESS_PRIVATE); pthread_rwlockattr_destroy(&attr); } int main() { test_write_lock_unlock(); test_read_lock_unlock(); test_write_trylock_unlock(); test_read_trylock_unlock(); test_write_prevents_read(); test_write_prevents_write(); test_read_prevents_write(); test_read_allows_read(); test_attr(); }
7a33193c57a4562b150e8da420079711e2d05c8e
c26d7b0ed875357278e61627da2da0650da77986
/src/cmd/init/init.c
f08015a11e5abc174d2fa61fa968687a8f6207a2
[ "BSD-3-Clause" ]
permissive
RetroBSD/retrobsd
5343d9e3c424637fc3ad5b03fe720b2744490025
486f81f6abff01c7dcc207235cd2979b226a95ff
refs/heads/master
2023-09-02T23:12:05.110883
2023-07-07T18:41:40
2023-07-07T18:41:40
18,598,087
282
59
BSD-3-Clause
2023-07-18T07:35:36
2014-04-09T13:25:46
C
UTF-8
C
false
false
13,723
c
init.c
/* * Copyright (c) 1980,1986 Regents of the University of California. * All rights reserved. The Berkeley software License Agreement * specifies the terms and conditions for redistribution. */ #include <sys/param.h> #include <sys/sysctl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <signal.h> #include <fcntl.h> #include <utmp.h> #include <setjmp.h> #include <sys/reboot.h> #include <errno.h> #include <sys/file.h> #include <ttyent.h> #include <sys/syslog.h> #include <sys/stat.h> #include <sys/wait.h> #include <paths.h> //#undef KERN_SECURELVL #define LINSIZ sizeof(wtmp.ut_line) #define CMDSIZ 200 /* max string length for getty or window command*/ #define SCPYN(a, b) strncpy(a, b, sizeof(a)) #define SCMPN(a, b) strncmp(a, b, sizeof(a)) char shell[] = _PATH_BSHELL; char minus[] = "-"; char runc[] = "/etc/rc"; char utmpf[] = _PATH_UTMP; char wtmpf[] = _PATH_WTMP; char ctty[] = _PATH_CONSOLE; void merge (int signum); struct utmp wtmp; struct tab { char line[LINSIZ]; char comn[CMDSIZ]; char xflag; int pid; int wpid; /* window system pid for SIGHUP */ char wcmd[CMDSIZ]; /* command to start window system process */ time_t gettytime; int gettycnt; time_t windtime; int windcnt; struct tab *next; } *itab; int fi; int mergflag; char tty[20]; jmp_buf sjbuf, shutpass; time_t time0; void reset(); void setsecuritylevel(); int getsecuritylevel(); extern int errno; struct sigvec rvec = { reset, sigmask (SIGHUP), 0 }; jmp_buf idlebuf; /* * Catch a SIGSYS signal. * * These may arise if a system does not support sysctl. * We tolerate up to 25 of these, then throw in the towel. */ void badsys (sig) int sig; { static int badcount = 0; if (badcount++ < 25) return; syslog(LOG_EMERG, "fatal signal: %d", sig); sleep(30); _exit(sig); } void idlehup (sig) int sig; { longjmp (idlebuf, 1); } /* * Remove utmp entry. */ void rmut(p) register struct tab *p; { register int f; int found = 0; static unsigned utmpsize; static struct utmp *utmp; register struct utmp *u; int nutmp; struct stat statbf; f = open(utmpf, O_RDWR); if (f >= 0) { fstat(f, &statbf); if (utmpsize < statbf.st_size) { utmpsize = statbf.st_size + 10 * sizeof(struct utmp); if (utmp) utmp = (struct utmp *)realloc(utmp, utmpsize); else utmp = (struct utmp *)malloc(utmpsize); if (!utmp) syslog(LOG_ERR, "utmp malloc failed"); } if (statbf.st_size && utmp) { nutmp = read(f, utmp, (int)statbf.st_size); nutmp /= sizeof(struct utmp); for (u = utmp ; u < &utmp[nutmp] ; u++) { if (SCMPN(u->ut_line, p->line) || u->ut_name[0]==0) continue; lseek(f, ((long)u)-((long)utmp), L_SET); SCPYN(u->ut_name, ""); SCPYN(u->ut_host, ""); time(&u->ut_time); write(f, (char *)u, sizeof(*u)); found++; } } close(f); } if (found) { f = open(wtmpf, O_WRONLY|O_APPEND); if (f >= 0) { SCPYN(wtmp.ut_line, p->line); SCPYN(wtmp.ut_name, ""); SCPYN(wtmp.ut_host, ""); time(&wtmp.ut_time); write(f, (char *)&wtmp, sizeof(wtmp)); close(f); } /* * After a proper login force reset * of error detection code in dfork. */ p->gettytime = 0; p->windtime = 0; } } void idle (sig) int sig; { register struct tab *p; register int pid; signal (SIGHUP, idlehup); for (;;) { if (setjmp(idlebuf)) return; pid = wait((int *) 0); if (pid == -1) { sigpause(0L); continue; } for (p=itab; p; p=p->next) { /* if window system dies, mark it for restart */ if (p->wpid == pid) p->wpid = -1; if (p->pid == pid) { rmut(p); p->pid = -1; } } } } void term(p) register struct tab *p; { if (p->pid != 0) { rmut(p); kill(p->pid, SIGKILL); } p->pid = 0; /* send SIGHUP to get rid of connections */ if (p->wpid > 0) kill(p->wpid, SIGHUP); } int shutend() { register int i, f; signal(SIGALRM, SIG_DFL); for (i = 0; i < 10; i++) close(i); f = open(wtmpf, O_WRONLY|O_APPEND); if (f >= 0) { SCPYN(wtmp.ut_line, "~"); SCPYN(wtmp.ut_name, "shutdown"); SCPYN(wtmp.ut_host, ""); time(&wtmp.ut_time); write(f, (char *)&wtmp, sizeof(wtmp)); close(f); } return (1); } void shutreset (sig) int sig; { const char shutfailm[] = "WARNING: Something is hung (wont die); ps axl advised\n"; if (fork() == 0) { int ct = open(ctty, 1); write(ct, shutfailm, sizeof (shutfailm)); sleep(1); exit(1); } //sleep(1); shutend(); longjmp(shutpass, 1); } void shutdown() { register int i; register struct tab *p, *p1; close(creat(utmpf, 0644)); signal(SIGHUP, SIG_IGN); for (p = itab; p ; ) { term(p); p1 = p->next; free(p); p = p1; } itab = (struct tab *)0; signal(SIGALRM, shutreset); (void) kill(-1, SIGTERM); /* one chance to catch it */ //sleep(1); alarm(30); for (i = 0; i < 5; i++) kill(-1, SIGKILL); while (wait((int *)0) != -1) ; alarm(0); shutend(); } void single() { register int pid, xpid; int fd; /* * If the kernel is in secure mode, downgrade it to insecure mode. */ if (getsecuritylevel() > 0) setsecuritylevel(0); do { pid = fork(); if (pid == 0) { signal(SIGTERM, SIG_DFL); signal(SIGHUP, SIG_DFL); signal(SIGALRM, SIG_DFL); signal(SIGTSTP, SIG_IGN); fd = open(ctty, O_RDWR, 0); if (fd) dup2(fd, 0); dup2(0, 1); dup2(0, 2); execl(shell, minus, (char *)0); perror(shell); exit(0); } while ((xpid = wait((int *)0)) != pid) if (xpid == -1 && errno == ECHILD) break; } while (xpid == -1); } int runcom(oldhowto) int oldhowto; { register int pid, f; int status; pid = fork(); if (pid == 0) { f = open("/", O_RDONLY, 0); if (f > 0) dup2(f, 0); dup2(0, 1); dup2(0, 2); if (oldhowto & RB_SINGLE) execl(shell, shell, runc, (char *)0); else execl(shell, shell, runc, "autoboot", (char *)0); exit(1); } while (wait(&status) != pid) ; if (status) { syslog(LOG_ERR, "%s failed: status = %#x", runc, status); closelog(); sleep(1); return (0); } f = open(wtmpf, O_WRONLY|O_APPEND); if (f >= 0) { SCPYN(wtmp.ut_line, "~"); SCPYN(wtmp.ut_name, "reboot"); SCPYN(wtmp.ut_host, ""); if (time0) { wtmp.ut_time = time0; time0 = 0; } else time(&wtmp.ut_time); write(f, (char *)&wtmp, sizeof(wtmp)); close(f); } return (1); } #define NARGS 20 /* must be at least 4 */ #define ARGLEN 512 /* total size for all the argument strings */ void execit(s, arg) char *s; char *arg; /* last argument on line */ { char *argv[NARGS], args[ARGLEN], *envp[1]; register char *sp = s; register char *ap = args; register char c; register int i; /* * First we have to set up the argument vector. * "prog arg1 arg2" maps to exec("prog", "-", "arg1", "arg2"). */ for (i = 1; i < NARGS - 2; i++) { argv[i] = ap; for (;;) { if ((c = *sp++) == '\0' || ap >= &args[ARGLEN-1]) { *ap = '\0'; goto done; } if (c == ' ') { *ap++ = '\0'; while (*sp == ' ') sp++; if (*sp == '\0') goto done; break; } *ap++ = c; } } done: argv[0] = argv[1]; argv[1] = "-"; argv[i+1] = arg; argv[i+2] = 0; envp[0] = 0; execve(argv[0], &argv[1], envp); /* report failure of exec */ syslog(LOG_ERR, "%s: %m", argv[0]); closelog(); sleep(10); /* prevent failures from eating machine */ } void wstart(p) register struct tab *p; { register int pid; time_t t; int dowait = 0; time(&t); p->windcnt++; if ((t - p->windtime) >= 60) { p->windtime = t; p->windcnt = 1; } else if (p->windcnt >= 5) { dowait = 1; p->windtime = t; p->windcnt = 1; } pid = fork(); if (pid == 0) { signal(SIGTERM, SIG_DFL); signal(SIGHUP, SIG_IGN); sigsetmask(0L); /* since can be called from masked code */ if (dowait) { syslog(LOG_ERR, "'%s %s' failing, sleeping", p->wcmd, p->line); closelog(); sleep(30); } execit(p->wcmd, p->line); exit(0); } p->wpid = pid; } void dfork(p) struct tab *p; { register int pid; time_t t; int dowait = 0; time(&t); p->gettycnt++; if ((t - p->gettytime) >= 60) { p->gettytime = t; p->gettycnt = 1; } else if (p->gettycnt >= 5) { dowait = 1; p->gettytime = t; p->gettycnt = 1; } pid = fork(); if (pid == 0) { signal(SIGTERM, SIG_DFL); signal(SIGHUP, SIG_IGN); sigsetmask(0L); /* since can be called from masked code */ if (dowait) { syslog(LOG_ERR, "'%s %s' failing, sleeping", p->comn, p->line); closelog(); sleep(30); } execit(p->comn, p->line); exit(0); } p->pid = pid; } /* * Multi-user. Listen for users leaving, SIGHUP's * which indicate ttys has changed, and SIGTERM's which * are used to shutdown the system. */ void multiple() { register struct tab *p; register int pid; long omask; static struct sigvec mvec = { merge, sigmask(SIGTERM), 0 }; /* * If the administrator has not set the security level to -1 * to indicate that the kernel should not run multiuser in secure * mode, and the run script has not set a higher level of security * than level 1, then put the kernel into secure mode. */ if (getsecuritylevel() == 0) setsecuritylevel(1); sigvec(SIGHUP, &mvec, (struct sigvec *)0); for (;;) { pid = wait((int *)0); if (pid == -1) return; omask = sigblock(sigmask(SIGHUP)); for (p=itab; p; p=p->next) { /* must restart window system BEFORE emulator */ if (p->wpid == pid || p->wpid == -1) wstart(p); if (p->pid == pid || p->pid == -1) { /* disown the window system */ if (p->wpid) kill(p->wpid, SIGHUP); rmut(p); dfork(p); } } sigsetmask(omask); } } int main(argc, argv) char **argv; { #if 0 /* Trivial init: just start shell. */ int fd = open(ctty, O_RDWR, 0); if (fd < 0) return 0; write(fd, "init: starting /bin/sh\n", 23); if (fd > 0) dup2(fd, 0); dup2(0, 1); dup2(0, 2); execl(shell, minus, (char *)0); perror(shell); return 0; #else int howto, oldhowto; time0 = time(0); if (argc > 1 && argv[1][0] == '-') { char *cp; howto = 0; cp = &argv[1][1]; while (*cp) switch (*cp++) { case 'a': howto |= RB_ASKNAME; break; case 's': howto |= RB_SINGLE; break; } } else { howto = RB_SINGLE; } if (getuid() != 0) exit(1); if (getpid() != 1) exit(1); openlog("init", LOG_CONS|LOG_ODELAY, LOG_AUTH); signal(SIGSYS, badsys); sigvec(SIGTERM, &rvec, (struct sigvec *)0); signal(SIGTSTP, idle); signal(SIGSTOP, SIG_IGN); signal(SIGTTIN, SIG_IGN); signal(SIGTTOU, SIG_IGN); (void) setjmp(sjbuf); for (;;) { oldhowto = howto; howto = RB_SINGLE; if (setjmp(shutpass) == 0) shutdown(); if (oldhowto & RB_SINGLE) single(); if (runcom(oldhowto) == 0) continue; merge(0); multiple(); } #endif } /* * Get the security level of the kernel. */ int getsecuritylevel() { #ifdef KERN_SECURELVL int name[2], curlevel; size_t len; name[0] = CTL_KERN; name[1] = KERN_SECURELVL; len = sizeof curlevel; if (sysctl(name, 2, &curlevel, &len, NULL, 0) == -1) { syslog(LOG_EMERG, "cannot get kernel security level: %s", strerror(errno)); return (-1); } return (curlevel); #else return (-1); #endif } /* * Set the security level of the kernel. */ void setsecuritylevel(newlevel) int newlevel; { #ifdef KERN_SECURELVL int name[2], curlevel; curlevel = getsecuritylevel(); if (newlevel == curlevel) return; name[0] = CTL_KERN; name[1] = KERN_SECURELVL; if (sysctl(name, 2, NULL, NULL, &newlevel, sizeof newlevel) == -1) { syslog(LOG_EMERG, "cannot change kernel security level from %d to %d: %s", curlevel, newlevel, strerror(errno)); return; } syslog(LOG_ALERT, "kernel security level changed from %d to %d", curlevel, newlevel); #endif } void wterm(p) register struct tab *p; { if (p->wpid != 0) { kill(p->wpid, SIGKILL); p->wpid = 0; } } /* * Merge current contents of ttys file * into in-core table of configured tty lines. * Entered as signal handler for SIGHUP. */ #define FOUND 1 #define CHANGE 2 #define WCHANGE 4 void merge(int signum) { register struct tab *p; register struct ttyent *t; register struct tab *p1; for (p=itab; p; p=p->next) p->xflag = 0; setttyent(); while ((t = getttyent()) != 0) { if ((t->ty_status & TTY_ON) == 0) continue; for (p=itab; p; p=p->next) { if (SCMPN(p->line, t->ty_name)) continue; p->xflag |= FOUND; if (SCMPN(p->comn, t->ty_getty)) { p->xflag |= CHANGE; SCPYN(p->comn, t->ty_getty); } if (SCMPN(p->wcmd, t->ty_window ? t->ty_window : "")) { p->xflag |= WCHANGE | CHANGE; SCPYN(p->wcmd, t->ty_window); } goto contin1; } /* * Make space for a new one */ p1 = (struct tab *)calloc(1, sizeof(*p1)); if (!p1) { syslog(LOG_ERR, "no space for '%s' !?!", t->ty_name); goto contin1; } /* * Put new terminal at the end of the linked list. */ if (itab) { for (p = itab; p->next ; p = p->next) ; p->next = p1; } else itab = p1; p = p1; SCPYN(p->line, t->ty_name); p->xflag |= FOUND|CHANGE; SCPYN(p->comn, t->ty_getty); if (t->ty_window && strcmp(t->ty_window, "") != 0) { p->xflag |= WCHANGE; SCPYN(p->wcmd, t->ty_window); } contin1: ; } endttyent(); p1 = (struct tab *)0; for (p=itab; p; p=p->next) { if ((p->xflag & FOUND) == 0) { term(p); wterm(p); if (p1) p1->next = p->next; else itab = p->next; free(p); p = p1 ? p1 : itab; } else { /* window system should be started first */ if (p->xflag & WCHANGE) { wterm(p); wstart(p); } if (p->xflag & CHANGE) { term(p); dfork(p); } } p1 = p; } } void reset() { longjmp(sjbuf, 1); }
0369b060e0e0d08cba529fd6177cff6f4b240b7f
1661c43eaf9e44dfe7cce269cfaae62e336036f1
/tool/config/sysctl.c
d971685dc29b82633cbb55f357faf8aa3d728553
[]
permissive
jart/blink
3354eaf084e3e85a50372f1a93fc75ff2b9488b1
312a027d0908c1b1f9d1e9ebba837da569606b82
refs/heads/master
2023-08-31T21:30:40.551686
2023-08-22T15:42:44
2023-08-22T15:42:44
561,183,031
6,089
192
ISC
2023-08-22T15:42:46
2022-11-03T06:07:09
C
UTF-8
C
false
false
516
c
sysctl.c
// tests for bsd sysctl() system call #include <sys/types.h> // ordering sometimes matters #include <sys/sysctl.h> #include <sys/time.h> int features_we_care_about[] = { CTL_HW, // CTL_KERN, // KERN_BOOTTIME, // HW_NCPU, // #ifdef HW_MEMSIZE HW_MEMSIZE, #else HW_PHYSMEM, #endif }; int main(int argc, char *argv[]) { struct timeval x; size_t n = sizeof(x); int mib[] = {CTL_KERN, KERN_BOOTTIME}; if (sysctl(mib, 2, &x, &n, 0, 0) == -1) return 1; return 0; }
8e7e95e94437d726228efb9f08e69673ea7d3bf0
e1cddfd754d952134e72dfd03522c5ea4fb6008e
/extras/deprecated/plugins/gbp/gbp_recirc.c
8d56f11b4e313d4a544eb14869332e72c6d112a7
[ "Apache-2.0" ]
permissive
FDio/vpp
0ad30fa1bec2975ffa6b66b45c9f4f32163123b6
f234b0d4626d7e686422cc9dfd25958584f4931e
refs/heads/master
2023-08-31T16:09:04.068646
2022-03-14T09:49:15
2023-08-31T09:50:00
96,556,718
1,048
630
Apache-2.0
2023-06-21T05:39:17
2017-07-07T16:29:40
C
UTF-8
C
false
false
7,349
c
gbp_recirc.c
/* * Copyright (c) 2018 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <plugins/gbp/gbp_recirc.h> #include <plugins/gbp/gbp_endpoint_group.h> #include <plugins/gbp/gbp_endpoint.h> #include <plugins/gbp/gbp_itf.h> #include <vnet/dpo/dvr_dpo.h> #include <vnet/fib/fib_table.h> #include <vlib/unix/plugin.h> /** * Pool of GBP recircs */ gbp_recirc_t *gbp_recirc_pool; /** * Recirc configs keyed by sw_if_index */ index_t *gbp_recirc_db; /** * logger */ vlib_log_class_t gr_logger; /** * L2 Emulation enable/disable symbols */ static void (*l2e_enable) (u32 sw_if_index); static void (*l2e_disable) (u32 sw_if_index); #define GBP_RECIRC_DBG(...) \ vlib_log_debug (gr_logger, __VA_ARGS__); u8 * format_gbp_recirc (u8 * s, va_list * args) { gbp_recirc_t *gr = va_arg (*args, gbp_recirc_t *); vnet_main_t *vnm = vnet_get_main (); return format (s, " %U, sclass:%d, ext:%d", format_vnet_sw_if_index_name, vnm, gr->gr_sw_if_index, gr->gr_sclass, gr->gr_is_ext); } int gbp_recirc_add (u32 sw_if_index, sclass_t sclass, u8 is_ext) { gbp_recirc_t *gr; index_t gri; vec_validate_init_empty (gbp_recirc_db, sw_if_index, INDEX_INVALID); gri = gbp_recirc_db[sw_if_index]; if (INDEX_INVALID == gri) { gbp_endpoint_group_t *gg; fib_protocol_t fproto; index_t ggi; ggi = gbp_endpoint_group_find (sclass); if (INDEX_INVALID == ggi) return (VNET_API_ERROR_NO_SUCH_ENTRY); gbp_endpoint_group_lock (ggi); pool_get_zero (gbp_recirc_pool, gr); gri = gr - gbp_recirc_pool; gr->gr_sclass = sclass; gr->gr_is_ext = is_ext; gr->gr_sw_if_index = sw_if_index; /* * IP enable the recirc interface */ ip4_sw_interface_enable_disable (gr->gr_sw_if_index, 1); ip6_sw_interface_enable_disable (gr->gr_sw_if_index, 1); /* * cache the FIB indicies of the EPG */ gr->gr_epgi = ggi; gg = gbp_endpoint_group_get (gr->gr_epgi); FOR_EACH_FIB_IP_PROTOCOL (fproto) { gr->gr_fib_index[fib_proto_to_dpo (fproto)] = gbp_endpoint_group_get_fib_index (gg, fproto); } /* * bind to the bridge-domain of the EPG */ gr->gr_itf = gbp_itf_l2_add_and_lock (gr->gr_sw_if_index, gg->gg_gbd); /* * set the interface into L2 emulation mode */ l2e_enable (gr->gr_sw_if_index); /* * Packets on the recirculation interface are subject to src-EPG * classification. Recirc interfaces are L2-emulation mode. * for internal EPGs this is via an LPM on all external subnets. * for external EPGs this is via a port mapping. */ if (gr->gr_is_ext) { mac_address_t mac; /* * recirc is for post-NAT translation packets going into * the external EPG, these are classified to the NAT EPG * based on its port */ mac_address_from_bytes (&mac, vnet_sw_interface_get_hw_address (vnet_get_main (), gr->gr_sw_if_index)); gbp_endpoint_update_and_lock (GBP_ENDPOINT_SRC_CP, gr->gr_sw_if_index, NULL, &mac, INDEX_INVALID, INDEX_INVALID, gr->gr_sclass, GBP_ENDPOINT_FLAG_NONE, NULL, NULL, &gr->gr_ep); vnet_feature_enable_disable ("ip4-unicast", "ip4-gbp-src-classify", gr->gr_sw_if_index, 1, 0, 0); vnet_feature_enable_disable ("ip6-unicast", "ip6-gbp-src-classify", gr->gr_sw_if_index, 1, 0, 0); } else { /* * recirc is for pre-NAT translation packets coming from * the external EPG, these are classified based on a LPM * in the EPG's route-domain */ vnet_feature_enable_disable ("ip4-unicast", "ip4-gbp-lpm-classify", gr->gr_sw_if_index, 1, 0, 0); vnet_feature_enable_disable ("ip6-unicast", "ip6-gbp-lpm-classify", gr->gr_sw_if_index, 1, 0, 0); } gbp_recirc_db[sw_if_index] = gri; } else { gr = gbp_recirc_get (gri); } GBP_RECIRC_DBG ("add: %U", format_gbp_recirc, gr); return (0); } int gbp_recirc_delete (u32 sw_if_index) { gbp_recirc_t *gr; index_t gri; if (vec_len (gbp_recirc_db) <= sw_if_index) return VNET_API_ERROR_INVALID_SW_IF_INDEX; gri = gbp_recirc_db[sw_if_index]; if (INDEX_INVALID != gri) { gr = pool_elt_at_index (gbp_recirc_pool, gri); GBP_RECIRC_DBG ("del: %U", format_gbp_recirc, gr); if (gr->gr_is_ext) { gbp_endpoint_unlock (GBP_ENDPOINT_SRC_CP, gr->gr_ep); vnet_feature_enable_disable ("ip4-unicast", "ip4-gbp-src-classify", gr->gr_sw_if_index, 0, 0, 0); vnet_feature_enable_disable ("ip6-unicast", "ip6-gbp-src-classify", gr->gr_sw_if_index, 0, 0, 0); } else { vnet_feature_enable_disable ("ip4-unicast", "ip4-gbp-lpm-classify", gr->gr_sw_if_index, 0, 0, 0); vnet_feature_enable_disable ("ip6-unicast", "ip6-gbp-lpm-classify", gr->gr_sw_if_index, 0, 0, 0); } ip4_sw_interface_enable_disable (gr->gr_sw_if_index, 0); ip6_sw_interface_enable_disable (gr->gr_sw_if_index, 0); l2e_disable (gr->gr_sw_if_index); gbp_itf_unlock (&gr->gr_itf); gbp_endpoint_group_unlock (gr->gr_epgi); gbp_recirc_db[sw_if_index] = INDEX_INVALID; pool_put (gbp_recirc_pool, gr); return (0); } return VNET_API_ERROR_NO_SUCH_ENTRY; } void gbp_recirc_walk (gbp_recirc_cb_t cb, void *ctx) { gbp_recirc_t *ge; /* *INDENT-OFF* */ pool_foreach (ge, gbp_recirc_pool) { if (!cb(ge, ctx)) break; } /* *INDENT-ON* */ } static walk_rc_t gbp_recirc_show_one (gbp_recirc_t * gr, void *ctx) { vlib_cli_output (ctx, " %U", format_gbp_recirc, gr); return (WALK_CONTINUE); } static clib_error_t * gbp_recirc_show (vlib_main_t * vm, unformat_input_t * input, vlib_cli_command_t * cmd) { vlib_cli_output (vm, "Recirculation-Interfaces:"); gbp_recirc_walk (gbp_recirc_show_one, vm); return (NULL); } /*? * Show Group Based Policy Recircs and derived information * * @cliexpar * @cliexstart{show gbp recirc} * @cliexend ?*/ /* *INDENT-OFF* */ VLIB_CLI_COMMAND (gbp_recirc_show_node, static) = { .path = "show gbp recirc", .short_help = "show gbp recirc\n", .function = gbp_recirc_show, }; /* *INDENT-ON* */ static clib_error_t * gbp_recirc_init (vlib_main_t * vm) { gr_logger = vlib_log_register_class ("gbp", "recirc"); l2e_enable = vlib_get_plugin_symbol ("l2e_plugin.so", "l2_emulation_enable"); l2e_disable = vlib_get_plugin_symbol ("l2e_plugin.so", "l2_emulation_disable"); return (NULL); } VLIB_INIT_FUNCTION (gbp_recirc_init); /* * fd.io coding-style-patch-verification: ON * * Local Variables: * eval: (c-set-style "gnu") * End: */
7e5861dbc550281a0bee9a62d9822314d96b0371
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/mm/msync.c
02d770eb9fc74140960f3475312cc885ab2ca8e9
[ "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
2,485
c
msync.c
/* * linux/mm/msync.c * * Copyright (C) 1994-1999 Linus Torvalds */ /* * The msync() system call. */ #include <linux/fs.h> #include <linux/mm.h> #include <linux/mman.h> #include <linux/file.h> #include <linux/syscalls.h> #include <linux/sched.h> /* * MS_SYNC syncs the entire file - including mappings. * * MS_ASYNC does not start I/O (it used to, up to 2.5.67). * Nor does it marks the relevant pages dirty (it used to up to 2.6.17). * Now it doesn't do anything, since dirty pages are properly tracked. * * The application may now run fsync() to * write out the dirty pages and wait on the writeout and check the result. * Or the application may run fadvise(FADV_DONTNEED) against the fd to start * async writeout immediately. * So by _not_ starting I/O in MS_ASYNC we provide complete flexibility to * applications. */ SYSCALL_DEFINE3(msync, unsigned long, start, size_t, len, int, flags) { unsigned long end; struct mm_struct *mm = current->mm; struct vm_area_struct *vma; int unmapped_error = 0; int error = -EINVAL; if (flags & ~(MS_ASYNC | MS_INVALIDATE | MS_SYNC)) goto out; if (start & ~PAGE_MASK) goto out; if ((flags & MS_ASYNC) && (flags & MS_SYNC)) goto out; error = -ENOMEM; len = (len + ~PAGE_MASK) & PAGE_MASK; end = start + len; if (end < start) goto out; error = 0; if (end == start) goto out; /* * If the interval [start,end) covers some unmapped address ranges, * just ignore them, but return -ENOMEM at the end. */ down_read(&mm->mmap_sem); vma = find_vma(mm, start); for (;;) { struct file *file; /* Still start < end. */ error = -ENOMEM; if (!vma) goto out_unlock; /* Here start < vma->vm_end. */ if (start < vma->vm_start) { start = vma->vm_start; if (start >= end) goto out_unlock; unmapped_error = -ENOMEM; } /* Here vma->vm_start <= start < vma->vm_end. */ if ((flags & MS_INVALIDATE) && (vma->vm_flags & VM_LOCKED)) { error = -EBUSY; goto out_unlock; } file = vma->vm_file; start = vma->vm_end; if ((flags & MS_SYNC) && file && (vma->vm_flags & VM_SHARED)) { vma_get_file(vma); up_read(&mm->mmap_sem); error = vfs_fsync(file, 0); vma_fput(vma); if (error || start >= end) goto out; down_read(&mm->mmap_sem); vma = find_vma(mm, start); } else { if (start >= end) { error = 0; goto out_unlock; } vma = vma->vm_next; } } out_unlock: up_read(&mm->mmap_sem); out: return error ? : unmapped_error; }
8d27f388b5f6ee77db01322f464bcf63122a6900
85ccd32aa73eecf274a937f1fc3b6f4d484b77da
/test cases/common/80 declare dep/entity/entity.h
959a8c30db68ef2aa8ddb1c6b1de542d6dbe926f
[ "Apache-2.0" ]
permissive
mesonbuild/meson
48321cf4235dfcc0194fed90ff43a57367592bf7
cf5adf0c646474f0259d123fad60ca5ed38ec891
refs/heads/master
2023-09-01T05:58:50.807952
2023-03-17T20:27:37
2023-08-31T11:52:41
19,784,232
5,122
1,848
Apache-2.0
2023-09-14T15:47:23
2014-05-14T15:08:16
Python
UTF-8
C
false
false
62
h
entity.h
#pragma once int entity_func1(void); int entity_func2(void);
8045091f6a2f8bf0c7f169ebe945b7d3dfd786ff
6b265b404d74b09e1b1e3710e8ea872cd50f4263
/DataStorage/NetCDF/CSamples/write_netcdf.c
f474312486d14448cebe355701ba48c52136aa95
[ "CC-BY-4.0" ]
permissive
gjbex/training-material
cdc189469ae2c7d43784ecdcb4bcca10ecbc21ae
e748466a2af9f3388a8b0ed091aa061dbfc752d6
refs/heads/master
2023-08-17T11:02:27.322865
2023-04-27T14:42:55
2023-04-27T14:42:55
18,587,808
130
60
CC-BY-4.0
2023-08-03T07:07:25
2014-04-09T06:35:58
Jupyter Notebook
UTF-8
C
false
false
3,574
c
write_netcdf.c
#include <err.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <netcdf.h> #include "grid.h" #define MAX_STR_LEN 1024 #define N_DIMS 3 float gauss(float x, float y, float z, void *params); int main(int argc, char *argv[]) { const int default_ooints = 10; int nr_points = default_ooints; int dims[N_DIMS]; float **grid = NULL; float *data = NULL; int nc_id, dim_ids[N_DIMS], var_x_id, var_y_id, var_z_id, var_value_id; int ret_val; char file_name[MAX_STR_LEN]; /* handle command line arguments */ if (argc >= 2) { strncpy(file_name, argv[1], MAX_STR_LEN); } else { errx(EXIT_FAILURE, "no file name speicified"); } if (argc >= 3) { nr_points = atoi(argv[2]); } /* set dimensions */ dims[0] = dims[1] = dims[2] = nr_points; /* create NetCDF file, overwrite if it exists (NC_CLOBBER */ if ((ret_val = nc_create(file_name, NC_CLOBBER, &nc_id)) != 0) { errx(ret_val, "file creation failed"); } /* define NetCDF dimensions */ if ((ret_val = nc_def_dim(nc_id, "x", dims[0], &(dim_ids[0]))) != 0) { errx(ret_val, "x dimension definition failed"); } if ((ret_val = nc_def_dim(nc_id, "y", dims[1], &(dim_ids[1]))) != 0) { errx(ret_val, "y dimension definition failed"); } if ((ret_val = nc_def_dim(nc_id, "z", dims[2], &(dim_ids[2]))) != 0) { errx(ret_val, "z dimension definition failed"); } /* define x, y, z grid variables */ if ((ret_val = nc_def_var(nc_id, "x", NC_FLOAT, 1, &(dim_ids[0]), &var_x_id)) != 0) { errx(ret_val, "variable x definition failed"); } if ((ret_val = nc_def_var(nc_id, "y", NC_FLOAT, 1, &(dim_ids[1]), &var_y_id)) != 0) { errx(ret_val, "variable y definition failed"); } if ((ret_val = nc_def_var(nc_id, "z", NC_FLOAT, 1, &(dim_ids[2]), &var_z_id)) != 0) { errx(ret_val, "variable z definition failed"); } /* define value variable */ if ((ret_val = nc_def_var(nc_id, "value", NC_FLOAT, N_DIMS, dim_ids, &var_value_id)) != 0) { errx(ret_val, "variable value definition failed"); } /* all metadata has been defined, end definition mode */ if ((ret_val = nc_enddef(nc_id)) != 0) { errx(ret_val, "end defintition mode failed"); } /* create grid */ grid = create_quadratic_grid(dims, N_DIMS); /* write x, y, z grid to NetCDF file */ if ((ret_val = nc_put_var_float(nc_id, var_x_id, &(grid[0][0]))) != 0) { errx(ret_val, "writing x grid variable failed"); } if ((ret_val = nc_put_var_float(nc_id, var_y_id, &(grid[1][0]))) != 0) { errx(ret_val, "writing y grid variable failed"); } if ((ret_val = nc_put_var_float(nc_id, var_z_id, &(grid[2][0]))) != 0) { errx(ret_val, "writing z grid variable failed"); } /* create data */ data = compute_3d_data(gauss, (void *) NULL, grid, dims); /* write data to NetCDF file */ if ((ret_val = nc_put_var_float(nc_id, var_value_id, &(data[0]))) != 0) { errx(ret_val, "writing value variable failed"); } /* free data */ free(data); /* free grid */ free_grid(grid, N_DIMS); /* close file */ if ((ret_val = nc_close(nc_id)) != 0) { errx(ret_val, "file close failed"); } return EXIT_SUCCESS; } float gauss(float x, float y, float z, void *params) { return exp(-(x*x + y*y + z*z)); }
a541515644997fbfd9a7cbceb44e8e5d322e1d1f
1c90c9a656cf14fa877957c7504e67665d961733
/tests/feature_tests/implicit_cast.c
e8ea79167bf83fa3be2983eb1a085f0e337205b0
[ "MIT" ]
permissive
ShivamSarodia/ShivyC
dd5d1161d6da78491386c5f0a4ebcbca7ee506dd
6232136be38a29e8c18beae3d23e49ecfb7906fd
refs/heads/master
2023-05-25T01:38:55.008484
2023-05-23T06:44:15
2023-05-23T06:44:15
63,022,542
1,072
97
MIT
2023-05-23T06:44:16
2016-07-10T23:16:02
Python
UTF-8
C
false
false
2,021
c
implicit_cast.c
int main() { _Bool b; char c; unsigned char uc; short s; unsigned short us; unsigned short us_2; int i; unsigned int ui; long l; unsigned long ul; // Until negative literals are supported, this is how we insert -1. int neg_one = 4294967295; c = neg_one; if(c != neg_one) return 1; s = neg_one; if(s != neg_one) return 2; if(s == 65535) return 3; us = neg_one; if(us == neg_one) return 4; if(us != 65535) return 5; s = neg_one; us_2 = s; if(us != 65535) return 6; if(us != us_2) return 7; ui = neg_one; if(ui != 4294967295) return 8; s = neg_one; ui = s; if(ui != 4294967295) return 9; us = neg_one; ui = us; if(ui != 65535) return 9; s = neg_one; ui = s; i = ui; // Technically undefined behavior, per the spec. if(i != neg_one) return 10; c = neg_one; l = c; if(l + 1 != 0) return 11; s = neg_one; l = s; if(l + 1 != 0) return 12; l = neg_one; if(l + 1 != 0) return 13; // Test integer promotion char c1 = 30, c2 = 40, c3 = 10, c4; c4 = (c1 * c2) / c3; if(c4 != 120) return 14; unsigned short us1 = 30, us2 = 40, us3 = 10, us4; us1 = 30; us2 = 40; us3 = 10; us4 = (us1 * us2) / us3; if(us4 != 120) return 15; // Test integer conversion long l1 = 1073741824, i1; // Because large immediate values are not yet supported, we split up // l1 in this way. l1 = 2^32. l1 = l1 + l1 + l1 + l1; if(l1 * 2 / 8 != 1073741824) return 16; // Test unsigned integer conversion int i2; unsigned int ui2; i2 = 2*neg_one; ui2 = 1; if(i2 + ui2 != 4294967295) return 17; // Test int/long conversion. long l2; int i3; l2 = 2147483644; // 2^31-4 i3 = 4; if(i3 * l2 / i3 != 2147483644) return 18; // Test signed/unsigned conversion when signed is bigger long l3 = 100; unsigned int i4 = 100; if(l3 != i4) { return 20; } if(i4 != l3) { return 21; } b = 0; if(b) return 19; b = 10; if(b) { b = i3; if(b) { return 0; } } return 1; }
58bfc8fafba5c1f430fc659e427029648690b9cf
182bbadb0ee7f59f1abd154d06484e555a30c6d8
/third_party/cairo/src/drm/cairo-drm-intel-debug.c
bfe5136675196a2e57b243f542c7f6d984e234b3
[ "Apache-2.0" ]
permissive
epam/Indigo
08559861adf474122366b6e2e499ed3aa56272d1
8e473e69f393c3a57ff75b7728999c5fb4cbf1a3
refs/heads/master
2023-09-02T10:14:46.843829
2023-08-25T08:39:24
2023-08-25T08:39:24
37,536,320
265
106
Apache-2.0
2023-09-14T17:34:00
2015-06-16T14:45:56
C++
UTF-8
C
false
false
33,114
c
cairo-drm-intel-debug.c
/************************************************************************** * * Copyright 2003 Tungsten Graphics, Inc., Cedar Park, Texas. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sub license, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial portions * of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS BE LIABLE FOR * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * **************************************************************************/ #include "cairoint.h" #include "cairo-drm-intel-private.h" struct debug_stream { unsigned offset; /* current gtt offset */ const char *ptr; /* pointer to gtt offset zero */ const char *end; /* pointer to gtt offset zero */ }; static cairo_bool_t debug (struct debug_stream *stream, const char *name, uint32_t len) { uint32_t i; const uint32_t *ptr = (uint32_t *)(stream->ptr + stream->offset); if (len == 0) { fprintf (stderr, "Error - zero length packet (0x%08x)\n", stream->ptr[0]); ASSERT_NOT_REACHED; return FALSE; } fprintf (stderr, "%04x: ", stream->offset); fprintf (stderr, "%s (%d dwords):\n", name, len); for (i = 0; i < len; i++) fprintf (stderr, "\t0x%08x\n", ptr[i]); fprintf (stderr, "\n"); stream->offset += len * sizeof(uint32_t); return TRUE; } static const char * get_prim_name (uint32_t val) { switch (val & PRIM3D_MASK) { case PRIM3D_TRILIST: return "TRILIST"; case PRIM3D_TRISTRIP: return "TRISTRIP"; case PRIM3D_TRISTRIP_RVRSE: return "TRISTRIP_RVRSE"; case PRIM3D_TRIFAN: return "TRIFAN"; case PRIM3D_POLY: return "POLY"; case PRIM3D_LINELIST: return "LINELIST"; case PRIM3D_LINESTRIP: return "LINESTRIP"; case PRIM3D_RECTLIST: return "RECTLIST"; case PRIM3D_POINTLIST: return "POINTLIST"; case PRIM3D_DIB: return "DIB"; case PRIM3D_CLEAR_RECT: return "CLEAR_RECT"; case PRIM3D_ZONE_INIT: return "ZONE_INIT"; default: return "????"; } } static cairo_bool_t debug_prim (struct debug_stream *stream, const char *name, cairo_bool_t dump_floats, uint32_t len) { uint32_t *ptr = (uint32_t *)(stream->ptr + stream->offset); const char *prim = get_prim_name( ptr[0] ); uint32_t i; fprintf (stderr, "%04x: ", stream->offset); fprintf (stderr, "%s %s (%d dwords):\n", name, prim, len); fprintf (stderr, "\t0x%08x\n", ptr[0]); for (i = 1; i < len; i++) { if (dump_floats) fprintf (stderr, "\t0x%08x // %f\n", ptr[i], *(float *)&ptr[i]); else fprintf (stderr, "\t0x%08x\n", ptr[i]); } fprintf (stderr, "\n"); stream->offset += len * sizeof(uint32_t); return TRUE; } static const char *opcodes[] = { "NOP", "ADD", "MOV", "MUL", "MAD", "DP2ADD", "DP3", "DP4", "FRC", "RCP", "RSQ", "EXP", "LOG", "CMP", "MIN", "MAX", "FLR", "MOD", "TRC", "SGE", "SLT", "TEXLD", "TEXLDP", "TEXLDB", "TEXKILL", "DCL", "0x1a", "0x1b", "0x1c", "0x1d", "0x1e", "0x1f", }; static const int args[] = { 0, /* 0 nop */ 2, /* 1 add */ 1, /* 2 mov */ 2, /* 3 m ul */ 3, /* 4 mad */ 3, /* 5 dp2add */ 2, /* 6 dp3 */ 2, /* 7 dp4 */ 1, /* 8 frc */ 1, /* 9 rcp */ 1, /* a rsq */ 1, /* b exp */ 1, /* c log */ 3, /* d cmp */ 2, /* e min */ 2, /* f max */ 1, /* 10 flr */ 1, /* 11 mod */ 1, /* 12 trc */ 2, /* 13 sge */ 2, /* 14 slt */ 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, }; static const char *regname[] = { "R", "T", "CONST", "S", "OC", "OD", "U", "UNKNOWN", }; static void print_reg_type_nr(uint32_t type, uint32_t nr) { switch (type) { case REG_TYPE_T: switch (nr) { case T_DIFFUSE: fprintf (stderr, "T_DIFFUSE"); return; case T_SPECULAR: fprintf (stderr, "T_SPECULAR"); return; case T_FOG_W: fprintf (stderr, "T_FOG_W"); return; default: fprintf (stderr, "T_TEX%d", nr); return; } case REG_TYPE_OC: if (nr == 0) { fprintf (stderr, "oC"); return; } break; case REG_TYPE_OD: if (nr == 0) { fprintf (stderr, "oD"); return; } break; default: break; } fprintf (stderr, "%s[%d]", regname[type], nr); } #define REG_SWIZZLE_MASK 0x7777 #define REG_NEGATE_MASK 0x8888 #define REG_SWIZZLE_XYZW ((SRC_X << A2_SRC2_CHANNEL_X_SHIFT) | \ (SRC_Y << A2_SRC2_CHANNEL_Y_SHIFT) | \ (SRC_Z << A2_SRC2_CHANNEL_Z_SHIFT) | \ (SRC_W << A2_SRC2_CHANNEL_W_SHIFT)) static void print_reg_neg_swizzle(uint32_t reg) { int i; if ((reg & REG_SWIZZLE_MASK) == REG_SWIZZLE_XYZW && (reg & REG_NEGATE_MASK) == 0) return; fprintf (stderr, "."); for (i = 12; i >= 0; i -= 4) { if (reg & (8 << i)) fprintf (stderr, "-"); switch ((reg >> i) & 0x7) { case 0: fprintf (stderr, "x"); break; case 1: fprintf (stderr, "y"); break; case 2: fprintf (stderr, "z"); break; case 3: fprintf (stderr, "w"); break; case 4: fprintf (stderr, "0"); break; case 5: fprintf (stderr, "1"); break; default: fprintf (stderr, "?"); break; } } } static void print_src_reg(uint32_t dword) { uint32_t nr = (dword >> A2_SRC2_NR_SHIFT) & REG_NR_MASK; uint32_t type = (dword >> A2_SRC2_TYPE_SHIFT) & REG_TYPE_MASK; print_reg_type_nr(type, nr); print_reg_neg_swizzle(dword); } static void print_dest_reg(uint32_t dword) { uint32_t nr = (dword >> A0_DEST_NR_SHIFT) & REG_NR_MASK; uint32_t type = (dword >> A0_DEST_TYPE_SHIFT) & REG_TYPE_MASK; print_reg_type_nr(type, nr); if ((dword & A0_DEST_CHANNEL_ALL) == A0_DEST_CHANNEL_ALL) return; fprintf (stderr, "."); if (dword & A0_DEST_CHANNEL_X) fprintf (stderr, "x"); if (dword & A0_DEST_CHANNEL_Y) fprintf (stderr, "y"); if (dword & A0_DEST_CHANNEL_Z) fprintf (stderr, "z"); if (dword & A0_DEST_CHANNEL_W) fprintf (stderr, "w"); } #define GET_SRC0_REG(r0, r1) ((r0<<14)|(r1>>A1_SRC0_CHANNEL_W_SHIFT)) #define GET_SRC1_REG(r0, r1) ((r0<<8)|(r1>>A2_SRC1_CHANNEL_W_SHIFT)) #define GET_SRC2_REG(r) (r) static void print_arith_op(uint32_t opcode, const uint32_t * program) { if (opcode != A0_NOP) { print_dest_reg(program[0]); if (program[0] & A0_DEST_SATURATE) fprintf (stderr, " = SATURATE "); else fprintf (stderr, " = "); } fprintf (stderr, "%s ", opcodes[opcode]); print_src_reg(GET_SRC0_REG(program[0], program[1])); if (args[opcode] == 1) { fprintf (stderr, "\n"); return; } fprintf (stderr, ", "); print_src_reg(GET_SRC1_REG(program[1], program[2])); if (args[opcode] == 2) { fprintf (stderr, "\n"); return; } fprintf (stderr, ", "); print_src_reg(GET_SRC2_REG(program[2])); fprintf (stderr, "\n"); return; } static void print_tex_op(uint32_t opcode, const uint32_t * program) { print_dest_reg(program[0] | A0_DEST_CHANNEL_ALL); fprintf (stderr, " = "); fprintf (stderr, "%s ", opcodes[opcode]); fprintf (stderr, "S[%d],", program[0] & T0_SAMPLER_NR_MASK); print_reg_type_nr((program[1] >> T1_ADDRESS_REG_TYPE_SHIFT) & REG_TYPE_MASK, (program[1] >> T1_ADDRESS_REG_NR_SHIFT) & REG_NR_MASK); fprintf (stderr, "\n"); } static void print_dcl_op(uint32_t opcode, const uint32_t * program) { fprintf (stderr, "%s ", opcodes[opcode]); print_dest_reg(program[0] | A0_DEST_CHANNEL_ALL); fprintf (stderr, "\n"); } static void i915_disassemble_program (const uint32_t * program, uint32_t sz) { uint32_t size = program[0] & 0x1ff; uint32_t i; fprintf (stderr, "\tPROGRAM\n"); assert(size + 2 == sz); program++; for (i = 1; i < sz; i += 3, program += 3) { uint32_t opcode = program[0] & (0x1f << 24); fprintf (stderr, "\t\t"); if ((int) opcode >= A0_NOP && opcode <= A0_SLT) print_arith_op(opcode >> 24, program); else if (opcode >= T0_TEXLD && opcode <= T0_TEXKILL) print_tex_op(opcode >> 24, program); else if (opcode == D0_DCL) print_dcl_op(opcode >> 24, program); else fprintf (stderr, "Unknown opcode 0x%x\n", opcode); } fprintf (stderr, "\tEND-PROGRAM\n\n"); } static cairo_bool_t debug_program (struct debug_stream *stream, const char *name, uint32_t len) { uint32_t *ptr = (uint32_t *)(stream->ptr + stream->offset); if (len == 0) { fprintf (stderr, "Error - zero length packet (0x%08x)\n", stream->ptr[0]); ASSERT_NOT_REACHED; return FALSE; } fprintf (stderr, "%04x: ", stream->offset); fprintf (stderr, "%s (%d dwords):\n", name, len); i915_disassemble_program (ptr, len); stream->offset += len * sizeof(uint32_t); return TRUE; } static cairo_bool_t debug_chain (struct debug_stream *stream, const char *name, uint32_t len) { uint32_t *ptr = (uint32_t *)(stream->ptr + stream->offset); uint32_t old_offset = stream->offset + len * sizeof(uint32_t); uint32_t i; fprintf (stderr, "%s (%d dwords):\n", name, len); for (i = 0; i < len; i++) fprintf (stderr, "\t0x%08x\n", ptr[i]); stream->offset = ptr[1] & ~0x3; if (stream->offset < old_offset) fprintf (stderr, "\n... skipping backwards from 0x%x --> 0x%x ...\n\n", old_offset, stream->offset ); else fprintf (stderr, "\n... skipping from 0x%x --> 0x%x ...\n\n", old_offset, stream->offset ); return TRUE; } static cairo_bool_t debug_variable_length_prim (struct debug_stream *stream) { uint32_t *ptr = (uint32_t *)(stream->ptr + stream->offset); const char *prim = get_prim_name( ptr[0] ); uint32_t i, len; uint16_t *idx = (uint16_t *)(ptr+1); for (i = 0; idx[i] != 0xffff; i++) ; len = 1+(i+2)/2; fprintf (stderr, "%04x: ", stream->offset); fprintf (stderr, "3DPRIM, %s variable length %d indices (%d dwords):\n", prim, i, len); for (i = 0; i < len; i++) fprintf (stderr, "\t0x%08x\n", ptr[i]); fprintf (stderr, "\n"); stream->offset += len * sizeof(uint32_t); return TRUE; } #define BITS(dw, hi, lo, ...) \ do { \ unsigned himask = 0xffffffffU >> (31 - (hi)); \ fprintf (stderr, "\t\t "); \ fprintf (stderr, __VA_ARGS__); \ fprintf (stderr, ": 0x%x\n", ((dw) & himask) >> (lo)); \ } while (0) #define MBZ(dw, hi, lo) do { \ unsigned x = (dw) >> (lo); \ unsigned lomask = (1 << (lo)) - 1; \ unsigned himask; \ himask = (1UL << (hi)) - 1; \ assert ((x & himask & ~lomask) == 0); \ } while (0) #define FLAG(dw, bit, ... ) \ do { \ if (((dw) >> (bit)) & 1) { \ fprintf (stderr, "\t\t "); \ fprintf (stderr, __VA_ARGS__); \ fprintf (stderr, "\n"); \ } \ } while (0) static cairo_bool_t debug_load_immediate (struct debug_stream *stream, const char *name, uint32_t len) { uint32_t *ptr = (uint32_t *)(stream->ptr + stream->offset); uint32_t bits = (ptr[0] >> 4) & 0xff; uint32_t j = 0; fprintf (stderr, "%04x: ", stream->offset); fprintf (stderr, "%s (%d dwords, flags: %x):\n", name, len, bits); fprintf (stderr, "\t0x%08x\n", ptr[j++]); if (bits & (1<<0)) { fprintf (stderr, "\t LIS0: 0x%08x\n", ptr[j]); fprintf (stderr, "\t vb address: 0x%08x\n", (ptr[j] & ~0x3)); BITS (ptr[j], 0, 0, "vb invalidate disable"); j++; } if (bits & (1<<1)) { fprintf (stderr, "\t LIS1: 0x%08x\n", ptr[j]); BITS (ptr[j], 29, 24, "vb dword width"); BITS (ptr[j], 21, 16, "vb dword pitch"); BITS (ptr[j], 15, 0, "vb max index"); j++; } if (bits & (1<<2)) { int i; fprintf (stderr, "\t LIS2: 0x%08x\n", ptr[j]); for (i = 0; i < 8; i++) { unsigned tc = (ptr[j] >> (i * 4)) & 0xf; if (tc != 0xf) BITS (tc, 3, 0, "tex coord %d", i); } j++; } if (bits & (1<<3)) { fprintf (stderr, "\t LIS3: 0x%08x\n", ptr[j]); j++; } if (bits & (1<<4)) { fprintf (stderr, "\t LIS4: 0x%08x\n", ptr[j]); BITS (ptr[j], 31, 23, "point width"); BITS (ptr[j], 22, 19, "line width"); FLAG (ptr[j], 18, "alpha flatshade"); FLAG (ptr[j], 17, "fog flatshade"); FLAG (ptr[j], 16, "spec flatshade"); FLAG (ptr[j], 15, "rgb flatshade"); BITS (ptr[j], 14, 13, "cull mode"); FLAG (ptr[j], 12, "vfmt: point width"); FLAG (ptr[j], 11, "vfmt: specular/fog"); FLAG (ptr[j], 10, "vfmt: rgba"); FLAG (ptr[j], 9, "vfmt: depth offset"); BITS (ptr[j], 8, 6, "vfmt: position (2==xyzw)"); FLAG (ptr[j], 5, "force dflt diffuse"); FLAG (ptr[j], 4, "force dflt specular"); FLAG (ptr[j], 3, "local depth offset enable"); FLAG (ptr[j], 2, "vfmt: fp32 fog coord"); FLAG (ptr[j], 1, "sprite point"); FLAG (ptr[j], 0, "antialiasing"); j++; } if (bits & (1<<5)) { fprintf (stderr, "\t LIS5: 0x%08x\n", ptr[j]); BITS (ptr[j], 31, 28, "rgba write disables"); FLAG (ptr[j], 27, "force dflt point width"); FLAG (ptr[j], 26, "last pixel enable"); FLAG (ptr[j], 25, "global z offset enable"); FLAG (ptr[j], 24, "fog enable"); BITS (ptr[j], 23, 16, "stencil ref"); BITS (ptr[j], 15, 13, "stencil test"); BITS (ptr[j], 12, 10, "stencil fail op"); BITS (ptr[j], 9, 7, "stencil pass z fail op"); BITS (ptr[j], 6, 4, "stencil pass z pass op"); FLAG (ptr[j], 3, "stencil write enable"); FLAG (ptr[j], 2, "stencil test enable"); FLAG (ptr[j], 1, "color dither enable"); FLAG (ptr[j], 0, "logiop enable"); j++; } if (bits & (1<<6)) { fprintf (stderr, "\t LIS6: 0x%08x\n", ptr[j]); FLAG (ptr[j], 31, "alpha test enable"); BITS (ptr[j], 30, 28, "alpha func"); BITS (ptr[j], 27, 20, "alpha ref"); FLAG (ptr[j], 19, "depth test enable"); BITS (ptr[j], 18, 16, "depth func"); FLAG (ptr[j], 15, "blend enable"); BITS (ptr[j], 14, 12, "blend func"); BITS (ptr[j], 11, 8, "blend src factor"); BITS (ptr[j], 7, 4, "blend dst factor"); FLAG (ptr[j], 3, "depth write enable"); FLAG (ptr[j], 2, "color write enable"); BITS (ptr[j], 1, 0, "provoking vertex"); j++; } fprintf (stderr, "\n"); assert(j == len); stream->offset += len * sizeof(uint32_t); return TRUE; } static cairo_bool_t debug_load_indirect (struct debug_stream *stream, const char *name, uint32_t len) { uint32_t *ptr = (uint32_t *)(stream->ptr + stream->offset); uint32_t bits = (ptr[0] >> 8) & 0x3f; uint32_t i, j = 0; fprintf (stderr, "%04x: ", stream->offset); fprintf (stderr, "%s (%d dwords):\n", name, len); fprintf (stderr, "\t0x%08x\n", ptr[j++]); for (i = 0; i < 6; i++) { if (bits & (1<<i)) { switch (1<<(8+i)) { case LI0_STATE_STATIC_INDIRECT: fprintf (stderr, " STATIC: 0x%08x | %x\n", ptr[j]&~3, ptr[j]&3); j++; fprintf (stderr, " 0x%08x\n", ptr[j++]); break; case LI0_STATE_DYNAMIC_INDIRECT: fprintf (stderr, " DYNAMIC: 0x%08x | %x\n", ptr[j]&~3, ptr[j]&3); j++; break; case LI0_STATE_SAMPLER: fprintf (stderr, " SAMPLER: 0x%08x | %x\n", ptr[j]&~3, ptr[j]&3); j++; fprintf (stderr, " 0x%08x\n", ptr[j++]); break; case LI0_STATE_MAP: fprintf (stderr, " MAP: 0x%08x | %x\n", ptr[j]&~3, ptr[j]&3); j++; fprintf (stderr, " 0x%08x\n", ptr[j++]); break; case LI0_STATE_PROGRAM: fprintf (stderr, " PROGRAM: 0x%08x | %x\n", ptr[j]&~3, ptr[j]&3); j++; fprintf (stderr, " 0x%08x\n", ptr[j++]); break; case LI0_STATE_CONSTANTS: fprintf (stderr, " CONSTANTS: 0x%08x | %x\n", ptr[j]&~3, ptr[j]&3); j++; fprintf (stderr, " 0x%08x\n", ptr[j++]); break; default: ASSERT_NOT_REACHED; break; } } } if (bits == 0) { fprintf (stderr, "\t DUMMY: 0x%08x\n", ptr[j++]); } fprintf (stderr, "\n"); assert(j == len); stream->offset += len * sizeof(uint32_t); return TRUE; } static void BR13 (struct debug_stream *stream, uint32_t val) { fprintf (stderr, "\t0x%08x\n", val); FLAG (val, 30, "clipping enable"); BITS (val, 25, 24, "color depth (3==32bpp)"); BITS (val, 23, 16, "raster op"); BITS (val, 15, 0, "dest pitch"); } static void BR2223 (struct debug_stream *stream, uint32_t val22, uint32_t val23) { union { uint32_t val; short field[2]; } BR22, BR23; BR22.val = val22; BR23.val = val23; fprintf (stderr, "\t0x%08x\n", val22); BITS (val22, 31, 16, "dest y1"); BITS (val22, 15, 0, "dest x1"); fprintf (stderr, "\t0x%08x\n", val23); BITS (val23, 31, 16, "dest y2"); BITS (val23, 15, 0, "dest x2"); /* The blit engine may produce unexpected results when these aren't met */ assert(BR22.field[0] < BR23.field[0]); assert(BR22.field[1] < BR23.field[1]); } static void BR09 (struct debug_stream *stream, uint32_t val) { fprintf (stderr, "\t0x%08x -- dest address\n", val); } static void BR26 (struct debug_stream *stream, uint32_t val) { fprintf (stderr, "\t0x%08x\n", val); BITS (val, 31, 16, "src y1"); BITS (val, 15, 0, "src x1"); } static void BR11 (struct debug_stream *stream, uint32_t val) { fprintf (stderr, "\t0x%08x\n", val); BITS (val, 15, 0, "src pitch"); } static void BR12 (struct debug_stream *stream, uint32_t val) { fprintf (stderr, "\t0x%08x -- src address\n", val); } static void BR16 (struct debug_stream *stream, uint32_t val) { fprintf (stderr, "\t0x%08x -- color\n", val); } static cairo_bool_t debug_copy_blit (struct debug_stream *stream, const char *name, uint32_t len) { uint32_t *ptr = (uint32_t *)(stream->ptr + stream->offset); uint32_t j = 0; fprintf (stderr, "%04x: ", stream->offset); fprintf (stderr, "%s (%d dwords):\n", name, len); fprintf (stderr, "\t0x%08x\n", ptr[j++]); BR13(stream, ptr[j++]); BR2223(stream, ptr[j], ptr[j+1]); j += 2; BR09(stream, ptr[j++]); BR26(stream, ptr[j++]); BR11(stream, ptr[j++]); BR12(stream, ptr[j++]); stream->offset += len * sizeof(uint32_t); assert(j == len); return TRUE; } static cairo_bool_t debug_color_blit (struct debug_stream *stream, const char *name, uint32_t len) { uint32_t *ptr = (uint32_t *)(stream->ptr + stream->offset); uint32_t j = 0; fprintf (stderr, "%04x: ", stream->offset); fprintf (stderr, "%s (%d dwords):\n", name, len); fprintf (stderr, "\t0x%08x\n", ptr[j++]); BR13(stream, ptr[j++]); BR2223(stream, ptr[j], ptr[j+1]); j += 2; BR09(stream, ptr[j++]); BR16(stream, ptr[j++]); stream->offset += len * sizeof(uint32_t); assert(j == len); return TRUE; } static cairo_bool_t debug_modes4 (struct debug_stream *stream, const char *name, uint32_t len) { uint32_t *ptr = (uint32_t *)(stream->ptr + stream->offset); uint32_t j = 0; fprintf (stderr, "%04x: ", stream->offset); fprintf (stderr, "%s (%d dwords):\n", name, len); fprintf (stderr, "\t0x%08x\n", ptr[j]); BITS (ptr[j], 21, 18, "logicop func"); FLAG (ptr[j], 17, "stencil test mask modify-enable"); FLAG (ptr[j], 16, "stencil write mask modify-enable"); BITS (ptr[j], 15, 8, "stencil test mask"); BITS (ptr[j], 7, 0, "stencil write mask"); fprintf (stderr, "\n"); j++; stream->offset += len * sizeof(uint32_t); assert(j == len); return TRUE; } static cairo_bool_t debug_map_state (struct debug_stream *stream, const char *name, uint32_t len) { uint32_t *ptr = (uint32_t *)(stream->ptr + stream->offset); uint32_t j = 0; fprintf (stderr, "%04x: ", stream->offset); fprintf (stderr, "%s (%d dwords):\n", name, len); fprintf (stderr, "\t0x%08x\n", ptr[j++]); { fprintf (stderr, "\t0x%08x\n", ptr[j]); BITS (ptr[j], 15, 0, "map mask"); j++; } while (j < len) { { fprintf (stderr, "\t TMn.0: 0x%08x\n", ptr[j]); fprintf (stderr, "\t map address: 0x%08x\n", (ptr[j] & ~0x3)); FLAG (ptr[j], 1, "vertical line stride"); FLAG (ptr[j], 0, "vertical line stride offset"); j++; } { fprintf (stderr, "\t TMn.1: 0x%08x\n", ptr[j]); BITS (ptr[j], 31, 21, "height"); BITS (ptr[j], 20, 10, "width"); BITS (ptr[j], 9, 7, "surface format"); BITS (ptr[j], 6, 3, "texel format"); FLAG (ptr[j], 2, "use fence regs"); FLAG (ptr[j], 1, "tiled surface"); FLAG (ptr[j], 0, "tile walk ymajor"); j++; } { fprintf (stderr, "\t TMn.2: 0x%08x\n", ptr[j]); BITS (ptr[j], 31, 21, "dword pitch"); BITS (ptr[j], 20, 15, "cube face enables"); BITS (ptr[j], 14, 9, "max lod"); FLAG (ptr[j], 8, "mip layout right"); BITS (ptr[j], 7, 0, "depth"); j++; } } stream->offset += len * sizeof(uint32_t); assert(j == len); return TRUE; } static cairo_bool_t debug_sampler_state (struct debug_stream *stream, const char *name, uint32_t len) { uint32_t *ptr = (uint32_t *)(stream->ptr + stream->offset); uint32_t j = 0; fprintf (stderr, "%04x: ", stream->offset); fprintf (stderr, "%s (%d dwords):\n", name, len); fprintf (stderr, "\t0x%08x\n", ptr[j++]); { fprintf (stderr, "\t0x%08x\n", ptr[j]); BITS (ptr[j], 15, 0, "sampler mask"); j++; } while (j < len) { { fprintf (stderr, "\t TSn.0: 0x%08x\n", ptr[j]); FLAG (ptr[j], 31, "reverse gamma"); FLAG (ptr[j], 30, "planar to packed"); FLAG (ptr[j], 29, "yuv->rgb"); BITS (ptr[j], 28, 27, "chromakey index"); BITS (ptr[j], 26, 22, "base mip level"); BITS (ptr[j], 21, 20, "mip mode filter"); BITS (ptr[j], 19, 17, "mag mode filter"); BITS (ptr[j], 16, 14, "min mode filter"); BITS (ptr[j], 13, 5, "lod bias (s4.4)"); FLAG (ptr[j], 4, "shadow enable"); FLAG (ptr[j], 3, "max-aniso-4"); BITS (ptr[j], 2, 0, "shadow func"); j++; } { fprintf (stderr, "\t TSn.1: 0x%08x\n", ptr[j]); BITS (ptr[j], 31, 24, "min lod"); MBZ( ptr[j], 23, 18 ); FLAG (ptr[j], 17, "kill pixel enable"); FLAG (ptr[j], 16, "keyed tex filter mode"); FLAG (ptr[j], 15, "chromakey enable"); BITS (ptr[j], 14, 12, "tcx wrap mode"); BITS (ptr[j], 11, 9, "tcy wrap mode"); BITS (ptr[j], 8, 6, "tcz wrap mode"); FLAG (ptr[j], 5, "normalized coords"); BITS (ptr[j], 4, 1, "map (surface) index"); FLAG (ptr[j], 0, "EAST deinterlacer enable"); j++; } { fprintf (stderr, "\t TSn.2: 0x%08x (default color)\n", ptr[j]); j++; } } stream->offset += len * sizeof(uint32_t); assert(j == len); return TRUE; } static cairo_bool_t debug_dest_vars (struct debug_stream *stream, const char *name, uint32_t len) { uint32_t *ptr = (uint32_t *)(stream->ptr + stream->offset); uint32_t j = 0; fprintf (stderr, "%04x: ", stream->offset); fprintf (stderr, "%s (%d dwords):\n", name, len); fprintf (stderr, "\t0x%08x\n", ptr[j++]); { fprintf (stderr, "\t0x%08x\n", ptr[j]); FLAG (ptr[j], 31, "early classic ztest"); FLAG (ptr[j], 30, "opengl tex default color"); FLAG (ptr[j], 29, "bypass iz"); FLAG (ptr[j], 28, "lod preclamp"); BITS (ptr[j], 27, 26, "dither pattern"); FLAG (ptr[j], 25, "linear gamma blend"); FLAG (ptr[j], 24, "debug dither"); BITS (ptr[j], 23, 20, "dstorg x"); BITS (ptr[j], 19, 16, "dstorg y"); MBZ (ptr[j], 15, 15 ); BITS (ptr[j], 14, 12, "422 write select"); BITS (ptr[j], 11, 8, "cbuf format"); BITS (ptr[j], 3, 2, "zbuf format"); FLAG (ptr[j], 1, "vert line stride"); FLAG (ptr[j], 1, "vert line stride offset"); j++; } stream->offset += len * sizeof(uint32_t); assert(j == len); return TRUE; } static cairo_bool_t debug_buf_info( struct debug_stream *stream, const char *name, uint32_t len ) { uint32_t *ptr = (uint32_t *)(stream->ptr + stream->offset); uint32_t j = 0; fprintf (stderr, "%04x: ", stream->offset); fprintf (stderr, "%s (%d dwords):\n", name, len); fprintf (stderr, "\t0x%08x\n", ptr[j++]); { fprintf (stderr, "\t0x%08x\n", ptr[j]); BITS (ptr[j], 28, 28, "aux buffer id"); BITS (ptr[j], 27, 24, "buffer id (7=depth, 3=back)"); FLAG (ptr[j], 23, "use fence regs"); FLAG (ptr[j], 22, "tiled surface"); FLAG (ptr[j], 21, "tile walk ymajor"); MBZ (ptr[j], 20, 14); BITS (ptr[j], 13, 2, "dword pitch"); MBZ (ptr[j], 2, 0); j++; } fprintf (stderr, "\t0x%08x -- buffer base address\n", ptr[j++]); stream->offset += len * sizeof(uint32_t); assert(j == len); return TRUE; } static cairo_bool_t decode_3d_i915 (struct debug_stream *stream) { uint32_t *ptr = (uint32_t *)(stream->ptr + stream->offset); uint32_t cmd = *ptr; switch ((cmd >> 24) & 0x1f) { case 0x6: return debug (stream, "3DSTATE_ANTI_ALIASING", 1); case 0x7: return debug (stream, "3DSTATE_RASTERIZATION_RULES", 1); case 0x8: return debug (stream, "3DSTATE_BACKFACE_STENCIL_OPS", 1); case 0x9: return debug (stream, "3DSTATE_BACKFACE_STENCIL_MASKS", 1); case 0xb: return debug (stream, "3DSTATE_INDEPENDENT_ALPHA_BLEND", 1); case 0xc: return debug (stream, "3DSTATE_MODES5", 1); case 0xd: return debug_modes4(stream, "3DSTATE_MODES4", 1); case 0x15: return debug (stream, "3DSTATE_FOG_COLOR", 1); case 0x16: return debug (stream, "3DSTATE_COORD_SET_BINDINGS", 1); case 0x1c: /* 3DState16NP */ switch((cmd >> 19) & 0x1f) { case 0x10: return debug (stream, "3DSTATE_SCISSOR_ENABLE", 1); case 0x11: return debug (stream, "3DSTATE_DEPTH_SUBRECTANGLE_DISABLE", 1); default: break; } break; case 0x1d: /* 3DStateMW */ switch ((cmd >> 16) & 0xff) { case 0x0: return debug_map_state(stream, "3DSTATE_MAP_STATE", (cmd & 0x1f) + 2); case 0x1: return debug_sampler_state(stream, "3DSTATE_SAMPLER_STATE", (cmd & 0x1f) + 2); case 0x4: return debug_load_immediate(stream, "3DSTATE_LOAD_STATE_IMMEDIATE", (cmd & 0xf) + 2); case 0x5: return debug_program(stream, "3DSTATE_PIXEL_SHADER_PROGRAM", (cmd & 0x1ff) + 2); case 0x6: return debug (stream, "3DSTATE_PIXEL_SHADER_CONSTANTS", (cmd & 0xff) + 2); case 0x7: return debug_load_indirect(stream, "3DSTATE_LOAD_INDIRECT", (cmd & 0xff) + 2); case 0x80: return debug (stream, "3DSTATE_DRAWING_RECTANGLE", (cmd & 0xffff) + 2); case 0x81: return debug (stream, "3DSTATE_SCISSOR_RECTANGLE", (cmd & 0xffff) + 2); case 0x83: return debug (stream, "3DSTATE_SPAN_STIPPLE", (cmd & 0xffff) + 2); case 0x85: return debug_dest_vars(stream, "3DSTATE_DEST_BUFFER_VARS", (cmd & 0xffff) + 2); case 0x88: return debug (stream, "3DSTATE_CONSTANT_BLEND_COLOR", (cmd & 0xffff) + 2); case 0x89: return debug (stream, "3DSTATE_FOG_MODE", (cmd & 0xffff) + 2); case 0x8e: return debug_buf_info(stream, "3DSTATE_BUFFER_INFO", (cmd & 0xffff) + 2); case 0x97: return debug (stream, "3DSTATE_DEPTH_OFFSET_SCALE", (cmd & 0xffff) + 2); case 0x98: return debug (stream, "3DSTATE_DEFAULT_Z", (cmd & 0xffff) + 2); case 0x99: return debug (stream, "3DSTATE_DEFAULT_DIFFUSE", (cmd & 0xffff) + 2); case 0x9a: return debug (stream, "3DSTATE_DEFAULT_SPECULAR", (cmd & 0xffff) + 2); case 0x9c: return debug (stream, "3DSTATE_CLEAR_PARAMETERS", (cmd & 0xffff) + 2); default: ASSERT_NOT_REACHED; return 0; } break; case 0x1e: if (cmd & (1 << 23)) return debug (stream, "???", (cmd & 0xffff) + 1); else return debug (stream, "", 1); break; case 0x1f: if ((cmd & (1 << 23)) == 0) { return debug_prim (stream, "3DPRIM (inline)", 1, (cmd & 0x1ffff) + 2); } else if (cmd & (1 << 17)) { if ((cmd & 0xffff) == 0) return debug_variable_length_prim (stream); else return debug_prim (stream, "3DPRIM (indexed)", 0, (((cmd & 0xffff) + 1) / 2) + 1); } else return debug_prim (stream, "3DPRIM (indirect sequential)", 0, 2); break; default: return debug (stream, "", 0); } return FALSE; } static cairo_bool_t decode_3d_i965 (struct debug_stream *stream) { const uint32_t *data = (uint32_t *) (stream->ptr + stream->offset); const uint32_t opcode = (data[0] & 0xffff0000) >> 16; unsigned int idx; const struct { uint32_t opcode; int min_len; int max_len; const char *name; } opcodes_3d[] = { { 0x6000, 3, 3, "URB_FENCE" }, { 0x6001, 2, 2, "CS_URB_STATE" }, { 0x6002, 2, 2, "CONSTANT_BUFFER" }, { 0x6101, 6, 6, "STATE_BASE_ADDRESS" }, { 0x6102, 2, 2 , "STATE_SIP" }, { 0x6104, 1, 1, "3DSTATE_PIPELINE_SELECT" }, { 0x680b, 1, 1, "3DSTATE_VF_STATISTICS" }, { 0x6904, 1, 1, "3DSTATE_PIPELINE_SELECT" }, { 0x7800, 7, 7, "3DSTATE_PIPELINED_POINTERS" }, { 0x7801, 6, 6, "3DSTATE_BINDING_TABLE_POINTERS" }, { 0x780b, 1, 1, "3DSTATE_VF_STATISTICS" }, { 0x7808, 5, 257, "3DSTATE_VERTEX_BUFFERS" }, { 0x7809, 3, 256, "3DSTATE_VERTEX_ELEMENTS" }, { 0x780a, 3, 3, "3DSTATE_INDEX_BUFFER" }, { 0x7900, 4, 4, "3DSTATE_DRAWING_RECTANGLE" }, { 0x7901, 5, 5, "3DSTATE_CONSTANT_COLOR" }, { 0x7905, 5, 7, "3DSTATE_DEPTH_BUFFER" }, { 0x7906, 2, 2, "3DSTATE_POLY_STIPPLE_OFFSET" }, { 0x7907, 33, 33, "3DSTATE_POLY_STIPPLE_PATTERN" }, { 0x7908, 3, 3, "3DSTATE_LINE_STIPPLE" }, { 0x7909, 2, 2, "3DSTATE_GLOBAL_DEPTH_OFFSET_CLAMP" }, { 0x790a, 3, 3, "3DSTATE_AA_LINE_PARAMETERS" }, { 0x7b00, 6, 6, "3DPRIMITIVE" }, }, *opcode_3d; for (idx = 0; idx < ARRAY_LENGTH (opcodes_3d); idx++) { opcode_3d = &opcodes_3d[idx]; if (opcode == opcode_3d->opcode) { unsigned int len = 1; if (opcode_3d->max_len != 1) len = (data[0] & 0x000000ff) + 2; return debug (stream, opcode_3d->name, len); } } return FALSE; } static cairo_bool_t decode_3d_i830 (struct debug_stream *stream) { ASSERT_NOT_REACHED; return FALSE; } static cairo_bool_t i915_debug_packet (struct debug_stream *stream, int devid) { uint32_t *ptr = (uint32_t *)(stream->ptr + stream->offset); uint32_t cmd = *ptr; switch (((cmd >> 29) & 0x7)) { case 0x0: switch ((cmd >> 23) & 0x3f) { case 0x0: return debug (stream, "MI_NOOP", 1); case 0x3: return debug (stream, "MI_WAIT_FOR_EVENT", 1); case 0x4: return debug (stream, "MI_FLUSH", 1); case 0xA: debug (stream, "MI_BATCH_BUFFER_END", 1); return FALSE; case 0x22: return debug (stream, "MI_LOAD_REGISTER_IMM", 3); case 0x31: return debug_chain(stream, "MI_BATCH_BUFFER_START", 2); default: break; } break; case 0x1: break; case 0x2: switch ((cmd >> 22) & 0xff) { case 0x50: return debug_color_blit(stream, "XY_COLOR_BLT", (cmd & 0xff) + 2); case 0x53: return debug_copy_blit(stream, "XY_SRC_COPY_BLT", (cmd & 0xff) + 2); default: return debug (stream, "blit command", (cmd & 0xff) + 2); } break; case 0x3: if (IS_965(devid)) return decode_3d_i965 (stream); else if (IS_9XX(devid)) return decode_3d_i915 (stream); else return decode_3d_i830 (stream); default: break; } fprintf (stderr, "Bogus cmd: %x [%x]\n", (cmd >> 29) & 7, cmd); ASSERT_NOT_REACHED; return 0; } void intel_dump_batchbuffer (const void *batch, uint32_t length, int devid) { struct debug_stream stream; cairo_bool_t done = FALSE; fprintf (stderr, "\nBATCH: (%d dwords)\n", length / 4); stream.offset = 0; stream.ptr = batch; while (! done && stream.offset < length) { if (! i915_debug_packet (&stream, devid)) break; assert (stream.offset <= length); } fprintf (stderr, "END-BATCH\n\n"); fflush (stderr); }
8739937139368dda06329aeb9c1e9fd488f51231
b7d4fc29e02e1379b0d44a756b4697dc19f8a792
/deps/boost/tools/build/src/engine/boehm_gc/include/gc_pthread_redirects.h
b567f63e14f0efd1b6a140162df4e694369ce976
[ "BSL-1.0", "GPL-1.0-or-later", "MIT", "Boehm-GC" ]
permissive
vslavik/poedit
45140ca86a853db58ddcbe65ab588da3873c4431
1b0940b026b429a10f310d98eeeaadfab271d556
refs/heads/master
2023-08-29T06:24:16.088676
2023-08-14T15:48:18
2023-08-14T15:48:18
477,156
1,424
275
MIT
2023-09-01T16:57:47
2010-01-18T08:23:13
C++
UTF-8
C
false
false
1,986
h
gc_pthread_redirects.h
/* Our pthread support normally needs to intercept a number of thread */ /* calls. We arrange to do that here, if appropriate. */ #ifndef GC_PTHREAD_REDIRECTS_H #define GC_PTHREAD_REDIRECTS_H #if !defined(GC_USE_LD_WRAP) && defined(GC_PTHREADS) /* We need to intercept calls to many of the threads primitives, so */ /* that we can locate thread stacks and stop the world. */ /* Note also that the collector cannot always see thread specific data. */ /* Thread specific data should generally consist of pointers to */ /* uncollectable objects (allocated with GC_malloc_uncollectable, */ /* not the system malloc), which are deallocated using the destructor */ /* facility in thr_keycreate. Alternatively, keep a redundant pointer */ /* to thread specific data on the thread stack. */ # include <pthread.h> # include <signal.h> int GC_pthread_create(pthread_t *new_thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg); #ifndef GC_DARWIN_THREADS int GC_pthread_sigmask(int how, const sigset_t *set, sigset_t *oset); #endif int GC_pthread_join(pthread_t thread, void **retval); int GC_pthread_detach(pthread_t thread); #if defined(GC_OSF1_THREADS) \ && defined(_PTHREAD_USE_MANGLED_NAMES_) && !defined(_PTHREAD_USE_PTDNAM_) /* Unless the compiler supports #pragma extern_prefix, the Tru64 UNIX <pthread.h> redefines some POSIX thread functions to use mangled names. If so, undef them before redefining. */ # undef pthread_create # undef pthread_join # undef pthread_detach #endif # define pthread_create GC_pthread_create # define pthread_join GC_pthread_join # define pthread_detach GC_pthread_detach #ifndef GC_DARWIN_THREADS # ifdef pthread_sigmask # undef pthread_sigmask # endif /* pthread_sigmask */ # define pthread_sigmask GC_pthread_sigmask # define dlopen GC_dlopen #endif #endif /* GC_xxxxx_THREADS */ #endif /* GC_PTHREAD_REDIRECTS_H */
39db8c02839295ab2fc9b89fb0c586942fcfb83c
79d343002bb63a44f8ab0dbac0c9f4ec54078c3a
/lib/libc/include/any-linux-any/linux/netfilter/xt_u32.h
2853c70dddebde53f104021aee30c90e7213ea41
[ "MIT" ]
permissive
ziglang/zig
4aa75d8d3bcc9e39bf61d265fd84b7f005623fc5
f4c9e19bc3213c2bc7e03d7b06d7129882f39f6c
refs/heads/master
2023-08-31T13:16:45.980913
2023-08-31T05:50:29
2023-08-31T05:50:29
40,276,274
25,560
2,399
MIT
2023-09-14T21:09:50
2015-08-06T00:51:28
Zig
UTF-8
C
false
false
751
h
xt_u32.h
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_U32_H #define _XT_U32_H 1 #include <linux/types.h> enum xt_u32_ops { XT_U32_AND, XT_U32_LEFTSH, XT_U32_RIGHTSH, XT_U32_AT, }; struct xt_u32_location_element { __u32 number; __u8 nextop; }; struct xt_u32_value_element { __u32 min; __u32 max; }; /* * Any way to allow for an arbitrary number of elements? * For now, I settle with a limit of 10 each. */ #define XT_U32_MAXSIZE 10 struct xt_u32_test { struct xt_u32_location_element location[XT_U32_MAXSIZE+1]; struct xt_u32_value_element value[XT_U32_MAXSIZE+1]; __u8 nnums; __u8 nvalues; }; struct xt_u32 { struct xt_u32_test tests[XT_U32_MAXSIZE+1]; __u8 ntests; __u8 invert; }; #endif /* _XT_U32_H */
d7212b43bf9dea30723868a15f1dd5a7f6c9b3e8
03666e5f961946fc1a0ac67781ac1425562ef0d7
/src/tools/third_party/qtssh/ssh/ttymode-list.h
8fffe1c58be6fd03dcc6fc73fc8bceb055889c34
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
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
5,620
h
ttymode-list.h
/* * List of SSH terminal modes, indicating whether SSH types them as * char or boolean, and if they're boolean, which POSIX flags field of * a termios structure they appear in, and what bit mask removes them * (e.g. CS7 and CS8 aren't single bits). * * Sources: RFC 4254, SSH-1 RFC-1.2.31, POSIX 2017, and the Linux * termios manpage for flags not specified by POSIX. * * This is a separate header file rather than my usual style of a * parametric list macro, because in this case I need to be able to * #ifdef out each mode in case it's not defined on a particular * target system. * * If you want only the locally defined modes, #define * TTYMODES_LOCAL_ONLY before including this header. */ #if !defined TTYMODES_LOCAL_ONLY || defined VINTR TTYMODE_CHAR(INTR, 1, VINTR) #endif #if !defined TTYMODES_LOCAL_ONLY || defined VQUIT TTYMODE_CHAR(QUIT, 2, VQUIT) #endif #if !defined TTYMODES_LOCAL_ONLY || defined VERASE TTYMODE_CHAR(ERASE, 3, VERASE) #endif #if !defined TTYMODES_LOCAL_ONLY || defined VKILL TTYMODE_CHAR(KILL, 4, VKILL) #endif #if !defined TTYMODES_LOCAL_ONLY || defined VEOF TTYMODE_CHAR(EOF, 5, VEOF) #endif #if !defined TTYMODES_LOCAL_ONLY || defined VEOL TTYMODE_CHAR(EOL, 6, VEOL) #endif #if !defined TTYMODES_LOCAL_ONLY || defined VEOL2 TTYMODE_CHAR(EOL2, 7, VEOL2) #endif #if !defined TTYMODES_LOCAL_ONLY || defined VSTART TTYMODE_CHAR(START, 8, VSTART) #endif #if !defined TTYMODES_LOCAL_ONLY || defined VSTOP TTYMODE_CHAR(STOP, 9, VSTOP) #endif #if !defined TTYMODES_LOCAL_ONLY || defined VSUSP TTYMODE_CHAR(SUSP, 10, VSUSP) #endif #if !defined TTYMODES_LOCAL_ONLY || defined VDSUSP TTYMODE_CHAR(DSUSP, 11, VDSUSP) #endif #if !defined TTYMODES_LOCAL_ONLY || defined VREPRINT TTYMODE_CHAR(REPRINT, 12, VREPRINT) #endif #if !defined TTYMODES_LOCAL_ONLY || defined VWERASE TTYMODE_CHAR(WERASE, 13, VWERASE) #endif #if !defined TTYMODES_LOCAL_ONLY || defined VLNEXT TTYMODE_CHAR(LNEXT, 14, VLNEXT) #endif #if !defined TTYMODES_LOCAL_ONLY || defined VFLUSH TTYMODE_CHAR(FLUSH, 15, VFLUSH) #endif #if !defined TTYMODES_LOCAL_ONLY || defined VSWTCH TTYMODE_CHAR(SWTCH, 16, VSWTCH) #endif #if !defined TTYMODES_LOCAL_ONLY || defined VSTATUS TTYMODE_CHAR(STATUS, 17, VSTATUS) #endif #if !defined TTYMODES_LOCAL_ONLY || defined VDISCARD TTYMODE_CHAR(DISCARD, 18, VDISCARD) #endif #if !defined TTYMODES_LOCAL_ONLY || defined IGNPAR TTYMODE_FLAG(IGNPAR, 30, i, IGNPAR) #endif #if !defined TTYMODES_LOCAL_ONLY || defined PARMRK TTYMODE_FLAG(PARMRK, 31, i, PARMRK) #endif #if !defined TTYMODES_LOCAL_ONLY || defined INPCK TTYMODE_FLAG(INPCK, 32, i, INPCK) #endif #if !defined TTYMODES_LOCAL_ONLY || defined ISTRIP TTYMODE_FLAG(ISTRIP, 33, i, ISTRIP) #endif #if !defined TTYMODES_LOCAL_ONLY || defined INLCR TTYMODE_FLAG(INLCR, 34, i, INLCR) #endif #if !defined TTYMODES_LOCAL_ONLY || defined IGNCR TTYMODE_FLAG(IGNCR, 35, i, IGNCR) #endif #if !defined TTYMODES_LOCAL_ONLY || defined ICRNL TTYMODE_FLAG(ICRNL, 36, i, ICRNL) #endif #if !defined TTYMODES_LOCAL_ONLY || defined IUCLC TTYMODE_FLAG(IUCLC, 37, i, IUCLC) #endif #if !defined TTYMODES_LOCAL_ONLY || defined IXON TTYMODE_FLAG(IXON, 38, i, IXON) #endif #if !defined TTYMODES_LOCAL_ONLY || defined IXANY TTYMODE_FLAG(IXANY, 39, i, IXANY) #endif #if !defined TTYMODES_LOCAL_ONLY || defined IXOFF TTYMODE_FLAG(IXOFF, 40, i, IXOFF) #endif #if !defined TTYMODES_LOCAL_ONLY || defined IMAXBEL TTYMODE_FLAG(IMAXBEL, 41, i, IMAXBEL) #endif #if !defined TTYMODES_LOCAL_ONLY || defined IUTF8 TTYMODE_FLAG(IUTF8, 42, i, IUTF8) #endif #if !defined TTYMODES_LOCAL_ONLY || defined ISIG TTYMODE_FLAG(ISIG, 50, l, ISIG) #endif #if !defined TTYMODES_LOCAL_ONLY || defined ICANON TTYMODE_FLAG(ICANON, 51, l, ICANON) #endif #if !defined TTYMODES_LOCAL_ONLY || defined XCASE TTYMODE_FLAG(XCASE, 52, l, XCASE) #endif #if !defined TTYMODES_LOCAL_ONLY || defined ECHO TTYMODE_FLAG(ECHO, 53, l, ECHO) #endif #if !defined TTYMODES_LOCAL_ONLY || defined ECHOE TTYMODE_FLAG(ECHOE, 54, l, ECHOE) #endif #if !defined TTYMODES_LOCAL_ONLY || defined ECHOK TTYMODE_FLAG(ECHOK, 55, l, ECHOK) #endif #if !defined TTYMODES_LOCAL_ONLY || defined ECHONL TTYMODE_FLAG(ECHONL, 56, l, ECHONL) #endif #if !defined TTYMODES_LOCAL_ONLY || defined NOFLSH TTYMODE_FLAG(NOFLSH, 57, l, NOFLSH) #endif #if !defined TTYMODES_LOCAL_ONLY || defined TOSTOP TTYMODE_FLAG(TOSTOP, 58, l, TOSTOP) #endif #if !defined TTYMODES_LOCAL_ONLY || defined IEXTEN TTYMODE_FLAG(IEXTEN, 59, l, IEXTEN) #endif #if !defined TTYMODES_LOCAL_ONLY || defined ECHOCTL TTYMODE_FLAG(ECHOCTL, 60, l, ECHOCTL) #endif #if !defined TTYMODES_LOCAL_ONLY || defined ECHOKE TTYMODE_FLAG(ECHOKE, 61, l, ECHOKE) #endif #if !defined TTYMODES_LOCAL_ONLY || defined PENDIN TTYMODE_FLAG(PENDIN, 62, l, PENDIN) #endif #if !defined TTYMODES_LOCAL_ONLY || defined OPOST TTYMODE_FLAG(OPOST, 70, o, OPOST) #endif #if !defined TTYMODES_LOCAL_ONLY || defined OLCUC TTYMODE_FLAG(OLCUC, 71, o, OLCUC) #endif #if !defined TTYMODES_LOCAL_ONLY || defined ONLCR TTYMODE_FLAG(ONLCR, 72, o, ONLCR) #endif #if !defined TTYMODES_LOCAL_ONLY || defined OCRNL TTYMODE_FLAG(OCRNL, 73, o, OCRNL) #endif #if !defined TTYMODES_LOCAL_ONLY || defined ONOCR TTYMODE_FLAG(ONOCR, 74, o, ONOCR) #endif #if !defined TTYMODES_LOCAL_ONLY || defined ONLRET TTYMODE_FLAG(ONLRET, 75, o, ONLRET) #endif #if !defined TTYMODES_LOCAL_ONLY || defined CS7 TTYMODE_FLAG(CS7, 90, c, CSIZE) #endif #if !defined TTYMODES_LOCAL_ONLY || defined CS8 TTYMODE_FLAG(CS8, 91, c, CSIZE) #endif #if !defined TTYMODES_LOCAL_ONLY || defined PARENB TTYMODE_FLAG(PARENB, 92, c, PARENB) #endif #if !defined TTYMODES_LOCAL_ONLY || defined PARODD TTYMODE_FLAG(PARODD, 93, c, PARODD) #endif
1d754d9ae594b6ff75e8dd3c505c70711b435552
05819963250c2ae0ba59ffef48d7c99a5b6b7cfd
/lib/usb/device/cdc/cdcd_serial_port.c
5174e140829c294c44823e93ee922969b101f041
[ "LicenseRef-scancode-bsd-atmel" ]
permissive
atmelcorp/atmel-software-package
cefa3213069995d453d3b47b8b3aa7a7aca683ac
e0428c7c8175a42a2460cff27bb0501db0bbe160
refs/heads/master
2023-04-13T16:34:56.181081
2023-04-06T17:30:10
2023-04-11T06:05:12
47,840,424
117
94
NOASSERTION
2022-10-20T03:07:15
2015-12-11T17:18:56
C
UTF-8
C
false
false
14,320
c
cdcd_serial_port.c
/* ---------------------------------------------------------------------------- * SAM Software Package License * ---------------------------------------------------------------------------- * Copyright (c) 2015, Atmel Corporation * * 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 disclaimer below. * * Atmel's name may not be used to endorse or promote products derived from * this software without specific prior written permission. * * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. * ---------------------------------------------------------------------------- */ /**\file * Implementation of the CDCDSerialPort class methods. */ /** \addtogroup usbd_cdc *@{ */ /*------------------------------------------------------------------------------ * Headers *------------------------------------------------------------------------------*/ #include "trace.h" #include "usb/common/cdc/cdc_descriptors.h" #include "usb/device/cdc/cdcd_serial_port.h" /*------------------------------------------------------------------------------ * Types *------------------------------------------------------------------------------*/ /** Parse data extention for descriptor parsing */ typedef struct _CDCDParseData { /** Pointer to CDCDSerialPort instance */ CDCDSerialPort * p_cdcd; /** Pointer to found interface descriptor */ USBInterfaceDescriptor * p_if_desc; } CDCDParseData; /*------------------------------------------------------------------------------ * Internal variables *------------------------------------------------------------------------------*/ /** Line coding values */ static CDCLineCoding line_coding; static struct { CDCSerialNotification notification; uint16_t serial_state; } notification_data; /*------------------------------------------------------------------------------ * Internal functions *------------------------------------------------------------------------------*/ /** * Parse descriptors: Interface, Bulk IN/OUT, Interrupt IN. * \param p_desc Pointer to descriptor list. * \param p_arg Argument, pointer to AUDDParseData instance. */ static uint32_t _interfaces_parse(USBGenericDescriptor *desc, CDCDParseData *p_arg) { CDCDSerialPort *p_cdcd = p_arg->p_cdcd; /* Not a valid descriptor */ if (desc->bLength == 0) return USBRC_PARAM_ERR; /* Find interface descriptor */ if (desc->bDescriptorType == USBGenericDescriptor_INTERFACE) { USBInterfaceDescriptor *pIf = (USBInterfaceDescriptor*)desc; /* Obtain interface from descriptor */ if (p_cdcd->bInterfaceNdx == 0xFF) { /* First interface is communication */ if (pIf->bInterfaceClass == CDCCommunicationInterfaceDescriptor_CLASS) { p_cdcd->bInterfaceNdx = pIf->bInterfaceNumber; p_cdcd->bNumInterface = 2; } /* Only data interface */ else if(pIf->bInterfaceClass == CDCDataInterfaceDescriptor_CLASS) { p_cdcd->bInterfaceNdx = pIf->bInterfaceNumber; p_cdcd->bNumInterface = 1; } p_arg->p_if_desc = pIf; } else if (p_cdcd->bInterfaceNdx <= pIf->bInterfaceNumber && p_cdcd->bInterfaceNdx + p_cdcd->bNumInterface > pIf->bInterfaceNumber) { p_arg->p_if_desc = pIf; } } /* Parse valid interfaces */ if (p_arg->p_if_desc == 0) return 0; /* Find endpoint descriptors */ if (desc->bDescriptorType == USBGenericDescriptor_ENDPOINT) { USBEndpointDescriptor *pEp = (USBEndpointDescriptor*)desc; switch(pEp->bmAttributes & 0x3) { case USBEndpointDescriptor_INTERRUPT: if (pEp->bEndpointAddress & 0x80) p_cdcd->bIntInPIPE = pEp->bEndpointAddress & 0x7F; break; case USBEndpointDescriptor_BULK: if (pEp->bEndpointAddress & 0x80) p_cdcd->bBulkInPIPE = pEp->bEndpointAddress & 0x7F; else p_cdcd->bBulkOutPIPE = pEp->bEndpointAddress; } } if (p_cdcd->bInterfaceNdx != 0xFF && p_cdcd->bBulkInPIPE != 0 && p_cdcd->bBulkOutPIPE != 0) return USBRC_FINISHED; return 0; } /** * Callback function which should be invoked after the data of a * SetLineCoding request has been retrieved. Sends a zero-length packet * to the host for acknowledging the request. * \param p_cdcd Pointer to CDCDSerialPort instance. */ static void _set_line_coding_callback(void *arg, uint8_t status, uint32_t transferred, uint32_t remaining) { CDCDSerialPort *p_cdcd = (CDCDSerialPort*)arg; bool ok = true; if (p_cdcd->fEventHandler) { uint32_t rc = p_cdcd->fEventHandler( CDCDSerialPortEvent_SETLINECODING, (uint32_t)&line_coding, p_cdcd->pArg); if (rc == USBD_STATUS_SUCCESS) { p_cdcd->lineCoding.dwDTERate = line_coding.dwDTERate; p_cdcd->lineCoding.bCharFormat = line_coding.bCharFormat; p_cdcd->lineCoding.bParityType = line_coding.bParityType; p_cdcd->lineCoding.bDataBits = line_coding.bDataBits; } else { ok = false; } } if (ok) usbd_write(0, 0, 0, 0, 0); else usbd_stall(0); } /** * Receives new line coding information from the USB host. * \param p_cdcd Pointer to CDCDSerialPort instance. */ static void _set_line_coding(CDCDSerialPort *p_cdcd) { LIBUSB_TRACE("sLineCoding "); usbd_read(0, &line_coding, sizeof(CDCLineCoding), _set_line_coding_callback, p_cdcd); } /** * Sends the current line coding information to the host through Control * endpoint 0. * \param p_cdcd Pointer to CDCDSerialPort instance. */ static void _get_line_coding(CDCDSerialPort *p_cdcd) { LIBUSB_TRACE("gLineCoding "); usbd_write(0, &p_cdcd->lineCoding, sizeof(CDCLineCoding), NULL, NULL); } /** * Changes the state of the serial driver according to the information * sent by the host via a SetControlLineState request, and acknowledges * the request with a zero-length packet. * \param p_cdcd Pointer to CDCDSerialPort instance. * \param request Pointer to a USBGenericRequest instance. */ static void _set_control_line_state(CDCDSerialPort * p_cdcd, const USBGenericRequest *request) { LIBUSB_TRACE("sControlLineState(%d, %d) ", ((request->wValue & CDCControlLineState_DTR) > 0), ((request->wValue & CDCControlLineState_RTS) > 0)); p_cdcd->bControlLineState = (uint8_t)request->wValue; usbd_write(0, 0, 0, 0, 0); if (p_cdcd->fEventHandler) p_cdcd->fEventHandler( CDCDSerialPortEvent_SETCONTROLLINESTATE, (uint32_t)p_cdcd->bControlLineState, p_cdcd->pArg); } /*------------------------------------------------------------------------------ * Exported functions *------------------------------------------------------------------------------*/ /** * Initializes the USB Device CDC serial port function. * \param p_cdcd Pointer to CDCDSerialPort instance. * \param p_usbd Pointer to USBDDriver instance. * \param f_event_handler Pointer to event handler function. * \param first_interface First interface index for the function * (0xFF to parse from descriptors). * \param num_interface Number of interfaces for the function. */ void cdcd_serial_port_initialize(CDCDSerialPort *p_cdcd, CDCDSerialPortEventHandler f_event_handler, void *p_arg, uint8_t first_interface, uint8_t num_interface) { LIBUSB_TRACE("cdcd_serial_port_initialize "); /* Initialize event handler */ p_cdcd->fEventHandler = f_event_handler; p_cdcd->pArg = p_arg; /* Initialize USB Device Driver interface */ p_cdcd->bInterfaceNdx = first_interface; p_cdcd->bNumInterface = num_interface; p_cdcd->bIntInPIPE = 0; p_cdcd->bBulkInPIPE = 0; p_cdcd->bBulkOutPIPE = 0; /* Initialize Abstract Control Model attributes */ p_cdcd->bControlLineState = 0; p_cdcd->wSerialState = 0; cdc_line_coding_initialize(&(p_cdcd->lineCoding), 115200, CDCLineCoding_ONESTOPBIT, CDCLineCoding_NOPARITY, 8); } /** * Parse CDC Serial Port information for CDCDSerialPort instance. * Accepted interfaces: * - Communication Interface + Data Interface * - Data Interface ONLY * \param p_cdcd Pointer to CDCDSerialPort instance. * \param descriptors Pointer to descriptor list. * \param length Descriptor list size in bytes. */ const USBGenericDescriptor *cdcd_serial_port_parse_interfaces( CDCDSerialPort *p_cdcd, const USBGenericDescriptor *descriptors, uint32_t length) { CDCDParseData parse_data; parse_data.p_cdcd = p_cdcd; parse_data.p_if_desc = 0; return usb_generic_descriptor_parse(descriptors, length, (USBDescriptorParseFunction)_interfaces_parse, &parse_data); } /** * Handles CDC-specific SETUP requests. Should be called from a * re-implementation of usbd_callbacks_request_received() method. * \param p_cdcd Pointer to CDCDSerialPort instance. * \param request Pointer to a USBGenericRequest instance. * \return USBRC_SUCCESS if request handled, otherwise error. */ uint32_t cdcd_serial_port_request_handler(CDCDSerialPort *p_cdcd, const USBGenericRequest *request) { if (usb_generic_request_get_type(request) != USBGenericRequest_CLASS) return USBRC_PARAM_ERR; LIBUSB_TRACE("Cdcs "); /* Validate interface */ if (request->wIndex >= p_cdcd->bInterfaceNdx && request->wIndex < p_cdcd->bInterfaceNdx + p_cdcd->bNumInterface) { } else { return USBRC_PARAM_ERR; } /* Handle the request */ switch (usb_generic_request_get_request(request)) { case CDCGenericRequest_SETLINECODING: _set_line_coding(p_cdcd); break; case CDCGenericRequest_GETLINECODING: _get_line_coding(p_cdcd); break; case CDCGenericRequest_SETCONTROLLINESTATE: _set_control_line_state(p_cdcd, request); break; default: return USBRC_PARAM_ERR; } return USBRC_SUCCESS; } /** * Receives data from the host through the virtual COM port created by * the CDC device serial driver. This function behaves like usbd_read. * \param p_cdcd Pointer to CDCDSerialPort instance. * \param data Pointer to the data buffer to put received data. * \param length Size of the data buffer in bytes. * \param callback Optional callback function to invoke when the transfer * finishes. * \param callback_arg Optional argument to the callback function. * \return USBD_STATUS_SUCCESS if the read operation has been started normally; * otherwise, the corresponding error code. */ uint32_t cdcd_serial_port_read(const CDCDSerialPort *p_cdcd, void *data, uint32_t length, usbd_xfer_cb_t callback, void *callback_arg) { if (p_cdcd->bBulkOutPIPE == 0) return USBRC_PARAM_ERR; return usbd_read(p_cdcd->bBulkOutPIPE, data, length, callback, callback_arg); } /** * Sends a data buffer through the virtual COM port created by the CDC * device serial driver. This function behaves exactly like usbd_write. * \param p_cdcd Pointer to CDCDSerialPort instance. * \param data Pointer to the data buffer to send. * \param length Size of the data buffer in bytes. * \param callback Optional callback function to invoke when the transfer * finishes. * \param callback_arg Optional argument to the callback function. * \return USBD_STATUS_SUCCESS if the read operation has been started normally; * otherwise, the corresponding error code. */ uint32_t cdcd_serial_port_write(const CDCDSerialPort *p_cdcd, void *data, uint32_t length, usbd_xfer_cb_t callback, void *callback_arg) { if (p_cdcd->bBulkInPIPE == 0) return USBRC_PARAM_ERR; return usbd_write(p_cdcd->bBulkInPIPE, data, length, callback, callback_arg); } /** * Returns the current control line state of the RS-232 line. * \param p_cdcd Pointer to CDCDSerialPort instance. */ uint8_t cdcd_serial_port_get_control_line_state(const CDCDSerialPort *p_cdcd) { return p_cdcd->bControlLineState; } /** * Copy current line coding settings to pointered space. * \param p_cdcd Pointer to CDCDSerialPort instance. * \param pLineCoding Pointer to CDCLineCoding instance. */ void cdcd_serial_port_get_line_coding(const CDCDSerialPort *p_cdcd, CDCLineCoding* coding) { if (coding) { coding->dwDTERate = p_cdcd->lineCoding.dwDTERate; coding->bCharFormat = p_cdcd->lineCoding.bCharFormat; coding->bParityType = p_cdcd->lineCoding.bParityType; coding->bDataBits = p_cdcd->lineCoding.bDataBits; } } /** * Returns the current status of the RS-232 line. * \param p_cdcd Pointer to CDCDSerialPort instance. */ uint16_t cdcd_serial_port_get_serial_state(const CDCDSerialPort *p_cdcd) { return p_cdcd->wSerialState; } /** * Sets the current serial state of the device to the given value. * \param p_cdcd Pointer to CDCDSerialPort instance. * \param wSerialState New device state. */ void cdcd_serial_port_set_serial_state(CDCDSerialPort *p_cdcd, uint16_t wSerialState) { notification_data.notification.bmRequestType = 0xA1; notification_data.notification.bNotificationType = 0x20; notification_data.notification.wValue = 0; notification_data.notification.wIndex = 0; notification_data.notification.wLength = 2; notification_data.serial_state = p_cdcd->wSerialState; if (p_cdcd->bIntInPIPE == 0) return; /* If new state is different from previous one, send a notification to the host */ if (p_cdcd->wSerialState != wSerialState) { p_cdcd->wSerialState = wSerialState; usbd_write(p_cdcd->bIntInPIPE, (uint8_t*)&notification_data, sizeof(notification_data), NULL, NULL); /* Reset one-time flags */ p_cdcd->wSerialState &= ~(CDCSerialState_OVERRUN | CDCSerialState_PARITY | CDCSerialState_FRAMING | CDCSerialState_RINGSIGNAL | CDCSerialState_BREAK); } } /**@}*/
5ca62ee324fabd4059b251a8c2bfe0a8a86d8c0b
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/modules/gpu/mali400/kernel_mode/driver/src/devicedrv/ump/common/ump_kernel_memory_backend.h
056244ebe1629f2a6676215e81e9133bf1b74c41
[ "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
1,845
h
ump_kernel_memory_backend.h
/* * Copyright (C) 2010-2011, 2013-2015 ARM Limited. All rights reserved. * * This program is free software and is provided to you under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation, and any use by you of this program is subject to the terms of such GNU licence. * * A copy of the licence is included with the program, and can also be obtained from Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file ump_kernel_memory_mapping.h */ #ifndef __UMP_KERNEL_MEMORY_BACKEND_H__ #define __UMP_KERNEL_MEMORY_BACKEND_H__ #include "ump_kernel_interface.h" #include "ump_kernel_types.h" typedef struct ump_memory_allocation { void *phys_addr; void *mapping; unsigned long size; ump_dd_handle handle; void *process_mapping_info; u32 cookie; /**< necessary on some U/K interface implementations */ struct ump_session_data *ump_session; /**< Session that this allocation belongs to */ _mali_osk_list_t list; /**< List for linking together memory allocations into the session's memory head */ u32 is_cached; } ump_memory_allocation; typedef struct ump_memory_backend { int (*allocate)(void *ctx, ump_dd_mem *descriptor); void (*release)(void *ctx, ump_dd_mem *descriptor); void (*shutdown)(struct ump_memory_backend *backend); u32(*stat)(struct ump_memory_backend *backend); int (*pre_allocate_physical_check)(void *ctx, u32 size); u32(*adjust_to_mali_phys)(void *ctx, u32 cpu_phys); void *ctx; } ump_memory_backend; ump_memory_backend *ump_memory_backend_create(void); void ump_memory_backend_destroy(void); #endif /*__UMP_KERNEL_MEMORY_BACKEND_H__ */
0d749cb6d60e0c83df2d1051b7ba199ebed4e701
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/arch/sh/include/asm/topology.h
b0a282d65f6a16bc0753faac736e67adc00f62e7
[ "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
658
h
topology.h
#ifndef _ASM_SH_TOPOLOGY_H #define _ASM_SH_TOPOLOGY_H #ifdef CONFIG_NUMA #define cpu_to_node(cpu) ((void)(cpu),0) #define parent_node(node) ((void)(node),0) #define cpumask_of_node(node) ((void)node, cpu_online_mask) #define pcibus_to_node(bus) ((void)(bus), -1) #define cpumask_of_pcibus(bus) (pcibus_to_node(bus) == -1 ? \ cpu_all_mask : \ cpumask_of_node(pcibus_to_node(bus))) #endif #define mc_capable() (1) const struct cpumask *cpu_coregroup_mask(unsigned int cpu); extern cpumask_t cpu_core_map[NR_CPUS]; #define topology_core_cpumask(cpu) (&cpu_core_map[cpu]) #include <asm-generic/topology.h> #endif /* _ASM_SH_TOPOLOGY_H */
4347f4de9344ff026bf7415f4846d235130e4aba
d0dc556f8b1d18ecbadef182bafd97b632dd3104
/ch8/ble_mesh_ex/src/appmesh_setup.c
fef1a319279b1d9eb6d163aca76f419a372ebe9a
[ "MIT" ]
permissive
PacktPublishing/Internet-of-Things-with-ESP32
da3f2c57e2bd871b134b22841fd275c51f88d487
3ada8b905e53961940511636991a839059de7cd1
refs/heads/main
2023-02-08T13:58:32.585403
2023-01-30T10:03:23
2023-01-30T10:03:23
315,618,086
114
36
null
null
null
null
UTF-8
C
false
false
2,274
c
appmesh_setup.c
#include <stdint.h> #include "esp_log.h" #include "esp_ble_mesh_common_api.h" #include "esp_ble_mesh_networking_api.h" #include "esp_ble_mesh_provisioning_api.h" #include "esp_ble_mesh_config_model_api.h" #include "esp_ble_mesh_local_data_operation_api.h" #include "appmesh_setup.h" #include "appbt_init.h" #define TAG "app.mesh" #define CID_ESP 0x02E5 static uint8_t dev_uuid[16] = {0xdd, 0xdd}; static esp_ble_mesh_cfg_srv_t config_server = { .relay = ESP_BLE_MESH_RELAY_DISABLED, .beacon = ESP_BLE_MESH_BEACON_ENABLED, .friend_state = ESP_BLE_MESH_FRIEND_ENABLED, .gatt_proxy = ESP_BLE_MESH_GATT_PROXY_ENABLED, .default_ttl = 7, .net_transmit = ESP_BLE_MESH_TRANSMIT(2, 20), .relay_retransmit = ESP_BLE_MESH_TRANSMIT(2, 20), }; ESP_BLE_MESH_MODEL_PUB_DEFINE(onoff_pub_0, 2 + 3, ROLE_NODE); static esp_ble_mesh_gen_onoff_srv_t onoff_server_0 = { .rsp_ctrl.get_auto_rsp = ESP_BLE_MESH_SERVER_AUTO_RSP, .rsp_ctrl.set_auto_rsp = ESP_BLE_MESH_SERVER_AUTO_RSP, }; static esp_ble_mesh_model_t root_models[] = { ESP_BLE_MESH_MODEL_CFG_SRV(&config_server), ESP_BLE_MESH_MODEL_GEN_ONOFF_SRV(&onoff_pub_0, &onoff_server_0), }; static esp_ble_mesh_elem_t elements[] = { ESP_BLE_MESH_ELEMENT(0, root_models, ESP_BLE_MESH_MODEL_NONE), }; static esp_ble_mesh_comp_t composition = { .cid = CID_ESP, .elements = elements, .element_count = ARRAY_SIZE(elements), }; static esp_ble_mesh_prov_t provision = { .uuid = dev_uuid, .output_size = 0, .output_actions = 0, }; esp_ble_mesh_model_t *appmesh_get_onoff_model(void) { return &root_models[1]; } esp_ble_mesh_gen_onoff_srv_t *appmesh_get_onoff_server(void) { return &onoff_server_0; } esp_err_t appmesh_init(void) { esp_err_t err = ESP_OK; ble_mesh_get_dev_uuid(dev_uuid); err = esp_ble_mesh_init(&provision, &composition); if (err != ESP_OK) { ESP_LOGE(TAG, "Failed to initialize mesh stack (err %d)", err); return err; } err = esp_ble_mesh_node_prov_enable(ESP_BLE_MESH_PROV_ADV | ESP_BLE_MESH_PROV_GATT); if (err != ESP_OK) { ESP_LOGE(TAG, "Failed to enable mesh node (err %d)", err); return err; } ESP_LOGI(TAG, "BLE Mesh Node initialized"); return err; }
ca9a445eea1a6960f126af528af6b9e84153351f
336d3942e52ba91604d479e590a1e35d6d7c14a4
/src/version.h
89aef53fcb55a6c56d7709b2b3d4ffab4e26971c
[ "BSD-3-Clause" ]
permissive
redis/redis
8fb932a09677ed8854c94d81c941655eceda2138
e792653753dc62b5a00822121e585511542a024b
refs/heads/unstable
2023-08-29T14:53:21.757052
2023-08-27T08:42:55
2023-08-27T08:42:55
156,018
19,822
6,754
BSD-3-Clause
2023-09-14T18:06:48
2009-03-21T22:32:25
C
UTF-8
C
false
false
73
h
version.h
#define REDIS_VERSION "255.255.255" #define REDIS_VERSION_NUM 0x00ffffff
4c41aa31e0227499ec4613f850e61fe6ebffdcae
8301e9607481f19635c9ab5bfa0b879c5d6234f8
/libiso9660/iso9660.c
4da95be62118987669ebd35b382fd3053184c4d6
[ "Zlib" ]
permissive
devkitPro/libogc
ba6af8f0e848cccb3054662edb98127c9616144a
0a35583f638c3705be220ae5b65bd7ec20db234d
refs/heads/master
2023-06-23T08:05:17.433798
2023-06-16T15:47:02
2023-06-16T15:47:02
28,180,403
249
163
NOASSERTION
2023-06-16T15:47:03
2014-12-18T11:13:41
C
UTF-8
C
false
false
22,836
c
iso9660.c
/**************************************************************************** * ISO9660 devoptab * * Copyright (C) 2008-2010 * tipoloski, clava, shagkur, Tantric, joedj ****************************************************************************/ #include <errno.h> #include <ogc/lwp_watchdog.h> #include <ogcsys.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/dir.h> #include <sys/iosupport.h> #include "iso9660.h" #define OFFSET_EXTENDED 1 #define OFFSET_SECTOR 6 #define OFFSET_SIZE 14 #define OFFSET_FLAGS 25 #define OFFSET_NAMELEN 32 #define OFFSET_NAME 33 #define SECTOR_SIZE 0x800 #define BUFFER_SIZE 0x8000 #define DIR_SEPARATOR '/' #define FLAG_DIR 2 struct pvd_s { char id[8]; char system_id[32]; char volume_id[32]; char zero[8]; unsigned long total_sector_le, total_sect_be; char zero2[32]; unsigned long volume_set_size, volume_seq_nr; unsigned short sector_size_le, sector_size_be; unsigned long path_table_len_le, path_table_len_be; unsigned long path_table_le, path_table_2nd_le; unsigned long path_table_be, path_table_2nd_be; u8 root[34]; char volume_set_id[128], publisher_id[128], data_preparer_id[128], application_id[128]; char copyright_file_id[37], abstract_file_id[37], bibliographical_file_id[37]; }__attribute__((packed)); typedef struct { u8 name_length; u8 extended_sectors; u32 sector; u16 parent; char name[ISO_MAXPATHLEN]; }__attribute__((packed)) PATHTABLE_ENTRY; typedef struct pentry_s { u16 index; u32 childCount; PATHTABLE_ENTRY table_entry; struct pentry_s *children; } PATH_ENTRY; typedef struct dentry_s { char name[ISO_MAXPATHLEN]; u32 sector; u32 size; u8 flags; u32 fileCount; PATH_ENTRY *path_entry; struct dentry_s *children; } DIR_ENTRY; typedef struct iso9660mount_s { const DISC_INTERFACE *disc_interface; u8 read_buffer[BUFFER_SIZE] __attribute__((aligned(32))); u8 cluster_buffer[BUFFER_SIZE] __attribute__((aligned(32))); u32 cache_start; u32 cache_sectors; bool iso_unicode; PATH_ENTRY *iso_rootentry; PATH_ENTRY *iso_currententry; char volume_id[32]; } MOUNT_DESCR; typedef struct filestruct_s { DIR_ENTRY entry; off_t offset; bool inUse; MOUNT_DESCR *mdescr; } FILE_STRUCT; typedef struct dstate_s { DIR_ENTRY entry; u32 index; bool inUse; } DIR_STATE_STRUCT; static MOUNT_DESCR* _ISO9660_getMountDescrFromPath(const char *path, devoptab_t **pdevops); static __inline__ bool is_dir(DIR_ENTRY *entry) { return entry->flags & FLAG_DIR; } static int __read(MOUNT_DESCR *mdescr, void *ptr, u64 offset, size_t len) { u32 sector = offset / SECTOR_SIZE; u32 end_sector = (offset + len - 1) / SECTOR_SIZE; u32 sectors = MIN(BUFFER_SIZE / SECTOR_SIZE, end_sector - sector + 1); u32 sector_offset = offset % SECTOR_SIZE; const DISC_INTERFACE *disc = mdescr->disc_interface; len = MIN(BUFFER_SIZE - sector_offset, len); if (mdescr->cache_sectors && sector >= mdescr->cache_start && (sector + sectors) <= (mdescr->cache_start + mdescr->cache_sectors)) { memcpy(ptr, mdescr->read_buffer + (sector - mdescr->cache_start) * SECTOR_SIZE + sector_offset, len); return len; } if (!disc->readSectors(sector, BUFFER_SIZE / SECTOR_SIZE, mdescr->read_buffer)) { mdescr->cache_sectors = 0; return -1; } mdescr->cache_start = sector; mdescr->cache_sectors = BUFFER_SIZE / SECTOR_SIZE; memcpy(ptr, mdescr->read_buffer + sector_offset, len); return len; } static int _read(MOUNT_DESCR *mdescr, void *ptr, u64 offset, size_t len) { int ret, read = 0; char *cptr = ptr; while (read < len) { ret = __read(mdescr, cptr + read, offset + read, len - read); if (ret > 0) read += ret; else if (ret == 0) break; else return -1; } return read; } static void stat_entry(DIR_ENTRY *entry, struct stat *st) { st->st_dev = 69; st->st_ino = (ino_t) entry->sector; st->st_mode = (is_dir(entry) ? S_IFDIR : S_IFREG) | (S_IRUSR | S_IRGRP | S_IROTH); st->st_nlink = 1; st->st_uid = 1; st->st_gid = 2; st->st_rdev = st->st_dev; st->st_size = entry->size; st->st_atime = 0; st->st_mtime = 0; st->st_ctime = 0; st->st_blksize = SECTOR_SIZE; st->st_blocks = (entry->size + SECTOR_SIZE - 1) / SECTOR_SIZE; st->st_spare4[0] = 0; st->st_spare4[1] = 0; } static char* basename(char *path) { s32 i; for (i = strlen(path) - 1; i >= 0; i--) { if (path[i] == DIR_SEPARATOR) return path + i + 1; } return path; } static char* dirname(char *path) { size_t i, j; char *result = strdup(path); j = strlen(result) - 1; if (j < 0) return result; for (i = j; i >= 0; i--) { if (result[i] == DIR_SEPARATOR) { result[i] = '\0'; return result; } } result[0] = '\0'; return result; } static s32 read_direntry(MOUNT_DESCR *mdescr, DIR_ENTRY *entry, u8 *buf) { u8 extended_sectors = buf[OFFSET_EXTENDED]; u32 sector = *(u32 *) (buf + OFFSET_SECTOR) + extended_sectors; u32 size = *(u32 *) (buf + OFFSET_SIZE); u8 flags = buf[OFFSET_FLAGS]; u8 namelen = buf[OFFSET_NAMELEN]; if (namelen == 1 && buf[OFFSET_NAME] == 1 && mdescr->iso_rootentry->table_entry.sector == entry->sector) { // .. at root - do not show } else if (namelen == 1 && !buf[OFFSET_NAME]) { entry->sector = sector; entry->size = size; entry->flags = flags; } else { DIR_ENTRY *newChildren = realloc(entry->children, sizeof(DIR_ENTRY) * (entry->fileCount + 1)); if (!newChildren) return -1; memset(newChildren + entry->fileCount, 0, sizeof(DIR_ENTRY)); entry->children = newChildren; DIR_ENTRY *child = &entry->children[entry->fileCount++]; child->sector = sector; child->size = size; child->flags = flags; char *name = child->name; if (namelen == 1 && buf[OFFSET_NAME] == 1) { // .. sprintf(name, ".."); } else if (mdescr->iso_unicode) { u32 i; for (i = 0; i < (namelen / 2); i++) name[i] = buf[OFFSET_NAME + i * 2 + 1]; name[i] = '\x00'; namelen = i; } else { memcpy(name, buf + OFFSET_NAME, namelen); name[namelen] = '\x00'; } if (!(flags & FLAG_DIR) && namelen >= 2 && name[namelen - 2] == ';') name[namelen - 2] = '\x00'; } return *buf; } static bool read_directory(MOUNT_DESCR *mdescr, DIR_ENTRY *dir_entry, PATH_ENTRY *path_entry) { u32 sector = path_entry->table_entry.sector; u32 remaining = 0; u32 sector_offset = 0; do { if (__read(mdescr, mdescr->cluster_buffer, (u64) sector * SECTOR_SIZE + sector_offset, (SECTOR_SIZE - sector_offset)) != (SECTOR_SIZE - sector_offset)) return false; int offset = read_direntry(mdescr, dir_entry, mdescr->cluster_buffer); if (offset == -1) return false; if (!remaining) { remaining = dir_entry->size; dir_entry->path_entry = path_entry; } sector_offset += offset; if (sector_offset >= SECTOR_SIZE || !mdescr->cluster_buffer[offset]) { remaining -= SECTOR_SIZE; sector_offset = 0; sector++; } } while (remaining > 0); return true; } static bool path_entry_from_path(MOUNT_DESCR *mdescr, PATH_ENTRY *path_entry, const char *path) { bool found = false; bool notFound = false; const char *pathPosition = path; const char *pathEnd = strchr(path, '\0'); PATH_ENTRY *entry = mdescr->iso_rootentry; while (pathPosition[0] == DIR_SEPARATOR) pathPosition++; if (pathPosition >= pathEnd) found = true; PATH_ENTRY *dir = entry; while (!found && !notFound) { const char *nextPathPosition = strchr(pathPosition, DIR_SEPARATOR); size_t dirnameLength; if (nextPathPosition != NULL) dirnameLength = nextPathPosition - pathPosition; else dirnameLength = strlen(pathPosition); if (dirnameLength >= ISO_MAXPATHLEN) return false; u32 childIndex = 0; while (childIndex < dir->childCount && !found && !notFound) { entry = &dir->children[childIndex]; if (dirnameLength == strnlen(entry->table_entry.name, ISO_MAXPATHLEN - 1) && !strncasecmp(pathPosition, entry->table_entry.name, dirnameLength)) found = true; if (!found) childIndex++; } if (childIndex >= dir->childCount) { notFound = true; found = false; } else if (!nextPathPosition || nextPathPosition >= pathEnd) { found = true; } else { dir = entry; pathPosition = nextPathPosition; while (pathPosition[0] == DIR_SEPARATOR) pathPosition++; if (pathPosition >= pathEnd) found = true; else found = false; } } if (found) memcpy(path_entry, entry, sizeof(PATH_ENTRY)); return found; } static bool find_in_directory(MOUNT_DESCR *mdescr, DIR_ENTRY *entry, PATH_ENTRY *parent, const char *base) { u32 childIdx; u32 nl = strlen(base); if (!nl) return read_directory(mdescr, entry, parent); for (childIdx = 0; childIdx < parent->childCount; childIdx++) { PATH_ENTRY *child = parent->children + childIdx; if (nl == strnlen(child->table_entry.name, ISO_MAXPATHLEN - 1) && !strncasecmp(base, child->table_entry.name, nl)) { return read_directory(mdescr, entry, child); } } if (!read_directory(mdescr, entry, parent)) return false; for (childIdx = 0; childIdx < entry->fileCount; childIdx++) { DIR_ENTRY *child = entry->children + childIdx; if (nl == strnlen(child->name, ISO_MAXPATHLEN - 1) && !strncasecmp(base, child->name, nl)) { memcpy(entry, child, sizeof(DIR_ENTRY)); return true; } } return false; } static bool entry_from_path(MOUNT_DESCR *mdescr, DIR_ENTRY *entry, const char *const_path) { u32 len; bool found = false; char *path, *dir, *base; PATH_ENTRY parent_entry; memset(entry, 0, sizeof(DIR_ENTRY)); if (strchr(const_path, ':') != NULL) const_path = strchr(const_path, ':') + 1; path = strdup(const_path); len = strlen(path); while (len > 1 && path[len - 1] == DIR_SEPARATOR) path[--len] = '\x00'; dir = dirname(path); base = basename(path); if (!path_entry_from_path(mdescr, &parent_entry, dir)) goto done; found = find_in_directory(mdescr, entry, &parent_entry, base); if (!found && entry->children) free(entry->children); done: free(path); free(dir); return found; } static bool check_dev_name(const char* name, char *devname, size_t devname_size) { size_t len; if (!name) return false; len = strlen(name); if (len == 0 || len > devname_size-2) return false; // append ':' if missing strcpy(devname, name); if (devname[len-1] != ':') strcat(devname, ":"); return true; } static int _ISO9660_open_r(struct _reent *r, void *fileStruct, const char *path, int flags, int mode) { DIR_ENTRY entry; FILE_STRUCT *file = (FILE_STRUCT *) fileStruct; MOUNT_DESCR *mdescr; mdescr = _ISO9660_getMountDescrFromPath(path, NULL); if (mdescr == NULL) { r->_errno = ENODEV; return -1; } if (!entry_from_path(mdescr, &entry, path)) { r->_errno = ENOENT; return -1; } else if (is_dir(&entry)) { if (entry.children) free(entry.children); r->_errno = EISDIR; return -1; } memcpy(&file->entry, &entry, sizeof(DIR_ENTRY)); file->offset = 0; file->inUse = true; file->mdescr = mdescr; return (int) file; } static int _ISO9660_close_r(struct _reent *r, void *fd) { FILE_STRUCT *file = (FILE_STRUCT*) fd; if (!file->inUse) { r->_errno = EBADF; return -1; } file->inUse = false; return 0; } static ssize_t _ISO9660_read_r(struct _reent *r, void *fd, char *ptr, size_t len) { u64 offset; int ret; FILE_STRUCT *file = (FILE_STRUCT*) fd; if (!file->inUse) { r->_errno = EBADF; return -1; } if (file->offset >= file->entry.size) { r->_errno = EOVERFLOW; return 0; } if (len + file->offset > file->entry.size) { r->_errno = EOVERFLOW; len = file->entry.size - file->offset; } if (len == 0) return 0; offset = (u64) file->entry.sector * SECTOR_SIZE + file->offset; if ((ret = _read(file->mdescr, ptr, offset, len)) < 0) { r->_errno = EIO; return -1; } len = (size_t)ret; file->offset += len; return len; } static off_t _ISO9660_seek_r(struct _reent *r, void *fd, off_t pos, int dir) { off_t position; FILE_STRUCT *file = (FILE_STRUCT*) fd; if (!file->inUse) { r->_errno = EBADF; return -1; } switch (dir) { case SEEK_SET: position = pos; break; case SEEK_CUR: position = file->offset + pos; break; case SEEK_END: position = file->entry.size + pos; break; default: r->_errno = EINVAL; return -1; } if (pos > 0 && position < 0) { r->_errno = EOVERFLOW; return -1; } if (position < 0 || position > file->entry.size) { r->_errno = EINVAL; return -1; } file->offset = position; return position; } static int _ISO9660_fstat_r(struct _reent *r, void *fd, struct stat *st) { FILE_STRUCT *file = (FILE_STRUCT*) fd; if (!file->inUse) { r->_errno = EBADF; return -1; } stat_entry(&file->entry, st); return 0; } static int _ISO9660_stat_r(struct _reent *r, const char *path, struct stat *st) { DIR_ENTRY entry; MOUNT_DESCR *mdescr; mdescr = _ISO9660_getMountDescrFromPath(path, NULL); if (mdescr == NULL) { r->_errno = ENODEV; return -1; } if (!entry_from_path(mdescr, &entry, path)) { r->_errno = ENOENT; return -1; } stat_entry(&entry, st); if (entry.children) free(entry.children); return 0; } static int _ISO9660_chdir_r(struct _reent *r, const char *path) { DIR_ENTRY entry; MOUNT_DESCR *mdescr; mdescr = _ISO9660_getMountDescrFromPath(path, NULL); if (mdescr == NULL) { r->_errno = ENODEV; return -1; } if (!entry_from_path(mdescr, &entry, path)) { r->_errno = ENOENT; return -1; } else if (!is_dir(&entry)) { r->_errno = ENOTDIR; return -1; } mdescr->iso_currententry = entry.path_entry; if (entry.children) free(entry.children); return 0; } static DIR_ITER* _ISO9660_diropen_r(struct _reent *r, DIR_ITER *dirState, const char *path) { DIR_STATE_STRUCT *state = (DIR_STATE_STRUCT*) (dirState->dirStruct); MOUNT_DESCR *mdescr; mdescr = _ISO9660_getMountDescrFromPath(path, NULL); if (mdescr == NULL) { r->_errno = ENODEV; return NULL; } if (!entry_from_path(mdescr, &state->entry, path)) { r->_errno = ENOENT; return NULL; } else if (!is_dir(&state->entry)) { r->_errno = ENOTDIR; return NULL; } state->index = 0; state->inUse = true; return dirState; } static int _ISO9660_dirreset_r(struct _reent *r, DIR_ITER *dirState) { DIR_STATE_STRUCT *state = (DIR_STATE_STRUCT*) (dirState->dirStruct); if (!state->inUse) { r->_errno = EBADF; return -1; } state->index = 0; return 0; } static int _ISO9660_dirnext_r(struct _reent *r, DIR_ITER *dirState, char *filename, struct stat *st) { DIR_ENTRY *entry; DIR_STATE_STRUCT *state = (DIR_STATE_STRUCT*) (dirState->dirStruct); if (!state->inUse) { r->_errno = EBADF; return -1; } if (state->index >= state->entry.fileCount) { r->_errno = ENOENT; return -1; } entry = &state->entry.children[state->index++]; strncpy(filename, entry->name, ISO_MAXPATHLEN); stat_entry(entry, st); return 0; } static int _ISO9660_dirclose_r(struct _reent *r, DIR_ITER *dirState) { DIR_STATE_STRUCT *state = (DIR_STATE_STRUCT*) (dirState->dirStruct); if (!state->inUse) { r->_errno = EBADF; return -1; } state->inUse = false; if (state->entry.children) free(state->entry.children); return 0; } static int _ISO9660_statvfs_r(struct _reent *r, const char *path, struct statvfs *buf) { // FAT clusters = POSIX blocks buf->f_bsize = 0x800; // File system block size. buf->f_frsize = 0x800; // Fundamental file system block size. //buf->f_blocks = totalsectors; // Total number of blocks on file system in units of f_frsize. buf->f_bfree = 0; // Total number of free blocks. buf->f_bavail = 0; // Number of free blocks available to non-privileged process. // Treat requests for info on inodes as clusters //buf->f_files = totalentries; // Total number of file serial numbers. buf->f_ffree = 0; // Total number of free file serial numbers. buf->f_favail = 0; // Number of file serial numbers available to non-privileged process. // File system ID. 32bit ioType value buf->f_fsid = 0; //??!!? // Bit mask of f_flag values. buf->f_flag = ST_NOSUID // No support for ST_ISUID and ST_ISGID file mode bits | ST_RDONLY; // Read only file system // Maximum filename length. buf->f_namemax = 208; return 0; } static const devoptab_t dotab_iso9660 = { NULL, sizeof(FILE_STRUCT), _ISO9660_open_r, _ISO9660_close_r, NULL, _ISO9660_read_r, _ISO9660_seek_r, _ISO9660_fstat_r, _ISO9660_stat_r, NULL, NULL, _ISO9660_chdir_r, NULL, NULL, sizeof(DIR_STATE_STRUCT), _ISO9660_diropen_r, _ISO9660_dirreset_r, _ISO9660_dirnext_r, _ISO9660_dirclose_r, _ISO9660_statvfs_r, NULL, // device ftruncate_r NULL, // device fsync_r NULL // device data }; static MOUNT_DESCR* _ISO9660_getMountDescrFromPath(const char *path, devoptab_t **pdevops) { devoptab_t *devops; if (!path) return NULL; devops = (devoptab_t *) GetDeviceOpTab(path); if (!devops) return NULL; // Perform a quick check to make sure we're dealing with a libiso9660 controlled device if (devops->open_r != dotab_iso9660.open_r) return NULL; if (pdevops) *pdevops = devops; return (MOUNT_DESCR*) devops->deviceData; } static PATH_ENTRY* entry_from_index(PATH_ENTRY *entry, u16 index) { u32 i; if (entry->index == index) return entry; for (i = 0; i < entry->childCount; i++) { PATH_ENTRY *match = entry_from_index(&entry->children[i], index); if (match) return match; } return NULL; } static PATH_ENTRY* add_child_entry(PATH_ENTRY *dir) { PATH_ENTRY *child; PATH_ENTRY *newChildren = NULL; newChildren = realloc(dir->children, (dir->childCount + 1) * sizeof(PATH_ENTRY)); if (newChildren == NULL) return NULL; memset(newChildren + dir->childCount, 0, sizeof(PATH_ENTRY)); dir->children = newChildren; child = &dir->children[dir->childCount++]; return child; } static void cleanup_recursive(PATH_ENTRY *entry) { u32 i; for (i = 0; i < entry->childCount; i++) cleanup_recursive(&entry->children[i]); if (entry->children) free(entry->children); } static struct pvd_s* read_volume_descriptor(MOUNT_DESCR *mdescr, u8 descriptor) { u8 sector; const DISC_INTERFACE *disc = mdescr->disc_interface; for (sector = 16; sector < 32; sector++) { if (!disc->readSectors(sector, 1, mdescr->read_buffer)) return NULL; if (!memcmp(mdescr->read_buffer + 1, "CD001\1", 6)) { if (*mdescr->read_buffer == descriptor) return (struct pvd_s*) mdescr->read_buffer; else if (*mdescr->read_buffer == 0xff) return NULL; } } return NULL; } static bool read_directories(MOUNT_DESCR *mdescr) { struct pvd_s *volume = read_volume_descriptor(mdescr, 2); if (volume) mdescr->iso_unicode = true; else if (!(volume = read_volume_descriptor(mdescr, 1))) return false; if (!(mdescr->iso_rootentry = malloc(sizeof(PATH_ENTRY)))) return false; memset(mdescr->iso_rootentry, 0, sizeof(PATH_ENTRY)); mdescr->iso_rootentry->table_entry.name_length = 1; mdescr->iso_rootentry->table_entry.extended_sectors = volume->root[OFFSET_EXTENDED]; mdescr->iso_rootentry->table_entry.sector = *(u32 *) (volume->root + OFFSET_SECTOR); mdescr->iso_rootentry->table_entry.parent = 0; mdescr->iso_rootentry->table_entry.name[0] = '\x00'; mdescr->iso_rootentry->index = 1; mdescr->iso_currententry = mdescr->iso_rootentry; strncpy(mdescr->volume_id, volume->volume_id, 32); mdescr->volume_id[31] = '\0'; u32 path_table = volume->path_table_be; u32 path_table_len = volume->path_table_len_be; u16 i = 1; u64 offset = sizeof(PATHTABLE_ENTRY) - ISO_MAXPATHLEN + 2; PATH_ENTRY *parent = mdescr->iso_rootentry; while (i < 0xffff && offset < path_table_len) { PATHTABLE_ENTRY entry; if (__read(mdescr, &entry, (u64) path_table * SECTOR_SIZE + offset, sizeof(PATHTABLE_ENTRY)) != sizeof(PATHTABLE_ENTRY)) return false; // kinda dodgy - could be reading too far if (parent->index != entry.parent) parent = entry_from_index(mdescr->iso_rootentry, entry.parent); if (!parent) return false; PATH_ENTRY *child = add_child_entry(parent); if (!child) return false; memcpy(&child->table_entry, &entry, sizeof(PATHTABLE_ENTRY)); offset += sizeof(PATHTABLE_ENTRY) - ISO_MAXPATHLEN + child->table_entry.name_length; if (child->table_entry.name_length % 2) offset++; child->index = ++i; if (mdescr->iso_unicode) { u32 i; for (i = 0; i < (child->table_entry.name_length / 2); i++) child->table_entry.name[i] = entry.name[i * 2 + 1]; child->table_entry.name[i] = '\x00'; child->table_entry.name_length = i; } else { child->table_entry.name[child->table_entry.name_length] = '\x00'; } } return true; } static MOUNT_DESCR *_ISO9660_mdescr_constructor(const DISC_INTERFACE *disc_interface) { MOUNT_DESCR *mdescr = NULL; mdescr = malloc(sizeof(MOUNT_DESCR)); if (!mdescr) return NULL; mdescr->disc_interface = disc_interface; mdescr->cache_start = 0; mdescr->cache_sectors = 0; mdescr->iso_unicode = false; mdescr->iso_rootentry = NULL; mdescr->iso_currententry = NULL; if (!read_directories(mdescr)) { free(mdescr); return NULL; } return mdescr; } bool ISO9660_Mount(const char* name, const DISC_INTERFACE *disc_interface) { char *nameCopy; devoptab_t *devops = NULL; MOUNT_DESCR *mdescr = NULL; char devname[10]; if (!name || strlen(name) > 8 || !disc_interface) return false; if (!disc_interface->startup()) return false; if (!disc_interface->isInserted()) return false; sprintf(devname, "%s:", name); if (FindDevice(devname) >= 0) return false; devops = malloc(sizeof(dotab_iso9660) + strlen(name) + 1); if (!devops) return false; // Use the space allocated at the end of the devoptab struct for storing the name nameCopy = (char*) (devops + 1); // Initialize the file system mdescr = _ISO9660_mdescr_constructor(disc_interface); if (!mdescr) { free(devops); return false; } // Add an entry for this device to the devoptab table memcpy(devops, &dotab_iso9660, sizeof(dotab_iso9660)); strcpy(nameCopy, name); devops->name = nameCopy; devops->deviceData = mdescr; if (AddDevice(devops) < 0) { free(mdescr); free(devops); return false; } return true; } bool ISO9660_Unmount(const char* name) { devoptab_t *devops; MOUNT_DESCR *mdescr; char devname[11]; if (! check_dev_name(name, devname, sizeof(devname))) return false; mdescr = _ISO9660_getMountDescrFromPath(devname, &devops); if (!mdescr) return false; if (RemoveDevice(devname) == -1) return false; if (mdescr->iso_rootentry) { cleanup_recursive(mdescr->iso_rootentry); free(mdescr->iso_rootentry); } free(mdescr); free(devops); return true; } const char *ISO9660_GetVolumeLabel(const char *name) { MOUNT_DESCR *mdescr; char devname[11]; if (! check_dev_name(name, devname, sizeof(devname))) return NULL; mdescr = _ISO9660_getMountDescrFromPath(devname, NULL); if (!mdescr) return NULL; return mdescr->volume_id; }
6487a11ce5f469994b8ae2709560caacf0d52eb8
779cd3de885ad7c23e2f625684a55e1d1b27730a
/include/point_box_squared_distance.h
32b09ea0e41a7859315d4789d143dd80c0c8bbdc
[]
no_license
alecjacobson/computer-graphics-bounding-volume-hierarchy
fa0daf9d38651f4ccf5f680ef9b2283e0e481ee0
b5e801ea101fcba5a068cd564a905c11e6bc7635
refs/heads/master
2022-02-14T05:03:23.086216
2022-02-01T22:54:37
2022-02-01T22:54:37
147,458,320
103
44
null
2022-02-02T15:56:05
2018-09-05T04:11:20
C++
UTF-8
C
false
false
453
h
point_box_squared_distance.h
#ifndef POINT_BOX_SQUARED_DISTANCE_H #define POINT_BOX_SQUARED_DISTANCE_H #include "BoundingBox.h" #include <Eigen/Core> // Compute the squared distance between a query point and a box // // Inputs: // query 3D position of query point // box 3D axis-aligned bounding box // Returns squared distance to closest point on bounding box to query double point_box_squared_distance( const Eigen::RowVector3d & query, const BoundingBox & box); #endif
5929473321bfe4ba8beca52730077dca68762e0d
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
/sys/arch/hpcmips/vr/vrc4172gpioreg.h
de1fff32fb945e6ecebcedbd0c777190d1e5d4ae
[]
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
2,741
h
vrc4172gpioreg.h
/* $NetBSD: vrc4172gpioreg.h,v 1.2 2001/05/06 14:25:16 takemura Exp $ */ /* * Copyright (c) 2000 SATO Kazumi. 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. */ /* * Vrc4172 GPIO (General Purpose I/O) Unit Registers. */ #define VRC2_EXGPREG_MAX 0x4a #define VRC2_EXGP_NPORTS 24 #define VRC2_EXGP_OFFSET 0x40 #define VRC2_EXGPDATA VRC2_EXGPDATA0 #define VRC2_EXGPDIR VRC2_EXGPDIR0 #define VRC2_EXGPINTEN VRC2_EXGPINTEN0 #define VRC2_EXGPINTST VRC2_EXGPINTST0 #define VRC2_EXGPINTTYP VRC2_EXGPINTTYP0 #define VRC2_EXGPDATA0 0x00 /* I/O data (0..15) */ #define VRC2_EXGPDIR0 0x02 /* direction (0..15) */ #define VRC2_EXGPINTEN0 0x04 /* interrupt enable (0..15) */ #define VRC2_EXGPINTST0 0x06 /* interrupt status (0..15) */ #define VRC2_EXGPINTTYP0 0x08 /* interrupt type (0..15) */ #define VRC2_EXGPINTLV0L 0x0a /* interrupt level low (0..15) */ #define VRC2_EXGPINTLV0H 0x0c /* interrupt level high (0..15) */ #define VRC2_EXGPDATA1 0x40 /* I/O data (16..23) */ #define VRC2_EXGPDIR1 0x42 /* direction (16..23) */ #define VRC2_EXGPINTEN1 0x44 /* interrupt enable (16..23) */ #define VRC2_EXGPINTST1 0x46 /* interrupt status (16..23) */ #define VRC2_EXGPINTTYP1 0x48 /* interrupt type (16..23) */ #define VRC2_EXGPINTLV1L 0x4a /* interrupt level low (16..23) */ #define VRC2_EXGPINTTYP_EDGE 1 #define VRC2_EXGPINTTYP_LEVEL 0 #define VRC2_EXGPINTAL_HIGH 1 #define VRC2_EXGPINTAL_LOW 0 #define VRC2_EXGPINTHT_HOLD 1 #define VRC2_EXGPINTHT_THROUGH 0 /* end */
8801d7c7cab8a759faf5db239c6805d2fba6bbc5
62bf09400de89c1aa77d8c2570d7f66cec0b5d36
/fnet_stack/service/ping/fnet_ping_config.h
b52f5cbbf727ddc9bd8ab8b61a9735cfa4e41018
[ "Apache-2.0" ]
permissive
butok/FNET
41b1d2ec4cc683c1b5c188a17ab6a4bb890a6af6
ea43715752e6f6823bfcc8bdc94e440443112e7c
refs/heads/master
2023-08-03T16:32:09.317085
2023-07-20T07:01:55
2023-07-20T07:01:55
50,664,554
115
40
Apache-2.0
2023-07-20T07:01:56
2016-01-29T13:39:30
C
UTF-8
C
false
false
2,678
h
fnet_ping_config.h
/************************************************************************** * * Copyright 2011-2018 by Andrey Butok. FNET Community. * *************************************************************************** * * 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. * *************************************************************************** * * PING service configuration file. * ***************************************************************************/ /************************************************************************** * !!!DO NOT MODIFY THIS FILE!!! **************************************************************************/ #ifndef _FNET_PING_CONFIG_H_ #define _FNET_PING_CONFIG_H_ /*! @addtogroup fnet_ping_config */ /*! @{ */ /**************************************************************************/ /*! * @def FNET_CFG_PING * @brief PING service support: * - @c 1 = is enabled. * - @b @c 0 = is disabled (Default value). ******************************************************************************/ #ifndef FNET_CFG_PING #define FNET_CFG_PING (0) #endif /**************************************************************************/ /*! * @def FNET_CFG_PING_PACKET_MAX * @brief The maximum size of the echo request packet. It defines send * and receive buffer size, used by the PING service.@n * Default value is @b @c 64. * @showinitializer ******************************************************************************/ #ifndef FNET_CFG_PING_PACKET_MAX #define FNET_CFG_PING_PACKET_MAX (64U) #endif /**************************************************************************/ /*! * @def FNET_CFG_PING_IDENTIFIER * @brief The ICMP Identifier (in network byte order).@n * It is used to help match echo requests to the associated reply.@n * Default value is @b @c 1. * @showinitializer ******************************************************************************/ #ifndef FNET_CFG_PING_IDENTIFIER #define FNET_CFG_PING_IDENTIFIER (FNET_HTONS(1U)) #endif /*! @} */ #endif /* _FNET_PING_CONFIG_H_ */
996202d4db9871abfa0b8d17c131f34f91589b7c
26000e6aab937c324a9805f8727a59b644fcf7f4
/includes/windows_cconv.h
1ece48e9862528dbbafeab7d20569a24a181d5f0
[ "BSD-3-Clause" ]
permissive
judah/haskeline
e8edd4eeb9527362c18235f065661edc7907cf6b
81336ac5bf7c116b114c99a9a9cdd9e1e4491c34
refs/heads/master
2023-08-31T23:02:04.700937
2023-06-29T16:27:41
2023-06-29T16:27:41
14,008,276
207
88
BSD-3-Clause
2023-06-29T16:27:44
2013-10-31T05:19:04
Haskell
UTF-8
C
false
false
219
h
windows_cconv.h
#ifndef WINDOWS_CCONV_H #define WINDOWS_CCONV_H #if defined(i386_HOST_ARCH) # define WINDOWS_CCONV stdcall #elif defined(x86_64_HOST_ARCH) # define WINDOWS_CCONV ccall #else # error Unknown mingw32 arch #endif #endif
7b68d6b609d8bf7ea54c518b0bb24d7f9bf25263
99bdb3251fecee538e0630f15f6574054dfc1468
/bsp/allwinner/libraries/sunxi-hal/hal/source/phy/hal_miiphyutil.c
a990e0d5c797ba904b29ffa53b9e7386147d3f21
[ "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
16,469
c
hal_miiphyutil.c
/* * Copyright (c) 2019-2025 Allwinner Technology Co., Ltd. ALL rights reserved. * * Allwinner is a trademark of Allwinner Technology Co.,Ltd., registered in * the the People's Republic of China and other countries. * All Allwinner Technology Co.,Ltd. trademarks are used with permission. * * DISCLAIMER * THIRD PARTY LICENCES MAY BE REQUIRED TO IMPLEMENT THE SOLUTION/PRODUCT. * IF YOU NEED TO INTEGRATE THIRD PARTY’S TECHNOLOGY (SONY, DTS, DOLBY, AVS OR MPEGLA, ETC.) * IN ALLWINNERS’SDK OR PRODUCTS, YOU SHALL BE SOLELY RESPONSIBLE TO OBTAIN * ALL APPROPRIATELY REQUIRED THIRD PARTY LICENCES. * ALLWINNER SHALL HAVE NO WARRANTY, INDEMNITY OR OTHER OBLIGATIONS WITH RESPECT TO MATTERS * COVERED UNDER ANY REQUIRED THIRD PARTY LICENSE. * YOU ARE SOLELY RESPONSIBLE FOR YOUR USAGE OF THIRD PARTY’S TECHNOLOGY. * * * THIS SOFTWARE IS PROVIDED BY ALLWINNER"AS IS" AND TO THE MAXIMUM EXTENT * PERMITTED BY LAW, ALLWINNER EXPRESSLY DISCLAIMS ALL WARRANTIES OF ANY KIND, * WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING WITHOUT LIMITATION REGARDING * THE TITLE, NON-INFRINGEMENT, ACCURACY, CONDITION, COMPLETENESS, PERFORMANCE * OR MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * IN NO EVENT SHALL ALLWINNER 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 <common.h> #include <typedef.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <hal_thread.h> #include <sunxi_hal_common.h> #include <sunxi_hal_miiphy.h> #include <sunxi_hal_phy.h> //#include <asm/types.h> //#include <list.h> #include <hal_mem.h> //#include <net.h> /* local debug macro */ #undef MII_DEBUG #undef debug #ifdef MII_DEBUG #define debug(fmt, args...) printf(fmt, ##args) #else #define debug(fmt, args...) #endif /* MII_DEBUG */ static struct list_head mii_devs; static struct mii_dev *current_mii; /* * Lookup the mii_dev struct by the registered device name. */ struct mii_dev *miiphy_get_dev_by_name(const char *devname) { struct list_head *entry; struct mii_dev *dev; if (!devname) { printf("NULL device name!\n"); return NULL; } list_for_each(entry, &mii_devs) { dev = list_entry(entry, struct mii_dev, link); if (strcmp(dev->name, devname) == 0) return dev; } return NULL; } /***************************************************************************** * * Initialize global data. Need to be called before any other miiphy routine. */ void miiphy_init(void) { INIT_LIST_HEAD(&mii_devs); current_mii = NULL; } static int legacy_miiphy_read(struct mii_dev *bus, int addr, int devad, int reg) { unsigned short val; int ret; struct legacy_mii_dev *ldev = bus->priv; ret = ldev->read(bus->name, addr, reg, &val); return ret ? -1 : (int)val; } static int legacy_miiphy_write(struct mii_dev *bus, int addr, int devad, int reg, uint16_t val) { struct legacy_mii_dev *ldev = bus->priv; return ldev->write(bus->name, addr, reg, val); } /***************************************************************************** * * Register read and write MII access routines for the device <name>. * This API is now deprecated. Please use mdio_alloc and mdio_register, instead. */ void miiphy_register(const char *name, int (*read)(const char *devname, unsigned char addr, unsigned char reg, unsigned short *value), int (*write)(const char *devname, unsigned char addr, unsigned char reg, unsigned short value)) { struct mii_dev *new_dev; struct legacy_mii_dev *ldev; BUG_ON(strlen(name) >= MDIO_NAME_LEN); /* check if we have unique name */ new_dev = miiphy_get_dev_by_name(name); if (new_dev) { printf("miiphy_register: non unique device name '%s'\n", name); return; } /* allocate memory */ new_dev = mdio_alloc(); ldev = malloc(sizeof(*ldev)); if (new_dev == NULL || ldev == NULL) { printf("miiphy_register: cannot allocate memory for '%s'\n", name); return; } /* initalize mii_dev struct fields */ new_dev->read = legacy_miiphy_read; new_dev->write = legacy_miiphy_write; strncpy(new_dev->name, name, MDIO_NAME_LEN); new_dev->name[MDIO_NAME_LEN - 1] = 0; ldev->read = read; ldev->write = write; new_dev->priv = ldev; printf("miiphy_register: added '%s', read=0x%08lx, write=0x%08lx\n", new_dev->name, ldev->read, ldev->write); /* add it to the list */ list_add_tail(&new_dev->link, &mii_devs); if (!current_mii) current_mii = new_dev; } struct mii_dev *mdio_alloc(void) { struct mii_dev *bus; bus = malloc(sizeof(*bus)); if (!bus) return bus; memset(bus, 0, sizeof(*bus)); /* initalize mii_dev struct fields */ INIT_LIST_HEAD(&bus->link); return bus; } int mdio_register(struct mii_dev *bus) { if (!bus || !bus->name || !bus->read || !bus->write) return -1; /* check if we have unique name */ if (miiphy_get_dev_by_name(bus->name)) { printf("mdio_register: non unique device name '%s'\n", bus->name); return -1; } /* add it to the list */ list_add_tail(&bus->link, &mii_devs); if (!current_mii) current_mii = bus; return 0; } void mdio_list_devices(void) { struct list_head *entry; list_for_each(entry, &mii_devs) { int i; struct mii_dev *bus = list_entry(entry, struct mii_dev, link); printf("%s:\n", bus->name); for (i = 0; i < PHY_MAX_ADDR; i++) { struct phy_device *phydev = bus->phymap[i]; if (phydev) { printf("%d - %s", i, phydev->drv->name); if (phydev->dev) printf(" <--> %s\n", "eth0"); else printf("\n"); } } } } int miiphy_set_current_dev(const char *devname) { struct mii_dev *dev; dev = miiphy_get_dev_by_name(devname); if (dev) { current_mii = dev; return 0; } printf("No such device: %s\n", devname); return 1; } struct mii_dev *mdio_get_current_dev(void) { return current_mii; } struct phy_device *mdio_phydev_for_ethname(const char *ethname) { struct list_head *entry; struct mii_dev *bus; list_for_each(entry, &mii_devs) { int i; bus = list_entry(entry, struct mii_dev, link); for (i = 0; i < PHY_MAX_ADDR; i++) { if (!bus->phymap[i] || !bus->phymap[i]->dev) continue; /*if (strcmp(bus->phymap[i]->dev->name, ethname) == 0) return bus->phymap[i];*/ } } printf("%s is not a known ethernet\n", ethname); return NULL; } const char *miiphy_get_current_dev(void) { if (current_mii) return current_mii->name; return NULL; } static struct mii_dev *miiphy_get_active_dev(const char *devname) { /* If the current mii is the one we want, return it */ if (current_mii) if (strcmp(current_mii->name, devname) == 0) return current_mii; /* Otherwise, set the active one to the one we want */ if (miiphy_set_current_dev(devname)) return NULL; else return current_mii; } /***************************************************************************** * * Read to variable <value> from the PHY attached to device <devname>, * use PHY address <addr> and register <reg>. * * This API is deprecated. Use phy_read on a phy_device found via phy_connect * * Returns: * 0 on success */ int miiphy_read(const char *devname, unsigned char addr, unsigned char reg, unsigned short *value) { struct mii_dev *bus; int ret; bus = miiphy_get_active_dev(devname); if (!bus) return 1; ret = bus->read(bus, addr, MDIO_DEVAD_NONE, reg); if (ret < 0) return 1; *value = (unsigned short)ret; return 0; } /***************************************************************************** * * Write <value> to the PHY attached to device <devname>, * use PHY address <addr> and register <reg>. * * This API is deprecated. Use phy_write on a phy_device found by phy_connect * * Returns: * 0 on success */ int miiphy_write(const char *devname, unsigned char addr, unsigned char reg, unsigned short value) { struct mii_dev *bus; bus = miiphy_get_active_dev(devname); if (bus) return bus->write(bus, addr, MDIO_DEVAD_NONE, reg, value); return 1; } /***************************************************************************** * * Print out list of registered MII capable devices. */ void miiphy_listdev(void) { struct list_head *entry; struct mii_dev *dev; puts("MII devices: "); list_for_each(entry, &mii_devs) { dev = list_entry(entry, struct mii_dev, link); printf("'%s' ", dev->name); } puts("\n"); if (current_mii) printf("Current device: '%s'\n", current_mii->name); } /***************************************************************************** * * Read the OUI, manufacture's model number, and revision number. * * OUI: 22 bits (unsigned int) * Model: 6 bits (unsigned char) * Revision: 4 bits (unsigned char) * * This API is deprecated. * * Returns: * 0 on success */ int miiphy_info(const char *devname, unsigned char addr, unsigned int *oui, unsigned char *model, unsigned char *rev) { unsigned int reg = 0; unsigned short tmp; if (miiphy_read(devname, addr, MII_PHYSID2, &tmp) != 0) { printf("PHY ID register 2 read failed\n"); return -1; } reg = tmp; printf("MII_PHYSID2 @ 0x%x = 0x%04x\n", addr, reg); if (reg == 0xFFFF) { /* No physical device present at this address */ return -1; } if (miiphy_read(devname, addr, MII_PHYSID1, &tmp) != 0) { printf("PHY ID register 1 read failed\n"); return -1; } reg |= tmp << 16; printf("PHY_PHYIDR[1,2] @ 0x%x = 0x%08x\n", addr, reg); *oui = (reg >> 10); *model = (unsigned char)((reg >> 4) & 0x0000003F); *rev = (unsigned char)(reg & 0x0000000F); return 0; } #ifndef CONFIG_PHYLIB /***************************************************************************** * * Reset the PHY. * * This API is deprecated. Use PHYLIB. * * Returns: * 0 on success */ #if 0 int miiphy_reset(const char *devname, unsigned char addr) { unsigned short reg; int timeout = 500; if (miiphy_read(devname, addr, MII_BMCR, &reg) != 0) { printf("PHY status read failed\n"); return -1; } if (miiphy_write(devname, addr, MII_BMCR, reg | BMCR_RESET) != 0) { printf("PHY reset failed\n"); return -1; } #ifdef CONFIG_PHY_RESET_DELAY udelay(CONFIG_PHY_RESET_DELAY); /* Intel LXT971A needs this */ #endif /* * Poll the control register for the reset bit to go to 0 (it is * auto-clearing). This should happen within 0.5 seconds per the * IEEE spec. */ reg = 0x8000; while (((reg & 0x8000) != 0) && timeout--) { if (miiphy_read(devname, addr, MII_BMCR, &reg) != 0) { printf("PHY status read failed\n"); return -1; } udelay(1000); } if ((reg & 0x8000) == 0) { return 0; } else { printf("PHY reset timed out\n"); return -1; } return 0; } #endif #endif /* !PHYLIB */ /***************************************************************************** * * Determine the ethernet speed (10/100/1000). Return 10 on error. */ int miiphy_speed(const char *devname, unsigned char addr) { uint16_t bmcr, anlpar; #if defined(CONFIG_PHY_GIGE) uint16_t btsr; /* * Check for 1000BASE-X. If it is supported, then assume that the speed * is 1000. */ if (miiphy_is_1000base_x(devname, addr)) return _1000BASET; /* * No 1000BASE-X, so assume 1000BASE-T/100BASE-TX/10BASE-T register set. */ /* Check for 1000BASE-T. */ if (miiphy_read(devname, addr, MII_STAT1000, &btsr)) { printf("PHY 1000BT status"); goto miiphy_read_failed; } if (btsr != 0xFFFF && (btsr & (PHY_1000BTSR_1000FD | PHY_1000BTSR_1000HD))) return _1000BASET; #endif /* CONFIG_PHY_GIGE */ /* Check Basic Management Control Register first. */ if (miiphy_read(devname, addr, MII_BMCR, &bmcr)) { printf("PHY speed"); goto miiphy_read_failed; } /* Check if auto-negotiation is on. */ if (bmcr & BMCR_ANENABLE) { /* Get auto-negotiation results. */ if (miiphy_read(devname, addr, MII_LPA, &anlpar)) { printf("PHY AN speed"); goto miiphy_read_failed; } return (anlpar & LPA_100) ? _100BASET : _10BASET; } /* Get speed from basic control settings. */ return (bmcr & BMCR_SPEED100) ? _100BASET : _10BASET; miiphy_read_failed: printf(" read failed, assuming 10BASE-T\n"); return _10BASET; } /***************************************************************************** * * Determine full/half duplex. Return half on error. */ int miiphy_duplex(const char *devname, unsigned char addr) { uint16_t bmcr, anlpar; #if defined(CONFIG_PHY_GIGE) uint16_t btsr; /* Check for 1000BASE-X. */ if (miiphy_is_1000base_x(devname, addr)) { /* 1000BASE-X */ if (miiphy_read(devname, addr, MII_LPA, &anlpar)) { printf("1000BASE-X PHY AN duplex"); goto miiphy_read_failed; } } /* * No 1000BASE-X, so assume 1000BASE-T/100BASE-TX/10BASE-T register set. */ /* Check for 1000BASE-T. */ if (miiphy_read(devname, addr, MII_STAT1000, &btsr)) { printf("PHY 1000BT status"); goto miiphy_read_failed; } if (btsr != 0xFFFF) { if (btsr & PHY_1000BTSR_1000FD) { return FULL; } else if (btsr & PHY_1000BTSR_1000HD) { return HALF; } } #endif /* CONFIG_PHY_GIGE */ /* Check Basic Management Control Register first. */ if (miiphy_read(devname, addr, MII_BMCR, &bmcr)) { printf("PHY duplex"); goto miiphy_read_failed; } /* Check if auto-negotiation is on. */ if (bmcr & BMCR_ANENABLE) { /* Get auto-negotiation results. */ if (miiphy_read(devname, addr, MII_LPA, &anlpar)) { printf("PHY AN duplex"); goto miiphy_read_failed; } return (anlpar & (LPA_10FULL | LPA_100FULL)) ? FULL : HALF; } /* Get speed from basic control settings. */ return (bmcr & BMCR_FULLDPLX) ? FULL : HALF; miiphy_read_failed: printf(" read failed, assuming half duplex\n"); return HALF; } /***************************************************************************** * * Return 1 if PHY supports 1000BASE-X, 0 if PHY supports 10BASE-T/100BASE-TX/ * 1000BASE-T, or on error. */ int miiphy_is_1000base_x(const char *devname, unsigned char addr) { #if defined(CONFIG_PHY_GIGE) uint16_t exsr; if (miiphy_read(devname, addr, MII_ESTATUS, &exsr)) { printf("PHY extended status read failed, assuming no " "1000BASE-X\n"); return 0; } return 0 != (exsr & (ESTATUS_1000XF | ESTATUS_1000XH)); #else return 0; #endif } #ifdef CONFIG_SYS_FAULT_ECHO_LINK_DOWN /***************************************************************************** * * Determine link status */ int miiphy_link(const char *devname, unsigned char addr) { unsigned short reg; /* dummy read; needed to latch some phys */ (void)miiphy_read(devname, addr, MII_BMSR, &reg); if (miiphy_read(devname, addr, MII_BMSR, &reg)) { printf("MII_BMSR read failed, assuming no link\n"); return 0; } /* Determine if a link is active */ if ((reg & BMSR_LSTATUS) != 0) { return 1; } else { return 0; } } #endif
d17b968a8eb80a4a721628db828f654294d38dbe
baf824f8819f90928e11480d0eae89efb60341a1
/ports/nxp_rt1050_60/uniqueID.h
65adecf05d000d3b712a161a0ee3a53c2e719103
[ "GPL-1.0-or-later", "MIT" ]
permissive
RockySong/micropython-rocky
549770723ba92cb311c468880ead0ffdd4fa8fe5
2d728f414bf8d041ca609e00448850759aade3cd
refs/heads/omv_initial_integrate
2021-05-12T12:20:18.404341
2021-01-15T01:15:48
2021-01-15T01:15:48
117,408,452
198
90
MIT
2020-08-25T03:31:32
2018-01-14T06:40:36
C
UTF-8
C
false
false
65
h
uniqueID.h
#include "py/obj.h" extern const mp_obj_type_t pyb_uniqueID_type;
c6fc05465466dc819b1cc121049fa16fdc7b1e73
fb0f9abad373cd635c2635bbdf491ea0f32da5ff
/src/native/libs/System.Native/pal_dynamicload.h
21d570363120a9426c6bf78f078a0e4e759ff0cc
[ "MIT" ]
permissive
dotnet/runtime
f6fd23936752e202f8e4d6d94f3a4f3b0e77f58f
47bb554d298e1e34c4e3895d7731e18ad1c47d02
refs/heads/main
2023-09-03T15:35:46.493337
2023-09-03T08:13:23
2023-09-03T08:13:23
210,716,005
13,765
5,179
MIT
2023-09-14T21:58:52
2019-09-24T23:36:39
C#
UTF-8
C
false
false
530
h
pal_dynamicload.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #pragma once #include "pal_compiler.h" #include "pal_types.h" PALEXPORT void* SystemNative_LoadLibrary(const char* filename); PALEXPORT void* SystemNative_GetLoadLibraryError(void); PALEXPORT void* SystemNative_GetProcAddress(void* handle, const char* symbol); PALEXPORT void SystemNative_FreeLibrary(void* handle); PALEXPORT void* SystemNative_GetDefaultSearchOrderPseudoHandle(void);
2fe6ec3f2b5381747c707c5eef28bd565a5e9506
2376f587d9ecf892b2e6af0ba8f35a387b75160d
/modules/acct_rtcp_hep/rtpp_sbuf.c
391a9354d9af589403e07bcc3b60541d7522a21b
[ "BSD-2-Clause" ]
permissive
sippy/rtpproxy
605939c4afef8cdbb78e09d8fbe1deef80a3828d
a7f1b1e3617ca8179f7ff6619d5920ecc615bd20
refs/heads/master
2023-08-27T21:37:48.239135
2023-07-24T20:33:48
2023-07-24T22:01:48
20,834,852
396
122
BSD-2-Clause
2023-01-20T00:39:46
2014-06-14T15:22:11
Makefile
UTF-8
C
false
false
5,384
c
rtpp_sbuf.c
/* * Copyright (c) 2018 Sippy Software, Inc., http://www.sippysoft.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. * */ #include <assert.h> #include <stdarg.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #if defined(RTPP_MODULE) #include "rtpp_module.h" #endif #include "rtpp_sbuf.h" int rtpp_sbuf_write(struct rtpp_sbuf *sbp, const char *format, ...) { va_list ap; int rlen, len; len = sbp->alen - RS_ULEN(sbp); assert(len > 0); va_start(ap, format); rlen = vsnprintf(sbp->cp, len, format, ap); va_end(ap); if (rlen < 0) return (SBW_ERR); if (rlen >= len) { sbp->cp[0] = '\0'; return (SBW_SHRT); } sbp->cp += rlen; return (SBW_OK); } struct rtpp_sbuf * rtpp_sbuf_ctor(int ilen) { struct rtpp_sbuf *sbp; sbp = malloc(sizeof(struct rtpp_sbuf)); if (sbp == NULL) return (NULL); memset(sbp, '\0', sizeof(struct rtpp_sbuf)); sbp->bp = sbp->cp = malloc(ilen); if (sbp->bp == NULL) { free(sbp); return (NULL); } sbp->cp[0] = '\0'; sbp->alen = ilen; return(sbp); } void rtpp_sbuf_dtor(struct rtpp_sbuf *sbp) { free(sbp->bp); free(sbp); } int rtpp_sbuf_extend(struct rtpp_sbuf *sbp, int nlen) { void *nbp, *ncp; assert(nlen > sbp->alen); nbp = realloc(sbp->bp, nlen); if (nbp == NULL) return (-1); sbp->alen = nlen; if (sbp->bp != nbp) { ncp = nbp + RS_ULEN(sbp); sbp->cp = ncp; sbp->bp = nbp; } return (0); } #if defined(rtpp_sbuf_selftest) #include <stdint.h> #include "rtpp_memdeb_internal.h" #include "libexecinfo/stacktraverse.h" #include "libexecinfo/execinfo.h" #include "config_pp.h" #if !defined(NO_ERR_H) #include <err.h> #include "rtpp_util.h" #else #include "rtpp_util.h" #endif #define errx_ifnot(expr) \ if (!(expr)) \ errx(1, "`%s` check has failed in %s() at %s:%d", #expr, __func__, \ __FILE__, __LINE__); RTPP_MEMDEB_APP_STATIC; int rtpp_sbuf_selftest(void) { struct rtpp_sbuf *sbp; int rval; const char *longtest = "INFO:GLOBAL:rtpp_proc_async_run: ncycles=2600 load=0.068641"; RTPP_MEMDEB_APP_INIT(); sbp = rtpp_sbuf_ctor(6); errx_ifnot(sbp != NULL); errx_ifnot(sbp->alen == 6); errx_ifnot(sbp->cp == sbp->bp); errx_ifnot(RS_ULEN(sbp) == 0); rval = rtpp_sbuf_write(sbp, "%d", 12345); errx_ifnot(rval == SBW_OK); errx_ifnot(sbp->cp[0] == '\0'); errx_ifnot(strcmp(sbp->bp, "12345") == 0); errx_ifnot(RS_ULEN(sbp) == 5); rval = rtpp_sbuf_write(sbp, "%s", "F"); errx_ifnot(rval == SBW_SHRT); errx_ifnot(sbp->cp[0] == '\0'); errx_ifnot(strcmp(sbp->bp, "12345") == 0); errx_ifnot(RS_ULEN(sbp) == 5); errx_ifnot(rtpp_sbuf_extend(sbp, 7) == 0); errx_ifnot(RS_ULEN(sbp) == 5); errx_ifnot(strcmp(sbp->bp, "12345") == 0); rval = rtpp_sbuf_write(sbp, "%s", "F"); errx_ifnot(rval == SBW_OK); errx_ifnot(RS_ULEN(sbp) == 6); errx_ifnot(strcmp(sbp->bp, "12345F") == 0); do { errx_ifnot(rtpp_sbuf_extend(sbp, sbp->alen + 1) == 0); rval = rtpp_sbuf_write(sbp, "%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n", longtest, longtest, longtest, longtest, longtest, longtest, longtest, longtest, longtest, longtest, longtest, longtest, longtest, longtest, longtest, longtest, longtest, longtest, longtest, longtest, longtest, longtest, longtest, longtest); } while (rval == SBW_SHRT); errx_ifnot(rval == SBW_OK); errx_ifnot(RS_ULEN(sbp) == 1446); errx_ifnot(sbp->alen == RS_ULEN(sbp) + 1); errx_ifnot(strncmp(sbp->bp, "12345F", 6) == 0); rval = RS_ULEN(sbp); rtpp_sbuf_reset(sbp); errx_ifnot(sbp->cp == sbp->bp); errx_ifnot(sbp->cp[0] == '\0'); errx_ifnot(sbp->alen == rval + 1); rtpp_sbuf_dtor(sbp); rval = rtpp_memdeb_dumpstats(MEMDEB_SYM, 0); return (rval); } #endif /* rtpp_sbuf_selftest */ void rtpp_sbuf_reset(struct rtpp_sbuf *sbp) { sbp->cp = sbp->bp; sbp->cp[0] = '\0'; }
1758fa9227688537a74517a9a9c68e55928e229f
128268956eeb76f92d5e89e7002f005bfaddd59d
/get_flags_from_cpuid.c
20692f39fd7677ff0ebd754093e839da3c60d503
[ "BSD-2-Clause" ]
permissive
openstack/liberasurecode
f95dba37221e534494596842799b664700fa5cbc
cc7de356d6c210b84622264b2ff93a22abdbaf8d
refs/heads/master
2023-07-30T11:19:27.008201
2023-07-13T19:33:26
2023-07-13T19:33:26
58,626,647
136
45
BSD-2-Clause
2021-08-08T06:11:00
2016-05-12T09:15:38
C
UTF-8
C
false
false
2,924
c
get_flags_from_cpuid.c
#include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #define EDX_MMX_BIT 23 #define EDX_SSE_BIT 25 #define EDX_SSE2_BIT 26 #define ECX_SSE3_BIT 0 #define ECX_SSSE3_BIT 9 #define ECX_SSE41_BIT 19 #define ECX_SSE42_BIT 20 #define ECX_AVXOS_BIT 27 #define ECX_AVX_BIT 28 uint64_t get_supported_flags() { uint64_t supp_comp_flgs = 0; char *comp_flag = NULL; char SUPPORTED_COMP_FLAGS[] ="FLAGSFROMAUTOCONF\0"; for (comp_flag = strtok(SUPPORTED_COMP_FLAGS, " "); comp_flag != NULL; comp_flag = strtok(NULL, " ")) { if (strncmp(comp_flag, "-m", 2) != 0) { fprintf(stderr, "Invalid comp_flag: %s\n", comp_flag); exit(2); } if (strcmp(comp_flag, "-mmmx\0") == 0) { supp_comp_flgs |= (1 << EDX_MMX_BIT); } if (strcmp(comp_flag, "-msse\0") == 0) { supp_comp_flgs |= (1 << EDX_SSE_BIT); } if (strcmp(comp_flag, "-msse2\0") == 0) { supp_comp_flgs |= (1 << EDX_SSE2_BIT); } if (strcmp(comp_flag, "-msse3\0") == 0) { supp_comp_flgs |= (1 << ECX_SSE3_BIT); } if (strcmp(comp_flag, "-mssse3\0") == 0) { supp_comp_flgs |= (1 << ECX_SSSE3_BIT); } if (strcmp(comp_flag, "-msse4.1\0") == 0) { supp_comp_flgs |= (1 << ECX_SSE41_BIT); } if (strcmp(comp_flag, "-msse4.2\0") == 0) { supp_comp_flgs |= (1 << ECX_SSE42_BIT); } if (strcmp(comp_flag, "-mavx\0") == 0) { supp_comp_flgs |= (1 << ECX_AVX_BIT); } } return supp_comp_flgs; } int is_supported(int cpuid_reg, uint64_t comp_flags, int feature_bit) { return ((cpuid_reg >> feature_bit) & 0x1) && ((comp_flags >> feature_bit) & 0x1); } int main(int argc, char** argv) { int feature_eax, feature_ebx, feature_ecx, feature_edx; uint64_t supp_comp_flgs = get_supported_flags(); FILE *f = fopen("compiler_flags", "w"); __asm__("cpuid" : "=a" (feature_eax), "=b" (feature_ebx), "=c" (feature_ecx), "=d" (feature_edx) : "a" (0x00000001)); if (is_supported(feature_edx, supp_comp_flgs, EDX_MMX_BIT)) { fprintf(f, "-mmmx -DINTEL_MMX "); } if (is_supported(feature_edx, supp_comp_flgs, EDX_SSE_BIT)) { fprintf(f, "-msse -DINTEL_SSE "); } if (is_supported(feature_edx, supp_comp_flgs, EDX_SSE2_BIT)) { fprintf(f, "-msse2 -DINTEL_SSE2 "); } if (is_supported(feature_ecx, supp_comp_flgs, ECX_SSE3_BIT)) { fprintf(f, "-msse3 -DINTEL_SSE3 "); } if (is_supported(feature_ecx, supp_comp_flgs, ECX_SSSE3_BIT)) { fprintf(f, "-mssse3 -DINTEL_SSSE3 "); } if (is_supported(feature_ecx, supp_comp_flgs, ECX_SSE41_BIT)) { fprintf(f, "-msse4.1 -DINTEL_SSE41 "); } if (is_supported(feature_ecx, supp_comp_flgs, ECX_SSE42_BIT)) { fprintf(f, "-msse4.2 -DINTEL_SSE42 "); } if (is_supported(feature_ecx, supp_comp_flgs, ECX_AVX_BIT)) { if ((feature_ecx >> ECX_AVXOS_BIT) & 0x1) { fprintf(f, "-mavx -DINTEL_AVX "); } } fclose(f); return 0; }
e75118f4b7f3174ea44254fc2dbe5b656dd531f2
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/u-boot_new/drivers/net/fm/eth.c
218a5ed17509a6d2d50eb83cbebabd55fe110a53
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "GPL-2.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
18,038
c
eth.c
/* * Copyright 2009-2012 Freescale Semiconductor, Inc. * Dave Liu <daveliu@freescale.com> * * SPDX-License-Identifier: GPL-2.0+ */ #include <common.h> #include <asm/io.h> #include <malloc.h> #include <net.h> #include <hwconfig.h> #include <fm_eth.h> #include <fsl_mdio.h> #include <miiphy.h> #include <phy.h> #include <asm/fsl_dtsec.h> #include <asm/fsl_tgec.h> #include <asm/fsl_memac.h> #include "fm.h" static struct eth_device *devlist[NUM_FM_PORTS]; static int num_controllers; #if defined(CONFIG_MII) || defined(CONFIG_CMD_MII) && !defined(BITBANGMII) #define TBIANA_SETTINGS (TBIANA_ASYMMETRIC_PAUSE | TBIANA_SYMMETRIC_PAUSE | \ TBIANA_FULL_DUPLEX) #define TBIANA_SGMII_ACK 0x4001 #define TBICR_SETTINGS (TBICR_ANEG_ENABLE | TBICR_RESTART_ANEG | \ TBICR_FULL_DUPLEX | TBICR_SPEED1_SET) /* Configure the TBI for SGMII operation */ static void dtsec_configure_serdes(struct fm_eth *priv) { #ifdef CONFIG_SYS_FMAN_V3 u32 value; struct mii_dev bus; bus.priv = priv->mac->phyregs; /* SGMII IF mode + AN enable */ value = PHY_SGMII_IF_MODE_AN | PHY_SGMII_IF_MODE_SGMII; memac_mdio_write(&bus, 0, MDIO_DEVAD_NONE, 0x14, value); /* Dev ability according to SGMII specification */ value = PHY_SGMII_DEV_ABILITY_SGMII; memac_mdio_write(&bus, 0, MDIO_DEVAD_NONE, 0x4, value); /* Adjust link timer for SGMII - 1.6 ms in units of 8 ns = 2 * 10^5 = 0x30d40 */ memac_mdio_write(&bus, 0, MDIO_DEVAD_NONE, 0x13, 0x3); memac_mdio_write(&bus, 0, MDIO_DEVAD_NONE, 0x12, 0xd40); /* Restart AN */ value = PHY_SGMII_CR_DEF_VAL | PHY_SGMII_CR_RESET_AN; memac_mdio_write(&bus, 0, MDIO_DEVAD_NONE, 0, value); #else struct dtsec *regs = priv->mac->base; struct tsec_mii_mng *phyregs = priv->mac->phyregs; /* * Access TBI PHY registers at given TSEC register offset as * opposed to the register offset used for external PHY accesses */ tsec_local_mdio_write(phyregs, in_be32(&regs->tbipa), 0, TBI_TBICON, TBICON_CLK_SELECT); tsec_local_mdio_write(phyregs, in_be32(&regs->tbipa), 0, TBI_ANA, TBIANA_SGMII_ACK); tsec_local_mdio_write(phyregs, in_be32(&regs->tbipa), 0, TBI_CR, TBICR_SETTINGS); #endif } static void dtsec_init_phy(struct eth_device *dev) { struct fm_eth *fm_eth = dev->priv; #ifndef CONFIG_SYS_FMAN_V3 struct dtsec *regs = (struct dtsec *)CONFIG_SYS_FSL_FM1_DTSEC1_ADDR; /* Assign a Physical address to the TBI */ out_be32(&regs->tbipa, CONFIG_SYS_TBIPA_VALUE); #endif if (fm_eth->enet_if == PHY_INTERFACE_MODE_SGMII) dtsec_configure_serdes(fm_eth); } static int tgec_is_fibre(struct eth_device *dev) { struct fm_eth *fm = dev->priv; char phyopt[20]; sprintf(phyopt, "fsl_fm%d_xaui_phy", fm->fm_index + 1); return hwconfig_arg_cmp(phyopt, "xfi"); } #endif static u16 muram_readw(u16 *addr) { u32 base = (u32)addr & ~0x3; u32 val32 = *(u32 *)base; int byte_pos; u16 ret; byte_pos = (u32)addr & 0x3; if (byte_pos) ret = (u16)(val32 & 0x0000ffff); else ret = (u16)((val32 & 0xffff0000) >> 16); return ret; } static void muram_writew(u16 *addr, u16 val) { u32 base = (u32)addr & ~0x3; u32 org32 = *(u32 *)base; u32 val32; int byte_pos; byte_pos = (u32)addr & 0x3; if (byte_pos) val32 = (org32 & 0xffff0000) | val; else val32 = (org32 & 0x0000ffff) | ((u32)val << 16); *(u32 *)base = val32; } static void bmi_rx_port_disable(struct fm_bmi_rx_port *rx_port) { int timeout = 1000000; clrbits_be32(&rx_port->fmbm_rcfg, FMBM_RCFG_EN); /* wait until the rx port is not busy */ while ((in_be32(&rx_port->fmbm_rst) & FMBM_RST_BSY) && timeout--) ; } static void bmi_rx_port_init(struct fm_bmi_rx_port *rx_port) { /* set BMI to independent mode, Rx port disable */ out_be32(&rx_port->fmbm_rcfg, FMBM_RCFG_IM); /* clear FOF in IM case */ out_be32(&rx_port->fmbm_rim, 0); /* Rx frame next engine -RISC */ out_be32(&rx_port->fmbm_rfne, NIA_ENG_RISC | NIA_RISC_AC_IM_RX); /* Rx command attribute - no order, MR[3] = 1 */ clrbits_be32(&rx_port->fmbm_rfca, FMBM_RFCA_ORDER | FMBM_RFCA_MR_MASK); setbits_be32(&rx_port->fmbm_rfca, FMBM_RFCA_MR(4)); /* enable Rx statistic counters */ out_be32(&rx_port->fmbm_rstc, FMBM_RSTC_EN); /* disable Rx performance counters */ out_be32(&rx_port->fmbm_rpc, 0); } static void bmi_tx_port_disable(struct fm_bmi_tx_port *tx_port) { int timeout = 1000000; clrbits_be32(&tx_port->fmbm_tcfg, FMBM_TCFG_EN); /* wait until the tx port is not busy */ while ((in_be32(&tx_port->fmbm_tst) & FMBM_TST_BSY) && timeout--) ; } static void bmi_tx_port_init(struct fm_bmi_tx_port *tx_port) { /* set BMI to independent mode, Tx port disable */ out_be32(&tx_port->fmbm_tcfg, FMBM_TCFG_IM); /* Tx frame next engine -RISC */ out_be32(&tx_port->fmbm_tfne, NIA_ENG_RISC | NIA_RISC_AC_IM_TX); out_be32(&tx_port->fmbm_tfene, NIA_ENG_RISC | NIA_RISC_AC_IM_TX); /* Tx command attribute - no order, MR[3] = 1 */ clrbits_be32(&tx_port->fmbm_tfca, FMBM_TFCA_ORDER | FMBM_TFCA_MR_MASK); setbits_be32(&tx_port->fmbm_tfca, FMBM_TFCA_MR(4)); /* enable Tx statistic counters */ out_be32(&tx_port->fmbm_tstc, FMBM_TSTC_EN); /* disable Tx performance counters */ out_be32(&tx_port->fmbm_tpc, 0); } static int fm_eth_rx_port_parameter_init(struct fm_eth *fm_eth) { struct fm_port_global_pram *pram; u32 pram_page_offset; void *rx_bd_ring_base; void *rx_buf_pool; struct fm_port_bd *rxbd; struct fm_port_qd *rxqd; struct fm_bmi_rx_port *bmi_rx_port = fm_eth->rx_port; int i; /* alloc global parameter ram at MURAM */ pram = (struct fm_port_global_pram *)fm_muram_alloc(fm_eth->fm_index, FM_PRAM_SIZE, FM_PRAM_ALIGN); fm_eth->rx_pram = pram; /* parameter page offset to MURAM */ pram_page_offset = (u32)pram - fm_muram_base(fm_eth->fm_index); /* enable global mode- snooping data buffers and BDs */ pram->mode = PRAM_MODE_GLOBAL; /* init the Rx queue descriptor pionter */ pram->rxqd_ptr = pram_page_offset + 0x20; /* set the max receive buffer length, power of 2 */ muram_writew(&pram->mrblr, MAX_RXBUF_LOG2); /* alloc Rx buffer descriptors from main memory */ rx_bd_ring_base = malloc(sizeof(struct fm_port_bd) * RX_BD_RING_SIZE); if (!rx_bd_ring_base) return 0; memset(rx_bd_ring_base, 0, sizeof(struct fm_port_bd) * RX_BD_RING_SIZE); /* alloc Rx buffer from main memory */ rx_buf_pool = malloc(MAX_RXBUF_LEN * RX_BD_RING_SIZE); if (!rx_buf_pool) return 0; memset(rx_buf_pool, 0, MAX_RXBUF_LEN * RX_BD_RING_SIZE); /* save them to fm_eth */ fm_eth->rx_bd_ring = rx_bd_ring_base; fm_eth->cur_rxbd = rx_bd_ring_base; fm_eth->rx_buf = rx_buf_pool; /* init Rx BDs ring */ rxbd = (struct fm_port_bd *)rx_bd_ring_base; for (i = 0; i < RX_BD_RING_SIZE; i++) { rxbd->status = RxBD_EMPTY; rxbd->len = 0; rxbd->buf_ptr_hi = 0; rxbd->buf_ptr_lo = (u32)rx_buf_pool + i * MAX_RXBUF_LEN; rxbd++; } /* set the Rx queue descriptor */ rxqd = &pram->rxqd; muram_writew(&rxqd->gen, 0); muram_writew(&rxqd->bd_ring_base_hi, 0); rxqd->bd_ring_base_lo = (u32)rx_bd_ring_base; muram_writew(&rxqd->bd_ring_size, sizeof(struct fm_port_bd) * RX_BD_RING_SIZE); muram_writew(&rxqd->offset_in, 0); muram_writew(&rxqd->offset_out, 0); /* set IM parameter ram pointer to Rx Frame Queue ID */ out_be32(&bmi_rx_port->fmbm_rfqid, pram_page_offset); return 1; } static int fm_eth_tx_port_parameter_init(struct fm_eth *fm_eth) { struct fm_port_global_pram *pram; u32 pram_page_offset; void *tx_bd_ring_base; struct fm_port_bd *txbd; struct fm_port_qd *txqd; struct fm_bmi_tx_port *bmi_tx_port = fm_eth->tx_port; int i; /* alloc global parameter ram at MURAM */ pram = (struct fm_port_global_pram *)fm_muram_alloc(fm_eth->fm_index, FM_PRAM_SIZE, FM_PRAM_ALIGN); fm_eth->tx_pram = pram; /* parameter page offset to MURAM */ pram_page_offset = (u32)pram - fm_muram_base(fm_eth->fm_index); /* enable global mode- snooping data buffers and BDs */ pram->mode = PRAM_MODE_GLOBAL; /* init the Tx queue descriptor pionter */ pram->txqd_ptr = pram_page_offset + 0x40; /* alloc Tx buffer descriptors from main memory */ tx_bd_ring_base = malloc(sizeof(struct fm_port_bd) * TX_BD_RING_SIZE); if (!tx_bd_ring_base) return 0; memset(tx_bd_ring_base, 0, sizeof(struct fm_port_bd) * TX_BD_RING_SIZE); /* save it to fm_eth */ fm_eth->tx_bd_ring = tx_bd_ring_base; fm_eth->cur_txbd = tx_bd_ring_base; /* init Tx BDs ring */ txbd = (struct fm_port_bd *)tx_bd_ring_base; for (i = 0; i < TX_BD_RING_SIZE; i++) { txbd->status = TxBD_LAST; txbd->len = 0; txbd->buf_ptr_hi = 0; txbd->buf_ptr_lo = 0; } /* set the Tx queue decriptor */ txqd = &pram->txqd; muram_writew(&txqd->bd_ring_base_hi, 0); txqd->bd_ring_base_lo = (u32)tx_bd_ring_base; muram_writew(&txqd->bd_ring_size, sizeof(struct fm_port_bd) * TX_BD_RING_SIZE); muram_writew(&txqd->offset_in, 0); muram_writew(&txqd->offset_out, 0); /* set IM parameter ram pointer to Tx Confirmation Frame Queue ID */ out_be32(&bmi_tx_port->fmbm_tcfqid, pram_page_offset); return 1; } static int fm_eth_init(struct fm_eth *fm_eth) { if (!fm_eth_rx_port_parameter_init(fm_eth)) return 0; if (!fm_eth_tx_port_parameter_init(fm_eth)) return 0; return 1; } static int fm_eth_startup(struct fm_eth *fm_eth) { struct fsl_enet_mac *mac; mac = fm_eth->mac; /* Rx/TxBDs, Rx/TxQDs, Rx buff and parameter ram init */ if (!fm_eth_init(fm_eth)) return 0; /* setup the MAC controller */ mac->init_mac(mac); /* For some reason we need to set SPEED_100 */ if (((fm_eth->enet_if == PHY_INTERFACE_MODE_SGMII) || (fm_eth->enet_if == PHY_INTERFACE_MODE_QSGMII)) && mac->set_if_mode) mac->set_if_mode(mac, fm_eth->enet_if, SPEED_100); /* init bmi rx port, IM mode and disable */ bmi_rx_port_init(fm_eth->rx_port); /* init bmi tx port, IM mode and disable */ bmi_tx_port_init(fm_eth->tx_port); return 1; } static void fmc_tx_port_graceful_stop_enable(struct fm_eth *fm_eth) { struct fm_port_global_pram *pram; pram = fm_eth->tx_pram; /* graceful stop transmission of frames */ pram->mode |= PRAM_MODE_GRACEFUL_STOP; sync(); } static void fmc_tx_port_graceful_stop_disable(struct fm_eth *fm_eth) { struct fm_port_global_pram *pram; pram = fm_eth->tx_pram; /* re-enable transmission of frames */ pram->mode &= ~PRAM_MODE_GRACEFUL_STOP; sync(); } static int fm_eth_open(struct eth_device *dev, bd_t *bd) { struct fm_eth *fm_eth; struct fsl_enet_mac *mac; #ifdef CONFIG_PHYLIB int ret; #endif fm_eth = (struct fm_eth *)dev->priv; mac = fm_eth->mac; /* setup the MAC address */ if (dev->enetaddr[0] & 0x01) { printf("%s: MacAddress is multcast address\n", __func__); return 1; } mac->set_mac_addr(mac, dev->enetaddr); /* enable bmi Rx port */ setbits_be32(&fm_eth->rx_port->fmbm_rcfg, FMBM_RCFG_EN); /* enable MAC rx/tx port */ mac->enable_mac(mac); /* enable bmi Tx port */ setbits_be32(&fm_eth->tx_port->fmbm_tcfg, FMBM_TCFG_EN); /* re-enable transmission of frame */ fmc_tx_port_graceful_stop_disable(fm_eth); #ifdef CONFIG_PHYLIB ret = phy_startup(fm_eth->phydev); if (ret) { printf("%s: Could not initialize\n", fm_eth->phydev->dev->name); return ret; } #else fm_eth->phydev->speed = SPEED_1000; fm_eth->phydev->link = 1; fm_eth->phydev->duplex = DUPLEX_FULL; #endif /* set the MAC-PHY mode */ mac->set_if_mode(mac, fm_eth->enet_if, fm_eth->phydev->speed); if (!fm_eth->phydev->link) printf("%s: No link.\n", fm_eth->phydev->dev->name); return fm_eth->phydev->link ? 0 : -1; } static void fm_eth_halt(struct eth_device *dev) { struct fm_eth *fm_eth; struct fsl_enet_mac *mac; fm_eth = (struct fm_eth *)dev->priv; mac = fm_eth->mac; /* graceful stop the transmission of frames */ fmc_tx_port_graceful_stop_enable(fm_eth); /* disable bmi Tx port */ bmi_tx_port_disable(fm_eth->tx_port); /* disable MAC rx/tx port */ mac->disable_mac(mac); /* disable bmi Rx port */ bmi_rx_port_disable(fm_eth->rx_port); phy_shutdown(fm_eth->phydev); } static int fm_eth_send(struct eth_device *dev, void *buf, int len) { struct fm_eth *fm_eth; struct fm_port_global_pram *pram; struct fm_port_bd *txbd, *txbd_base; u16 offset_in; int i; fm_eth = (struct fm_eth *)dev->priv; pram = fm_eth->tx_pram; txbd = fm_eth->cur_txbd; /* find one empty TxBD */ for (i = 0; txbd->status & TxBD_READY; i++) { udelay(100); if (i > 0x1000) { printf("%s: Tx buffer not ready\n", dev->name); return 0; } } /* setup TxBD */ txbd->buf_ptr_hi = 0; txbd->buf_ptr_lo = (u32)buf; txbd->len = len; sync(); txbd->status = TxBD_READY | TxBD_LAST; sync(); /* update TxQD, let RISC to send the packet */ offset_in = muram_readw(&pram->txqd.offset_in); offset_in += sizeof(struct fm_port_bd); if (offset_in >= muram_readw(&pram->txqd.bd_ring_size)) offset_in = 0; muram_writew(&pram->txqd.offset_in, offset_in); sync(); /* wait for buffer to be transmitted */ for (i = 0; txbd->status & TxBD_READY; i++) { udelay(100); if (i > 0x10000) { printf("%s: Tx error\n", dev->name); return 0; } } /* advance the TxBD */ txbd++; txbd_base = (struct fm_port_bd *)fm_eth->tx_bd_ring; if (txbd >= (txbd_base + TX_BD_RING_SIZE)) txbd = txbd_base; /* update current txbd */ fm_eth->cur_txbd = (void *)txbd; return 1; } static int fm_eth_recv(struct eth_device *dev) { struct fm_eth *fm_eth; struct fm_port_global_pram *pram; struct fm_port_bd *rxbd, *rxbd_base; u16 status, len; u8 *data; u16 offset_out; fm_eth = (struct fm_eth *)dev->priv; pram = fm_eth->rx_pram; rxbd = fm_eth->cur_rxbd; status = rxbd->status; while (!(status & RxBD_EMPTY)) { if (!(status & RxBD_ERROR)) { data = (u8 *)rxbd->buf_ptr_lo; len = rxbd->len; NetReceive(data, len); } else { printf("%s: Rx error\n", dev->name); return 0; } /* clear the RxBDs */ rxbd->status = RxBD_EMPTY; rxbd->len = 0; sync(); /* advance RxBD */ rxbd++; rxbd_base = (struct fm_port_bd *)fm_eth->rx_bd_ring; if (rxbd >= (rxbd_base + RX_BD_RING_SIZE)) rxbd = rxbd_base; /* read next status */ status = rxbd->status; /* update RxQD */ offset_out = muram_readw(&pram->rxqd.offset_out); offset_out += sizeof(struct fm_port_bd); if (offset_out >= muram_readw(&pram->rxqd.bd_ring_size)) offset_out = 0; muram_writew(&pram->rxqd.offset_out, offset_out); sync(); } fm_eth->cur_rxbd = (void *)rxbd; return 1; } static int fm_eth_init_mac(struct fm_eth *fm_eth, struct ccsr_fman *reg) { struct fsl_enet_mac *mac; int num; void *base, *phyregs = NULL; num = fm_eth->num; #ifdef CONFIG_SYS_FMAN_V3 if (fm_eth->type == FM_ETH_10G_E) { /* 10GEC1/10GEC2 use mEMAC9/mEMAC10 * 10GEC3/10GEC4 use mEMAC1/mEMAC2 * so it needs to change the num. */ if (fm_eth->num >= 2) num -= 2; else num += 8; } base = &reg->memac[num].fm_memac; phyregs = &reg->memac[num].fm_memac_mdio; #else /* Get the mac registers base address */ if (fm_eth->type == FM_ETH_1G_E) { base = &reg->mac_1g[num].fm_dtesc; phyregs = &reg->mac_1g[num].fm_mdio.miimcfg; } else { base = &reg->mac_10g[num].fm_10gec; phyregs = &reg->mac_10g[num].fm_10gec_mdio; } #endif /* alloc mac controller */ mac = malloc(sizeof(struct fsl_enet_mac)); if (!mac) return 0; memset(mac, 0, sizeof(struct fsl_enet_mac)); /* save the mac to fm_eth struct */ fm_eth->mac = mac; #ifdef CONFIG_SYS_FMAN_V3 init_memac(mac, base, phyregs, MAX_RXBUF_LEN); #else if (fm_eth->type == FM_ETH_1G_E) init_dtsec(mac, base, phyregs, MAX_RXBUF_LEN); else init_tgec(mac, base, phyregs, MAX_RXBUF_LEN); #endif return 1; } static int init_phy(struct eth_device *dev) { struct fm_eth *fm_eth = dev->priv; struct phy_device *phydev = NULL; u32 supported; #ifdef CONFIG_PHYLIB if (fm_eth->type == FM_ETH_1G_E) dtsec_init_phy(dev); if (fm_eth->bus) { phydev = phy_connect(fm_eth->bus, fm_eth->phyaddr, dev, fm_eth->enet_if); } if (!phydev) { printf("Failed to connect\n"); return -1; } if (fm_eth->type == FM_ETH_1G_E) { supported = (SUPPORTED_10baseT_Half | SUPPORTED_10baseT_Full | SUPPORTED_100baseT_Half | SUPPORTED_100baseT_Full | SUPPORTED_1000baseT_Full); } else { supported = SUPPORTED_10000baseT_Full; if (tgec_is_fibre(dev)) phydev->port = PORT_FIBRE; } phydev->supported &= supported; phydev->advertising = phydev->supported; fm_eth->phydev = phydev; phy_config(phydev); #endif return 0; } int fm_eth_initialize(struct ccsr_fman *reg, struct fm_eth_info *info) { struct eth_device *dev; struct fm_eth *fm_eth; int i, num = info->num; /* alloc eth device */ dev = (struct eth_device *)malloc(sizeof(struct eth_device)); if (!dev) return 0; memset(dev, 0, sizeof(struct eth_device)); /* alloc the FMan ethernet private struct */ fm_eth = (struct fm_eth *)malloc(sizeof(struct fm_eth)); if (!fm_eth) return 0; memset(fm_eth, 0, sizeof(struct fm_eth)); /* save off some things we need from the info struct */ fm_eth->fm_index = info->index - 1; /* keep as 0 based for muram */ fm_eth->num = num; fm_eth->type = info->type; fm_eth->rx_port = (void *)&reg->port[info->rx_port_id - 1].fm_bmi; fm_eth->tx_port = (void *)&reg->port[info->tx_port_id - 1].fm_bmi; /* set the ethernet max receive length */ fm_eth->max_rx_len = MAX_RXBUF_LEN; /* init global mac structure */ if (!fm_eth_init_mac(fm_eth, reg)) return 0; /* keep same as the manual, we call FMAN1, FMAN2, DTSEC1, DTSEC2, etc */ if (fm_eth->type == FM_ETH_1G_E) sprintf(dev->name, "FM%d@DTSEC%d", info->index, num + 1); else sprintf(dev->name, "FM%d@TGEC%d", info->index, num + 1); devlist[num_controllers++] = dev; dev->iobase = 0; dev->priv = (void *)fm_eth; dev->init = fm_eth_open; dev->halt = fm_eth_halt; dev->send = fm_eth_send; dev->recv = fm_eth_recv; fm_eth->dev = dev; fm_eth->bus = info->bus; fm_eth->phyaddr = info->phy_addr; fm_eth->enet_if = info->enet_if; /* startup the FM im */ if (!fm_eth_startup(fm_eth)) return 0; if (init_phy(dev)) return 0; /* clear the ethernet address */ for (i = 0; i < 6; i++) dev->enetaddr[i] = 0; eth_register(dev); return 1; }
56a6c9e5165fed880015457d67845fa80e17408b
8a51a96f61699f0318315ccc89cef39f6866f2b5
/src/include/commands/createas.h
3647f96f73329eb4ed9f6975ccf6545cea31746a
[ "PostgreSQL" ]
permissive
postgres/postgres
979febf2b41c00090d1256228f768f33e7ef3b6f
b5934bfd6071fed3a38cea0cfaa93afda63d9c0c
refs/heads/master
2023-08-31T00:10:01.373472
2023-08-30T23:07:48
2023-08-30T23:07:48
927,442
13,691
4,807
NOASSERTION
2023-09-09T13:59:15
2010-09-21T11:35:45
C
UTF-8
C
false
false
989
h
createas.h
/*------------------------------------------------------------------------- * * createas.h * prototypes for createas.c. * * * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * src/include/commands/createas.h * *------------------------------------------------------------------------- */ #ifndef CREATEAS_H #define CREATEAS_H #include "catalog/objectaddress.h" #include "nodes/params.h" #include "parser/parse_node.h" #include "tcop/dest.h" #include "utils/queryenvironment.h" extern ObjectAddress ExecCreateTableAs(ParseState *pstate, CreateTableAsStmt *stmt, ParamListInfo params, QueryEnvironment *queryEnv, QueryCompletion *qc); extern int GetIntoRelEFlags(IntoClause *intoClause); extern DestReceiver *CreateIntoRelDestReceiver(IntoClause *intoClause); extern bool CreateTableAsRelExists(CreateTableAsStmt *ctas); #endif /* CREATEAS_H */
53415184c0c5c02b9beae6c9ca8413419c2a30c1
086cfcedd5742ff9377d3d235ddc3c3664fa0d94
/c/array/ex1.c
fc316e1ce6d82d6fd1463a99e21f871a21ca39a0
[ "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
346
c
ex1.c
#include <stdio.h> void hello( int (*x)[4]) { for (int i = 0; i < 4; i++) printf("%d\n", x[0][i]); } void hello2(int **p) { for (int i = 0; i < 4; i++) printf("%d\n", *(*p + 4 + i)); } int main(void) { int a[3][4] = {0}; a[1][0] = 1; a[1][1] = 2; a[1][2] = 3; a[1][3] = 4; hello(&a[1]); hello2((int **) &a[1][0]); return 0; }
2f3b3b2958e3dba73d513dff41f71a52759b2132
98f272704d0a3849acd1a2eec8a99285308633dc
/regress/test-json-controlchars.c
0fbaa1ea409fa15e014acd7e92c8cf68ba027584
[ "ISC" ]
permissive
kristapsdz/kcgi
35a6f8c86a3816be222c8f2bd44d0683c5595318
575e9267f73ab575a0082242a41a6b77c487914e
refs/heads/master
2023-06-08T08:47:47.785495
2022-04-02T19:17:13
2022-04-02T19:17:13
50,068,029
285
77
ISC
2023-07-16T20:03:48
2016-01-20T23:30:58
C
UTF-8
C
false
false
2,341
c
test-json-controlchars.c
/* $Id$ */ /* * Copyright (c) 2018 Kristaps Dzonsons <kristaps@bsd.lv> * * 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 "../config.h" #include <stdarg.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <curl/curl.h> #include "../kcgi.h" #include "../kcgijson.h" #include "regress.h" static size_t bufcb(void *contents, size_t sz, size_t nm, void *dat) { struct kcgi_buf *buf = dat; if (KCGI_OK != kcgi_buf_write(contents, nm * sz, buf)) return 0; return nm * sz; } static int parent(CURL *curl) { struct kcgi_buf buf; int rc; memset(&buf, 0, sizeof(struct kcgi_buf)); curl_easy_setopt(curl, CURLOPT_URL, "http://localhost:17123/index.json"); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, bufcb); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buf); if (CURLE_OK != curl_easy_perform(curl)) return 0; rc = 0 == strcmp(buf.buf, "{\"für\": \"für\"}"); free(buf.buf); return rc; } static int child(void) { struct kreq r; struct kjsonreq req; const char *page[] = { "index" }; int rc = 0; if (KCGI_OK != khttp_parse(&r, NULL, 0, page, 1, 0)) return(0); if (r.page) goto out; if (KMIME_APP_JSON != r.mime) goto out; rc = 1; khttp_head(&r, kresps[KRESP_STATUS], "%s", khttps[KHTTP_200]); khttp_head(&r, kresps[KRESP_CONTENT_TYPE], "%s", kmimetypes[r.mime]); khttp_body(&r); kjson_open(&req, &r); kjson_obj_open(&req); kjson_putstringp(&req, "für", "für"); kjson_obj_close(&req); kjson_close(&req); out: khttp_free(&r); return(rc); } int main(int argc, char *argv[]) { return(regress_cgi(parent, child) ? EXIT_SUCCESS : EXIT_FAILURE); }
63ec56c1fae3ff4f6e67c08859de695f46b603fd
5f86fc385c7dcfcb5b166cdea7c8b13057b8bb5f
/enclave/core/init_fini.c
47bfc0d10cf7b533e8412c25fe82bb764c7411fb
[ "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
6,251
c
init_fini.c
// Copyright (c) Open Enclave SDK contributors. // Licensed under the MIT License. #include "init_fini.h" #include <openenclave/internal/globals.h> /* **============================================================================== ** ** oe_call_init_functions() ** ** Call all global initialization functions. The compiler generates an ** array of initialization functions which it places in one of the dynamic ** program segments (where elf64_phdr_t.type == PT_DYNAMIC). This segment ** contains two elf64_dyn structures whose tags are given as follows: ** ** elf64_dyn.d_tag == DT_INIT_ARRAY ** elf64_dyn.d_tag == DT_INIT_ARRAYSZ ** ** The first (INIT_ARRAY) is an array of function pointers to global ** initializers. The second (INIT_ARRAYSZ) is the size of that array in ** bytes (not the number of functions). When the compiler encounters the ** following extern declarations in user object code ** ** extern void (*__init_array_start)(void); ** extern void (*__init_array_end)(void); ** ** it generates corresponding definitions that refer to INIT_ARRAY and ** INIT_ARRAYSZ as follows: ** ** __init_array_start = INIT_ARRAY ** __init_array_end = INIT_ARRAY + DT_INIT_ARRAYSZ; ** ** Initialization functions are of two types: ** ** (1) C functions tagged with __attribute__(constructor) ** (2) C++ global constructors ** ** oe_call_init_functions() invokes all functions in this array from start ** to finish. ** ** Here are some notes on initialization functions that relate to C++ ** construction. There is typically one initialization function per ** compilation unit, so that calling that function will invoke all global ** constructors for that compilation unit. Further, for each object ** being constructed, the compiler generates a function that: ** ** (1) Invokes the constructor ** (2) Invokes oe_cxa_atexit() passing it the destructor ** ** Note that the FINI_ARRAY (used by oe_call_fini_functions) does not ** contain any finalization functions for calling destructors. Instead ** the oe_cxa_atexit() implementation must save the destructor functions ** and invoke them on enclave termination. ** **============================================================================== */ static void _call_init_functions( void (**init_array_start)(void), void (**init_array_end)(void)) { void (**fn)(void); for (fn = init_array_start; fn < init_array_end; fn++) { (*fn)(); } } void oe_call_init_functions(void) { extern void (*__init_array_start)(void); extern void (*__init_array_end)(void); const uint64_t start_address = (uint64_t)__oe_get_enclave_start_address(); const oe_enclave_module_info_t* module_info = oe_get_module_info(); if (module_info && module_info->base_rva && module_info->init_array_rva && module_info->init_array_size) { uint64_t init_array_start = start_address + module_info->init_array_rva; uint64_t init_array_end = start_address + module_info->init_array_rva + module_info->init_array_size; _call_init_functions( (void (**)(void))(init_array_start), (void (**)(void))(init_array_end)); } _call_init_functions(&__init_array_start, &__init_array_end); } /* **============================================================================== ** ** oe_call_fini_functions() ** ** Call all global finalization functions. The compiler generates an array ** of finalization functions which it places in one of the dynamic program ** segments (where elf64_phdr_t.type == PT_DYNAMIC). This segment contains ** two elf64_dyn structures whose tags are given as follows: ** ** elf64_dyn.d_tag == DT_FINI_ARRAY ** elf64_dyn.d_tag == DT_FINI_ARRAYSZ ** ** The first (FINI_ARRAY) is an array of function pointers to the ** finalizers. The second (FINI_ARRAYSZ) is the size of that array in ** bytes (not the number of functions). When the compiler encounters the ** following extern declarations in user object code: ** ** extern void (*__fini_array_start)(void); ** extern void (*__fini_array_end)(void); ** ** it generates corresponding definitions that refer to FINI_ARRAY and ** FINI_ARRAYSZ as follows: ** ** __fini_array_start = FINI_ARRAY ** __fini_array_end = FINI_ARRAY + DT_FINI_ARRAYSZ; ** ** Finalization functions are of one type of interest: ** ** (1) C functions tagged with __attribute__(destructor) ** ** Note that global C++ destructors are not referenced by the FINI_ARRAY. ** Destructors are passed to oe_cxa_atexit() by invoking functions in the ** INIT_ARRAY (see oe_call_init_functions() for more information). ** ** oe_call_fini_functions() invokes all functions in this array from finish ** to start (reverse order). ** ** For more information on C++ destruction invocation, see the ** "Itanium C++ ABI". ** **============================================================================== */ static void _call_fini_functions( void (**fini_array_start)(void), void (**fini_array_end)(void)) { void (**fn)(void); for (fn = fini_array_end - 1; fn >= fini_array_start; fn--) { (*fn)(); } } void oe_call_fini_functions(void) { extern void (*__fini_array_start)(void); extern void (*__fini_array_end)(void); const uint64_t start_address = (uint64_t)__oe_get_enclave_start_address(); const oe_enclave_module_info_t* module_info = oe_get_module_info(); _call_fini_functions(&__fini_array_start, &__fini_array_end); if (module_info && module_info->base_rva && module_info->fini_array_rva && module_info->fini_array_size) { uint64_t fini_array_start = start_address + module_info->fini_array_rva; uint64_t fini_array_end = start_address + module_info->fini_array_rva + module_info->fini_array_size; _call_fini_functions( (void (**)(void))(fini_array_start), (void (**)(void))(fini_array_end)); } }
19ae51074734784acacfa77a481a370e9ee3d55c
da1500e0d3040497614d5327d2461a22e934b4d8
/third_party/musl/src/starboard/locale/setlocale.c
d3f3ecb831b1d50af00f06013585b0d9bc1b68b9
[ "BSD-3-Clause", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-musl-exception", "MIT", "GPL-1.0-or-later", "LGPL-2.0-or-later", "Apache-2.0" ]
permissive
youtube/cobalt
34085fc93972ebe05b988b15410e99845efd1968
acefdaaadd3ef46f10f63d1acae2259e4024d383
refs/heads/main
2023-09-01T13:09:47.225174
2023-09-01T08:54:54
2023-09-01T08:54:54
50,049,789
169
80
BSD-3-Clause
2023-09-14T21:50:50
2016-01-20T18:11:34
null
UTF-8
C
false
false
314
c
setlocale.c
#include <locale.h> #include "locale_impl.h" #include "starboard/common/log.h" #include "starboard/system.h" // Starboard provides a mechanism for querying for the system's locale name, but // not for setting it. char *setlocale(int cat, const char *name) { SB_DCHECK(!name); return SbSystemGetLocaleId(); }
ed119de16049feb2f660a6571abb0d89531dfdf7
5afb6e0e2b32e96b46bc4cfdd3fee8c266c2420b
/source/mainMenu.c
f9539a07b5425c807c52ee91dfb0b8a8f8d8572c
[ "MIT" ]
permissive
Nanquitas/BootNTR
f4ad52ee883941543cbafd1be35cde8847e90ece
e0e754e6110b9d169bb9248eced29a709fd21495
refs/heads/master
2022-09-18T23:37:45.010732
2022-08-30T10:35:40
2022-08-30T10:35:40
56,778,440
716
80
MIT
2018-08-04T12:11:33
2016-04-21T14:02:23
C
UTF-8
C
false
false
5,017
c
mainMenu.c
#include "main.h" #include "draw.h" #include "config.h" #include "button.h" #include <time.h> extern bootNtrConfig_t *bnConfig; static button_t *V32Button; static button_t *V33Button; static button_t *V36Button; static sprite_t *desiredVersionSprite; static sprite_t *tinyButtonBGSprite; static sprite_t *pressExitSprite; static bool userTouch = false; void selectVersion(u32 mode) { V32Button->disable(V32Button); V33Button->disable(V33Button); V36Button->disable(V36Button); userTouch = true; switch(mode) { case 1: bnConfig->versionToLaunch = V32; break; case 2: bnConfig->versionToLaunch = V33; break; case 3: bnConfig->versionToLaunch = V36; break; default: break; } } void initMainMenu(void) { static bool inited = false; if (inited) return; inited = true; if (!bnConfig->isMode3) { sprite_t *sprite; newSpriteFromPNG(&desiredVersionSprite, "romfs:/sprites/textSprites/touchDesiredVersion.png"); newSpriteFromPNG(&tinyButtonBGSprite, "romfs:/sprites/tinyButtonBackground.png"); setSpritePos(desiredVersionSprite, 34.0f, 7.0f); changeBottomHeader(desiredVersionSprite); newSpriteFromPNG(&sprite, "romfs:/sprites/textSprites/32Version.png"); V32Button = newButton(11.0f, 35.0f, selectVersion, 1, tinyButtonBGSprite, sprite); newSpriteFromPNG(&sprite, "romfs:/sprites/textSprites/33Version.png"); V33Button = newButton(11.0f, 94.0f, selectVersion, 2, tinyButtonBGSprite, sprite); newSpriteFromPNG(&sprite, "romfs:/sprites/textSprites/36Version.png"); V36Button = newButton(11.0f, 152.0f, selectVersion, 3, tinyButtonBGSprite, sprite); } newSpriteFromPNG(&pressExitSprite, "romfs:/sprites/textSprites/pressBExit.png"); setSpritePos(pressExitSprite, 180.0f, 217.0f); changeBottomFooter(pressExitSprite); } void exitMainMenu(void) { if (!bnConfig->isMode3) { destroyButton(V32Button); destroyButton(V33Button); destroyButton(V36Button); deleteSprite(tinyButtonBGSprite); deleteSprite(desiredVersionSprite); } deleteSprite(pressExitSprite); } static const char * versionString[] = { "3.2", "3.3", "3.6" }; int mainMenu(void) { time_t baseTime; int timer; int timerBak; u32 keys; bool noTimer; static bool first = true; if (first && !bnConfig->isMode3) { V32Button->show(V32Button); V33Button->show(V33Button); V36Button->show(V36Button); addBottomObject(V32Button); addBottomObject(V33Button); addBottomObject(V36Button); first = false; } waitAllKeysReleased(); if (!bnConfig->isMode3 && !bnConfig->config->flags) noTimer = true; else noTimer = false; appInfoDisableAutoUpdate(); if (!noTimer) { timerBak = timer = TIMER; newAppStatus(DEFAULT_COLOR, CENTER | TINY | SKINNY, "Loading %s in %d", versionString[bnConfig->versionToLaunch], timerBak); baseTime = time(NULL); updateUI(); } keys = 0; while (userTouch == false) { keys = hidKeysDown() | hidKeysHeld(); if (keys == (KEY_L | KEY_R | KEY_X | KEY_DUP)) goto dumpMode; if (keys && !bnConfig->isMode3) { noTimer = true; removeAppStatus(); updateUI(); } if (abort_and_exit()) goto abort; if (!noTimer) { timer -= (time(NULL) - baseTime); if (timer != timerBak) { timerBak = timer; removeAppStatus(); newAppStatus(DEFAULT_COLOR, CENTER | TINY | SKINNY, "Loading %s in %d", versionString[bnConfig->versionToLaunch], timerBak); baseTime = time(NULL); } if (timer <= 0) break; } updateUI(); } if (!noTimer) removeAppStatus(); appInfoEnableAutoUpdate(); newAppStatus(DEFAULT_COLOR, CENTER | TINY | SKINNY, "Loading %s ...", versionString[bnConfig->versionToLaunch]); return (1); abort: appInfoEnableAutoUpdate(); return (0); dumpMode: removeAppStatus(); appInfoEnableAutoUpdate(); ntrDumpMode(); return (2); } void ntrDumpMode(void) { newAppTop(DEFAULT_COLOR, TINY | SKINNY, "Starting NTR Dump Mode..."); newAppTop(DEFAULT_COLOR, TINY, ""); newAppStatus(DEFAULT_COLOR, TINY | SKINNY | CENTER, "NTR Dump Mode"); newAppStatus(DEFAULT_COLOR, TINY | SKINNY | CENTER, "See the top screen"); updateUI(); launchNTRDumpMode(); newAppTop(DEFAULT_COLOR, TINY | SKINNY, "Done !"); newAppTop(DEFAULT_COLOR, TINY | SKINNY | NEWLINE, "Exiting Dump Mode..."); newAppStatus(DEFAULT_COLOR, CENTER | BOLD | NEWLINE, "Done !"); updateUI(); }
cb9f862deb13202cd9b0c1d86c730b764ff5f7ff
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
/sys/arch/pmax/stand/common/if_prom.c
c6f5771a3c2aa881515345e3a946a75d6bf8fffb
[]
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
6,969
c
if_prom.c
/* $NetBSD: if_prom.c,v 1.11 2011/01/12 15:32:43 tsutsui Exp $ */ /* Copyright (c) 1999 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Gregory McGarry. * * 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/param.h> #include <sys/types.h> #include <net/if_ether.h> #include <netinet/in.h> #include <netinet/in_systm.h> #include <netinet/ip.h> #include <lib/libsa/stand.h> #include <lib/libsa/net.h> #include <lib/libsa/netif.h> #include <lib/libsa/dev_net.h> #include <lib/libkern/libkern.h> #include <machine/dec_prom.h> #include <stand/common/common.h> #ifdef NET_DEBUG #define DPRINTF(x) printf(x) #else #define DPRINTF(x) #endif #ifdef NET_DEBUG void dump_packet_info(void *, int); #endif /* * For some reason the proms won't pass arp responses back to us. I * have checked if the first parameter to bootread/bootwrite do anything * but it doesn't appear so. Therefore, we stop the upper layers from * sending arp requests in the first place, by monitoring packets which * come in and filling the arp cache ourselves. - gmcgarry */ #ifdef FILL_ARPCACHE struct arp_list { struct in_addr addr; u_char ea[6]; }; extern struct arp_list arp_list[8]; extern int arp_num; void fill_arpcache(void *, int); #endif /* forward declarations */ int prom_probe(struct netif *, void *); int prom_match(struct netif *, void *); void prom_init(struct iodesc *, void *); int prom_get(struct iodesc *, void *, size_t, saseconds_t); int prom_put(struct iodesc *, void *, size_t); void prom_end(struct netif *); extern struct netif_stats prom_stats[]; struct netif_dif prom_ifs[] = { /* dif_unit dif_nsel dif_stats dif_private */ { 0, 1, &prom_stats[0], 0, }, }; #define NPROM_IFS (sizeof(prom_ifs) / sizeof(prom_ifs[0])) struct netif_stats prom_stats[NPROM_IFS]; struct netif_driver prom_netif_driver = { "prom", /* netif_bname */ prom_match, /* netif_match */ prom_probe, /* netif_probe */ prom_init, /* netif_init */ prom_get, /* netif_get */ prom_put, /* netif_put */ prom_end, /* netif_end */ prom_ifs, /* netif_ifs */ NPROM_IFS /* netif_nifs */ }; static int sc_fd; /* PROM file id */ int prom_match(struct netif *nif, void *machdep_hint) { DPRINTF(("prom_match: called\n")); return 1; } int prom_probe(struct netif *nif, void *machdep_hint) { DPRINTF(("prom_probe: called\n")); return 0; } void prom_init(struct iodesc *desc, void *machdep_hint) { struct netif *nif; char *device, *enet; uint8_t *cp, *dest; int i; DPRINTF(("prom_init: called\n")); try_bootp = 1; /* * Get our hardware address (this prom call is one of the rare ones * which is the same for new and old proms) */ enet = (*callv->_getenv)("enet"); if (enet == NULL) { printf("No `enet' environment variable found.\n" "Set MAC address to `enet' manually by setenv command.\n"); prom_restart(); /* NOTREACHED */ } #ifdef NET_DEBUG if (debug) printf("enet=%s\n", enet); #endif #define atox(c) (((c) <= '9') ? ((c) - '0') : ((toupper(c) - 'A') + 10)) cp = (uint8_t *)enet; dest = desc->myea; for (i = 0; i < 6; i++) { if (isxdigit(*cp)) { *dest = atox(*cp); cp++; if (isxdigit(*cp)) { *dest = (*dest << 4) | atox(*cp); cp++; } } dest++; cp++; /* skip '-' or ':' etc. */ } desc->xid = 0x66d30000; nif = desc->io_netif; device = nif->nif_driver->netif_bname; if (callv == &callvec) sc_fd = prom_open(device, 0); else sc_fd = (*callv->_bootinit)(device); if (sc_fd < 0) printf("problem initialising device\n"); } int prom_put(struct iodesc *desc, void *pkt, size_t len) { int s; DPRINTF(("prom_put: called\n")); #ifdef NET_DEBUG if (debug) dump_packet_info(pkt,len); #endif if (callv == &callvec) s = prom_write(sc_fd, pkt, len); else { s = (*callv->_bootwrite)(0, pkt, len); (*callv->_wbflush)(); /* didn't really make a difference */ } if (s < 0) return EIO; return s; } int prom_get(struct iodesc *desc, void *pkt, size_t len, saseconds_t timeout) { int s; satime_t t; DPRINTF(("prom_get: called\n")); t = getsecs(); s = 0; while (((getsecs() - t) < timeout) && !s) { if (callv == &callvec) s = prom_read(sc_fd, pkt, len); else s = (*callv->_bootread)(0, pkt, len); } #ifdef FILL_ARPCACHE if (s > 0) fill_arpcache(pkt,s); #endif return s; } void prom_end(struct netif *nif) { DPRINTF(("prom_end: called\n")); if (callv == &callvec) prom_close(sc_fd); } #ifdef FILL_ARPCACHE void fill_arpcache(void *pkt, int len) { int i; struct arp_list *al; struct ether_header *eh = (struct ether_header *)pkt; struct ip *ih = (struct ip *)(eh + 1); #ifdef NET_DEBUG if (debug) dump_packet_info(pkt, len); #endif if (ntohs(eh->ether_type) == 0x0800) { /* check arp cache */ for (i=0, al=arp_list; i<arp_num; ++i, ++al) { if (al->addr.s_addr == ih->ip_src.s_addr) { /* already in cache */ return; } } if (arp_num > 7) arp_num = 1; /* recycle */ al->addr.s_addr = ih->ip_src.s_addr; for (i = 0; i < 6; i++) al->ea[i] = eh->ether_shost[i]; ++arp_num; } } #endif #ifdef NET_DEBUG void dump_packet_info(void *pkt, int len) { struct ether_header *eh = (struct ether_header *)pkt; struct ip *ih = (struct ip *)(eh + 1); printf("ether_dhost = %s\n", ether_sprintf(eh->ether_dhost)); printf("ether_shost = %s\n", ether_sprintf(eh->ether_shost)); printf("ether_type = 0x%x\n", ntohs(eh->ether_type)); if (ntohs(eh->ether_type) == 0x0800) { printf("ip packet version %d\n", ih->ip_v); printf("source ip: 0x%x\n", ih->ip_src.s_addr); printf("dest ip: 0x%x\n", ih->ip_dst.s_addr); } } #endif
1c6cacde2f3f59f25ce1321e43810b1c6853a60f
376e1818d427b5e4d32fa6dd6c7b71e9fd88afdb
/lang/gcc7/patches/patch-gcc_config_arm_netbsd-elf.h
97573f1a869e13912ef41f0c444fa82c3063f96a
[]
no_license
NetBSD/pkgsrc
a0732c023519650ef821ab89c23ab6ab59e25bdb
d042034ec4896cc5b47ed6f2e5b8802d9bc5c556
refs/heads/trunk
2023-09-01T07:40:12.138283
2023-09-01T05:25:19
2023-09-01T05:25:19
88,439,572
321
138
null
2023-07-12T22:34:14
2017-04-16T20:04:15
null
UTF-8
C
false
false
2,848
h
patch-gcc_config_arm_netbsd-elf.h
$NetBSD: patch-gcc_config_arm_netbsd-elf.h,v 1.1 2018/06/17 19:50:52 maya Exp $ netbsd/arm EABI support --- gcc/config/arm/netbsd-elf.h.orig 2017-01-01 12:07:43.000000000 +0000 +++ gcc/config/arm/netbsd-elf.h @@ -27,9 +27,20 @@ /* arm.h defaults to ARM6 CPU. */ -/* This defaults us to little-endian. */ -#ifndef TARGET_ENDIAN_DEFAULT -#define TARGET_ENDIAN_DEFAULT 0 +/* Default EABI to armv5t so that thumb shared libraries work. + The ARM926EH-S core is the default for armv5te, so set + SUBTARGET_CPU_DEFAULT to achieve this. */ + +#define SUBTARGET_CPU_DEFAULT \ + (ARM_DEFAULT_ABI != ARM_ABI_APCS && ARM_DEFAULT_ABI != ARM_ABI_ATPCS \ + ? TARGET_CPU_arm926ejs : TARGET_CPU_arm6) + +/* TARGET_BIG_ENDIAN_DEFAULT is set in + config.gcc for big endian configurations. */ +#if TARGET_BIG_ENDIAN_DEFAULT +#define TARGET_ENDIAN_DEFAULT MASK_BIG_END +#else +#define TARGET_ENDIAN_DEFAULT 0 #endif #undef MULTILIB_DEFAULTS @@ -43,6 +54,7 @@ #undef ARM_DEFAULT_ABI #define ARM_DEFAULT_ABI ARM_ABI_ATPCS +#undef TARGET_OS_CPP_BUILTINS #define TARGET_OS_CPP_BUILTINS() \ do \ { \ @@ -55,25 +67,21 @@ #undef SUBTARGET_EXTRA_ASM_SPEC #define SUBTARGET_EXTRA_ASM_SPEC \ - "-matpcs %{" FPIE_OR_FPIC_SPEC ":-k}" + "-matpcs %{mabi=aapcs*:-meabi=5} %{" FPIE_OR_FPIC_SPEC ":-k}" /* Default to full VFP if -mfloat-abi=hard is specified. */ #undef SUBTARGET_ASM_FLOAT_SPEC #define SUBTARGET_ASM_FLOAT_SPEC \ - "%{mfloat-abi=hard:{!mfpu=*:-mfpu=vfp}}" - -#undef SUBTARGET_EXTRA_SPECS -#define SUBTARGET_EXTRA_SPECS \ - { "subtarget_extra_asm_spec", SUBTARGET_EXTRA_ASM_SPEC }, \ - { "subtarget_asm_float_spec", SUBTARGET_ASM_FLOAT_SPEC }, \ - { "netbsd_link_spec", NETBSD_LINK_SPEC_ELF }, \ - { "netbsd_entry_point", NETBSD_ENTRY_POINT }, + "%{mhard-float:%{!mfpu=*:-mfpu=vfp}} \ + %{mfloat-abi=hard:%{!mfpu=*:-mfpu=vfp}}" #define NETBSD_ENTRY_POINT "__start" #undef LINK_SPEC #define LINK_SPEC \ - "-X %{mbig-endian:-EB} %{mlittle-endian:-EL} \ + "-X \ + %{mbig-endian:-EB %{-mabi=aapcs*:-m armelfb_nbsd_eabi}} \ + %{mlittle-endian:-EL %{-mabi=aapcs*:-m armelf_nbsd_eabi}} \ %(netbsd_link_spec)" /* Make GCC agree with <machine/ansi.h>. */ @@ -84,6 +92,12 @@ #undef PTRDIFF_TYPE #define PTRDIFF_TYPE "long int" +#undef INTPTR_TYPE +#define INTPTR_TYPE PTRDIFF_TYPE + +#undef UINTPTR_TYPE +#define UINTPTR_TYPE SIZE_TYPE + /* We don't have any limit on the length as out debugger is GDB. */ #undef DBX_CONTIN_LENGTH @@ -157,3 +171,12 @@ while (0) #undef FPUTYPE_DEFAULT #define FPUTYPE_DEFAULT "vfp" +/* Ensure that libgcc does not attempt to define __[CD]TOR_LIST__[] for APCS, + which belongs in crtbegin on NetBSD. */ +#ifndef __ARM_EABI__ +#define CTOR_LISTS_DEFINED_EXTERNALLY +#endif + +#undef FPUTYPE_DEFAULT +#define FPUTYPE_DEFAULT "vfp" +
649acbecdace66059a2d5a7f0a139d7ec9c3ef1e
baa9fffc817a2a993d4ecc774d3f277783308c20
/src/uct/ib/ud/base/ud_iface.h
62932b9e76cf180bb4f086beaa70c9cc3eb423ed
[ "BSD-3-Clause" ]
permissive
openucx/ucx
9a0f2205295afbdf3cff14b5d24af781b123f5ea
73a48700badb7cbace64d94b82f408e2a26fca32
refs/heads/master
2023-09-01T16:51:26.913950
2023-09-01T13:02:25
2023-09-01T13:02:25
25,379,390
966
420
NOASSERTION
2023-09-14T12:29:35
2014-10-17T22:17:24
C
UTF-8
C
false
false
19,211
h
ud_iface.h
/** * Copyright (c) NVIDIA CORPORATION & AFFILIATES, 2001-2020. ALL RIGHTS RESERVED. * * See file LICENSE for terms. */ #ifndef UCT_UD_IFACE_H #define UCT_UD_IFACE_H #include <uct/base/uct_worker.h> #include <uct/ib/base/ib_device.h> #include <uct/ib/base/ib_iface.h> #include <ucs/datastruct/sglib_wrapper.h> #include <ucs/datastruct/ptr_array.h> #include <ucs/datastruct/sglib.h> #include <ucs/datastruct/list.h> #include <ucs/datastruct/arbiter.h> #include <ucs/async/async.h> #include <ucs/time/timer_wheel.h> #include <ucs/sys/compiler_def.h> #include <ucs/sys/sock.h> #include "ud_def.h" #include "ud_ep.h" #include "ud_iface_common.h" BEGIN_C_DECLS #define UCT_UD_MIN_TIMER_TIMER_BACKOFF 1.0 /** @file ud_iface.h */ enum { UCT_UD_IFACE_STAT_RX_DROP, UCT_UD_IFACE_STAT_LAST }; /* flags for uct_ud_iface_send_ctl() */ enum { UCT_UD_IFACE_SEND_CTL_FLAG_INLINE = UCS_BIT(0), UCT_UD_IFACE_SEND_CTL_FLAG_SOLICITED = UCS_BIT(1), UCT_UD_IFACE_SEND_CTL_FLAG_SIGNALED = UCS_BIT(2) }; /* TODO: maybe tx_moderation can be defined at compile-time since tx completions are used only to know how much space is there in tx qp */ typedef struct uct_ud_iface_config { uct_ib_iface_config_t super; uct_ud_iface_common_config_t ud_common; double linger_timeout; double peer_timeout; double min_poke_time; double timer_tick; double timer_backoff; double event_timer_tick; int dgid_check; unsigned max_window; unsigned rx_async_max_poll; } uct_ud_iface_config_t; #if UCT_UD_EP_DEBUG_HOOKS typedef ucs_status_t (*uct_ud_iface_hook_t)(uct_ud_iface_t *iface, uct_ud_neth_t *neth); #define UCT_UD_IFACE_HOOK_DECLARE(_name) \ uct_ud_iface_hook_t _name; #define UCT_UD_IFACE_HOOK_CALL_RX(_iface, _neth, _len) \ if ((_iface)->rx.hook(_iface, _neth) != UCS_OK) { \ ucs_trace_data("RX: dropping packet"); \ return; \ } #define UCT_UD_IFACE_HOOK_INIT(_iface) { \ (_iface)->rx.hook = uct_ud_iface_null_hook; \ } static inline ucs_status_t uct_ud_iface_null_hook(uct_ud_iface_t *iface, uct_ud_neth_t *neth) { return UCS_OK; } #else #define UCT_UD_IFACE_HOOK_DECLARE(_name) #define UCT_UD_IFACE_HOOK_CALL_RX(_iface, _neth, _len) #define UCT_UD_IFACE_HOOK_INIT(_iface) #endif typedef struct uct_ud_iface_ops { uct_ib_iface_ops_t super; unsigned (*async_progress)(uct_ud_iface_t *iface); uint16_t (*send_ctl)(uct_ud_ep_t *ud_ep, uct_ud_send_skb_t *skb, const uct_ud_iov_t *iov, uint16_t iovcnt, int flags, int max_log_sge); ucs_status_t (*ep_new)(const uct_ep_params_t* params, uct_ep_h *ep_p); void (*ep_free)(uct_ep_h ep); ucs_status_t (*create_qp)(uct_ib_iface_t *iface, uct_ib_qp_attr_t *attr, struct ibv_qp **qp_p); void (*destroy_qp)(uct_ud_iface_t *ud_iface); ucs_status_t (*unpack_peer_address)(uct_ud_iface_t *iface, const uct_ib_address_t *ib_addr, const uct_ud_iface_addr_t *if_addr, int path_index, void *address_p); void* (*ep_get_peer_address)(uct_ud_ep_t *ud_ep); size_t (*get_peer_address_length)(); const char* (*peer_address_str)(const uct_ud_iface_t *iface, const void *address, char *str, size_t max_size); } uct_ud_iface_ops_t; /* device GIDs set */ KHASH_TYPE(uct_ud_iface_gid, union ibv_gid, char); static UCS_F_ALWAYS_INLINE khint32_t uct_ud_iface_kh_gid_hash_func(union ibv_gid gid) { return kh_int64_hash_func(gid.global.subnet_prefix ^ gid.global.interface_id); } static UCS_F_ALWAYS_INLINE int uct_ud_gid_equal(const union ibv_gid *a, const union ibv_gid *b, size_t length) { ucs_assert(length <= sizeof(union ibv_gid)); return !memcmp(UCS_PTR_BYTE_OFFSET(a, sizeof(*a) - length), UCS_PTR_BYTE_OFFSET(b, sizeof(*b) - length), length); } static UCS_F_ALWAYS_INLINE int uct_ud_iface_kh_gid_hash_equal(union ibv_gid a, union ibv_gid b) { return uct_ud_gid_equal(&a, &b, sizeof(a)); } KHASH_IMPL(uct_ud_iface_gid, union ibv_gid, char, 0, uct_ud_iface_kh_gid_hash_func, uct_ud_iface_kh_gid_hash_equal) struct uct_ud_iface { uct_ib_iface_t super; struct ibv_qp *qp; struct { ucs_mpool_t mp; unsigned available; unsigned quota; unsigned async_max_poll; ucs_queue_head_t pending_q; UCT_UD_IFACE_HOOK_DECLARE(hook) } rx; struct { uct_ud_send_skb_t *skb; /* ready to use skb */ ucs_mpool_t mp; /* got async events but pending queue was not dispatched */ uint8_t async_before_pending; int16_t available; unsigned unsignaled; ucs_queue_head_t outstanding_q; ucs_arbiter_t pending_q; ucs_queue_head_t async_comp_q; ucs_twheel_t timer; ucs_time_t tick; double timer_backoff; unsigned timer_sweep_count; } tx; struct { ucs_time_t linger_timeout; ucs_time_t peer_timeout; ucs_time_t min_poke_time; unsigned tx_qp_len; unsigned rx_qp_len; unsigned max_inline; int check_grh_dgid; unsigned max_window; } config; UCS_STATS_NODE_DECLARE(stats) ucs_conn_match_ctx_t conn_match_ctx; ucs_ptr_array_t eps; struct { ucs_time_t tick; int timer_id; void *event_arg; uct_async_event_cb_t event_cb; unsigned disable; } async; /* used for GRH GID filter */ struct { union ibv_gid last; unsigned last_len; khash_t(uct_ud_iface_gid) hash; } gid_table; }; UCS_CLASS_DECLARE(uct_ud_iface_t, uct_ud_iface_ops_t*, uct_iface_ops_t*, uct_md_h, uct_worker_h, const uct_iface_params_t*, const uct_ud_iface_config_t*, uct_ib_iface_init_attr_t*) struct uct_ud_ctl_hdr { uint8_t type; uint8_t reserved[3]; union { struct { uct_ud_ep_addr_t ep_addr; uct_ud_ep_conn_sn_t conn_sn; uint8_t path_index; } conn_req; struct { uint32_t src_ep_id; } conn_rep; uint32_t data; }; uct_ud_peer_name_t peer; /* For CREQ packet, IB address follows */ } UCS_S_PACKED; extern ucs_config_field_t uct_ud_iface_config_table[]; ucs_status_t uct_ud_iface_query(uct_ud_iface_t *iface, uct_iface_attr_t *iface_attr, size_t am_max_iov, size_t am_max_hdr); void uct_ud_iface_release_desc(uct_recv_desc_t *self, void *desc); ucs_status_t uct_ud_iface_get_address(uct_iface_h tl_iface, uct_iface_addr_t *addr); void uct_ud_iface_add_ep(uct_ud_iface_t *iface, uct_ud_ep_t *ep); void uct_ud_iface_remove_ep(uct_ud_iface_t *iface, uct_ud_ep_t *ep); ucs_status_t uct_ud_iface_flush(uct_iface_h tl_iface, unsigned flags, uct_completion_t *comp); ucs_status_t uct_ud_iface_complete_init(uct_ud_iface_t *iface); ucs_status_t uct_ud_iface_set_event_cb(uct_ud_iface_t *iface, ucs_async_event_cb_t event_cb); void uct_ud_iface_remove_async_handlers(uct_ud_iface_t *iface); void uct_ud_dump_packet(uct_base_iface_t *iface, uct_am_trace_type_t type, void *data, size_t length, size_t valid_length, char *buffer, size_t max); union ibv_gid* uct_ud_grh_get_dgid(struct ibv_grh *grh, size_t dgid_len); uct_ud_send_skb_t *uct_ud_iface_ctl_skb_get(uct_ud_iface_t *iface); /* management of connecting endpoints (cep) Such endpoint are created either by explicitely calling ep_create_connected() or implicitely as a result of UD connection protocol. Calling ep_create_connected() may reuse already existing endpoint that was implicitely created. UD connection protocol The protocol allows connection establishment in environment where UD packets can be dropped, duplicated or reordered. The connection is done as 3 way handshake: 1: CREQ (src_if_addr, src_ep_addr, conn_sn) Connection request. It includes source interface address, source ep address and connection id. Connection id is essentially a counter of endpoints that are created by ep_create_connected(). The counter is per destination interface. Purpose of conn_sn is to ensure order between multiple CREQ packets and to handle simultaneous connection establishment. The case when both sides call ep_create_connected(). The rule is that connected endpoints must have same conn_sn. 2: CREP (dest_ep_id) Connection reply. It includes id of destination endpoint and optionally ACK request flag. From this point reliability is handled by UD protocol as source and destination endpoint ids are known. Endpoint may be created upon reception of CREQ. It is possible that the endpoint already exists because CREQ is retransmitted or because of simultaneous connection. In any case endpoint connection id must be equal to connection id in CREQ. 3: ACK Ack on connection reply. It may be send as part of the data packet. Implicit endpoints reuse Endpoints created upon receive of CREP request can be re-used when application calls ep_create_connected(). */ void uct_ud_iface_cep_cleanup(uct_ud_iface_t *iface); ucs_status_t uct_ud_iface_cep_get_conn_sn(uct_ud_iface_t *iface, const uct_ib_address_t *ib_addr, const uct_ud_iface_addr_t *if_addr, int path_index, uct_ud_ep_conn_sn_t *conn_sn_p); ucs_status_t uct_ud_iface_cep_insert_ep(uct_ud_iface_t *iface, const uct_ib_address_t *ib_addr, const uct_ud_iface_addr_t *if_addr, int path_index, uct_ud_ep_conn_sn_t conn_sn, uct_ud_ep_t *ep); uct_ud_ep_t *uct_ud_iface_cep_get_ep(uct_ud_iface_t *iface, const uct_ib_address_t *ib_addr, const uct_ud_iface_addr_t *if_addr, int path_index, uct_ud_ep_conn_sn_t conn_sn, int is_private); void uct_ud_iface_cep_remove_ep(uct_ud_iface_t *iface, uct_ud_ep_t *ep); unsigned uct_ud_iface_dispatch_pending_rx_do(uct_ud_iface_t *iface); ucs_status_t uct_ud_iface_event_arm_common(uct_ud_iface_t *iface, unsigned events, uint64_t *dirs_p); void uct_ud_iface_progress_enable(uct_iface_h tl_iface, unsigned flags); void uct_ud_iface_progress_disable(uct_iface_h tl_iface, unsigned flags); void uct_ud_iface_ctl_skb_complete(uct_ud_iface_t *iface, uct_ud_ctl_desc_t *cdesc, int is_async); void uct_ud_iface_vfs_refresh(uct_iface_h iface); void uct_ud_iface_send_completion(uct_ud_iface_t *iface, uint16_t sn, int is_async); unsigned uct_ud_iface_dispatch_async_comps_do(uct_ud_iface_t *iface, uct_ud_ep_t *ep); static UCS_F_ALWAYS_INLINE int uct_ud_iface_can_tx(uct_ud_iface_t *iface) { return iface->tx.available > 0; } static UCS_F_ALWAYS_INLINE int uct_ud_iface_has_skbs(uct_ud_iface_t *iface) { return iface->tx.skb || !ucs_mpool_is_empty(&iface->tx.mp); } static inline uct_ib_address_t* uct_ud_creq_ib_addr(uct_ud_ctl_hdr_t *conn_req) { ucs_assert(conn_req->type == UCT_UD_PACKET_CREQ); return (uct_ib_address_t*)(conn_req + 1); } static UCS_F_ALWAYS_INLINE void uct_ud_enter(uct_ud_iface_t *iface) { UCS_ASYNC_BLOCK(iface->super.super.worker->async); } static UCS_F_ALWAYS_INLINE void uct_ud_leave(uct_ud_iface_t *iface) { UCS_ASYNC_UNBLOCK(iface->super.super.worker->async); } static UCS_F_ALWAYS_INLINE int uct_ud_iface_check_grh(uct_ud_iface_t *iface, void *packet, int is_grh_present, uint8_t roce_pkt_type) { struct ibv_grh *grh = (struct ibv_grh *)packet; size_t gid_len; union ibv_gid *gid; khiter_t khiter; char gid_str[128] UCS_V_UNUSED; if (!iface->config.check_grh_dgid) { return 1; } if (ucs_unlikely(!is_grh_present)) { ucs_warn("RoCE packet does not contain GRH"); return 1; } /* * Take the packet type from CQE, because: * 1. According to Annex17_RoCEv2 (A17.4.5.1): * For UD, the Completion Queue Entry (CQE) includes remote address * information (InfiniBand Specification Vol. 1 Rev 1.2.1 Section 11.4.2.1). * For RoCEv2, the remote address information comprises the source L2 * Address and a flag that indicates if the received frame is an IPv4, * IPv6 or RoCE packet. * 2. According to PRM, for responder UD/DC over RoCE sl represents RoCE * packet type as: * bit 3 : when set R-RoCE frame contains an UDP header otherwise not * Bits[2:0]: L3_Header_Type, as defined below * - 0x0 : GRH - (RoCE v1.0) * - 0x1 : IPv6 - (RoCE v1.5/v2.0) * - 0x2 : IPv4 - (RoCE v1.5/v2.0) */ gid_len = ((roce_pkt_type & UCT_IB_CQE_SL_PKTYPE_MASK) == 0x2) ? UCS_IPV4_ADDR_LEN : UCS_IPV6_ADDR_LEN; if (ucs_likely((gid_len == iface->gid_table.last_len) && uct_ud_gid_equal(&grh->dgid, &iface->gid_table.last, gid_len))) { return 1; } gid = uct_ud_grh_get_dgid(grh, gid_len); khiter = kh_get(uct_ud_iface_gid, &iface->gid_table.hash, *gid); if (ucs_likely(khiter != kh_end(&iface->gid_table.hash))) { iface->gid_table.last = *gid; iface->gid_table.last_len = gid_len; return 1; } UCS_STATS_UPDATE_COUNTER(iface->stats, UCT_UD_IFACE_STAT_RX_DROP, 1); ucs_trace_data("iface %p: drop packet with wrong dgid %s", iface, uct_ib_gid_str(gid, gid_str, sizeof(gid_str))); return 0; } static UCS_F_ALWAYS_INLINE void uct_ud_iface_twheel_sweep(uct_ud_iface_t *iface) { if (iface->tx.timer_sweep_count++ % UCT_UD_SKIP_SWEEP) { return; } if (ucs_twheel_is_empty(&iface->tx.timer)) { return; } ucs_twheel_sweep(&iface->tx.timer, ucs_get_time()); } static UCS_F_ALWAYS_INLINE void uct_ud_iface_progress_pending(uct_ud_iface_t *iface, const uintptr_t is_async) { uct_ud_iface_twheel_sweep(iface); if (!is_async) { iface->tx.async_before_pending = 0; } if (!uct_ud_iface_can_tx(iface)) { return; } ucs_arbiter_dispatch(&iface->tx.pending_q, 1, uct_ud_ep_do_pending, (void *)is_async); } static UCS_F_ALWAYS_INLINE int uct_ud_iface_has_pending_async_ev(uct_ud_iface_t *iface) { return iface->tx.async_before_pending; } static UCS_F_ALWAYS_INLINE void uct_ud_iface_raise_pending_async_ev(uct_ud_iface_t *iface) { if (!ucs_arbiter_is_empty(&iface->tx.pending_q)) { iface->tx.async_before_pending = 1; } } static UCS_F_ALWAYS_INLINE const void * uct_ud_ep_get_peer_address(const ucs_conn_match_elem_t *elem) { uct_ud_ep_t *ep = ucs_container_of(elem, uct_ud_ep_t, conn_match); uct_ib_iface_t *ib_iface = ucs_derived_of(ep->super.super.iface, uct_ib_iface_t); return uct_iface_invoke_ops_func(ib_iface, uct_ud_iface_ops_t, ep_get_peer_address, ep); } static UCS_F_ALWAYS_INLINE ucs_status_t uct_ud_iface_unpack_peer_address(uct_ud_iface_t *iface, const uct_ib_address_t *ib_addr, const uct_ud_iface_addr_t *if_addr, unsigned path_index, void *address_p) { uct_ud_iface_ops_t *ud_ops = ucs_derived_of(iface->super.ops, uct_ud_iface_ops_t); return ud_ops->unpack_peer_address(iface, ib_addr, if_addr, path_index, address_p); } static UCS_F_ALWAYS_INLINE uint16_t uct_ud_iface_send_ctl(uct_ud_iface_t *iface, uct_ud_ep_t *ep, uct_ud_send_skb_t *skb, const uct_ud_iov_t *iov, uint16_t iovcnt, int flags, int max_log_sge) { uct_ud_iface_ops_t *ud_ops = ucs_derived_of(iface->super.ops, uct_ud_iface_ops_t); return ud_ops->send_ctl(ep, skb, iov, iovcnt, flags, max_log_sge); } static UCS_F_ALWAYS_INLINE void uct_ud_iface_add_ctl_desc(uct_ud_iface_t *iface, uct_ud_ctl_desc_t *cdesc) { ucs_queue_push(&iface->tx.outstanding_q, &cdesc->queue); } static UCS_F_ALWAYS_INLINE unsigned uct_ud_iface_dispatch_pending_rx(uct_ud_iface_t *iface) { if (ucs_likely(ucs_queue_is_empty(&iface->rx.pending_q))) { return 0; } return uct_ud_iface_dispatch_pending_rx_do(iface); } static UCS_F_ALWAYS_INLINE unsigned uct_ud_iface_dispatch_async_comps(uct_ud_iface_t *iface, uct_ud_ep_t *ep) { if (ucs_likely(ucs_queue_is_empty(&iface->tx.async_comp_q))) { return 0; } return uct_ud_iface_dispatch_async_comps_do(iface, ep); } #if ENABLE_PARAMS_CHECK #define UCT_UD_CHECK_LENGTH(iface, header_len, payload_len, msg) \ do { \ int mtu; \ mtu = uct_ib_mtu_value(uct_ib_iface_port_attr(&(iface)->super)->active_mtu); \ UCT_CHECK_LENGTH(sizeof(uct_ud_neth_t) + payload_len + header_len, \ 0, mtu, msg); \ } while(0); #define UCT_UD_CHECK_BCOPY_LENGTH(iface, len) \ UCT_UD_CHECK_LENGTH(iface, 0, len, "am_bcopy") #define UCT_UD_CHECK_ZCOPY_LENGTH(iface, header_len, payload_len) \ UCT_UD_CHECK_LENGTH(iface, header_len, payload_len, "am_zcopy payload") #else #define UCT_UD_CHECK_ZCOPY_LENGTH(iface, header_len, payload_len) #define UCT_UD_CHECK_BCOPY_LENGTH(iface, len) #endif END_C_DECLS #endif
459e7f9797e443bff9fefd5b127d901edb27ca61
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
/audio/libcanberra/files/patch-src_oss.c
dd9ea89e4b0e3b857286d45cc0103085fe88f571
[ "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
360
c
patch-src_oss.c
--- src/oss.c.orig 2011-02-23 01:51:00 UTC +++ src/oss.c @@ -259,7 +259,7 @@ static int open_oss(ca_context *c, struc val = AFMT_S16_NE; break; case CA_SAMPLE_S16RE: -#if __BYTE_ORDER == __LITTLE_ENDIAN +#if _BYTE_ORDER == _LITTLE_ENDIAN val = AFMT_S16_BE; #else val = AFMT_S16_LE;
3621d0b6526c58b1a6bce5f2e0fb1c73d7db0de9
50dd46b8ece33f3cdd174284b15d1d51f89669d4
/third_party/edk2/ArmPkg/Library/CompilerIntrinsicsLib/Arm/divsi3.c
24e43dd6d7de3c0d42798aa8c87459e9c467a511
[ "LicenseRef-scancode-generic-cla", "Apache-2.0", "BSD-2-Clause", "OpenSSL" ]
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
3,102
c
divsi3.c
/** @file Compiler intrinsic for 32--bit unsigned division, ported from LLVM code. Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR> This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. **/ /** University of Illinois/NCSA Open Source License Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign. All rights reserved. Developed by: LLVM Team University of Illinois at Urbana-Champaign http://llvm.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal with 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: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimers. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimers in the documentation and/or other materials provided with the distribution. * Neither the names of the LLVM Team, University of Illinois at Urbana-Champaign, nor the names of its contributors may be used to endorse or promote products derived from this Software without specific prior written permission. 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 CONTRIBUTORS 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 WITH THE SOFTWARE. **/ #include "Llvm_int_lib.h" UINT32 __udivsi3(UINT32 n, UINT32 d); // Returns: a / b INT32 __divsi3(INT32 a, INT32 b) { const int bits_in_word_m1 = (int)(sizeof(INT32) * CHAR_BIT) - 1; INT32 s_a = a >> bits_in_word_m1; // s_a = a < 0 ? -1 : 0 INT32 s_b = b >> bits_in_word_m1; // s_b = b < 0 ? -1 : 0 a = (a ^ s_a) - s_a; // negate if s_a == -1 b = (b ^ s_b) - s_b; // negate if s_b == -1 s_a ^= s_b; // sign of quotient return (__udivsi3(a, b) ^ s_a) - s_a; // negate if s_a == -1 }
5abe75cf18a2fede23529194b406c3cf742edced
b14db9403f921df7ff32b884de73dad877243552
/nvidia-include/ctrl/ctrlxxxx.h
7a5eaad23ffa1a0d9c31e612cb22086e5499b828
[ "MIT" ]
permissive
elFarto/nvidia-vaapi-driver
a91d91e927779ea9c59a52b0b1a4bd3a44924127
cd54d4029490d6703de5a9080f1475e40efc242a
refs/heads/master
2023-09-04T11:47:26.834407
2023-08-26T20:47:20
2023-08-26T20:47:20
428,422,859
951
60
NOASSERTION
2023-09-11T07:11:32
2021-11-15T21:11:36
C
UTF-8
C
false
false
2,427
h
ctrlxxxx.h
/* * SPDX-FileCopyrightText: Copyright (c) 2005-2008,2013,2021 NVIDIA CORPORATION & AFFILIATES. All rights reserved. * SPDX-License-Identifier: MIT * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #pragma once // // This file was generated with FINN, an NVIDIA coding tool. // Source file: ctrl/ctrlxxxx.finn // #include "nvtypes.h" /* definitions shared by all CTRL interfaces */ /* Basic command format: * cmd_class [31:16], * cmd_reserved [15:15], * cmd_reserved [14:14], * cmd_category [13:8], * cmd_index [7:0] */ #define NVXXXX_CTRL_CMD_CLASS 31:16 #define NVXXXX_CTRL_CMD_CATEGORY 13:8 #define NVXXXX_CTRL_CMD_INDEX 7:0 /* don't use DRF_NUM - not always available */ # define NVXXXX_CTRL_CMD(cls,cat,idx) \ (((cls) << 16) | ((0) << 15) | ((0) << 14) \ | ((cat) << 8) | ((idx) & 0xFF)) /* * NVXXXX_CTRL_CMD_NULL * * This command does nothing. * This command does not take any parameters. * This command is valid for all classes. * * Possible status values returned are: * NV_OK */ #define NVXXXX_CTRL_CMD_NULL (0x00000000) #define NVxxxx_CTRL_LEGACY_PRIVILEGED (0xC0) #define NVxxxx_CTRL_LEGACY_NON_PRIVILEGED (0x80)
80882e2aaa6f3ecfcd2d8bf8fe7eeca2480f6c15
98e19516c8c6ccdcd3b092955d47773a0aaabf7b
/lib/std/core/core-inline.c
3a5f690bcf3268f736924cfcf7bc3c94efaec3bc
[ "Apache-2.0" ]
permissive
koka-lang/koka
d31daf7d06b28ea7b1fc8084cc76cdf5459610b6
b3122869ac74bfb6f432f7e76eeb723b1f69a491
refs/heads/master
2023-08-31T05:54:48.476729
2023-07-03T18:18:28
2023-07-03T18:18:28
75,982,258
2,806
154
NOASSERTION
2023-07-20T16:27:34
2016-12-08T23:00:37
Haskell
UTF-8
C
false
false
13,388
c
core-inline.c
/*--------------------------------------------------------------------------- Copyright 2020-2021, Microsoft Research, Daan Leijen. This is free software; you can redistribute it and/or modify it under the terms of the Apache License, Version 2.0. A copy of the License can be found in the LICENSE file at the root of this distribution. ---------------------------------------------------------------------------*/ kk_std_core__list kk_vector_to_list(kk_vector_t v, kk_std_core__list tail, kk_context_t* ctx) { // todo: avoid boxed_dup if v is unique kk_ssize_t n; kk_box_t* p = kk_vector_buf_borrow(v, &n, ctx); if (n <= 0) { kk_vector_drop(v,ctx); return tail; } kk_std_core__list nil = kk_std_core__new_Nil(ctx); struct kk_std_core_Cons* cons = NULL; kk_std_core__list list = kk_std_core__new_Nil(ctx); for( kk_ssize_t i = 0; i < n; i++ ) { kk_std_core__list hd = kk_std_core__new_Cons(kk_reuse_null,0,kk_box_dup(p[i],ctx), nil, ctx); if (cons==NULL) { list = hd; } else { cons->tail = hd; } cons = kk_std_core__as_Cons(hd,ctx); } if (cons == NULL) { list = tail; } else { cons->tail = tail; } kk_vector_drop(v,ctx); return list; } kk_vector_t kk_list_to_vector(kk_std_core__list xs, kk_context_t* ctx) { // todo: avoid boxed_dup if xs is unique // find the length kk_ssize_t len = 0; kk_std_core__list ys = xs; while (kk_std_core__is_Cons(ys,ctx)) { struct kk_std_core_Cons* cons = kk_std_core__as_Cons(ys,ctx); len++; ys = cons->tail; } // alloc the vector and copy kk_box_t* p; kk_vector_t v = kk_vector_alloc_uninit(len, &p, ctx); ys = xs; for( kk_ssize_t i = 0; i < len; i++) { struct kk_std_core_Cons* cons = kk_std_core__as_Cons(ys,ctx); ys = cons->tail; p[i] = kk_box_dup(cons->head,ctx); } kk_std_core__list_drop(xs,ctx); // todo: drop while visiting? return v; } kk_vector_t kk_vector_init( kk_ssize_t n, kk_function_t init, kk_context_t* ctx) { kk_box_t* p; kk_vector_t v = kk_vector_alloc_uninit(n, &p, ctx); for(kk_ssize_t i = 0; i < n; i++) { kk_function_dup(init,ctx); p[i] = kk_function_call(kk_box_t,(kk_function_t,kk_ssize_t,kk_context_t*),init,(init,i,ctx),ctx); } kk_function_drop(init,ctx); return v; } kk_box_t kk_main_console( kk_function_t action, kk_context_t* ctx ) { return kk_function_call(kk_box_t,(kk_function_t,kk_unit_t,kk_context_t*),action,(action,kk_Unit,ctx),ctx); } kk_std_core__list kk_string_to_list(kk_string_t s, kk_context_t* ctx) { kk_ssize_t len; const uint8_t* p = kk_string_buf_borrow(s,&len,ctx); const uint8_t* const end = p + len; kk_std_core__list nil = kk_std_core__new_Nil(ctx); kk_std_core__list list = nil; struct kk_std_core_Cons* tl = NULL; kk_ssize_t count; while( p < end ) { kk_char_t c = kk_utf8_read(p,&count); p += count; kk_std_core__list cons = kk_std_core__new_Cons(kk_reuse_null,0,kk_char_box(c,ctx), nil, ctx); if (tl!=NULL) { tl->tail = cons; } else { list = cons; } tl = kk_std_core__as_Cons(cons,ctx); } kk_string_drop(s,ctx); return list; } kk_string_t kk_string_from_list(kk_std_core__list cs, kk_context_t* ctx) { // TODO: optimize for short strings to write directly into a local buffer? // find total UTF8 length kk_ssize_t len = 0; kk_std_core__list xs = cs; while (kk_std_core__is_Cons(xs,ctx)) { struct kk_std_core_Cons* cons = kk_std_core__as_Cons(xs,ctx); len += kk_utf8_len(kk_char_unbox(cons->head,KK_BORROWED,ctx)); xs = cons->tail; } // allocate and copy the characters uint8_t* p; kk_string_t s = kk_unsafe_string_alloc_buf(len,&p,ctx); // must be initialized xs = cs; while (kk_std_core__is_Cons(xs,ctx)) { struct kk_std_core_Cons* cons = kk_std_core__as_Cons(xs,ctx); kk_ssize_t count; kk_utf8_write( kk_char_unbox(cons->head,KK_BORROWED,ctx), p, &count ); p += count; xs = cons->tail; } kk_assert_internal(*p == 0 && (p - kk_string_buf_borrow(s,NULL,ctx)) == len); kk_std_core__list_drop(cs,ctx); // todo: drop while visiting? return s; } static inline void kk_sslice_start_end_borrowx( kk_std_core__sslice sslice, const uint8_t** start, const uint8_t** end, const uint8_t** sstart, const uint8_t** send, kk_context_t* ctx) { kk_ssize_t strlen; const uint8_t* s = kk_string_buf_borrow(sslice.str,&strlen,ctx); kk_ssize_t slstart = kk_integer_clamp_ssize_t_borrow(sslice.start,ctx); kk_ssize_t sllen = kk_integer_clamp_ssize_t_borrow(sslice.len,ctx); *start = s + slstart; *end = s + slstart + sllen; if (sstart != NULL) *sstart = s; if (send != NULL) *send = s + strlen; kk_assert_internal(*start >= s && *start <= *end); kk_assert_internal(*end >= *start && *end <= s + strlen); } static inline void kk_sslice_start_end_borrow( kk_std_core__sslice sslice, const uint8_t** start, const uint8_t** end, kk_context_t* ctx) { kk_sslice_start_end_borrowx(sslice,start,end,NULL,NULL,ctx); } kk_integer_t kk_slice_count( kk_std_core__sslice sslice, kk_context_t* ctx ) { // TODO: optimize this by extending kk_string_count const uint8_t* start; const uint8_t* end; kk_sslice_start_end_borrow(sslice, &start, &end, ctx); kk_ssize_t count = 0; while( start < end && *start != 0 ) { const uint8_t* next = kk_utf8_next(start); count++; start = next; } kk_std_core__sslice_drop(sslice,ctx); return kk_integer_from_ssize_t(count,ctx); } kk_string_t kk_slice_to_string( kk_std_core__sslice sslice, kk_context_t* ctx ) { const uint8_t* start; const uint8_t* end; kk_sslice_start_end_borrow(sslice, &start, &end, ctx); // is it the full string? if (kk_integer_is_zero_borrow(sslice.start) && kk_integer_eq_borrow(sslice.len,kk_integer_from_ssize_t(kk_string_len_borrow(sslice.str,ctx),ctx),ctx)) { // TODO: drop sslice and dup sslice.str? return sslice.str; } else { // if not, we copy len bytes kk_string_t s = kk_string_alloc_dupn_valid_utf8(kk_integer_clamp_ssize_t_borrow(sslice.len,ctx), start, ctx); kk_std_core__sslice_drop(sslice,ctx); return s; } } kk_std_core__sslice kk_slice_first( kk_string_t str, kk_context_t* ctx ) { kk_ssize_t slen; const uint8_t* s = kk_string_buf_borrow(str,&slen,ctx); const uint8_t* next = (slen > 0 ? kk_utf8_next(s) : s); return kk_std_core__new_Sslice(str, kk_integer_zero, kk_integer_from_ptrdiff_t(next - s,ctx), ctx); } kk_std_core__sslice kk_slice_last( kk_string_t str, kk_context_t* ctx ) { kk_ssize_t slen; const uint8_t* s = kk_string_buf_borrow(str,&slen,ctx); const uint8_t* end = s + slen; const uint8_t* prev = (s==end ? s : kk_utf8_prev(end)); return kk_std_core__new_Sslice(str, kk_integer_from_ptrdiff_t(prev - s,ctx), kk_integer_from_ptrdiff_t(end - prev,ctx), ctx); } kk_std_core__sslice kk_slice_between( struct kk_std_core_Sslice slice1, struct kk_std_core_Sslice slice2, kk_context_t* ctx ) { const uint8_t* s1 = kk_string_buf_borrow( slice1.str, NULL, ctx ); const uint8_t* s2 = kk_string_buf_borrow( slice2.str, NULL, ctx ); if (s1 != s2) { kk_info_message("between: not equal slices: %p vs. %p\n", s1, s2); return kk_std_core__new_Sslice(kk_string_empty(), kk_integer_zero, kk_integer_min_one, ctx); // invalid slice } kk_integer_t start; kk_integer_t len; if (kk_integer_lte_borrow(slice1.start,slice2.start,ctx)) { start = kk_integer_dup(slice1.start,ctx); len = kk_integer_sub(kk_integer_dup(slice2.start,ctx),kk_integer_dup(slice1.start,ctx),ctx); } else { start = kk_integer_dup(slice2.start,ctx); len = kk_integer_sub(kk_integer_dup(slice1.start,ctx),kk_integer_dup(slice2.start,ctx),ctx); } return kk_std_core__new_Sslice(slice1.str, start, len, ctx); } kk_std_core_types__maybe kk_slice_next( struct kk_std_core_Sslice slice, kk_context_t* ctx ) { if (!kk_integer_is_pos_borrow(slice.len,ctx)) { kk_std_core__sslice_drop(slice,ctx); return kk_std_core_types__new_Nothing(ctx); } const uint8_t* start; const uint8_t* end; kk_sslice_start_end_borrow(slice, &start, &end, ctx); kk_ssize_t clen; const kk_char_t c = kk_utf8_read(start,&clen); kk_assert_internal(clen > 0 && clen <= kk_integer_clamp_ssize_t_borrow(slice.len,ctx)); kk_integer_t iclen = kk_integer_min(kk_integer_from_ssize_t(clen,ctx),kk_integer_dup(slice.len,ctx),ctx); // TODO: specialize type to avoid boxing // note: don't drop slice as we take over all fields kk_integer_t istart = kk_integer_add(slice.start,kk_integer_dup(iclen,ctx),ctx); kk_integer_t ilen = kk_integer_sub(slice.len,iclen,ctx); kk_std_core__sslice snext = kk_std_core__new_Sslice(slice.str, istart, ilen, ctx); kk_std_core_types__tuple2_ res = kk_std_core_types__new_dash__lp__comma__rp_( kk_char_box(c,ctx), kk_std_core__sslice_box(snext,ctx), ctx); return kk_std_core_types__new_Just( kk_std_core_types__tuple2__box(res,ctx), ctx ); } /* Borrow count */ struct kk_std_core_Sslice kk_slice_extend_borrow( struct kk_std_core_Sslice slice, kk_integer_t count, kk_context_t* ctx ) { kk_ssize_t cnt = kk_integer_clamp_ssize_t_borrow(count,ctx); if (cnt==0 || (!kk_integer_is_pos_borrow(slice.len,ctx) && cnt<0)) return slice; const uint8_t* s0; const uint8_t* s1; kk_sslice_start_end_borrow(slice,&s0,&s1,ctx); const uint8_t* t = s1; if (cnt >= 0) { do { t = kk_utf8_next(t); cnt--; } while (cnt > 0 && *t != 0); } else { // cnt < 0 const uint8_t* sstart = s0 - kk_integer_clamp_ssize_t_borrow(slice.start,ctx); do { t = kk_utf8_prev(t); cnt++; } while (cnt < 0 && t > sstart); } if (t == s1) return slice; // length is unchanged kk_integer_drop(slice.len,ctx); return kk_std_core__new_Sslice(slice.str, slice.start, kk_integer_from_ptrdiff_t(t < s0 ? 0 : (t - s0),ctx), ctx); } /* Borrow count */ struct kk_std_core_Sslice kk_slice_advance_borrow( struct kk_std_core_Sslice slice, kk_integer_t count, kk_context_t* ctx ) { const kk_ssize_t cnt0 = kk_integer_clamp_ssize_t_borrow(count,ctx); kk_ssize_t cnt = cnt0; if (cnt==0 || (kk_integer_is_zero_borrow(slice.start) && cnt<0)) return slice; const uint8_t* sstart; const uint8_t* s0; const uint8_t* s1; const uint8_t* send; kk_sslice_start_end_borrowx(slice,&s0,&s1,&sstart,&send,ctx); // advance the start const uint8_t* t0 = s0; if (cnt >= 0) { do { t0 = kk_utf8_next(t0); cnt--; } while (cnt > 0 && t0 < send); } else { // cnt < 0 do { t0 = kk_utf8_prev(t0); cnt++; } while (cnt < 0 && t0 > sstart); } if (t0 == s0) return slice; // start is unchanged // "t0" points to the new start, now advance the end by the same amount of codepoints const uint8_t* t1 = s1; cnt = cnt0; if (cnt >= 0) { do { t1 = kk_utf8_next(t1); cnt--; } while (cnt > 0 && t1 < send); } else { // cnt < 0 do { t1 = kk_utf8_prev(t1); cnt++; } while (cnt < 0 && t1 > sstart); } // t1 points to the new end kk_assert_internal(t1 >= t0); kk_integer_drop(slice.start,ctx); kk_integer_drop(slice.len,ctx); return kk_std_core__new_Sslice(slice.str, kk_integer_from_ptrdiff_t(t0 - sstart,ctx), kk_integer_from_ptrdiff_t(t1 - t0,ctx), ctx); } /* Borrow iupto */ struct kk_std_core_Sslice kk_slice_common_prefix_borrow( kk_string_t str1, kk_string_t str2, kk_integer_t iupto, kk_context_t* ctx ) { const uint8_t* s1 = kk_string_buf_borrow(str1,NULL,ctx); const uint8_t* s2 = kk_string_buf_borrow(str2,NULL,ctx); kk_ssize_t upto = kk_integer_clamp_ssize_t_borrow(iupto,ctx); kk_ssize_t count; for(count = 0; count < upto && *s1 != 0 && *s2 != 0; count++, s1++, s2++ ) { if (*s1 != *s2) break; } kk_string_drop(str2,ctx); return kk_std_core__new_Sslice(str1, kk_integer_zero, kk_integer_from_ssize_t(count,ctx), ctx); } kk_std_core__error kk_error_ok( kk_box_t result, kk_context_t* ctx ) { return kk_std_core__new_Ok( result, ctx ); } kk_std_core__error kk_error_from_errno( int err, kk_context_t* ctx ) { kk_string_t msg; #if defined(__GLIBC__) && !defined(WIN32) && !defined(__APPLE__) && !defined(__FreeBSD__) // GNU version of strerror_r char buf[256]; char* serr = strerror_r(err, buf, 255); buf[255] = 0; msg = kk_string_alloc_from_qutf8( serr, ctx ); #elif (/* _POSIX_C_SOURCE >= 200112L ||*/ !defined(WIN32) && (_XOPEN_SOURCE >= 600 || defined(__APPLE__) || defined(__FreeBSD__) || defined(__MUSL__))) // XSI version of strerror_r char buf[256]; strerror_r(err, buf, 255); buf[255] = 0; msg = kk_string_alloc_from_qutf8( buf, ctx ); #elif defined(_MSC_VER) || (__STDC_VERSION__ >= 201112L || __cplusplus >= 201103L) // MSVC, or C/C++ 11 char buf[256]; strerror_s(buf, 255, err); buf[255] = 0; msg = kk_string_alloc_from_qutf8( buf, ctx ); #else // Old style msg = kk_string_alloc_from_qutf8( strerror(err), ctx ); #endif return kk_std_core__new_Error( kk_std_core__new_Exception( msg, kk_std_core__new_ExnSystem(kk_reuse_null, 0, kk_integer_from_int(err,ctx), ctx), ctx), ctx ); } kk_unit_t kk_assert_fail( kk_string_t msg, kk_context_t* ctx ) { kk_fatal_error(EINVAL, "assertion failed: %s\n", kk_string_cbuf_borrow(msg,NULL,ctx)); kk_string_drop(msg,ctx); return kk_Unit; }
09c5a4d81faeaeae442351fc58869befa6391dad
0dd85c72c457ac317ecdde7dc40518f7be1a2602
/sdk/third-party/protos/discovery/protocol.pb-c.c
20bb48ac44d2ad96658b0ec6631641859ccbaf0d
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
aitos-io/BoAT-X-Framework
00072acd6e570b8dda5c3e211103717110303915
92c09bd1ed269903b542b7b39a02137bb0b4f9be
refs/heads/master
2023-07-08T11:20:52.441231
2023-03-08T01:43:57
2023-03-08T01:43:57
249,309,472
2,165
141
Apache-2.0
2023-06-27T03:22:02
2020-03-23T01:39:16
C
UTF-8
C
false
false
80,459
c
protocol.pb-c.c
/* Generated by the protocol buffer compiler. DO NOT EDIT! */ /* Generated from: discovery/protocol.proto */ /* Do not generate deprecated warnings for self */ #ifndef PROTOBUF_C__NO_DEPRECATED #define PROTOBUF_C__NO_DEPRECATED #endif #include "discovery/protocol.pb-c.h" void discovery__signed_request__init (Discovery__SignedRequest *message) { static Discovery__SignedRequest init_value = DISCOVERY__SIGNED_REQUEST__INIT; *message = init_value; } size_t discovery__signed_request__get_packed_size (const Discovery__SignedRequest *message) { assert(message->base.descriptor == &discovery__signed_request__descriptor); return protobuf_c_message_get_packed_size ((const ProtobufCMessage*)(message)); } size_t discovery__signed_request__pack (const Discovery__SignedRequest *message, uint8_t *out) { assert(message->base.descriptor == &discovery__signed_request__descriptor); return protobuf_c_message_pack ((const ProtobufCMessage*)message, out); } size_t discovery__signed_request__pack_to_buffer (const Discovery__SignedRequest *message, ProtobufCBuffer *buffer) { assert(message->base.descriptor == &discovery__signed_request__descriptor); return protobuf_c_message_pack_to_buffer ((const ProtobufCMessage*)message, buffer); } Discovery__SignedRequest * discovery__signed_request__unpack (ProtobufCAllocator *allocator, size_t len, const uint8_t *data) { return (Discovery__SignedRequest *) protobuf_c_message_unpack (&discovery__signed_request__descriptor, allocator, len, data); } void discovery__signed_request__free_unpacked (Discovery__SignedRequest *message, ProtobufCAllocator *allocator) { assert(message->base.descriptor == &discovery__signed_request__descriptor); protobuf_c_message_free_unpacked ((ProtobufCMessage*)message, allocator); } void discovery__request__init (Discovery__Request *message) { static Discovery__Request init_value = DISCOVERY__REQUEST__INIT; *message = init_value; } size_t discovery__request__get_packed_size (const Discovery__Request *message) { assert(message->base.descriptor == &discovery__request__descriptor); return protobuf_c_message_get_packed_size ((const ProtobufCMessage*)(message)); } size_t discovery__request__pack (const Discovery__Request *message, uint8_t *out) { assert(message->base.descriptor == &discovery__request__descriptor); return protobuf_c_message_pack ((const ProtobufCMessage*)message, out); } size_t discovery__request__pack_to_buffer (const Discovery__Request *message, ProtobufCBuffer *buffer) { assert(message->base.descriptor == &discovery__request__descriptor); return protobuf_c_message_pack_to_buffer ((const ProtobufCMessage*)message, buffer); } Discovery__Request * discovery__request__unpack (ProtobufCAllocator *allocator, size_t len, const uint8_t *data) { return (Discovery__Request *) protobuf_c_message_unpack (&discovery__request__descriptor, allocator, len, data); } void discovery__request__free_unpacked (Discovery__Request *message, ProtobufCAllocator *allocator) { assert(message->base.descriptor == &discovery__request__descriptor); protobuf_c_message_free_unpacked ((ProtobufCMessage*)message, allocator); } void discovery__response__init (Discovery__Response *message) { static Discovery__Response init_value = DISCOVERY__RESPONSE__INIT; *message = init_value; } size_t discovery__response__get_packed_size (const Discovery__Response *message) { assert(message->base.descriptor == &discovery__response__descriptor); return protobuf_c_message_get_packed_size ((const ProtobufCMessage*)(message)); } size_t discovery__response__pack (const Discovery__Response *message, uint8_t *out) { assert(message->base.descriptor == &discovery__response__descriptor); return protobuf_c_message_pack ((const ProtobufCMessage*)message, out); } size_t discovery__response__pack_to_buffer (const Discovery__Response *message, ProtobufCBuffer *buffer) { assert(message->base.descriptor == &discovery__response__descriptor); return protobuf_c_message_pack_to_buffer ((const ProtobufCMessage*)message, buffer); } Discovery__Response * discovery__response__unpack (ProtobufCAllocator *allocator, size_t len, const uint8_t *data) { return (Discovery__Response *) protobuf_c_message_unpack (&discovery__response__descriptor, allocator, len, data); } void discovery__response__free_unpacked (Discovery__Response *message, ProtobufCAllocator *allocator) { assert(message->base.descriptor == &discovery__response__descriptor); protobuf_c_message_free_unpacked ((ProtobufCMessage*)message, allocator); } void discovery__auth_info__init (Discovery__AuthInfo *message) { static Discovery__AuthInfo init_value = DISCOVERY__AUTH_INFO__INIT; *message = init_value; } size_t discovery__auth_info__get_packed_size (const Discovery__AuthInfo *message) { assert(message->base.descriptor == &discovery__auth_info__descriptor); return protobuf_c_message_get_packed_size ((const ProtobufCMessage*)(message)); } size_t discovery__auth_info__pack (const Discovery__AuthInfo *message, uint8_t *out) { assert(message->base.descriptor == &discovery__auth_info__descriptor); return protobuf_c_message_pack ((const ProtobufCMessage*)message, out); } size_t discovery__auth_info__pack_to_buffer (const Discovery__AuthInfo *message, ProtobufCBuffer *buffer) { assert(message->base.descriptor == &discovery__auth_info__descriptor); return protobuf_c_message_pack_to_buffer ((const ProtobufCMessage*)message, buffer); } Discovery__AuthInfo * discovery__auth_info__unpack (ProtobufCAllocator *allocator, size_t len, const uint8_t *data) { return (Discovery__AuthInfo *) protobuf_c_message_unpack (&discovery__auth_info__descriptor, allocator, len, data); } void discovery__auth_info__free_unpacked (Discovery__AuthInfo *message, ProtobufCAllocator *allocator) { assert(message->base.descriptor == &discovery__auth_info__descriptor); protobuf_c_message_free_unpacked ((ProtobufCMessage*)message, allocator); } void discovery__query__init (Discovery__Query *message) { static Discovery__Query init_value = DISCOVERY__QUERY__INIT; *message = init_value; } size_t discovery__query__get_packed_size (const Discovery__Query *message) { assert(message->base.descriptor == &discovery__query__descriptor); return protobuf_c_message_get_packed_size ((const ProtobufCMessage*)(message)); } size_t discovery__query__pack (const Discovery__Query *message, uint8_t *out) { assert(message->base.descriptor == &discovery__query__descriptor); return protobuf_c_message_pack ((const ProtobufCMessage*)message, out); } size_t discovery__query__pack_to_buffer (const Discovery__Query *message, ProtobufCBuffer *buffer) { assert(message->base.descriptor == &discovery__query__descriptor); return protobuf_c_message_pack_to_buffer ((const ProtobufCMessage*)message, buffer); } Discovery__Query * discovery__query__unpack (ProtobufCAllocator *allocator, size_t len, const uint8_t *data) { return (Discovery__Query *) protobuf_c_message_unpack (&discovery__query__descriptor, allocator, len, data); } void discovery__query__free_unpacked (Discovery__Query *message, ProtobufCAllocator *allocator) { assert(message->base.descriptor == &discovery__query__descriptor); protobuf_c_message_free_unpacked ((ProtobufCMessage*)message, allocator); } void discovery__query_result__init (Discovery__QueryResult *message) { static Discovery__QueryResult init_value = DISCOVERY__QUERY_RESULT__INIT; *message = init_value; } size_t discovery__query_result__get_packed_size (const Discovery__QueryResult *message) { assert(message->base.descriptor == &discovery__query_result__descriptor); return protobuf_c_message_get_packed_size ((const ProtobufCMessage*)(message)); } size_t discovery__query_result__pack (const Discovery__QueryResult *message, uint8_t *out) { assert(message->base.descriptor == &discovery__query_result__descriptor); return protobuf_c_message_pack ((const ProtobufCMessage*)message, out); } size_t discovery__query_result__pack_to_buffer (const Discovery__QueryResult *message, ProtobufCBuffer *buffer) { assert(message->base.descriptor == &discovery__query_result__descriptor); return protobuf_c_message_pack_to_buffer ((const ProtobufCMessage*)message, buffer); } Discovery__QueryResult * discovery__query_result__unpack (ProtobufCAllocator *allocator, size_t len, const uint8_t *data) { return (Discovery__QueryResult *) protobuf_c_message_unpack (&discovery__query_result__descriptor, allocator, len, data); } void discovery__query_result__free_unpacked (Discovery__QueryResult *message, ProtobufCAllocator *allocator) { assert(message->base.descriptor == &discovery__query_result__descriptor); protobuf_c_message_free_unpacked ((ProtobufCMessage*)message, allocator); } void discovery__config_query__init (Discovery__ConfigQuery *message) { static Discovery__ConfigQuery init_value = DISCOVERY__CONFIG_QUERY__INIT; *message = init_value; } size_t discovery__config_query__get_packed_size (const Discovery__ConfigQuery *message) { assert(message->base.descriptor == &discovery__config_query__descriptor); return protobuf_c_message_get_packed_size ((const ProtobufCMessage*)(message)); } size_t discovery__config_query__pack (const Discovery__ConfigQuery *message, uint8_t *out) { assert(message->base.descriptor == &discovery__config_query__descriptor); return protobuf_c_message_pack ((const ProtobufCMessage*)message, out); } size_t discovery__config_query__pack_to_buffer (const Discovery__ConfigQuery *message, ProtobufCBuffer *buffer) { assert(message->base.descriptor == &discovery__config_query__descriptor); return protobuf_c_message_pack_to_buffer ((const ProtobufCMessage*)message, buffer); } Discovery__ConfigQuery * discovery__config_query__unpack (ProtobufCAllocator *allocator, size_t len, const uint8_t *data) { return (Discovery__ConfigQuery *) protobuf_c_message_unpack (&discovery__config_query__descriptor, allocator, len, data); } void discovery__config_query__free_unpacked (Discovery__ConfigQuery *message, ProtobufCAllocator *allocator) { assert(message->base.descriptor == &discovery__config_query__descriptor); protobuf_c_message_free_unpacked ((ProtobufCMessage*)message, allocator); } void discovery__config_result__msps_entry__init (Discovery__ConfigResult__MspsEntry *message) { static Discovery__ConfigResult__MspsEntry init_value = DISCOVERY__CONFIG_RESULT__MSPS_ENTRY__INIT; *message = init_value; } void discovery__config_result__orderers_entry__init (Discovery__ConfigResult__OrderersEntry *message) { static Discovery__ConfigResult__OrderersEntry init_value = DISCOVERY__CONFIG_RESULT__ORDERERS_ENTRY__INIT; *message = init_value; } void discovery__config_result__init (Discovery__ConfigResult *message) { static Discovery__ConfigResult init_value = DISCOVERY__CONFIG_RESULT__INIT; *message = init_value; } size_t discovery__config_result__get_packed_size (const Discovery__ConfigResult *message) { assert(message->base.descriptor == &discovery__config_result__descriptor); return protobuf_c_message_get_packed_size ((const ProtobufCMessage*)(message)); } size_t discovery__config_result__pack (const Discovery__ConfigResult *message, uint8_t *out) { assert(message->base.descriptor == &discovery__config_result__descriptor); return protobuf_c_message_pack ((const ProtobufCMessage*)message, out); } size_t discovery__config_result__pack_to_buffer (const Discovery__ConfigResult *message, ProtobufCBuffer *buffer) { assert(message->base.descriptor == &discovery__config_result__descriptor); return protobuf_c_message_pack_to_buffer ((const ProtobufCMessage*)message, buffer); } Discovery__ConfigResult * discovery__config_result__unpack (ProtobufCAllocator *allocator, size_t len, const uint8_t *data) { return (Discovery__ConfigResult *) protobuf_c_message_unpack (&discovery__config_result__descriptor, allocator, len, data); } void discovery__config_result__free_unpacked (Discovery__ConfigResult *message, ProtobufCAllocator *allocator) { assert(message->base.descriptor == &discovery__config_result__descriptor); protobuf_c_message_free_unpacked ((ProtobufCMessage*)message, allocator); } void discovery__peer_membership_query__init (Discovery__PeerMembershipQuery *message) { static Discovery__PeerMembershipQuery init_value = DISCOVERY__PEER_MEMBERSHIP_QUERY__INIT; *message = init_value; } size_t discovery__peer_membership_query__get_packed_size (const Discovery__PeerMembershipQuery *message) { assert(message->base.descriptor == &discovery__peer_membership_query__descriptor); return protobuf_c_message_get_packed_size ((const ProtobufCMessage*)(message)); } size_t discovery__peer_membership_query__pack (const Discovery__PeerMembershipQuery *message, uint8_t *out) { assert(message->base.descriptor == &discovery__peer_membership_query__descriptor); return protobuf_c_message_pack ((const ProtobufCMessage*)message, out); } size_t discovery__peer_membership_query__pack_to_buffer (const Discovery__PeerMembershipQuery *message, ProtobufCBuffer *buffer) { assert(message->base.descriptor == &discovery__peer_membership_query__descriptor); return protobuf_c_message_pack_to_buffer ((const ProtobufCMessage*)message, buffer); } Discovery__PeerMembershipQuery * discovery__peer_membership_query__unpack (ProtobufCAllocator *allocator, size_t len, const uint8_t *data) { return (Discovery__PeerMembershipQuery *) protobuf_c_message_unpack (&discovery__peer_membership_query__descriptor, allocator, len, data); } void discovery__peer_membership_query__free_unpacked (Discovery__PeerMembershipQuery *message, ProtobufCAllocator *allocator) { assert(message->base.descriptor == &discovery__peer_membership_query__descriptor); protobuf_c_message_free_unpacked ((ProtobufCMessage*)message, allocator); } void discovery__peer_membership_result__peers_by_org_entry__init (Discovery__PeerMembershipResult__PeersByOrgEntry *message) { static Discovery__PeerMembershipResult__PeersByOrgEntry init_value = DISCOVERY__PEER_MEMBERSHIP_RESULT__PEERS_BY_ORG_ENTRY__INIT; *message = init_value; } void discovery__peer_membership_result__init (Discovery__PeerMembershipResult *message) { static Discovery__PeerMembershipResult init_value = DISCOVERY__PEER_MEMBERSHIP_RESULT__INIT; *message = init_value; } size_t discovery__peer_membership_result__get_packed_size (const Discovery__PeerMembershipResult *message) { assert(message->base.descriptor == &discovery__peer_membership_result__descriptor); return protobuf_c_message_get_packed_size ((const ProtobufCMessage*)(message)); } size_t discovery__peer_membership_result__pack (const Discovery__PeerMembershipResult *message, uint8_t *out) { assert(message->base.descriptor == &discovery__peer_membership_result__descriptor); return protobuf_c_message_pack ((const ProtobufCMessage*)message, out); } size_t discovery__peer_membership_result__pack_to_buffer (const Discovery__PeerMembershipResult *message, ProtobufCBuffer *buffer) { assert(message->base.descriptor == &discovery__peer_membership_result__descriptor); return protobuf_c_message_pack_to_buffer ((const ProtobufCMessage*)message, buffer); } Discovery__PeerMembershipResult * discovery__peer_membership_result__unpack (ProtobufCAllocator *allocator, size_t len, const uint8_t *data) { return (Discovery__PeerMembershipResult *) protobuf_c_message_unpack (&discovery__peer_membership_result__descriptor, allocator, len, data); } void discovery__peer_membership_result__free_unpacked (Discovery__PeerMembershipResult *message, ProtobufCAllocator *allocator) { assert(message->base.descriptor == &discovery__peer_membership_result__descriptor); protobuf_c_message_free_unpacked ((ProtobufCMessage*)message, allocator); } void discovery__chaincode_query__init (Discovery__ChaincodeQuery *message) { static Discovery__ChaincodeQuery init_value = DISCOVERY__CHAINCODE_QUERY__INIT; *message = init_value; } size_t discovery__chaincode_query__get_packed_size (const Discovery__ChaincodeQuery *message) { assert(message->base.descriptor == &discovery__chaincode_query__descriptor); return protobuf_c_message_get_packed_size ((const ProtobufCMessage*)(message)); } size_t discovery__chaincode_query__pack (const Discovery__ChaincodeQuery *message, uint8_t *out) { assert(message->base.descriptor == &discovery__chaincode_query__descriptor); return protobuf_c_message_pack ((const ProtobufCMessage*)message, out); } size_t discovery__chaincode_query__pack_to_buffer (const Discovery__ChaincodeQuery *message, ProtobufCBuffer *buffer) { assert(message->base.descriptor == &discovery__chaincode_query__descriptor); return protobuf_c_message_pack_to_buffer ((const ProtobufCMessage*)message, buffer); } Discovery__ChaincodeQuery * discovery__chaincode_query__unpack (ProtobufCAllocator *allocator, size_t len, const uint8_t *data) { return (Discovery__ChaincodeQuery *) protobuf_c_message_unpack (&discovery__chaincode_query__descriptor, allocator, len, data); } void discovery__chaincode_query__free_unpacked (Discovery__ChaincodeQuery *message, ProtobufCAllocator *allocator) { assert(message->base.descriptor == &discovery__chaincode_query__descriptor); protobuf_c_message_free_unpacked ((ProtobufCMessage*)message, allocator); } void discovery__chaincode_interest__init (Discovery__ChaincodeInterest *message) { static Discovery__ChaincodeInterest init_value = DISCOVERY__CHAINCODE_INTEREST__INIT; *message = init_value; } size_t discovery__chaincode_interest__get_packed_size (const Discovery__ChaincodeInterest *message) { assert(message->base.descriptor == &discovery__chaincode_interest__descriptor); return protobuf_c_message_get_packed_size ((const ProtobufCMessage*)(message)); } size_t discovery__chaincode_interest__pack (const Discovery__ChaincodeInterest *message, uint8_t *out) { assert(message->base.descriptor == &discovery__chaincode_interest__descriptor); return protobuf_c_message_pack ((const ProtobufCMessage*)message, out); } size_t discovery__chaincode_interest__pack_to_buffer (const Discovery__ChaincodeInterest *message, ProtobufCBuffer *buffer) { assert(message->base.descriptor == &discovery__chaincode_interest__descriptor); return protobuf_c_message_pack_to_buffer ((const ProtobufCMessage*)message, buffer); } Discovery__ChaincodeInterest * discovery__chaincode_interest__unpack (ProtobufCAllocator *allocator, size_t len, const uint8_t *data) { return (Discovery__ChaincodeInterest *) protobuf_c_message_unpack (&discovery__chaincode_interest__descriptor, allocator, len, data); } void discovery__chaincode_interest__free_unpacked (Discovery__ChaincodeInterest *message, ProtobufCAllocator *allocator) { assert(message->base.descriptor == &discovery__chaincode_interest__descriptor); protobuf_c_message_free_unpacked ((ProtobufCMessage*)message, allocator); } void discovery__chaincode_call__init (Discovery__ChaincodeCall *message) { static Discovery__ChaincodeCall init_value = DISCOVERY__CHAINCODE_CALL__INIT; *message = init_value; } size_t discovery__chaincode_call__get_packed_size (const Discovery__ChaincodeCall *message) { assert(message->base.descriptor == &discovery__chaincode_call__descriptor); return protobuf_c_message_get_packed_size ((const ProtobufCMessage*)(message)); } size_t discovery__chaincode_call__pack (const Discovery__ChaincodeCall *message, uint8_t *out) { assert(message->base.descriptor == &discovery__chaincode_call__descriptor); return protobuf_c_message_pack ((const ProtobufCMessage*)message, out); } size_t discovery__chaincode_call__pack_to_buffer (const Discovery__ChaincodeCall *message, ProtobufCBuffer *buffer) { assert(message->base.descriptor == &discovery__chaincode_call__descriptor); return protobuf_c_message_pack_to_buffer ((const ProtobufCMessage*)message, buffer); } Discovery__ChaincodeCall * discovery__chaincode_call__unpack (ProtobufCAllocator *allocator, size_t len, const uint8_t *data) { return (Discovery__ChaincodeCall *) protobuf_c_message_unpack (&discovery__chaincode_call__descriptor, allocator, len, data); } void discovery__chaincode_call__free_unpacked (Discovery__ChaincodeCall *message, ProtobufCAllocator *allocator) { assert(message->base.descriptor == &discovery__chaincode_call__descriptor); protobuf_c_message_free_unpacked ((ProtobufCMessage*)message, allocator); } void discovery__chaincode_query_result__init (Discovery__ChaincodeQueryResult *message) { static Discovery__ChaincodeQueryResult init_value = DISCOVERY__CHAINCODE_QUERY_RESULT__INIT; *message = init_value; } size_t discovery__chaincode_query_result__get_packed_size (const Discovery__ChaincodeQueryResult *message) { assert(message->base.descriptor == &discovery__chaincode_query_result__descriptor); return protobuf_c_message_get_packed_size ((const ProtobufCMessage*)(message)); } size_t discovery__chaincode_query_result__pack (const Discovery__ChaincodeQueryResult *message, uint8_t *out) { assert(message->base.descriptor == &discovery__chaincode_query_result__descriptor); return protobuf_c_message_pack ((const ProtobufCMessage*)message, out); } size_t discovery__chaincode_query_result__pack_to_buffer (const Discovery__ChaincodeQueryResult *message, ProtobufCBuffer *buffer) { assert(message->base.descriptor == &discovery__chaincode_query_result__descriptor); return protobuf_c_message_pack_to_buffer ((const ProtobufCMessage*)message, buffer); } Discovery__ChaincodeQueryResult * discovery__chaincode_query_result__unpack (ProtobufCAllocator *allocator, size_t len, const uint8_t *data) { return (Discovery__ChaincodeQueryResult *) protobuf_c_message_unpack (&discovery__chaincode_query_result__descriptor, allocator, len, data); } void discovery__chaincode_query_result__free_unpacked (Discovery__ChaincodeQueryResult *message, ProtobufCAllocator *allocator) { assert(message->base.descriptor == &discovery__chaincode_query_result__descriptor); protobuf_c_message_free_unpacked ((ProtobufCMessage*)message, allocator); } void discovery__local_peer_query__init (Discovery__LocalPeerQuery *message) { static Discovery__LocalPeerQuery init_value = DISCOVERY__LOCAL_PEER_QUERY__INIT; *message = init_value; } size_t discovery__local_peer_query__get_packed_size (const Discovery__LocalPeerQuery *message) { assert(message->base.descriptor == &discovery__local_peer_query__descriptor); return protobuf_c_message_get_packed_size ((const ProtobufCMessage*)(message)); } size_t discovery__local_peer_query__pack (const Discovery__LocalPeerQuery *message, uint8_t *out) { assert(message->base.descriptor == &discovery__local_peer_query__descriptor); return protobuf_c_message_pack ((const ProtobufCMessage*)message, out); } size_t discovery__local_peer_query__pack_to_buffer (const Discovery__LocalPeerQuery *message, ProtobufCBuffer *buffer) { assert(message->base.descriptor == &discovery__local_peer_query__descriptor); return protobuf_c_message_pack_to_buffer ((const ProtobufCMessage*)message, buffer); } Discovery__LocalPeerQuery * discovery__local_peer_query__unpack (ProtobufCAllocator *allocator, size_t len, const uint8_t *data) { return (Discovery__LocalPeerQuery *) protobuf_c_message_unpack (&discovery__local_peer_query__descriptor, allocator, len, data); } void discovery__local_peer_query__free_unpacked (Discovery__LocalPeerQuery *message, ProtobufCAllocator *allocator) { assert(message->base.descriptor == &discovery__local_peer_query__descriptor); protobuf_c_message_free_unpacked ((ProtobufCMessage*)message, allocator); } void discovery__endorsement_descriptor__endorsers_by_groups_entry__init (Discovery__EndorsementDescriptor__EndorsersByGroupsEntry *message) { static Discovery__EndorsementDescriptor__EndorsersByGroupsEntry init_value = DISCOVERY__ENDORSEMENT_DESCRIPTOR__ENDORSERS_BY_GROUPS_ENTRY__INIT; *message = init_value; } void discovery__endorsement_descriptor__init (Discovery__EndorsementDescriptor *message) { static Discovery__EndorsementDescriptor init_value = DISCOVERY__ENDORSEMENT_DESCRIPTOR__INIT; *message = init_value; } size_t discovery__endorsement_descriptor__get_packed_size (const Discovery__EndorsementDescriptor *message) { assert(message->base.descriptor == &discovery__endorsement_descriptor__descriptor); return protobuf_c_message_get_packed_size ((const ProtobufCMessage*)(message)); } size_t discovery__endorsement_descriptor__pack (const Discovery__EndorsementDescriptor *message, uint8_t *out) { assert(message->base.descriptor == &discovery__endorsement_descriptor__descriptor); return protobuf_c_message_pack ((const ProtobufCMessage*)message, out); } size_t discovery__endorsement_descriptor__pack_to_buffer (const Discovery__EndorsementDescriptor *message, ProtobufCBuffer *buffer) { assert(message->base.descriptor == &discovery__endorsement_descriptor__descriptor); return protobuf_c_message_pack_to_buffer ((const ProtobufCMessage*)message, buffer); } Discovery__EndorsementDescriptor * discovery__endorsement_descriptor__unpack (ProtobufCAllocator *allocator, size_t len, const uint8_t *data) { return (Discovery__EndorsementDescriptor *) protobuf_c_message_unpack (&discovery__endorsement_descriptor__descriptor, allocator, len, data); } void discovery__endorsement_descriptor__free_unpacked (Discovery__EndorsementDescriptor *message, ProtobufCAllocator *allocator) { assert(message->base.descriptor == &discovery__endorsement_descriptor__descriptor); protobuf_c_message_free_unpacked ((ProtobufCMessage*)message, allocator); } void discovery__layout__quantities_by_group_entry__init (Discovery__Layout__QuantitiesByGroupEntry *message) { static Discovery__Layout__QuantitiesByGroupEntry init_value = DISCOVERY__LAYOUT__QUANTITIES_BY_GROUP_ENTRY__INIT; *message = init_value; } void discovery__layout__init (Discovery__Layout *message) { static Discovery__Layout init_value = DISCOVERY__LAYOUT__INIT; *message = init_value; } size_t discovery__layout__get_packed_size (const Discovery__Layout *message) { assert(message->base.descriptor == &discovery__layout__descriptor); return protobuf_c_message_get_packed_size ((const ProtobufCMessage*)(message)); } size_t discovery__layout__pack (const Discovery__Layout *message, uint8_t *out) { assert(message->base.descriptor == &discovery__layout__descriptor); return protobuf_c_message_pack ((const ProtobufCMessage*)message, out); } size_t discovery__layout__pack_to_buffer (const Discovery__Layout *message, ProtobufCBuffer *buffer) { assert(message->base.descriptor == &discovery__layout__descriptor); return protobuf_c_message_pack_to_buffer ((const ProtobufCMessage*)message, buffer); } Discovery__Layout * discovery__layout__unpack (ProtobufCAllocator *allocator, size_t len, const uint8_t *data) { return (Discovery__Layout *) protobuf_c_message_unpack (&discovery__layout__descriptor, allocator, len, data); } void discovery__layout__free_unpacked (Discovery__Layout *message, ProtobufCAllocator *allocator) { assert(message->base.descriptor == &discovery__layout__descriptor); protobuf_c_message_free_unpacked ((ProtobufCMessage*)message, allocator); } void discovery__peers__init (Discovery__Peers *message) { static Discovery__Peers init_value = DISCOVERY__PEERS__INIT; *message = init_value; } size_t discovery__peers__get_packed_size (const Discovery__Peers *message) { assert(message->base.descriptor == &discovery__peers__descriptor); return protobuf_c_message_get_packed_size ((const ProtobufCMessage*)(message)); } size_t discovery__peers__pack (const Discovery__Peers *message, uint8_t *out) { assert(message->base.descriptor == &discovery__peers__descriptor); return protobuf_c_message_pack ((const ProtobufCMessage*)message, out); } size_t discovery__peers__pack_to_buffer (const Discovery__Peers *message, ProtobufCBuffer *buffer) { assert(message->base.descriptor == &discovery__peers__descriptor); return protobuf_c_message_pack_to_buffer ((const ProtobufCMessage*)message, buffer); } Discovery__Peers * discovery__peers__unpack (ProtobufCAllocator *allocator, size_t len, const uint8_t *data) { return (Discovery__Peers *) protobuf_c_message_unpack (&discovery__peers__descriptor, allocator, len, data); } void discovery__peers__free_unpacked (Discovery__Peers *message, ProtobufCAllocator *allocator) { assert(message->base.descriptor == &discovery__peers__descriptor); protobuf_c_message_free_unpacked ((ProtobufCMessage*)message, allocator); } void discovery__peer__init (Discovery__Peer *message) { static Discovery__Peer init_value = DISCOVERY__PEER__INIT; *message = init_value; } size_t discovery__peer__get_packed_size (const Discovery__Peer *message) { assert(message->base.descriptor == &discovery__peer__descriptor); return protobuf_c_message_get_packed_size ((const ProtobufCMessage*)(message)); } size_t discovery__peer__pack (const Discovery__Peer *message, uint8_t *out) { assert(message->base.descriptor == &discovery__peer__descriptor); return protobuf_c_message_pack ((const ProtobufCMessage*)message, out); } size_t discovery__peer__pack_to_buffer (const Discovery__Peer *message, ProtobufCBuffer *buffer) { assert(message->base.descriptor == &discovery__peer__descriptor); return protobuf_c_message_pack_to_buffer ((const ProtobufCMessage*)message, buffer); } Discovery__Peer * discovery__peer__unpack (ProtobufCAllocator *allocator, size_t len, const uint8_t *data) { return (Discovery__Peer *) protobuf_c_message_unpack (&discovery__peer__descriptor, allocator, len, data); } void discovery__peer__free_unpacked (Discovery__Peer *message, ProtobufCAllocator *allocator) { assert(message->base.descriptor == &discovery__peer__descriptor); protobuf_c_message_free_unpacked ((ProtobufCMessage*)message, allocator); } void discovery__error__init (Discovery__Error *message) { static Discovery__Error init_value = DISCOVERY__ERROR__INIT; *message = init_value; } size_t discovery__error__get_packed_size (const Discovery__Error *message) { assert(message->base.descriptor == &discovery__error__descriptor); return protobuf_c_message_get_packed_size ((const ProtobufCMessage*)(message)); } size_t discovery__error__pack (const Discovery__Error *message, uint8_t *out) { assert(message->base.descriptor == &discovery__error__descriptor); return protobuf_c_message_pack ((const ProtobufCMessage*)message, out); } size_t discovery__error__pack_to_buffer (const Discovery__Error *message, ProtobufCBuffer *buffer) { assert(message->base.descriptor == &discovery__error__descriptor); return protobuf_c_message_pack_to_buffer ((const ProtobufCMessage*)message, buffer); } Discovery__Error * discovery__error__unpack (ProtobufCAllocator *allocator, size_t len, const uint8_t *data) { return (Discovery__Error *) protobuf_c_message_unpack (&discovery__error__descriptor, allocator, len, data); } void discovery__error__free_unpacked (Discovery__Error *message, ProtobufCAllocator *allocator) { assert(message->base.descriptor == &discovery__error__descriptor); protobuf_c_message_free_unpacked ((ProtobufCMessage*)message, allocator); } void discovery__endpoints__init (Discovery__Endpoints *message) { static Discovery__Endpoints init_value = DISCOVERY__ENDPOINTS__INIT; *message = init_value; } size_t discovery__endpoints__get_packed_size (const Discovery__Endpoints *message) { assert(message->base.descriptor == &discovery__endpoints__descriptor); return protobuf_c_message_get_packed_size ((const ProtobufCMessage*)(message)); } size_t discovery__endpoints__pack (const Discovery__Endpoints *message, uint8_t *out) { assert(message->base.descriptor == &discovery__endpoints__descriptor); return protobuf_c_message_pack ((const ProtobufCMessage*)message, out); } size_t discovery__endpoints__pack_to_buffer (const Discovery__Endpoints *message, ProtobufCBuffer *buffer) { assert(message->base.descriptor == &discovery__endpoints__descriptor); return protobuf_c_message_pack_to_buffer ((const ProtobufCMessage*)message, buffer); } Discovery__Endpoints * discovery__endpoints__unpack (ProtobufCAllocator *allocator, size_t len, const uint8_t *data) { return (Discovery__Endpoints *) protobuf_c_message_unpack (&discovery__endpoints__descriptor, allocator, len, data); } void discovery__endpoints__free_unpacked (Discovery__Endpoints *message, ProtobufCAllocator *allocator) { assert(message->base.descriptor == &discovery__endpoints__descriptor); protobuf_c_message_free_unpacked ((ProtobufCMessage*)message, allocator); } void discovery__endpoint__init (Discovery__Endpoint *message) { static Discovery__Endpoint init_value = DISCOVERY__ENDPOINT__INIT; *message = init_value; } size_t discovery__endpoint__get_packed_size (const Discovery__Endpoint *message) { assert(message->base.descriptor == &discovery__endpoint__descriptor); return protobuf_c_message_get_packed_size ((const ProtobufCMessage*)(message)); } size_t discovery__endpoint__pack (const Discovery__Endpoint *message, uint8_t *out) { assert(message->base.descriptor == &discovery__endpoint__descriptor); return protobuf_c_message_pack ((const ProtobufCMessage*)message, out); } size_t discovery__endpoint__pack_to_buffer (const Discovery__Endpoint *message, ProtobufCBuffer *buffer) { assert(message->base.descriptor == &discovery__endpoint__descriptor); return protobuf_c_message_pack_to_buffer ((const ProtobufCMessage*)message, buffer); } Discovery__Endpoint * discovery__endpoint__unpack (ProtobufCAllocator *allocator, size_t len, const uint8_t *data) { return (Discovery__Endpoint *) protobuf_c_message_unpack (&discovery__endpoint__descriptor, allocator, len, data); } void discovery__endpoint__free_unpacked (Discovery__Endpoint *message, ProtobufCAllocator *allocator) { assert(message->base.descriptor == &discovery__endpoint__descriptor); protobuf_c_message_free_unpacked ((ProtobufCMessage*)message, allocator); } static const ProtobufCFieldDescriptor discovery__signed_request__field_descriptors[2] = { { "payload", 1, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_TYPE_BYTES, offsetof(Discovery__SignedRequest, has_payload), offsetof(Discovery__SignedRequest, payload), NULL, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, { "signature", 2, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_TYPE_BYTES, offsetof(Discovery__SignedRequest, has_signature), offsetof(Discovery__SignedRequest, signature), NULL, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, }; static const unsigned discovery__signed_request__field_indices_by_name[] = { 0, /* field[0] = payload */ 1, /* field[1] = signature */ }; static const ProtobufCIntRange discovery__signed_request__number_ranges[1 + 1] = { { 1, 0 }, { 0, 2 } }; const ProtobufCMessageDescriptor discovery__signed_request__descriptor = { PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC, "discovery.SignedRequest", "SignedRequest", "Discovery__SignedRequest", "discovery", sizeof(Discovery__SignedRequest), 2, discovery__signed_request__field_descriptors, discovery__signed_request__field_indices_by_name, 1, discovery__signed_request__number_ranges, (ProtobufCMessageInit) discovery__signed_request__init, NULL,NULL,NULL /* reserved[123] */ }; static const ProtobufCFieldDescriptor discovery__request__field_descriptors[2] = { { "authentication", 1, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_TYPE_MESSAGE, 0, /* quantifier_offset */ offsetof(Discovery__Request, authentication), &discovery__auth_info__descriptor, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, { "queries", 2, PROTOBUF_C_LABEL_REPEATED, PROTOBUF_C_TYPE_MESSAGE, offsetof(Discovery__Request, n_queries), offsetof(Discovery__Request, queries), &discovery__query__descriptor, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, }; static const unsigned discovery__request__field_indices_by_name[] = { 0, /* field[0] = authentication */ 1, /* field[1] = queries */ }; static const ProtobufCIntRange discovery__request__number_ranges[1 + 1] = { { 1, 0 }, { 0, 2 } }; const ProtobufCMessageDescriptor discovery__request__descriptor = { PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC, "discovery.Request", "Request", "Discovery__Request", "discovery", sizeof(Discovery__Request), 2, discovery__request__field_descriptors, discovery__request__field_indices_by_name, 1, discovery__request__number_ranges, (ProtobufCMessageInit) discovery__request__init, NULL,NULL,NULL /* reserved[123] */ }; static const ProtobufCFieldDescriptor discovery__response__field_descriptors[1] = { { "results", 1, PROTOBUF_C_LABEL_REPEATED, PROTOBUF_C_TYPE_MESSAGE, offsetof(Discovery__Response, n_results), offsetof(Discovery__Response, results), &discovery__query_result__descriptor, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, }; static const unsigned discovery__response__field_indices_by_name[] = { 0, /* field[0] = results */ }; static const ProtobufCIntRange discovery__response__number_ranges[1 + 1] = { { 1, 0 }, { 0, 1 } }; const ProtobufCMessageDescriptor discovery__response__descriptor = { PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC, "discovery.Response", "Response", "Discovery__Response", "discovery", sizeof(Discovery__Response), 1, discovery__response__field_descriptors, discovery__response__field_indices_by_name, 1, discovery__response__number_ranges, (ProtobufCMessageInit) discovery__response__init, NULL,NULL,NULL /* reserved[123] */ }; static const ProtobufCFieldDescriptor discovery__auth_info__field_descriptors[2] = { { "client_identity", 1, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_TYPE_BYTES, offsetof(Discovery__AuthInfo, has_client_identity), offsetof(Discovery__AuthInfo, client_identity), NULL, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, { "client_tls_cert_hash", 2, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_TYPE_BYTES, offsetof(Discovery__AuthInfo, has_client_tls_cert_hash), offsetof(Discovery__AuthInfo, client_tls_cert_hash), NULL, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, }; static const unsigned discovery__auth_info__field_indices_by_name[] = { 0, /* field[0] = client_identity */ 1, /* field[1] = client_tls_cert_hash */ }; static const ProtobufCIntRange discovery__auth_info__number_ranges[1 + 1] = { { 1, 0 }, { 0, 2 } }; const ProtobufCMessageDescriptor discovery__auth_info__descriptor = { PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC, "discovery.AuthInfo", "AuthInfo", "Discovery__AuthInfo", "discovery", sizeof(Discovery__AuthInfo), 2, discovery__auth_info__field_descriptors, discovery__auth_info__field_indices_by_name, 1, discovery__auth_info__number_ranges, (ProtobufCMessageInit) discovery__auth_info__init, NULL,NULL,NULL /* reserved[123] */ }; static const ProtobufCFieldDescriptor discovery__query__field_descriptors[5] = { { "channel", 1, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_TYPE_STRING, 0, /* quantifier_offset */ offsetof(Discovery__Query, channel), NULL, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, { "config_query", 2, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_TYPE_MESSAGE, offsetof(Discovery__Query, query_case), offsetof(Discovery__Query, config_query), &discovery__config_query__descriptor, NULL, 0 | PROTOBUF_C_FIELD_FLAG_ONEOF, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, { "peer_query", 3, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_TYPE_MESSAGE, offsetof(Discovery__Query, query_case), offsetof(Discovery__Query, peer_query), &discovery__peer_membership_query__descriptor, NULL, 0 | PROTOBUF_C_FIELD_FLAG_ONEOF, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, { "cc_query", 4, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_TYPE_MESSAGE, offsetof(Discovery__Query, query_case), offsetof(Discovery__Query, cc_query), &discovery__chaincode_query__descriptor, NULL, 0 | PROTOBUF_C_FIELD_FLAG_ONEOF, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, { "local_peers", 5, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_TYPE_MESSAGE, offsetof(Discovery__Query, query_case), offsetof(Discovery__Query, local_peers), &discovery__local_peer_query__descriptor, NULL, 0 | PROTOBUF_C_FIELD_FLAG_ONEOF, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, }; static const unsigned discovery__query__field_indices_by_name[] = { 3, /* field[3] = cc_query */ 0, /* field[0] = channel */ 1, /* field[1] = config_query */ 4, /* field[4] = local_peers */ 2, /* field[2] = peer_query */ }; static const ProtobufCIntRange discovery__query__number_ranges[1 + 1] = { { 1, 0 }, { 0, 5 } }; const ProtobufCMessageDescriptor discovery__query__descriptor = { PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC, "discovery.Query", "Query", "Discovery__Query", "discovery", sizeof(Discovery__Query), 5, discovery__query__field_descriptors, discovery__query__field_indices_by_name, 1, discovery__query__number_ranges, (ProtobufCMessageInit) discovery__query__init, NULL,NULL,NULL /* reserved[123] */ }; static const ProtobufCFieldDescriptor discovery__query_result__field_descriptors[4] = { { "error", 1, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_TYPE_MESSAGE, offsetof(Discovery__QueryResult, result_case), offsetof(Discovery__QueryResult, error), &discovery__error__descriptor, NULL, 0 | PROTOBUF_C_FIELD_FLAG_ONEOF, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, { "config_result", 2, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_TYPE_MESSAGE, offsetof(Discovery__QueryResult, result_case), offsetof(Discovery__QueryResult, config_result), &discovery__config_result__descriptor, NULL, 0 | PROTOBUF_C_FIELD_FLAG_ONEOF, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, { "cc_query_res", 3, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_TYPE_MESSAGE, offsetof(Discovery__QueryResult, result_case), offsetof(Discovery__QueryResult, cc_query_res), &discovery__chaincode_query_result__descriptor, NULL, 0 | PROTOBUF_C_FIELD_FLAG_ONEOF, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, { "members", 4, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_TYPE_MESSAGE, offsetof(Discovery__QueryResult, result_case), offsetof(Discovery__QueryResult, members), &discovery__peer_membership_result__descriptor, NULL, 0 | PROTOBUF_C_FIELD_FLAG_ONEOF, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, }; static const unsigned discovery__query_result__field_indices_by_name[] = { 2, /* field[2] = cc_query_res */ 1, /* field[1] = config_result */ 0, /* field[0] = error */ 3, /* field[3] = members */ }; static const ProtobufCIntRange discovery__query_result__number_ranges[1 + 1] = { { 1, 0 }, { 0, 4 } }; const ProtobufCMessageDescriptor discovery__query_result__descriptor = { PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC, "discovery.QueryResult", "QueryResult", "Discovery__QueryResult", "discovery", sizeof(Discovery__QueryResult), 4, discovery__query_result__field_descriptors, discovery__query_result__field_indices_by_name, 1, discovery__query_result__number_ranges, (ProtobufCMessageInit) discovery__query_result__init, NULL,NULL,NULL /* reserved[123] */ }; #define discovery__config_query__field_descriptors NULL #define discovery__config_query__field_indices_by_name NULL #define discovery__config_query__number_ranges NULL const ProtobufCMessageDescriptor discovery__config_query__descriptor = { PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC, "discovery.ConfigQuery", "ConfigQuery", "Discovery__ConfigQuery", "discovery", sizeof(Discovery__ConfigQuery), 0, discovery__config_query__field_descriptors, discovery__config_query__field_indices_by_name, 0, discovery__config_query__number_ranges, (ProtobufCMessageInit) discovery__config_query__init, NULL,NULL,NULL /* reserved[123] */ }; static const ProtobufCFieldDescriptor discovery__config_result__msps_entry__field_descriptors[2] = { { "key", 1, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_TYPE_STRING, 0, /* quantifier_offset */ offsetof(Discovery__ConfigResult__MspsEntry, key), NULL, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, { "value", 2, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_TYPE_MESSAGE, 0, /* quantifier_offset */ offsetof(Discovery__ConfigResult__MspsEntry, value), &msp__fabric_mspconfig__descriptor, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, }; static const unsigned discovery__config_result__msps_entry__field_indices_by_name[] = { 0, /* field[0] = key */ 1, /* field[1] = value */ }; static const ProtobufCIntRange discovery__config_result__msps_entry__number_ranges[1 + 1] = { { 1, 0 }, { 0, 2 } }; const ProtobufCMessageDescriptor discovery__config_result__msps_entry__descriptor = { PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC, "discovery.ConfigResult.MspsEntry", "MspsEntry", "Discovery__ConfigResult__MspsEntry", "discovery", sizeof(Discovery__ConfigResult__MspsEntry), 2, discovery__config_result__msps_entry__field_descriptors, discovery__config_result__msps_entry__field_indices_by_name, 1, discovery__config_result__msps_entry__number_ranges, (ProtobufCMessageInit) discovery__config_result__msps_entry__init, NULL,NULL,NULL /* reserved[123] */ }; static const ProtobufCFieldDescriptor discovery__config_result__orderers_entry__field_descriptors[2] = { { "key", 1, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_TYPE_STRING, 0, /* quantifier_offset */ offsetof(Discovery__ConfigResult__OrderersEntry, key), NULL, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, { "value", 2, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_TYPE_MESSAGE, 0, /* quantifier_offset */ offsetof(Discovery__ConfigResult__OrderersEntry, value), &discovery__endpoints__descriptor, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, }; static const unsigned discovery__config_result__orderers_entry__field_indices_by_name[] = { 0, /* field[0] = key */ 1, /* field[1] = value */ }; static const ProtobufCIntRange discovery__config_result__orderers_entry__number_ranges[1 + 1] = { { 1, 0 }, { 0, 2 } }; const ProtobufCMessageDescriptor discovery__config_result__orderers_entry__descriptor = { PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC, "discovery.ConfigResult.OrderersEntry", "OrderersEntry", "Discovery__ConfigResult__OrderersEntry", "discovery", sizeof(Discovery__ConfigResult__OrderersEntry), 2, discovery__config_result__orderers_entry__field_descriptors, discovery__config_result__orderers_entry__field_indices_by_name, 1, discovery__config_result__orderers_entry__number_ranges, (ProtobufCMessageInit) discovery__config_result__orderers_entry__init, NULL,NULL,NULL /* reserved[123] */ }; static const ProtobufCFieldDescriptor discovery__config_result__field_descriptors[2] = { { "msps", 1, PROTOBUF_C_LABEL_REPEATED, PROTOBUF_C_TYPE_MESSAGE, offsetof(Discovery__ConfigResult, n_msps), offsetof(Discovery__ConfigResult, msps), &discovery__config_result__msps_entry__descriptor, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, { "orderers", 2, PROTOBUF_C_LABEL_REPEATED, PROTOBUF_C_TYPE_MESSAGE, offsetof(Discovery__ConfigResult, n_orderers), offsetof(Discovery__ConfigResult, orderers), &discovery__config_result__orderers_entry__descriptor, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, }; static const unsigned discovery__config_result__field_indices_by_name[] = { 0, /* field[0] = msps */ 1, /* field[1] = orderers */ }; static const ProtobufCIntRange discovery__config_result__number_ranges[1 + 1] = { { 1, 0 }, { 0, 2 } }; const ProtobufCMessageDescriptor discovery__config_result__descriptor = { PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC, "discovery.ConfigResult", "ConfigResult", "Discovery__ConfigResult", "discovery", sizeof(Discovery__ConfigResult), 2, discovery__config_result__field_descriptors, discovery__config_result__field_indices_by_name, 1, discovery__config_result__number_ranges, (ProtobufCMessageInit) discovery__config_result__init, NULL,NULL,NULL /* reserved[123] */ }; static const ProtobufCFieldDescriptor discovery__peer_membership_query__field_descriptors[1] = { { "filter", 1, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_TYPE_MESSAGE, 0, /* quantifier_offset */ offsetof(Discovery__PeerMembershipQuery, filter), &discovery__chaincode_interest__descriptor, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, }; static const unsigned discovery__peer_membership_query__field_indices_by_name[] = { 0, /* field[0] = filter */ }; static const ProtobufCIntRange discovery__peer_membership_query__number_ranges[1 + 1] = { { 1, 0 }, { 0, 1 } }; const ProtobufCMessageDescriptor discovery__peer_membership_query__descriptor = { PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC, "discovery.PeerMembershipQuery", "PeerMembershipQuery", "Discovery__PeerMembershipQuery", "discovery", sizeof(Discovery__PeerMembershipQuery), 1, discovery__peer_membership_query__field_descriptors, discovery__peer_membership_query__field_indices_by_name, 1, discovery__peer_membership_query__number_ranges, (ProtobufCMessageInit) discovery__peer_membership_query__init, NULL,NULL,NULL /* reserved[123] */ }; static const ProtobufCFieldDescriptor discovery__peer_membership_result__peers_by_org_entry__field_descriptors[2] = { { "key", 1, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_TYPE_STRING, 0, /* quantifier_offset */ offsetof(Discovery__PeerMembershipResult__PeersByOrgEntry, key), NULL, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, { "value", 2, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_TYPE_MESSAGE, 0, /* quantifier_offset */ offsetof(Discovery__PeerMembershipResult__PeersByOrgEntry, value), &discovery__peers__descriptor, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, }; static const unsigned discovery__peer_membership_result__peers_by_org_entry__field_indices_by_name[] = { 0, /* field[0] = key */ 1, /* field[1] = value */ }; static const ProtobufCIntRange discovery__peer_membership_result__peers_by_org_entry__number_ranges[1 + 1] = { { 1, 0 }, { 0, 2 } }; const ProtobufCMessageDescriptor discovery__peer_membership_result__peers_by_org_entry__descriptor = { PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC, "discovery.PeerMembershipResult.PeersByOrgEntry", "PeersByOrgEntry", "Discovery__PeerMembershipResult__PeersByOrgEntry", "discovery", sizeof(Discovery__PeerMembershipResult__PeersByOrgEntry), 2, discovery__peer_membership_result__peers_by_org_entry__field_descriptors, discovery__peer_membership_result__peers_by_org_entry__field_indices_by_name, 1, discovery__peer_membership_result__peers_by_org_entry__number_ranges, (ProtobufCMessageInit) discovery__peer_membership_result__peers_by_org_entry__init, NULL,NULL,NULL /* reserved[123] */ }; static const ProtobufCFieldDescriptor discovery__peer_membership_result__field_descriptors[1] = { { "peers_by_org", 1, PROTOBUF_C_LABEL_REPEATED, PROTOBUF_C_TYPE_MESSAGE, offsetof(Discovery__PeerMembershipResult, n_peers_by_org), offsetof(Discovery__PeerMembershipResult, peers_by_org), &discovery__peer_membership_result__peers_by_org_entry__descriptor, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, }; static const unsigned discovery__peer_membership_result__field_indices_by_name[] = { 0, /* field[0] = peers_by_org */ }; static const ProtobufCIntRange discovery__peer_membership_result__number_ranges[1 + 1] = { { 1, 0 }, { 0, 1 } }; const ProtobufCMessageDescriptor discovery__peer_membership_result__descriptor = { PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC, "discovery.PeerMembershipResult", "PeerMembershipResult", "Discovery__PeerMembershipResult", "discovery", sizeof(Discovery__PeerMembershipResult), 1, discovery__peer_membership_result__field_descriptors, discovery__peer_membership_result__field_indices_by_name, 1, discovery__peer_membership_result__number_ranges, (ProtobufCMessageInit) discovery__peer_membership_result__init, NULL,NULL,NULL /* reserved[123] */ }; static const ProtobufCFieldDescriptor discovery__chaincode_query__field_descriptors[1] = { { "interests", 1, PROTOBUF_C_LABEL_REPEATED, PROTOBUF_C_TYPE_MESSAGE, offsetof(Discovery__ChaincodeQuery, n_interests), offsetof(Discovery__ChaincodeQuery, interests), &discovery__chaincode_interest__descriptor, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, }; static const unsigned discovery__chaincode_query__field_indices_by_name[] = { 0, /* field[0] = interests */ }; static const ProtobufCIntRange discovery__chaincode_query__number_ranges[1 + 1] = { { 1, 0 }, { 0, 1 } }; const ProtobufCMessageDescriptor discovery__chaincode_query__descriptor = { PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC, "discovery.ChaincodeQuery", "ChaincodeQuery", "Discovery__ChaincodeQuery", "discovery", sizeof(Discovery__ChaincodeQuery), 1, discovery__chaincode_query__field_descriptors, discovery__chaincode_query__field_indices_by_name, 1, discovery__chaincode_query__number_ranges, (ProtobufCMessageInit) discovery__chaincode_query__init, NULL,NULL,NULL /* reserved[123] */ }; static const ProtobufCFieldDescriptor discovery__chaincode_interest__field_descriptors[1] = { { "chaincodes", 1, PROTOBUF_C_LABEL_REPEATED, PROTOBUF_C_TYPE_MESSAGE, offsetof(Discovery__ChaincodeInterest, n_chaincodes), offsetof(Discovery__ChaincodeInterest, chaincodes), &discovery__chaincode_call__descriptor, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, }; static const unsigned discovery__chaincode_interest__field_indices_by_name[] = { 0, /* field[0] = chaincodes */ }; static const ProtobufCIntRange discovery__chaincode_interest__number_ranges[1 + 1] = { { 1, 0 }, { 0, 1 } }; const ProtobufCMessageDescriptor discovery__chaincode_interest__descriptor = { PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC, "discovery.ChaincodeInterest", "ChaincodeInterest", "Discovery__ChaincodeInterest", "discovery", sizeof(Discovery__ChaincodeInterest), 1, discovery__chaincode_interest__field_descriptors, discovery__chaincode_interest__field_indices_by_name, 1, discovery__chaincode_interest__number_ranges, (ProtobufCMessageInit) discovery__chaincode_interest__init, NULL,NULL,NULL /* reserved[123] */ }; static const ProtobufCFieldDescriptor discovery__chaincode_call__field_descriptors[2] = { { "name", 1, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_TYPE_STRING, 0, /* quantifier_offset */ offsetof(Discovery__ChaincodeCall, name), NULL, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, { "collection_names", 2, PROTOBUF_C_LABEL_REPEATED, PROTOBUF_C_TYPE_STRING, offsetof(Discovery__ChaincodeCall, n_collection_names), offsetof(Discovery__ChaincodeCall, collection_names), NULL, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, }; static const unsigned discovery__chaincode_call__field_indices_by_name[] = { 1, /* field[1] = collection_names */ 0, /* field[0] = name */ }; static const ProtobufCIntRange discovery__chaincode_call__number_ranges[1 + 1] = { { 1, 0 }, { 0, 2 } }; const ProtobufCMessageDescriptor discovery__chaincode_call__descriptor = { PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC, "discovery.ChaincodeCall", "ChaincodeCall", "Discovery__ChaincodeCall", "discovery", sizeof(Discovery__ChaincodeCall), 2, discovery__chaincode_call__field_descriptors, discovery__chaincode_call__field_indices_by_name, 1, discovery__chaincode_call__number_ranges, (ProtobufCMessageInit) discovery__chaincode_call__init, NULL,NULL,NULL /* reserved[123] */ }; static const ProtobufCFieldDescriptor discovery__chaincode_query_result__field_descriptors[1] = { { "content", 1, PROTOBUF_C_LABEL_REPEATED, PROTOBUF_C_TYPE_MESSAGE, offsetof(Discovery__ChaincodeQueryResult, n_content), offsetof(Discovery__ChaincodeQueryResult, content), &discovery__endorsement_descriptor__descriptor, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, }; static const unsigned discovery__chaincode_query_result__field_indices_by_name[] = { 0, /* field[0] = content */ }; static const ProtobufCIntRange discovery__chaincode_query_result__number_ranges[1 + 1] = { { 1, 0 }, { 0, 1 } }; const ProtobufCMessageDescriptor discovery__chaincode_query_result__descriptor = { PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC, "discovery.ChaincodeQueryResult", "ChaincodeQueryResult", "Discovery__ChaincodeQueryResult", "discovery", sizeof(Discovery__ChaincodeQueryResult), 1, discovery__chaincode_query_result__field_descriptors, discovery__chaincode_query_result__field_indices_by_name, 1, discovery__chaincode_query_result__number_ranges, (ProtobufCMessageInit) discovery__chaincode_query_result__init, NULL,NULL,NULL /* reserved[123] */ }; #define discovery__local_peer_query__field_descriptors NULL #define discovery__local_peer_query__field_indices_by_name NULL #define discovery__local_peer_query__number_ranges NULL const ProtobufCMessageDescriptor discovery__local_peer_query__descriptor = { PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC, "discovery.LocalPeerQuery", "LocalPeerQuery", "Discovery__LocalPeerQuery", "discovery", sizeof(Discovery__LocalPeerQuery), 0, discovery__local_peer_query__field_descriptors, discovery__local_peer_query__field_indices_by_name, 0, discovery__local_peer_query__number_ranges, (ProtobufCMessageInit) discovery__local_peer_query__init, NULL,NULL,NULL /* reserved[123] */ }; static const ProtobufCFieldDescriptor discovery__endorsement_descriptor__endorsers_by_groups_entry__field_descriptors[2] = { { "key", 1, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_TYPE_STRING, 0, /* quantifier_offset */ offsetof(Discovery__EndorsementDescriptor__EndorsersByGroupsEntry, key), NULL, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, { "value", 2, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_TYPE_MESSAGE, 0, /* quantifier_offset */ offsetof(Discovery__EndorsementDescriptor__EndorsersByGroupsEntry, value), &discovery__peers__descriptor, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, }; static const unsigned discovery__endorsement_descriptor__endorsers_by_groups_entry__field_indices_by_name[] = { 0, /* field[0] = key */ 1, /* field[1] = value */ }; static const ProtobufCIntRange discovery__endorsement_descriptor__endorsers_by_groups_entry__number_ranges[1 + 1] = { { 1, 0 }, { 0, 2 } }; const ProtobufCMessageDescriptor discovery__endorsement_descriptor__endorsers_by_groups_entry__descriptor = { PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC, "discovery.EndorsementDescriptor.EndorsersByGroupsEntry", "EndorsersByGroupsEntry", "Discovery__EndorsementDescriptor__EndorsersByGroupsEntry", "discovery", sizeof(Discovery__EndorsementDescriptor__EndorsersByGroupsEntry), 2, discovery__endorsement_descriptor__endorsers_by_groups_entry__field_descriptors, discovery__endorsement_descriptor__endorsers_by_groups_entry__field_indices_by_name, 1, discovery__endorsement_descriptor__endorsers_by_groups_entry__number_ranges, (ProtobufCMessageInit) discovery__endorsement_descriptor__endorsers_by_groups_entry__init, NULL,NULL,NULL /* reserved[123] */ }; static const ProtobufCFieldDescriptor discovery__endorsement_descriptor__field_descriptors[3] = { { "chaincode", 1, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_TYPE_STRING, 0, /* quantifier_offset */ offsetof(Discovery__EndorsementDescriptor, chaincode), NULL, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, { "endorsers_by_groups", 2, PROTOBUF_C_LABEL_REPEATED, PROTOBUF_C_TYPE_MESSAGE, offsetof(Discovery__EndorsementDescriptor, n_endorsers_by_groups), offsetof(Discovery__EndorsementDescriptor, endorsers_by_groups), &discovery__endorsement_descriptor__endorsers_by_groups_entry__descriptor, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, { "layouts", 3, PROTOBUF_C_LABEL_REPEATED, PROTOBUF_C_TYPE_MESSAGE, offsetof(Discovery__EndorsementDescriptor, n_layouts), offsetof(Discovery__EndorsementDescriptor, layouts), &discovery__layout__descriptor, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, }; static const unsigned discovery__endorsement_descriptor__field_indices_by_name[] = { 0, /* field[0] = chaincode */ 1, /* field[1] = endorsers_by_groups */ 2, /* field[2] = layouts */ }; static const ProtobufCIntRange discovery__endorsement_descriptor__number_ranges[1 + 1] = { { 1, 0 }, { 0, 3 } }; const ProtobufCMessageDescriptor discovery__endorsement_descriptor__descriptor = { PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC, "discovery.EndorsementDescriptor", "EndorsementDescriptor", "Discovery__EndorsementDescriptor", "discovery", sizeof(Discovery__EndorsementDescriptor), 3, discovery__endorsement_descriptor__field_descriptors, discovery__endorsement_descriptor__field_indices_by_name, 1, discovery__endorsement_descriptor__number_ranges, (ProtobufCMessageInit) discovery__endorsement_descriptor__init, NULL,NULL,NULL /* reserved[123] */ }; static const ProtobufCFieldDescriptor discovery__layout__quantities_by_group_entry__field_descriptors[2] = { { "key", 1, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_TYPE_STRING, 0, /* quantifier_offset */ offsetof(Discovery__Layout__QuantitiesByGroupEntry, key), NULL, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, { "value", 2, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_TYPE_UINT32, offsetof(Discovery__Layout__QuantitiesByGroupEntry, has_value), offsetof(Discovery__Layout__QuantitiesByGroupEntry, value), NULL, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, }; static const unsigned discovery__layout__quantities_by_group_entry__field_indices_by_name[] = { 0, /* field[0] = key */ 1, /* field[1] = value */ }; static const ProtobufCIntRange discovery__layout__quantities_by_group_entry__number_ranges[1 + 1] = { { 1, 0 }, { 0, 2 } }; const ProtobufCMessageDescriptor discovery__layout__quantities_by_group_entry__descriptor = { PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC, "discovery.Layout.QuantitiesByGroupEntry", "QuantitiesByGroupEntry", "Discovery__Layout__QuantitiesByGroupEntry", "discovery", sizeof(Discovery__Layout__QuantitiesByGroupEntry), 2, discovery__layout__quantities_by_group_entry__field_descriptors, discovery__layout__quantities_by_group_entry__field_indices_by_name, 1, discovery__layout__quantities_by_group_entry__number_ranges, (ProtobufCMessageInit) discovery__layout__quantities_by_group_entry__init, NULL,NULL,NULL /* reserved[123] */ }; static const ProtobufCFieldDescriptor discovery__layout__field_descriptors[1] = { { "quantities_by_group", 1, PROTOBUF_C_LABEL_REPEATED, PROTOBUF_C_TYPE_MESSAGE, offsetof(Discovery__Layout, n_quantities_by_group), offsetof(Discovery__Layout, quantities_by_group), &discovery__layout__quantities_by_group_entry__descriptor, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, }; static const unsigned discovery__layout__field_indices_by_name[] = { 0, /* field[0] = quantities_by_group */ }; static const ProtobufCIntRange discovery__layout__number_ranges[1 + 1] = { { 1, 0 }, { 0, 1 } }; const ProtobufCMessageDescriptor discovery__layout__descriptor = { PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC, "discovery.Layout", "Layout", "Discovery__Layout", "discovery", sizeof(Discovery__Layout), 1, discovery__layout__field_descriptors, discovery__layout__field_indices_by_name, 1, discovery__layout__number_ranges, (ProtobufCMessageInit) discovery__layout__init, NULL,NULL,NULL /* reserved[123] */ }; static const ProtobufCFieldDescriptor discovery__peers__field_descriptors[1] = { { "peers", 1, PROTOBUF_C_LABEL_REPEATED, PROTOBUF_C_TYPE_MESSAGE, offsetof(Discovery__Peers, n_peers), offsetof(Discovery__Peers, peers), &discovery__peer__descriptor, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, }; static const unsigned discovery__peers__field_indices_by_name[] = { 0, /* field[0] = peers */ }; static const ProtobufCIntRange discovery__peers__number_ranges[1 + 1] = { { 1, 0 }, { 0, 1 } }; const ProtobufCMessageDescriptor discovery__peers__descriptor = { PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC, "discovery.Peers", "Peers", "Discovery__Peers", "discovery", sizeof(Discovery__Peers), 1, discovery__peers__field_descriptors, discovery__peers__field_indices_by_name, 1, discovery__peers__number_ranges, (ProtobufCMessageInit) discovery__peers__init, NULL,NULL,NULL /* reserved[123] */ }; static const ProtobufCFieldDescriptor discovery__peer__field_descriptors[3] = { { "state_info", 1, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_TYPE_MESSAGE, 0, /* quantifier_offset */ offsetof(Discovery__Peer, state_info), &gossip__envelope__descriptor, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, { "membership_info", 2, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_TYPE_MESSAGE, 0, /* quantifier_offset */ offsetof(Discovery__Peer, membership_info), &gossip__envelope__descriptor, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, { "identity", 3, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_TYPE_BYTES, offsetof(Discovery__Peer, has_identity), offsetof(Discovery__Peer, identity), NULL, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, }; static const unsigned discovery__peer__field_indices_by_name[] = { 2, /* field[2] = identity */ 1, /* field[1] = membership_info */ 0, /* field[0] = state_info */ }; static const ProtobufCIntRange discovery__peer__number_ranges[1 + 1] = { { 1, 0 }, { 0, 3 } }; const ProtobufCMessageDescriptor discovery__peer__descriptor = { PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC, "discovery.Peer", "Peer", "Discovery__Peer", "discovery", sizeof(Discovery__Peer), 3, discovery__peer__field_descriptors, discovery__peer__field_indices_by_name, 1, discovery__peer__number_ranges, (ProtobufCMessageInit) discovery__peer__init, NULL,NULL,NULL /* reserved[123] */ }; static const ProtobufCFieldDescriptor discovery__error__field_descriptors[1] = { { "content", 1, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_TYPE_STRING, 0, /* quantifier_offset */ offsetof(Discovery__Error, content), NULL, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, }; static const unsigned discovery__error__field_indices_by_name[] = { 0, /* field[0] = content */ }; static const ProtobufCIntRange discovery__error__number_ranges[1 + 1] = { { 1, 0 }, { 0, 1 } }; const ProtobufCMessageDescriptor discovery__error__descriptor = { PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC, "discovery.Error", "Error", "Discovery__Error", "discovery", sizeof(Discovery__Error), 1, discovery__error__field_descriptors, discovery__error__field_indices_by_name, 1, discovery__error__number_ranges, (ProtobufCMessageInit) discovery__error__init, NULL,NULL,NULL /* reserved[123] */ }; static const ProtobufCFieldDescriptor discovery__endpoints__field_descriptors[1] = { { "endpoint", 1, PROTOBUF_C_LABEL_REPEATED, PROTOBUF_C_TYPE_MESSAGE, offsetof(Discovery__Endpoints, n_endpoint), offsetof(Discovery__Endpoints, endpoint), &discovery__endpoint__descriptor, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, }; static const unsigned discovery__endpoints__field_indices_by_name[] = { 0, /* field[0] = endpoint */ }; static const ProtobufCIntRange discovery__endpoints__number_ranges[1 + 1] = { { 1, 0 }, { 0, 1 } }; const ProtobufCMessageDescriptor discovery__endpoints__descriptor = { PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC, "discovery.Endpoints", "Endpoints", "Discovery__Endpoints", "discovery", sizeof(Discovery__Endpoints), 1, discovery__endpoints__field_descriptors, discovery__endpoints__field_indices_by_name, 1, discovery__endpoints__number_ranges, (ProtobufCMessageInit) discovery__endpoints__init, NULL,NULL,NULL /* reserved[123] */ }; static const ProtobufCFieldDescriptor discovery__endpoint__field_descriptors[2] = { { "host", 1, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_TYPE_STRING, 0, /* quantifier_offset */ offsetof(Discovery__Endpoint, host), NULL, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, { "port", 2, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_TYPE_UINT32, offsetof(Discovery__Endpoint, has_port), offsetof(Discovery__Endpoint, port), NULL, NULL, 0, /* flags */ 0,NULL,NULL /* reserved1,reserved2, etc */ }, }; static const unsigned discovery__endpoint__field_indices_by_name[] = { 0, /* field[0] = host */ 1, /* field[1] = port */ }; static const ProtobufCIntRange discovery__endpoint__number_ranges[1 + 1] = { { 1, 0 }, { 0, 2 } }; const ProtobufCMessageDescriptor discovery__endpoint__descriptor = { PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC, "discovery.Endpoint", "Endpoint", "Discovery__Endpoint", "discovery", sizeof(Discovery__Endpoint), 2, discovery__endpoint__field_descriptors, discovery__endpoint__field_indices_by_name, 1, discovery__endpoint__number_ranges, (ProtobufCMessageInit) discovery__endpoint__init, NULL,NULL,NULL /* reserved[123] */ }; static const ProtobufCMethodDescriptor discovery__discovery__method_descriptors[1] = { { "Discover", &discovery__signed_request__descriptor, &discovery__response__descriptor }, }; const unsigned discovery__discovery__method_indices_by_name[] = { 0 /* Discover */ }; const ProtobufCServiceDescriptor discovery__discovery__descriptor = { PROTOBUF_C__SERVICE_DESCRIPTOR_MAGIC, "discovery.Discovery", "Discovery", "Discovery__Discovery", "discovery", 1, discovery__discovery__method_descriptors, discovery__discovery__method_indices_by_name }; void discovery__discovery__discover(ProtobufCService *service, const Discovery__SignedRequest *input, Discovery__Response_Closure closure, void *closure_data) { assert(service->descriptor == &discovery__discovery__descriptor); service->invoke(service, 0, (const ProtobufCMessage *) input, (ProtobufCClosure) closure, closure_data); } void discovery__discovery__init (Discovery__Discovery_Service *service, Discovery__Discovery_ServiceDestroy destroy) { protobuf_c_service_generated_init (&service->base, &discovery__discovery__descriptor, (ProtobufCServiceDestroy) destroy); }
2425623b4e688b3a587e9e20017e90a4781c2e48
2308899071a849a199e3b70806b4dd1c396efc8a
/base64/base64.h
cdcce58b466ce48c839436cb5ea2da70cec53e35
[ "MIT" ]
permissive
cyd01/KiTTY
b0b06d771508668ccbd6316474382b538a65bac0
0e5d8582aad192db96ba240444a6840fa82ccf05
refs/heads/master
2023-08-10T21:25:06.926589
2023-05-23T17:23:03
2023-05-23T17:56:00
154,540,955
1,451
147
NOASSERTION
2023-05-30T17:16:10
2018-10-24T17:26:24
C
UTF-8
C
false
false
196
h
base64.h
/* Fichier base64.h Auteur Bernard Chardonneau */ /* prototypes des fonctions de la bibliothèque base64 */ void encode64 (char *orig, char *dest, int nbcar); int decode64 (char *buffer);
5099e9a6f53c44c00df581ab6326ff175657925d
d38ed5f31d74a79a054ed55dd9123a8d615283b9
/third_party/libgit2/src/hash/hash_win32.c
4b68303588948057991c95ce3faedf1bb6fa0509
[ "Apache-2.0", "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" ]
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
8,895
c
hash_win32.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 "hash_win32.h" #include "global.h" #include "hash.h" #include <wincrypt.h> #include <strsafe.h> static struct git_hash_prov hash_prov = {0}; /* Hash initialization */ /* Initialize CNG, if available */ GIT_INLINE(int) hash_cng_prov_init(void) { char dll_path[MAX_PATH]; DWORD dll_path_len, size_len; /* Only use CNG on Windows 2008 / Vista SP1 or better (Windows 6.0 SP1) */ if (!git_has_win32_version(6, 0, 1)) { git_error_set(GIT_ERROR_SHA1, "CryptoNG is not supported on this platform"); return -1; } /* Load bcrypt.dll explicitly from the system directory */ if ((dll_path_len = GetSystemDirectory(dll_path, MAX_PATH)) == 0 || dll_path_len > MAX_PATH || StringCchCat(dll_path, MAX_PATH, "\\") < 0 || StringCchCat(dll_path, MAX_PATH, GIT_HASH_CNG_DLL_NAME) < 0 || (hash_prov.prov.cng.dll = LoadLibrary(dll_path)) == NULL) { git_error_set(GIT_ERROR_SHA1, "CryptoNG library could not be loaded"); return -1; } /* Load the function addresses */ if ((hash_prov.prov.cng.open_algorithm_provider = (hash_win32_cng_open_algorithm_provider_fn)GetProcAddress(hash_prov.prov.cng.dll, "BCryptOpenAlgorithmProvider")) == NULL || (hash_prov.prov.cng.get_property = (hash_win32_cng_get_property_fn)GetProcAddress(hash_prov.prov.cng.dll, "BCryptGetProperty")) == NULL || (hash_prov.prov.cng.create_hash = (hash_win32_cng_create_hash_fn)GetProcAddress(hash_prov.prov.cng.dll, "BCryptCreateHash")) == NULL || (hash_prov.prov.cng.finish_hash = (hash_win32_cng_finish_hash_fn)GetProcAddress(hash_prov.prov.cng.dll, "BCryptFinishHash")) == NULL || (hash_prov.prov.cng.hash_data = (hash_win32_cng_hash_data_fn)GetProcAddress(hash_prov.prov.cng.dll, "BCryptHashData")) == NULL || (hash_prov.prov.cng.destroy_hash = (hash_win32_cng_destroy_hash_fn)GetProcAddress(hash_prov.prov.cng.dll, "BCryptDestroyHash")) == NULL || (hash_prov.prov.cng.close_algorithm_provider = (hash_win32_cng_close_algorithm_provider_fn)GetProcAddress(hash_prov.prov.cng.dll, "BCryptCloseAlgorithmProvider")) == NULL) { FreeLibrary(hash_prov.prov.cng.dll); git_error_set(GIT_ERROR_OS, "CryptoNG functions could not be loaded"); return -1; } /* Load the SHA1 algorithm */ if (hash_prov.prov.cng.open_algorithm_provider(&hash_prov.prov.cng.handle, GIT_HASH_CNG_HASH_TYPE, NULL, GIT_HASH_CNG_HASH_REUSABLE) < 0) { FreeLibrary(hash_prov.prov.cng.dll); git_error_set(GIT_ERROR_OS, "algorithm provider could not be initialized"); return -1; } /* Get storage space for the hash object */ if (hash_prov.prov.cng.get_property(hash_prov.prov.cng.handle, GIT_HASH_CNG_HASH_OBJECT_LEN, (PBYTE)&hash_prov.prov.cng.hash_object_size, sizeof(DWORD), &size_len, 0) < 0) { hash_prov.prov.cng.close_algorithm_provider(hash_prov.prov.cng.handle, 0); FreeLibrary(hash_prov.prov.cng.dll); git_error_set(GIT_ERROR_OS, "algorithm handle could not be found"); return -1; } hash_prov.type = CNG; return 0; } GIT_INLINE(void) hash_cng_prov_shutdown(void) { hash_prov.prov.cng.close_algorithm_provider(hash_prov.prov.cng.handle, 0); FreeLibrary(hash_prov.prov.cng.dll); hash_prov.type = INVALID; } /* Initialize CryptoAPI */ GIT_INLINE(int) hash_cryptoapi_prov_init() { if (!CryptAcquireContext(&hash_prov.prov.cryptoapi.handle, NULL, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { git_error_set(GIT_ERROR_OS, "legacy hash context could not be started"); return -1; } hash_prov.type = CRYPTOAPI; return 0; } GIT_INLINE(void) hash_cryptoapi_prov_shutdown(void) { CryptReleaseContext(hash_prov.prov.cryptoapi.handle, 0); hash_prov.type = INVALID; } static void git_hash_global_shutdown(void) { if (hash_prov.type == CNG) hash_cng_prov_shutdown(); else if(hash_prov.type == CRYPTOAPI) hash_cryptoapi_prov_shutdown(); } int git_hash_global_init(void) { int error = 0; if (hash_prov.type != INVALID) return 0; if ((error = hash_cng_prov_init()) < 0) error = hash_cryptoapi_prov_init(); git__on_shutdown(git_hash_global_shutdown); return error; } /* CryptoAPI: available in Windows XP and newer */ GIT_INLINE(int) hash_ctx_cryptoapi_init(git_hash_ctx *ctx) { ctx->type = CRYPTOAPI; ctx->prov = &hash_prov; return git_hash_init(ctx); } GIT_INLINE(int) hash_cryptoapi_init(git_hash_ctx *ctx) { if (ctx->ctx.cryptoapi.valid) CryptDestroyHash(ctx->ctx.cryptoapi.hash_handle); if (!CryptCreateHash(ctx->prov->prov.cryptoapi.handle, CALG_SHA1, 0, 0, &ctx->ctx.cryptoapi.hash_handle)) { ctx->ctx.cryptoapi.valid = 0; git_error_set(GIT_ERROR_OS, "legacy hash implementation could not be created"); return -1; } ctx->ctx.cryptoapi.valid = 1; return 0; } GIT_INLINE(int) hash_cryptoapi_update(git_hash_ctx *ctx, const void *_data, size_t len) { const BYTE *data = (BYTE *)_data; assert(ctx->ctx.cryptoapi.valid); while (len > 0) { DWORD chunk = (len > MAXDWORD) ? MAXDWORD : (DWORD)len; if (!CryptHashData(ctx->ctx.cryptoapi.hash_handle, data, chunk, 0)) { git_error_set(GIT_ERROR_OS, "legacy hash data could not be updated"); return -1; } data += chunk; len -= chunk; } return 0; } GIT_INLINE(int) hash_cryptoapi_final(git_oid *out, git_hash_ctx *ctx) { DWORD len = 20; int error = 0; assert(ctx->ctx.cryptoapi.valid); if (!CryptGetHashParam(ctx->ctx.cryptoapi.hash_handle, HP_HASHVAL, out->id, &len, 0)) { git_error_set(GIT_ERROR_OS, "legacy hash data could not be finished"); error = -1; } CryptDestroyHash(ctx->ctx.cryptoapi.hash_handle); ctx->ctx.cryptoapi.valid = 0; return error; } GIT_INLINE(void) hash_ctx_cryptoapi_cleanup(git_hash_ctx *ctx) { if (ctx->ctx.cryptoapi.valid) CryptDestroyHash(ctx->ctx.cryptoapi.hash_handle); } /* CNG: Available in Windows Server 2008 and newer */ GIT_INLINE(int) hash_ctx_cng_init(git_hash_ctx *ctx) { if ((ctx->ctx.cng.hash_object = git__malloc(hash_prov.prov.cng.hash_object_size)) == NULL) return -1; if (hash_prov.prov.cng.create_hash(hash_prov.prov.cng.handle, &ctx->ctx.cng.hash_handle, ctx->ctx.cng.hash_object, hash_prov.prov.cng.hash_object_size, NULL, 0, 0) < 0) { git__free(ctx->ctx.cng.hash_object); git_error_set(GIT_ERROR_OS, "hash implementation could not be created"); return -1; } ctx->type = CNG; ctx->prov = &hash_prov; return 0; } GIT_INLINE(int) hash_cng_init(git_hash_ctx *ctx) { BYTE hash[GIT_OID_RAWSZ]; if (!ctx->ctx.cng.updated) return 0; /* CNG needs to be finished to restart */ if (ctx->prov->prov.cng.finish_hash(ctx->ctx.cng.hash_handle, hash, GIT_OID_RAWSZ, 0) < 0) { git_error_set(GIT_ERROR_OS, "hash implementation could not be finished"); return -1; } ctx->ctx.cng.updated = 0; return 0; } GIT_INLINE(int) hash_cng_update(git_hash_ctx *ctx, const void *_data, size_t len) { PBYTE data = (PBYTE)_data; while (len > 0) { ULONG chunk = (len > ULONG_MAX) ? ULONG_MAX : (ULONG)len; if (ctx->prov->prov.cng.hash_data(ctx->ctx.cng.hash_handle, data, chunk, 0) < 0) { git_error_set(GIT_ERROR_OS, "hash could not be updated"); return -1; } data += chunk; len -= chunk; } return 0; } GIT_INLINE(int) hash_cng_final(git_oid *out, git_hash_ctx *ctx) { if (ctx->prov->prov.cng.finish_hash(ctx->ctx.cng.hash_handle, out->id, GIT_OID_RAWSZ, 0) < 0) { git_error_set(GIT_ERROR_OS, "hash could not be finished"); return -1; } ctx->ctx.cng.updated = 0; return 0; } GIT_INLINE(void) hash_ctx_cng_cleanup(git_hash_ctx *ctx) { ctx->prov->prov.cng.destroy_hash(ctx->ctx.cng.hash_handle); git__free(ctx->ctx.cng.hash_object); } /* Indirection between CryptoAPI and CNG */ int git_hash_ctx_init(git_hash_ctx *ctx) { int error = 0; assert(ctx); /* * When compiled with GIT_THREADS, the global hash_prov data is * initialized with git_libgit2_init. Otherwise, it must be initialized * at first use. */ if (hash_prov.type == INVALID && (error = git_hash_global_init()) < 0) return error; memset(ctx, 0x0, sizeof(git_hash_ctx)); return (hash_prov.type == CNG) ? hash_ctx_cng_init(ctx) : hash_ctx_cryptoapi_init(ctx); } int git_hash_init(git_hash_ctx *ctx) { assert(ctx && ctx->type); return (ctx->type == CNG) ? hash_cng_init(ctx) : hash_cryptoapi_init(ctx); } int git_hash_update(git_hash_ctx *ctx, const void *data, size_t len) { assert(ctx && ctx->type); return (ctx->type == CNG) ? hash_cng_update(ctx, data, len) : hash_cryptoapi_update(ctx, data, len); } int git_hash_final(git_oid *out, git_hash_ctx *ctx) { assert(ctx && ctx->type); return (ctx->type == CNG) ? hash_cng_final(out, ctx) : hash_cryptoapi_final(out, ctx); } void git_hash_ctx_cleanup(git_hash_ctx *ctx) { assert(ctx); if (ctx->type == CNG) hash_ctx_cng_cleanup(ctx); else if(ctx->type == CRYPTOAPI) hash_ctx_cryptoapi_cleanup(ctx); }
ecf3be0fc53696a28b11a111ec05c1f3eb6961bd
99bdb3251fecee538e0630f15f6574054dfc1468
/bsp/samd21/sam_d2x_asflib/sam0/utils/cmsis/samd20/include/instance/tc2.h
513733ddf9fb19438d779f94d37f2b5f9f735af4
[ "Zlib", "LicenseRef-scancode-proprietary-license", "MIT", "BSD-3-Clause", "X11", "BSD-4-Clause-UC", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
RT-Thread/rt-thread
03a7c52c2aeb1b06a544143b0e803d72f47d1ece
3602f891211904a27dcbd51e5ba72fefce7326b2
refs/heads/master
2023-09-01T04:10:20.295801
2023-08-31T16:20:55
2023-08-31T16:20:55
7,408,108
9,599
5,805
Apache-2.0
2023-09-14T13:37:26
2013-01-02T14:49:21
C
UTF-8
C
false
false
6,563
h
tc2.h
/** * \file * * \brief Instance description for TC2 * * Copyright (c) 2014-2015 Atmel Corporation. All rights reserved. * * \asf_license_start * * \page 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. * * 3. The name of Atmel may not be used to endorse or promote products derived * from this software without specific prior written permission. * * 4. This software may only be redistributed and used in connection with an * Atmel microcontroller product. * * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. * * \asf_license_stop * */ /* * Support and FAQ: visit <a href="http://www.atmel.com/design-support/">Atmel Support</a> */ #ifndef _SAMD20_TC2_INSTANCE_ #define _SAMD20_TC2_INSTANCE_ /* ========== Register definition for TC2 peripheral ========== */ #if (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) #define REG_TC2_CTRLA (0x42002800U) /**< \brief (TC2) Control A */ #define REG_TC2_READREQ (0x42002802U) /**< \brief (TC2) Read Request */ #define REG_TC2_CTRLBCLR (0x42002804U) /**< \brief (TC2) Control B Clear */ #define REG_TC2_CTRLBSET (0x42002805U) /**< \brief (TC2) Control B Set */ #define REG_TC2_CTRLC (0x42002806U) /**< \brief (TC2) Control C */ #define REG_TC2_DBGCTRL (0x42002808U) /**< \brief (TC2) Debug Control */ #define REG_TC2_EVCTRL (0x4200280AU) /**< \brief (TC2) Event Control */ #define REG_TC2_INTENCLR (0x4200280CU) /**< \brief (TC2) Interrupt Enable Clear */ #define REG_TC2_INTENSET (0x4200280DU) /**< \brief (TC2) Interrupt Enable Set */ #define REG_TC2_INTFLAG (0x4200280EU) /**< \brief (TC2) Interrupt Flag Status and Clear */ #define REG_TC2_STATUS (0x4200280FU) /**< \brief (TC2) Status */ #define REG_TC2_COUNT16_COUNT (0x42002810U) /**< \brief (TC2) COUNT16 Counter Value */ #define REG_TC2_COUNT16_CC0 (0x42002818U) /**< \brief (TC2) COUNT16 Compare/Capture 0 */ #define REG_TC2_COUNT16_CC1 (0x4200281AU) /**< \brief (TC2) COUNT16 Compare/Capture 1 */ #define REG_TC2_COUNT32_COUNT (0x42002810U) /**< \brief (TC2) COUNT32 Counter Value */ #define REG_TC2_COUNT32_CC0 (0x42002818U) /**< \brief (TC2) COUNT32 Compare/Capture 0 */ #define REG_TC2_COUNT32_CC1 (0x4200281CU) /**< \brief (TC2) COUNT32 Compare/Capture 1 */ #define REG_TC2_COUNT8_COUNT (0x42002810U) /**< \brief (TC2) COUNT8 Counter Value */ #define REG_TC2_COUNT8_PER (0x42002814U) /**< \brief (TC2) COUNT8 Period Value */ #define REG_TC2_COUNT8_CC0 (0x42002818U) /**< \brief (TC2) COUNT8 Compare/Capture 0 */ #define REG_TC2_COUNT8_CC1 (0x42002819U) /**< \brief (TC2) COUNT8 Compare/Capture 1 */ #else #define REG_TC2_CTRLA (*(RwReg16*)0x42002800U) /**< \brief (TC2) Control A */ #define REG_TC2_READREQ (*(RwReg16*)0x42002802U) /**< \brief (TC2) Read Request */ #define REG_TC2_CTRLBCLR (*(RwReg8 *)0x42002804U) /**< \brief (TC2) Control B Clear */ #define REG_TC2_CTRLBSET (*(RwReg8 *)0x42002805U) /**< \brief (TC2) Control B Set */ #define REG_TC2_CTRLC (*(RwReg8 *)0x42002806U) /**< \brief (TC2) Control C */ #define REG_TC2_DBGCTRL (*(RwReg8 *)0x42002808U) /**< \brief (TC2) Debug Control */ #define REG_TC2_EVCTRL (*(RwReg16*)0x4200280AU) /**< \brief (TC2) Event Control */ #define REG_TC2_INTENCLR (*(RwReg8 *)0x4200280CU) /**< \brief (TC2) Interrupt Enable Clear */ #define REG_TC2_INTENSET (*(RwReg8 *)0x4200280DU) /**< \brief (TC2) Interrupt Enable Set */ #define REG_TC2_INTFLAG (*(RwReg8 *)0x4200280EU) /**< \brief (TC2) Interrupt Flag Status and Clear */ #define REG_TC2_STATUS (*(RoReg8 *)0x4200280FU) /**< \brief (TC2) Status */ #define REG_TC2_COUNT16_COUNT (*(RwReg16*)0x42002810U) /**< \brief (TC2) COUNT16 Counter Value */ #define REG_TC2_COUNT16_CC0 (*(RwReg16*)0x42002818U) /**< \brief (TC2) COUNT16 Compare/Capture 0 */ #define REG_TC2_COUNT16_CC1 (*(RwReg16*)0x4200281AU) /**< \brief (TC2) COUNT16 Compare/Capture 1 */ #define REG_TC2_COUNT32_COUNT (*(RwReg *)0x42002810U) /**< \brief (TC2) COUNT32 Counter Value */ #define REG_TC2_COUNT32_CC0 (*(RwReg *)0x42002818U) /**< \brief (TC2) COUNT32 Compare/Capture 0 */ #define REG_TC2_COUNT32_CC1 (*(RwReg *)0x4200281CU) /**< \brief (TC2) COUNT32 Compare/Capture 1 */ #define REG_TC2_COUNT8_COUNT (*(RwReg8 *)0x42002810U) /**< \brief (TC2) COUNT8 Counter Value */ #define REG_TC2_COUNT8_PER (*(RwReg8 *)0x42002814U) /**< \brief (TC2) COUNT8 Period Value */ #define REG_TC2_COUNT8_CC0 (*(RwReg8 *)0x42002818U) /**< \brief (TC2) COUNT8 Compare/Capture 0 */ #define REG_TC2_COUNT8_CC1 (*(RwReg8 *)0x42002819U) /**< \brief (TC2) COUNT8 Compare/Capture 1 */ #endif /* (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */ /* ========== Instance parameters for TC2 peripheral ========== */ #define TC2_CC8_NUM 2 #define TC2_CC16_NUM 2 #define TC2_CC32_NUM 2 #define TC2_DITHERING_EXT 0 #define TC2_GCLK_ID 20 #define TC2_MASTER 1 #define TC2_OW_NUM 2 #define TC2_PERIOD_EXT 0 #define TC2_SHADOW_EXT 0 #endif /* _SAMD20_TC2_INSTANCE_ */
8c0bb7dc3d6f89d0db619b53119bde648db28fc2
52c8ed39b32ccc7c0673278c1adea3638797c9ff
/src/lib/libm/__sindf.c
f5fc4690165f6eeb2d6129e39ec270bed86cf935
[ "MIT" ]
permissive
xboot/xboot
0cab7b440b612aa0a4c366025598a53a7ec3adf1
6d6b93947b7fcb8c3924fedb0715c23877eedd5e
refs/heads/master
2023-08-20T05:56:25.149388
2023-07-12T07:38:29
2023-07-12T07:38:29
471,539
765
296
MIT
2023-05-25T09:39:01
2010-01-14T08:25:12
C
UTF-8
C
false
false
552
c
__sindf.c
#include <math.h> /* |sin(x)/x - s(x)| < 2**-37.5 (~[-4.89e-12, 4.824e-12]). */ static const double S1 = -0x15555554cbac77.0p-55, /* -0.166666666416265235595 */ S2 = 0x111110896efbb2.0p-59, /* 0.0083333293858894631756 */ S3 = -0x1a00f9e2cae774.0p-65, /* -0.000198393348360966317347 */ S4 = 0x16cd878c3b46a7.0p-71; /* 0.0000027183114939898219064 */ float __sindf(double x) { double_t r, s, w, z; /* Try to optimize for parallel evaluation as in __tandf.c. */ z = x*x; w = z*z; r = S3 + z*S4; s = z*x; return (x + s*(S1 + z*S2)) + s*w*r; }
ddbf1275275adeb9e03fc77f682f7db034e35d20
ab6aef3d7a1a848f9608df01a7a87b02809ba4ab
/platform/posix/ota_pal/source/ota_pal_posix.c
34568462607806021d1f9396d91e55868aed7c41
[ "MIT" ]
permissive
aws/aws-iot-device-sdk-embedded-C
acab1a9ec9e3abfc9fe30d708c1695e2b35cc22f
61c9847af8e27f066c0c86c45183ce4e420be414
refs/heads/main
2023-09-06T03:47:48.078471
2022-02-23T23:38:30
2023-08-30T18:15:46
43,013,346
1,004
735
MIT
2023-09-12T20:26:33
2015-09-23T16:32:49
C
UTF-8
C
false
false
24,873
c
ota_pal_posix.c
/* * OTA PAL V2.0.1 for POSIX * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, 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. */ /* OTA PAL implementation for POSIX platform. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <assert.h> #include <libgen.h> #include <unistd.h> #include "ota.h" #include "ota_pal_posix.h" #include <openssl/evp.h> #include <openssl/bio.h> #include <openssl/x509.h> #include <openssl/pem.h> /** * @brief Code signing certificate * * The certificate is used for OTA image signing. If a platform does not support a file * system the signing certificate can be pasted here for testing purpose. * * PEM-encoded code signer certificate * * Must include the PEM header and footer: * "-----BEGIN CERTIFICATE-----\n" * "...base64 data...\n" * "-----END CERTIFICATE-----\n"; */ static const char signingcredentialSIGNING_CERTIFICATE_PEM[] = "Paste code signing certificate here"; /** * @brief Size of buffer used in file operations on this platform (POSIX). */ #define OTA_PAL_POSIX_BUF_SIZE ( ( size_t ) 4096U ) /** * @brief Name of the file used for storing platform image state. */ #define OTA_PLATFORM_IMAGE_STATE_FILE "PlatformImageState.txt" /** * @brief Specify the OTA signature algorithm we support on this platform. */ const char OTA_JsonFileSignatureKey[ OTA_FILE_SIG_KEY_STR_MAX_LENGTH ] = "sig-sha256-ecdsa"; /** * @brief Read the specified signer certificate from the filesystem into a local buffer. The allocated * memory becomes the property of the caller who is responsible for freeing it. */ static EVP_PKEY * Openssl_GetPkeyFromCertificate( uint8_t * pCertFilePath ); /** * @brief Verify the signature of the input content with OpenSSL. */ static OtaPalMainStatus_t Openssl_DigestVerify( EVP_MD_CTX * pSigContext, EVP_PKEY * pPkey, FILE * pFile, Sig_t * pSignature ); /** * @brief Verify the signature of the specified file using OpenSSL. */ static OtaPalStatus_t otaPal_CheckFileSignature( OtaFileContext_t * const C ); /** * @brief Get the absolute file path from the environment. * * @param realFilePath Buffer to store the file path + file name. * @param pFilePath File name to append to the end of current path. */ static OtaPalPathGenStatus_t getFilePathFromCWD( char * realFilePath, const char * pFilePath ); /*-----------------------------------------------------------*/ static EVP_PKEY * Openssl_GetPkeyFromCertificate( uint8_t * pCertFilePath ) { BIO * pBio = NULL; X509 * pCert = NULL; EVP_PKEY * pPkey = NULL; int32_t rc = 0; /* Read the cert file */ pBio = BIO_new( BIO_s_file() ); if( pBio != NULL ) { /* coverity[misra_c_2012_rule_10_1_violation] */ rc = BIO_read_filename( pBio, pCertFilePath ); if( rc != 1 ) { LogDebug( ( " No cert file, reading signer cert from header file\n" ) ); /* Get the signer cert from a predefined PEM string */ BIO_free_all( pBio ); pBio = BIO_new( BIO_s_mem() ); if( pBio != NULL ) { rc = BIO_puts( pBio, signingcredentialSIGNING_CERTIFICATE_PEM ); if( rc <= 0 ) { LogError( ( "Failed to write a PEM string to BIO stream" ) ); } } else { LogError( ( "Failed to read certificate from a PEM string." ) ); } } else { LogDebug( ( "Opened certificate file." ) ); } } if( ( pBio != NULL ) && ( rc > 0 ) ) { pCert = PEM_read_bio_X509( pBio, NULL, NULL, NULL ); if( pCert != NULL ) { LogDebug( ( "Getting the pkey from the X509 cert." ) ); /* Extract the public key */ pPkey = X509_get_pubkey( pCert ); if( pPkey == NULL ) { LogError( ( "Failed to get pkey from the signer cert." ) ); } } else { LogError( ( "Failed to load cert from either file or predefined string." ) ); } } else { LogError( ( "Failed to read signer cert." ) ); } BIO_free_all( pBio ); X509_free( pCert ); /* pPkey should be freed by the caller */ return pPkey; } static OtaPalMainStatus_t Openssl_DigestVerifyStart( EVP_MD_CTX * pSigContext, EVP_PKEY * pPkey, FILE * pFile, uint8_t ** pBuf ) { OtaPalMainStatus_t mainErr = OtaPalSignatureCheckFailed; assert( pBuf != NULL ); assert( ( pSigContext != NULL ) && ( pPkey != NULL ) ); /* Verify an ECDSA-SHA256 signature. */ if( ( pFile != NULL ) && ( 1 == EVP_DigestVerifyInit( pSigContext, NULL, EVP_sha256(), NULL, pPkey ) ) ) { LogDebug( ( "Started signature verification." ) ); *pBuf = OPENSSL_malloc( OTA_PAL_POSIX_BUF_SIZE ); if( *pBuf == NULL ) { LogError( ( "Failed to allocate buffer memory." ) ); mainErr = OtaPalOutOfMemory; } else { mainErr = OtaPalSuccess; } } else { LogError( ( "File signature check failed at INIT." ) ); } return mainErr; } static bool Openssl_DigestVerifyUpdate( EVP_MD_CTX * pSigContext, FILE * pFile, uint8_t * pBuf ) { size_t bytesRead; do { /* POSIX port using standard library */ /* coverity[misra_c_2012_rule_21_6_violation] */ bytesRead = fread( pBuf, 1U, OTA_PAL_POSIX_BUF_SIZE, pFile ); assert( bytesRead <= OTA_PAL_POSIX_BUF_SIZE ); /* feof returns non-zero if end of file is reached, otherwise it returns 0. When * bytesRead is not equal to OTA_PAL_POSIX_BUF_SIZE, we should be reading last * chunk and reach to end of file. */ /* POSIX port using standard library */ /* coverity[misra_c_2012_rule_21_6_violation] */ if( ( bytesRead < OTA_PAL_POSIX_BUF_SIZE ) && ( 0 == feof( pFile ) ) ) { break; } /* Include the file chunk in the signature validation. Zero size is OK. */ if( 1 != EVP_DigestVerifyUpdate( pSigContext, pBuf, bytesRead ) ) { break; } } while( bytesRead > 0UL ); /* POSIX port using standard library */ /* coverity[misra_c_2012_rule_21_6_violation] */ return( 0 != feof( pFile ) ? true : false ); } static OtaPalMainStatus_t Openssl_DigestVerify( EVP_MD_CTX * pSigContext, EVP_PKEY * pPkey, FILE * pFile, Sig_t * pSignature ) { OtaPalMainStatus_t mainErr = OtaPalSignatureCheckFailed; OtaPalMainStatus_t startErr; uint8_t * pBuf; startErr = Openssl_DigestVerifyStart( pSigContext, pPkey, pFile, &pBuf ); if( OtaPalSuccess == startErr ) { /* Rewind the received file to the beginning. */ /* POSIX port using standard library */ /* coverity[misra_c_2012_rule_21_6_violation] */ if( fseek( pFile, 0L, SEEK_SET ) == 0 ) { bool eof = Openssl_DigestVerifyUpdate( pSigContext, pFile, pBuf ); if( ( eof == true ) && ( 1 == EVP_DigestVerifyFinal( pSigContext, pSignature->data, pSignature->size ) ) ) { mainErr = OtaPalSuccess; } else { LogError( ( "File signature check failed at FINAL" ) ); } } /* Free the temporary file page buffer. */ OPENSSL_free( pBuf ); } else { mainErr = startErr; } return mainErr; } static OtaPalStatus_t otaPal_CheckFileSignature( OtaFileContext_t * const C ) { OtaPalMainStatus_t mainErr = OtaPalSignatureCheckFailed; EVP_PKEY * pPkey = NULL; EVP_MD_CTX * pSigContext = NULL; assert( C != NULL ); /* Extract the signer cert from the file. */ pPkey = Openssl_GetPkeyFromCertificate( C->pCertFilepath ); /* Create a new signature context for verification purpose. */ pSigContext = EVP_MD_CTX_new(); if( ( pPkey != NULL ) && ( pSigContext != NULL ) ) { /* Verify the signature. */ mainErr = Openssl_DigestVerify( pSigContext, pPkey, C->pFile, C->pSignature ); } else { if( pSigContext == NULL ) { LogError( ( "File signature check failed at NEW sig context." ) ); } else { LogError( ( "File signature check failed at EXTRACT pkey from signer certificate." ) ); mainErr = OtaPalBadSignerCert; } } /* Free up objects */ EVP_MD_CTX_free( pSigContext ); EVP_PKEY_free( pPkey ); return OTA_PAL_COMBINE_ERR( mainErr, 0 ); } static OtaPalPathGenStatus_t getFilePathFromCWD( char * pCompleteFilePath, const char * pFileName ) { char * pCurrentDir = NULL; OtaPalPathGenStatus_t status = OtaPalFileGenSuccess; /* Get current directory. */ pCurrentDir = getcwd( pCompleteFilePath, OTA_FILE_PATH_LENGTH_MAX - 1 ); if( pCurrentDir == NULL ) { LogError( ( "Failed to get current working directory: %s", strerror( errno ) ) ); status = OtaPalCWDFailed; } else { /* Add the filename . */ if( strlen( pCompleteFilePath ) + strlen( pFileName ) + 2U > OTA_FILE_PATH_LENGTH_MAX ) { LogError( ( "Insufficient space to generate file path" ) ); status = OtaPalBufferInsufficient; } else { strcat( pCompleteFilePath, "/" ); strcat( pCompleteFilePath, pFileName ); } } return status; } /*-----------------------------------------------------------*/ OtaPalStatus_t otaPal_Abort( OtaFileContext_t * const C ) { /* Set default return status to uninitialized. */ OtaPalMainStatus_t mainErr = OtaPalUninitialized; int32_t subErr = 0; int32_t lFileCloseResult; if( NULL != C ) { /* Close the OTA update file if it's open. */ if( NULL != C->pFile ) { /* POSIX port using standard library */ /* coverity[misra_c_2012_rule_21_6_violation] */ lFileCloseResult = fclose( C->pFile ); C->pFile = NULL; if( 0 == lFileCloseResult ) { LogInfo( ( "Closed file." ) ); mainErr = OtaPalSuccess; } else /* Failed to close file. */ { LogError( ( "Failed to close file." ) ); mainErr = OtaPalFileAbort; subErr = errno; } } else { /* Nothing to do. No open file associated with this context. */ mainErr = OtaPalSuccess; } } else /* Context was not valid. */ { LogError( ( "Parameter check failed: Input is NULL." ) ); mainErr = OtaPalFileAbort; } return OTA_PAL_COMBINE_ERR( mainErr, subErr ); } OtaPalStatus_t otaPal_CreateFileForRx( OtaFileContext_t * const C ) { OtaPalStatus_t result = OTA_PAL_COMBINE_ERR( OtaPalUninitialized, 0 ); char realFilePath[ OTA_FILE_PATH_LENGTH_MAX ]; OtaPalPathGenStatus_t status = OtaPalFileGenSuccess; if( C != NULL ) { if( ( C->pFilePath != NULL ) && ( ( strlen( ( const char * ) C->pFilePath ) + 1U ) > OTA_FILE_PATH_LENGTH_MAX ) ) { LogError( ( "File path exceed length limit." ) ); result = OTA_PAL_COMBINE_ERR( OtaPalRxFileCreateFailed, 0 ); } else if( C->pFilePath != NULL ) { if( C->pFilePath[ 0 ] != ( uint8_t ) '/' ) { status = getFilePathFromCWD( realFilePath, ( const char * ) C->pFilePath ); } else { ( void ) memcpy( realFilePath, ( const char * ) C->pFilePath, strlen( ( const char * ) C->pFilePath ) + 1U ); } if( status == OtaPalFileGenSuccess ) { /* POSIX port using standard library */ /* coverity[misra_c_2012_rule_21_6_violation] */ C->pFile = fopen( ( const char * ) realFilePath, "w+b" ); if( C->pFile != NULL ) { result = OTA_PAL_COMBINE_ERR( OtaPalSuccess, 0 ); LogInfo( ( "Receive file created." ) ); } else { result = OTA_PAL_COMBINE_ERR( OtaPalRxFileCreateFailed, errno ); LogError( ( "Failed to start operation: Operation already started. failed to open -- %s Path ", C->pFilePath ) ); } } else { LogError( ( "Could not generate the absolute path for the file" ) ); result = OTA_PAL_COMBINE_ERR( OtaPalRxFileCreateFailed, 0 ); } } else { result = OTA_PAL_COMBINE_ERR( OtaPalRxFileCreateFailed, 0 ); LogError( ( "Invalid file path provided." ) ); } } else { result = OTA_PAL_COMBINE_ERR( OtaPalRxFileCreateFailed, 0 ); LogError( ( "Invalid context provided." ) ); } /* Exiting function without calling fclose. Context file handle state is managed by this API. */ return result; } OtaPalStatus_t otaPal_CloseFile( OtaFileContext_t * const C ) { int32_t filerc = 0; OtaPalMainStatus_t mainErr = OtaPalSuccess; OtaPalSubStatus_t subErr = 0; OtaPalStatus_t result; if( C != NULL ) { if( C->pSignature != NULL ) { /* Verify the file signature, close the file and return the signature verification result. */ result = otaPal_CheckFileSignature( C ); mainErr = OTA_PAL_MAIN_ERR( result ); subErr = OTA_PAL_SUB_ERR( result ); } else { LogError( ( "Parameter check failed: OTA signature structure is NULL." ) ); mainErr = OtaPalSignatureCheckFailed; } /* Close the file. */ /* POSIX port using standard library */ /* coverity[misra_c_2012_rule_21_6_violation] */ filerc = fclose( C->pFile ); C->pFile = NULL; if( filerc != 0 ) { LogError( ( "Failed to close OTA update file." ) ); mainErr = OtaPalFileClose; subErr = ( uint32_t ) errno; } if( mainErr == OtaPalSuccess ) { LogInfo( ( "%s signature verification passed.", OTA_JsonFileSignatureKey ) ); ( void ) otaPal_SetPlatformImageState( C, OtaImageStateTesting ); } else { LogError( ( "Failed to pass %s signature verification: %d.", OTA_JsonFileSignatureKey, OTA_PAL_COMBINE_ERR( mainErr, subErr ) ) ); /* If we fail to verify the file signature that means the image is not valid. We need to set the image state to aborted. */ ( void ) otaPal_SetPlatformImageState( C, OtaImageStateAborted ); } } else /* Invalid OTA Context. */ { LogError( ( "Failed to close file: " "Parameter check failed: " "Invalid context." ) ); mainErr = OtaPalFileClose; } return OTA_PAL_COMBINE_ERR( mainErr, subErr ); } int16_t otaPal_WriteBlock( OtaFileContext_t * const C, uint32_t ulOffset, uint8_t * const pcData, uint32_t ulBlockSize ) { int32_t filerc = 0; size_t writeSize = 0; if( C != NULL ) { /* POSIX port using standard library */ /* coverity[misra_c_2012_rule_21_6_violation] */ filerc = fseek( C->pFile, ( int64_t ) ulOffset, SEEK_SET ); if( 0 == filerc ) { /* POSIX port using standard library */ /* coverity[misra_c_2012_rule_21_6_violation] */ writeSize = fwrite( pcData, 1, ulBlockSize, C->pFile ); if( writeSize != ulBlockSize ) { LogError( ( "Failed to write block to file: " "fwrite returned error: " "errno=%d", errno ) ); filerc = -1; } else { filerc = ( int32_t ) writeSize; } } else { LogError( ( "fseek failed. fseek returned errno = %d", errno ) ); filerc = -1; } } else /* Invalid context or file pointer provided. */ { LogError( ( "Invalid context." ) ); filerc = -1; } return ( int16_t ) filerc; } /* Return no error. POSIX implementation simply does nothing on activate. */ OtaPalStatus_t otaPal_ActivateNewImage( OtaFileContext_t * const C ) { ( void ) C; return OTA_PAL_COMBINE_ERR( OtaPalSuccess, 0 ); } /* Set the final state of the last transferred (final) OTA file (or bundle). * On POSIX, the state of the OTA image is stored in PlatformImageState.txt. */ OtaPalStatus_t otaPal_SetPlatformImageState( OtaFileContext_t * const C, OtaImageState_t eState ) { OtaPalMainStatus_t mainErr = OtaPalBadImageState; OtaPalPathGenStatus_t status = OtaPalFileGenSuccess; int32_t subErr = 0; FILE * pPlatformImageState = NULL; char imageStateFile[ OTA_FILE_PATH_LENGTH_MAX ] = { 0 }; ( void ) C; if( ( eState != OtaImageStateUnknown ) && ( eState <= OtaLastImageState ) ) { /* Get file path for the image state file. */ status = getFilePathFromCWD( imageStateFile, OTA_PLATFORM_IMAGE_STATE_FILE ); if( status == OtaPalFileGenSuccess ) { /* POSIX port using standard library */ /* coverity[misra_c_2012_rule_21_6_violation] */ pPlatformImageState = fopen( imageStateFile, "w+b" ); } else { LogError( ( "Could not generate the absolute path for the file" ) ); } if( pPlatformImageState != NULL ) { /* Write the image state to PlatformImageState.txt. */ /* POSIX port using standard library */ /* coverity[misra_c_2012_rule_21_6_violation] */ if( 1UL == fwrite( &eState, sizeof( OtaImageState_t ), 1, pPlatformImageState ) ) { /* Close PlatformImageState.txt. */ /* POSIX port using standard library */ /* coverity[misra_c_2012_rule_21_6_violation] */ if( 0 == fclose( pPlatformImageState ) ) { mainErr = OtaPalSuccess; } else { LogError( ( "Unable to close image state file." ) ); subErr = errno; } } else { LogError( ( "Unable to write to image state file. error-- %d", errno ) ); subErr = errno; /* The file should be closed, but errno passed out is fwrite error */ /* POSIX port using standard library */ /* coverity[misra_c_2012_rule_21_6_violation] */ ( void ) fclose( pPlatformImageState ); } } else { LogError( ( "Unable to open image state file. Path: %s error: %s", imageStateFile, strerror( errno ) ) ); subErr = errno; } } else /* Image state invalid. */ { LogError( ( "Invalid image state provided." ) ); } /* Allow calls to fopen and fclose in this context. */ return OTA_PAL_COMBINE_ERR( mainErr, subErr ); } OtaPalStatus_t otaPal_ResetDevice( OtaFileContext_t * const C ) { ( void ) C; /* Return no error. POSIX implementation does not reset device. */ return OTA_PAL_COMBINE_ERR( OtaPalSuccess, 0 ); } /* Get the state of the currently running image. * * On POSIX, this is simulated by looking for and reading the state from * the PlatformImageState.txt file in the current working directory. * * We read this at OTA_Init time so we can tell if the MCU image is in self * test mode. If it is, we expect a successful connection to the OTA services * within a reasonable amount of time. If we don't satisfy that requirement, * we assume there is something wrong with the firmware and reset the device, * causing it to rollback to the previous code. On POSIX, this is not * fully simulated as there is no easy way to reset the simulated device. */ OtaPalImageState_t otaPal_GetPlatformImageState( OtaFileContext_t * const C ) { FILE * pPlatformImageState = NULL; OtaImageState_t eSavedAgentState = OtaImageStateUnknown; OtaPalImageState_t ePalState = OtaPalImageStateUnknown; OtaPalPathGenStatus_t status = OtaPalFileGenSuccess; char imageStateFile[ OTA_FILE_PATH_LENGTH_MAX ] = { 0 }; ( void ) C; /* Get file path for the image state file. */ status = getFilePathFromCWD( imageStateFile, OTA_PLATFORM_IMAGE_STATE_FILE ); if( status != OtaPalFileGenSuccess ) { LogError( ( "Could not generate the absolute path for the file" ) ); ePalState = OtaPalImageStateInvalid; } else { /* POSIX port using standard library */ /* coverity[misra_c_2012_rule_21_6_violation] */ pPlatformImageState = fopen( imageStateFile, "r+b" ); if( pPlatformImageState != NULL ) { /* POSIX port using standard library */ /* coverity[misra_c_2012_rule_21_6_violation] */ if( 1U != fread( &eSavedAgentState, sizeof( OtaImageState_t ), 1, pPlatformImageState ) ) { /* If an error occurred reading the file, mark the state as aborted. */ LogError( ( "Failed to read image state file." ) ); ePalState = OtaPalImageStateInvalid; } else { if( eSavedAgentState == OtaImageStateTesting ) { ePalState = OtaPalImageStatePendingCommit; } else if( eSavedAgentState == OtaImageStateAccepted ) { ePalState = OtaPalImageStateValid; } else { ePalState = OtaPalImageStateInvalid; } } /* POSIX port using standard library */ /* coverity[misra_c_2012_rule_21_6_violation] */ if( 0 != fclose( pPlatformImageState ) ) { LogError( ( "Failed to close image state file." ) ); ePalState = OtaPalImageStateInvalid; } } else { /* If no image state file exists, assume a factory image. */ ePalState = OtaPalImageStateValid; /*lint !e64 Allow assignment. */ } } return ePalState; } /*-----------------------------------------------------------*/
a88e2eac9b517e76b256fcac521ef2ab2c82087f
5e4913b3d7b6dfd9f35d9e5f24486bb6b6145125
/src/plugins/gopts/testdata.h
d276594eb7700de3226ab0f16a9d64beb2879c45
[ "BSD-3-Clause" ]
permissive
ElektraInitiative/libelektra
ff5d5cfc4bf91d704f58405b14ea694aad3a2edd
dbbe4ae4f669c322a8f95f59112d3f5fc370bbd9
refs/heads/master
2023-08-05T14:54:48.081359
2023-08-04T12:40:00
2023-08-04T12:40:00
21,063,580
215
170
BSD-3-Clause
2023-09-07T13:34:30
2014-06-21T08:01:04
C
UTF-8
C
false
false
2,481
h
testdata.h
/** * @file * * @brief Tests for specload plugin * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) * */ #ifndef ELEKTRA_GOPTS_TESTDATA_H #define ELEKTRA_GOPTS_TESTDATA_H #define TEST_EMPTY "empty" #define TEST_KS_EMPTY ksNew (1, keyNew ("spec:/tests/gopts/key", KEY_META, "default", "5", KEY_END), KS_END) #define TEST_SINGLEOPT "singleopt" #define TEST_KS_SINGLEOPT \ ksNew (1, keyNew ("spec:/tests/gopts/key", KEY_META, "opt", "c", KEY_META, "opt/long", "longopt", KEY_END), KS_END) #define TEST_TWOOPT "twoopt" #define TEST_KS_TWOOPT \ ksNew (2, keyNew ("spec:/tests/gopts/key", KEY_META, "opt", "c", KEY_META, "opt/long", "longopt", KEY_END), \ keyNew ("spec:/tests/gopts/key2", KEY_META, "opt", "b", KEY_META, "opt/long", "longopt2", KEY_END), KS_END) #define TEST_SINGLEENV "singleenv" #define TEST_KS_SINGLEENV ksNew (1, keyNew ("spec:/tests/gopts/key", KEY_META, "env", "ENV_VAR", KEY_END), KS_END) #define TEST_TWOENV "twoenv" #define TEST_KS_TWOENV \ ksNew (2, keyNew ("spec:/tests/gopts/key", KEY_META, "env", "ENV_VAR", KEY_END), \ keyNew ("spec:/tests/gopts/key2", KEY_META, "env", "OTHER_ENV_VAR", KEY_END), KS_END) #define TEST_MIXED "mixed" #define TEST_KS_MIXED \ ksNew (2, \ keyNew ("spec:/tests/gopts/key", KEY_META, "opt", "c", KEY_META, "opt/long", "longopt", KEY_META, "env", "ENV_VAR", \ KEY_END), \ keyNew ("spec:/tests/gopts/key2", KEY_META, "opt", "b", KEY_META, "opt/long", "longopt2", KEY_META, "env", "OTHER_ENV_VAR", \ KEY_END), \ KS_END) #endif // ELEKTRA_GOPTS_TESTDATA_H
2b9b2075f11f289cce7df8e92029cad5f2382acc
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
/security/pgpin/files/patch-fileio.h
a745a57ae0b8a0a62828166457274eba77d29c4a
[ "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
312
h
patch-fileio.h
--- fileio.h.orig Mon Jan 12 09:13:04 1998 +++ fileio.h Fri Mar 23 13:55:39 2001 @@ -28,7 +28,7 @@ #ifdef LINUX # define PGP_SYSTEM_DIR "/usr/lib/pgp/" #else -# define PGP_SYSTEM_DIR "/usr/local/lib/pgp/" +# define PGP_SYSTEM_DIR "/usr/local/lib/pgpin/" #endif #define FOPRBIN "r" #define FOPRTXT "r"
04dd673497d19b1c9c1e2aeba825fc019856cbfc
35e28d7705773eed54345af4440700522c9d1863
/deps/libproj/proj/src/PJ_cea.c
44c0a887de4a62547e317d89bc27bafa5bf81560
[ "Apache-2.0", "LicenseRef-scancode-us-govt-public-domain", "MIT" ]
permissive
naturalatlas/node-gdal
0ee3447861bf2d1abc48d4fbdbcf15aba5473a27
c83e7858a9ec566cc91d65db74fd07b99789c0f0
refs/heads/master
2023-09-03T00:11:41.576937
2022-03-12T20:41:59
2022-03-12T20:41:59
19,504,824
522
122
Apache-2.0
2022-06-04T20:03:43
2014-05-06T18:02:34
C++
UTF-8
C
false
false
1,351
c
PJ_cea.c
#define PROJ_PARMS__ \ double qp; \ double *apa; #define PJ_LIB__ # include <projects.h> PROJ_HEAD(cea, "Equal Area Cylindrical") "\n\tCyl, Sph&Ell\n\tlat_ts="; # define EPS 1e-10 FORWARD(e_forward); /* spheroid */ xy.x = P->k0 * lp.lam; xy.y = .5 * pj_qsfn(sin(lp.phi), P->e, P->one_es) / P->k0; return (xy); } FORWARD(s_forward); /* spheroid */ xy.x = P->k0 * lp.lam; xy.y = sin(lp.phi) / P->k0; return (xy); } INVERSE(e_inverse); /* spheroid */ lp.phi = pj_authlat(asin( 2. * xy.y * P->k0 / P->qp), P->apa); lp.lam = xy.x / P->k0; return (lp); } INVERSE(s_inverse); /* spheroid */ double t; if ((t = fabs(xy.y *= P->k0)) - EPS <= 1.) { if (t >= 1.) lp.phi = xy.y < 0. ? -HALFPI : HALFPI; else lp.phi = asin(xy.y); lp.lam = xy.x / P->k0; } else I_ERROR; return (lp); } FREEUP; if (P) { if (P->apa) pj_dalloc(P->apa); pj_dalloc(P); } } ENTRY1(cea, apa) double t = 0.0; if (pj_param(P->ctx, P->params, "tlat_ts").i) { P->k0 = cos(t = pj_param(P->ctx, P->params, "rlat_ts").f); if (P->k0 < 0.) { E_ERROR(-24); } } if (P->es) { t = sin(t); P->k0 /= sqrt(1. - P->es * t * t); P->e = sqrt(P->es); if (!(P->apa = pj_authset(P->es))) E_ERROR_0; P->qp = pj_qsfn(1., P->e, P->one_es); P->inv = e_inverse; P->fwd = e_forward; } else { P->inv = s_inverse; P->fwd = s_forward; } ENDENTRY(P)
99f28901678cfdc9687c60b115da6815c809107e
e89c145809bcba2f80f330d5e1c64c3de12f2463
/thirdparty/SDL_inprint/inline_font.h
fecce734baf32497e36f8fddbaa8aed353c8fbf1
[ "MIT" ]
permissive
daniel5151/ANESE
1454540e29fffdb258f38cc3340425a70133f324
8ae814d615479b1496c98033a1f5bc4da5921c6f
refs/heads/master
2022-01-24T01:53:49.246518
2022-01-11T22:34:56
2022-01-11T22:34:56
106,771,696
383
35
MIT
2021-12-03T22:30:03
2017-10-13T03:05:39
C++
UTF-8
C
false
false
6,329
h
inline_font.h
#define inline_font_width 128 #define inline_font_height 64 static unsigned char inline_font_bits[] = { 0x01, 0x66, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x39, 0xa5, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0xc3, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x39, 0x18, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x39, 0x18, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x19, 0xc3, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x98, 0xa5, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x66, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xbf, 0xe7, 0x99, 0x01, 0x83, 0xff, 0xe7, 0xe7, 0xe7, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x8f, 0xc3, 0x99, 0x24, 0x39, 0xff, 0xc3, 0xc3, 0xe7, 0xe7, 0xf3, 0xff, 0xff, 0xff, 0xff, 0xe0, 0x83, 0x81, 0x99, 0x24, 0xe3, 0xff, 0x81, 0x81, 0xe7, 0xcf, 0xf9, 0xff, 0xff, 0xff, 0xff, 0x80, 0x80, 0xe7, 0x99, 0x21, 0xc9, 0xff, 0xe7, 0xe7, 0xe7, 0x80, 0x80, 0xff, 0xff, 0xff, 0xff, 0xe0, 0x83, 0xe7, 0x99, 0x27, 0xc9, 0x81, 0x81, 0xe7, 0x81, 0xcf, 0xf9, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x8f, 0x81, 0xff, 0x27, 0xe3, 0x81, 0xc3, 0xe7, 0xc3, 0xe7, 0xf3, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xbf, 0xc3, 0x99, 0x27, 0xcc, 0x81, 0xe7, 0xe7, 0xe7, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe7, 0xff, 0xff, 0xe1, 0xff, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf3, 0xc9, 0xc9, 0xf3, 0xff, 0xe3, 0xf9, 0xe7, 0xf9, 0xff, 0xff, 0xff, 0xff, 0xff, 0x9f, 0xff, 0xe1, 0xc9, 0xc9, 0xc1, 0x9c, 0xc9, 0xf9, 0xf3, 0xf3, 0x99, 0xf3, 0xff, 0xff, 0xff, 0xcf, 0xff, 0xe1, 0xc9, 0x80, 0xfc, 0xcc, 0xe3, 0xfc, 0xf9, 0xe7, 0xc3, 0xf3, 0xff, 0xff, 0xff, 0xe7, 0xff, 0xf3, 0xff, 0xc9, 0xe1, 0xe7, 0x91, 0xff, 0xf9, 0xe7, 0x00, 0xc0, 0xff, 0xc0, 0xff, 0xf3, 0xff, 0xf3, 0xff, 0x80, 0xcf, 0xf3, 0xc4, 0xff, 0xf9, 0xe7, 0xc3, 0xf3, 0xff, 0xff, 0xff, 0xf9, 0xff, 0xff, 0xff, 0xc9, 0xe0, 0x99, 0xcc, 0xff, 0xf3, 0xf3, 0x99, 0xf3, 0xf3, 0xff, 0xf3, 0xfc, 0xff, 0xf3, 0xff, 0xc9, 0xf3, 0x9c, 0x91, 0xff, 0xe7, 0xf9, 0xff, 0xff, 0xf3, 0xff, 0xf3, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf9, 0xff, 0xff, 0xff, 0xc1, 0xf3, 0xe1, 0xe1, 0xc7, 0xc0, 0xe3, 0xc0, 0xe1, 0xe1, 0xff, 0xff, 0xe7, 0xff, 0xf9, 0xe1, 0x9c, 0xf1, 0xcc, 0xcc, 0xc3, 0xfc, 0xf9, 0xcc, 0xcc, 0xcc, 0xf3, 0xf3, 0xf3, 0xff, 0xf3, 0xcc, 0x8c, 0xf3, 0xcf, 0xcf, 0xc9, 0xe0, 0xfc, 0xcf, 0xcc, 0xcc, 0xf3, 0xf3, 0xf9, 0xc0, 0xe7, 0xcf, 0x84, 0xf3, 0xe3, 0xe3, 0xcc, 0xcf, 0xe0, 0xe7, 0xe1, 0xc1, 0xff, 0xff, 0xfc, 0xff, 0xcf, 0xe7, 0x90, 0xf3, 0xf9, 0xcf, 0x80, 0xcf, 0xcc, 0xf3, 0xcc, 0xcf, 0xff, 0xff, 0xf9, 0xff, 0xe7, 0xf3, 0x98, 0xf3, 0xcc, 0xcc, 0xcf, 0xcc, 0xcc, 0xf3, 0xcc, 0xe7, 0xf3, 0xf3, 0xf3, 0xc0, 0xf3, 0xff, 0xc1, 0xc0, 0xc0, 0xe1, 0x87, 0xe1, 0xe1, 0xf3, 0xe1, 0xf1, 0xf3, 0xf3, 0xe7, 0xff, 0xf9, 0xf3, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf9, 0xff, 0xff, 0xff, 0xff, 0xc1, 0xf3, 0xc0, 0xc3, 0xe0, 0x80, 0x80, 0xc3, 0xcc, 0xe1, 0x87, 0x98, 0xf0, 0x9c, 0x9c, 0xe3, 0x9c, 0xe1, 0x99, 0x99, 0xc9, 0xb9, 0xb9, 0x99, 0xcc, 0xf3, 0xcf, 0x99, 0xf9, 0x88, 0x98, 0xc9, 0x84, 0xcc, 0x99, 0xfc, 0x99, 0xe9, 0xe9, 0xfc, 0xcc, 0xf3, 0xcf, 0xc9, 0xf9, 0x80, 0x90, 0x9c, 0x84, 0xcc, 0xc1, 0xfc, 0x99, 0xe1, 0xe1, 0xfc, 0xc0, 0xf3, 0xcf, 0xe1, 0xf9, 0x80, 0x84, 0x9c, 0x84, 0xc0, 0x99, 0xfc, 0x99, 0xe9, 0xe9, 0x8c, 0xcc, 0xf3, 0xcc, 0xc9, 0xb9, 0x94, 0x8c, 0x9c, 0xfc, 0xcc, 0x99, 0x99, 0xc9, 0xb9, 0xf9, 0x99, 0xcc, 0xf3, 0xcc, 0x99, 0x99, 0x9c, 0x9c, 0xc9, 0xe1, 0xcc, 0xc0, 0xc3, 0xe0, 0x80, 0xf0, 0x83, 0xcc, 0xe1, 0xe1, 0x98, 0x80, 0x9c, 0x9c, 0xe3, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0xe1, 0xc0, 0xe1, 0xc0, 0xcc, 0xcc, 0x9c, 0x9c, 0xcc, 0x80, 0xe1, 0xfc, 0xe1, 0xf7, 0xff, 0x99, 0xcc, 0x99, 0xcc, 0xd2, 0xcc, 0xcc, 0x9c, 0x9c, 0xcc, 0x9c, 0xf9, 0xf9, 0xe7, 0xe3, 0xff, 0x99, 0xcc, 0x99, 0xf8, 0xf3, 0xcc, 0xcc, 0x9c, 0xc9, 0xcc, 0xce, 0xf9, 0xf3, 0xe7, 0xc9, 0xff, 0xc1, 0xcc, 0xc1, 0xf1, 0xf3, 0xcc, 0xcc, 0x94, 0xe3, 0xe1, 0xe7, 0xf9, 0xe7, 0xe7, 0x9c, 0xff, 0xf9, 0xc4, 0xc9, 0xc7, 0xf3, 0xcc, 0xcc, 0x80, 0xe3, 0xf3, 0xb3, 0xf9, 0xcf, 0xe7, 0xff, 0xff, 0xf9, 0xe1, 0x99, 0xcc, 0xf3, 0xcc, 0xe1, 0x88, 0xc9, 0xf3, 0x99, 0xf9, 0x9f, 0xe7, 0xff, 0xff, 0xf0, 0xc7, 0x98, 0xe1, 0xe1, 0xc0, 0xf3, 0x9c, 0x9c, 0xe1, 0x80, 0xe1, 0xbf, 0xe1, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0xf3, 0xff, 0xf8, 0xff, 0xc7, 0xff, 0xe3, 0xff, 0xf8, 0xf3, 0xcf, 0xf8, 0xf1, 0xff, 0xff, 0xff, 0xf3, 0xff, 0xf9, 0xff, 0xcf, 0xff, 0xc9, 0xff, 0xf9, 0xff, 0xff, 0xf9, 0xf3, 0xff, 0xff, 0xff, 0xe7, 0xe1, 0xf9, 0xe1, 0xcf, 0xe1, 0xf9, 0x91, 0xc9, 0xf1, 0xcf, 0x99, 0xf3, 0xcc, 0xe0, 0xe1, 0xff, 0xcf, 0xc1, 0xcc, 0xc1, 0xcc, 0xf0, 0xcc, 0x91, 0xf3, 0xcf, 0xc9, 0xf3, 0x80, 0xcc, 0xcc, 0xff, 0xc1, 0x99, 0xfc, 0xcc, 0xc0, 0xf9, 0xcc, 0x99, 0xf3, 0xcf, 0xe1, 0xf3, 0x80, 0xcc, 0xcc, 0xff, 0xcc, 0x99, 0xcc, 0xcc, 0xfc, 0xf9, 0xc1, 0x99, 0xf3, 0xcc, 0xc9, 0xf3, 0x94, 0xcc, 0xcc, 0xff, 0x91, 0xc4, 0xe1, 0x91, 0xe1, 0xf0, 0xcf, 0x98, 0xe1, 0xcc, 0x98, 0xe1, 0x9c, 0xcc, 0xe1, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe0, 0xff, 0xff, 0xe1, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf7, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc7, 0xe7, 0xf8, 0x91, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf3, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf3, 0xe7, 0xf3, 0xc4, 0xf7, 0xc4, 0x91, 0xc4, 0xc1, 0xc1, 0xcc, 0xcc, 0x9c, 0x9c, 0xcc, 0xc0, 0xf3, 0xe7, 0xf3, 0xff, 0xe3, 0x99, 0xcc, 0x91, 0xfc, 0xf3, 0xcc, 0xcc, 0x94, 0xc9, 0xcc, 0xe6, 0xf8, 0xff, 0xc7, 0xff, 0xc9, 0x99, 0xcc, 0x99, 0xe1, 0xf3, 0xcc, 0xcc, 0x80, 0xe3, 0xcc, 0xf3, 0xf3, 0xe7, 0xf3, 0xff, 0x9c, 0xc1, 0xc1, 0xf9, 0xcf, 0xd3, 0xcc, 0xe1, 0x80, 0xc9, 0xc1, 0xd9, 0xf3, 0xe7, 0xf3, 0xff, 0x9c, 0xf9, 0xcf, 0xf0, 0xe0, 0xe7, 0x91, 0xf3, 0xc9, 0x9c, 0xcf, 0xc0, 0xc7, 0xe7, 0xf8, 0xff, 0x80, 0xf0, 0x87, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
da1909d4c6fbe1c9c25868a49df07000d2d1cfb9
5d814ca12e2efdab3475870f836e182dd4abaf7f
/src/tms/backends/common.h
cc69e7899c8bc0a80333f08a7f9c1acb4cee2173
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Bithack/principia
dc5eb36f3ccc5c525c5a3f352463d0373bdbfc48
789b7090970ed62e10afa35d6631fb1c86fa9893
refs/heads/master
2023-09-04T02:58:59.499137
2023-09-03T21:05:15
2023-09-03T21:05:15
55,718,601
211
25
NOASSERTION
2023-09-04T17:26:19
2016-04-07T18:34:03
C
UTF-8
C
false
false
937
h
common.h
// This file contains common snippets shared across backends #define CUTE_ASCII_ART \ tms_progressf( \ " _ _ _ \n" \ " _ __ _ __(_)_ __ ___(_)_ __ (_) __ _ \n" \ "| '_ \\| '__| | '_ \\ / __| | '_ \\| |/ _` |\n" \ "| |_) | | | | | | | (__| | |_) | | (_| |\n" \ "| .__/|_| |_|_| |_|\\___|_| .__/|_|\\__,_|\n" \ "|_| |_| \n" \ "Version: %d. " __DATE__ "/" __TIME__ "\n", PRINCIPIA_VERSION_CODE); #define RESIZE_WINDOW \ tms_infof("Window %d resized to %dx%d", \ ev.window.windowID, ev.window.data1, \ ev.window.data2); \ int w = ev.window.data1; \ int h = ev.window.data2; \ \ if (w < 64) w = 64; \ if (h < 64) h = 64; \ \ _tms.window_width = _tms.opengl_width = w; \ _tms.window_height = _tms.opengl_height = h; \ \ SDL_SetWindowSize(_window, _tms.window_width, _tms.window_height); \ \ tproject_window_size_changed();
5aa6fb153a3afd64c4c64bdd96e304404fa277a8
a5f3b0001cdb692aeffc444a16f79a0c4422b9d0
/main/rsc/source/rscpp/cpp2.c
77dbaaaa958d773c89302c5cfe6707b29b89a8db
[ "Apache-2.0", "CPL-1.0", "bzip2-1.0.6", "LicenseRef-scancode-other-permissive", "Zlib", "LZMA-exception", "LGPL-2.0-or-later", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-philippe-de-muyter", "OFL-1.1", "LGPL-2.1-only", "MPL-1.1", "X11", "LGPL-2.1-or-later", "GPL-2.0-only", "OpenSSL", "LicenseRef-scancode-cpl-0.5", "GPL-1.0-or-later", "NPL-1.1", "MIT", "MPL-2.0", "LicenseRef-scancode-other-copyleft", "LicenseRef-scancode-unknown-license-reference", "MPL-1.0", "LicenseRef-scancode-openssl", "LicenseRef-scancode-ssleay-windows", "BSL-1.0", "LicenseRef-scancode-docbook", "LicenseRef-scancode-mit-old-style", "Python-2.0", "BSD-3-Clause", "IJG", "LicenseRef-scancode-warranty-disclaimer", "GPL-2.0-or-later", "LGPL-2.0-only", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown", "BSD-2-Clause", "Autoconf-exception-generic", "PSF-2.0", "NTP", "LicenseRef-scancode-python-cwi", "Afmparse", "W3C", "W3C-19980720", "curl", "LicenseRef-scancode-x11-xconsortium-veillard", "Bitstream-Vera", "HPND-sell-variant", "ICU" ]
permissive
apache/openoffice
b9518e36d784898c6c2ea3ebd44458a5e47825bb
681286523c50f34f13f05f7b87ce0c70e28295de
refs/heads/trunk
2023-08-30T15:25:48.357535
2023-08-28T19:50:26
2023-08-28T19:50:26
14,357,669
907
379
Apache-2.0
2023-08-16T20:49:37
2013-11-13T08:00:13
C++
UTF-8
C
false
false
22,153
c
cpp2.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 <stdio.h> #include <ctype.h> #include "cppdef.h" #include "cpp.h" #if HOST == SYS_VMS /* * Include the rms stuff. (We can't just include rms.h as it uses the * VaxC-specific library include syntax that Decus CPP doesn't support. * By including things by hand, we can CPP ourself.) */ #include <nam.h> #include <fab.h> #include <rab.h> #include <rmsdef.h> #endif /* * Generate (by hand-inspection) a set of unique values for each control * operator. Note that this is not guaranteed to work for non-Ascii * machines. CPP won't compile if there are hash conflicts. */ #define L_assert ('a' + ('s' << 1)) #define L_define ('d' + ('f' << 1)) #define L_elif ('e' + ('i' << 1)) #define L_else ('e' + ('s' << 1)) #define L_endif ('e' + ('d' << 1)) #define L_if ('i' + (EOS << 1)) #define L_ifdef ('i' + ('d' << 1)) #define L_ifndef ('i' + ('n' << 1)) #define L_include ('i' + ('c' << 1)) #define L_line ('l' + ('n' << 1)) #define L_nogood (EOS + (EOS << 1)) /* To catch #i */ #define L_pragma ('p' + ('a' << 1)) #define L_undef ('u' + ('d' << 1)) #define L_error ('e' + ('r' << 1)) /* BP 5.3.92, #error */ #define MAXLINE 80 /* BP 5.3.92, #error */ #if OSL_DEBUG_LEVEL > 1 #define L_debug ('d' + ('b' << 1)) /* #debug */ #define L_nodebug ('n' + ('d' << 1)) /* #nodebug */ #endif void InitCpp2() { } int control(int counter) /* * Process #control lines. Simple commands are processed inline, * while complex commands have their own subroutines. * * The counter is used to force out a newline before #line, and * #pragma commands. This prevents these commands from ending up at * the end of the previous line if cpp is invoked with the -C option. */ { register int c; register char *tp; register int hash; char *ep; c = skipws(); if (c == '\n' || c == EOF_CHAR) return (counter + 1); if (!isdigit(c)) scanid(c); /* Get #word to token[] */ else { unget(); /* Hack -- allow #123 as a */ strcpy(token, "line"); /* synonym for #line 123 */ } hash = (token[1] == EOS) ? L_nogood : (token[0] + (token[2] << 1)); switch (hash) { case L_assert: tp = "assert"; break; case L_define: tp = "define"; break; case L_elif: tp = "elif"; break; case L_else: tp = "else"; break; case L_endif: tp = "endif"; break; case L_if: tp = "if"; break; case L_ifdef: tp = "ifdef"; break; case L_ifndef: tp = "ifndef"; break; case L_include: tp = "include"; break; case L_line: tp = "line"; break; case L_pragma: tp = "pragma"; break; case L_undef: tp = "undef"; break; case L_error: tp = "error"; break; #if OSL_DEBUG_LEVEL > 1 case L_debug: tp = "debug"; break; case L_nodebug: tp = "nodebug"; break; #endif default: hash = L_nogood; case L_nogood: tp = ""; break; } if (!streq(tp, token)) hash = L_nogood; /* * hash is set to a unique value corresponding to the * control keyword (or L_nogood if we think it's nonsense). */ if (infile->fp == NULL) cwarn("Control line \"%s\" within macro expansion", token); if (!compiling) { /* Not compiling now */ switch (hash) { case L_if: /* These can't turn */ case L_ifdef: /* compilation on, but */ case L_ifndef: /* we must nest #if's */ if (++ifptr >= &ifstack[BLK_NEST]) goto if_nest_err; *ifptr = 0; /* !WAS_COMPILING */ case L_line: /* Many */ /* * Are pragma's always processed? */ case L_pragma: /* options */ case L_include: /* are uninteresting */ case L_define: /* if we */ case L_undef: /* aren't */ case L_assert: /* compiling. */ case L_error: /* BP 5.3.92, #error */ dump_line: skipnl(); /* Ignore rest of line */ return (counter + 1); } } /* * Make sure that #line and #pragma are output on a fresh line. */ if (counter > 0 && (hash == L_line || hash == L_pragma)) { PUTCHAR('\n'); counter--; } switch (hash) { case L_line: /* * Parse the line to update the line number and "progname" * field and line number for the next input line. * Set wrongline to force it out later. */ c = skipws(); workp = work; /* Save name in work */ while (c != '\n' && c != EOF_CHAR) { save(c); c = get(); } unget(); save(EOS); /* * Split #line argument into <line-number> and <name> * We subtract 1 as we want the number of the next line. */ line = atoi(work) - 1; /* Reset line number */ for (tp = work; isdigit(*tp) || type[(int)*tp] == SPA; tp++) ; /* Skip over digits */ if (*tp != EOS) { /* Got a filename, so: */ if (*tp == '"' && (ep = strrchr(tp + 1, '"')) != NULL) { tp++; /* Skip over left quote */ *ep = EOS; /* And ignore right one */ } if (infile->progname != NULL) /* Give up the old name */ free(infile->progname); /* if it's allocated. */ infile->progname = savestring(tp); } wrongline = TRUE; /* Force output later */ break; case L_include: doinclude(); break; case L_define: dodefine(); break; case L_undef: doundef(); break; case L_else: if (ifptr == &ifstack[0]) goto nest_err; else if ((*ifptr & ELSE_SEEN) != 0) goto else_seen_err; *ifptr |= ELSE_SEEN; if ((*ifptr & WAS_COMPILING) != 0) { if (compiling || (*ifptr & TRUE_SEEN) != 0) compiling = FALSE; else { compiling = TRUE; } } break; case L_elif: if (ifptr == &ifstack[0]) goto nest_err; else if ((*ifptr & ELSE_SEEN) != 0) { else_seen_err: cerror("#%s may not follow #else", token); goto dump_line; } if ((*ifptr & (WAS_COMPILING | TRUE_SEEN)) != WAS_COMPILING) { compiling = FALSE; /* Done compiling stuff */ goto dump_line; /* Skip this clause */ } doif(L_if); break; case L_if: case L_ifdef: case L_ifndef: if (++ifptr >= &ifstack[BLK_NEST]) if_nest_err: cfatal("Too many nested #%s statements", token); *ifptr = WAS_COMPILING; doif(hash); break; case L_endif: if (ifptr == &ifstack[0]) { nest_err: cerror("#%s must be in an #if", token); goto dump_line; } if (!compiling && (*ifptr & WAS_COMPILING) != 0) wrongline = TRUE; compiling = ((*ifptr & WAS_COMPILING) != 0); --ifptr; break; case L_assert: if (eval() == 0) cerror("Preprocessor assertion failure", NULLST); break; case L_pragma: /* * #pragma is provided to pass "options" to later * passes of the compiler. cpp doesn't have any yet. */ fprintf( pCppOut, "#pragma "); while ((c = get()) != '\n' && c != EOF_CHAR) cput(c); unget(); break; #if OSL_DEBUG_LEVEL > 1 case L_debug: if (debug == 0) dumpdef("debug set on"); debug++; break; case L_nodebug: debug--; break; #endif case L_error: /* BP 5.3.92, #error */ { fprintf( pCppOut, "cpp: line %u, Error directive: ", line ); while ((c = get()) != '\n' && c != EOF_CHAR) cput(c); fprintf( pCppOut, "\n" ); exit( 1 ); break; } default: /* * Undefined #control keyword. * Note: the correct behavior may be to warn and * pass the line to a subsequent compiler pass. * This would allow #asm or similar extensions. */ cerror("Illegal # command \"%s\"", token); break; } if (hash != L_include) { #if OLD_PREPROCESSOR /* * Ignore the rest of the #control line so you can write * #if foo * #endif foo */ goto dump_line; /* Take common exit */ #else if (skipws() != '\n') { cwarn("Unexpected text in #control line ignored", NULLST); skipnl(); } #endif } return (counter + 1); } FILE_LOCAL void doif(int hash) /* * Process an #if, #ifdef, or #ifndef. The latter two are straightforward, * while #if needs a subroutine of its own to evaluate the expression. * * doif() is called only if compiling is TRUE. If false, compilation * is always suppressed, so we don't need to evaluate anything. This * suppresses unnecessary warnings. */ { register int c; register int found; if ((c = skipws()) == '\n' || c == EOF_CHAR) { unget(); goto badif; } if (hash == L_if) { unget(); found = (eval() != 0); /* Evaluate expr, != 0 is TRUE */ hash = L_ifdef; /* #if is now like #ifdef */ } else { if (type[c] != LET) /* Next non-blank isn't letter */ goto badif; /* ... is an error */ found = (lookid(c) != NULL); /* Look for it in symbol table */ } if (found == (hash == L_ifdef)) { compiling = TRUE; *ifptr |= TRUE_SEEN; } else { compiling = FALSE; } return; badif: cerror("#if, #ifdef, or #ifndef without an argument", NULLST); #if !OLD_PREPROCESSOR skipnl(); /* Prevent an extra */ unget(); /* Error message */ #endif return; } FILE_LOCAL void doinclude() /* * Process the #include control line. * There are three variations: * #include "file" search somewhere relative to the * current source file, if not found, * treat as #include <file>. * #include <file> Search in an implementation-dependent * list of places. * #include token Expand the token, it must be one of * "file" or <file>, process as such. * * Note: the November 12 draft forbids '>' in the #include <file> format. * This restriction is unnecessary and not implemented. */ { register int c; register int delim; #if HOST == SYS_VMS char def_filename[NAM$C_MAXRSS + 1]; #endif delim = macroid(skipws()); if (delim != '<' && delim != '"') goto incerr; if (delim == '<') delim = '>'; workp = work; instring = TRUE; /* Accept all characters */ #ifdef CONTROL_COMMENTS_NOT_ALLOWED while ((c = get()) != '\n' && c != EOF_CHAR) save(c); /* Put it away. */ unget(); /* Force nl after includee */ /* * The draft is unclear if the following should be done. */ while (--workp >= work && *workp == ' ') ; /* Trim blanks from filename */ if (*workp != delim) goto incerr; #else while ((c = get()) != delim && c != EOF_CHAR) save(c); #endif *workp = EOS; /* Terminate filename */ instring = FALSE; #if HOST == SYS_VMS /* * Assume the default .h filetype. */ if (!vmsparse(work, ".H", def_filename)) { perror(work); /* Oops. */ goto incerr; } else if (openinclude(def_filename, (delim == '"'))) return; #else if (openinclude(work, (delim == '"'))) return; #endif /* * No sense continuing if #include file isn't there. */ cfatal("Cannot open include file \"%s\"", work); incerr: cerror("#include syntax error", NULLST); return; } FILE_LOCAL int openinclude(char* filename, int searchlocal) /* * Actually open an include file. This routine is only called from * doinclude() above, but was written as a separate subroutine for * programmer convenience. It searches the list of directories * and actually opens the file, linking it into the list of * active files. Returns TRUE if the file was opened, FALSE * if openinclude() fails. No error message is printed. */ { register char **incptr; #if HOST == SYS_VMS #if NFWORK < (NAM$C_MAXRSS + 1) << error, NFWORK is not greater than NAM$C_MAXRSS >> #endif #endif char tmpname[NFWORK]; /* Filename work area */ if (searchlocal) { /* * Look in local directory first */ #if HOST == SYS_UNIX /* * Try to open filename relative to the directory of the current * source file (as opposed to the current directory). (ARF, SCK). */ if (filename[0] != '/' && hasdirectory(infile->filename, tmpname)) strcat(tmpname, filename); else { strcpy(tmpname, filename); } #else if (!hasdirectory(filename, tmpname) && hasdirectory(infile->filename, tmpname)) strcat(tmpname, filename); else { strcpy(tmpname, filename); } #endif if (openfile(tmpname)) return (TRUE); } /* * Look in any directories specified by -I command line * arguments, then in the builtin search list. */ for (incptr = incdir; incptr < incend; incptr++) { if (strlen(*incptr) + strlen(filename) >= (NFWORK - 1)) cfatal("Filename work buffer overflow", NULLST); else { #if HOST == SYS_UNIX if (filename[0] == '/') strcpy(tmpname, filename); else { sprintf(tmpname, "%s/%s", *incptr, filename); } #elif HOST == SYS_UNKNOWN if (filename[0] == '\\') strcpy(tmpname, filename); else { sprintf(tmpname, "%s\\%s", *incptr, filename); } #else if (!hasdirectory(filename, tmpname)) sprintf(tmpname, "%s%s", *incptr, filename); #endif if (openfile(tmpname)) return (TRUE); } } return (FALSE); } FILE_LOCAL int hasdirectory(char* source, char* result) /* * If a device or directory is found in the source filename string, the * node/device/directory part of the string is copied to result and * hasdirectory returns TRUE. Else, nothing is copied and it returns FALSE. */ { #if HOST == SYS_UNIX register char *tp; if ((tp = strrchr(source, '/')) == NULL) return (FALSE); else { strncpy(result, source, tp - source + 1); result[tp - source + 1] = EOS; return (TRUE); } #else #if HOST == SYS_VMS if (vmsparse(source, NULLST, result) && result[0] != EOS) return (TRUE); else { return (FALSE); } #else /* * Random DEC operating system (RSX, RT11, RSTS/E) */ register char *tp; if ((tp = strrchr(source, ']')) == NULL && (tp = strrchr(source, ':')) == NULL) return (FALSE); else { strncpy(result, source, tp - source + 1); result[tp - source + 1] = EOS; return (TRUE); } #endif #endif } #if HOST == SYS_VMS /* * EXP_DEV is set if a device was specified, EXP_DIR if a directory * is specified. (Both set indicate a file-logical, but EXP_DEV * would be set by itself if you are reading, say, SYS$INPUT:) */ #define DEVDIR (NAM$M_EXP_DEV | NAM$M_EXP_DIR) FILE_LOCAL int vmsparse(source, defstring, result) char *source; char *defstring; /* non-NULL -> default string. */ char *result; /* Size is at least NAM$C_MAXRSS + 1 */ /* * Parse the source string, applying the default (properly, using * the system parse routine), storing it in result. * TRUE if it parsed, FALSE on error. * * If defstring is NULL, there are no defaults and result gets * (just) the node::[directory] part of the string (possibly "") */ { struct FAB fab = cc$rms_fab; /* File access block */ struct NAM nam = cc$rms_nam; /* File name block */ char fullname[NAM$C_MAXRSS + 1]; register char *rp; /* Result pointer */ fab.fab$l_nam = &nam; /* fab -> nam */ fab.fab$l_fna = source; /* Source filename */ fab.fab$b_fns = strlen(source); /* Size of source */ fab.fab$l_dna = defstring; /* Default string */ if (defstring != NULLST) fab.fab$b_dns = strlen(defstring); /* Size of default */ nam.nam$l_esa = fullname; /* Expanded filename */ nam.nam$b_ess = NAM$C_MAXRSS; /* Expanded name size */ if (sys$parse(&fab) == RMS$_NORMAL) { /* Parse away */ fullname[nam.nam$b_esl] = EOS; /* Terminate string */ result[0] = EOS; /* Just in case */ rp = &result[0]; /* * Remove stuff added implicitly, accepting node names and * dev:[directory] strings (but not process-permanent files). */ if ((nam.nam$l_fnb & NAM$M_PPF) == 0) { if ((nam.nam$l_fnb & NAM$M_NODE) != 0) { strncpy(result, nam.nam$l_node, nam.nam$b_node); rp += nam.nam$b_node; *rp = EOS; } if ((nam.nam$l_fnb & DEVDIR) == DEVDIR) { strncpy(rp, nam.nam$l_dev, nam.nam$b_dev + nam.nam$b_dir); rp += nam.nam$b_dev + nam.nam$b_dir; *rp = EOS; } } if (defstring != NULLST) { strncpy(rp, nam.nam$l_name, nam.nam$b_name + nam.nam$b_type); rp += nam.nam$b_name + nam.nam$b_type; *rp = EOS; if ((nam.nam$l_fnb & NAM$M_EXP_VER) != 0) { strncpy(rp, nam.nam$l_ver, nam.nam$b_ver); rp[nam.nam$b_ver] = EOS; } } return (TRUE); } return (FALSE); } #endif
8095f6fb1d50df6ba2b828552f455419387713db
fdbb74a95924e2677466614f6ab6e2bb13b2a95a
/third_party/chibicc/parse.c
8c1c98e9a8ea2edcdbfda276f8bdb08941f1ca94
[ "MIT", "LicenseRef-scancode-free-unknown", "ISC" ]
permissive
jart/cosmopolitan
fb11b5658939023977060a7c6c71a74093d9cb44
0d748ad58e1063dd1f8560f18a0c75293b9415b7
refs/heads/master
2023-09-06T09:17:29.303607
2023-09-02T03:49:13
2023-09-02T03:50:18
272,457,606
11,887
435
ISC
2023-09-14T17:47:58
2020-06-15T14:16:13
C
UTF-8
C
false
false
121,351
c
parse.c
// This file contains a recursive descent parser for C. // // Most functions in this file are named after the symbols they are // supposed to read from an input token list. For example, stmt() is // responsible for reading a statement from a token list. The function // then construct an AST node representing a statement. // // Each function conceptually returns two values, an AST node and // remaining part of the input tokens. Since C doesn't support // multiple return values, the remaining tokens are returned to the // caller via a pointer argument. // // Input tokens are represented by a linked list. Unlike many recursive // descent parsers, we don't have the notion of the "input token stream". // Most parsing functions don't change the global state of the parser. // So it is very easy to lookahead arbitrary number of tokens in this // parser. #include "libc/dce.h" #include "libc/intrin/asan.internal.h" #include "libc/log/libfatal.internal.h" #include "libc/log/log.h" #include "libc/mem/mem.h" #include "libc/nexgen32e/ffs.h" #include "libc/stdio/stdio.h" #include "libc/testlib/testlib.h" #include "libc/x/xasprintf.h" #include "third_party/chibicc/chibicc.h" #include "third_party/chibicc/kw.h" #define IMPLICIT_FUNCTIONS typedef struct InitDesg InitDesg; typedef struct Initializer Initializer; typedef struct Scope Scope; // Scope for local variables, global variables, typedefs // or enum constants typedef struct { Obj *var; Type *type_def; Type *enum_ty; int enum_val; } VarScope; // Represents a block scope. struct Scope { Scope *next; // C has two block scopes; one is for variables/typedefs and // the other is for struct/union/enum tags. HashMap vars; HashMap tags; }; // Variable attributes such as typedef or extern. typedef struct { bool is_typedef; bool is_static; bool is_extern; bool is_inline; bool is_tls; bool is_weak; bool is_ms_abi; bool is_aligned; bool is_noreturn; bool is_destructor; bool is_constructor; bool is_externally_visible; bool is_no_instrument_function; bool is_force_align_arg_pointer; bool is_no_caller_saved_registers; int align; char *section; char *visibility; } VarAttr; // This struct represents a variable initializer. Since initializers // can be nested (e.g. `int x[2][2] = {{1, 2}, {3, 4}}`), this struct // is a tree data structure. struct Initializer { Initializer *next; Type *ty; Token *tok; bool is_flexible; // If it's not an aggregate type and has an initializer, // `expr` has an initialization expression. Node *expr; // If it's an initializer for an aggregate type (e.g. array or struct), // `children` has initializers for its children. Initializer **children; // Only one member can be initialized for a union. // `mem` is used to clarify which member is initialized. Member *mem; }; // For local variable initializer. struct InitDesg { InitDesg *next; int idx; Member *member; Obj *var; }; // All local variable instances created during parsing are // accumulated to this list. static Obj *locals; // Likewise, global variables are accumulated to this list. static Obj *globals; static Scope *scope = &(Scope){}; // Points to the function object the parser is currently parsing. static Obj *current_fn; // Lists of all goto statements and labels in the curent function. static Node *gotos; static Node *labels; // Current "goto" and "continue" jump targets. static char *brk_label; static char *cont_label; // Points to a node representing a switch if we are parsing // a switch statement. Otherwise, NULL. static Node *current_switch; static Obj *builtin_alloca; static Token *current_javadown; static Initializer *initializer(Token **, Token *, Type *, Type **); static Member *get_struct_member(Type *, Token *); static Node *binor(Token **, Token *); static Node *add(Token **, Token *); static Node *assign(Token **, Token *); static Node *binand(Token **, Token *); static Node *binxor(Token **, Token *); static Node *cast(Token **, Token *); static Node *compound_stmt(Token **, Token *); static Node *conditional(Token **, Token *); static Node *declaration(Token **, Token *, Type *, VarAttr *); static Node *equality(Token **, Token *); static Node *expr_stmt(Token **, Token *); static Node *funcall(Token **, Token *, Node *); static Node *logand(Token **, Token *); static Node *logor(Token **, Token *); static Node *lvar_initializer(Token **, Token *, Obj *); static Node *mul(Token **, Token *); static Node *new_add(Node *, Node *, Token *); static Node *new_sub(Node *, Node *, Token *); static Node *postfix(Token **, Token *); static Node *primary(Token **, Token *); static Node *relational(Token **, Token *); static Node *shift(Token **, Token *); static Node *stmt(Token **, Token *); static Node *unary(Token **, Token *); static Token *function(Token *, Type *, VarAttr *); static Token *global_variable(Token *, Type *, VarAttr *); static Token *parse_typedef(Token *, Type *); static Type *declarator(Token **, Token *, Type *); static Type *enum_specifier(Token **, Token *); static Type *struct_decl(Token **, Token *); static Type *type_suffix(Token **, Token *, Type *); static Type *typename(Token **, Token *); static Type *typeof_specifier(Token **, Token *); static Type *union_decl(Token **, Token *); static bool is_function(Token *); static bool is_typename(Token *); static double eval_double(Node *); static int64_t eval_rval(Node *, char ***); static void array_initializer2(Token **, Token *, Initializer *, int); static void gvar_initializer(Token **, Token *, Obj *); static void initializer2(Token **, Token *, Initializer *); static void struct_initializer2(Token **, Token *, Initializer *, Member *); static void enter_scope(void) { Scope *sc = calloc(1, sizeof(Scope)); sc->next = scope; scope = sc; } static void leave_scope(void) { scope = scope->next; } // Find a variable by name. static VarScope *find_var(Token *tok) { for (Scope *sc = scope; sc; sc = sc->next) { VarScope *sc2 = hashmap_get2(&sc->vars, tok->loc, tok->len); if (sc2) return sc2; } return NULL; } static Type *find_tag(Token *tok) { for (Scope *sc = scope; sc; sc = sc->next) { Type *ty = hashmap_get2(&sc->tags, tok->loc, tok->len); if (ty) return ty; } return NULL; } Node *new_node(NodeKind kind, Token *tok) { Node *node = alloc_node(); node->kind = kind; node->tok = tok; return node; } static Node *new_binary(NodeKind kind, Node *lhs, Node *rhs, Token *tok) { Node *node = new_node(kind, tok); node->lhs = lhs; node->rhs = rhs; return node; } static Node *new_unary(NodeKind kind, Node *expr, Token *tok) { Node *node = new_node(kind, tok); node->lhs = expr; return node; } static Node *new_num(int64_t val, Token *tok) { Node *node = new_node(ND_NUM, tok); node->val = val; return node; } static Node *new_int(int64_t val, Token *tok) { Node *node = new_num(val, tok); node->ty = ty_int; return node; } static Node *new_bool(int64_t val, Token *tok) { Node *node = new_num(val, tok); node->ty = ty_bool; return node; } static Node *new_long(int64_t val, Token *tok) { Node *node = new_num(val, tok); node->ty = ty_long; return node; } static Node *new_ulong(int64_t val, Token *tok) { Node *node = new_num(val, tok); node->ty = ty_ulong; return node; } static Node *new_var_node(Obj *var, Token *tok) { CHECK_NOTNULL(var); Node *node = new_node(ND_VAR, tok); node->var = var; return node; } static Node *new_vla_ptr(Obj *var, Token *tok) { Node *node = new_node(ND_VLA_PTR, tok); node->var = var; return node; } Node *new_cast(Node *expr, Type *ty) { add_type(expr); Node *node = alloc_node(); node->kind = ND_CAST; node->tok = expr->tok; node->lhs = expr; node->ty = copy_type(ty); return node; } static VarScope *push_scope(char *name) { VarScope *sc = calloc(1, sizeof(VarScope)); hashmap_put(&scope->vars, name, sc); return sc; } static Initializer *new_initializer(Type *ty, bool is_flexible) { Initializer *init = calloc(1, sizeof(Initializer)); init->ty = ty; if (ty->kind == TY_ARRAY) { if (is_flexible && ty->size < 0) { init->is_flexible = true; return init; } init->children = calloc(ty->array_len, sizeof(Initializer *)); for (int i = 0; i < ty->array_len; i++) { init->children[i] = new_initializer(ty->base, false); } return init; } if (ty->kind == TY_STRUCT || ty->kind == TY_UNION) { // Count the number of struct members. int len = 0; for (Member *mem = ty->members; mem; mem = mem->next) len++; init->children = calloc(len, sizeof(Initializer *)); for (Member *mem = ty->members; mem; mem = mem->next) { if (is_flexible && ty->is_flexible && !mem->next) { Initializer *child = calloc(1, sizeof(Initializer)); child->ty = mem->ty; child->is_flexible = true; init->children[mem->idx] = child; } else { init->children[mem->idx] = new_initializer(mem->ty, false); } } return init; } return init; } static Obj *new_var(char *name, Type *ty) { Obj *var = alloc_obj(); var->name = name; var->ty = ty; var->align = ty->align; push_scope(name)->var = var; return var; } static Obj *new_lvar(char *name, Type *ty) { Obj *var = new_var(name, ty); var->is_local = true; var->next = locals; locals = var; return var; } static Obj *new_gvar(char *name, Type *ty) { Obj *var = new_var(name, ty); var->next = globals; var->is_static = true; var->is_definition = true; globals = var; return var; } static char *new_unique_name(void) { static int id = 0; return xasprintf(".L..%d", id++); } static Obj *new_anon_gvar(Type *ty) { return new_gvar(new_unique_name(), ty); } static Obj *new_string_literal(char *p, Type *ty) { Obj *var = new_anon_gvar(ty); var->init_data = p; var->is_string_literal = true; return var; } static char *get_ident(Token *tok) { if (tok->kind != TK_IDENT) { __die(); error_tok(tok, "expected an identifier"); } return strndup(tok->loc, tok->len); } static Type *find_typedef(Token *tok) { if (tok->kind == TK_IDENT) { VarScope *sc = find_var(tok); if (sc) return sc->type_def; } return NULL; } static void push_tag_scope(Token *tok, Type *ty) { hashmap_put2(&scope->tags, tok->loc, tok->len, ty); } // Consumes token if equal to STR or __STR__. static bool consume_attribute(Token **rest, Token *tok, char *name) { size_t n = strlen(name); if ((n == tok->len && !memcmp(tok->loc, name, n)) || (2 + n + 2 == tok->len && tok->loc[0] == '_' && tok->loc[1] == '_' && tok->loc[tok->len - 2] == '_' && tok->loc[tok->len - 1] == '_' && !memcmp(tok->loc + 2, name, n))) { *rest = tok->next; return true; } *rest = tok; return false; } static Token *attribute_list(Token *tok, void *arg, Token *(*f)(Token *, void *)) { while (CONSUME(&tok, tok, "__attribute__")) { tok = skip(tok, '('); tok = skip(tok, '('); bool first = true; while (!CONSUME(&tok, tok, ")")) { if (!first) tok = skip(tok, ','); first = false; tok = f(tok, arg); } tok = skip(tok, ')'); } return tok; } static Token *type_attributes(Token *tok, void *arg) { Type *ty = arg; if (consume_attribute(&tok, tok, "packed")) { ty->is_packed = true; return tok; } if (consume_attribute(&tok, tok, "ms_abi")) { ty->is_ms_abi = true; return tok; } if (consume_attribute(&tok, tok, "aligned")) { ty->is_aligned = true; if (CONSUME(&tok, tok, "(")) { Token *altok = tok; ty->align = const_expr(&tok, tok); if (popcnt(ty->align) != 1) error_tok(altok, "must be two power"); tok = skip(tok, ')'); } else { ty->align = 16; /* biggest alignment */ } return tok; } if (consume_attribute(&tok, tok, "vector_size")) { tok = skip(tok, '('); int vs = const_expr(&tok, tok); if (vs != 16) { error_tok(tok, "only vector_size 16 supported"); } if (vs != ty->vector_size) { ty->size = vs; ty->vector_size = vs; if (!ty->is_aligned) ty->align = vs; /* ty->base = ty; */ /* ty->array_len = vs / ty->size; */ } return skip(tok, ')'); } if (consume_attribute(&tok, tok, "warn_if_not_aligned")) { tok = skip(tok, '('); const_expr(&tok, tok); return skip(tok, ')'); } if (consume_attribute(&tok, tok, "deprecated") || consume_attribute(&tok, tok, "may_alias") || consume_attribute(&tok, tok, "unused")) { return tok; } if (consume_attribute(&tok, tok, "alloc_size") || consume_attribute(&tok, tok, "alloc_align")) { if (CONSUME(&tok, tok, "(")) { const_expr(&tok, tok); tok = skip(tok, ')'); } return tok; } error_tok(tok, "unknown type attribute"); } static Token *thing_attributes(Token *tok, void *arg) { VarAttr *attr = arg; if (consume_attribute(&tok, tok, "weak")) { attr->is_weak = true; return tok; } if (consume_attribute(&tok, tok, "hot")) { attr->section = ".text.likely"; return tok; } if (consume_attribute(&tok, tok, "cold")) { attr->section = ".text.unlikely"; return tok; } if (consume_attribute(&tok, tok, "section")) { tok = skip(tok, '('); attr->section = ConsumeStringLiteral(&tok, tok); return skip(tok, ')'); } if (consume_attribute(&tok, tok, "noreturn")) { attr->is_noreturn = true; return tok; } if (consume_attribute(&tok, tok, "always_inline")) { attr->is_inline = true; return tok; } if (consume_attribute(&tok, tok, "visibility")) { tok = skip(tok, '('); attr->visibility = ConsumeStringLiteral(&tok, tok); return skip(tok, ')'); } if (consume_attribute(&tok, tok, "externally_visible")) { attr->is_externally_visible = true; return tok; } if (consume_attribute(&tok, tok, "no_instrument_function")) { attr->is_no_instrument_function = true; return tok; } if (consume_attribute(&tok, tok, "force_align_arg_pointer")) { attr->is_force_align_arg_pointer = true; return tok; } if (consume_attribute(&tok, tok, "no_caller_saved_registers")) { attr->is_no_caller_saved_registers = true; return tok; } if (consume_attribute(&tok, tok, "ms_abi")) { attr->is_ms_abi = true; return tok; } if (consume_attribute(&tok, tok, "constructor")) { attr->is_constructor = true; if (CONSUME(&tok, tok, "(")) { const_expr(&tok, tok); tok = skip(tok, ')'); } return tok; } if (consume_attribute(&tok, tok, "destructor")) { attr->is_destructor = true; if (CONSUME(&tok, tok, "(")) { const_expr(&tok, tok); tok = skip(tok, ')'); } return tok; } if (consume_attribute(&tok, tok, "aligned")) { attr->is_aligned = true; if (CONSUME(&tok, tok, "(")) { Token *altok = tok; attr->align = const_expr(&tok, tok); if (popcnt(attr->align) != 1) error_tok(altok, "must be two power"); tok = skip(tok, ')'); } else { attr->align = 16; /* biggest alignment */ } return tok; } if (consume_attribute(&tok, tok, "warn_if_not_aligned")) { tok = skip(tok, '('); const_expr(&tok, tok); return skip(tok, ')'); } if (consume_attribute(&tok, tok, "error") || consume_attribute(&tok, tok, "warning")) { tok = skip(tok, '('); ConsumeStringLiteral(&tok, tok); return skip(tok, ')'); } if (consume_attribute(&tok, tok, "noinline") || consume_attribute(&tok, tok, "const") || consume_attribute(&tok, tok, "pure") || consume_attribute(&tok, tok, "dontclone") || consume_attribute(&tok, tok, "may_alias") || consume_attribute(&tok, tok, "warn_unused_result") || consume_attribute(&tok, tok, "flatten") || consume_attribute(&tok, tok, "leaf") || consume_attribute(&tok, tok, "no_reorder") || consume_attribute(&tok, tok, "dontthrow") || consume_attribute(&tok, tok, "optnone") || consume_attribute(&tok, tok, "returns_twice") || consume_attribute(&tok, tok, "nodebug") || consume_attribute(&tok, tok, "artificial") || consume_attribute(&tok, tok, "returns_nonnull") || consume_attribute(&tok, tok, "malloc") || consume_attribute(&tok, tok, "deprecated") || consume_attribute(&tok, tok, "gnu_inline") || consume_attribute(&tok, tok, "used") || consume_attribute(&tok, tok, "unused") || consume_attribute(&tok, tok, "no_icf") || consume_attribute(&tok, tok, "noipa") || consume_attribute(&tok, tok, "noplt") || consume_attribute(&tok, tok, "stack_protect") || consume_attribute(&tok, tok, "no_sanitize_address") || consume_attribute(&tok, tok, "no_sanitize_thread") || consume_attribute(&tok, tok, "no_split_stack") || consume_attribute(&tok, tok, "no_stack_limit") || consume_attribute(&tok, tok, "no_sanitize_undefined") || consume_attribute(&tok, tok, "no_profile_instrument_function")) { return tok; } if (consume_attribute(&tok, tok, "sentinel") || consume_attribute(&tok, tok, "nonnull") || consume_attribute(&tok, tok, "warning") || consume_attribute(&tok, tok, "optimize") || consume_attribute(&tok, tok, "target") || consume_attribute(&tok, tok, "assume_aligned") || consume_attribute(&tok, tok, "visibility") || consume_attribute(&tok, tok, "alloc_size") || consume_attribute(&tok, tok, "alloc_align")) { if (CONSUME(&tok, tok, "(")) { for (;;) { const_expr(&tok, tok); if (CONSUME(&tok, tok, ")")) break; tok = skip(tok, ','); } } return tok; } if (consume_attribute(&tok, tok, "format")) { tok = skip(tok, '('); consume_attribute(&tok, tok, "printf"); consume_attribute(&tok, tok, "scanf"); consume_attribute(&tok, tok, "strftime"); consume_attribute(&tok, tok, "strfmon"); consume_attribute(&tok, tok, "gnu_printf"); consume_attribute(&tok, tok, "gnu_scanf"); consume_attribute(&tok, tok, "gnu_strftime"); tok = skip(tok, ','); const_expr(&tok, tok); tok = skip(tok, ','); const_expr(&tok, tok); return skip(tok, ')'); } if (consume_attribute(&tok, tok, "format_arg")) { tok = skip(tok, '('); const_expr(&tok, tok); return skip(tok, ')'); } error_tok(tok, "unknown function attribute"); } // declspec = ("void" | "_Bool" | "char" | "short" | "int" | "long" // | "typedef" | "static" | "extern" | "inline" // | "_Thread_local" | "__thread" // | "signed" | "unsigned" // | struct-decl | union-decl | typedef-name // | enum-specifier | typeof-specifier // | "const" | "volatile" | "auto" | "register" | "restrict" // | "__restrict" | "__restrict__" | "_Noreturn")+ // // The order of typenames in a type-specifier doesn't matter. For // example, `int long static` means the same as `static long int`. // That can also be written as `static long` because you can omit // `int` if `long` or `short` are specified. However, something like // `char int` is not a valid type specifier. We have to accept only a // limited combinations of the typenames. // // In this function, we count the number of occurrences of each typename // while keeping the "current" type object that the typenames up // until that point represent. When we reach a non-typename token, // we returns the current type object. static Type *declspec(Token **rest, Token *tok, VarAttr *attr) { // We use a single integer as counters for all typenames. // For example, bits 0 and 1 represents how many times we saw the // keyword "void" so far. With this, we can use a switch statement // as you can see below. enum { VOID = 1 << 0, BOOL = 1 << 2, CHAR = 1 << 4, SHORT = 1 << 6, INT = 1 << 8, LONG = 1 << 10, FLOAT = 1 << 12, DOUBLE = 1 << 14, OTHER = 1 << 16, SIGNED = 1 << 17, UNSIGNED = 1 << 18, INT128 = 1 << 19, }; unsigned char kw; Type *ty = copy_type(ty_long); // [jart] use long as implicit type int counter = 0; bool is_const = false; bool is_atomic = false; while (is_typename(tok)) { if ((kw = GetKw(tok->loc, tok->len))) { // Handle storage class specifiers. if (kw == KW_TYPEDEF || kw == KW_STATIC || kw == KW_EXTERN || kw == KW_INLINE || kw == KW__THREAD_LOCAL) { if (!attr) error_tok(tok, "storage class specifier is not allowed in this context"); if (kw == KW_TYPEDEF) { attr->is_typedef = true; } else if (kw == KW_STATIC) { attr->is_static = true; } else if (kw == KW_EXTERN) { attr->is_extern = true; } else if (kw == KW_INLINE) { attr->is_inline = true; } else { attr->is_tls = true; } if (attr->is_typedef && attr->is_static + attr->is_extern + attr->is_inline + attr->is_tls > 1) { error_tok(tok, "typedef may not be used together with static," " extern, inline, __thread or _Thread_local"); } tok = tok->next; goto Continue; } if (kw == KW__NORETURN) { if (attr) attr->is_noreturn = true; tok = tok->next; goto Continue; } if (kw == KW_CONST) { is_const = true; tok = tok->next; goto Continue; } // These keywords are recognized but ignored. if (kw == KW_VOLATILE || kw == KW_AUTO || kw == KW_REGISTER || kw == KW_RESTRICT) { tok = tok->next; goto Continue; } if (kw == KW__ATOMIC) { tok = tok->next; if (EQUAL(tok, "(")) { ty = typename(&tok, tok->next); tok = skip(tok, ')'); } is_atomic = true; goto Continue; } if (kw == KW__ALIGNAS) { if (!attr) error_tok(tok, "_Alignas is not allowed in this context"); tok = skip(tok->next, '('); if (is_typename(tok)) { attr->align = typename(&tok, tok)->align; } else { Token *altok = tok; attr->align = const_expr(&tok, tok); if (popcnt(ty->align) != 1) { error_tok(altok, "_Alignas needs two power"); } } tok = skip(tok, ')'); goto Continue; } } // Handle user-defined types. Type *ty2 = find_typedef(tok); if (ty2 || kw == KW_STRUCT || kw == KW_UNION || kw == KW_ENUM || kw == KW_TYPEOF) { if (counter) break; if (kw == KW_STRUCT) { ty = struct_decl(&tok, tok->next); } else if (kw == KW_UNION) { ty = union_decl(&tok, tok->next); } else if (kw == KW_ENUM) { ty = enum_specifier(&tok, tok->next); } else if (kw == KW_TYPEOF) { ty = typeof_specifier(&tok, tok->next); } else { ty = ty2; tok = tok->next; } counter += OTHER; goto Continue; } // Handle built-in types. if (kw == KW_VOID) { counter += VOID; } else if (kw == KW__BOOL) { counter += BOOL; } else if (kw == KW_CHAR) { counter += CHAR; } else if (kw == KW_SHORT) { counter += SHORT; } else if (kw == KW_INT) { counter += INT; } else if (kw == KW_LONG) { counter += LONG; } else if (kw == KW___INT128) { counter += INT128; } else if (kw == KW_FLOAT) { counter += FLOAT; } else if (kw == KW_DOUBLE) { counter += DOUBLE; } else if (kw == KW_SIGNED) { counter |= SIGNED; } else if (kw == KW_UNSIGNED) { counter |= UNSIGNED; } else { UNREACHABLE(); } switch (counter) { case VOID: ty = copy_type(ty_void); break; case BOOL: ty = copy_type(ty_bool); break; case CHAR: case SIGNED + CHAR: ty = copy_type(ty_char); break; case UNSIGNED + CHAR: ty = copy_type(ty_uchar); break; case SHORT: case SHORT + INT: case SIGNED + SHORT: case SIGNED + SHORT + INT: ty = copy_type(ty_short); break; case UNSIGNED + SHORT: case UNSIGNED + SHORT + INT: ty = copy_type(ty_ushort); break; case INT: case SIGNED: case SIGNED + INT: ty = copy_type(ty_int); break; case UNSIGNED: case UNSIGNED + INT: ty = copy_type(ty_uint); break; case LONG: case LONG + INT: case LONG + LONG: case LONG + LONG + INT: case SIGNED + LONG: case SIGNED + LONG + INT: case SIGNED + LONG + LONG: case SIGNED + LONG + LONG + INT: ty = copy_type(ty_long); break; case UNSIGNED + LONG: case UNSIGNED + LONG + INT: case UNSIGNED + LONG + LONG: case UNSIGNED + LONG + LONG + INT: ty = copy_type(ty_ulong); break; case INT128: case SIGNED + INT128: ty = copy_type(ty_int128); break; case UNSIGNED + INT128: ty = copy_type(ty_uint128); break; case FLOAT: ty = copy_type(ty_float); break; case DOUBLE: ty = copy_type(ty_double); break; case LONG + DOUBLE: ty = copy_type(ty_ldouble); break; default: error_tok(tok, "invalid type"); } tok = tok->next; Continue: if (attr && attr->is_typedef) { tok = attribute_list(tok, ty, type_attributes); } else if (attr) { tok = attribute_list(tok, attr, thing_attributes); } } if (is_atomic) { ty = copy_type(ty); ty->is_atomic = true; } if (is_const) { ty = copy_type(ty); ty->is_const = true; } *rest = tok; return ty; } static Token *static_assertion(Token *tok) { char *msg; Token *start = tok; tok = skip(tok->next, '('); int64_t cond = const_expr(&tok, tok); if (CONSUME(&tok, tok, ",")) { msg = ConsumeStringLiteral(&tok, tok); } else { msg = "assertion failed"; } tok = skip(tok, ')'); tok = skip(tok, ';'); if (!cond) { error_tok(start, "%s", msg); } return tok; } // func-params = ("void" | param ("," param)* ("," "...")?)? ")" // param = declspec declarator static Type *func_params(Token **rest, Token *tok, Type *ty) { if (EQUAL(tok, "void") && EQUAL(tok->next, ")")) { *rest = tok->next->next; return func_type(ty); } Type head = {}; Type *cur = &head; bool is_variadic = false; enter_scope(); while (!EQUAL(tok, ")")) { if (cur != &head) tok = skip(tok, ','); if (EQUAL(tok, "...")) { is_variadic = true; tok = tok->next; skip(tok, ')'); break; } Type *ty2 = declspec(&tok, tok, NULL); ty2 = declarator(&tok, tok, ty2); Token *name = ty2->name; if (name) { new_lvar(strndup(name->loc, name->len), ty2); } if (ty2->kind == TY_ARRAY) { // "array of T" decays to "pointer to T" only in the parameter // context. For example, *argv[] is converted to **argv here. Type *ty3 = ty2; ty3 = pointer_to(ty2->base); ty3->name = name; ty3->array_len = ty2->array_len; ty3->is_static = ty2->is_static; ty3->is_restrict = ty2->is_restrict; ty2 = ty3; } else if (ty2->kind == TY_FUNC) { // Likewise, a function is converted to a pointer to a function // only in the parameter context. ty2 = pointer_to(ty2); ty2->name = name; } cur = cur->next = copy_type(ty2); } leave_scope(); if (cur == &head) is_variadic = true; ty = func_type(ty); ty->params = head.next; ty->is_variadic = is_variadic; *rest = tok->next; return ty; } // array-dimensions = ("static" | "restrict")* const-expr? "]" type-suffix static Type *array_dimensions(Token **rest, Token *tok, Type *ty) { Node *expr; bool is_static, is_restrict; is_static = false; is_restrict = false; for (;; tok = tok->next) { if (EQUAL(tok, "static")) { is_static = true; } else if (EQUAL(tok, "restrict")) { is_restrict = true; } else { break; } } if (EQUAL(tok, "]")) { ty = type_suffix(rest, tok->next, ty); ty = array_of(ty, -1); } else { expr = conditional(&tok, tok); tok = skip(tok, ']'); ty = type_suffix(rest, tok, ty); if (ty->kind == TY_VLA || !is_const_expr(expr)) return vla_of(ty, expr); ty = array_of(ty, eval(expr)); } ty->is_static = is_static; ty->is_restrict = is_restrict; return ty; } // type-suffix = "(" func-params // | "[" array-dimensions // | ε static Type *type_suffix(Token **rest, Token *tok, Type *ty) { if (EQUAL(tok, "(")) return func_params(rest, tok->next, ty); if (EQUAL(tok, "[")) return array_dimensions(rest, tok->next, ty); *rest = tok; return ty; } // pointers = ("*" ("const" | "volatile" | "restrict" | attribute)*)* static Type *pointers(Token **rest, Token *tok, Type *ty) { while (CONSUME(&tok, tok, "*")) { ty = pointer_to(ty); for (;;) { tok = attribute_list(tok, ty, type_attributes); if (EQUAL(tok, "const")) { ty->is_const = true; tok = tok->next; } else if (EQUAL(tok, "volatile")) { ty->is_volatile = true; tok = tok->next; } else if (EQUAL(tok, "restrict") || EQUAL(tok, "__restrict") || EQUAL(tok, "__restrict__")) { ty->is_restrict = true; tok = tok->next; } else { break; } } } *rest = tok; return ty; } // declarator = pointers ("(" ident ")" | "(" declarator ")" | ident) // type-suffix static Type *declarator(Token **rest, Token *tok, Type *ty) { ty = pointers(&tok, tok, ty); if (EQUAL(tok, "(")) { Token *start = tok; Type dummy = {}; declarator(&tok, start->next, &dummy); tok = skip(tok, ')'); ty = type_suffix(rest, tok, ty); ty = declarator(&tok, start->next, ty); return ty; } Token *name = NULL; Token *name_pos = tok; if (tok->kind == TK_IDENT) { name = tok; tok = tok->next; } ty = type_suffix(rest, tok, ty); ty->name = name; ty->name_pos = name_pos; return ty; } // abstract-declarator = pointers ("(" abstract-declarator ")")? type-suffix static Type *abstract_declarator(Token **rest, Token *tok, Type *ty) { ty = pointers(&tok, tok, ty); if (EQUAL(tok, "(")) { Token *start = tok; Type dummy = {}; abstract_declarator(&tok, start->next, &dummy); tok = skip(tok, ')'); ty = type_suffix(rest, tok, ty); return abstract_declarator(&tok, start->next, ty); } return type_suffix(rest, tok, ty); } // type-name = declspec abstract-declarator static Type *typename(Token **rest, Token *tok) { Type *ty = declspec(&tok, tok, NULL); return abstract_declarator(rest, tok, ty); } static bool is_end(Token *tok) { return EQUAL(tok, "}") || (EQUAL(tok, ",") && EQUAL(tok->next, "}")); } static bool consume_end(Token **rest, Token *tok) { if (EQUAL(tok, "}")) { *rest = tok->next; return true; } if (EQUAL(tok, ",") && EQUAL(tok->next, "}")) { *rest = tok->next->next; return true; } return false; } // enum-specifier = ident? "{" enum-list? "}" // | ident ("{" enum-list? "}")? // // enum-list = ident ("=" num)? ("," ident ("=" num)?)* ","? static Type *enum_specifier(Token **rest, Token *tok) { Type *ty = enum_type(); // Read a struct tag. Token *tag = NULL; if (tok->kind == TK_IDENT) { tag = tok; tok = tok->next; } if (tag && !EQUAL(tok, "{")) { Type *ty = find_tag(tag); if (!ty) error_tok(tag, "unknown enum type"); if (ty->kind != TY_ENUM) error_tok(tag, "not an enum tag"); *rest = tok; return ty; } ty->name = tag; tok = skip(tok, '{'); // Read an enum-list. int i = 0; int val = 0; while (!consume_end(rest, tok)) { if (i++ > 0) tok = skip(tok, ','); if (tok->kind == TK_JAVADOWN) { current_javadown = tok; tok = tok->next; } char *name = get_ident(tok); tok = tok->next; if (EQUAL(tok, "=")) val = const_expr(&tok, tok->next); VarScope *sc = push_scope(name); sc->enum_ty = ty; sc->enum_val = val++; } if (tag) push_tag_scope(tag, ty); return ty; } // typeof-specifier = "(" (expr | typename) ")" static Type *typeof_specifier(Token **rest, Token *tok) { tok = skip(tok, '('); Type *ty; if (is_typename(tok)) { ty = typename(&tok, tok); } else { Node *node = expr(&tok, tok); add_type(node); ty = node->ty; } *rest = skip(tok, ')'); return ty; } // Generate code for computing a VLA size. static Node *compute_vla_size(Type *ty, Token *tok) { Node *node = new_node(ND_NULL_EXPR, tok); if (ty->base) { node = new_binary(ND_COMMA, node, compute_vla_size(ty->base, tok), tok); } if (ty->kind != TY_VLA) return node; Node *base_sz; if (ty->base->kind == TY_VLA) { base_sz = new_var_node(ty->base->vla_size, tok); } else { base_sz = new_num(ty->base->size, tok); } ty->vla_size = new_lvar("", ty_ulong); Node *expr = new_binary(ND_ASSIGN, new_var_node(ty->vla_size, tok), new_binary(ND_MUL, ty->vla_len, base_sz, tok), tok); return new_binary(ND_COMMA, node, expr, tok); } static Node *new_alloca(Node *sz) { Node *node; node = new_unary(ND_FUNCALL, new_var_node(builtin_alloca, sz->tok), sz->tok); node->func_ty = builtin_alloca->ty; node->ty = builtin_alloca->ty->return_ty; node->args = sz; add_type(sz); return node; } // declaration = declspec (declarator ("=" expr)? // ("," declarator ("=" expr)?)*)? ";" static Node *declaration(Token **rest, Token *tok, Type *basety, VarAttr *attr) { Node head = {}; Node *cur = &head; int i = 0; while (!EQUAL(tok, ";")) { if (i++ > 0) tok = skip(tok, ','); Type *ty = declarator(&tok, tok, basety); if (ty->kind == TY_VOID) error_tok(tok, "variable declared void"); if (!ty->name) error_tok(ty->name_pos, "variable name omitted"); if (attr && attr->is_static) { // static local variable Obj *var = new_anon_gvar(ty); push_scope(get_ident(ty->name))->var = var; if (EQUAL(tok, "=")) gvar_initializer(&tok, tok->next, var); continue; } // Generate code for computing a VLA size. We need to do this // even if ty is not VLA because ty may be a pointer to VLA // (e.g. int (*foo)[n][m] where n and m are variables.) cur = cur->next = new_unary(ND_EXPR_STMT, compute_vla_size(ty, tok), tok); tok = attribute_list(tok, attr, thing_attributes); if (ty->kind == TY_VLA) { if (EQUAL(tok, "=")) error_tok(tok, "variable-sized object may not be initialized"); // Variable length arrays (VLAs) are translated to alloca() calls. // For example, `int x[n+2]` is translated to `tmp = n + 2, // x = alloca(tmp)`. Obj *var = new_lvar(get_ident(ty->name), ty); Token *tok = ty->name; Node *expr = new_binary(ND_ASSIGN, new_vla_ptr(var, tok), new_alloca(new_var_node(ty->vla_size, tok)), tok); cur = cur->next = new_unary(ND_EXPR_STMT, expr, tok); continue; } Obj *var = new_lvar(get_ident(ty->name), ty); if (attr && attr->align) var->align = attr->align; if (EQUAL(tok, "=")) { Node *expr = lvar_initializer(&tok, tok->next, var); cur = cur->next = new_unary(ND_EXPR_STMT, expr, tok); } if (var->ty->size < 0) error_tok(ty->name, "variable has incomplete type"); if (var->ty->kind == TY_VOID) error_tok(ty->name, "variable declared void"); } Node *node = new_node(ND_BLOCK, tok); node->body = head.next; *rest = tok->next; return node; } static Token *skip_excess_element(Token *tok) { if (EQUAL(tok, "{")) { tok = skip_excess_element(tok->next); return skip(tok, '}'); } assign(&tok, tok); return tok; } // string-initializer = string-literal static void string_initializer(Token **rest, Token *tok, Initializer *init) { if (init->is_flexible) { *init = *new_initializer(array_of(init->ty->base, tok->ty->array_len), false); } int len = MIN(init->ty->array_len, tok->ty->array_len); switch (init->ty->base->size) { case 1: { char *str = tok->str; for (int i = 0; i < len; i++) init->children[i]->expr = new_num(str[i], tok); break; } case 2: { uint16_t *str = (uint16_t *)tok->str; for (int i = 0; i < len; i++) init->children[i]->expr = new_num(str[i], tok); break; } case 4: { uint32_t *str = (uint32_t *)tok->str; for (int i = 0; i < len; i++) init->children[i]->expr = new_num(str[i], tok); break; } default: UNREACHABLE(); } *rest = tok->next; } // array-designator = "[" const-expr "]" // // C99 added the designated initializer to the language, which allows // programmers to move the "cursor" of an initializer to any element. // The syntax looks like this: // // int x[10] = { 1, 2, [5]=3, 4, 5, 6, 7 }; // // `[5]` moves the cursor to the 5th element, so the 5th element of x // is set to 3. Initialization then continues forward in order, so // 6th, 7th, 8th and 9th elements are initialized with 4, 5, 6 and 7, // respectively. Unspecified elements (in this case, 3rd and 4th // elements) are initialized with zero. // // Nesting is allowed, so the following initializer is valid: // // int x[5][10] = { [5][8]=1, 2, 3 }; // // It sets x[5][8], x[5][9] and x[6][0] to 1, 2 and 3, respectively. // // Use `.fieldname` to move the cursor for a struct initializer. E.g. // // struct { int a, b, c; } x = { .c=5 }; // // The above initializer sets x.c to 5. static void array_designator(Token **rest, Token *tok, Type *ty, int *begin, int *end) { *begin = const_expr(&tok, tok->next); if (*begin >= ty->array_len) error_tok(tok, "array designator index exceeds array bounds"); if (EQUAL(tok, "...")) { *end = const_expr(&tok, tok->next); if (*end >= ty->array_len) error_tok(tok, "array designator index exceeds array bounds"); if (*end < *begin) error_tok(tok, "array designator range [%d, %d] is empty", *begin, *end); } else { *end = *begin; } *rest = skip(tok, ']'); } // struct-designator = "." ident static Member *struct_designator(Token **rest, Token *tok, Type *ty) { Token *start = tok; tok = skip(tok, '.'); if (tok->kind == TK_JAVADOWN) { current_javadown = tok; tok = tok->next; } if (tok->kind != TK_IDENT) error_tok(tok, "expected a field designator"); for (Member *mem = ty->members; mem; mem = mem->next) { // Anonymous struct member if ((mem->ty->kind == TY_STRUCT || mem->ty->kind == TY_UNION) && !mem->name) { if (get_struct_member(mem->ty, tok)) { *rest = start; return mem; } continue; } // Regular struct member if (mem->name->len == tok->len && !strncmp(mem->name->loc, tok->loc, tok->len)) { *rest = tok->next; return mem; } } error_tok(tok, "struct has no such member"); } // designation = ("[" const-expr "]" | "." ident)* "="? initializer static void designation(Token **rest, Token *tok, Initializer *init) { if (EQUAL(tok, "[")) { if (init->ty->kind != TY_ARRAY) error_tok(tok, "array index in non-array initializer"); int begin, end; array_designator(&tok, tok, init->ty, &begin, &end); Token *tok2; for (int i = begin; i <= end; i++) designation(&tok2, tok, init->children[i]); array_initializer2(rest, tok2, init, begin + 1); return; } if (EQUAL(tok, ".") && init->ty->kind == TY_STRUCT) { Member *mem = struct_designator(&tok, tok, init->ty); designation(&tok, tok, init->children[mem->idx]); init->expr = NULL; struct_initializer2(rest, tok, init, mem->next); return; } if (EQUAL(tok, ".") && init->ty->kind == TY_UNION) { Member *mem = struct_designator(&tok, tok, init->ty); init->mem = mem; designation(rest, tok, init->children[mem->idx]); return; } if (EQUAL(tok, ".")) { error_tok(tok, "field name not in struct or union initializer"); } if (EQUAL(tok, "=")) tok = tok->next; initializer2(rest, tok, init); } // An array length can be omitted if an array has an initializer // (e.g. `int x[] = {1,2,3}`). If it's omitted, count the number // of initializer elements. static int count_array_init_elements(Token *tok, Type *ty) { bool first = true; Initializer *dummy = new_initializer(ty->base, true); int i = 0, max = 0; while (!consume_end(&tok, tok)) { if (!first) tok = skip(tok, ','); first = false; if (EQUAL(tok, "[")) { i = const_expr(&tok, tok->next); if (EQUAL(tok, "...")) i = const_expr(&tok, tok->next); tok = skip(tok, ']'); designation(&tok, tok, dummy); } else { initializer2(&tok, tok, dummy); } i++; max = MAX(max, i); } return max; } // array-initializer1 = "{" initializer ("," initializer)* ","? "}" static void array_initializer1(Token **rest, Token *tok, Initializer *init) { tok = skip(tok, '{'); if (init->is_flexible) { int len = count_array_init_elements(tok, init->ty); *init = *new_initializer(array_of(init->ty->base, len), false); } bool first = true; if (init->is_flexible) { int len = count_array_init_elements(tok, init->ty); *init = *new_initializer(array_of(init->ty->base, len), false); } for (int i = 0; !consume_end(rest, tok); i++) { if (!first) tok = skip(tok, ','); first = false; if (EQUAL(tok, "[")) { int begin, end; array_designator(&tok, tok, init->ty, &begin, &end); Token *tok2; for (int j = begin; j <= end; j++) designation(&tok2, tok, init->children[j]); tok = tok2; i = end; continue; } if (i < init->ty->array_len) { initializer2(&tok, tok, init->children[i]); } else { tok = skip_excess_element(tok); } } } // array-initializer2 = initializer (',' initializer)* static void array_initializer2(Token **rest, Token *tok, Initializer *init, int i) { if (init->is_flexible) { int len = count_array_init_elements(tok, init->ty); *init = *new_initializer(array_of(init->ty->base, len), false); } for (; i < init->ty->array_len && !is_end(tok); i++) { Token *start = tok; if (i > 0) tok = skip(tok, ','); if (EQUAL(tok, "[") || EQUAL(tok, ".")) { *rest = start; return; } initializer2(&tok, tok, init->children[i]); } *rest = tok; } // struct-initializer1 = "{" initializer ("," initializer)* ","? "}" static void struct_initializer1(Token **rest, Token *tok, Initializer *init) { tok = skip(tok, '{'); Member *mem = init->ty->members; bool first = true; while (!consume_end(rest, tok)) { if (!first) tok = skip(tok, ','); first = false; if (EQUAL(tok, ".")) { mem = struct_designator(&tok, tok, init->ty); designation(&tok, tok, init->children[mem->idx]); mem = mem->next; continue; } if (mem) { initializer2(&tok, tok, init->children[mem->idx]); mem = mem->next; } else { tok = skip_excess_element(tok); } } } // struct-initializer2 = initializer ("," initializer)* static void struct_initializer2(Token **rest, Token *tok, Initializer *init, Member *mem) { bool first = true; for (; mem && !is_end(tok); mem = mem->next) { Token *start = tok; if (!first) tok = skip(tok, ','); first = false; if (EQUAL(tok, "[") || EQUAL(tok, ".")) { *rest = start; return; } initializer2(&tok, tok, init->children[mem->idx]); } *rest = tok; } static void union_initializer(Token **rest, Token *tok, Initializer *init) { // Unlike structs, union initializers take only one initializer, // and that initializes the first union member by default. // You can initialize other member using a designated initializer. if (EQUAL(tok, "{") && EQUAL(tok->next, ".")) { Member *mem = struct_designator(&tok, tok->next, init->ty); init->mem = mem; designation(&tok, tok, init->children[mem->idx]); *rest = skip(tok, '}'); return; } init->mem = init->ty->members; if (EQUAL(tok, "{")) { initializer2(&tok, tok->next, init->children[0]); CONSUME(&tok, tok, ","); *rest = skip(tok, '}'); } else { initializer2(rest, tok, init->children[0]); } } // initializer = string-initializer | array-initializer // | struct-initializer | union-initializer // | assign static void initializer2(Token **rest, Token *tok, Initializer *init) { if (EQUAL(tok, "(") && init->ty->kind == TY_ARRAY && tok->next->kind == TK_STR) { /* XXX: Kludge so typeof("str") s = ("str"); macros work. */ initializer2(rest, tok->next, init); *rest = skip(*rest, ')'); return; } if (init->ty->kind == TY_ARRAY && tok->kind == TK_STR) { string_initializer(rest, tok, init); return; } if (init->ty->kind == TY_ARRAY) { if (EQUAL(tok, "{")) { array_initializer1(rest, tok, init); } else { array_initializer2(rest, tok, init, 0); } return; } if (init->ty->kind == TY_STRUCT) { if (EQUAL(tok, "{")) { struct_initializer1(rest, tok, init); return; } // A struct can be initialized with another struct. E.g. // `struct T x = y;` where y is a variable of type `struct T`. // Handle that case first. Node *expr = assign(rest, tok); add_type(expr); if (expr->ty->kind == TY_STRUCT) { init->expr = expr; return; } struct_initializer2(rest, tok, init, init->ty->members); return; } if (init->ty->kind == TY_UNION) { union_initializer(rest, tok, init); return; } if (EQUAL(tok, "{")) { // An initializer for a scalar variable can be surrounded by // braces. E.g. `int x = {3};`. Handle that case. initializer2(&tok, tok->next, init); *rest = skip(tok, '}'); return; } init->expr = assign(rest, tok); } static Type *copy_struct_type(Type *ty) { ty = copy_type(ty); Member head = {}; Member *cur = &head; for (Member *mem = ty->members; mem; mem = mem->next) { Member *m = calloc(1, sizeof(Member)); *m = *mem; cur = cur->next = m; } ty->members = head.next; return ty; } static Initializer *initializer(Token **rest, Token *tok, Type *ty, Type **new_ty) { Initializer *init = new_initializer(ty, true); initializer2(rest, tok, init); if ((ty->kind == TY_STRUCT || ty->kind == TY_UNION) && ty->is_flexible) { ty = copy_struct_type(ty); Member *mem = ty->members; while (mem->next) mem = mem->next; mem->ty = init->children[mem->idx]->ty; ty->size += mem->ty->size; *new_ty = ty; return init; } *new_ty = init->ty; return init; } static Node *init_desg_expr(InitDesg *desg, Token *tok) { if (desg->var) return new_var_node(desg->var, tok); if (desg->member) { Node *node = new_unary(ND_MEMBER, init_desg_expr(desg->next, tok), tok); node->member = desg->member; return node; } Node *lhs = init_desg_expr(desg->next, tok); Node *rhs = new_num(desg->idx, tok); return new_unary(ND_DEREF, new_add(lhs, rhs, tok), tok); } static Node *create_lvar_init(Initializer *init, Type *ty, InitDesg *desg, Token *tok) { if (ty->kind == TY_ARRAY) { Node *node = new_node(ND_NULL_EXPR, tok); for (int i = 0; i < ty->array_len; i++) { InitDesg desg2 = {desg, i}; Node *rhs = create_lvar_init(init->children[i], ty->base, &desg2, tok); node = new_binary(ND_COMMA, node, rhs, tok); } return node; } if (ty->kind == TY_STRUCT && !init->expr) { Node *node = new_node(ND_NULL_EXPR, tok); for (Member *mem = ty->members; mem; mem = mem->next) { InitDesg desg2 = {desg, 0, mem}; Node *rhs = create_lvar_init(init->children[mem->idx], mem->ty, &desg2, tok); node = new_binary(ND_COMMA, node, rhs, tok); } return node; } if (ty->kind == TY_UNION) { Member *mem = init->mem ? init->mem : ty->members; InitDesg desg2 = {desg, 0, mem}; return create_lvar_init(init->children[mem->idx], mem->ty, &desg2, tok); } if (!init->expr) return new_node(ND_NULL_EXPR, tok); Node *lhs = init_desg_expr(desg, tok); return new_binary(ND_ASSIGN, lhs, init->expr, tok); } // A variable definition with an initializer is a shorthand notation // for a variable definition followed by assignments. This function // generates assignment expressions for an initializer. For example, // `int x[2][2] = {{6, 7}, {8, 9}}` is converted to the following // expressions: // // x[0][0] = 6; // x[0][1] = 7; // x[1][0] = 8; // x[1][1] = 9; // static Node *lvar_initializer(Token **rest, Token *tok, Obj *var) { Initializer *init = initializer(rest, tok, var->ty, &var->ty); InitDesg desg = {NULL, 0, NULL, var}; // If a partial initializer list is given, the standard requires // that unspecified elements are set to 0. Here, we simply // zero-initialize the entire memory region of a variable before // initializing it with user-supplied values. Node *lhs = new_node(ND_MEMZERO, tok); lhs->var = var; Node *rhs = create_lvar_init(init, var->ty, &desg, tok); return new_binary(ND_COMMA, lhs, rhs, tok); } static uint64_t read_buf(char *buf, int sz) { if (sz == 1) return *buf; if (sz == 2) return *(uint16_t *)buf; if (sz == 4) return *(uint32_t *)buf; if (sz == 8) return *(uint64_t *)buf; UNREACHABLE(); } static void write_buf(char *buf, uint64_t val, int sz) { if (sz == 1) { *buf = val; } else if (sz == 2) { *(uint16_t *)buf = val; } else if (sz == 4) { *(uint32_t *)buf = val; } else if (sz == 8) { *(uint64_t *)buf = val; } else { UNREACHABLE(); } } static Relocation *write_gvar_data(Relocation *cur, Initializer *init, Type *ty, char *buf, int offset) { if (ty->kind == TY_ARRAY) { int sz = ty->base->size; for (int i = 0; i < ty->array_len; i++) cur = write_gvar_data(cur, init->children[i], ty->base, buf, offset + sz * i); return cur; } if (ty->kind == TY_STRUCT) { for (Member *mem = ty->members; mem; mem = mem->next) { if (mem->is_bitfield) { Node *expr = init->children[mem->idx]->expr; if (!expr) break; char *loc = buf + offset + mem->offset; uint64_t oldval = read_buf(loc, mem->ty->size); uint64_t newval = eval(expr); uint64_t mask = (1L << mem->bit_width) - 1; uint64_t combined = oldval | ((newval & mask) << mem->bit_offset); write_buf(loc, combined, mem->ty->size); } else { cur = write_gvar_data(cur, init->children[mem->idx], mem->ty, buf, offset + mem->offset); } } return cur; } if (ty->kind == TY_UNION) { if (!init->mem) return cur; return write_gvar_data(cur, init->children[init->mem->idx], init->mem->ty, buf, offset); } if (!init->expr) return cur; if (ty->kind == TY_FLOAT) { *(float *)(buf + offset) = eval_double(init->expr); return cur; } if (ty->kind == TY_DOUBLE) { *(double *)(buf + offset) = eval_double(init->expr); return cur; } char **label = NULL; uint64_t val = eval2(init->expr, &label); if (!label) { write_buf(buf + offset, val, ty->size); return cur; } Relocation *rel = calloc(1, sizeof(Relocation)); rel->offset = offset; rel->label = label; rel->addend = val; cur->next = rel; return cur->next; } // Initializers for global variables are evaluated at compile-time and // embedded to .data section. This function serializes Initializer // objects to a flat byte array. It is a compile error if an // initializer list contains a non-constant expression. static void gvar_initializer(Token **rest, Token *tok, Obj *var) { Initializer *init = initializer(rest, tok, var->ty, &var->ty); Relocation head = {}; char *buf = calloc(1, var->ty->size); write_gvar_data(&head, init, var->ty, buf, 0); var->init_data = buf; var->rel = head.next; } // Returns true if a given token represents a type. static bool is_typename(Token *tok) { unsigned char kw; kw = GetKw(tok->loc, tok->len); return (kw && !(kw & -32)) || find_typedef(tok); } static bool is_const_expr_true(Node *node) { if (is_flonum(node->ty)) { return !!eval_double(node); } else { return eval(node); } } // stmt = "return" expr? ";" // | "if" "(" expr ")" stmt ("else" stmt)? // | "switch" "(" expr ")" stmt // | "case" const-expr ("..." const-expr)? ":" stmt // | "default" ":" stmt // | "for" "(" expr-stmt expr? ";" expr? ")" stmt // | "while" "(" expr ")" stmt // | "do" stmt "while" "(" expr ")" ";" // | "asm" asm-stmt // | "goto" (ident | "*" expr) ";" // | "break" ";" // | "continue" ";" // | ident ":" stmt // | "{" compound-stmt // | expr-stmt static Node *stmt(Token **rest, Token *tok) { if (EQUAL(tok, "return")) { Node *node = new_node(ND_RETURN, tok); if (CONSUME(rest, tok->next, ";")) return node; Node *exp = expr(&tok, tok->next); *rest = skip(tok, ';'); add_type(exp); Type *ty = current_fn->ty->return_ty; if (ty->kind != TY_STRUCT && ty->kind != TY_UNION) exp = new_cast(exp, current_fn->ty->return_ty); node->lhs = exp; return node; } if (EQUAL(tok, "if")) { Node *node = new_node(ND_IF, tok); tok = skip(tok->next, '('); node->cond = expr(&tok, tok); tok = skip(tok, ')'); node->then = stmt(&tok, tok); if (EQUAL(tok, "else")) node->els = stmt(&tok, tok->next); *rest = tok; if (is_const_expr(node->cond)) { if (is_const_expr_true(node->cond)) { /* DCE */ return node->then; } else if (node->els) { return node->els; } else { return new_node(ND_BLOCK, node->tok); } } return node; } if (EQUAL(tok, "_Static_assert")) { Token *start = tok; *rest = static_assertion(tok); return new_node(ND_BLOCK, start); } if (EQUAL(tok, "switch")) { Node *node = new_node(ND_SWITCH, tok); tok = skip(tok->next, '('); node->cond = expr(&tok, tok); tok = skip(tok, ')'); Node *sw = current_switch; current_switch = node; char *brk = brk_label; brk_label = node->brk_label = new_unique_name(); node->then = stmt(rest, tok); current_switch = sw; brk_label = brk; return node; } if (EQUAL(tok, "case")) { if (!current_switch) error_tok(tok, "stray case"); Node *node = new_node(ND_CASE, tok); int begin = const_expr(&tok, tok->next); int end; if (EQUAL(tok, "...")) { // [GNU] Case ranges, e.g. "case 1 ... 5:" end = const_expr(&tok, tok->next); if (end < begin) error_tok(tok, "empty case range specified"); } else { end = begin; } tok = skip(tok, ':'); node->label = new_unique_name(); node->lhs = stmt(rest, tok); node->begin = begin; node->end = end; node->case_next = current_switch->case_next; current_switch->case_next = node; return node; } if (EQUAL(tok, "default")) { if (!current_switch) error_tok(tok, "stray default"); Node *node = new_node(ND_CASE, tok); tok = skip(tok->next, ':'); node->label = new_unique_name(); node->lhs = stmt(rest, tok); current_switch->default_case = node; return node; } if (EQUAL(tok, "for")) { Node *node = new_node(ND_FOR, tok); tok = skip(tok->next, '('); enter_scope(); char *brk = brk_label; char *cont = cont_label; brk_label = node->brk_label = new_unique_name(); cont_label = node->cont_label = new_unique_name(); if (is_typename(tok)) { Type *basety = declspec(&tok, tok, NULL); node->init = declaration(&tok, tok, basety, NULL); } else { node->init = expr_stmt(&tok, tok); } if (!EQUAL(tok, ";")) node->cond = expr(&tok, tok); tok = skip(tok, ';'); if (!EQUAL(tok, ")")) node->inc = expr(&tok, tok); tok = skip(tok, ')'); node->then = stmt(rest, tok); leave_scope(); brk_label = brk; cont_label = cont; return node; } if (EQUAL(tok, "while")) { Node *node = new_node(ND_FOR, tok); tok = skip(tok->next, '('); node->cond = expr(&tok, tok); tok = skip(tok, ')'); char *brk = brk_label; char *cont = cont_label; brk_label = node->brk_label = new_unique_name(); cont_label = node->cont_label = new_unique_name(); node->then = stmt(rest, tok); brk_label = brk; cont_label = cont; return node; } if (EQUAL(tok, "do")) { Node *node = new_node(ND_DO, tok); char *brk = brk_label; char *cont = cont_label; brk_label = node->brk_label = new_unique_name(); cont_label = node->cont_label = new_unique_name(); node->then = stmt(&tok, tok->next); brk_label = brk; cont_label = cont; if (!EQUAL(tok, "while")) { error_tok(tok, "expected while"); } tok = skip(tok->next, '('); node->cond = expr(&tok, tok); tok = skip(tok, ')'); *rest = skip(tok, ';'); return node; } if (EQUAL(tok, "asm") || EQUAL(tok, "__asm__")) { Node *node = new_node(ND_ASM, tok); node->azm = asm_stmt(rest, tok); return node; } if (EQUAL(tok, "goto")) { if (EQUAL(tok->next, "*")) { // [GNU] `goto *ptr` jumps to the address specified by `ptr`. Node *node = new_node(ND_GOTO_EXPR, tok); node->lhs = expr(&tok, tok->next->next); *rest = skip(tok, ';'); return node; } Node *node = new_node(ND_GOTO, tok); node->label = get_ident(tok->next); node->goto_next = gotos; gotos = node; *rest = skip(tok->next->next, ';'); return node; } if (EQUAL(tok, "break")) { if (!brk_label) error_tok(tok, "stray break"); Node *node = new_node(ND_GOTO, tok); node->unique_label = brk_label; *rest = skip(tok->next, ';'); return node; } if (EQUAL(tok, "continue")) { if (!cont_label) error_tok(tok, "stray continue"); Node *node = new_node(ND_GOTO, tok); node->unique_label = cont_label; *rest = skip(tok->next, ';'); return node; } if (tok->kind == TK_IDENT && EQUAL(tok->next, ":")) { Node *node = new_node(ND_LABEL, tok); node->label = strndup(tok->loc, tok->len); node->unique_label = new_unique_name(); node->lhs = stmt(rest, tok->next->next); node->goto_next = labels; labels = node; return node; } if (EQUAL(tok, "{")) return compound_stmt(rest, tok->next); return expr_stmt(rest, tok); } // compound-stmt = (typedef | declaration | stmt)* "}" static Node *compound_stmt(Token **rest, Token *tok) { Node *node = new_node(ND_BLOCK, tok); Node head = {}; Node *cur = &head; enter_scope(); while (!EQUAL(tok, "}")) { if (is_typename(tok) && !EQUAL(tok->next, ":")) { VarAttr attr = {}; Type *basety = declspec(&tok, tok, &attr); if (attr.is_typedef) { tok = parse_typedef(tok, basety); continue; } if (is_function(tok)) { tok = function(tok, basety, &attr); continue; } if (attr.is_extern) { tok = global_variable(tok, basety, &attr); continue; } cur = cur->next = declaration(&tok, tok, basety, &attr); } else { cur = cur->next = stmt(&tok, tok); } add_type(cur); } leave_scope(); node->body = head.next; *rest = tok->next; return node; } // expr-stmt = expr? ";" static Node *expr_stmt(Token **rest, Token *tok) { if (EQUAL(tok, ";")) { *rest = tok->next; return new_node(ND_BLOCK, tok); } Node *node = new_node(ND_EXPR_STMT, tok); node->lhs = expr(&tok, tok); *rest = skip(tok, ';'); return node; } // expr = assign ("," expr)? Node *expr(Token **rest, Token *tok) { Node *node = assign(&tok, tok); if (EQUAL(tok, ",")) { return new_binary(ND_COMMA, node, expr(rest, tok->next), tok); } *rest = tok; return node; } int64_t eval(Node *node) { return eval2(node, NULL); } // Evaluate a given node as a constant expression. // // A constant expression is either just a number or ptr+n where ptr // is a pointer to a global variable and n is a postiive/negative // number. The latter form is accepted only as an initialization // expression for a global variable. int64_t eval2(Node *node, char ***label) { int64_t x, y; add_type(node); if (is_flonum(node->ty)) return eval_double(node); switch (node->kind) { case ND_ADD: return eval2(node->lhs, label) + eval(node->rhs); case ND_SUB: return eval2(node->lhs, label) - eval(node->rhs); case ND_MUL: return eval(node->lhs) * eval(node->rhs); case ND_DIV: y = eval(node->rhs); if (!y) error_tok(node->rhs->tok, "constexpr div by zero"); if (node->ty->is_unsigned) { return (uint64_t)eval(node->lhs) / y; } x = eval(node->lhs); if (x == 0x8000000000000000 && y == -1) { error_tok(node->rhs->tok, "constexpr divide error"); } return x / y; case ND_NEG: return -eval(node->lhs); case ND_REM: y = eval(node->rhs); if (!y) error_tok(node->rhs->tok, "constexpr rem by zero"); if (node->ty->is_unsigned) { return (uint64_t)eval(node->lhs) % y; } return eval(node->lhs) % y; case ND_BINAND: return eval(node->lhs) & eval(node->rhs); case ND_BINOR: return eval(node->lhs) | eval(node->rhs); case ND_BINXOR: return eval(node->lhs) ^ eval(node->rhs); case ND_SHL: return eval(node->lhs) << eval(node->rhs); case ND_SHR: if (node->ty->is_unsigned && node->ty->size == 8) return (uint64_t)eval(node->lhs) >> eval(node->rhs); return eval(node->lhs) >> eval(node->rhs); case ND_EQ: { bool lhs = is_const_expr(node->lhs); bool rhs = is_const_expr(node->rhs); if (rhs && node->lhs->kind == ND_VAR && node->lhs->ty->kind == TY_ARRAY && node->lhs->var->is_string_literal) { return eval(node->rhs) == (intptr_t)node->lhs->var->init_data; } else if (lhs && node->rhs->kind == ND_VAR && node->rhs->ty->kind == TY_ARRAY && node->rhs->var->is_string_literal) { return eval(node->lhs) == (intptr_t)node->rhs->var->init_data; } else { return eval(node->lhs) == eval(node->rhs); } } case ND_NE: { bool lhs = is_const_expr(node->lhs); bool rhs = is_const_expr(node->rhs); if (rhs && node->lhs->kind == ND_VAR && node->lhs->ty->kind == TY_ARRAY && node->lhs->var->is_string_literal) { return eval(node->rhs) != (intptr_t)node->lhs->var->init_data; } else if (lhs && node->rhs->kind == ND_VAR && node->rhs->ty->kind == TY_ARRAY && node->rhs->var->is_string_literal) { return eval(node->lhs) != (intptr_t)node->rhs->var->init_data; } else { return eval(node->lhs) != eval(node->rhs); } } case ND_LT: if (node->lhs->ty->is_unsigned) return (uint64_t)eval(node->lhs) < eval(node->rhs); return eval(node->lhs) < eval(node->rhs); case ND_LE: if (node->lhs->ty->is_unsigned) return (uint64_t)eval(node->lhs) <= eval(node->rhs); return eval(node->lhs) <= eval(node->rhs); case ND_COND: return eval(node->cond) ? eval2(node->then, label) : eval2(node->els, label); case ND_COMMA: return eval2(node->rhs, label); case ND_NOT: return !eval(node->lhs); case ND_BITNOT: return ~eval(node->lhs); case ND_LOGAND: return eval(node->lhs) && eval(node->rhs); case ND_LOGOR: return eval(node->lhs) || eval(node->rhs); case ND_CAST: { int64_t val = eval2(node->lhs, label); if (is_integer(node->ty)) { switch (node->ty->size) { case 1: return node->ty->is_unsigned ? (uint8_t)val : (int8_t)val; case 2: return node->ty->is_unsigned ? (uint16_t)val : (int16_t)val; case 4: return node->ty->is_unsigned ? (uint32_t)val : (int32_t)val; } } return val; } case ND_ADDR: return eval_rval(node->lhs, label); case ND_LABEL_VAL: *label = &node->unique_label; return 0; case ND_MEMBER: if (!label) error_tok(node->tok, "not a compile-time constant"); if (node->ty->kind != TY_ARRAY) error_tok(node->tok, "invalid initializer"); return eval_rval(node->lhs, label) + node->member->offset; case ND_VAR: if (!label) { if (node->ty->kind == TY_ARRAY && node->var->is_string_literal) { return (intptr_t)node->var->init_data; } error_tok(node->tok, "not a compile-time constant"); } if (node->var->ty->kind != TY_ARRAY && node->var->ty->kind != TY_FUNC) { error_tok(node->tok, "invalid initializer"); } *label = &node->var->name; return 0; case ND_NUM: return node->val; } error_tok(node->tok, "not a compile-time constant"); } static int64_t eval_rval(Node *node, char ***label) { switch (node->kind) { case ND_VAR: if (node->var->is_local) { error_tok(node->tok, "not a compile-time constant"); } *label = &node->var->name; return 0; case ND_DEREF: return eval2(node->lhs, label); case ND_MEMBER: return eval_rval(node->lhs, label) + node->member->offset; } error_tok(node->tok, "invalid initializer"); } bool is_const_expr(Node *node) { add_type(node); switch (node->kind) { case ND_ADD: case ND_SUB: case ND_MUL: case ND_DIV: case ND_REM: case ND_BINAND: case ND_BINOR: case ND_BINXOR: case ND_SHL: case ND_SHR: case ND_LT: case ND_LE: case ND_LOGAND: case ND_LOGOR: return is_const_expr(node->lhs) && is_const_expr(node->rhs); case ND_EQ: case ND_NE: { bool lhs = is_const_expr(node->lhs); bool rhs = is_const_expr(node->rhs); return (lhs && rhs) || (rhs && node->lhs->kind == ND_VAR && node->lhs->var->is_string_literal) || (lhs && node->rhs->kind == ND_VAR && node->rhs->var->is_string_literal); } case ND_COND: if (!is_const_expr(node->cond)) return false; return is_const_expr(eval(node->cond) ? node->then : node->els); case ND_COMMA: return is_const_expr(node->rhs); case ND_NEG: case ND_NOT: case ND_BITNOT: case ND_CAST: return is_const_expr(node->lhs); case ND_NUM: return true; case ND_VAR: return node->var->is_string_literal; } return false; } int64_t const_expr(Token **rest, Token *tok) { Node *node = conditional(rest, tok); return eval(node); } static double eval_double(Node *node) { add_type(node); if (is_integer(node->ty)) { if (node->ty->is_unsigned) { return (unsigned long)eval(node); } return eval(node); } switch (node->kind) { case ND_ADD: return eval_double(node->lhs) + eval_double(node->rhs); case ND_SUB: return eval_double(node->lhs) - eval_double(node->rhs); case ND_MUL: return eval_double(node->lhs) * eval_double(node->rhs); case ND_DIV: return eval_double(node->lhs) / eval_double(node->rhs); case ND_NEG: return -eval_double(node->lhs); case ND_COND: return eval_double(node->cond) ? eval_double(node->then) : eval_double(node->els); case ND_COMMA: return eval_double(node->rhs); case ND_CAST: if (is_flonum(node->lhs->ty)) return eval_double(node->lhs); return eval(node->lhs); case ND_NUM: return node->fval; } error_tok(node->tok, "not a compile-time constant"); } // Convert op= operators to expressions containing an assignment. // // In general, `A op= C` is converted to ``tmp = &A, *tmp = *tmp op B`. // However, if a given expression is of form `A.x op= C`, the input is // converted to `tmp = &A, (*tmp).x = (*tmp).x op C` to handle assignments // to bitfields. static Node *to_assign(Node *binary) { add_type(binary->lhs); add_type(binary->rhs); Token *tok = binary->tok; // Convert `A.x op= C` to `tmp = &A, (*tmp).x = (*tmp).x op C`. if (binary->lhs->kind == ND_MEMBER) { Obj *var = new_lvar("", pointer_to(binary->lhs->lhs->ty)); Node *expr1 = new_binary(ND_ASSIGN, new_var_node(var, tok), new_unary(ND_ADDR, binary->lhs->lhs, tok), tok); Node *expr2 = new_unary( ND_MEMBER, new_unary(ND_DEREF, new_var_node(var, tok), tok), tok); expr2->member = binary->lhs->member; Node *expr3 = new_unary( ND_MEMBER, new_unary(ND_DEREF, new_var_node(var, tok), tok), tok); expr3->member = binary->lhs->member; Node *expr4 = new_binary(ND_ASSIGN, expr2, new_binary(binary->kind, expr3, binary->rhs, tok), tok); return new_binary(ND_COMMA, expr1, expr4, tok); } // If A is an atomic type, Convert `A op= B` to // // ({ // T1 *addr = &A; T2 val = (B); T1 old = *addr; T1 new; // do { // new = old op val; // } while (!atomic_compare_exchange_strong(addr, &old, new)); // new; // }) if (binary->lhs->ty->is_atomic) { Node head = {}; Node *cur = &head; Obj *addr = new_lvar("", pointer_to(binary->lhs->ty)); Obj *val = new_lvar("", binary->rhs->ty); Obj *old = new_lvar("", binary->lhs->ty); Obj *new = new_lvar("", binary->lhs->ty); cur = cur->next = new_unary(ND_EXPR_STMT, new_binary(ND_ASSIGN, new_var_node(addr, tok), new_unary(ND_ADDR, binary->lhs, tok), tok), tok); cur = cur->next = new_unary( ND_EXPR_STMT, new_binary(ND_ASSIGN, new_var_node(val, tok), binary->rhs, tok), tok); cur = cur->next = new_unary( ND_EXPR_STMT, new_binary(ND_ASSIGN, new_var_node(old, tok), new_unary(ND_DEREF, new_var_node(addr, tok), tok), tok), tok); Node *loop = new_node(ND_DO, tok); loop->brk_label = new_unique_name(); loop->cont_label = new_unique_name(); Node *body = new_binary(ND_ASSIGN, new_var_node(new, tok), new_binary(binary->kind, new_var_node(old, tok), new_var_node(val, tok), tok), tok); loop->then = new_node(ND_BLOCK, tok); loop->then->body = new_unary(ND_EXPR_STMT, body, tok); Node *cas = new_node(ND_CAS, tok); cas->cas_addr = new_var_node(addr, tok); cas->cas_old = new_unary(ND_ADDR, new_var_node(old, tok), tok); cas->cas_new = new_var_node(new, tok); loop->cond = new_unary(ND_NOT, cas, tok); cur = cur->next = loop; cur = cur->next = new_unary(ND_EXPR_STMT, new_var_node(new, tok), tok); Node *node = new_node(ND_STMT_EXPR, tok); node->body = head.next; return node; } // Convert `A op= B` to ``tmp = &A, *tmp = *tmp op B`. Obj *var = new_lvar("", pointer_to(binary->lhs->ty)); Node *expr1 = new_binary(ND_ASSIGN, new_var_node(var, tok), new_unary(ND_ADDR, binary->lhs, tok), tok); Node *expr2 = new_binary( ND_ASSIGN, new_unary(ND_DEREF, new_var_node(var, tok), tok), new_binary(binary->kind, new_unary(ND_DEREF, new_var_node(var, tok), tok), binary->rhs, tok), tok); return new_binary(ND_COMMA, expr1, expr2, tok); } // @hint it's expr() without the commas // assign = conditional (assign-op assign)? // assign-op = "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "&=" | "|=" | "^=" // | "<<=" | ">>=" static Node *assign(Token **rest, Token *tok) { Node *node = conditional(&tok, tok); if (tok->len == 1) { if (tok->loc[0] == '=') { return new_binary(ND_ASSIGN, node, assign(rest, tok->next), tok); } } else if (tok->len == 2) { if (tok->loc[0] == '+' && tok->loc[1] == '=') { return to_assign(new_add(node, assign(rest, tok->next), tok)); } if (tok->loc[0] == '-' && tok->loc[1] == '=') { return to_assign(new_sub(node, assign(rest, tok->next), tok)); } if (tok->loc[0] == '*' && tok->loc[1] == '=') { return to_assign(new_binary(ND_MUL, node, assign(rest, tok->next), tok)); } if (tok->loc[0] == '/' && tok->loc[1] == '=') { return to_assign(new_binary(ND_DIV, node, assign(rest, tok->next), tok)); } if (tok->loc[0] == '%' && tok->loc[1] == '=') { return to_assign(new_binary(ND_REM, node, assign(rest, tok->next), tok)); } if (tok->loc[0] == '&' && tok->loc[1] == '=') { return to_assign( new_binary(ND_BINAND, node, assign(rest, tok->next), tok)); } if (tok->loc[0] == '|' && tok->loc[1] == '=') { return to_assign( new_binary(ND_BINOR, node, assign(rest, tok->next), tok)); } if (tok->loc[0] == '^' && tok->loc[1] == '=') { return to_assign( new_binary(ND_BINXOR, node, assign(rest, tok->next), tok)); } } else if (tok->len == 3) { if (tok->loc[0] == '<' && tok->loc[1] == '<' && tok->loc[2] == '=') { return to_assign(new_binary(ND_SHL, node, assign(rest, tok->next), tok)); } if (tok->loc[0] == '>' && tok->loc[1] == '>' && tok->loc[2] == '=') { return to_assign(new_binary(ND_SHR, node, assign(rest, tok->next), tok)); } } *rest = tok; return node; } // conditional = logor ("?" expr? ":" conditional)? static Node *conditional(Token **rest, Token *tok) { Node *cond = logor(&tok, tok); if (!EQUAL(tok, "?")) { *rest = tok; return cond; } if (EQUAL(tok->next, ":")) { // [GNU] Compile `a ?: b` as `tmp = a, tmp ? tmp : b`. Node *els = conditional(rest, tok->next->next); if (is_const_expr(cond)) { /* DCE */ if (is_const_expr_true(cond)) { return cond; } else { return els; } } Obj *var = new_lvar("", cond->ty); Node *lhs = new_binary(ND_ASSIGN, new_var_node(var, tok), cond, tok); Node *rhs = new_node(ND_COND, tok); rhs->cond = new_var_node(var, tok); rhs->then = new_var_node(var, tok); rhs->els = els; return new_binary(ND_COMMA, lhs, rhs, tok); } Node *node = new_node(ND_COND, tok); node->cond = cond; node->then = expr(&tok, tok->next); tok = skip(tok, ':'); node->els = conditional(rest, tok); add_type(node); if (is_const_expr(cond)) { /* DCE */ if (is_const_expr_true(cond)) { return new_cast(node->then, node->ty); } else { return new_cast(node->els, node->ty); } } return node; } // logor = logand ("||" logand)* static Node *logor(Token **rest, Token *tok) { Node *node = logand(&tok, tok); while (EQUAL(tok, "||")) { Token *start = tok; node = new_binary(ND_LOGOR, node, logand(&tok, tok->next), start); } *rest = tok; return node; } // logand = binor ("&&" binor)* static Node *logand(Token **rest, Token *tok) { Node *node = binor(&tok, tok); while (EQUAL(tok, "&&")) { Token *start = tok; node = new_binary(ND_LOGAND, node, binor(&tok, tok->next), start); } *rest = tok; #if 0 if (node->lhs && node->rhs) { add_type(node->lhs); add_type(node->rhs); if (((is_const_expr(node->lhs) && !is_const_expr_true(node->lhs)) || (is_const_expr(node->rhs) && !is_const_expr_true(node->rhs)))) { node->lhs = new_cast(new_num(0, start), node->lhs->ty); /* DCE */ node->rhs = new_cast(new_num(0, start), node->rhs->ty); } } #endif return node; } // binor = binxor ("|" binxor)* static Node *binor(Token **rest, Token *tok) { Node *node = binxor(&tok, tok); while (EQUAL(tok, "|")) { Token *start = tok; node = new_binary(ND_BINOR, node, binxor(&tok, tok->next), start); } *rest = tok; return node; } // binxor = binand ("^" binand)* static Node *binxor(Token **rest, Token *tok) { Node *node = binand(&tok, tok); while (EQUAL(tok, "^")) { Token *start = tok; node = new_binary(ND_BINXOR, node, binand(&tok, tok->next), start); } *rest = tok; return node; } // binand = equality ("&" equality)* static Node *binand(Token **rest, Token *tok) { Node *node = equality(&tok, tok); while (EQUAL(tok, "&")) { Token *start = tok; node = new_binary(ND_BINAND, node, equality(&tok, tok->next), start); } *rest = tok; return node; } // equality = relational ("==" relational | "!=" relational)* static Node *equality(Token **rest, Token *tok) { Node *node = relational(&tok, tok); for (;;) { Token *start = tok; if (EQUAL(tok, "==")) { node = new_binary(ND_EQ, node, relational(&tok, tok->next), start); continue; } if (EQUAL(tok, "!=")) { node = new_binary(ND_NE, node, relational(&tok, tok->next), start); continue; } *rest = tok; return node; } } // relational = shift ("<" shift | "<=" shift | ">" shift | ">=" shift)* static Node *relational(Token **rest, Token *tok) { Node *node = shift(&tok, tok); for (;;) { Token *start = tok; if (EQUAL(tok, "<")) { node = new_binary(ND_LT, node, shift(&tok, tok->next), start); continue; } if (tok->len == 2) { if (tok->loc[0] == '<' && tok->loc[1] == '=') { node = new_binary(ND_LE, node, shift(&tok, tok->next), start); continue; } if (tok->loc[0] == '>' && tok->loc[1] == '=') { node = new_binary(ND_LE, shift(&tok, tok->next), node, start); continue; } } else if (tok->len == 1) { if (tok->loc[0] == '>') { node = new_binary(ND_LT, shift(&tok, tok->next), node, start); continue; } } *rest = tok; return node; } } // shift = add ("<<" add | ">>" add)* static Node *shift(Token **rest, Token *tok) { Node *node = add(&tok, tok); for (;;) { Token *start = tok; if (tok->len == 2) { if (tok->loc[0] == '<' && tok->loc[1] == '<') { node = new_binary(ND_SHL, node, add(&tok, tok->next), start); continue; } if (tok->loc[0] == '>' && tok->loc[1] == '>') { node = new_binary(ND_SHR, node, add(&tok, tok->next), start); continue; } } *rest = tok; return node; } } static Node *get_vla_size(Type *ty, Token *tok) { if (ty->vla_size) { return new_var_node(ty->vla_size, tok); } else { Node *lhs = compute_vla_size(ty, tok); Node *rhs = new_var_node(ty->vla_size, tok); return new_binary(ND_COMMA, lhs, rhs, tok); } } // In C, `+` operator is overloaded to perform the pointer arithmetic. // If p is a pointer, p+n adds not n but sizeof(*p)*n to the value of p, // so that p+n points to the location n elements (not bytes) ahead of p. // In other words, we need to scale an integer value before adding to a // pointer value. This function takes care of the scaling. static Node *new_add(Node *lhs, Node *rhs, Token *tok) { add_type(lhs); add_type(rhs); // num + num if (is_numeric(lhs->ty) && is_numeric(rhs->ty)) return new_binary(ND_ADD, lhs, rhs, tok); if (lhs->ty->base && rhs->ty->base) error_tok(tok, "invalid operands"); // Canonicalize `num + ptr` to `ptr + num`. if (!lhs->ty->base && rhs->ty->base) { Node *tmp = lhs; lhs = rhs; rhs = tmp; } // VLA + num if (lhs->ty->base->kind == TY_VLA) { rhs = new_binary(ND_MUL, rhs, get_vla_size(lhs->ty->base, tok), tok); return new_binary(ND_ADD, lhs, rhs, tok); } // ptr + num rhs = new_binary(ND_MUL, rhs, new_long(lhs->ty->base->size, tok), tok); return new_binary(ND_ADD, lhs, rhs, tok); } // Like `+`, `-` is overloaded for the pointer type. static Node *new_sub(Node *lhs, Node *rhs, Token *tok) { add_type(lhs); add_type(rhs); // num - num if (is_numeric(lhs->ty) && is_numeric(rhs->ty)) return new_binary(ND_SUB, lhs, rhs, tok); // VLA + num if (lhs->ty->base->kind == TY_VLA) { rhs = new_binary(ND_MUL, rhs, get_vla_size(lhs->ty->base, tok), tok); add_type(rhs); Node *node = new_binary(ND_SUB, lhs, rhs, tok); node->ty = lhs->ty; return node; } // ptr - num if (lhs->ty->base && is_integer(rhs->ty)) { rhs = new_binary(ND_MUL, rhs, new_long(lhs->ty->base->size, tok), tok); add_type(rhs); Node *node = new_binary(ND_SUB, lhs, rhs, tok); node->ty = lhs->ty; return node; } // ptr - ptr, which returns how many elements are between the two. if (lhs->ty->base && rhs->ty->base) { Node *node = new_binary(ND_SUB, lhs, rhs, tok); node->ty = ty_long; return new_binary(ND_DIV, node, new_num(lhs->ty->base->size, tok), tok); } error_tok(tok, "invalid operands"); } static Node *new_mul(Node *lhs, Node *rhs, Token *tok) { return new_binary(ND_MUL, lhs, rhs, tok); } // add = mul ("+" mul | "-" mul)* static Node *add(Token **rest, Token *tok) { Node *node = mul(&tok, tok); for (;;) { Token *start = tok; if (tok->len == 1) { if (tok->loc[0] == '+') { node = new_add(node, mul(&tok, tok->next), start); continue; } if (tok->loc[0] == '-') { node = new_sub(node, mul(&tok, tok->next), start); continue; } } *rest = tok; return node; } } // mul = cast ("*" cast | "/" cast | "%" cast)* static Node *mul(Token **rest, Token *tok) { Node *node = cast(&tok, tok); for (;;) { Token *start = tok; if (tok->len == 1) { if (tok->loc[0] == '*') { node = new_mul(node, cast(&tok, tok->next), start); continue; } if (tok->loc[0] == '/') { node = new_binary(ND_DIV, node, cast(&tok, tok->next), start); continue; } if (tok->loc[0] == '%') { node = new_binary(ND_REM, node, cast(&tok, tok->next), start); continue; } } *rest = tok; return node; } } // cast = "(" type-name ")" cast | unary static Node *cast(Token **rest, Token *tok) { if (EQUAL(tok, "(") && is_typename(tok->next)) { Token *start = tok; Type *ty = typename(&tok, tok->next); tok = skip(tok, ')'); // compound literal if (EQUAL(tok, "{")) return unary(rest, start); // type cast Node *node = new_cast(cast(rest, tok), ty); node->tok = start; return node; } return unary(rest, tok); } // unary = ("+" | "-" | "*" | "&" | "!" | "~") cast // | ("++" | "--") unary // | "&&" ident // | postfix static Node *unary(Token **rest, Token *tok) { if (tok->len == 1) { if (tok->loc[0] == '+') { return cast(rest, tok->next); } if (tok->loc[0] == '-') { return new_unary(ND_NEG, cast(rest, tok->next), tok); } if (tok->loc[0] == '&') { Node *lhs = cast(rest, tok->next); add_type(lhs); if (lhs->kind == ND_MEMBER && lhs->member->is_bitfield) { error_tok(tok, "cannot take address of bitfield"); } return new_unary(ND_ADDR, lhs, tok); } if (tok->loc[0] == '*') { // [https://www.sigbus.info/n1570#6.5.3.2p4] This is an oddity // in the C spec, but dereferencing a function shouldn't do // anything. If foo is a function, `*foo`, `**foo` or `*****foo` // are all equivalent to just `foo`. Node *node = cast(rest, tok->next); add_type(node); if (node->ty->kind == TY_FUNC) return node; return new_unary(ND_DEREF, node, tok); } if (tok->loc[0] == '!') { return new_unary(ND_NOT, cast(rest, tok->next), tok); } if (tok->loc[0] == '~') { return new_unary(ND_BITNOT, cast(rest, tok->next), tok); } } else if (tok->len == 2) { // Read ++i as i+=1 if (tok->loc[0] == '+' && tok->loc[1] == '+') { return to_assign(new_add(unary(rest, tok->next), new_num(1, tok), tok)); } // Read --i as i-=1 if (tok->loc[0] == '-' && tok->loc[1] == '-') { return to_assign(new_sub(unary(rest, tok->next), new_num(1, tok), tok)); } // [GNU] labels-as-values if (tok->loc[0] == '&' && tok->loc[1] == '&') { Node *node = new_node(ND_LABEL_VAL, tok); node->label = get_ident(tok->next); node->goto_next = gotos; gotos = node; *rest = tok->next->next; return node; } } return postfix(rest, tok); } // struct-members = (declspec declarator ("," declarator)* ";" javadown?)* static void struct_members(Token **rest, Token *tok, Type *ty) { Member head = {}; Member *cur = &head; int idx = 0; while (!EQUAL(tok, "}")) { VarAttr attr = {}; Type *basety = declspec(&tok, tok, &attr); bool first = true; // Anonymous struct member if ((basety->kind == TY_STRUCT || basety->kind == TY_UNION) && CONSUME(&tok, tok, ";")) { Member *mem = calloc(1, sizeof(Member)); mem->ty = basety; mem->idx = idx++; mem->align = attr.align ? attr.align : mem->ty->align; cur = cur->next = mem; continue; } // Regular struct members while (!CONSUME(&tok, tok, ";")) { if (!first) tok = skip(tok, ','); if (tok->kind == TK_JAVADOWN) { current_javadown = tok; tok = tok->next; } first = false; Member *mem = calloc(1, sizeof(Member)); mem->ty = declarator(&tok, tok, basety); mem->name = mem->ty->name; mem->idx = idx++; mem->align = attr.align ? attr.align : mem->ty->align; if (CONSUME(&tok, tok, ":")) { mem->is_bitfield = true; mem->bit_width = const_expr(&tok, tok); } cur = cur->next = mem; } if (tok->kind == TK_JAVADOWN) { tok = tok->next; } } // If the last element is an array of incomplete type, it's // called a "flexible array member". It should behave as if // if were a zero-sized array. if (cur != &head && cur->ty->kind == TY_ARRAY && cur->ty->array_len < 0) { cur->ty = array_of(cur->ty->base, 0); ty->is_flexible = true; } *rest = tok->next; ty->members = head.next; } char *ConsumeStringLiteral(Token **rest, Token *tok) { char *s; if (tok->kind != TK_STR || tok->ty->base->kind != TY_CHAR) { error_tok(tok, "expected string literal"); } s = tok->str; *rest = tok->next; return s; } // struct-union-decl = attribute? ident? ("{" struct-members)? static Type *struct_union_decl(Token **rest, Token *tok) { Type *ty = struct_type(); tok = attribute_list(tok, ty, type_attributes); // Read a tag. Token *tag = NULL; if (tok->kind == TK_IDENT) { tag = tok; tok = tok->next; } if (tag && !EQUAL(tok, "{")) { *rest = tok; Type *ty2 = find_tag(tag); if (ty2) return ty2; ty->size = -1; push_tag_scope(tag, ty); return ty; } ty->name = tag; tok = skip(tok, '{'); // Construct a struct object. if (tok->kind == TK_JAVADOWN) { current_javadown = tok; tok = tok->next; } struct_members(&tok, tok, ty); *rest = attribute_list(tok, ty, type_attributes); if (tag) { // If this is a redefinition, overwrite a previous type. // Otherwise, register the struct type. Type *ty2 = hashmap_get2(&scope->tags, tag->loc, tag->len); if (ty2) { *ty2 = *ty; return ty2; } push_tag_scope(tag, ty); } return ty; } // struct-decl = struct-union-decl static Type *struct_decl(Token **rest, Token *tok) { Type *ty = struct_union_decl(rest, tok); ty->kind = TY_STRUCT; if (ty->size < 0) return ty; // Assign offsets within the struct to members. int bits = 0; for (Member *m = ty->members; m; m = m->next) { if (m->is_bitfield && m->bit_width == 0) { // Zero-width anonymous bitfield has a special meaning. // It affects only alignment. bits = ROUNDUP(bits, m->ty->size * 8); } else if (m->is_bitfield) { int sz = m->ty->size; if (bits / (sz * 8) != (bits + m->bit_width - 1) / (sz * 8)) { bits = ROUNDUP(bits, sz * 8); } m->offset = ROUNDDOWN(bits / 8, sz); m->bit_offset = bits % (sz * 8); bits += m->bit_width; } else { if (!ty->is_packed) { bits = ROUNDUP(bits, m->align * 8); } m->offset = bits / 8; bits += m->ty->size * 8; } if (!ty->is_packed && !ty->is_aligned && ty->align < m->align) { ty->align = m->align; } } ty->size = ROUNDUP(bits, ty->align * 8) / 8; return ty; } // union-decl = struct-union-decl static Type *union_decl(Token **rest, Token *tok) { Type *ty = struct_union_decl(rest, tok); ty->kind = TY_UNION; if (ty->size < 0) return ty; // If union, we don't have to assign offsets because they // are already initialized to zero. We need to compute the // alignment and the size though. for (Member *mem = ty->members; mem; mem = mem->next) { if (ty->align < mem->align) ty->align = mem->align; if (ty->size < mem->ty->size) ty->size = mem->ty->size; } ty->size = ROUNDUP(ty->size, ty->align); return ty; } // Find a struct member by name. static Member *get_struct_member(Type *ty, Token *tok) { for (Member *mem = ty->members; mem; mem = mem->next) { // Anonymous struct member if ((mem->ty->kind == TY_STRUCT || mem->ty->kind == TY_UNION) && !mem->name) { if (get_struct_member(mem->ty, tok)) return mem; continue; } // Regular struct member if (mem->name->len == tok->len && !strncmp(mem->name->loc, tok->loc, tok->len)) { return mem; } } return NULL; } // Create a node representing a struct member access, such as foo.bar // where foo is a struct and bar is a member name. // // C has a feature called "anonymous struct" which allows a struct to // have another unnamed struct as a member like this: // // struct { struct { int a; }; int b; } x; // // The members of an anonymous struct belong to the outer struct's // member namespace. Therefore, in the above example, you can access // member "a" of the anonymous struct as "x.a". // // This function takes care of anonymous structs. static Node *struct_ref(Node *node, Token *tok) { add_type(node); if (node->ty->kind != TY_STRUCT && node->ty->kind != TY_UNION) error_tok(node->tok, "not a struct nor a union"); Type *ty = node->ty; for (;;) { Member *mem = get_struct_member(ty, tok); if (!mem) error_tok(tok, "no such member"); node = new_unary(ND_MEMBER, node, tok); node->member = mem; if (mem->name) break; ty = mem->ty; } return node; } // Convert A++ to `(typeof A)((A += 1) - 1)` static Node *new_inc_dec(Node *node, Token *tok, int addend) { add_type(node); return new_cast(new_add(to_assign(new_add(node, new_num(addend, tok), tok)), new_num(-addend, tok), tok), node->ty); } // postfix = "(" type-name ")" "{" initializer-list "}" // | ident "(" func-args ")" postfix-tail* // | primary postfix-tail* // // postfix-tail = "[" expr "]" // | "(" func-args ")" // | "." ident // | "->" ident // | "++" // | "--" static Node *postfix(Token **rest, Token *tok) { if (EQUAL(tok, "(") && is_typename(tok->next)) { // Compound literal Token *start = tok; Type *ty = typename(&tok, tok->next); tok = skip(tok, ')'); if (scope->next == NULL) { Obj *var = new_anon_gvar(ty); gvar_initializer(rest, tok, var); return new_var_node(var, start); } Obj *var = new_lvar("", ty); Node *lhs = lvar_initializer(rest, tok, var); Node *rhs = new_var_node(var, tok); return new_binary(ND_COMMA, lhs, rhs, start); } Node *node = primary(&tok, tok); for (;;) { if (tok->len == 1) { if (tok->loc[0] == '(') { node = funcall(&tok, tok->next, node); continue; } if (tok->loc[0] == '[') { // x[y] is short for *(x+y) Token *start = tok; Node *idx = expr(&tok, tok->next); tok = skip(tok, ']'); node = new_unary(ND_DEREF, new_add(node, idx, start), start); continue; } if (tok->loc[0] == '.') { node = struct_ref(node, tok->next); tok = tok->next->next; continue; } } else if (tok->len == 2) { if (tok->loc[0] == '-' && tok->loc[1] == '>') { // x->y is short for (*x).y node = new_unary(ND_DEREF, node, tok); node = struct_ref(node, tok->next); tok = tok->next->next; continue; } if (tok->loc[0] == '+' && tok->loc[1] == '+') { node = new_inc_dec(node, tok, 1); tok = tok->next; continue; } if (tok->loc[0] == '-' && tok->loc[1] == '-') { node = new_inc_dec(node, tok, -1); tok = tok->next; continue; } } *rest = tok; return node; } } // funcall = (assign ("," assign)*)? ")" static Node *funcall(Token **rest, Token *tok, Node *fn) { add_type(fn); if (fn->ty->kind != TY_FUNC && (fn->ty->kind != TY_PTR || fn->ty->base->kind != TY_FUNC)) { error_tok(fn->tok, "not a function"); } Type *ty = (fn->ty->kind == TY_FUNC) ? fn->ty : fn->ty->base; Type *param_ty = ty->params; Node head = {}; Node *cur = &head; while (!EQUAL(tok, ")")) { if (cur != &head) tok = skip(tok, ','); Node *arg = assign(&tok, tok); add_type(arg); if (!param_ty && !ty->is_variadic) error_tok(tok, "too many arguments"); if (param_ty) { if (param_ty->kind != TY_STRUCT && param_ty->kind != TY_UNION) { arg = new_cast(arg, param_ty); } param_ty = param_ty->next; } else if (arg->ty->kind == TY_FLOAT) { // If parameter type is omitted (e.g. in "..."), float // arguments are promoted to double. arg = new_cast(arg, ty_double); } cur = cur->next = arg; } if (param_ty) error_tok(tok, "too few arguments"); *rest = skip(tok, ')'); Node *node = new_unary(ND_FUNCALL, fn, tok); node->func_ty = ty; node->ty = ty->return_ty; node->args = head.next; // If a function returns a struct, it is caller's responsibility // to allocate a space for the return value. if (node->ty->kind == TY_STRUCT || node->ty->kind == TY_UNION) { node->ret_buffer = new_lvar("", node->ty); } return node; } // generic-selection = "(" assign "," generic-assoc ("," generic-assoc)* ")" // // generic-assoc = type-name ":" assign // | "default" ":" assign static Node *generic_selection(Token **rest, Token *tok) { Token *start = tok; tok = skip(tok, '('); Node *ctrl = assign(&tok, tok); add_type(ctrl); Type *t1 = ctrl->ty; if (t1->kind == TY_FUNC) t1 = pointer_to(t1); else if (t1->kind == TY_ARRAY) t1 = pointer_to(t1->base); Node *ret = NULL; while (!CONSUME(rest, tok, ")")) { tok = skip(tok, ','); if (EQUAL(tok, "default")) { tok = skip(tok->next, ':'); Node *node = assign(&tok, tok); if (!ret) ret = node; continue; } Type *t2 = typename(&tok, tok); tok = skip(tok, ':'); Node *node = assign(&tok, tok); if (is_compatible(t1, t2)) ret = node; } if (!ret) error_tok(start, "controlling expression type not compatible with" " any generic association type"); return ret; } static Node *ParseAtomic2(NodeKind kind, Token *tok, Token **rest) { Node *node = new_node(kind, tok); tok = skip(tok->next, '('); node->lhs = assign(&tok, tok); add_type(node->lhs); node->ty = node->lhs->ty->base; tok = skip(tok, ','); node->memorder = const_expr(&tok, tok); *rest = skip(tok, ')'); return node; } static Node *ParseAtomic3(NodeKind kind, Token *tok, Token **rest) { Node *node = new_node(kind, tok); tok = skip(tok->next, '('); node->lhs = assign(&tok, tok); add_type(node->lhs); node->ty = node->lhs->ty->base; tok = skip(tok, ','); node->rhs = assign(&tok, tok); add_type(node->rhs); tok = skip(tok, ','); node->memorder = const_expr(&tok, tok); *rest = skip(tok, ')'); return node; } // primary = "(" "{" stmt+ "}" ")" // | "(" expr ")" // | "sizeof" "(" type-name ")" // | "sizeof" unary // | "_Alignof" "(" type-name ")" // | "_Alignof" unary // | "_Generic" generic-selection // | "__builtin_constant_p" "(" expr ")" // | "__builtin_reg_class" "(" type-name ")" // | "__builtin_types_compatible_p" "(" type-name, type-name, ")" // | ident // | str // | num static Node *primary(Token **rest, Token *tok) { Token *start; unsigned char kw; start = tok; if ((kw = GetKw(tok->loc, tok->len))) { if (kw == KW_LP && EQUAL(tok->next, "{")) { // This is a GNU statement expresssion. Node *node = new_node(ND_STMT_EXPR, tok); node->body = compound_stmt(&tok, tok->next->next)->body; *rest = skip(tok, ')'); return node; } if (kw == KW_LP) { Node *node = expr(&tok, tok->next); *rest = skip(tok, ')'); return node; } if (kw == KW_SIZEOF && EQUAL(tok->next, "(") && is_typename(tok->next->next)) { Type *ty = typename(&tok, tok->next->next); *rest = skip(tok, ')'); if (ty->kind == TY_VLA) { if (ty->vla_size) { return new_var_node(ty->vla_size, tok); } Node *lhs = compute_vla_size(ty, tok); Node *rhs = new_var_node(ty->vla_size, tok); return new_binary(ND_COMMA, lhs, rhs, tok); } return new_ulong(ty->size, start); } if (kw == KW_SIZEOF) { Node *node = unary(rest, tok->next); add_type(node); if (node->ty->kind == TY_VLA) { return get_vla_size(node->ty, tok); } return new_ulong(node->ty->size, tok); } if ((kw == KW__ALIGNOF || kw == KW___ALIGNOF__) && EQUAL(tok->next, "(") && is_typename(tok->next->next)) { Type *ty = typename(&tok, tok->next->next); *rest = skip(tok, ')'); return new_ulong(ty->align, tok); } if ((kw == KW__ALIGNOF || kw == KW___ALIGNOF__)) { Node *node = unary(rest, tok->next); add_type(node); return new_ulong(node->ty->align, tok); } if (kw == KW__GENERIC) { return generic_selection(rest, tok->next); } if (kw == KW___BUILTIN_CONSTANT_P) { tok = skip(tok->next, '('); Node *e = assign(&tok, tok); *rest = skip(tok, ')'); return new_bool(is_const_expr(e), start); /* DCE */ } if (kw == KW___BUILTIN_TYPES_COMPATIBLE_P) { tok = skip(tok->next, '('); Type *t1 = typename(&tok, tok); tok = skip(tok, ','); Type *t2 = typename(&tok, tok); *rest = skip(tok, ')'); return new_bool(is_compatible(t1, t2), start); } if (kw == KW___BUILTIN_OFFSETOF) { tok = skip(tok->next, '('); Token *stok = tok; Type *tstruct = typename(&tok, tok); if (tstruct->kind != TY_STRUCT && tstruct->kind != TY_UNION) { error_tok(stok, "not a structure or union type"); } tok = skip(tok, ','); Token *member = tok; tok = tok->next; *rest = skip(tok, ')'); for (Member *m = tstruct->members; m; m = m->next) { if (m->name->len == member->len && !memcmp(m->name->loc, member->loc, m->name->len)) { return new_ulong(m->offset, start); } } error_tok(member, "no such member"); } if (kw == KW___BUILTIN_REG_CLASS) { tok = skip(tok->next, '('); Type *ty = typename(&tok, tok); *rest = skip(tok, ')'); if (is_integer(ty) || ty->kind == TY_PTR) return new_int(0, start); if (is_flonum(ty)) return new_int(1, start); return new_int(2, start); } if (kw == KW___ATOMIC_COMPARE_EXCHANGE_N) { Node *node = new_node(ND_CAS, tok); tok = skip(tok->next, '('); node->cas_addr = assign(&tok, tok); add_type(node->cas_addr); tok = skip(tok, ','); node->cas_old = assign(&tok, tok); add_type(node->cas_old); tok = skip(tok, ','); node->cas_new = assign(&tok, tok); add_type(node->cas_new); tok = skip(tok, ','); /* weak = */ const_expr(&tok, tok); tok = skip(tok, ','); node->memorder = const_expr(&tok, tok); tok = skip(tok, ','); /* memorder_failure = */ const_expr(&tok, tok); *rest = skip(tok, ')'); node->ty = node->cas_addr->ty->base; return node; } if (kw == KW___ATOMIC_EXCHANGE_N) { return ParseAtomic3(ND_EXCH_N, tok, rest); } if (kw == KW___ATOMIC_LOAD) { return ParseAtomic3(ND_LOAD, tok, rest); } if (kw == KW___ATOMIC_STORE) { return ParseAtomic3(ND_STORE, tok, rest); } if (kw == KW___ATOMIC_LOAD_N) { return ParseAtomic2(ND_LOAD_N, tok, rest); } if (kw == KW___ATOMIC_STORE_N) { return ParseAtomic3(ND_STORE_N, tok, rest); } if (kw == KW___ATOMIC_FETCH_ADD) { return ParseAtomic3(ND_FETCHADD, tok, rest); } if (kw == KW___ATOMIC_FETCH_SUB) { return ParseAtomic3(ND_FETCHSUB, tok, rest); } if (kw == KW___ATOMIC_FETCH_XOR) { return ParseAtomic3(ND_FETCHXOR, tok, rest); } if (kw == KW___ATOMIC_FETCH_AND) { return ParseAtomic3(ND_FETCHAND, tok, rest); } if (kw == KW___ATOMIC_FETCH_OR) { return ParseAtomic3(ND_FETCHOR, tok, rest); } if (kw == KW___ATOMIC_TEST_AND_SET) { return ParseAtomic2(ND_TESTANDSETA, tok, rest); } if (kw == KW___ATOMIC_CLEAR) { return ParseAtomic2(ND_CLEAR, tok, rest); } if (kw == KW___SYNC_LOCK_TEST_AND_SET) { // TODO(jart): delete me Node *node = new_node(ND_TESTANDSET, tok); tok = skip(tok->next, '('); node->lhs = assign(&tok, tok); add_type(node->lhs); node->ty = node->lhs->ty->base; tok = skip(tok, ','); node->rhs = assign(&tok, tok); *rest = skip(tok, ')'); return node; } if (kw == KW___SYNC_LOCK_RELEASE) { // TODO(jart): delete me Node *node = new_node(ND_RELEASE, tok); tok = skip(tok->next, '('); node->lhs = assign(&tok, tok); add_type(node->lhs); node->ty = node->lhs->ty->base; *rest = skip(tok, ')'); return node; } if (kw == KW___BUILTIN_IA32_MOVNTDQ) { Node *node = new_node(ND_MOVNTDQ, tok); tok = skip(tok->next, '('); node->lhs = assign(&tok, tok); add_type(node->lhs); node->ty = node->lhs->ty->base; tok = skip(tok, ','); node->rhs = assign(&tok, tok); add_type(node->rhs); *rest = skip(tok, ')'); return node; } if (kw == KW___BUILTIN_IA32_PMOVMSKB128) { Node *node = new_node(ND_PMOVMSKB, tok); tok = skip(tok->next, '('); node->lhs = assign(&tok, tok); add_type(node->lhs); node->ty = node->lhs->ty->base; *rest = skip(tok, ')'); return node; } if (kw == KW___BUILTIN_EXPECT) { /* do nothing */ tok = skip(tok->next, '('); Node *node = assign(&tok, tok); tok = skip(tok, ','); const_expr(&tok, tok); *rest = skip(tok, ')'); return node; } if (kw == KW___BUILTIN_ASSUME_ALIGNED) { /* do nothing */ tok = skip(tok->next, '('); Node *node = assign(&tok, tok); tok = skip(tok, ','); const_expr(&tok, tok); if (EQUAL(tok, ",")) { const_expr(&tok, tok->next); } *rest = skip(tok, ')'); return node; } if (kw == KW___BUILTIN_FPCLASSIFY) { Node *node = new_node(ND_FPCLASSIFY, tok); node->fpc = calloc(1, sizeof(FpClassify)); node->ty = ty_int; tok = skip(tok->next, '('); for (int i = 0; i < 5; ++i) { node->fpc->args[i] = const_expr(&tok, tok); tok = skip(tok, ','); } node->fpc->node = expr(&tok, tok); add_type(node->fpc->node); if (!is_flonum(node->fpc->node->ty)) { error_tok(node->fpc->node->tok, "need floating point"); } *rest = skip(tok, ')'); return node; } if (kw == KW___BUILTIN_POPCOUNT) { Token *t = skip(tok->next, '('); Node *node = assign(&t, t); if (is_const_expr(node)) { *rest = skip(t, ')'); return new_num(__builtin_popcount(eval(node)), t); } } if (kw == KW___BUILTIN_POPCOUNTL || kw == KW___BUILTIN_POPCOUNTLL) { Token *t = skip(tok->next, '('); Node *node = assign(&t, t); if (is_const_expr(node)) { *rest = skip(t, ')'); return new_num(__builtin_popcountl(eval(node)), t); } } if (kw == KW___BUILTIN_FFS) { Token *t = skip(tok->next, '('); Node *node = assign(&t, t); if (is_const_expr(node)) { *rest = skip(t, ')'); return new_num(__builtin_ffs(eval(node)), t); } } if (kw == KW___BUILTIN_FFSL || kw == KW___BUILTIN_FFSLL) { Token *t = skip(tok->next, '('); Node *node = assign(&t, t); if (is_const_expr(node)) { *rest = skip(t, ')'); return new_num(__builtin_ffsl(eval(node)), t); } } if ((kw == KW___BUILTIN_STRLEN || (!opt_no_builtin && kw == KW_STRLEN)) && EQUAL(tok->next, "(") && tok->next->next->kind == TK_STR && EQUAL(tok->next->next->next, ")")) { *rest = tok->next->next->next->next; return new_num(strlen(tok->next->next->str), tok); } if ((kw == KW___BUILTIN_STRPBRK || (!opt_no_builtin && kw == KW_STRPBRK))) { if (EQUAL(tok->next, "(") && tok->next->next->kind == TK_STR && EQUAL(tok->next->next->next, ",") && tok->next->next->next->next->kind == TK_STR && EQUAL(tok->next->next->next->next->next, ")")) { *rest = tok->next->next->next->next->next->next; char *res = strpbrk(tok->next->next->str, tok->next->next->next->next->str); if (res) { return new_var_node( new_string_literal(res, array_of(ty_char, strlen(res) + 1)), tok); } else { return new_num(0, tok); } } } if (kw == KW___BUILTIN_STRSTR || (!opt_no_builtin && kw == KW_STRSTR)) { if (EQUAL(tok->next, "(") && tok->next->next->kind == TK_STR && EQUAL(tok->next->next->next, ",") && tok->next->next->next->next->kind == TK_STR && EQUAL(tok->next->next->next->next->next, ")")) { *rest = tok->next->next->next->next->next->next; char *res = strstr(tok->next->next->str, tok->next->next->next->next->str); if (res) { return new_var_node( new_string_literal(res, array_of(ty_char, strlen(res) + 1)), tok); } else { return new_num(0, tok); } } } if (kw == KW___BUILTIN_STRCHR || (!opt_no_builtin && kw == KW_STRCHR)) { if (EQUAL(tok->next, "(") && tok->next->next->kind == TK_STR && EQUAL(tok->next->next->next, ",") && tok->next->next->next->next->kind == TK_NUM && EQUAL(tok->next->next->next->next->next, ")")) { *rest = tok->next->next->next->next->next->next; char *res = strchr(tok->next->next->str, tok->next->next->next->next->val); if (res) { return new_var_node( new_string_literal(res, array_of(ty_char, strlen(res) + 1)), tok); } else { return new_num(0, tok); } } } } if (tok->kind == TK_IDENT) { // Variable or enum constant VarScope *sc = find_var(tok); // [jart] support implicit function declarations with `long` type if (!sc && EQUAL(tok->next, "(")) { Type *ty = func_type(ty_long); ty->is_variadic = true; Obj *fn = new_var(strndup(tok->loc, tok->len), ty); fn->next = globals; fn->is_function = true; globals = fn; sc = find_var(tok); } *rest = tok->next; // For "static inline" function if (sc && sc->var && sc->var->is_function) { if (current_fn) { strarray_push(&current_fn->refs, sc->var->name); } else { sc->var->is_root = true; } } if (sc) { if (sc->var) return new_var_node(sc->var, tok); if (sc->enum_ty) return new_num(sc->enum_val, tok); } if (EQUAL(tok->next, "(")) { error_tok(tok, "implicit declaration of a function"); } error_tok(tok, "undefined variable"); } if (tok->kind == TK_STR) { Obj *var = new_string_literal(tok->str, tok->ty); *rest = tok->next; return new_var_node(var, tok); } if (tok->kind == TK_NUM) { Node *node; if (is_flonum(tok->ty)) { node = new_node(ND_NUM, tok); node->fval = tok->fval; } else { node = new_num(tok->val, tok); } node->ty = tok->ty; *rest = tok->next; return node; } error_tok(tok, "expected an expression"); } static Token *parse_typedef(Token *tok, Type *basety) { bool first = true; while (!CONSUME(&tok, tok, ";")) { if (!first) { tok = skip(tok, ','); } first = false; Type *ty = declarator(&tok, tok, basety); if (!ty->name) error_tok(ty->name_pos, "typedef name omitted"); tok = attribute_list(tok, ty, type_attributes); push_scope(get_ident(ty->name))->type_def = ty; } return tok; } static void create_param_lvars(Type *param) { if (param) { create_param_lvars(param->next); if (!param->name) error_tok(param->name_pos, "parameter name omitted"); new_lvar(get_ident(param->name), param); } } // This function matches gotos or labels-as-values with labels. // // We cannot resolve gotos as we parse a function because gotos // can refer a label that appears later in the function. // So, we need to do this after we parse the entire function. static void resolve_goto_labels(void) { for (Node *x = gotos; x; x = x->goto_next) { for (Node *y = labels; y; y = y->goto_next) { if (!strcmp(x->label, y->label)) { x->unique_label = y->unique_label; break; } } if (x->unique_label == NULL) { error_tok(x->tok->next, "use of undeclared label"); } } gotos = labels = NULL; } static Obj *find_func(char *name) { Scope *sc = scope; while (sc->next) sc = sc->next; VarScope *sc2 = hashmap_get(&sc->vars, name); if (sc2 && sc2->var && sc2->var->is_function) return sc2->var; return NULL; } static void mark_live(Obj *var) { int i; Obj *fn; if (!var->is_function || var->is_live) return; var->is_live = true; for (i = 0; i < var->refs.len; i++) { fn = find_func(var->refs.data[i]); if (fn) mark_live(fn); } } static Token *function(Token *tok, Type *basety, VarAttr *attr) { Type *ty = declarator(&tok, tok, basety); if (!ty->name) error_tok(ty->name_pos, "function name omitted"); char *name_str = get_ident(ty->name); Obj *fn = find_func(name_str); if (fn) { // Redeclaration if (!fn->is_function) error_tok(tok, "redeclared as a different kind of symbol"); if (fn->is_definition && EQUAL(tok, "{")) error_tok(tok, "redefinition of %s", name_str); if (!fn->is_static && attr->is_static) error_tok(tok, "static declaration follows a non-static declaration"); fn->is_definition = fn->is_definition || EQUAL(tok, "{"); fn->is_weak |= attr->is_weak; fn->is_noreturn |= attr->is_noreturn; fn->tok = ty->name; } else { fn = new_gvar(name_str, ty); fn->tok = ty->name; fn->is_function = true; fn->is_definition = EQUAL(tok, "{"); fn->is_static = attr->is_static || (attr->is_inline && !attr->is_extern); fn->is_inline = attr->is_inline; } fn->align = MAX(fn->align, attr->align); fn->is_weak |= attr->is_weak; fn->section = fn->section ?: attr->section; fn->is_ms_abi |= attr->is_ms_abi; fn->visibility = fn->visibility ?: attr->visibility; fn->is_aligned |= attr->is_aligned; fn->is_noreturn |= attr->is_noreturn; fn->is_destructor |= attr->is_destructor; fn->is_constructor |= attr->is_constructor; fn->is_externally_visible |= attr->is_externally_visible; fn->is_no_instrument_function |= attr->is_no_instrument_function; fn->is_force_align_arg_pointer |= attr->is_force_align_arg_pointer; fn->is_no_caller_saved_registers |= attr->is_no_caller_saved_registers; fn->is_root = !(fn->is_static && fn->is_inline); fn->javadown = fn->javadown ?: current_javadown; current_javadown = NULL; if (consume_attribute(&tok, tok, "asm")) { tok = skip(tok, '('); fn->asmname = ConsumeStringLiteral(&tok, tok); tok = skip(tok, ')'); } tok = attribute_list(tok, attr, thing_attributes); if (CONSUME(&tok, tok, ";")) return tok; current_fn = fn; locals = NULL; enter_scope(); create_param_lvars(ty->params); // A buffer for a struct/union return value is passed // as the hidden first parameter. Type *rty = ty->return_ty; if ((rty->kind == TY_STRUCT || rty->kind == TY_UNION) && rty->size > 16) { new_lvar("", pointer_to(rty)); } fn->params = locals; if (ty->is_variadic) { fn->va_area = new_lvar("__va_area__", array_of(ty_char, 136)); } fn->alloca_bottom = new_lvar("__alloca_size__", pointer_to(ty_char)); tok = skip(tok, '{'); // [https://www.sigbus.info/n1570#6.4.2.2p1] "__func__" is // automatically defined as a local variable containing the // current function name. push_scope("__func__")->var = new_string_literal(fn->name, array_of(ty_char, strlen(fn->name) + 1)); // [GNU] __FUNCTION__ is yet another name of __func__. push_scope("__FUNCTION__")->var = new_string_literal(fn->name, array_of(ty_char, strlen(fn->name) + 1)); fn->body = compound_stmt(&tok, tok); fn->locals = locals; leave_scope(); resolve_goto_labels(); return tok; } static Token *global_variable(Token *tok, Type *basety, VarAttr *attr) { bool first = true; bool isjavadown = tok->kind == TK_JAVADOWN; while (!CONSUME(&tok, tok, ";")) { if (!first) tok = skip(tok, ','); first = false; Type *ty = declarator(&tok, tok, basety); if (!ty->name) { if (isjavadown) { return tok; } else { error_tok(ty->name_pos, "variable name omitted"); } } Obj *var = new_gvar(get_ident(ty->name), ty); if (!var->tok) var->tok = ty->name; var->javadown = current_javadown; if (consume_attribute(&tok, tok, "asm")) { tok = skip(tok, '('); var->asmname = ConsumeStringLiteral(&tok, tok); tok = skip(tok, ')'); } tok = attribute_list(tok, attr, thing_attributes); var->align = MAX(var->align, attr->align); var->is_weak = attr->is_weak; var->section = attr->section; var->visibility = attr->visibility; var->is_aligned = var->is_aligned | attr->is_aligned; var->is_externally_visible = attr->is_externally_visible; var->is_definition = !attr->is_extern; var->is_static = attr->is_static; var->is_tls = attr->is_tls; var->section = attr->section; if (attr->align) var->align = attr->align; if (EQUAL(tok, "=")) { gvar_initializer(&tok, tok->next, var); } else if (!attr->is_extern && !attr->is_tls) { var->is_tentative = true; } } return tok; } // Lookahead tokens and returns true if a given token is a start // of a function definition or declaration. static bool is_function(Token *tok) { if (EQUAL(tok, ";")) return false; Type dummy = {}; Type *ty = declarator(&tok, tok, &dummy); return ty->kind == TY_FUNC; } // Remove redundant tentative definitions. static void scan_globals(void) { Obj head; Obj *cur = &head; for (Obj *var = globals; var; var = var->next) { if (!var->is_tentative) { cur = cur->next = var; continue; } // Find another definition of the same identifier. Obj *var2 = globals; for (; var2; var2 = var2->next) { if (var != var2 && var2->is_definition && !strcmp(var->name, var2->name)) { break; } } // If there's another definition, the tentative definition // is redundant if (!var2) cur = cur->next = var; } cur->next = NULL; globals = head.next; } static char *prefix_builtin(const char *name) { return xstrcat("__builtin_", name); } static Obj *declare0(char *name, Type *ret) { if (!opt_no_builtin) new_gvar(name, func_type(ret)); return new_gvar(prefix_builtin(name), func_type(ret)); } static Obj *declare1(char *name, Type *ret, Type *p1) { Type *ty = func_type(ret); ty->params = copy_type(p1); if (!opt_no_builtin) new_gvar(name, ty); return new_gvar(prefix_builtin(name), ty); } static Obj *declare2(char *name, Type *ret, Type *p1, Type *p2) { Type *ty = func_type(ret); ty->params = copy_type(p1); ty->params->next = copy_type(p2); if (!opt_no_builtin) new_gvar(name, ty); return new_gvar(prefix_builtin(name), ty); } static Obj *declare3(char *s, Type *r, Type *a, Type *b, Type *c) { Type *ty = func_type(r); ty->params = copy_type(a); ty->params->next = copy_type(b); ty->params->next->next = copy_type(c); if (!opt_no_builtin) new_gvar(s, ty); return new_gvar(prefix_builtin(s), ty); } static void math0(char *name) { declare0(name, ty_double); declare0(xstrcat(name, 'f'), ty_float); declare0(xstrcat(name, 'l'), ty_ldouble); } static void math1(char *name) { declare1(name, ty_double, ty_double); declare1(xstrcat(name, 'f'), ty_float, ty_float); declare1(xstrcat(name, 'l'), ty_ldouble, ty_ldouble); } static void math2(char *name) { declare2(name, ty_double, ty_double, ty_double); declare2(xstrcat(name, 'f'), ty_float, ty_float, ty_float); declare2(xstrcat(name, 'l'), ty_ldouble, ty_ldouble, ty_ldouble); } void declare_builtin_functions(void) { Type *pvoid = pointer_to(ty_void); Type *pchar = pointer_to(ty_char); builtin_alloca = declare1("alloca", pointer_to(ty_void), ty_int); declare0("trap", ty_int); declare0("ia32_pause", ty_void); declare0("unreachable", ty_int); declare1("ctz", ty_int, ty_int); declare1("ctzl", ty_int, ty_long); declare1("ctzll", ty_int, ty_long); declare1("clz", ty_int, ty_int); declare1("clzl", ty_int, ty_long); declare1("clzll", ty_int, ty_long); declare1("ffs", ty_int, ty_int); declare1("ffsl", ty_int, ty_long); declare1("ffsll", ty_int, ty_long); declare1("bswap16", ty_ushort, ty_ushort); declare1("bswap32", ty_uint, ty_uint); declare1("bswap64", ty_ulong, ty_ulong); declare1("popcount", ty_int, ty_uint); declare1("popcountl", ty_long, ty_ulong); declare1("popcountll", ty_long, ty_ulong); declare1("signbitf", ty_int, ty_float); declare1("signbit", ty_long, ty_double); declare1("signbitl", ty_int, ty_ldouble); declare1("nanf", ty_float, pchar); declare1("nan", ty_double, pchar); declare1("nanl", ty_ldouble, pchar); declare1("isnan", ty_int, ty_double); declare1("isinf", ty_int, ty_double); declare1("isfinite", ty_int, ty_double); declare2("isgreater", ty_int, ty_double, ty_double); declare2("isgreaterequal", ty_int, ty_double, ty_double); declare2("isless", ty_int, ty_double, ty_double); declare2("islessequal", ty_int, ty_double, ty_double); declare2("islessgreater", ty_int, ty_double, ty_double); declare2("isunordered", ty_int, ty_double, ty_double); declare2("strpbrk", pchar, pchar, pchar); declare3("memcpy", pvoid, pvoid, pvoid, ty_ulong); declare3("memset", pvoid, pvoid, ty_int, ty_ulong); declare1("strlen", ty_ulong, pchar); declare2("strchr", pchar, pchar, ty_int); declare2("strstr", pchar, pchar, pchar); declare1("frame_address", pvoid, ty_int); declare2("scalbnf", ty_float, ty_float, ty_int); declare2("scalbn", ty_double, ty_double, ty_int); declare2("scalbnl", ty_ldouble, ty_ldouble, ty_int); math0("inf"); math0("huge_val"); math1("fabs"); math1("logb"); math2("fmax"); math2("fmin"); math2("copysign"); } // program = (typedef | function-definition | global-variable)* Obj *parse(Token *tok) { declare_builtin_functions(); globals = NULL; while (tok->kind != TK_EOF) { if (EQUAL(tok, "asm") || EQUAL(tok, "__asm__")) { StaticAsm *a = calloc(1, sizeof(StaticAsm)); a->next = staticasms; a->body = asm_stmt(&tok, tok); staticasms = a; continue; } if (EQUAL(tok, "_Static_assert")) { tok = static_assertion(tok); continue; } if (tok->kind == TK_JAVADOWN) { current_javadown = tok; tok = tok->next; } else { current_javadown = NULL; } VarAttr attr = {}; tok = attribute_list(tok, &attr, thing_attributes); Type *basety = declspec(&tok, tok, &attr); if (attr.is_typedef) { tok = parse_typedef(tok, basety); continue; } if (is_function(tok)) { tok = function(tok, basety, &attr); continue; } tok = global_variable(tok, basety, &attr); } for (Obj *var = globals; var; var = var->next) { if (var->is_root) { mark_live(var); } } scan_globals(); // remove redundant tentative definitions return globals; }
61550eff1a8e8150b777b3867798eeede1f33968
70a79d90a6a037071c41236ca0498f3e313ff1ce
/vpr/src/draw/buttons.h
853ad4cb50b5e069d8a1b9fcf2469cdf856d7505
[ "MIT", "MIT-Modern-Variant", "LicenseRef-scancode-unknown-license-reference" ]
permissive
verilog-to-routing/vtr-verilog-to-routing
7f327e74394fb35ca90d90c48e62df8db6080513
ef5f993959c6b6896f6821b14b361d581ebf46fe
refs/heads/master
2023-09-01T04:19:02.151710
2023-08-31T20:57:20
2023-08-31T20:57:20
38,118,370
898
403
NOASSERTION
2023-09-14T15:30:08
2015-06-26T15:24:42
C++
UTF-8
C
false
false
331
h
buttons.h
#ifndef BUTTONS_H #define BUTTONS_H #ifndef NO_GRAPHICS # include "draw_global.h" # include "ezgl/point.hpp" # include "ezgl/application.hpp" # include "ezgl/graphics.hpp" void delete_button(const char* button_name); GtkWidget* find_button(const char* button_name); #endif /* NO_GRAPHICS */ #endif /* BUTTONS_H */
c7053a9c35ed8080513b7f40bfa975634f1e943f
1f5eaf93c1ccfa0ec14a77ddec5b3c54cab7e57f
/src/dds.h
dddab1a8117f80a30ba45c31cda335771951ccbf
[ "GPL-1.0-or-later", "Apache-2.0" ]
permissive
dds-bridge/dds
6b7bb47f6ab183c23408818815c4279356ed3b94
d2bc4c2c703941664fc1d73e69caa5233cdeac18
refs/heads/develop
2022-10-13T13:15:27.930490
2020-07-25T12:24:25
2020-07-25T12:24:25
26,988,206
193
90
Apache-2.0
2023-08-28T11:56:51
2014-11-22T04:10:21
C++
UTF-8
C
false
false
3,098
h
dds.h
/* DDS, a bridge double dummy solver. Copyright (C) 2006-2014 by Bo Haglund / 2014-2018 by Bo Haglund & Soren Hein. See LICENSE and README. */ #ifndef DDS_DDS_H #define DDS_DDS_H #include "../include/portab.h" #include "../include/dll.h" #if defined(DDS_MEMORY_LEAKS) && defined(_MSC_VER) #define DDS_MEMORY_LEAKS_WIN32 #define _CRTDBG_MAP_ALLOC #include <crtdbg.h> #endif #define THREADMEM_SMALL_MAX_MB 30 #define THREADMEM_SMALL_DEF_MB 20 #define THREADMEM_LARGE_MAX_MB 160 #define THREADMEM_LARGE_DEF_MB 95 #define MAXNODE 1 #define MINNODE 0 #define SIMILARDEALLIMIT 5 #define SIMILARMAXWINNODES 700000 #define DDS_NOTRUMP 4 /* "hand" is leading hand, "relative" is hand relative leading hand. The handId macro implementation follows a solution by Thomas Andrews. All hand identities are given as 0=NORTH, 1=EAST, 2=SOUTH, 3=WEST. */ #define handId(hand, relative) (hand + relative) & 3 extern int lho[DDS_HANDS]; extern int rho[DDS_HANDS]; extern int partner[DDS_HANDS]; extern unsigned short int bitMapRank[16]; extern unsigned char cardRank[16]; extern unsigned char cardSuit[DDS_STRAINS]; extern unsigned char cardHand[DDS_HANDS]; // These five together take up 440 KB extern int highestRank[8192]; extern int lowestRank[8192]; extern int counttable[8192]; extern char relRank[8192][15]; extern unsigned short int winRanks[8192][14]; struct moveGroupType { // There are at most 7 groups of bit "runs" in a 13-bit vector int lastGroup; int rank[7]; int sequence[7]; int fullseq[7]; int gap[7]; }; extern moveGroupType groupData[8192]; struct moveType { int suit; int rank; int sequence; /* Whether or not this move is the first in a sequence */ int weight; /* Weight used at sorting */ }; struct movePlyType { moveType move[14]; int current; int last; }; struct highCardType { int rank; int hand; }; struct pos { unsigned short int rankInSuit[DDS_HANDS][DDS_SUITS]; unsigned short int aggr[DDS_SUITS]; unsigned char length[DDS_HANDS][DDS_SUITS]; int handDist[DDS_HANDS]; unsigned short int winRanks[50][DDS_SUITS]; /* Cards that win by rank, firstindex is depth. */ int first[50]; /* Hand that leads the trick for each ply */ moveType move[50]; /* Presently winning move */ int handRelFirst; /* The current hand, relative first hand */ int tricksMAX; /* Aggregated tricks won by MAX */ highCardType winner[DDS_SUITS]; /* Winning rank of trick. */ highCardType secondBest[DDS_SUITS]; /* Second best rank. */ }; struct evalType { int tricks; unsigned short int winRanks[DDS_SUITS]; }; struct card { int suit; int rank; }; struct extCard { int suit; int rank; int sequence; }; struct absRankType // 2 bytes { char rank; signed char hand; }; struct relRanksType // 120 bytes { absRankType absRank[15][DDS_SUITS]; }; struct paramType { int noOfBoards; boards * bop; solvedBoards * solvedp; int error; }; enum RunMode { DDS_RUN_SOLVE = 0, DDS_RUN_CALC = 1, DDS_RUN_TRACE = 2, DDS_RUN_SIZE = 3 }; #endif
0d96f5a05f85bb1ec63fa4cad0dbeac310ce6c9b
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/drivers/usb/gadget/f_hid.c
6e69a8e8d22a7c7468994fd40eab738bddb52d1c
[ "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
19,805
c
f_hid.c
/* * f_hid.c -- USB HID function driver * * Copyright (C) 2010 Fabien Chouteau <fabien.chouteau@barco.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/hid.h> #include <linux/cdev.h> #include <linux/mutex.h> #include <linux/poll.h> #include <linux/uaccess.h> #include <linux/wait.h> #include <linux/sched.h> #include <linux/usb/g_hid.h> static int major, minors; static struct class *hidg_class; /*-------------------------------------------------------------------------*/ /* HID gadget struct */ struct f_hidg_req_list { struct usb_request *req; unsigned int pos; struct list_head list; }; struct f_hidg { /* configuration */ unsigned char bInterfaceSubClass; unsigned char bInterfaceProtocol; unsigned short report_desc_length; char *report_desc; unsigned short report_length; /* recv report */ struct list_head completed_out_req; spinlock_t spinlock; wait_queue_head_t read_queue; unsigned int qlen; /* send report */ struct mutex lock; bool write_pending; wait_queue_head_t write_queue; struct usb_request *req; int minor; struct cdev cdev; struct usb_function func; struct usb_ep *in_ep; struct usb_ep *out_ep; }; static inline struct f_hidg *func_to_hidg(struct usb_function *f) { return container_of(f, struct f_hidg, func); } /*-------------------------------------------------------------------------*/ /* Static descriptors */ static struct usb_interface_descriptor hidg_interface_desc = { .bLength = sizeof hidg_interface_desc, .bDescriptorType = USB_DT_INTERFACE, /* .bInterfaceNumber = DYNAMIC */ .bAlternateSetting = 0, .bNumEndpoints = 2, .bInterfaceClass = USB_CLASS_HID, /* .bInterfaceSubClass = DYNAMIC */ /* .bInterfaceProtocol = DYNAMIC */ /* .iInterface = DYNAMIC */ }; static struct hid_descriptor hidg_desc = { .bLength = sizeof hidg_desc, .bDescriptorType = HID_DT_HID, .bcdHID = 0x0101, .bCountryCode = 0x00, .bNumDescriptors = 0x1, /*.desc[0].bDescriptorType = DYNAMIC */ /*.desc[0].wDescriptorLenght = DYNAMIC */ }; /* High-Speed Support */ static struct usb_endpoint_descriptor hidg_hs_in_ep_desc = { .bLength = USB_DT_ENDPOINT_SIZE, .bDescriptorType = USB_DT_ENDPOINT, .bEndpointAddress = USB_DIR_IN, .bmAttributes = USB_ENDPOINT_XFER_INT, /*.wMaxPacketSize = DYNAMIC */ .bInterval = 4, /* FIXME: Add this field in the * HID gadget configuration? * (struct hidg_func_descriptor) */ }; static struct usb_endpoint_descriptor hidg_hs_out_ep_desc = { .bLength = USB_DT_ENDPOINT_SIZE, .bDescriptorType = USB_DT_ENDPOINT, .bEndpointAddress = USB_DIR_OUT, .bmAttributes = USB_ENDPOINT_XFER_INT, /*.wMaxPacketSize = DYNAMIC */ .bInterval = 4, /* FIXME: Add this field in the * HID gadget configuration? * (struct hidg_func_descriptor) */ }; static struct usb_descriptor_header *hidg_hs_descriptors[] = { (struct usb_descriptor_header *)&hidg_interface_desc, (struct usb_descriptor_header *)&hidg_desc, (struct usb_descriptor_header *)&hidg_hs_in_ep_desc, (struct usb_descriptor_header *)&hidg_hs_out_ep_desc, NULL, }; /* Full-Speed Support */ static struct usb_endpoint_descriptor hidg_fs_in_ep_desc = { .bLength = USB_DT_ENDPOINT_SIZE, .bDescriptorType = USB_DT_ENDPOINT, .bEndpointAddress = USB_DIR_IN, .bmAttributes = USB_ENDPOINT_XFER_INT, /*.wMaxPacketSize = DYNAMIC */ .bInterval = 10, /* FIXME: Add this field in the * HID gadget configuration? * (struct hidg_func_descriptor) */ }; static struct usb_endpoint_descriptor hidg_fs_out_ep_desc = { .bLength = USB_DT_ENDPOINT_SIZE, .bDescriptorType = USB_DT_ENDPOINT, .bEndpointAddress = USB_DIR_OUT, .bmAttributes = USB_ENDPOINT_XFER_INT, /*.wMaxPacketSize = DYNAMIC */ .bInterval = 10, /* FIXME: Add this field in the * HID gadget configuration? * (struct hidg_func_descriptor) */ }; static struct usb_descriptor_header *hidg_fs_descriptors[] = { (struct usb_descriptor_header *)&hidg_interface_desc, (struct usb_descriptor_header *)&hidg_desc, (struct usb_descriptor_header *)&hidg_fs_in_ep_desc, (struct usb_descriptor_header *)&hidg_fs_out_ep_desc, NULL, }; /*-------------------------------------------------------------------------*/ /* Char Device */ static ssize_t f_hidg_read(struct file *file, char __user *buffer, size_t count, loff_t *ptr) { struct f_hidg *hidg = file->private_data; struct f_hidg_req_list *list; struct usb_request *req; unsigned long flags; int ret; if (!count) return 0; if (!access_ok(VERIFY_WRITE, buffer, count)) return -EFAULT; spin_lock_irqsave(&hidg->spinlock, flags); #define READ_COND (!list_empty(&hidg->completed_out_req)) /* wait for at least one buffer to complete */ while (!READ_COND) { spin_unlock_irqrestore(&hidg->spinlock, flags); if (file->f_flags & O_NONBLOCK) return -EAGAIN; if (wait_event_interruptible(hidg->read_queue, READ_COND)) return -ERESTARTSYS; spin_lock_irqsave(&hidg->spinlock, flags); } /* pick the first one */ list = list_first_entry(&hidg->completed_out_req, struct f_hidg_req_list, list); req = list->req; count = min_t(unsigned int, count, req->actual - list->pos); spin_unlock_irqrestore(&hidg->spinlock, flags); /* copy to user outside spinlock */ count -= copy_to_user(buffer, req->buf + list->pos, count); list->pos += count; /* * if this request is completely handled and transfered to * userspace, remove its entry from the list and requeue it * again. Otherwise, we will revisit it again upon the next * call, taking into account its current read position. */ if (list->pos == req->actual) { spin_lock_irqsave(&hidg->spinlock, flags); list_del(&list->list); kfree(list); spin_unlock_irqrestore(&hidg->spinlock, flags); req->length = hidg->report_length; ret = usb_ep_queue(hidg->out_ep, req, GFP_KERNEL); if (ret < 0) return ret; } return count; } static void f_hidg_req_complete(struct usb_ep *ep, struct usb_request *req) { struct f_hidg *hidg = (struct f_hidg *)ep->driver_data; if (req->status != 0) { ERROR(hidg->func.config->cdev, "End Point Request ERROR: %d\n", req->status); } hidg->write_pending = 0; wake_up(&hidg->write_queue); } static ssize_t f_hidg_write(struct file *file, const char __user *buffer, size_t count, loff_t *offp) { struct f_hidg *hidg = file->private_data; ssize_t status = -ENOMEM; if (!access_ok(VERIFY_READ, buffer, count)) return -EFAULT; mutex_lock(&hidg->lock); #define WRITE_COND (!hidg->write_pending) /* write queue */ while (!WRITE_COND) { mutex_unlock(&hidg->lock); if (file->f_flags & O_NONBLOCK) return -EAGAIN; if (wait_event_interruptible_exclusive( hidg->write_queue, WRITE_COND)) return -ERESTARTSYS; mutex_lock(&hidg->lock); } count = min_t(unsigned, count, hidg->report_length); status = copy_from_user(hidg->req->buf, buffer, count); if (status != 0) { ERROR(hidg->func.config->cdev, "copy_from_user error\n"); mutex_unlock(&hidg->lock); return -EINVAL; } hidg->req->status = 0; hidg->req->zero = 0; hidg->req->length = count; hidg->req->complete = f_hidg_req_complete; hidg->req->context = hidg; hidg->write_pending = 1; status = usb_ep_queue(hidg->in_ep, hidg->req, GFP_ATOMIC); if (status < 0) { ERROR(hidg->func.config->cdev, "usb_ep_queue error on int endpoint %zd\n", status); hidg->write_pending = 0; wake_up(&hidg->write_queue); } else { status = count; } mutex_unlock(&hidg->lock); return status; } static unsigned int f_hidg_poll(struct file *file, poll_table *wait) { struct f_hidg *hidg = file->private_data; unsigned int ret = 0; poll_wait(file, &hidg->read_queue, wait); poll_wait(file, &hidg->write_queue, wait); if (WRITE_COND) ret |= POLLOUT | POLLWRNORM; if (READ_COND) ret |= POLLIN | POLLRDNORM; return ret; } #undef WRITE_COND #undef READ_COND static int f_hidg_release(struct inode *inode, struct file *fd) { fd->private_data = NULL; return 0; } static int f_hidg_open(struct inode *inode, struct file *fd) { struct f_hidg *hidg = container_of(inode->i_cdev, struct f_hidg, cdev); fd->private_data = hidg; return 0; } /*-------------------------------------------------------------------------*/ /* usb_function */ static struct usb_request *hidg_alloc_ep_req(struct usb_ep *ep, unsigned length) { struct usb_request *req; req = usb_ep_alloc_request(ep, GFP_ATOMIC); if (req) { req->length = length; req->buf = kmalloc(length, GFP_ATOMIC); if (!req->buf) { usb_ep_free_request(ep, req); req = NULL; } } return req; } static void hidg_set_report_complete(struct usb_ep *ep, struct usb_request *req) { struct f_hidg *hidg = (struct f_hidg *) req->context; struct f_hidg_req_list *req_list; unsigned long flags; req_list = kzalloc(sizeof(*req_list), GFP_ATOMIC); if (!req_list) return; req_list->req = req; spin_lock_irqsave(&hidg->spinlock, flags); list_add_tail(&req_list->list, &hidg->completed_out_req); spin_unlock_irqrestore(&hidg->spinlock, flags); wake_up(&hidg->read_queue); } static int hidg_setup(struct usb_function *f, const struct usb_ctrlrequest *ctrl) { struct f_hidg *hidg = func_to_hidg(f); struct usb_composite_dev *cdev = f->config->cdev; struct usb_request *req = cdev->req; int status = 0; __u16 value, length; value = __le16_to_cpu(ctrl->wValue); length = __le16_to_cpu(ctrl->wLength); VDBG(cdev, "hid_setup crtl_request : bRequestType:0x%x bRequest:0x%x " "Value:0x%x\n", ctrl->bRequestType, ctrl->bRequest, value); switch ((ctrl->bRequestType << 8) | ctrl->bRequest) { case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8 | HID_REQ_GET_REPORT): VDBG(cdev, "get_report\n"); /* send an empty report */ length = min_t(unsigned, length, hidg->report_length); memset(req->buf, 0x0, length); goto respond; break; case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8 | HID_REQ_GET_PROTOCOL): VDBG(cdev, "get_protocol\n"); goto stall; break; case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8 | HID_REQ_SET_REPORT): VDBG(cdev, "set_report | wLenght=%d\n", ctrl->wLength); goto stall; break; case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8 | HID_REQ_SET_PROTOCOL): VDBG(cdev, "set_protocol\n"); goto stall; break; case ((USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_INTERFACE) << 8 | USB_REQ_GET_DESCRIPTOR): switch (value >> 8) { case HID_DT_HID: VDBG(cdev, "USB_REQ_GET_DESCRIPTOR: HID\n"); length = min_t(unsigned short, length, hidg_desc.bLength); memcpy(req->buf, &hidg_desc, length); goto respond; break; case HID_DT_REPORT: VDBG(cdev, "USB_REQ_GET_DESCRIPTOR: REPORT\n"); length = min_t(unsigned short, length, hidg->report_desc_length); memcpy(req->buf, hidg->report_desc, length); goto respond; break; default: VDBG(cdev, "Unknown descriptor request 0x%x\n", value >> 8); goto stall; break; } break; default: VDBG(cdev, "Unknown request 0x%x\n", ctrl->bRequest); goto stall; break; } stall: return -EOPNOTSUPP; respond: req->zero = 0; req->length = length; status = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC); if (status < 0) ERROR(cdev, "usb_ep_queue error on ep0 %d\n", value); return status; } static void hidg_disable(struct usb_function *f) { struct f_hidg *hidg = func_to_hidg(f); struct f_hidg_req_list *list, *next; usb_ep_disable(hidg->in_ep); hidg->in_ep->driver_data = NULL; usb_ep_disable(hidg->out_ep); hidg->out_ep->driver_data = NULL; list_for_each_entry_safe(list, next, &hidg->completed_out_req, list) { list_del(&list->list); kfree(list); } } static int hidg_set_alt(struct usb_function *f, unsigned intf, unsigned alt) { struct usb_composite_dev *cdev = f->config->cdev; struct f_hidg *hidg = func_to_hidg(f); int i, status = 0; VDBG(cdev, "hidg_set_alt intf:%d alt:%d\n", intf, alt); if (hidg->in_ep != NULL) { /* restart endpoint */ if (hidg->in_ep->driver_data != NULL) usb_ep_disable(hidg->in_ep); status = config_ep_by_speed(f->config->cdev->gadget, f, hidg->in_ep); if (status) { ERROR(cdev, "config_ep_by_speed FAILED!\n"); goto fail; } status = usb_ep_enable(hidg->in_ep); if (status < 0) { ERROR(cdev, "Enable IN endpoint FAILED!\n"); goto fail; } hidg->in_ep->driver_data = hidg; } if (hidg->out_ep != NULL) { /* restart endpoint */ if (hidg->out_ep->driver_data != NULL) usb_ep_disable(hidg->out_ep); status = config_ep_by_speed(f->config->cdev->gadget, f, hidg->out_ep); if (status) { ERROR(cdev, "config_ep_by_speed FAILED!\n"); goto fail; } status = usb_ep_enable(hidg->out_ep); if (status < 0) { ERROR(cdev, "Enable IN endpoint FAILED!\n"); goto fail; } hidg->out_ep->driver_data = hidg; /* * allocate a bunch of read buffers and queue them all at once. */ for (i = 0; i < hidg->qlen && status == 0; i++) { struct usb_request *req = hidg_alloc_ep_req(hidg->out_ep, hidg->report_length); if (req) { req->complete = hidg_set_report_complete; req->context = hidg; status = usb_ep_queue(hidg->out_ep, req, GFP_ATOMIC); if (status) ERROR(cdev, "%s queue req --> %d\n", hidg->out_ep->name, status); } else { usb_ep_disable(hidg->out_ep); hidg->out_ep->driver_data = NULL; status = -ENOMEM; goto fail; } } } fail: return status; } const struct file_operations f_hidg_fops = { .owner = THIS_MODULE, .open = f_hidg_open, .release = f_hidg_release, .write = f_hidg_write, .read = f_hidg_read, .poll = f_hidg_poll, .llseek = noop_llseek, }; static int __init hidg_bind(struct usb_configuration *c, struct usb_function *f) { struct usb_ep *ep; struct f_hidg *hidg = func_to_hidg(f); int status; dev_t dev; /* allocate instance-specific interface IDs, and patch descriptors */ status = usb_interface_id(c, f); if (status < 0) goto fail; hidg_interface_desc.bInterfaceNumber = status; /* allocate instance-specific endpoints */ status = -ENODEV; ep = usb_ep_autoconfig(c->cdev->gadget, &hidg_fs_in_ep_desc); if (!ep) goto fail; ep->driver_data = c->cdev; /* claim */ hidg->in_ep = ep; ep = usb_ep_autoconfig(c->cdev->gadget, &hidg_fs_out_ep_desc); if (!ep) goto fail; ep->driver_data = c->cdev; /* claim */ hidg->out_ep = ep; /* preallocate request and buffer */ status = -ENOMEM; hidg->req = usb_ep_alloc_request(hidg->in_ep, GFP_KERNEL); if (!hidg->req) goto fail; hidg->req->buf = kmalloc(hidg->report_length, GFP_KERNEL); if (!hidg->req->buf) goto fail; /* set descriptor dynamic values */ hidg_interface_desc.bInterfaceSubClass = hidg->bInterfaceSubClass; hidg_interface_desc.bInterfaceProtocol = hidg->bInterfaceProtocol; hidg_hs_in_ep_desc.wMaxPacketSize = cpu_to_le16(hidg->report_length); hidg_fs_in_ep_desc.wMaxPacketSize = cpu_to_le16(hidg->report_length); hidg_hs_out_ep_desc.wMaxPacketSize = cpu_to_le16(hidg->report_length); hidg_fs_out_ep_desc.wMaxPacketSize = cpu_to_le16(hidg->report_length); hidg_desc.desc[0].bDescriptorType = HID_DT_REPORT; hidg_desc.desc[0].wDescriptorLength = cpu_to_le16(hidg->report_desc_length); hidg_hs_in_ep_desc.bEndpointAddress = hidg_fs_in_ep_desc.bEndpointAddress; hidg_hs_out_ep_desc.bEndpointAddress = hidg_fs_out_ep_desc.bEndpointAddress; status = usb_assign_descriptors(f, hidg_fs_descriptors, hidg_hs_descriptors, NULL); if (status) goto fail; mutex_init(&hidg->lock); spin_lock_init(&hidg->spinlock); init_waitqueue_head(&hidg->write_queue); init_waitqueue_head(&hidg->read_queue); INIT_LIST_HEAD(&hidg->completed_out_req); /* create char device */ cdev_init(&hidg->cdev, &f_hidg_fops); dev = MKDEV(major, hidg->minor); status = cdev_add(&hidg->cdev, dev, 1); if (status) goto fail; device_create(hidg_class, NULL, dev, NULL, "%s%d", "hidg", hidg->minor); return 0; fail: ERROR(f->config->cdev, "hidg_bind FAILED\n"); if (hidg->req != NULL) { kfree(hidg->req->buf); if (hidg->in_ep != NULL) usb_ep_free_request(hidg->in_ep, hidg->req); } usb_free_all_descriptors(f); return status; } static void hidg_unbind(struct usb_configuration *c, struct usb_function *f) { struct f_hidg *hidg = func_to_hidg(f); device_destroy(hidg_class, MKDEV(major, hidg->minor)); cdev_del(&hidg->cdev); /* disable/free request and end point */ usb_ep_disable(hidg->in_ep); usb_ep_dequeue(hidg->in_ep, hidg->req); kfree(hidg->req->buf); usb_ep_free_request(hidg->in_ep, hidg->req); usb_free_all_descriptors(f); kfree(hidg->report_desc); kfree(hidg); } /*-------------------------------------------------------------------------*/ /* Strings */ #define CT_FUNC_HID_IDX 0 static struct usb_string ct_func_string_defs[] = { [CT_FUNC_HID_IDX].s = "HID Interface", {}, /* end of list */ }; static struct usb_gadget_strings ct_func_string_table = { .language = 0x0409, /* en-US */ .strings = ct_func_string_defs, }; static struct usb_gadget_strings *ct_func_strings[] = { &ct_func_string_table, NULL, }; /*-------------------------------------------------------------------------*/ /* usb_configuration */ int __init hidg_bind_config(struct usb_configuration *c, struct hidg_func_descriptor *fdesc, int index) { struct f_hidg *hidg; int status; if (index >= minors) return -ENOENT; /* maybe allocate device-global string IDs, and patch descriptors */ if (ct_func_string_defs[CT_FUNC_HID_IDX].id == 0) { status = usb_string_id(c->cdev); if (status < 0) return status; ct_func_string_defs[CT_FUNC_HID_IDX].id = status; hidg_interface_desc.iInterface = status; } /* allocate and initialize one new instance */ hidg = kzalloc(sizeof *hidg, GFP_KERNEL); if (!hidg) return -ENOMEM; hidg->minor = index; hidg->bInterfaceSubClass = fdesc->subclass; hidg->bInterfaceProtocol = fdesc->protocol; hidg->report_length = fdesc->report_length; hidg->report_desc_length = fdesc->report_desc_length; hidg->report_desc = kmemdup(fdesc->report_desc, fdesc->report_desc_length, GFP_KERNEL); if (!hidg->report_desc) { kfree(hidg); return -ENOMEM; } hidg->func.name = "hid"; hidg->func.strings = ct_func_strings; hidg->func.bind = hidg_bind; hidg->func.unbind = hidg_unbind; hidg->func.set_alt = hidg_set_alt; hidg->func.disable = hidg_disable; hidg->func.setup = hidg_setup; /* this could me made configurable at some point */ hidg->qlen = 4; status = usb_add_function(c, &hidg->func); if (status) kfree(hidg); return status; } int __init ghid_setup(struct usb_gadget *g, int count) { int status; dev_t dev; hidg_class = class_create(THIS_MODULE, "hidg"); status = alloc_chrdev_region(&dev, 0, count, "hidg"); if (!status) { major = MAJOR(dev); minors = count; } return status; } void ghid_cleanup(void) { if (major) { unregister_chrdev_region(MKDEV(major, 0), minors); major = minors = 0; } class_destroy(hidg_class); hidg_class = NULL; }
60519484cea8a6beb1a8d957f38397caaed5f0f3
7df190df28da7e4ff166e55dc8ce780f11236a9f
/src/router/wiviz2/structs.h
e79d6a2f702c3f024f3416b55d5375f51061c545
[]
no_license
mirror/dd-wrt
25416946e6132aa54b35809de61834a1825a9a36
8f2934a5a2adfbb59b471375aa3a38de5d036531
refs/heads/master
2023-08-31T14:54:47.496685
2023-08-30T17:40:54
2023-08-30T17:40:54
7,470,282
520
281
null
2023-05-29T20:56:24
2013-01-06T17:21:29
null
UTF-8
C
false
false
4,729
h
structs.h
//Structure definitions for wireless packets #define MAX_HOSTS 257 #ifdef DEFINE_TYPES typedef unsigned short u_short; typedef unsigned char u_char; typedef unsigned int u_int; #endif typedef enum { mgt_assocRequest = 0x00, mgt_assocResponse = 0x10, mgt_reassocRequest = 0x20, mgt_reassocResponse = 0x30, mgt_probeRequest = 0x40, mgt_probeResponse = 0x50, mgt_beacon = 0x80, mgt_atim = 0x90, mgt_disassoc = 0xa0, mgt_auth = 0xb0, mgt_deauth = 0xc0 } wifi_frametype; struct ieee80211_mtik_ie_data { u_char data1[2]; /* unknown yet 0x011e */ u_char flags; /* 4(100) - wds, 1(1) - nstream, 8(1000) - pooling, 0 - none */ u_char data2[3]; /* unknown yet fill with zero */ u_char version[4]; /* little endian version. Use 0x1f660902 */ u_char pad1; /* a kind of padding, 0xff */ u_char namelen; /* length of radio name. Change with caution. 0x0f is safe value */ u_char radioname[15]; /* Radio name */ u_char pad2[5]; /* unknown. fill with zero */ } __attribute__((packed)); struct ieee80211_mtik_ie { u_char id; /* IEEE80211_ELEMID_VENDOR */ u_char len; /* length in bytes */ u_char oui[3]; /* 0x00, 0x50, 0xf2 */ u_char type; /* OUI type */ u_short version; /* spec revision */ struct ieee80211_mtik_ie_data iedata; } __attribute__((packed)); typedef struct ieee802_11_hdr { u_char frame_control; u_char flags; #define IEEE80211_TO_DS 0x01 #define IEEE80211_FROM_DS 0x02 #define IEEE80211_MORE_FRAG 0x04 #define IEEE80211_RETRY 0x08 #define IEEE80211_PWR_MGT 0x10 #define IEEE80211_MORE_DATA 0x20 #define IEEE80211_WEP_FLAG 0x40 #define IEEE80211_ORDER_FLAG 0x80 u_short duration; u_char addr1[6]; u_char addr2[6]; u_char addr3[6]; u_short frag_and_seq; } __attribute__((packed)) ieee802_11_hdr; typedef struct { u_char timestamp[8]; u_short bcn_interval; u_short caps; #define MGT_CAPS_AP 0x1 #define MGT_CAPS_IBSS 0x2 #define MGT_CAPS_WEP 0x10 } __attribute__((packed)) ieee_802_11_mgt_frame; typedef struct { u_char tag; u_char length; } __attribute__((packed)) ieee_802_11_tag; typedef enum { tagSSID = 0, tagRates = 1, tagChannel = 3, tagRSN = 48, tagMESHSSID = 114, tagVendorSpecific = 0xDD } i81tag; typedef struct prism_hdr { u_int msg_code; u_int msg_length; char cap_device[16]; //char dids[0]; } __attribute__((packed)) prism_hdr; #ifdef HAVE_MADWIFI typedef struct prism_did { u_int did; u_short status1; u_short length; u_int data; //int value[0]; } __attribute__((packed)) prism_did; /* DIDmsg_lnxind_wlansniffrm = 0x00000044, DIDmsg_lnxind_wlansniffrm_hosttime = 0x00010044, DIDmsg_lnxind_wlansniffrm_mactime = 0x00020044, DIDmsg_lnxind_wlansniffrm_channel = 0x00030044, DIDmsg_lnxind_wlansniffrm_rssi = 0x00040044, DIDmsg_lnxind_wlansniffrm_sq = 0x00050044, DIDmsg_lnxind_wlansniffrm_signal = 0x00060044, DIDmsg_lnxind_wlansniffrm_noise = 0x00070044, DIDmsg_lnxind_wlansniffrm_rate = 0x00080044, DIDmsg_lnxind_wlansniffrm_istx = 0x00090044, DIDmsg_lnxind_wlansniffrm_frmlen = 0x000A0044 */ typedef enum prism_did_num { pdn_host_time = 0x00010044, pdn_mac_time = 0x00020044, pdn_rssi = 0x00040044, pdn_sq = 0x00050044, pdn_signal = 0x00060044, pdn_datarate = 0x00080044, pdn_framelen = 0x000a0044 } prism_did_num; #else typedef struct prism_did { u_short did; u_short status1; u_short status2; u_short length; //int value[0]; } __attribute__((packed)) prism_did; typedef enum prism_did_num { pdn_host_time = 0x1041, pdn_mac_time = 0x2041, pdn_rssi = 0x4041, pdn_sq = 0x5041, pdn_datarate = 0x8041, pdn_framelen = 0xa041 } prism_did_num; #endif //Structure definitions for data collection typedef enum { typeUnknown, typeAP, typeWDS, typeSta, typeAdhocHub, typeMesh } host_type; typedef enum { ssUnknown, ssUnassociated, ssAssociated } sta_state; typedef struct { u_char bssid[6]; char ssid[33]; char ssidlen; u_char channel; u_short flags; int encryption; char radioname[16]; } ap_info; typedef struct { sta_state state; u_char connectedBSSID[6]; char lastssid[33]; char lastssidlen; char radioname[16]; } sta_info; typedef struct { u_char occupied; u_char mac[6]; host_type type; time_t lastSeen; int RSSI; ap_info *apInfo; sta_info *staInfo; u_char isSelf; } wiviz_host; //Primary config struct typedef struct { wiviz_host hosts[MAX_HOSTS]; int numHosts; int readFromWl; time_t lastKeepAlive; int channelHopping; int channelDwellTime; int channelHopSeq[14]; int channelHopSeqLen; int curChannel; int channelHopperPID; } wiviz_cfg; void fprint_mac(FILE * outf, u_char * mac, char *extra); void print_mac(u_char * mac, char *extra);
405084c324f5be6a43fbc8d1bfef88eecdcf54aa
d169de4c5c6b281984df35536430dcc931a957a9
/source/hal/driver/common/rtc/rtc_common.c
6fefbdd2e27eeb50177abcfd2500de5e31864210
[ "LGPL-2.1-only", "Apache-2.0" ]
permissive
vsfteam/vsf
2ba968ba2ef53b036668019c6c6746149a63c38a
522a52ff2ee4ed149b52789a5bd366f80c08c458
refs/heads/master
2023-08-27T07:32:08.339123
2023-08-26T17:46:07
2023-08-26T17:46:07
181,911,464
273
83
Apache-2.0
2023-08-29T03:08:36
2019-04-17T14:43:42
C
UTF-8
C
false
false
5,603
c
rtc_common.c
/***************************************************************************** * Cop->right(C)2009-2019 by VSF Team * * * * 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 cop-> 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. * * * ****************************************************************************/ /*============================ INCLUDES ======================================*/ #define VSF_RTC_CFG_FUNCTION_RENAME DISABLED #include "hal/vsf_hal_cfg.h" #if VSF_HAL_USE_RTC == ENABLED #include "hal/driver/driver.h" /*============================ MACROS ========================================*/ /*============================ MACROFIED FUNCTIONS ===========================*/ /*============================ TYPES =========================================*/ /*============================ GLOBAL VARIABLES ==============================*/ /*============================ LOCAL VARIABLES ===============================*/ /*============================ PROTOTYPES ====================================*/ /*============================ IMPLEMENTATION ================================*/ #if VSF_RTC_CFG_MULTI_CLASS == ENABLED vsf_err_t vsf_rtc_init(vsf_rtc_t *rtc_ptr, vsf_rtc_cfg_t *cfg_ptr) { VSF_HAL_ASSERT(rtc_ptr != NULL); VSF_HAL_ASSERT(rtc_ptr->op != NULL); VSF_HAL_ASSERT(rtc_ptr->op->init != NULL); return rtc_ptr->op->init(rtc_ptr, cfg_ptr); } void vsf_rtc_fini(vsf_rtc_t *rtc_ptr) { VSF_HAL_ASSERT(rtc_ptr != NULL); VSF_HAL_ASSERT(rtc_ptr->op != NULL); VSF_HAL_ASSERT(rtc_ptr->op->init != NULL); rtc_ptr->op->fini(rtc_ptr); } fsm_rt_t vsf_rtc_enable(vsf_rtc_t *rtc_ptr) { VSF_HAL_ASSERT(rtc_ptr != NULL); VSF_HAL_ASSERT(rtc_ptr->op != NULL); VSF_HAL_ASSERT(rtc_ptr->op->enable != NULL); return rtc_ptr->op->enable(rtc_ptr); } fsm_rt_t vsf_rtc_disable(vsf_rtc_t *rtc_ptr) { VSF_HAL_ASSERT(rtc_ptr != NULL); VSF_HAL_ASSERT(rtc_ptr->op != NULL); VSF_HAL_ASSERT(rtc_ptr->op->disable != NULL); return rtc_ptr->op->disable(rtc_ptr); } vsf_err_t vsf_rtc_get(vsf_rtc_t *rtc_ptr, vsf_rtc_tm_t *rtc_tm) { VSF_HAL_ASSERT(rtc_ptr != NULL); VSF_HAL_ASSERT(rtc_ptr->op != NULL); VSF_HAL_ASSERT(rtc_ptr->op->get != NULL); return rtc_ptr->op->get(rtc_ptr, rtc_tm); } vsf_err_t vsf_rtc_set(vsf_rtc_t *rtc_ptr, const vsf_rtc_tm_t *rtc_tm) { VSF_HAL_ASSERT(rtc_ptr != NULL); VSF_HAL_ASSERT(rtc_ptr->op != NULL); VSF_HAL_ASSERT(rtc_ptr->op->set != NULL); return rtc_ptr->op->set(rtc_ptr, rtc_tm); } vsf_err_t vsf_rtc_get_time(vsf_rtc_t *rtc_ptr, vsf_rtc_time_t *second_ptr, vsf_rtc_time_t *millisecond_ptr) { VSF_HAL_ASSERT(rtc_ptr != NULL); VSF_HAL_ASSERT(rtc_ptr->op != NULL); VSF_HAL_ASSERT(rtc_ptr->op->get_time != NULL); return rtc_ptr->op->get_time(rtc_ptr, second_ptr, millisecond_ptr); } vsf_err_t vsf_rtc_set_time(vsf_rtc_t *rtc_ptr, vsf_rtc_time_t second, vsf_rtc_time_t millisecond) { VSF_HAL_ASSERT(rtc_ptr != NULL); VSF_HAL_ASSERT(rtc_ptr->op != NULL); VSF_HAL_ASSERT(rtc_ptr->op->set_time != NULL); return rtc_ptr->op->set_time(rtc_ptr, second, millisecond); } vsf_rtc_capability_t vsf_rtc_capability(vsf_rtc_t *rtc_ptr) { VSF_HAL_ASSERT(rtc_ptr != NULL); VSF_HAL_ASSERT(rtc_ptr->op != NULL); VSF_HAL_ASSERT(rtc_ptr->op->capability != NULL); return rtc_ptr->op->capability(rtc_ptr); } #endif /* VSF_RTC_CFG_MULTI_CLASS == ENABLED */ static bool _vsf_rtc_is_valid(const vsf_rtc_tm_t *rtc_tm) { VSF_HAL_ASSERT(rtc_tm != NULL); if (rtc_tm->tm_sec > 59) { return false; } if (rtc_tm->tm_min > 59) { return false; } if (rtc_tm->tm_hour > 23) { return false; } if ((rtc_tm->tm_mday < 1) || (rtc_tm->tm_mday > 23)) { return false; } if ((rtc_tm->tm_mday < 1) || (rtc_tm->tm_mday > 7)) { return false; } if ((rtc_tm->tm_mon < 1) || (rtc_tm->tm_mon > 12)) { return false; } if (rtc_tm->tm_year < 1900) { return false; } return true; } bool vsf_rtc_tm_is_valid(const vsf_rtc_tm_t *rtc_tm) { VSF_HAL_ASSERT(rtc_tm != NULL); if (rtc_tm->tm_year < 1900) { return false; } return _vsf_rtc_is_valid(rtc_tm); } bool vsf_rtc_tm_is_epoch_time(const vsf_rtc_tm_t *rtc_tm) { VSF_HAL_ASSERT(rtc_tm != NULL); if (rtc_tm->tm_year < 1970) { return false; } return _vsf_rtc_is_valid(rtc_tm); } #endif /* VSF_HAL_USE_RTC == ENABLED */
afedf7ae24b9c28689e3efa9c665210be49de257
c0bfd93cd7f26a271268e504959256f1e02c6806
/components/spi_flash/include/esp_partition.h
d7d295c925827e2c5382e55de37ea9eb68a9c329
[ "Apache-2.0" ]
permissive
espressif/ESP8266_RTOS_SDK
606f396e92d2675d9854f0fabd88587fbbbaf267
af0cdc36fa2600033d0a09301c754008cf1503c1
refs/heads/master
2023-08-24T22:40:15.373553
2023-05-06T02:04:24
2023-05-06T02:04:24
27,584,181
3,163
1,749
Apache-2.0
2023-08-09T10:48:13
2014-12-05T09:27:12
C
UTF-8
C
false
false
13,748
h
esp_partition.h
// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __ESP_PARTITION_H__ #define __ESP_PARTITION_H__ #include <stdint.h> #include <stdbool.h> #include <stddef.h> #include "esp_err.h" #include "esp_spi_flash.h" #ifdef __cplusplus extern "C" { #endif /** * @file esp_partition.h * @brief Partition APIs */ /** * @brief Partition type * @note Keep this enum in sync with PartitionDefinition class gen_esp32part.py */ typedef enum { ESP_PARTITION_TYPE_APP = 0x00, //!< Application partition type ESP_PARTITION_TYPE_DATA = 0x01, //!< Data partition type } esp_partition_type_t; /** * @brief Partition subtype * @note Keep this enum in sync with PartitionDefinition class gen_esp32part.py */ typedef enum { ESP_PARTITION_SUBTYPE_APP_FACTORY = 0x00, //!< Factory application partition ESP_PARTITION_SUBTYPE_APP_OTA_MIN = 0x10, //!< Base for OTA partition subtypes ESP_PARTITION_SUBTYPE_APP_OTA_0 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 0, //!< OTA partition 0 ESP_PARTITION_SUBTYPE_APP_OTA_1 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 1, //!< OTA partition 1 ESP_PARTITION_SUBTYPE_APP_OTA_2 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 2, //!< OTA partition 2 ESP_PARTITION_SUBTYPE_APP_OTA_3 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 3, //!< OTA partition 3 ESP_PARTITION_SUBTYPE_APP_OTA_4 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 4, //!< OTA partition 4 ESP_PARTITION_SUBTYPE_APP_OTA_5 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 5, //!< OTA partition 5 ESP_PARTITION_SUBTYPE_APP_OTA_6 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 6, //!< OTA partition 6 ESP_PARTITION_SUBTYPE_APP_OTA_7 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 7, //!< OTA partition 7 ESP_PARTITION_SUBTYPE_APP_OTA_8 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 8, //!< OTA partition 8 ESP_PARTITION_SUBTYPE_APP_OTA_9 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 9, //!< OTA partition 9 ESP_PARTITION_SUBTYPE_APP_OTA_10 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 10,//!< OTA partition 10 ESP_PARTITION_SUBTYPE_APP_OTA_11 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 11,//!< OTA partition 11 ESP_PARTITION_SUBTYPE_APP_OTA_12 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 12,//!< OTA partition 12 ESP_PARTITION_SUBTYPE_APP_OTA_13 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 13,//!< OTA partition 13 ESP_PARTITION_SUBTYPE_APP_OTA_14 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 14,//!< OTA partition 14 ESP_PARTITION_SUBTYPE_APP_OTA_15 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 15,//!< OTA partition 15 ESP_PARTITION_SUBTYPE_APP_OTA_MAX = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 16,//!< Max subtype of OTA partition ESP_PARTITION_SUBTYPE_APP_TEST = 0x20, //!< Test application partition ESP_PARTITION_SUBTYPE_DATA_OTA = 0x00, //!< OTA selection partition ESP_PARTITION_SUBTYPE_DATA_PHY = 0x01, //!< PHY init data partition ESP_PARTITION_SUBTYPE_DATA_NVS = 0x02, //!< NVS partition ESP_PARTITION_SUBTYPE_DATA_COREDUMP = 0x03, //!< COREDUMP partition ESP_PARTITION_SUBTYPE_DATA_ESPHTTPD = 0x80, //!< ESPHTTPD partition ESP_PARTITION_SUBTYPE_DATA_FAT = 0x81, //!< FAT partition ESP_PARTITION_SUBTYPE_DATA_SPIFFS = 0x82, //!< SPIFFS partition ESP_PARTITION_SUBTYPE_ANY = 0xff, //!< Used to search for partitions with any subtype } esp_partition_subtype_t; /** * @brief Convenience macro to get esp_partition_subtype_t value for the i-th OTA partition */ #define ESP_PARTITION_SUBTYPE_OTA(i) ((esp_partition_subtype_t)(ESP_PARTITION_SUBTYPE_APP_OTA_MIN + ((i) & 0xf))) /** * @brief Opaque partition iterator type */ typedef struct esp_partition_iterator_opaque_* esp_partition_iterator_t; /** * @brief partition information structure * * This is not the format in flash, that format is esp_partition_info_t. * * However, this is the format used by this API. */ typedef struct { esp_partition_type_t type; /*!< partition type (app/data) */ esp_partition_subtype_t subtype; /*!< partition subtype */ uint32_t address; /*!< starting address of the partition in flash */ uint32_t size; /*!< size of the partition, in bytes */ char label[17]; /*!< partition label, zero-terminated ASCII string */ bool encrypted; /*!< flag is set to true if partition is encrypted */ } esp_partition_t; /** * @brief Find partition based on one or more parameters * * @param type Partition type, one of esp_partition_type_t values * @param subtype Partition subtype, one of esp_partition_subtype_t values. * To find all partitions of given type, use * ESP_PARTITION_SUBTYPE_ANY. * @param label (optional) Partition label. Set this value if looking * for partition with a specific name. Pass NULL otherwise. * * @return iterator which can be used to enumerate all the partitions found, * or NULL if no partitions were found. * Iterator obtained through this function has to be released * using esp_partition_iterator_release when not used any more. */ esp_partition_iterator_t esp_partition_find(esp_partition_type_t type, esp_partition_subtype_t subtype, const char* label); /** * @brief Find first partition based on one or more parameters * * @param type Partition type, one of esp_partition_type_t values * @param subtype Partition subtype, one of esp_partition_subtype_t values. * To find all partitions of given type, use * ESP_PARTITION_SUBTYPE_ANY. * @param label (optional) Partition label. Set this value if looking * for partition with a specific name. Pass NULL otherwise. * * @return pointer to esp_partition_t structure, or NULL if no partition is found. * This pointer is valid for the lifetime of the application. */ const esp_partition_t* esp_partition_find_first(esp_partition_type_t type, esp_partition_subtype_t subtype, const char* label); /** * @brief Get esp_partition_t structure for given partition * * @param iterator Iterator obtained using esp_partition_find. Must be non-NULL. * * @return pointer to esp_partition_t structure. This pointer is valid for the lifetime * of the application. */ const esp_partition_t* esp_partition_get(esp_partition_iterator_t iterator); /** * @brief Move partition iterator to the next partition found * * Any copies of the iterator will be invalid after this call. * * @param iterator Iterator obtained using esp_partition_find. Must be non-NULL. * * @return NULL if no partition was found, valid esp_partition_iterator_t otherwise. */ esp_partition_iterator_t esp_partition_next(esp_partition_iterator_t iterator); /** * @brief Release partition iterator * * @param iterator Iterator obtained using esp_partition_find. Must be non-NULL. * */ void esp_partition_iterator_release(esp_partition_iterator_t iterator); /** * @brief Verify partition data * * Given a pointer to partition data, verify this partition exists in the partition table (all fields match.) * * This function is also useful to take partition data which may be in a RAM buffer and convert it to a pointer to the * permanent partition data stored in flash. * * Pointers returned from this function can be compared directly to the address of any pointer returned from * esp_partition_get(), as a test for equality. * * @param partition Pointer to partition data to verify. Must be non-NULL. All fields of this structure must match the * partition table entry in flash for this function to return a successful match. * * @return * - If partition not found, returns NULL. * - If found, returns a pointer to the esp_partition_t structure in flash. This pointer is always valid for the lifetime of the application. */ const esp_partition_t *esp_partition_verify(const esp_partition_t *partition); /** * @brief Read data from the partition * * @param partition Pointer to partition structure obtained using * esp_partition_find_first or esp_partition_get. * Must be non-NULL. * @param dst Pointer to the buffer where data should be stored. * Pointer must be non-NULL and buffer must be at least 'size' bytes long. * @param src_offset Address of the data to be read, relative to the * beginning of the partition. * @param size Size of data to be read, in bytes. * * @return ESP_OK, if data was read successfully; * ESP_ERR_INVALID_ARG, if src_offset exceeds partition size; * ESP_ERR_INVALID_SIZE, if read would go out of bounds of the partition; * or one of error codes from lower-level flash driver. */ esp_err_t esp_partition_read(const esp_partition_t* partition, size_t src_offset, void* dst, size_t size); /** * @brief Write data to the partition * * Before writing data to flash, corresponding region of flash needs to be erased. * This can be done using esp_partition_erase_range function. * * Partitions marked with an encryption flag will automatically be * written via the spi_flash_write_encrypted() function. If writing to * an encrypted partition, all write offsets and lengths must be * multiples of 16 bytes. See the spi_flash_write_encrypted() function * for more details. Unencrypted partitions do not have this * restriction. * * @param partition Pointer to partition structure obtained using * esp_partition_find_first or esp_partition_get. * Must be non-NULL. * @param dst_offset Address where the data should be written, relative to the * beginning of the partition. * @param src Pointer to the source buffer. Pointer must be non-NULL and * buffer must be at least 'size' bytes long. * @param size Size of data to be written, in bytes. * * @note Prior to writing to flash memory, make sure it has been erased with * esp_partition_erase_range call. * * @return ESP_OK, if data was written successfully; * ESP_ERR_INVALID_ARG, if dst_offset exceeds partition size; * ESP_ERR_INVALID_SIZE, if write would go out of bounds of the partition; * or one of error codes from lower-level flash driver. */ esp_err_t esp_partition_write(const esp_partition_t* partition, size_t dst_offset, const void* src, size_t size); /** * @brief Erase part of the partition * * @param partition Pointer to partition structure obtained using * esp_partition_find_first or esp_partition_get. * Must be non-NULL. * @param start_addr Address where erase operation should start. Must be aligned * to 4 kilobytes. * @param size Size of the range which should be erased, in bytes. * Must be divisible by 4 kilobytes. * * @return ESP_OK, if the range was erased successfully; * ESP_ERR_INVALID_ARG, if iterator or dst are NULL; * ESP_ERR_INVALID_SIZE, if erase would go out of bounds of the partition; * or one of error codes from lower-level flash driver. */ esp_err_t esp_partition_erase_range(const esp_partition_t* partition, uint32_t start_addr, uint32_t size); #ifdef CONFIG_ENABLE_FLASH_MMAP /** * @brief Configure MMU to map partition into data memory * * Unlike spi_flash_mmap function, which requires a 64kB aligned base address, * this function doesn't impose such a requirement. * If offset results in a flash address which is not aligned to 64kB boundary, * address will be rounded to the lower 64kB boundary, so that mapped region * includes requested range. * Pointer returned via out_ptr argument will be adjusted to point to the * requested offset (not necessarily to the beginning of mmap-ed region). * * To release mapped memory, pass handle returned via out_handle argument to * spi_flash_munmap function. * * @param partition Pointer to partition structure obtained using * esp_partition_find_first or esp_partition_get. * Must be non-NULL. * @param offset Offset from the beginning of partition where mapping should start. * @param size Size of the area to be mapped. * @param memory Memory space where the region should be mapped * @param out_ptr Output, pointer to the mapped memory region * @param out_handle Output, handle which should be used for spi_flash_munmap call * * @return ESP_OK, if successful */ esp_err_t esp_partition_mmap(const esp_partition_t* partition, uint32_t offset, uint32_t size, spi_flash_mmap_memory_t memory, const void** out_ptr, spi_flash_mmap_handle_t* out_handle); #endif /* CONFIG_ENABLE_FLASH_MMAP */ #ifdef __cplusplus } #endif #endif /* __ESP_PARTITION_H__ */
d3d6ca31da271411d4c0234326870feb9af820d7
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
/sys/fs/nfs/server/nfs_nfsdcache.c
2a68ccc4393f792ea40181309f1d805e54dd53f1
[]
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
28,561
c
nfs_nfsdcache.c
/* $NetBSD: nfs_nfsdcache.c,v 1.4 2016/12/13 21:50:32 pgoyette Exp $ */ /*- * Copyright (c) 1989, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Rick Macklem at The University of Guelph. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include <sys/cdefs.h> /* __FBSDID("FreeBSD: head/sys/fs/nfsserver/nfs_nfsdcache.c 304026 2016-08-12 22:44:59Z rmacklem "); */ __RCSID("$NetBSD: nfs_nfsdcache.c,v 1.4 2016/12/13 21:50:32 pgoyette Exp $"); /* * Here is the basic algorithm: * First, some design criteria I used: * - I think a false hit is more serious than a false miss * - A false hit for an RPC that has Op(s) that order via seqid# must be * avoided at all cost * - A valid hit will probably happen a long time after the original reply * and the TCP socket that the original request was received on will no * longer be active * (The long time delay implies to me that LRU is not appropriate.) * - The mechanism will satisfy the requirements of ordering Ops with seqid#s * in them as well as minimizing the risk of redoing retried non-idempotent * Ops. * Because it is biased towards avoiding false hits, multiple entries with * the same xid are to be expected, especially for the case of the entry * in the cache being related to a seqid# sequenced Op. * * The basic algorithm I'm about to code up: * - Null RPCs bypass the cache and are just done * For TCP * - key on <xid, NFS version> (as noted above, there can be several * entries with the same key) * When a request arrives: * For all that match key * - if RPC# != OR request_size != * - not a match with this one * - if NFSv4 and received on same TCP socket OR * received on a TCP connection created before the * entry was cached * - not a match with this one * (V2,3 clients might retry on same TCP socket) * - calculate checksum on first N bytes of NFS XDR * - if checksum != * - not a match for this one * If any of the remaining ones that match has a * seqid_refcnt > 0 * - not a match (go do RPC, using new cache entry) * If one match left * - a hit (reply from cache) * else * - miss (go do RPC, using new cache entry) * * During processing of NFSv4 request: * - set a flag when a non-idempotent Op is processed * - when an Op that uses a seqid# (Open,...) is processed * - if same seqid# as referenced entry in cache * - free new cache entry * - reply from referenced cache entry * else if next seqid# in order * - free referenced cache entry * - increment seqid_refcnt on new cache entry * - set pointer from Openowner/Lockowner to * new cache entry (aka reference it) * else if first seqid# in sequence * - increment seqid_refcnt on new cache entry * - set pointer from Openowner/Lockowner to * new cache entry (aka reference it) * * At end of RPC processing: * - if seqid_refcnt > 0 OR flagged non-idempotent on new * cache entry * - save reply in cache entry * - calculate checksum on first N bytes of NFS XDR * request * - note op and length of XDR request (in bytes) * - timestamp it * else * - free new cache entry * - Send reply (noting info for socket activity check, below) * * For cache entries saved above: * - if saved since seqid_refcnt was > 0 * - free when seqid_refcnt decrements to 0 * (when next one in sequence is processed above, or * when Openowner/Lockowner is discarded) * else { non-idempotent Op(s) } * - free when * - some further activity observed on same * socket * (I'm not yet sure how I'm going to do * this. Maybe look at the TCP connection * to see if the send_tcp_sequence# is well * past sent reply OR K additional RPCs * replied on same socket OR?) * OR * - when very old (hours, days, weeks?) * * For UDP (v2, 3 only), pretty much the old way: * - key on <xid, NFS version, RPC#, Client host ip#> * (at most one entry for each key) * * When a Request arrives: * - if a match with entry via key * - if RPC marked In_progress * - discard request (don't send reply) * else * - reply from cache * - timestamp cache entry * else * - add entry to cache, marked In_progress * - do RPC * - when RPC done * - if RPC# non-idempotent * - mark entry Done (not In_progress) * - save reply * - timestamp cache entry * else * - free cache entry * - send reply * * Later, entries with saved replies are free'd a short time (few minutes) * after reply sent (timestamp). * Reference: Chet Juszczak, "Improving the Performance and Correctness * of an NFS Server", in Proc. Winter 1989 USENIX Conference, * pages 53-63. San Diego, February 1989. * for the UDP case. * nfsrc_floodlevel is set to the allowable upper limit for saved replies * for TCP. For V3, a reply won't be saved when the flood level is * hit. For V4, the non-idempotent Op will return NFSERR_RESOURCE in * that case. This level should be set high enough that this almost * never happens. */ #ifndef APPLEKEXT #include <fs/nfs/common/nfsport.h> extern struct nfsstatsv1 nfsstatsv1; extern struct mtx nfsrc_udpmtx; extern struct nfsrchash_bucket nfsrchash_table[NFSRVCACHE_HASHSIZE]; extern struct nfsrchash_bucket nfsrcahash_table[NFSRVCACHE_HASHSIZE]; int nfsrc_floodlevel = NFSRVCACHE_FLOODLEVEL, nfsrc_tcpsavedreplies = 0; #endif /* !APPLEKEXT */ SYSCTL_DECL(_vfs_nfsd); static u_int nfsrc_tcphighwater = 0; static int sysctl_tcphighwater(SYSCTL_HANDLER_ARGS) { int error, newhighwater; newhighwater = nfsrc_tcphighwater; error = sysctl_handle_int(oidp, &newhighwater, 0, req); if (error != 0 || req->newptr == NULL) return (error); if (newhighwater < 0) return (EINVAL); if (newhighwater >= nfsrc_floodlevel) nfsrc_floodlevel = newhighwater + newhighwater / 5; nfsrc_tcphighwater = newhighwater; return (0); } SYSCTL_PROC(_vfs_nfsd, OID_AUTO, tcphighwater, CTLTYPE_UINT | CTLFLAG_RW, 0, sizeof(nfsrc_tcphighwater), sysctl_tcphighwater, "IU", "High water mark for TCP cache entries"); static u_int nfsrc_udphighwater = NFSRVCACHE_UDPHIGHWATER; SYSCTL_UINT(_vfs_nfsd, OID_AUTO, udphighwater, CTLFLAG_RW, &nfsrc_udphighwater, 0, "High water mark for UDP cache entries"); static u_int nfsrc_tcptimeout = NFSRVCACHE_TCPTIMEOUT; SYSCTL_UINT(_vfs_nfsd, OID_AUTO, tcpcachetimeo, CTLFLAG_RW, &nfsrc_tcptimeout, 0, "Timeout for TCP entries in the DRC"); static u_int nfsrc_tcpnonidempotent = 1; SYSCTL_UINT(_vfs_nfsd, OID_AUTO, cachetcp, CTLFLAG_RW, &nfsrc_tcpnonidempotent, 0, "Enable the DRC for NFS over TCP"); static int nfsrc_udpcachesize = 0; static TAILQ_HEAD(, nfsrvcache) nfsrvudplru; static struct nfsrvhashhead nfsrvudphashtbl[NFSRVCACHE_HASHSIZE]; /* * and the reverse mapping from generic to Version 2 procedure numbers */ static int newnfsv2_procid[NFS_V3NPROCS] = { NFSV2PROC_NULL, NFSV2PROC_GETATTR, NFSV2PROC_SETATTR, NFSV2PROC_LOOKUP, NFSV2PROC_NOOP, NFSV2PROC_READLINK, NFSV2PROC_READ, NFSV2PROC_WRITE, NFSV2PROC_CREATE, NFSV2PROC_MKDIR, NFSV2PROC_SYMLINK, NFSV2PROC_CREATE, NFSV2PROC_REMOVE, NFSV2PROC_RMDIR, NFSV2PROC_RENAME, NFSV2PROC_LINK, NFSV2PROC_READDIR, NFSV2PROC_NOOP, NFSV2PROC_STATFS, NFSV2PROC_NOOP, NFSV2PROC_NOOP, NFSV2PROC_NOOP, }; #define nfsrc_hash(xid) (((xid) + ((xid) >> 24)) % NFSRVCACHE_HASHSIZE) #define NFSRCUDPHASH(xid) \ (&nfsrvudphashtbl[nfsrc_hash(xid)]) #define NFSRCHASH(xid) \ (&nfsrchash_table[nfsrc_hash(xid)].tbl) #define NFSRCAHASH(xid) (&nfsrcahash_table[nfsrc_hash(xid)]) #define TRUE 1 #define FALSE 0 #define NFSRVCACHE_CHECKLEN 100 /* True iff the rpc reply is an nfs status ONLY! */ static int nfsv2_repstat[NFS_V3NPROCS] = { FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, }; /* * Will NFS want to work over IPv6 someday? */ #define NETFAMILY(rp) \ (((rp)->rc_flag & RC_INETIPV6) ? AF_INET6 : AF_INET) /* local functions */ static int nfsrc_getudp(struct nfsrv_descript *nd, struct nfsrvcache *newrp); static int nfsrc_gettcp(struct nfsrv_descript *nd, struct nfsrvcache *newrp); static void nfsrc_lock(struct nfsrvcache *rp); static void nfsrc_unlock(struct nfsrvcache *rp); static void nfsrc_wanted(struct nfsrvcache *rp); static void nfsrc_freecache(struct nfsrvcache *rp); static int nfsrc_getlenandcksum(mbuf_t m1, u_int16_t *cksum); static void nfsrc_marksametcpconn(u_int64_t); /* * Return the correct mutex for this cache entry. */ static __inline struct mtx * nfsrc_cachemutex(struct nfsrvcache *rp) { if ((rp->rc_flag & RC_UDP) != 0) return (&nfsrc_udpmtx); return (&nfsrchash_table[nfsrc_hash(rp->rc_xid)].mtx); } /* * Initialize the server request cache list */ APPLESTATIC void nfsrvd_initcache(void) { int i; static int inited = 0; if (inited) return; inited = 1; for (i = 0; i < NFSRVCACHE_HASHSIZE; i++) { LIST_INIT(&nfsrvudphashtbl[i]); LIST_INIT(&nfsrchash_table[i].tbl); LIST_INIT(&nfsrcahash_table[i].tbl); } TAILQ_INIT(&nfsrvudplru); nfsrc_tcpsavedreplies = 0; nfsrc_udpcachesize = 0; nfsstatsv1.srvcache_tcppeak = 0; nfsstatsv1.srvcache_size = 0; } /* * Get a cache entry for this request. Basically just malloc a new one * and then call nfsrc_getudp() or nfsrc_gettcp() to do the rest. */ APPLESTATIC int nfsrvd_getcache(struct nfsrv_descript *nd) { struct nfsrvcache *newrp; int ret; if (nd->nd_procnum == NFSPROC_NULL) panic("nfsd cache null"); MALLOC(newrp, struct nfsrvcache *, sizeof (struct nfsrvcache), M_NFSRVCACHE, M_WAITOK); NFSBZERO((caddr_t)newrp, sizeof (struct nfsrvcache)); if (nd->nd_flag & ND_NFSV4) newrp->rc_flag = RC_NFSV4; else if (nd->nd_flag & ND_NFSV3) newrp->rc_flag = RC_NFSV3; else newrp->rc_flag = RC_NFSV2; newrp->rc_xid = nd->nd_retxid; newrp->rc_proc = nd->nd_procnum; newrp->rc_sockref = nd->nd_sockref; newrp->rc_cachetime = nd->nd_tcpconntime; if (nd->nd_flag & ND_SAMETCPCONN) newrp->rc_flag |= RC_SAMETCPCONN; if (nd->nd_nam2 != NULL) { newrp->rc_flag |= RC_UDP; ret = nfsrc_getudp(nd, newrp); } else { ret = nfsrc_gettcp(nd, newrp); } NFSEXITCODE2(0, nd); return (ret); } /* * For UDP (v2, v3): * - key on <xid, NFS version, RPC#, Client host ip#> * (at most one entry for each key) */ static int nfsrc_getudp(struct nfsrv_descript *nd, struct nfsrvcache *newrp) { struct nfsrvcache *rp; struct sockaddr_in *saddr; struct sockaddr_in6 *saddr6; struct nfsrvhashhead *hp; int ret = 0; struct mtx *mutex; mutex = nfsrc_cachemutex(newrp); hp = NFSRCUDPHASH(newrp->rc_xid); loop: mtx_lock(mutex); LIST_FOREACH(rp, hp, rc_hash) { if (newrp->rc_xid == rp->rc_xid && newrp->rc_proc == rp->rc_proc && (newrp->rc_flag & rp->rc_flag & RC_NFSVERS) && nfsaddr_match(NETFAMILY(rp), &rp->rc_haddr, nd->nd_nam)) { if ((rp->rc_flag & RC_LOCKED) != 0) { rp->rc_flag |= RC_WANTED; (void)mtx_sleep(rp, mutex, (PZERO - 1) | PDROP, "nfsrc", 10 * hz); goto loop; } if (rp->rc_flag == 0) panic("nfs udp cache0"); rp->rc_flag |= RC_LOCKED; TAILQ_REMOVE(&nfsrvudplru, rp, rc_lru); TAILQ_INSERT_TAIL(&nfsrvudplru, rp, rc_lru); if (rp->rc_flag & RC_INPROG) { nfsstatsv1.srvcache_inproghits++; mtx_unlock(mutex); ret = RC_DROPIT; } else if (rp->rc_flag & RC_REPSTATUS) { /* * V2 only. */ nfsstatsv1.srvcache_nonidemdonehits++; mtx_unlock(mutex); nfsrvd_rephead(nd); *(nd->nd_errp) = rp->rc_status; ret = RC_REPLY; rp->rc_timestamp = NFSD_MONOSEC + NFSRVCACHE_UDPTIMEOUT; } else if (rp->rc_flag & RC_REPMBUF) { nfsstatsv1.srvcache_nonidemdonehits++; mtx_unlock(mutex); nd->nd_mreq = m_copym(rp->rc_reply, 0, M_COPYALL, M_WAITOK); ret = RC_REPLY; rp->rc_timestamp = NFSD_MONOSEC + NFSRVCACHE_UDPTIMEOUT; } else { panic("nfs udp cache1"); } nfsrc_unlock(rp); free((caddr_t)newrp, M_NFSRVCACHE); goto out; } } nfsstatsv1.srvcache_misses++; atomic_add_int(&nfsstatsv1.srvcache_size, 1); nfsrc_udpcachesize++; newrp->rc_flag |= RC_INPROG; saddr = NFSSOCKADDR(nd->nd_nam, struct sockaddr_in *); if (saddr->sin_family == AF_INET) newrp->rc_inet = saddr->sin_addr.s_addr; else if (saddr->sin_family == AF_INET6) { saddr6 = (struct sockaddr_in6 *)saddr; NFSBCOPY((caddr_t)&saddr6->sin6_addr, (caddr_t)&newrp->rc_inet6, sizeof (struct in6_addr)); newrp->rc_flag |= RC_INETIPV6; } LIST_INSERT_HEAD(hp, newrp, rc_hash); TAILQ_INSERT_TAIL(&nfsrvudplru, newrp, rc_lru); mtx_unlock(mutex); nd->nd_rp = newrp; ret = RC_DOIT; out: NFSEXITCODE2(0, nd); return (ret); } /* * Update a request cache entry after the rpc has been done */ APPLESTATIC struct nfsrvcache * nfsrvd_updatecache(struct nfsrv_descript *nd) { struct nfsrvcache *rp; struct nfsrvcache *retrp = NULL; mbuf_t m; struct mtx *mutex; rp = nd->nd_rp; if (!rp) panic("nfsrvd_updatecache null rp"); nd->nd_rp = NULL; mutex = nfsrc_cachemutex(rp); mtx_lock(mutex); nfsrc_lock(rp); if (!(rp->rc_flag & RC_INPROG)) panic("nfsrvd_updatecache not inprog"); rp->rc_flag &= ~RC_INPROG; if (rp->rc_flag & RC_UDP) { TAILQ_REMOVE(&nfsrvudplru, rp, rc_lru); TAILQ_INSERT_TAIL(&nfsrvudplru, rp, rc_lru); } /* * Reply from cache is a special case returned by nfsrv_checkseqid(). */ if (nd->nd_repstat == NFSERR_REPLYFROMCACHE) { nfsstatsv1.srvcache_nonidemdonehits++; mtx_unlock(mutex); nd->nd_repstat = 0; if (nd->nd_mreq) mbuf_freem(nd->nd_mreq); if (!(rp->rc_flag & RC_REPMBUF)) panic("reply from cache"); nd->nd_mreq = m_copym(rp->rc_reply, 0, M_COPYALL, M_WAITOK); rp->rc_timestamp = NFSD_MONOSEC + nfsrc_tcptimeout; nfsrc_unlock(rp); goto out; } /* * If rc_refcnt > 0, save it * For UDP, save it if ND_SAVEREPLY is set * For TCP, save it if ND_SAVEREPLY and nfsrc_tcpnonidempotent is set */ if (nd->nd_repstat != NFSERR_DONTREPLY && (rp->rc_refcnt > 0 || ((nd->nd_flag & ND_SAVEREPLY) && (rp->rc_flag & RC_UDP)) || ((nd->nd_flag & ND_SAVEREPLY) && !(rp->rc_flag & RC_UDP) && nfsrc_tcpsavedreplies <= nfsrc_floodlevel && nfsrc_tcpnonidempotent))) { if (rp->rc_refcnt > 0) { if (!(rp->rc_flag & RC_NFSV4)) panic("update_cache refcnt"); rp->rc_flag |= RC_REFCNT; } if ((nd->nd_flag & ND_NFSV2) && nfsv2_repstat[newnfsv2_procid[nd->nd_procnum]]) { rp->rc_status = nd->nd_repstat; rp->rc_flag |= RC_REPSTATUS; mtx_unlock(mutex); } else { if (!(rp->rc_flag & RC_UDP)) { atomic_add_int(&nfsrc_tcpsavedreplies, 1); if (nfsrc_tcpsavedreplies > nfsstatsv1.srvcache_tcppeak) nfsstatsv1.srvcache_tcppeak = nfsrc_tcpsavedreplies; } mtx_unlock(mutex); m = m_copym(nd->nd_mreq, 0, M_COPYALL, M_WAITOK); mtx_lock(mutex); rp->rc_reply = m; rp->rc_flag |= RC_REPMBUF; mtx_unlock(mutex); } if (rp->rc_flag & RC_UDP) { rp->rc_timestamp = NFSD_MONOSEC + NFSRVCACHE_UDPTIMEOUT; nfsrc_unlock(rp); } else { rp->rc_timestamp = NFSD_MONOSEC + nfsrc_tcptimeout; if (rp->rc_refcnt > 0) nfsrc_unlock(rp); else retrp = rp; } } else { nfsrc_freecache(rp); mtx_unlock(mutex); } out: NFSEXITCODE2(0, nd); return (retrp); } /* * Invalidate and, if possible, free an in prog cache entry. * Must not sleep. */ APPLESTATIC void nfsrvd_delcache(struct nfsrvcache *rp) { struct mtx *mutex; mutex = nfsrc_cachemutex(rp); if (!(rp->rc_flag & RC_INPROG)) panic("nfsrvd_delcache not in prog"); mtx_lock(mutex); rp->rc_flag &= ~RC_INPROG; if (rp->rc_refcnt == 0 && !(rp->rc_flag & RC_LOCKED)) nfsrc_freecache(rp); mtx_unlock(mutex); } /* * Called after nfsrvd_updatecache() once the reply is sent, to update * the entry's sequence number and unlock it. The argument is * the pointer returned by nfsrvd_updatecache(). */ APPLESTATIC void nfsrvd_sentcache(struct nfsrvcache *rp, int have_seq, uint32_t seq) { struct nfsrchash_bucket *hbp; KASSERT(rp->rc_flag & RC_LOCKED, ("nfsrvd_sentcache not locked")); if (have_seq) { hbp = NFSRCAHASH(rp->rc_sockref); mtx_lock(&hbp->mtx); rp->rc_tcpseq = seq; if (rp->rc_acked != RC_NO_ACK) LIST_INSERT_HEAD(&hbp->tbl, rp, rc_ahash); rp->rc_acked = RC_NO_ACK; mtx_unlock(&hbp->mtx); } nfsrc_unlock(rp); } /* * Get a cache entry for TCP * - key on <xid, nfs version> * (allow multiple entries for a given key) */ static int nfsrc_gettcp(struct nfsrv_descript *nd, struct nfsrvcache *newrp) { struct nfsrvcache *rp, *nextrp; int i; struct nfsrvcache *hitrp; struct nfsrvhashhead *hp, nfsrc_templist; int hit, ret = 0; struct mtx *mutex; mutex = nfsrc_cachemutex(newrp); hp = NFSRCHASH(newrp->rc_xid); newrp->rc_reqlen = nfsrc_getlenandcksum(nd->nd_mrep, &newrp->rc_cksum); tryagain: mtx_lock(mutex); hit = 1; LIST_INIT(&nfsrc_templist); /* * Get all the matches and put them on the temp list. */ rp = LIST_FIRST(hp); while (rp != NULL) { nextrp = LIST_NEXT(rp, rc_hash); if (newrp->rc_xid == rp->rc_xid && (!(rp->rc_flag & RC_INPROG) || ((newrp->rc_flag & RC_SAMETCPCONN) && newrp->rc_sockref == rp->rc_sockref)) && (newrp->rc_flag & rp->rc_flag & RC_NFSVERS) && newrp->rc_proc == rp->rc_proc && ((newrp->rc_flag & RC_NFSV4) && newrp->rc_sockref != rp->rc_sockref && newrp->rc_cachetime >= rp->rc_cachetime) && newrp->rc_reqlen == rp->rc_reqlen && newrp->rc_cksum == rp->rc_cksum) { LIST_REMOVE(rp, rc_hash); LIST_INSERT_HEAD(&nfsrc_templist, rp, rc_hash); } rp = nextrp; } /* * Now, use nfsrc_templist to decide if there is a match. */ i = 0; LIST_FOREACH(rp, &nfsrc_templist, rc_hash) { i++; if (rp->rc_refcnt > 0) { hit = 0; break; } } /* * Can be a hit only if one entry left. * Note possible hit entry and put nfsrc_templist back on hash * list. */ if (i != 1) hit = 0; hitrp = rp = LIST_FIRST(&nfsrc_templist); while (rp != NULL) { nextrp = LIST_NEXT(rp, rc_hash); LIST_REMOVE(rp, rc_hash); LIST_INSERT_HEAD(hp, rp, rc_hash); rp = nextrp; } if (LIST_FIRST(&nfsrc_templist) != NULL) panic("nfs gettcp cache templist"); if (hit) { rp = hitrp; if ((rp->rc_flag & RC_LOCKED) != 0) { rp->rc_flag |= RC_WANTED; (void)mtx_sleep(rp, mutex, (PZERO - 1) | PDROP, "nfsrc", 10 * hz); goto tryagain; } if (rp->rc_flag == 0) panic("nfs tcp cache0"); rp->rc_flag |= RC_LOCKED; if (rp->rc_flag & RC_INPROG) { nfsstatsv1.srvcache_inproghits++; mtx_unlock(mutex); if (newrp->rc_sockref == rp->rc_sockref) nfsrc_marksametcpconn(rp->rc_sockref); ret = RC_DROPIT; } else if (rp->rc_flag & RC_REPSTATUS) { /* * V2 only. */ nfsstatsv1.srvcache_nonidemdonehits++; mtx_unlock(mutex); if (newrp->rc_sockref == rp->rc_sockref) nfsrc_marksametcpconn(rp->rc_sockref); ret = RC_REPLY; nfsrvd_rephead(nd); *(nd->nd_errp) = rp->rc_status; rp->rc_timestamp = NFSD_MONOSEC + nfsrc_tcptimeout; } else if (rp->rc_flag & RC_REPMBUF) { nfsstatsv1.srvcache_nonidemdonehits++; mtx_unlock(mutex); if (newrp->rc_sockref == rp->rc_sockref) nfsrc_marksametcpconn(rp->rc_sockref); ret = RC_REPLY; nd->nd_mreq = m_copym(rp->rc_reply, 0, M_COPYALL, M_WAITOK); rp->rc_timestamp = NFSD_MONOSEC + nfsrc_tcptimeout; } else { panic("nfs tcp cache1"); } nfsrc_unlock(rp); free((caddr_t)newrp, M_NFSRVCACHE); goto out; } nfsstatsv1.srvcache_misses++; atomic_add_int(&nfsstatsv1.srvcache_size, 1); /* * For TCP, multiple entries for a key are allowed, so don't * chain it into the hash table until done. */ newrp->rc_cachetime = NFSD_MONOSEC; newrp->rc_flag |= RC_INPROG; LIST_INSERT_HEAD(hp, newrp, rc_hash); mtx_unlock(mutex); nd->nd_rp = newrp; ret = RC_DOIT; out: NFSEXITCODE2(0, nd); return (ret); } /* * Lock a cache entry. */ static void nfsrc_lock(struct nfsrvcache *rp) { struct mtx *mutex; mutex = nfsrc_cachemutex(rp); mtx_assert(mutex, MA_OWNED); while ((rp->rc_flag & RC_LOCKED) != 0) { rp->rc_flag |= RC_WANTED; (void)mtx_sleep(rp, mutex, PZERO - 1, "nfsrc", 0); } rp->rc_flag |= RC_LOCKED; } /* * Unlock a cache entry. */ static void nfsrc_unlock(struct nfsrvcache *rp) { struct mtx *mutex; mutex = nfsrc_cachemutex(rp); mtx_lock(mutex); rp->rc_flag &= ~RC_LOCKED; nfsrc_wanted(rp); mtx_unlock(mutex); } /* * Wakeup anyone wanting entry. */ static void nfsrc_wanted(struct nfsrvcache *rp) { if (rp->rc_flag & RC_WANTED) { rp->rc_flag &= ~RC_WANTED; wakeup((caddr_t)rp); } } /* * Free up the entry. * Must not sleep. */ static void nfsrc_freecache(struct nfsrvcache *rp) { struct nfsrchash_bucket *hbp; LIST_REMOVE(rp, rc_hash); if (rp->rc_flag & RC_UDP) { TAILQ_REMOVE(&nfsrvudplru, rp, rc_lru); nfsrc_udpcachesize--; } else if (rp->rc_acked != RC_NO_SEQ) { hbp = NFSRCAHASH(rp->rc_sockref); mtx_lock(&hbp->mtx); if (rp->rc_acked == RC_NO_ACK) LIST_REMOVE(rp, rc_ahash); mtx_unlock(&hbp->mtx); } nfsrc_wanted(rp); if (rp->rc_flag & RC_REPMBUF) { mbuf_freem(rp->rc_reply); if (!(rp->rc_flag & RC_UDP)) atomic_add_int(&nfsrc_tcpsavedreplies, -1); } FREE((caddr_t)rp, M_NFSRVCACHE); atomic_add_int(&nfsstatsv1.srvcache_size, -1); } /* * Clean out the cache. Called when nfsserver module is unloaded. */ APPLESTATIC void nfsrvd_cleancache(void) { struct nfsrvcache *rp, *nextrp; int i; for (i = 0; i < NFSRVCACHE_HASHSIZE; i++) { mtx_lock(&nfsrchash_table[i].mtx); LIST_FOREACH_SAFE(rp, &nfsrchash_table[i].tbl, rc_hash, nextrp) nfsrc_freecache(rp); mtx_unlock(&nfsrchash_table[i].mtx); } mtx_lock(&nfsrc_udpmtx); for (i = 0; i < NFSRVCACHE_HASHSIZE; i++) { LIST_FOREACH_SAFE(rp, &nfsrvudphashtbl[i], rc_hash, nextrp) { nfsrc_freecache(rp); } } nfsstatsv1.srvcache_size = 0; mtx_unlock(&nfsrc_udpmtx); nfsrc_tcpsavedreplies = 0; } #define HISTSIZE 16 /* * The basic rule is to get rid of entries that are expired. */ void nfsrc_trimcache(u_int64_t sockref, uint32_t snd_una, int final) { struct nfsrchash_bucket *hbp; struct nfsrvcache *rp, *nextrp; int force, lastslot, i, j, k, tto, time_histo[HISTSIZE]; time_t thisstamp; static time_t udp_lasttrim = 0, tcp_lasttrim = 0; static int onethread = 0, oneslot = 0; if (sockref != 0) { hbp = NFSRCAHASH(sockref); mtx_lock(&hbp->mtx); LIST_FOREACH_SAFE(rp, &hbp->tbl, rc_ahash, nextrp) { if (sockref == rp->rc_sockref) { if (SEQ_GEQ(snd_una, rp->rc_tcpseq)) { rp->rc_acked = RC_ACK; LIST_REMOVE(rp, rc_ahash); } else if (final) { rp->rc_acked = RC_NACK; LIST_REMOVE(rp, rc_ahash); } } } mtx_unlock(&hbp->mtx); } if (atomic_cmpset_acq_int(&onethread, 0, 1) == 0) return; if (NFSD_MONOSEC != udp_lasttrim || nfsrc_udpcachesize >= (nfsrc_udphighwater + nfsrc_udphighwater / 2)) { mtx_lock(&nfsrc_udpmtx); udp_lasttrim = NFSD_MONOSEC; TAILQ_FOREACH_SAFE(rp, &nfsrvudplru, rc_lru, nextrp) { if (!(rp->rc_flag & (RC_INPROG|RC_LOCKED|RC_WANTED)) && rp->rc_refcnt == 0 && ((rp->rc_flag & RC_REFCNT) || udp_lasttrim > rp->rc_timestamp || nfsrc_udpcachesize > nfsrc_udphighwater)) nfsrc_freecache(rp); } mtx_unlock(&nfsrc_udpmtx); } if (NFSD_MONOSEC != tcp_lasttrim || nfsrc_tcpsavedreplies >= nfsrc_tcphighwater) { force = nfsrc_tcphighwater / 4; if (force > 0 && nfsrc_tcpsavedreplies + force >= nfsrc_tcphighwater) { for (i = 0; i < HISTSIZE; i++) time_histo[i] = 0; i = 0; lastslot = NFSRVCACHE_HASHSIZE - 1; } else { force = 0; if (NFSD_MONOSEC != tcp_lasttrim) { i = 0; lastslot = NFSRVCACHE_HASHSIZE - 1; } else { lastslot = i = oneslot; if (++oneslot >= NFSRVCACHE_HASHSIZE) oneslot = 0; } } tto = nfsrc_tcptimeout; tcp_lasttrim = NFSD_MONOSEC; for (; i <= lastslot; i++) { mtx_lock(&nfsrchash_table[i].mtx); LIST_FOREACH_SAFE(rp, &nfsrchash_table[i].tbl, rc_hash, nextrp) { if (!(rp->rc_flag & (RC_INPROG|RC_LOCKED|RC_WANTED)) && rp->rc_refcnt == 0) { if ((rp->rc_flag & RC_REFCNT) || tcp_lasttrim > rp->rc_timestamp || rp->rc_acked == RC_ACK) { nfsrc_freecache(rp); continue; } if (force == 0) continue; /* * The timestamps range from roughly the * present (tcp_lasttrim) to the present * + nfsrc_tcptimeout. Generate a simple * histogram of where the timeouts fall. */ j = rp->rc_timestamp - tcp_lasttrim; if (j >= tto) j = HISTSIZE - 1; else if (j < 0) j = 0; else j = j * HISTSIZE / tto; time_histo[j]++; } } mtx_unlock(&nfsrchash_table[i].mtx); } if (force) { /* * Trim some more with a smaller timeout of as little * as 20% of nfsrc_tcptimeout to try and get below * 80% of the nfsrc_tcphighwater. */ k = 0; for (i = 0; i < (HISTSIZE - 2); i++) { k += time_histo[i]; if (k > force) break; } k = tto * (i + 1) / HISTSIZE; if (k < 1) k = 1; thisstamp = tcp_lasttrim + k; for (i = 0; i < NFSRVCACHE_HASHSIZE; i++) { mtx_lock(&nfsrchash_table[i].mtx); LIST_FOREACH_SAFE(rp, &nfsrchash_table[i].tbl, rc_hash, nextrp) { if (!(rp->rc_flag & (RC_INPROG|RC_LOCKED|RC_WANTED)) && rp->rc_refcnt == 0 && ((rp->rc_flag & RC_REFCNT) || thisstamp > rp->rc_timestamp || rp->rc_acked == RC_ACK)) nfsrc_freecache(rp); } mtx_unlock(&nfsrchash_table[i].mtx); } } } atomic_store_rel_int(&onethread, 0); } /* * Add a seqid# reference to the cache entry. */ APPLESTATIC void nfsrvd_refcache(struct nfsrvcache *rp) { struct mtx *mutex; if (rp == NULL) /* For NFSv4.1, there is no cache entry. */ return; mutex = nfsrc_cachemutex(rp); mtx_lock(mutex); if (rp->rc_refcnt < 0) panic("nfs cache refcnt"); rp->rc_refcnt++; mtx_unlock(mutex); } /* * Dereference a seqid# cache entry. */ APPLESTATIC void nfsrvd_derefcache(struct nfsrvcache *rp) { struct mtx *mutex; mutex = nfsrc_cachemutex(rp); mtx_lock(mutex); if (rp->rc_refcnt <= 0) panic("nfs cache derefcnt"); rp->rc_refcnt--; if (rp->rc_refcnt == 0 && !(rp->rc_flag & (RC_LOCKED | RC_INPROG))) nfsrc_freecache(rp); mtx_unlock(mutex); } /* * Calculate the length of the mbuf list and a checksum on the first up to * NFSRVCACHE_CHECKLEN bytes. */ static int nfsrc_getlenandcksum(mbuf_t m1, u_int16_t *cksum) { int len = 0, cklen; mbuf_t m; m = m1; while (m) { len += mbuf_len(m); m = mbuf_next(m); } cklen = (len > NFSRVCACHE_CHECKLEN) ? NFSRVCACHE_CHECKLEN : len; *cksum = in_cksum(m1, cklen); return (len); } /* * Mark a TCP connection that is seeing retries. Should never happen for * NFSv4. */ static void nfsrc_marksametcpconn(u_int64_t sockref) { }
8f5ecda5f4d6e9ede26a8452fd99245234d95e75
f79dec3c4033ca3cbb55d8a51a748cc7b8b6fbab
/sysutils/xentools48/patches/patch-tools_libs_evtchn_netbsd.c
437824ab0559168328c8bf6a1b01834baf96ad39
[]
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
679
c
patch-tools_libs_evtchn_netbsd.c
$NetBSD: patch-tools_libs_evtchn_netbsd.c,v 1.1 2017/03/30 09:15:10 bouyer Exp $ --- tools/libs/evtchn/netbsd.c.orig 2017-03-24 18:23:27.000000000 +0100 +++ tools/libs/evtchn/netbsd.c 2017-03-24 18:23:40.000000000 +0100 @@ -124,7 +124,7 @@ int fd = xce->fd; evtchn_port_t port; - if ( read_exact(fd, (char *)&port, sizeof(port)) == -1 ) + if ( read(fd, (char *)&port, sizeof(port)) == -1 ) return -1; return port; @@ -133,7 +133,7 @@ int xenevtchn_unmask(xenevtchn_handle *xce, evtchn_port_t port) { int fd = xce->fd; - return write_exact(fd, (char *)&port, sizeof(port)); + return write(fd, (char *)&port, sizeof(port)); } /*
6160e5af588da24262745501d1c0b32fd9a4e22c
6e8226bff5369d52885ab75c95f78e155d6afb48
/test/test_property.c
bd34e0d661a6a1f383a76139384042ce9b2786b8
[ "Apache-2.0" ]
permissive
jingweizhanghuai/Morn
a26fc8747fd82c10a94003759a9adc44a60a8353
b9ee92c26190dec03a6726b9ac9d18fb570b7a70
refs/heads/master
2023-03-03T12:02:06.835741
2023-02-17T14:16:34
2023-02-17T14:16:34
187,427,750
257
64
null
null
null
null
UTF-8
C
false
false
3,785
c
test_property.c
#include "morn_util.h" void work(char *name) { int zhuangtai; m_PropertyRead(name,"zhuangtai",&zhuangtai); int shengmingzhi;m_PropertyRead(name,"shengmingzhi",&shengmingzhi); if(zhuangtai==XIUZHENG) { if(shengmingzhi==10000) return; int tineng; m_PropertyRead(name,"tineng",&tineng); shengmingzhi=MIN(10000,shengmingzhi+tineng);mPropertyWrite(name,"shengmingzhi",&shengmingzhi,sizeof(int)); } else if(zhuangtai==BEIZHAN) { char *kaichangbai = mPropertyRead(name,"kaichangbai"); printf(kaichangbai); zhuangtai = ZHANDOU;mPropertyWrite(name,"zhuangtai",&zhuangtai,sizeof(int)); } else if(zhuangtai==ZHANDOU) { int gongjiliang; mPropertyRead(name,"gongjiliang",&gongjiliang,sizeof(int)); shengmingzhi-=gongjiliang;mPropertyWrite(name,"shengmingzhi",&shengmingzhi,sizeof(int)); char *duishou = mPropertyRead(name,"duishou"); if(shengmingzhi<=0) { printf("%s 被 %s"); zhuangtai=SIWANG; mPropertyWrite(name,"zhuangtai",&zhuangtai,sizeof(int)); return; } int wuli = mPropertyRead(name,"wuli",&wuli); char *wuqi = mPropertyRead(name,"wuqi"); int wuqijiacheng;mPropertyRead(wuqi,"wuqijiacheng",&wuqijiacheng); goongjiliang = wuli+wuqijiacheng+mRand(-5,5); mPropertyWrite(duishou,"gongjiliang",&gongjiliang,sizeof(int)); } } int main() { int wuli,shengmingzhi,wuqijiacheng; wuli=90; mPropertyWrite("guanyu","wuli",&wuli,sizeof(int)); shengmingzhi=10000;mPropertyWrite("guanyu","shengmingzhi",&shengmingzhi,sizeof(int)); mPropertyWrite("guanyu","wuqi","qinglongyanyuedao"); mPropertyWrite("guanyu","kaichangbai",""); mPropertyWrite("guanyu","work",work); wuli=85; mPropertyWrite("zhangfei","wuli",&wuli,sizeof(int)); shengmingzhi=10000;mPropertyWrite("zhangfei","shengmingzhi",&shengmingzhi,sizeof(int)); mPropertyWrite("zhangfei","wuqi","zhangbashemao"); mPropertyWrite("zhangfei","kaichangbai",""); mPropertyWrite("zhangfei","work",work); wuli=95; mPropertyWrite("lvbu","wuli",&wuli,sizeof(int)); shengmingzhi=10000;mPropertyWrite("lvbu","shengmingzhi",&shengmingzhi,sizeof(int)); mPropertyWrite("lvbu","wuqi","fangtianhuaji"); mPropertyWrite("lvbu","kaichangbai",""); mPropertyWrite("lvbu","work",work); wuli=80; mPropertyWrite("zhangliao","wuli",&wuli,sizeof(int)); shengmingzhi=10000;mPropertyWrite("zhangliao","shengmingzhi",&shengmingzhi,sizeof(int)); mPropertyWrite("zhangliao","wuqi","zhangbashemao"); mPropertyWrite("zhangliao","kaichangbai",""); mPropertyWrite("zhangliao","work",work); mPropertyWrite("qinglongyanyuedao","wuqijiacheng", } void battle(MObject *obj1,MObject *obj2) { char *name1 = mPropertyRead(obj1,"name"); char *name2 = mPropertyRead(obj2,"name"); int hitpoint1; mPropertyRead(obj1,"hit_point",&hitpoint1); int hitpoint2; mPropertyRead(obj2,"hit_point",&hitpoint2); int force1; mPropertyRead(obj1,"force",&force1); int force2; mPropertyRead(obj2,"force",&force2); printf("%s: %s\n",name1,mPropertyRead(obj1,"whereases")); printf("%s: %s\n",name2,mPropertyRead(obj2,"whereases")); int i;for(i=0;i<g_battle_round;i++) { hitpoint1 -= force2+mRand(-5,5); hitpoint2 -= force1+mRand(-5,5); if(hitpoint1<=0) break; if(hitpoint2<=0) break; mSleep(200); } mPropertyWrite(obj1,"hit_point",&hitpoint1,sizeof(int)); if(hitpoint1<=0) printf("%s 斩 %s 于马下\n",name2,name1); else if(hitpoint1<=0) printf("%s 斩 %s 于马下\n",name2,name1); else printf("大战%d回合,鸣金收兵,\n",g_battle_round); return; }
1c89796f87ed50233f83c3dd1faef84e9be493dd
30b736259b38c916e96f8e1517f92231070f5464
/apps/blemesh_models_example_2/src/transition.c
e31af75de5160bf908c7bb5d077acdb455443792
[ "Apache-2.0", "LicenseRef-scancode-gary-s-brown", "BSD-3-Clause" ]
permissive
apache/mynewt-nimble
5bcc87df4482705c5a6542467bab028c8fd4e5fe
b5e107e9c55f32d18b16e5afc0a7e1720b901b68
refs/heads/master
2023-09-01T19:28:57.874159
2023-08-31T09:07:59
2023-08-31T14:46:07
113,086,218
606
354
Apache-2.0
2023-09-14T12:14:19
2017-12-04T19:34:47
C
UTF-8
C
false
false
19,680
c
transition.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. */ /* Bluetooth: Mesh Generic OnOff, Generic Level, Lighting & Vendor Models * * Copyright (c) 2018 Vikrant More * * SPDX-License-Identifier: Apache-2.0 */ #include "ble_mesh.h" #include "common.h" #include "device_composition.h" #include "state_binding.h" #include "transition.h" struct os_callout onoff_work; struct os_callout level_lightness_work; struct os_callout level_temp_work; struct os_callout light_lightness_actual_work; struct os_callout light_lightness_linear_work; struct os_callout light_ctl_work; struct os_callout light_ctl_temp_work; struct os_callout dummy_timer; uint8_t transition_type, default_tt; uint32_t *ptr_counter; struct os_callout *ptr_timer = &dummy_timer; struct transition lightness_transition, temp_transition; /* Function to calculate Remaining Time (Start) */ void calculate_rt(struct transition *transition) { uint8_t steps, resolution; int32_t duration_remainder; int64_t now; if (transition->just_started) { transition->rt = transition->tt; } else { now = k_uptime_get(); duration_remainder = transition->total_duration - (now - transition->start_timestamp); if (duration_remainder > 620000) { /* > 620 seconds -> resolution = 0b11 [10 minutes] */ resolution = 0x03; steps = duration_remainder / 600000; } else if (duration_remainder > 62000) { /* > 62 seconds -> resolution = 0b10 [10 seconds] */ resolution = 0x02; steps = duration_remainder / 10000; } else if (duration_remainder > 6200) { /* > 6.2 seconds -> resolution = 0b01 [1 seconds] */ resolution = 0x01; steps = duration_remainder / 1000; } else if (duration_remainder > 0) { /* <= 6.2 seconds -> resolution = 0b00 [100 ms] */ resolution = 0x00; steps = duration_remainder / 100; } else { resolution = 0x00; steps = 0x00; } transition->rt = (resolution << 6) | steps; } } /* Function to calculate Remaining Time (End) */ static void bound_states_transition_type_reassignment(uint8_t type) { switch (type) { case ONOFF: case LEVEL: case ACTUAL: case LINEAR: light_ctl_srv_user_data.transition = &lightness_transition; break; case CTL: light_ctl_srv_user_data.transition = &lightness_transition; gen_level_srv_s0_user_data.transition = &lightness_transition; break; case LEVEL_TEMP: case CTL_TEMP: gen_level_srv_s0_user_data.transition = &temp_transition; light_ctl_srv_user_data.transition = &temp_transition; break; default: break; } } static void tt_values_calculator(struct transition *transition) { uint8_t steps_multiplier, resolution; resolution = (transition->tt >> 6); steps_multiplier = (transition->tt & 0x3F); switch (resolution) { case 0: /* 100ms */ transition->total_duration = steps_multiplier * 100; break; case 1: /* 1 second */ transition->total_duration = steps_multiplier * 1000; break; case 2: /* 10 seconds */ transition->total_duration = steps_multiplier * 10000; break; case 3: /* 10 minutes */ transition->total_duration = steps_multiplier * 600000; break; } transition->counter = ((float) transition->total_duration / 100); if (transition->counter > DEVICE_SPECIFIC_RESOLUTION) { transition->counter = DEVICE_SPECIFIC_RESOLUTION; } ptr_counter = &transition->counter; } void onoff_tt_values(struct generic_onoff_state *state, uint8_t tt, uint8_t delay) { bound_states_transition_type_reassignment(ONOFF); calculate_lightness_target_values(ONOFF); state->transition->tt = tt; state->transition->delay = delay; if (tt != 0) { tt_values_calculator(state->transition); } else { return; } state->transition->quo_tt = state->transition->total_duration / state->transition->counter; state->tt_delta = ((float) (lightness - target_lightness) / state->transition->counter); } void level_tt_values(struct generic_level_state *state, uint8_t tt, uint8_t delay) { if (state == &gen_level_srv_root_user_data) { bound_states_transition_type_reassignment(LEVEL); calculate_lightness_target_values(LEVEL); } else if (state == &gen_level_srv_s0_user_data) { bound_states_transition_type_reassignment(LEVEL_TEMP); calculate_temp_target_values(LEVEL_TEMP); } state->transition->tt = tt; state->transition->delay = delay; if (tt != 0) { tt_values_calculator(state->transition); } else { return; } state->transition->quo_tt = state->transition->total_duration / state->transition->counter; state->tt_delta = ((float) (state->level - state->target_level) / state->transition->counter); } void light_lightness_actual_tt_values(struct light_lightness_state *state, uint8_t tt, uint8_t delay) { bound_states_transition_type_reassignment(ACTUAL); calculate_lightness_target_values(ACTUAL); state->transition->tt = tt; state->transition->delay = delay; if (tt != 0) { tt_values_calculator(state->transition); } else { return; } state->transition->quo_tt = state->transition->total_duration / state->transition->counter; state->tt_delta_actual = ((float) (state->actual - state->target_actual) / state->transition->counter); } void light_lightness_linear_tt_values(struct light_lightness_state *state, uint8_t tt, uint8_t delay) { bound_states_transition_type_reassignment(LINEAR); calculate_lightness_target_values(LINEAR); state->transition->tt = tt; state->transition->delay = delay; if (tt != 0) { tt_values_calculator(state->transition); } else { return; } state->transition->quo_tt = state->transition->total_duration / state->transition->counter; state->tt_delta_linear = ((float) (state->linear - state->target_linear) / state->transition->counter); } void light_ctl_tt_values(struct light_ctl_state *state, uint8_t tt, uint8_t delay) { bound_states_transition_type_reassignment(CTL); calculate_lightness_target_values(CTL); state->transition->tt = tt; state->transition->delay = delay; if (tt != 0) { tt_values_calculator(state->transition); } else { return; } state->transition->quo_tt = state->transition->total_duration / state->transition->counter; state->tt_delta_lightness = ((float) (state->lightness - state->target_lightness) / state->transition->counter); state->tt_delta_temp = ((float) (state->temp - state->target_temp) / state->transition->counter); state->tt_delta_duv = ((float) (state->delta_uv - state->target_delta_uv) / state->transition->counter); } void light_ctl_temp_tt_values(struct light_ctl_state *state, uint8_t tt, uint8_t delay) { bound_states_transition_type_reassignment(CTL_TEMP); calculate_temp_target_values(CTL_TEMP); state->transition->tt = tt; state->transition->delay = delay; if (tt != 0) { tt_values_calculator(state->transition); } else { return; } state->transition->quo_tt = state->transition->total_duration / state->transition->counter; state->tt_delta_temp = ((float) (state->temp - state->target_temp) / state->transition->counter); state->tt_delta_duv = ((float) (state->delta_uv - state->target_delta_uv) / state->transition->counter); } /* Timers related handlers & threads (Start) */ static void onoff_work_handler(struct os_event *work) { struct generic_onoff_state *state = &gen_onoff_srv_root_user_data; if (state->transition->just_started) { state->transition->just_started = false; if (state->transition->counter == 0) { state_binding(ONOFF, IGNORE_TEMP); update_light_state(); os_callout_stop(ptr_timer); } else { state->transition->start_timestamp = k_uptime_get(); if (state->target_onoff == STATE_ON) { state->onoff = STATE_ON; } } return; } if (state->transition->counter != 0) { state->transition->counter--; lightness -= state->tt_delta; state_binding(IGNORE, IGNORE_TEMP); update_light_state(); } if (state->transition->counter == 0) { state->onoff = state->target_onoff; lightness = target_lightness; state_binding(IGNORE, IGNORE_TEMP); update_light_state(); os_callout_stop(ptr_timer); } } static void level_lightness_work_handler(struct os_event *work) { uint8_t level; struct generic_level_state *state = &gen_level_srv_root_user_data; switch (transition_type) { case LEVEL_TT: level = LEVEL; break; case LEVEL_TT_DELTA: level = DELTA_LEVEL; break; case LEVEL_TT_MOVE: level = LEVEL; break; default: return; } if (state->transition->just_started) { state->transition->just_started = false; if (state->transition->counter == 0) { state_binding(level, IGNORE_TEMP); update_light_state(); os_callout_stop(ptr_timer); } else { state->transition->start_timestamp = k_uptime_get(); } return; } if (state->transition->counter != 0) { state->transition->counter--; state->level -= state->tt_delta; state_binding(level, IGNORE_TEMP); update_light_state(); } if (state->transition->counter == 0) { state->level = state->target_level; state_binding(level, IGNORE_TEMP); update_light_state(); os_callout_stop(ptr_timer); } } static void level_temp_work_handler(struct os_event *work) { struct generic_level_state *state = &gen_level_srv_s0_user_data; switch (transition_type) { case LEVEL_TEMP_TT: break; case LEVEL_TEMP_TT_DELTA: break; case LEVEL_TEMP_TT_MOVE: break; default: return; } if (state->transition->just_started) { state->transition->just_started = false; if (state->transition->counter == 0) { state_binding(IGNORE, LEVEL_TEMP); update_light_state(); os_callout_stop(ptr_timer); } else { state->transition->start_timestamp = k_uptime_get(); } return; } if (state->transition->counter != 0) { state->transition->counter--; state->level -= state->tt_delta; state_binding(IGNORE, LEVEL_TEMP); update_light_state(); } if (state->transition->counter == 0) { state->level = state->target_level; state_binding(IGNORE, LEVEL_TEMP); update_light_state(); os_callout_stop(ptr_timer); } } static void light_lightness_actual_work_handler(struct os_event *work) { struct light_lightness_state *state = &light_lightness_srv_user_data; if (state->transition->just_started) { state->transition->just_started = false; if (state->transition->counter == 0) { state_binding(ACTUAL, IGNORE_TEMP); update_light_state(); os_callout_stop(ptr_timer); } else { state->transition->start_timestamp = k_uptime_get(); } return; } if (state->transition->counter != 0) { state->transition->counter--; state->actual -= state->tt_delta_actual; state_binding(ACTUAL, IGNORE_TEMP); update_light_state(); } if (state->transition->counter == 0) { state->actual = state->target_actual; state_binding(ACTUAL, IGNORE_TEMP); update_light_state(); os_callout_stop(ptr_timer); } } static void light_lightness_linear_work_handler(struct os_event *work) { struct light_lightness_state *state = &light_lightness_srv_user_data; if (state->transition->just_started) { state->transition->just_started = false; if (state->transition->counter == 0) { state_binding(LINEAR, IGNORE_TEMP); update_light_state(); os_callout_stop(ptr_timer); } else { state->transition->start_timestamp = k_uptime_get(); } return; } if (state->transition->counter != 0) { state->transition->counter--; state->linear -= state->tt_delta_linear; state_binding(LINEAR, IGNORE_TEMP); update_light_state(); } if (state->transition->counter == 0) { state->linear = state->target_linear; state_binding(LINEAR, IGNORE_TEMP); update_light_state(); os_callout_stop(ptr_timer); } } static void light_ctl_work_handler(struct os_event *work) { struct light_ctl_state *state = &light_ctl_srv_user_data; if (state->transition->just_started) { state->transition->just_started = false; if (state->transition->counter == 0) { state_binding(CTL, CTL_TEMP); update_light_state(); os_callout_stop(ptr_timer); } else { state->transition->start_timestamp = k_uptime_get(); } return; } if (state->transition->counter != 0) { state->transition->counter--; /* Lightness */ state->lightness -= state->tt_delta_lightness; /* Temperature */ state->temp -= state->tt_delta_temp; /* Delta_UV */ state->delta_uv -= state->tt_delta_duv; state_binding(CTL, CTL_TEMP); update_light_state(); } if (state->transition->counter == 0) { state->lightness = state->target_lightness; state->temp = state->target_temp; state->delta_uv = state->target_delta_uv; state_binding(CTL, CTL_TEMP); update_light_state(); os_callout_stop(ptr_timer); } } static void light_ctl_temp_work_handler(struct os_event *work) { struct light_ctl_state *state = &light_ctl_srv_user_data; if (state->transition->just_started) { state->transition->just_started = false; if (state->transition->counter == 0) { state_binding(IGNORE, CTL_TEMP); update_light_state(); os_callout_stop(ptr_timer); } else { state->transition->start_timestamp = k_uptime_get(); } return; } if (state->transition->counter != 0) { state->transition->counter--; /* Temperature */ state->temp -= state->tt_delta_temp; /* Delta UV */ state->delta_uv -= state->tt_delta_duv; state_binding(IGNORE, CTL_TEMP); update_light_state(); } if (state->transition->counter == 0) { state->temp = state->target_temp; state->delta_uv = state->target_delta_uv; state_binding(IGNORE, CTL_TEMP); update_light_state(); os_callout_stop(ptr_timer); } } static void dummy_timer_handler(struct os_event *ev) { } static void onoff_tt_handler(struct os_event *ev) { struct generic_onoff_state *state = ev->ev_arg; assert(state != NULL); os_callout_reset(&onoff_work, 0); os_callout_reset(&state->transition->timer, os_time_ms_to_ticks32( K_MSEC(state->transition->quo_tt))); } static void level_lightness_tt_handler(struct os_event *ev) { struct generic_level_state *state = ev->ev_arg; assert(state != NULL); os_callout_reset(&level_lightness_work, 0); os_callout_reset(&state->transition->timer, os_time_ms_to_ticks32( K_MSEC(state->transition->quo_tt))); } static void level_temp_tt_handler(struct os_event *ev) { struct generic_level_state *state = ev->ev_arg; assert(state != NULL); os_callout_reset(&level_temp_work, 0); os_callout_reset(&state->transition->timer, os_time_ms_to_ticks32( K_MSEC(state->transition->quo_tt))); } static void light_lightness_actual_tt_handler(struct os_event *ev) { struct light_lightness_state *state = ev->ev_arg; assert(state != NULL); os_callout_reset(&light_lightness_actual_work, 0); os_callout_reset(&state->transition->timer, os_time_ms_to_ticks32( K_MSEC(state->transition->quo_tt))); } static void light_lightness_linear_tt_handler(struct os_event *ev) { struct light_lightness_state *state = ev->ev_arg; assert(state != NULL); os_callout_reset(&light_lightness_linear_work, 0); os_callout_reset(&state->transition->timer, os_time_ms_to_ticks32( K_MSEC(state->transition->quo_tt))); } static void light_ctl_tt_handler(struct os_event *ev) { struct light_ctl_state *state = ev->ev_arg; assert(state != NULL); os_callout_reset(&light_ctl_work, 0); os_callout_reset(&state->transition->timer, os_time_ms_to_ticks32( K_MSEC(state->transition->quo_tt))); } static void light_ctl_temp_tt_handler(struct os_event *ev) { struct light_ctl_state *state = ev->ev_arg; assert(state != NULL); os_callout_reset(&light_ctl_temp_work, 0); os_callout_reset(&state->transition->timer, os_time_ms_to_ticks32( K_MSEC(state->transition->quo_tt))); } /* Timers related handlers & threads (End) */ /* Messages handlers (Start) */ void onoff_handler(struct generic_onoff_state *state) { ptr_timer = &state->transition->timer; os_callout_init(ptr_timer, os_eventq_dflt_get(), onoff_tt_handler, NULL); ptr_timer->c_ev.ev_arg = state; os_callout_reset(ptr_timer, os_time_ms_to_ticks32( K_MSEC(5 * state->transition->delay))); } void level_lightness_handler(struct generic_level_state *state) { ptr_timer = &state->transition->timer; os_callout_init(ptr_timer, os_eventq_dflt_get(), level_lightness_tt_handler, NULL); ptr_timer->c_ev.ev_arg = state; os_callout_reset(ptr_timer, os_time_ms_to_ticks32( K_MSEC(5 * state->transition->delay))); } void level_temp_handler(struct generic_level_state *state) { ptr_timer = &state->transition->timer; os_callout_init(ptr_timer, os_eventq_dflt_get(), level_temp_tt_handler, NULL); ptr_timer->c_ev.ev_arg = state; os_callout_reset(ptr_timer, os_time_ms_to_ticks32( K_MSEC(5 * state->transition->delay))); } void light_lightness_actual_handler(struct light_lightness_state *state) { ptr_timer = &state->transition->timer; os_callout_init(ptr_timer, os_eventq_dflt_get(), light_lightness_actual_tt_handler, NULL); ptr_timer->c_ev.ev_arg = state; os_callout_reset(ptr_timer, os_time_ms_to_ticks32( K_MSEC(5 * state->transition->delay))); } void light_lightness_linear_handler(struct light_lightness_state *state) { ptr_timer = &state->transition->timer; os_callout_init(ptr_timer, os_eventq_dflt_get(), light_lightness_linear_tt_handler, NULL); ptr_timer->c_ev.ev_arg = state; os_callout_reset(ptr_timer, os_time_ms_to_ticks32( K_MSEC(5 * state->transition->delay))); } void light_ctl_handler(struct light_ctl_state *state) { ptr_timer = &state->transition->timer; os_callout_init(ptr_timer, os_eventq_dflt_get(), light_ctl_tt_handler, NULL); ptr_timer->c_ev.ev_arg = state; os_callout_reset(ptr_timer, os_time_ms_to_ticks32( K_MSEC(5 * state->transition->delay))); } void light_ctl_temp_handler(struct light_ctl_state *state) { ptr_timer = &state->transition->timer; os_callout_init(ptr_timer, os_eventq_dflt_get(), light_ctl_temp_tt_handler, NULL); ptr_timer->c_ev.ev_arg = state; os_callout_reset(ptr_timer, os_time_ms_to_ticks32( K_MSEC(5 * state->transition->delay))); } /* Messages handlers (End) */ void transition_timers_init(void) { os_callout_init(&onoff_work, os_eventq_dflt_get(), onoff_work_handler, NULL); os_callout_init(&level_lightness_work, os_eventq_dflt_get(), level_lightness_work_handler, NULL); os_callout_init(&level_temp_work, os_eventq_dflt_get(), level_temp_work_handler, NULL); os_callout_init(&light_lightness_actual_work, os_eventq_dflt_get(), light_lightness_actual_work_handler, NULL); os_callout_init(&light_lightness_linear_work, os_eventq_dflt_get(), light_lightness_linear_work_handler, NULL); os_callout_init(&light_ctl_work, os_eventq_dflt_get(), light_ctl_work_handler, NULL); os_callout_init(&light_ctl_temp_work, os_eventq_dflt_get(), light_ctl_temp_work_handler, NULL); os_callout_init(&dummy_timer, os_eventq_dflt_get(), dummy_timer_handler, NULL); }
562eb276989cd5eb04d6dfac3d51b2a477bc40a8
19a9f2c19bcb81c4a14ba17831d3098de7731fb5
/ni/src/examples/mapplot/mp03c.c
88e4558a598bcbf5bc68373b1e6faf1ec48b1d5c
[ "Apache-2.0" ]
permissive
NCAR/ncl
243c30eaefce642d53373aa583b73df72eb59f22
8a96101fe14d0cf0f5ed66a5e6b1733084bc69df
refs/heads/develop
2023-03-17T07:53:18.883458
2022-05-11T16:01:03
2022-05-11T16:01:03
67,087,395
254
68
NOASSERTION
2022-10-08T07:20:06
2016-09-01T01:34:28
C
UTF-8
C
false
false
8,386
c
mp03c.c
/* * $Id: mp03c.c,v 1.11 2010-03-15 22:49:24 haley Exp $ */ /*********************************************************************** * * * Copyright (C) 1993 * * University Corporation for Atmospheric Research * * All Rights Reserved * * * ***********************************************************************/ /* * File: mp03c.c * * Author: David Brown * National Center for Atmospheric Research * PO 3000, Boulder, Colorado * * Date: Fri Oct 14 11:42:41 MDT 1994 * * Description: Demonstrates MapPlot masking; loosely emulates the * LLU example 'colcon' */ #include <stdio.h> #include <math.h> #include <ncarg/gks.h> #include <ncarg/ncargC.h> #include <ncarg/hlu/hlu.h> #include <ncarg/hlu/App.h> #include <ncarg/hlu/NcgmWorkstation.h> #include <ncarg/hlu/PSWorkstation.h> #include <ncarg/hlu/PDFWorkstation.h> #include <ncarg/hlu/CairoWorkstation.h> #include <ncarg/hlu/MapPlot.h> #include <ncarg/hlu/ContourPlot.h> #include <ncarg/hlu/ScalarField.h> int main(int argc, char *argv[]) { int appid,wid,mapid,dataid,cnid; int rlist; float Z[50*50]; int M = 50, N = 50; int mlow = 13, mhigh = 18; float dlow = 13.0, dhigh = 18.0; ng_size_t len_dims[2]; char const *wks_type = "x11"; extern void gendat(); NhlString mask_specs[] = { "oceans" }; /* * Initialize the high level utility library */ NhlInitialize(); /* * Create an application context. Set the app dir to the current * directory so the application looks for a resource file in the working * directory. */ rlist = NhlRLCreate(NhlSETRL); NhlRLClear(rlist); NhlRLSetString(rlist,NhlNappUsrDir,"./"); NhlCreate(&appid,"mp03",NhlappClass,NhlDEFAULT_APP,rlist); if (!strcmp(wks_type,"ncgm") || !strcmp(wks_type,"NCGM")) { /* * Create a meta file workstation. */ NhlRLClear(rlist); NhlRLSetString(rlist,NhlNwkMetaName,"./mp03c.ncgm"); NhlCreate(&wid,"mp03Work", NhlncgmWorkstationClass,NhlDEFAULT_APP,rlist); } else if (!strcmp(wks_type,"x11") || !strcmp(wks_type,"X11")) { /* * Create an X workstation. */ NhlRLClear(rlist); NhlRLSetInteger(rlist,NhlNwkPause,True); NhlCreate(&wid,"mp03Work",NhlcairoWindowWorkstationClass,appid,rlist); } else if (!strcmp(wks_type,"oldps") || !strcmp(wks_type,"OLDPS")) { /* * Create an older-style PostScript workstation. */ NhlRLClear(rlist); NhlRLSetString(rlist,NhlNwkPSFileName,"mp03c.ps"); NhlCreate(&wid,"mp03Work",NhlpsWorkstationClass,appid,rlist); } else if (!strcmp(wks_type,"oldpdf") || !strcmp(wks_type,"OLDPDF")) { /* * Create an older-style PDF workstation. */ NhlRLClear(rlist); NhlRLSetString(rlist,NhlNwkPDFFileName,"mp03c.pdf"); NhlCreate(&wid,"mp03Work",NhlpdfWorkstationClass,appid,rlist); } else if (!strcmp(wks_type,"pdf") || !strcmp(wks_type,"PDF") || !strcmp(wks_type,"ps") || !strcmp(wks_type,"PS")) { /* * Create a cairo PS/PDF workstation. */ NhlRLClear(rlist); NhlRLSetString(rlist,NhlNwkFileName,"mp03c"); NhlRLSetString(rlist,NhlNwkFormat,(char*)wks_type); NhlCreate(&wid,"mp03Work",NhlcairoDocumentWorkstationClass,appid,rlist); } else if (!strcmp(wks_type,"png") || !strcmp(wks_type,"PNG")) { /* * Create a cairo PNG workstation. */ NhlRLClear(rlist); NhlRLSetString(rlist,NhlNwkFileName,"mp03c"); NhlRLSetString(rlist,NhlNwkFormat,(char*)wks_type); NhlCreate(&wid,"mp03Work",NhlcairoImageWorkstationClass,appid,rlist); } /* * Call the routine 'gendat' to create the first array of contour * data. Create a ScalarField data object and hand it the data created by * 'gendat'. Define the extent of the data coordinates as the whole * globe */ NhlRLClear(rlist); len_dims[0] = N; len_dims[1] = M; gendat(Z,M,M,N,mlow,mhigh,dlow,dhigh); NhlRLSetMDFloatArray(rlist,NhlNsfDataArray,Z,2,len_dims); NhlRLSetInteger(rlist,NhlNsfXCStartV,-180); NhlRLSetInteger(rlist,NhlNsfXCEndV,180); NhlRLSetInteger(rlist,NhlNsfYCStartV,-90); NhlRLSetInteger(rlist,NhlNsfYCEndV,90); NhlCreate(&dataid,"Gendat",NhlscalarFieldClass,appid,rlist); /* * Create a Contour object, supplying the ScalarField object as data, * and setting the size of the viewport. */ NhlRLClear(rlist); NhlRLSetInteger(rlist,NhlNcnScalarFieldData,dataid); NhlRLSetString(rlist,NhlNcnLabelDrawOrder,"postdraw"); NhlCreate(&cnid,"Contour1",NhlcontourPlotClass,wid,rlist); /* * Create a MapPlot object, setting the fill to draw over the main draw, * and masking out the oceans. */ NhlRLClear(rlist); NhlRLSetString(rlist,NhlNmpFillOn,"true"); NhlRLSetString(rlist,NhlNpmTitleDisplayMode,"always"); NhlRLSetString(rlist,NhlNtiMainString,"mp03c"); NhlRLSetString(rlist,NhlNmpFillDrawOrder,"postdraw"); NhlRLSetString(rlist,NhlNmpAreaMaskingOn,"true"); NhlRLSetStringArray(rlist,NhlNmpMaskAreaSpecifiers, mask_specs,NhlNumber(mask_specs)); NhlCreate(&mapid,"Map1",NhlmapPlotClass,wid,rlist); /* * Overlay the Contour object on the MapPlot object */ NhlAddOverlay(mapid,cnid,-1); NhlDraw(mapid); NhlFrame(wid); /* * Destroy the objects created, close the HLU library and exit. */ NhlDestroy(mapid); NhlDestroy(wid); NhlClose(); exit(0); } #define max(x,y) ((x) > (y) ? (x) : (y) ) #define min(x,y) ((x) < (y) ? (x) : (y) ) #define pow2(x) ((x)*(x)) void gendat (data,idim,m,n,mlow,mhgh,dlow,dhgh) float *data, dlow, dhgh; int idim, m, n, mlow, mhgh; { /* * This is a routine to generate test data for two-dimensional graphics * routines. Given an array "DATA", dimensioned "IDIM x 1", it fills * the sub-array ((DATA(I,J),I=1,M),J=1,N) with a two-dimensional field * of data having approximately "MLOW" lows and "MHGH" highs, a minimum * value of exactly "DLOW" and a maximum value of exactly "DHGH". * * "MLOW" and "MHGH" are each forced to be greater than or equal to 1 * and less than or equal to 25. * * The function used is a sum of exponentials. */ float ccnt[3][50], fovm, fovn, dmin, dmax, temp; extern float fran(); int nlow, nhgh, ncnt, i, j, k, ii; fovm=9./(float)m; fovn=9./(float)n; nlow=max(1,min(25,mlow)); nhgh=max(1,min(25,mhgh)); ncnt=nlow+nhgh; for( k=1; k <= ncnt; k++ ) { ccnt[0][k-1]=1.+((float)m-1.)*fran(); ccnt[1][k-1]=1.+((float)n-1.)*fran(); if (k <= nlow) { ccnt[2][k-1]= -1.; } else { ccnt[2][k-1] = 1.; } } dmin = 1.e36; dmax = -1.e36; ii = 0; for( j = 1; j <= n; j++ ) { for( i = 1; i <= m; i++ ) { data[ii]=.5*(dlow+dhgh); for( k = 1; k <= ncnt; k++ ) { temp = -(pow2((fovm*((float)(i)-ccnt[0][k-1])))+ pow2(fovn*((float)(j)-ccnt[1][k-1]))); if (temp >= -20.) data[ii]=data[ii]+.5*(dhgh-dlow) *ccnt[2][k-1]*exp(temp); } dmin=min(dmin,data[ii]); dmax=max(dmax,data[ii]); ii++; } } for( j = 0; j < m*n; j++ ) { data[j]=(data[j]-dmin)/(dmax-dmin)*(dhgh-dlow)+dlow; } } float rseq[] = { .749, .973, .666, .804, .081, .483, .919, .903, .951, .960, .039, .269, .270, .756, .222, .478, .621, .063, .550, .798, .027, .569, .149, .697, .451, .738, .508, .041, .266, .249, .019, .191, .266, .625, .492, .940, .508, .406, .972, .311, .757, .378, .299, .536, .619, .844, .342, .295, .447, .499, .688, .193, .225, .520, .954, .749, .997, .693, .217, .273, .961, .948, .902, .104, .495, .257, .524, .100, .492, .347, .981, .019, .225, .806, .678, .710, .235, .600, .994, .758, .682, .373, .009, .469, .203, .730, .588, .603, .213, .495, .884, .032, .185, .127, .010, .180, .689, .354, .372, .429 }; float fran() { static int iseq = 0; iseq = (iseq % 100) + 1; return(rseq[iseq-1]); }
3cb1ad5647ac05e686c0566ba0591e891537e898
fbdc48c28e54fb33ae4842ef95ff63893902c99a
/src/drivers/lepton/include/LEPTON_OEM.h
c045c398b963005f1db36f711289623d922faa93
[ "MIT" ]
permissive
openmv/openmv
44d4b79fc8693950a2e330e5e0fd95b5c36e230f
8a90e070a88b7fc14c87a00351b9c4a213278419
refs/heads/master
2023-08-30T20:59:57.227603
2023-08-23T16:50:55
2023-08-23T16:50:55
14,360,940
2,150
1,226
MIT
2023-09-14T07:18:15
2013-11-13T10:23:44
C
UTF-8
C
false
false
25,531
h
LEPTON_OEM.h
/******************************************************************************* ** ** File NAME: LEPTON_OEM.h ** ** AUTHOR: David Dart ** ** CREATED: 8/6/2012 ** ** DESCRIPTION: COntains OEM Interfaces ** ** HISTORY: 8/6/2012 DWD - Initial Draft ** ** Copyright 2011,2012,2013,2014 FLIR Systems - Commercial ** Vision Systems. All rights reserved. ** ** Proprietary - PROPRIETARY - FLIR Systems Inc.. ** ** This document is controlled to FLIR Technology Level 2. ** The information contained in this document pertains to a ** dual use product Controlled for export by the Export ** Administration Regulations (EAR). Diversion contrary to ** US law is prohibited. US Department of Commerce ** authorization is not required prior to export or ** transfer to foreign persons or parties unless otherwise ** prohibited. ** ** 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 FLIR Systems Corporation 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 _LEPTON_OEM_H_ #define _LEPTON_OEM_H_ #ifdef __cplusplus extern "C" { #endif /******************************************************************************/ /** INCLUDE FILES **/ /******************************************************************************/ #include "LEPTON_Types.h" #include "LEPTON_ErrorCodes.h" /******************************************************************************/ /** EXPORTED DEFINES **/ /******************************************************************************/ /* OEM Module Command IDs */ #define LEP_OEM_MODULE_BASE 0x0800 #define LEP_CID_OEM_POWER_DOWN (LEP_OEM_MODULE_BASE + 0x4000 ) #define LEP_CID_OEM_STANDBY (LEP_OEM_MODULE_BASE + 0x4004 ) #define LEP_CID_OEM_LOW_POWER_MODE_1 (LEP_OEM_MODULE_BASE + 0x4008 ) #define LEP_CID_OEM_LOW_POWER_MODE_2 (LEP_OEM_MODULE_BASE + 0x400C ) #define LEP_CID_OEM_BIT_TEST (LEP_OEM_MODULE_BASE + 0x4010 ) #define LEP_CID_OEM_MASK_REVISION (LEP_OEM_MODULE_BASE + 0x4014 ) //#define LEP_CID_OEM_MASTER_ID (LEP_OEM_MODULE_BASE + 0x4018 ) #define LEP_CID_OEM_FLIR_PART_NUMBER (LEP_OEM_MODULE_BASE + 0x401C ) #define LEP_CID_OEM_SOFTWARE_VERSION (LEP_OEM_MODULE_BASE + 0x4020 ) #define LEP_CID_OEM_VIDEO_OUTPUT_ENABLE (LEP_OEM_MODULE_BASE + 0x4024 ) #define LEP_CID_OEM_VIDEO_OUTPUT_FORMAT (LEP_OEM_MODULE_BASE + 0x4028 ) #define LEP_CID_OEM_VIDEO_OUTPUT_SOURCE (LEP_OEM_MODULE_BASE + 0x402C ) #define LEP_CID_OEM_VIDEO_OUTPUT_CHANNEL (LEP_OEM_MODULE_BASE + 0x4030 ) #define LEP_CID_OEM_VIDEO_GAMMA_ENABLE (LEP_OEM_MODULE_BASE + 0x4034 ) #define LEP_CID_OEM_CUST_PART_NUMBER (LEP_OEM_MODULE_BASE + 0x4038 ) #define LEP_CID_OEM_VIDEO_OUTPUT_CONSTANT (LEP_OEM_MODULE_BASE + 0x403C ) #define LEP_CID_OEM_REBOOT (LEP_OEM_MODULE_BASE + 0x4040 ) #define LEP_CID_OEM_FFC_NORMALIZATION_TARGET (LEP_OEM_MODULE_BASE + 0x4044 ) #define LEP_CID_OEM_STATUS (LEP_OEM_MODULE_BASE + 0x4048 ) #define LEP_CID_OEM_SCENE_MEAN_VALUE (LEP_OEM_MODULE_BASE + 0x404C ) #define LEP_CID_OEM_POWER_MODE (LEP_OEM_MODULE_BASE + 0x4050 ) #define LEP_CID_OEM_GPIO_MODE_SELECT (LEP_OEM_MODULE_BASE + 0x4054 ) #define LEP_CID_OEM_GPIO_VSYNC_PHASE_DELAY (LEP_OEM_MODULE_BASE + 0x4058 ) #define LEP_CID_OEM_USER_DEFAULTS (LEP_OEM_MODULE_BASE + 0x405C ) #define LEP_CID_OEM_USER_DEFAULTS_RESTORE (LEP_OEM_MODULE_BASE + 0x4060 ) #define LEP_CID_OEM_SHUTTER_PROFILE_OBJ (LEP_OEM_MODULE_BASE + 0x4064 ) #define LEP_CID_OEM_THERMAL_SHUTDOWN_ENABLE_STATE (LEP_OEM_MODULE_BASE + 0x4068 ) #define LEP_CID_OEM_BAD_PIXEL_REPLACE_CONTROL (LEP_OEM_MODULE_BASE + 0x406C ) #define LEP_CID_OEM_TEMPORAL_FILTER_CONTROL (LEP_OEM_MODULE_BASE + 0x4070 ) #define LEP_CID_OEM_COLUMN_NOISE_ESTIMATE_CONTROL (LEP_OEM_MODULE_BASE + 0x4074 ) #define LEP_CID_OEM_PIXEL_NOISE_ESTIMATE_CONTROL (LEP_OEM_MODULE_BASE + 0x4078 ) #define LEP_OEM_MAX_PART_NUMBER_CHAR_SIZE 32 /******************************************************************************/ /** EXPORTED TYPE DEFINITIONS **/ /******************************************************************************/ /* Chip Mask Revision: An (8 bit depth) identifier for the chip ** mask revision located in bits 7-0 of the 16-bit word passed. */ typedef LEP_UINT16 LEP_OEM_MASK_REVISION_T,*LEP_OEM_MASK_REVISION_T_PTR; typedef LEP_UINT16 LEP_OEM_FFC_NORMALIZATION_TARGET_T, *LEP_OEM_FFC_NORMALIZATION_TARGET_T_PTR; typedef LEP_UINT16 LEP_OEM_FRAME_AVERAGE_T, *LEP_OEM_FRAME_AVERAGE_T_PTR; //typedef LEP_UINT16 LEP_OEM_VENDORID_T; /* Part Number: A (32 byte string) identifier unique to a ** specific configuration of module; essentially a module ** Configuration ID. */ #if USE_DEPRECATED_PART_NUMBER_INTERFACE typedef LEP_CHAR8 *LEP_OEM_PART_NUMBER_T, *LEP_OEM_PART_NUMBER_T_PTR; #else typedef struct LEP_OEM_PART_NUMBER_T_TAG { LEP_CHAR8 value[LEP_OEM_MAX_PART_NUMBER_CHAR_SIZE]; } LEP_OEM_PART_NUMBER_T, *LEP_OEM_PART_NUMBER_T_PTR; #endif #if 0 typedef struct { LEP_CHAR8 value[32]; /* 32-byte string */ } LEP_OEM_PART_NUMBER_T, *LEP_OEM_PART_NUMBER_T_PTR; #endif /* Software Version ID: A (24 bit depth) identifier for ** the software version stored in OTP. */ typedef struct LEP_OEM_SW_VERSION_TAG { LEP_UINT8 gpp_major; LEP_UINT8 gpp_minor; LEP_UINT8 gpp_build; LEP_UINT8 dsp_major; LEP_UINT8 dsp_minor; LEP_UINT8 dsp_build; LEP_UINT16 reserved; }LEP_OEM_SW_VERSION_T, *LEP_OEM_SW_VERSION_T_PTR; #if 0 /* Chip Master ID: A (16 byte depth) identifier for the ISC1103 ** signal processing ASIC. */ typedef struct LEP_OEM_MASTER_ID_T_TAG { LEP_UINT8 value[16]; /* 16 byte value */ } LEP_OEM_MASTER_ID_T, *LEP_OEM_MASTER_ID_T_PTR; #endif /* Video Output Enable Enum */ typedef enum LEP_OEM_VIDEO_OUTPUT_ENABLE_TAG { LEP_VIDEO_OUTPUT_DISABLE = 0, LEP_VIDEO_OUTPUT_ENABLE, LEP_END_VIDEO_OUTPUT_ENABLE, LEP_VIDEO_OUTPUT_ENABLE_MAKE_32_BIT_ENUM = 0x7FFFFFFF }LEP_OEM_VIDEO_OUTPUT_ENABLE_E, *LEP_OEM_VIDEO_OUTPUT_ENABLE_E_PTR; /* Video Output Format Selection */ typedef enum LEP_OEM_VIDEO_OUTPUT_FORMAT_TAG { LEP_VIDEO_OUTPUT_FORMAT_RAW8 = 0, // To be supported in later release LEP_VIDEO_OUTPUT_FORMAT_RAW10, // To be supported in later release LEP_VIDEO_OUTPUT_FORMAT_RAW12, // To be supported in later release LEP_VIDEO_OUTPUT_FORMAT_RGB888, // To be supported in later release LEP_VIDEO_OUTPUT_FORMAT_RGB666, // To be supported in later release LEP_VIDEO_OUTPUT_FORMAT_RGB565, // To be supported in later release LEP_VIDEO_OUTPUT_FORMAT_YUV422_8BIT, // To be supported in later release LEP_VIDEO_OUTPUT_FORMAT_RAW14, // SUPPORTED in this release LEP_VIDEO_OUTPUT_FORMAT_YUV422_10BIT, // To be supported in later release LEP_VIDEO_OUTPUT_FORMAT_USER_DEFINED, // To be supported in later release LEP_VIDEO_OUTPUT_FORMAT_RAW8_2, // To be supported in later release LEP_VIDEO_OUTPUT_FORMAT_RAW8_3, // To be supported in later release LEP_VIDEO_OUTPUT_FORMAT_RAW8_4, // To be supported in later release LEP_VIDEO_OUTPUT_FORMAT_RAW8_5, // To be supported in later release LEP_VIDEO_OUTPUT_FORMAT_RAW8_6, // To be supported in later release LEP_END_VIDEO_OUTPUT_FORMAT, LEP_VIDEO_OUTPUT_FORMAT_MAKE_32_BIT_ENUM = 0x7FFFFFFF }LEP_OEM_VIDEO_OUTPUT_FORMAT_E, *LEP_OEM_VIDEO_OUTPUT_FORMAT_E_PTR; /* Video Output Source Selection */ typedef enum LEP_OEM_VIDEO_OUTPUT_SOURCE_TAG { LEP_VIDEO_OUTPUT_SOURCE_RAW = 0, /* Before video processing */ LEP_VIDEO_OUTPUT_SOURCE_COOKED, /* Post video processing - NORMAL MODE */ LEP_VIDEO_OUTPUT_SOURCE_RAMP, /* Software Ramp pattern - increase in X, Y */ LEP_VIDEO_OUTPUT_SOURCE_CONSTANT, /* Software Constant value pattern */ LEP_VIDEO_OUTPUT_SOURCE_RAMP_H, /* Software Ramp pattern - increase in X only */ LEP_VIDEO_OUTPUT_SOURCE_RAMP_V, /* Software Ramp pattern - increase in Y only */ LEP_VIDEO_OUTPUT_SOURCE_RAMP_CUSTOM, /* Software Ramp pattern - uses custom settings */ /* Additions to support frame averaging, freeze frame, and data buffers */ LEP_VIDEO_OUTPUT_SOURCE_FRAME_CAPTURE, // Average, Capture frame LEP_VIDEO_OUTPUT_SOURCE_FRAME_FREEZE, // Freeze-Frame Buffer /* RESERVED BUFFERS */ LEP_VIDEO_OUTPUT_SOURCE_FRAME_0, // Reserved DATA Buffer LEP_VIDEO_OUTPUT_SOURCE_FRAME_1, // Reserved DATA Buffer LEP_VIDEO_OUTPUT_SOURCE_FRAME_2, // Reserved DATA Buffer LEP_VIDEO_OUTPUT_SOURCE_FRAME_3, // Reserved DATA Buffer LEP_VIDEO_OUTPUT_SOURCE_FRAME_4, // Reserved DATA Buffer LEP_END_VIDEO_OUTPUT_SOURCE, LEP_VIDEO_OUTPUT_SOURCE_MAKE_32_BIT_ENUM = 0x7FFFFFFF }LEP_OEM_VIDEO_OUTPUT_SOURCE_E, *LEP_OEM_VIDEO_OUTPUT_SOURCE_E_PTR; /* Video Output Channel Selection */ typedef enum LEP_OEM_VIDEO_OUTPUT_CHANNEL_TAG { LEP_VIDEO_OUTPUT_CHANNEL_MIPI = 0, LEP_VIDEO_OUTPUT_CHANNEL_VOSPI, LEP_END_VIDEO_OUTPUT_CHANNEL, LEP_VIDEO_OUTPUT_CHANNEL_MAKE_32_BIT_ENUM = 0x7FFFFFFF }LEP_OEM_VIDEO_OUTPUT_CHANNEL_E, *LEP_OEM_VIDEO_OUTPUT_CHANNEL_E_PTR; /* Video Gamma Enable Enum */ typedef enum LEP_OEM_VIDEO_GAMMA_ENABLE_TAG { LEP_VIDEO_GAMMA_DISABLE = 0, LEP_VIDEO_GAMMA_ENABLE, LEP_END_VIDEO_GAMMA_ENABLE, LEP_VIDEO_GAMMA_ENABLE_MAKE_32_BIT_ENUM = 0x7FFFFFFF }LEP_OEM_VIDEO_GAMMA_ENABLE_E, *LEP_OEM_VIDEO_GAMMA_ENABLE_E_PTR; typedef enum LEP_OEM_MEM_BUFFER_E_TAG { LEP_OEM_MEM_OTP_ODAC = 0, LEP_OEM_MEM_OTP_GAIN, LEP_OEM_MEM_OTP_OFFSET_0, LEP_OEM_MEM_OTP_OFFSET_1, LEP_OEM_MEM_OTP_FFC, LEP_OEM_MEM_OTP_LG0, LEP_OEM_MEM_OTP_LG1, LEP_OEM_MEM_OTP_LG2, LEP_OEM_MEM_OTP_TFPA_LUT, LEP_OEM_MEM_OTP_TAUX_LUT, LEP_OEM_MEM_OTP_BAD_PIXEL_LIST, LEP_OEM_MEM_SRAM_ODAC, LEP_OEM_MEM_SRAM_BAD_PIXEL_LIST, LEP_OEM_MEM_SHARED_BUFFER_0, LEP_OEM_MEM_SHARED_BUFFER_1, LEP_OEM_MEM_SHARED_BUFFER_2, LEP_OEM_MEM_SHARED_BUFFER_3, LEP_OEM_MEM_SHARED_BUFFER_4, LEP_OEM_END_MEM_BUFFERS, LEP_OEM_MEM_BUFFERS_MAKE_32_BIT_ENUM = 0x7FFFFFFF }LEP_OEM_MEM_BUFFER_E,*LEP_OEM_MEM_BUFFER_E_PTR; typedef enum { LEP_OEM_STATUS_OTP_WRITE_ERROR = -2, LEP_OEM_STATUS_ERROR = -1, LEP_OEM_STATUS_READY = 0, LEP_OEM_STATUS_BUSY, LEP_OEM_FRAME_AVERAGE_COLLECTING_FRAMES, LEP_OEM_STATUS_END, LEP_OEM_STATUS_MAKE_32_BIT_ENUM = 0x7FFFFFFF } LEP_OEM_STATUS_E, *LEP_OEM_STATUS_E_PTR; typedef enum LEP_OEM_STATE_E_TAG { LEP_OEM_DISABLE = 0, LEP_OEM_ENABLE, LEP_OEM_END_STATE, LEP_OEM_STATE_MAKE_32_BIT_ENUM = 0x7FFFFFFF }LEP_OEM_STATE_E,*LEP_OEM_STATE_E_PTR; typedef enum LEP_OEM_POWER_STATE_E_TAG { LEP_OEM_POWER_MODE_NORMAL = 0, LEP_OEM_POWER_MODE_LOW_POWER_1, LEP_OEM_POWER_MODE_LOW_POWER_2, LEP_OEM_END_POWER_MODE, LEP_OEM_POWER_MODE_MAKE_32_BIT_ENUM = 0x7FFFFFFF }LEP_OEM_POWER_STATE_E, *LEP_OEM_POWER_STATE_E_PTR; typedef enum LEP_OEM_VSYNC_DELAY_E_TAG { LEP_OEM_VSYNC_DELAY_MINUS_3 = -3, LEP_OEM_VSYNC_DELAY_MINUS_2 = -2, LEP_OEM_VSYNC_DELAY_MINUS_1 = -1, LEP_OEM_VSYNC_DELAY_NONE = 0, LEP_OEM_VSYNC_DELAY_PLUS_1 = 1, LEP_OEM_VSYNC_DELAY_PLUS_2 = 2, LEP_OEM_VSYNC_DELAY_PLUS_3 = 3, LEP_END_OEM_VSYNC_DELAY, LEP_OEM_VSYNC_DELAY_MAKE_32_BIT_ENUM = 0x7FFFFFFF } LEP_OEM_VSYNC_DELAY_E, *LEP_OEM_VSYNC_DELAY_E_PTR; typedef enum LEP_OEM_GPIO_MODE_E_TAG { LEP_OEM_GPIO_MODE_GPIO = 0, LEP_OEM_GPIO_MODE_I2C_MASTER = 1, LEP_OEM_GPIO_MODE_SPI_MASTER_VLB_DATA = 2, LEP_OEM_GPIO_MODE_SPIO_MASTER_REG_DATA = 3, LEP_OEM_GPIO_MODE_SPI_SLAVE_VLB_DATA = 4, LEP_OEM_GPIO_MODE_VSYNC = 5, LEP_OEM_END_GPIO_MODE, LEP_OEM_GPIO_MODE_MAKE_32_BIT_ENUM = 0x7FFFFFFF }LEP_OEM_GPIO_MODE_E, *LEP_OEM_GPIO_MODE_E_PTR; typedef enum LEP_OEM_USER_PARAMS_STATE_E_TAG { LEP_OEM_USER_PARAMS_STATE_NOT_WRITTEN = 0, LEP_OEM_USER_PARAMS_STATE_WRITTEN, LEP_OEM_END_USER_PARAMS_STATE, LEP_OEM_USER_PARAMS_STATE_MAKE_32_BIT_ENUM = 0x7FFFFFFF }LEP_OEM_USER_PARAMS_STATE_E, *LEP_OEM_USER_PARAMS_STATE_E_PTR; /* Shutter Profile Object */ typedef struct LEP_OEM_SHUTTER_PROFILE_OBJ_T_TAG { LEP_UINT16 closePeriodInFrames; /* in frame counts x1 */ LEP_UINT16 openPeriodInFrames; /* in frame counts x1 */ }LEP_OEM_SHUTTER_PROFILE_OBJ_T, *LEP_OEM_SHUTTER_PROFILE_OBJ_T_PTR; typedef struct LEP_OEM_BAD_PIXEL_REPLACE_CONTROL_T_TAG { LEP_OEM_STATE_E oemBadPixelReplaceEnable; // Bad Pixel Replacment in the video path }LEP_OEM_BAD_PIXEL_REPLACE_CONTROL_T, *LEP_OEM_BAD_PIXEL_REPLACE_CONTROL_T_PTR; typedef struct LEP_OEM_TEMPORAL_FILTER_CONTROL_T_TAG { LEP_OEM_STATE_E oemTemporalFilterEnable; // Temporal Filter in the video path }LEP_OEM_TEMPORAL_FILTER_CONTROL_T, *LEP_OEM_TEMPORAL_FILTER_CONTROL_T_PTR; typedef struct LEP_OEM_COLUMN_NOISE_ESTIMATE_CONTROL_T_TAG { LEP_OEM_STATE_E oemColumnNoiseEstimateEnable; // Column Noise Estimate in the video path }LEP_OEM_COLUMN_NOISE_ESTIMATE_CONTROL_T, *LEP_OEM_COLUMN_NOISE_ESTIMATE_CONTROL_T_PTR; typedef struct LEP_OEM_PIXEL_NOISE_SETTINGS_T_TAG { LEP_OEM_STATE_E oemPixelNoiseEstimateEnable; // Row Noise Estimate in the video path }LEP_OEM_PIXEL_NOISE_SETTINGS_T, *LEP_OEM_PIXEL_NOISE_SETTINGS_T_PTR; typedef struct LEP_OEM_THERMAL_SHUTDOWN_ENABLE_T_TAG { LEP_OEM_STATE_E oemThermalShutdownEnable; }LEP_OEM_THERMAL_SHUTDOWN_ENABLE_T, *LEP_OEM_THERMAL_SHUTDOWN_ENABLE_T_PTR; /******************************************************************************/ /** EXPORTED PUBLIC DATA **/ /******************************************************************************/ /******************************************************************************/ /** EXPORTED PUBLIC FUNCTIONS **/ /******************************************************************************/ extern LEP_RESULT LEP_RunOemPowerDown( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr ); extern LEP_RESULT LEP_RunOemPowerOn( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr ); extern LEP_RESULT LEP_RunOemStandby( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr ); extern LEP_RESULT LEP_RunOemReboot( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr ); extern LEP_RESULT LEP_RunOemLowPowerMode1( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr ); extern LEP_RESULT LEP_RunOemLowPowerMode2( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr ); extern LEP_RESULT LEP_RunOemBit( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr ); extern LEP_RESULT LEP_GetOemMaskRevision( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_MASK_REVISION_T *oemMaskRevisionPtr ); #if 0 extern LEP_RESULT LEP_GetOemMasterID( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_MASTER_ID_T_PTR oemMasterIDPtr ); #endif #if USE_DEPRECATED_PART_NUMBER_INTERFACE /* Deprecated: use LEP_GetOemFlirPN instead */ extern LEP_RESULT LEP_GetOemFlirPartNumber( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_PART_NUMBER_T_PTR oemPartNumberPtr ); /* Deprecated: use LEP_GetOemCustPN instead */ extern LEP_RESULT LEP_GetOemCustPartNumber( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_PART_NUMBER_T_PTR oemPartNumberPtr ); #else extern LEP_RESULT LEP_GetOemFlirPartNumber( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_PART_NUMBER_T_PTR oemPartNumberPtr ); extern LEP_RESULT LEP_GetOemCustPartNumber( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_PART_NUMBER_T_PTR oemPartNumberPtr ); #endif extern LEP_RESULT LEP_GetOemSoftwareVersion( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_SW_VERSION_T *oemSoftwareVersionPtr ); #if 0 extern LEP_RESULT LEP_GetOemVendorID(LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_VENDORID_T *oemVendorIDPtr); #endif extern LEP_RESULT LEP_GetOemVideoOutputEnable( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_VIDEO_OUTPUT_ENABLE_E_PTR oemVideoOutputEnablePtr ); extern LEP_RESULT LEP_SetOemVideoOutputEnable( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_VIDEO_OUTPUT_ENABLE_E oemVideoOutputEnable ); extern LEP_RESULT LEP_GetOemVideoOutputFormat( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_VIDEO_OUTPUT_FORMAT_E_PTR oemVideoOutputFormatPtr ); extern LEP_RESULT LEP_SetOemVideoOutputFormat( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_VIDEO_OUTPUT_FORMAT_E oemVideoOutputFormat ); extern LEP_RESULT LEP_GetOemVideoOutputSource( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_VIDEO_OUTPUT_SOURCE_E_PTR oemVideoOutputSourcePtr ); extern LEP_RESULT LEP_SetOemVideoOutputSource( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_VIDEO_OUTPUT_SOURCE_E oemVideoOutputSource ); extern LEP_RESULT LEP_GetOemVideoOutputSourceConstant( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_UINT16 *oemVideoOutputSourceConstant ); extern LEP_RESULT LEP_SetOemVideoOutputSourceConstant( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_UINT16 oemVideoOutputSourceConstant ); extern LEP_RESULT LEP_GetOemVideoOutputChannel( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_VIDEO_OUTPUT_CHANNEL_E_PTR oemVideoOutputChannelPtr ); extern LEP_RESULT LEP_SetOemVideoOutputChannel( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_VIDEO_OUTPUT_CHANNEL_E oemVideoOutputChannel ); extern LEP_RESULT LEP_GetOemVideoGammaEnable( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_VIDEO_GAMMA_ENABLE_E_PTR oemVideoGammaEnablePtr ); extern LEP_RESULT LEP_SetOemVideoGammaEnable( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_VIDEO_GAMMA_ENABLE_E oemVideoGammaEnable ); extern LEP_RESULT LEP_GetOemCalStatus( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_STATUS_E_PTR calStatusPtr ); extern LEP_RESULT LEP_GetOemFFCNormalizationTarget( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_FFC_NORMALIZATION_TARGET_T_PTR ffcTargetPtr ); extern LEP_RESULT LEP_SetOemFFCNormalizationTarget( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_FFC_NORMALIZATION_TARGET_T ffcTarget ); extern LEP_RESULT LEP_RunOemFFCNormalization( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_FFC_NORMALIZATION_TARGET_T ffcTarget ); extern LEP_RESULT LEP_GetOemFrameMean( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_FRAME_AVERAGE_T_PTR frameAveragePtr ); extern LEP_RESULT LEP_GetOemPowerMode( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_POWER_STATE_E_PTR powerModePtr ); extern LEP_RESULT LEP_SetOemPowerMode( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_POWER_STATE_E powerMode ); extern LEP_RESULT LEP_RunOemFFC( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr ); extern LEP_RESULT LEP_GetOemGpioMode( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_GPIO_MODE_E_PTR gpioModePtr ); extern LEP_RESULT LEP_SetOemGpioMode( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_GPIO_MODE_E gpioMode ); extern LEP_RESULT LEP_GetOemGpioVsyncPhaseDelay( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_VSYNC_DELAY_E_PTR numHsyncLinesPtr ); extern LEP_RESULT LEP_SetOemGpioVsyncPhaseDelay( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_VSYNC_DELAY_E numHsyncLines ); extern LEP_RESULT LEP_GetOemUserDefaultsState( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_USER_PARAMS_STATE_E_PTR userParamsStatePtr ); extern LEP_RESULT LEP_RunOemUserDefaultsCopyToOtp( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr ); extern LEP_RESULT LEP_RunOemUserDefaultsRestore( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr ); extern LEP_RESULT LEP_GetOemThermalShutdownEnable( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_THERMAL_SHUTDOWN_ENABLE_T_PTR ThermalShutdownEnableStatePtr ); extern LEP_RESULT LEP_SetOemThermalShutdownEnable( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_THERMAL_SHUTDOWN_ENABLE_T ThermalShutdownEnableState ); extern LEP_RESULT LEP_GetOemShutterProfileObj( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_SHUTTER_PROFILE_OBJ_T_PTR ShutterProfileObjPtr ); extern LEP_RESULT LEP_SetOemShutterProfileObj( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_SHUTTER_PROFILE_OBJ_T ShutterProfileObj ); extern LEP_RESULT LEP_GetOemBadPixelReplaceControl( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_BAD_PIXEL_REPLACE_CONTROL_T_PTR BadPixelReplaceControlPtr ); extern LEP_RESULT LEP_SetOemBadPixelReplaceControl( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_BAD_PIXEL_REPLACE_CONTROL_T BadPixelReplaceControl ); extern LEP_RESULT LEP_GetOemTemporalFilterControl( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_TEMPORAL_FILTER_CONTROL_T_PTR TemporalFilterControlPtr ); extern LEP_RESULT LEP_SetOemTemporalFilterControl( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_TEMPORAL_FILTER_CONTROL_T TemporalFilterControl ); extern LEP_RESULT LEP_GetOemColumnNoiseEstimateControl( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_COLUMN_NOISE_ESTIMATE_CONTROL_T_PTR ColumnNoiseEstimateControlPtr ); extern LEP_RESULT LEP_SetOemColumnNoiseEstimateControl( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_COLUMN_NOISE_ESTIMATE_CONTROL_T ColumnNoiseEstimateControl ); extern LEP_RESULT LEP_GetOemPixelNoiseSettings( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_PIXEL_NOISE_SETTINGS_T_PTR PixelNoiseEstimateControlPtr ); extern LEP_RESULT LEP_SetOemPixelNoiseSettings( LEP_CAMERA_PORT_DESC_T_PTR portDescPtr, LEP_OEM_PIXEL_NOISE_SETTINGS_T PixelNoiseEstimateControl ); /******************************************************************************/ #ifdef __cplusplus } #endif #endif /* _LEPTON_OEM_H_ */
734d7a05438b6bf1566d57d787e73bb5c45ce298
f8c0a188d1cf8ae5221c4cd11552c221a86e259a
/Firmware/Flux.Other/src/Utils/Fifo.c
729cbfa3f320a59cad9411f80bccc6875337ab75
[ "CC-BY-3.0", "BSD-2-Clause" ]
permissive
digitalinteraction/openmovement
6310abf35b379655073485e84719cc2521733c0e
9c2ee2eeb5eae457673e60699b2842c6df82abb1
refs/heads/master
2023-08-03T23:48:42.973605
2023-07-26T17:52:37
2023-07-26T17:52:37
27,082,024
135
86
null
2018-06-21T23:32:43
2014-11-24T15:38:43
C
UTF-8
C
false
false
12,311
c
Fifo.c
/* * Copyright (c) 2009-2012, Newcastle University, UK. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ // FIFO buffer // Dan Jackson, 2011-2012 #include <stdlib.h> #include <string.h> #include "Utils/Fifo.h" #include <Compiler.h> #include "HardwareProfile.h" /* // Circular buffer operations (b = buffer, h = head, t = tail, i = index / number of elements, c = capacity) static unsigned int _fifo_temp; #define FIFO_CLEAR(_h, _t) { _h = 0; _t = 0; } #define FIFO_INCREMENT(_i, _c) (((_i) + 1) % (_c)) #define FIFO_ADD(_b, _h, _t, _c, _v) { if (FIFO_INCREMENT(_t, _c) != (_h)) { (_b)[_t] = (_v); _t = FIFO_INCREMENT(_t, _c); } } #define FIFO_REMOVE(_b, _h, _t, _c) (((_h) == (_t)) ? 0 : (_fifo_temp = (_b)[_h], _h = FIFO_INCREMENT(_h, _c), _fifo_temp)) #define FIFO_LENGTH(_h, _t, _c) (((_t) >= (_h)) ? ((_t) - (_h)) : ((_c) - (_h) + (_t))) #define FIFO_FREE(_h, _t, _c) (((_t) >= (_h)) ? ((_c) - (_t) + (_h) - 1) : ((_h) - (_t) - 1)) #define FIFO_CONTIGUOUS_ENTRIES(_h, _t, _c) (((_t) >= (_h)) ? ((_t) - (_h)) : ((_c) - (_h))) #define FIFO_ENTRY_POINTER(_b, _h) ((_b) + (_h)) #define FIFO_CONTIGUOUS_FREE(_h, _t, _c) (((_t) >= (_h)) ? ((_c) - (_t) - ((_h) == 0 ? 1 : 0)) : ((_h) - (_t) - 1)) #define FIFO_FREE_POINTER(_b, _t) ((_b) + (_t)) #define FIFO_EXTERNALLY_ADDED(_t, _c, _i) ((_t) = (((_t) + (_i)) % (_c))) #define FIFO_EXTERNALLY_REMOVED(_h, _c, _i) ((_h) = (((_h) + (_i)) % (_c))) */ // Initialize FIFO data structure void FifoInit(fifo_t *fifo, size_t elementSize, unsigned int capacity, void FIFO_EDS *buffer) { fifo->elementSize = elementSize; fifo->capacity = capacity; fifo->buffer = buffer; fifo->head = 0; fifo->tail = 0; // Check if is power of two if ((capacity & (capacity - 1)) == 0) { fifo->mask = capacity - 1; } else { fifo->mask = 0; } } // Clear FIFO void FifoClear(fifo_t *fifo) { FIFO_IPL_shadow_t IPLshadow; FIFO_INTS_DISABLE(); fifo->head = 0; fifo->tail = 0; FIFO_INTS_ENABLE(); } // See how many contiguous free spaces there are unsigned int FifoContiguousSpaces(fifo_t *fifo, void **buffer) { unsigned int contiguous; FIFO_IPL_shadow_t IPLshadow; FIFO_INTS_DISABLE(); // Find the buffer pointer if (buffer != NULL) { // TODO: Save the multiply by keeping track of the byte pointer to the tail? // WARNING: Not EDS-compatible *buffer = (void *)((unsigned char *)fifo->buffer + fifo->tail * fifo->elementSize); } // See how many entries we can contiguously write to if (fifo->capacity == 0) { contiguous = 0; } else if (fifo->tail >= fifo->head) { contiguous = fifo->capacity - fifo->tail - ((fifo->head == 0) ? 1 : 0); } else { contiguous = fifo->head - fifo->tail - 1; } FIFO_INTS_ENABLE(); return contiguous; } // See how many contiguous free spaces there are (alternative) void FIFO_EDS *FifoContiguousSpaces2(fifo_t *fifo, unsigned int *contiguous) { void FIFO_EDS *retVal; FIFO_IPL_shadow_t IPLshadow; FIFO_INTS_DISABLE(); // TODO: Save the multiply by keeping track of the byte pointer to the tail? retVal = (void FIFO_EDS *)((unsigned char FIFO_EDS *)fifo->buffer + fifo->tail * fifo->elementSize); // See how many entries we can contiguously write to if (contiguous != NULL) { if (fifo->capacity == 0) { *contiguous = 0; } else if (fifo->tail >= fifo->head) { *contiguous = fifo->capacity - fifo->tail - ((fifo->head == 0) ? 1 : 0); } else { *contiguous = fifo->head - fifo->tail - 1; } } FIFO_INTS_ENABLE(); return retVal; } // See how many contiguous entries there are unsigned int FifoContiguousEntries(fifo_t *fifo, void **buffer) { unsigned int contiguous; FIFO_IPL_shadow_t IPLshadow; FIFO_INTS_DISABLE(); // Find the buffer pointer if (buffer != NULL) { // TODO: Save the multiply by keeping track of the byte pointer to the head? // WARNING: Not EDS-compatible *buffer = (void *)((unsigned char *)fifo->buffer + fifo->head * fifo->elementSize); } // See how many entries we can contiguously read from if (fifo->tail >= fifo->head) { contiguous = fifo->tail - fifo->head; } else { contiguous = fifo->capacity - fifo->head; } FIFO_INTS_ENABLE(); return contiguous; } // See how many contiguous entries there are (alternative) void FIFO_EDS *FifoContiguousEntries2(fifo_t *fifo, unsigned int *contiguous) { void FIFO_EDS *retVal; unsigned int offset; FIFO_IPL_shadow_t IPLshadow; FIFO_INTS_DISABLE(); // Find the buffer pointer // TODO: Save the multiply by keeping track of the byte pointer to the head? offset = fifo->head * fifo->elementSize; retVal = (void FIFO_EDS *)((unsigned char FIFO_EDS *)fifo->buffer + offset); // See how many entries we can contiguously read from if (contiguous != NULL) { if (fifo->tail >= fifo->head) { *contiguous = fifo->tail - fifo->head; } else { *contiguous = fifo->capacity - fifo->head; } } FIFO_INTS_ENABLE(); return retVal; } // Data has been directly added to the FIFO void FifoExternallyAdded(fifo_t *fifo, unsigned int count) { // TODO: Check if count > freeLength FIFO_IPL_shadow_t IPLshadow; FIFO_INTS_DISABLE(); if (fifo->capacity != 0) { fifo->tail = fifo->mask ? ((fifo->tail + count) & fifo->mask) : ((fifo->tail + count) % fifo->capacity); } FIFO_INTS_ENABLE(); } // Data has been directly removed from the FIFO void FifoExternallyRemoved(fifo_t *fifo, unsigned int count) { // TODO: Check if count > length FIFO_IPL_shadow_t IPLshadow; FIFO_INTS_DISABLE(); if (fifo->capacity != 0) { fifo->head = fifo->mask ? ((fifo->head + count) & fifo->mask) : ((fifo->head + count) % fifo->capacity); } FIFO_INTS_ENABLE(); } // Returns the current length of the FIFO unsigned int FifoLength(fifo_t *fifo) { unsigned int length; FIFO_IPL_shadow_t IPLshadow; FIFO_INTS_DISABLE(); // Calculate the length if (fifo->tail >= fifo->head) { length = fifo->tail - fifo->head; } else { length = (fifo->capacity - fifo->head) + fifo->tail; } FIFO_INTS_ENABLE(); return length; } // Returns the free space left in the FIFO unsigned int FifoFree(fifo_t *fifo) { unsigned int free; FIFO_IPL_shadow_t IPLshadow; FIFO_INTS_DISABLE(); // Calculate the free if (fifo->capacity == 0) { free = 0; } else if (fifo->tail >= fifo->head) { free = fifo->capacity - fifo->tail + fifo->head - 1; } else { free = fifo->head - fifo->tail - 1; } FIFO_INTS_ENABLE(); return free; } // Empty values from the FIFO unsigned int FifoPop(fifo_t *fifo, void *destination, unsigned int count) { unsigned int remaining; char pass = 0; // Up to two passes (FIFO wraps inside buffer) remaining = count; for (pass = 0; pass < 2; pass++) { void *bufferPointer = NULL; unsigned int contiguous, n = 0; // See how many entries to process in this pass // WARNING: This will not work with EDS memory bufferPointer = (void *)FifoContiguousEntries2(fifo, &contiguous); if (remaining <= contiguous) { n = remaining; } else { n = contiguous; } if (n <= 0) { break; } // No more // Copy n * fifo->elementSize bytes if (destination != NULL) { size_t length = n * fifo->elementSize; memcpy(destination, bufferPointer, length); destination = (unsigned char *)destination + length; } // Update head pointer FifoExternallyRemoved(fifo, n); // Decrease number remaining remaining -= n; if (remaining <= 0) { break; } // Processed all } // Return number of entries processed return (count - remaining); } // Empty values from the FIFO - modified to return valid pointer to the data IF it is contiguous unsigned int FifoPop2(fifo_t *fifo, void *destination, unsigned int count, void** dataSource) { unsigned int remaining; char pass = 0; // Up to two passes (FIFO wraps inside buffer) remaining = count; for (pass = 0; pass < 2; pass++) { void *bufferPointer = NULL; unsigned int contiguous, n = 0; // See how many entries to process in this pass // WARNING: This will not work with EDS memory bufferPointer = (void *)FifoContiguousEntries2(fifo, &contiguous); if (remaining <= contiguous) { // Continuous block of data is present n = remaining; if(pass==0) // First pass indicates that the chunk is at least as big as pop request size *dataSource = bufferPointer; // return valid pointer } else { // Partial chunk of data n = contiguous; *dataSource = NULL; // return null pointer } if (n <= 0) { break; } // No more // Copy n * fifo->elementSize bytes if (destination != NULL) { size_t length = n * fifo->elementSize; memcpy(destination, bufferPointer, length); destination = (unsigned char *)destination + length; } // Update head pointer FifoExternallyRemoved(fifo, n); // Decrease number remaining remaining -= n; if (remaining <= 0) { break; } // Processed all } // Return number of entries processed return (count - remaining); } // Add values to the FIFO unsigned int FifoPush(fifo_t *fifo, void *values, unsigned int count) { unsigned int remaining; char pass = 0; // Up to two passes (FIFO wraps inside buffer) remaining = count; for (pass = 0; pass < 2; pass++) { void *bufferPointer = NULL; unsigned int contiguous, n = 0; // See how many entries to process in this pass // WARNING: This will not work with EDS memory bufferPointer = (void *)FifoContiguousSpaces2(fifo, &contiguous); if (remaining <= contiguous) { n = remaining; } else { n = contiguous; } if (n <= 0) { break; } // No more // Copy n * fifo->elementSize bytes if (values != NULL) { size_t length = n * fifo->elementSize; memcpy(bufferPointer, values, length); values = (unsigned char *)values + length; } // Update tail pointer FifoExternallyAdded(fifo, n); // Decrease number remaining remaining -= n; if (remaining <= 0) { break; } // Processed all } // Return number of entries processed return (count - remaining); } // Directly set tail (specialist use only) void FifoSetTail(fifo_t *fifo, unsigned int tail) { // FIFO_IPL_shadow_t IPLshadow; // FIFO_INTS_DISABLE(); fifo->tail = tail; // FIFO_INTS_ENABLE(); }
701360eaef1b682ed93649ed633a3ab36284e0ca
f0b7a25593f6c908303f08f7aca83dc431d36d26
/Snap/Core/Infrastructure/Interoperability/Snap.h
7820d0c17859807ad77df6bc1ba6a6b517b73922
[ "MIT" ]
permissive
skyweb07/Snap.swift
6a097446eda322f4364d13419ee2a42dafcfff23
44350f67487610df7449d591c6e751bb629837a8
refs/heads/develop
2022-08-27T01:57:26.488614
2018-09-19T18:52:27
2018-09-19T18:52:27
111,916,587
439
28
MIT
2020-01-31T15:18:47
2017-11-24T12:33:48
Swift
UTF-8
C
false
false
776
h
Snap.h
#define verifyView(view) \ if (![view isKindOfClass: [UIView class]]) { \ @throw[NSException exceptionWithName: @"Invalid view" reason: [NSString stringWithFormat: @"View is invalid, you must provider a UIView subclass instead of %@", [view class]] userInfo: nil]; \ }\ [self verifyWithView:view function:NSStringFromSelector(_cmd) file:[NSString stringWithFormat:@"%s", __FILE__]]; #define verifyLayer(layer) \ if (![layer isKindOfClass: [CALayer class]]) { \ @throw[NSException exceptionWithName: @"Invalid layer" reason: [NSString stringWithFormat: @"Layer is invalid, you must provider a CALayer subclass instead of %@", [view class]] userInfo: nil]; \ }\ [self verifyWithLayer:layer function:NSStringFromSelector(_cmd) file:[NSString stringWithFormat:@"%s", __FILE__]];
658f8ecdd6b206bb3be6fa0f6f842bcf741229af
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/drivers/net/ethernet/qlogic/qlge/qlge_mpi.c
ff2bf8a4e24773429f02e1b66777e76bdd079134
[ "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later", "LicenseRef-scancode-free-unknown", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
30,806
c
qlge_mpi.c
#include "qlge.h" int ql_unpause_mpi_risc(struct ql_adapter *qdev) { u32 tmp; /* Un-pause the RISC */ tmp = ql_read32(qdev, CSR); if (!(tmp & CSR_RP)) return -EIO; ql_write32(qdev, CSR, CSR_CMD_CLR_PAUSE); return 0; } int ql_pause_mpi_risc(struct ql_adapter *qdev) { u32 tmp; int count = UDELAY_COUNT; /* Pause the RISC */ ql_write32(qdev, CSR, CSR_CMD_SET_PAUSE); do { tmp = ql_read32(qdev, CSR); if (tmp & CSR_RP) break; mdelay(UDELAY_DELAY); count--; } while (count); return (count == 0) ? -ETIMEDOUT : 0; } int ql_hard_reset_mpi_risc(struct ql_adapter *qdev) { u32 tmp; int count = UDELAY_COUNT; /* Reset the RISC */ ql_write32(qdev, CSR, CSR_CMD_SET_RST); do { tmp = ql_read32(qdev, CSR); if (tmp & CSR_RR) { ql_write32(qdev, CSR, CSR_CMD_CLR_RST); break; } mdelay(UDELAY_DELAY); count--; } while (count); return (count == 0) ? -ETIMEDOUT : 0; } int ql_read_mpi_reg(struct ql_adapter *qdev, u32 reg, u32 *data) { int status; /* wait for reg to come ready */ status = ql_wait_reg_rdy(qdev, PROC_ADDR, PROC_ADDR_RDY, PROC_ADDR_ERR); if (status) goto exit; /* set up for reg read */ ql_write32(qdev, PROC_ADDR, reg | PROC_ADDR_R); /* wait for reg to come ready */ status = ql_wait_reg_rdy(qdev, PROC_ADDR, PROC_ADDR_RDY, PROC_ADDR_ERR); if (status) goto exit; /* get the data */ *data = ql_read32(qdev, PROC_DATA); exit: return status; } int ql_write_mpi_reg(struct ql_adapter *qdev, u32 reg, u32 data) { int status = 0; /* wait for reg to come ready */ status = ql_wait_reg_rdy(qdev, PROC_ADDR, PROC_ADDR_RDY, PROC_ADDR_ERR); if (status) goto exit; /* write the data to the data reg */ ql_write32(qdev, PROC_DATA, data); /* trigger the write */ ql_write32(qdev, PROC_ADDR, reg); /* wait for reg to come ready */ status = ql_wait_reg_rdy(qdev, PROC_ADDR, PROC_ADDR_RDY, PROC_ADDR_ERR); if (status) goto exit; exit: return status; } int ql_soft_reset_mpi_risc(struct ql_adapter *qdev) { int status; status = ql_write_mpi_reg(qdev, 0x00001010, 1); return status; } /* Determine if we are in charge of the firwmare. If * we are the lower of the 2 NIC pcie functions, or if * we are the higher function and the lower function * is not enabled. */ int ql_own_firmware(struct ql_adapter *qdev) { u32 temp; /* If we are the lower of the 2 NIC functions * on the chip the we are responsible for * core dump and firmware reset after an error. */ if (qdev->func < qdev->alt_func) return 1; /* If we are the higher of the 2 NIC functions * on the chip and the lower function is not * enabled, then we are responsible for * core dump and firmware reset after an error. */ temp = ql_read32(qdev, STS); if (!(temp & (1 << (8 + qdev->alt_func)))) return 1; return 0; } static int ql_get_mb_sts(struct ql_adapter *qdev, struct mbox_params *mbcp) { int i, status; status = ql_sem_spinlock(qdev, SEM_PROC_REG_MASK); if (status) return -EBUSY; for (i = 0; i < mbcp->out_count; i++) { status = ql_read_mpi_reg(qdev, qdev->mailbox_out + i, &mbcp->mbox_out[i]); if (status) { netif_err(qdev, drv, qdev->ndev, "Failed mailbox read.\n"); break; } } ql_sem_unlock(qdev, SEM_PROC_REG_MASK); /* does flush too */ return status; } /* Wait for a single mailbox command to complete. * Returns zero on success. */ static int ql_wait_mbx_cmd_cmplt(struct ql_adapter *qdev) { int count = 100; u32 value; do { value = ql_read32(qdev, STS); if (value & STS_PI) return 0; mdelay(UDELAY_DELAY); /* 100ms */ } while (--count); return -ETIMEDOUT; } /* Execute a single mailbox command. * Caller must hold PROC_ADDR semaphore. */ static int ql_exec_mb_cmd(struct ql_adapter *qdev, struct mbox_params *mbcp) { int i, status; /* * Make sure there's nothing pending. * This shouldn't happen. */ if (ql_read32(qdev, CSR) & CSR_HRI) return -EIO; status = ql_sem_spinlock(qdev, SEM_PROC_REG_MASK); if (status) return status; /* * Fill the outbound mailboxes. */ for (i = 0; i < mbcp->in_count; i++) { status = ql_write_mpi_reg(qdev, qdev->mailbox_in + i, mbcp->mbox_in[i]); if (status) goto end; } /* * Wake up the MPI firmware. */ ql_write32(qdev, CSR, CSR_CMD_SET_H2R_INT); end: ql_sem_unlock(qdev, SEM_PROC_REG_MASK); return status; } /* We are being asked by firmware to accept * a change to the port. This is only * a change to max frame sizes (Tx/Rx), pause * parameters, or loopback mode. We wake up a worker * to handler processing this since a mailbox command * will need to be sent to ACK the request. */ static int ql_idc_req_aen(struct ql_adapter *qdev) { int status; struct mbox_params *mbcp = &qdev->idc_mbc; netif_err(qdev, drv, qdev->ndev, "Enter!\n"); /* Get the status data and start up a thread to * handle the request. */ mbcp = &qdev->idc_mbc; mbcp->out_count = 4; status = ql_get_mb_sts(qdev, mbcp); if (status) { netif_err(qdev, drv, qdev->ndev, "Could not read MPI, resetting ASIC!\n"); ql_queue_asic_error(qdev); } else { /* Begin polled mode early so * we don't get another interrupt * when we leave mpi_worker. */ ql_write32(qdev, INTR_MASK, (INTR_MASK_PI << 16)); queue_delayed_work(qdev->workqueue, &qdev->mpi_idc_work, 0); } return status; } /* Process an inter-device event completion. * If good, signal the caller's completion. */ static int ql_idc_cmplt_aen(struct ql_adapter *qdev) { int status; struct mbox_params *mbcp = &qdev->idc_mbc; mbcp->out_count = 4; status = ql_get_mb_sts(qdev, mbcp); if (status) { netif_err(qdev, drv, qdev->ndev, "Could not read MPI, resetting RISC!\n"); ql_queue_fw_error(qdev); } else /* Wake up the sleeping mpi_idc_work thread that is * waiting for this event. */ complete(&qdev->ide_completion); return status; } static void ql_link_up(struct ql_adapter *qdev, struct mbox_params *mbcp) { int status; mbcp->out_count = 2; status = ql_get_mb_sts(qdev, mbcp); if (status) { netif_err(qdev, drv, qdev->ndev, "%s: Could not get mailbox status.\n", __func__); return; } qdev->link_status = mbcp->mbox_out[1]; netif_err(qdev, drv, qdev->ndev, "Link Up.\n"); /* If we're coming back from an IDC event * then set up the CAM and frame routing. */ if (test_bit(QL_CAM_RT_SET, &qdev->flags)) { status = ql_cam_route_initialize(qdev); if (status) { netif_err(qdev, ifup, qdev->ndev, "Failed to init CAM/Routing tables.\n"); return; } else clear_bit(QL_CAM_RT_SET, &qdev->flags); } /* Queue up a worker to check the frame * size information, and fix it if it's not * to our liking. */ if (!test_bit(QL_PORT_CFG, &qdev->flags)) { netif_err(qdev, drv, qdev->ndev, "Queue Port Config Worker!\n"); set_bit(QL_PORT_CFG, &qdev->flags); /* Begin polled mode early so * we don't get another interrupt * when we leave mpi_worker dpc. */ ql_write32(qdev, INTR_MASK, (INTR_MASK_PI << 16)); queue_delayed_work(qdev->workqueue, &qdev->mpi_port_cfg_work, 0); } ql_link_on(qdev); } static void ql_link_down(struct ql_adapter *qdev, struct mbox_params *mbcp) { int status; mbcp->out_count = 3; status = ql_get_mb_sts(qdev, mbcp); if (status) netif_err(qdev, drv, qdev->ndev, "Link down AEN broken!\n"); ql_link_off(qdev); } static int ql_sfp_in(struct ql_adapter *qdev, struct mbox_params *mbcp) { int status; mbcp->out_count = 5; status = ql_get_mb_sts(qdev, mbcp); if (status) netif_err(qdev, drv, qdev->ndev, "SFP in AEN broken!\n"); else netif_err(qdev, drv, qdev->ndev, "SFP insertion detected.\n"); return status; } static int ql_sfp_out(struct ql_adapter *qdev, struct mbox_params *mbcp) { int status; mbcp->out_count = 1; status = ql_get_mb_sts(qdev, mbcp); if (status) netif_err(qdev, drv, qdev->ndev, "SFP out AEN broken!\n"); else netif_err(qdev, drv, qdev->ndev, "SFP removal detected.\n"); return status; } static int ql_aen_lost(struct ql_adapter *qdev, struct mbox_params *mbcp) { int status; mbcp->out_count = 6; status = ql_get_mb_sts(qdev, mbcp); if (status) netif_err(qdev, drv, qdev->ndev, "Lost AEN broken!\n"); else { int i; netif_err(qdev, drv, qdev->ndev, "Lost AEN detected.\n"); for (i = 0; i < mbcp->out_count; i++) netif_err(qdev, drv, qdev->ndev, "mbox_out[%d] = 0x%.08x.\n", i, mbcp->mbox_out[i]); } return status; } static void ql_init_fw_done(struct ql_adapter *qdev, struct mbox_params *mbcp) { int status; mbcp->out_count = 2; status = ql_get_mb_sts(qdev, mbcp); if (status) { netif_err(qdev, drv, qdev->ndev, "Firmware did not initialize!\n"); } else { netif_err(qdev, drv, qdev->ndev, "Firmware Revision = 0x%.08x.\n", mbcp->mbox_out[1]); qdev->fw_rev_id = mbcp->mbox_out[1]; status = ql_cam_route_initialize(qdev); if (status) netif_err(qdev, ifup, qdev->ndev, "Failed to init CAM/Routing tables.\n"); } } /* Process an async event and clear it unless it's an * error condition. * This can get called iteratively from the mpi_work thread * when events arrive via an interrupt. * It also gets called when a mailbox command is polling for * it's completion. */ static int ql_mpi_handler(struct ql_adapter *qdev, struct mbox_params *mbcp) { int status; int orig_count = mbcp->out_count; /* Just get mailbox zero for now. */ mbcp->out_count = 1; status = ql_get_mb_sts(qdev, mbcp); if (status) { netif_err(qdev, drv, qdev->ndev, "Could not read MPI, resetting ASIC!\n"); ql_queue_asic_error(qdev); goto end; } switch (mbcp->mbox_out[0]) { /* This case is only active when we arrive here * as a result of issuing a mailbox command to * the firmware. */ case MB_CMD_STS_INTRMDT: case MB_CMD_STS_GOOD: case MB_CMD_STS_INVLD_CMD: case MB_CMD_STS_XFC_ERR: case MB_CMD_STS_CSUM_ERR: case MB_CMD_STS_ERR: case MB_CMD_STS_PARAM_ERR: /* We can only get mailbox status if we're polling from an * unfinished command. Get the rest of the status data and * return back to the caller. * We only end up here when we're polling for a mailbox * command completion. */ mbcp->out_count = orig_count; status = ql_get_mb_sts(qdev, mbcp); return status; /* We are being asked by firmware to accept * a change to the port. This is only * a change to max frame sizes (Tx/Rx), pause * parameters, or loopback mode. */ case AEN_IDC_REQ: status = ql_idc_req_aen(qdev); break; /* Process and inbound IDC event. * This will happen when we're trying to * change tx/rx max frame size, change pause * parameters or loopback mode. */ case AEN_IDC_CMPLT: case AEN_IDC_EXT: status = ql_idc_cmplt_aen(qdev); break; case AEN_LINK_UP: ql_link_up(qdev, mbcp); break; case AEN_LINK_DOWN: ql_link_down(qdev, mbcp); break; case AEN_FW_INIT_DONE: /* If we're in process on executing the firmware, * then convert the status to normal mailbox status. */ if (mbcp->mbox_in[0] == MB_CMD_EX_FW) { mbcp->out_count = orig_count; status = ql_get_mb_sts(qdev, mbcp); mbcp->mbox_out[0] = MB_CMD_STS_GOOD; return status; } ql_init_fw_done(qdev, mbcp); break; case AEN_AEN_SFP_IN: ql_sfp_in(qdev, mbcp); break; case AEN_AEN_SFP_OUT: ql_sfp_out(qdev, mbcp); break; /* This event can arrive at boot time or after an * MPI reset if the firmware failed to initialize. */ case AEN_FW_INIT_FAIL: /* If we're in process on executing the firmware, * then convert the status to normal mailbox status. */ if (mbcp->mbox_in[0] == MB_CMD_EX_FW) { mbcp->out_count = orig_count; status = ql_get_mb_sts(qdev, mbcp); mbcp->mbox_out[0] = MB_CMD_STS_ERR; return status; } netif_err(qdev, drv, qdev->ndev, "Firmware initialization failed.\n"); status = -EIO; ql_queue_fw_error(qdev); break; case AEN_SYS_ERR: netif_err(qdev, drv, qdev->ndev, "System Error.\n"); ql_queue_fw_error(qdev); status = -EIO; break; case AEN_AEN_LOST: ql_aen_lost(qdev, mbcp); break; case AEN_DCBX_CHG: /* Need to support AEN 8110 */ break; default: netif_err(qdev, drv, qdev->ndev, "Unsupported AE %.08x.\n", mbcp->mbox_out[0]); /* Clear the MPI firmware status. */ } end: ql_write32(qdev, CSR, CSR_CMD_CLR_R2PCI_INT); /* Restore the original mailbox count to * what the caller asked for. This can get * changed when a mailbox command is waiting * for a response and an AEN arrives and * is handled. * */ mbcp->out_count = orig_count; return status; } /* Execute a single mailbox command. * mbcp is a pointer to an array of u32. Each * element in the array contains the value for it's * respective mailbox register. */ static int ql_mailbox_command(struct ql_adapter *qdev, struct mbox_params *mbcp) { int status; unsigned long count; mutex_lock(&qdev->mpi_mutex); /* Begin polled mode for MPI */ ql_write32(qdev, INTR_MASK, (INTR_MASK_PI << 16)); /* Load the mailbox registers and wake up MPI RISC. */ status = ql_exec_mb_cmd(qdev, mbcp); if (status) goto end; /* If we're generating a system error, then there's nothing * to wait for. */ if (mbcp->mbox_in[0] == MB_CMD_MAKE_SYS_ERR) goto end; /* Wait for the command to complete. We loop * here because some AEN might arrive while * we're waiting for the mailbox command to * complete. If more than 5 seconds expire we can * assume something is wrong. */ count = jiffies + HZ * MAILBOX_TIMEOUT; do { /* Wait for the interrupt to come in. */ status = ql_wait_mbx_cmd_cmplt(qdev); if (status) continue; /* Process the event. If it's an AEN, it * will be handled in-line or a worker * will be spawned. If it's our completion * we will catch it below. */ status = ql_mpi_handler(qdev, mbcp); if (status) goto end; /* It's either the completion for our mailbox * command complete or an AEN. If it's our * completion then get out. */ if (((mbcp->mbox_out[0] & 0x0000f000) == MB_CMD_STS_GOOD) || ((mbcp->mbox_out[0] & 0x0000f000) == MB_CMD_STS_INTRMDT)) goto done; } while (time_before(jiffies, count)); netif_err(qdev, drv, qdev->ndev, "Timed out waiting for mailbox complete.\n"); status = -ETIMEDOUT; goto end; done: /* Now we can clear the interrupt condition * and look at our status. */ ql_write32(qdev, CSR, CSR_CMD_CLR_R2PCI_INT); if (((mbcp->mbox_out[0] & 0x0000f000) != MB_CMD_STS_GOOD) && ((mbcp->mbox_out[0] & 0x0000f000) != MB_CMD_STS_INTRMDT)) { status = -EIO; } end: /* End polled mode for MPI */ ql_write32(qdev, INTR_MASK, (INTR_MASK_PI << 16) | INTR_MASK_PI); mutex_unlock(&qdev->mpi_mutex); return status; } /* Get MPI firmware version. This will be used for * driver banner and for ethtool info. * Returns zero on success. */ int ql_mb_about_fw(struct ql_adapter *qdev) { struct mbox_params mbc; struct mbox_params *mbcp = &mbc; int status = 0; memset(mbcp, 0, sizeof(struct mbox_params)); mbcp->in_count = 1; mbcp->out_count = 3; mbcp->mbox_in[0] = MB_CMD_ABOUT_FW; status = ql_mailbox_command(qdev, mbcp); if (status) return status; if (mbcp->mbox_out[0] != MB_CMD_STS_GOOD) { netif_err(qdev, drv, qdev->ndev, "Failed about firmware command\n"); status = -EIO; } /* Store the firmware version */ qdev->fw_rev_id = mbcp->mbox_out[1]; return status; } /* Get functional state for MPI firmware. * Returns zero on success. */ int ql_mb_get_fw_state(struct ql_adapter *qdev) { struct mbox_params mbc; struct mbox_params *mbcp = &mbc; int status = 0; memset(mbcp, 0, sizeof(struct mbox_params)); mbcp->in_count = 1; mbcp->out_count = 2; mbcp->mbox_in[0] = MB_CMD_GET_FW_STATE; status = ql_mailbox_command(qdev, mbcp); if (status) return status; if (mbcp->mbox_out[0] != MB_CMD_STS_GOOD) { netif_err(qdev, drv, qdev->ndev, "Failed Get Firmware State.\n"); status = -EIO; } /* If bit zero is set in mbx 1 then the firmware is * running, but not initialized. This should never * happen. */ if (mbcp->mbox_out[1] & 1) { netif_err(qdev, drv, qdev->ndev, "Firmware waiting for initialization.\n"); status = -EIO; } return status; } /* Send and ACK mailbox command to the firmware to * let it continue with the change. */ static int ql_mb_idc_ack(struct ql_adapter *qdev) { struct mbox_params mbc; struct mbox_params *mbcp = &mbc; int status = 0; memset(mbcp, 0, sizeof(struct mbox_params)); mbcp->in_count = 5; mbcp->out_count = 1; mbcp->mbox_in[0] = MB_CMD_IDC_ACK; mbcp->mbox_in[1] = qdev->idc_mbc.mbox_out[1]; mbcp->mbox_in[2] = qdev->idc_mbc.mbox_out[2]; mbcp->mbox_in[3] = qdev->idc_mbc.mbox_out[3]; mbcp->mbox_in[4] = qdev->idc_mbc.mbox_out[4]; status = ql_mailbox_command(qdev, mbcp); if (status) return status; if (mbcp->mbox_out[0] != MB_CMD_STS_GOOD) { netif_err(qdev, drv, qdev->ndev, "Failed IDC ACK send.\n"); status = -EIO; } return status; } /* Get link settings and maximum frame size settings * for the current port. * Most likely will block. */ int ql_mb_set_port_cfg(struct ql_adapter *qdev) { struct mbox_params mbc; struct mbox_params *mbcp = &mbc; int status = 0; memset(mbcp, 0, sizeof(struct mbox_params)); mbcp->in_count = 3; mbcp->out_count = 1; mbcp->mbox_in[0] = MB_CMD_SET_PORT_CFG; mbcp->mbox_in[1] = qdev->link_config; mbcp->mbox_in[2] = qdev->max_frame_size; status = ql_mailbox_command(qdev, mbcp); if (status) return status; if (mbcp->mbox_out[0] == MB_CMD_STS_INTRMDT) { netif_err(qdev, drv, qdev->ndev, "Port Config sent, wait for IDC.\n"); } else if (mbcp->mbox_out[0] != MB_CMD_STS_GOOD) { netif_err(qdev, drv, qdev->ndev, "Failed Set Port Configuration.\n"); status = -EIO; } return status; } static int ql_mb_dump_ram(struct ql_adapter *qdev, u64 req_dma, u32 addr, u32 size) { int status = 0; struct mbox_params mbc; struct mbox_params *mbcp = &mbc; memset(mbcp, 0, sizeof(struct mbox_params)); mbcp->in_count = 9; mbcp->out_count = 1; mbcp->mbox_in[0] = MB_CMD_DUMP_RISC_RAM; mbcp->mbox_in[1] = LSW(addr); mbcp->mbox_in[2] = MSW(req_dma); mbcp->mbox_in[3] = LSW(req_dma); mbcp->mbox_in[4] = MSW(size); mbcp->mbox_in[5] = LSW(size); mbcp->mbox_in[6] = MSW(MSD(req_dma)); mbcp->mbox_in[7] = LSW(MSD(req_dma)); mbcp->mbox_in[8] = MSW(addr); status = ql_mailbox_command(qdev, mbcp); if (status) return status; if (mbcp->mbox_out[0] != MB_CMD_STS_GOOD) { netif_err(qdev, drv, qdev->ndev, "Failed to dump risc RAM.\n"); status = -EIO; } return status; } /* Issue a mailbox command to dump RISC RAM. */ int ql_dump_risc_ram_area(struct ql_adapter *qdev, void *buf, u32 ram_addr, int word_count) { int status; char *my_buf; dma_addr_t buf_dma; my_buf = pci_alloc_consistent(qdev->pdev, word_count * sizeof(u32), &buf_dma); if (!my_buf) return -EIO; status = ql_mb_dump_ram(qdev, buf_dma, ram_addr, word_count); if (!status) memcpy(buf, my_buf, word_count * sizeof(u32)); pci_free_consistent(qdev->pdev, word_count * sizeof(u32), my_buf, buf_dma); return status; } /* Get link settings and maximum frame size settings * for the current port. * Most likely will block. */ int ql_mb_get_port_cfg(struct ql_adapter *qdev) { struct mbox_params mbc; struct mbox_params *mbcp = &mbc; int status = 0; memset(mbcp, 0, sizeof(struct mbox_params)); mbcp->in_count = 1; mbcp->out_count = 3; mbcp->mbox_in[0] = MB_CMD_GET_PORT_CFG; status = ql_mailbox_command(qdev, mbcp); if (status) return status; if (mbcp->mbox_out[0] != MB_CMD_STS_GOOD) { netif_err(qdev, drv, qdev->ndev, "Failed Get Port Configuration.\n"); status = -EIO; } else { netif_printk(qdev, drv, KERN_DEBUG, qdev->ndev, "Passed Get Port Configuration.\n"); qdev->link_config = mbcp->mbox_out[1]; qdev->max_frame_size = mbcp->mbox_out[2]; } return status; } int ql_mb_wol_mode(struct ql_adapter *qdev, u32 wol) { struct mbox_params mbc; struct mbox_params *mbcp = &mbc; int status; memset(mbcp, 0, sizeof(struct mbox_params)); mbcp->in_count = 2; mbcp->out_count = 1; mbcp->mbox_in[0] = MB_CMD_SET_WOL_MODE; mbcp->mbox_in[1] = wol; status = ql_mailbox_command(qdev, mbcp); if (status) return status; if (mbcp->mbox_out[0] != MB_CMD_STS_GOOD) { netif_err(qdev, drv, qdev->ndev, "Failed to set WOL mode.\n"); status = -EIO; } return status; } int ql_mb_wol_set_magic(struct ql_adapter *qdev, u32 enable_wol) { struct mbox_params mbc; struct mbox_params *mbcp = &mbc; int status; u8 *addr = qdev->ndev->dev_addr; memset(mbcp, 0, sizeof(struct mbox_params)); mbcp->in_count = 8; mbcp->out_count = 1; mbcp->mbox_in[0] = MB_CMD_SET_WOL_MAGIC; if (enable_wol) { mbcp->mbox_in[1] = (u32)addr[0]; mbcp->mbox_in[2] = (u32)addr[1]; mbcp->mbox_in[3] = (u32)addr[2]; mbcp->mbox_in[4] = (u32)addr[3]; mbcp->mbox_in[5] = (u32)addr[4]; mbcp->mbox_in[6] = (u32)addr[5]; mbcp->mbox_in[7] = 0; } else { mbcp->mbox_in[1] = 0; mbcp->mbox_in[2] = 1; mbcp->mbox_in[3] = 1; mbcp->mbox_in[4] = 1; mbcp->mbox_in[5] = 1; mbcp->mbox_in[6] = 1; mbcp->mbox_in[7] = 0; } status = ql_mailbox_command(qdev, mbcp); if (status) return status; if (mbcp->mbox_out[0] != MB_CMD_STS_GOOD) { netif_err(qdev, drv, qdev->ndev, "Failed to set WOL mode.\n"); status = -EIO; } return status; } /* IDC - Inter Device Communication... * Some firmware commands require consent of adjacent FCOE * function. This function waits for the OK, or a * counter-request for a little more time.i * The firmware will complete the request if the other * function doesn't respond. */ static int ql_idc_wait(struct ql_adapter *qdev) { int status = -ETIMEDOUT; long wait_time = 1 * HZ; struct mbox_params *mbcp = &qdev->idc_mbc; do { /* Wait here for the command to complete * via the IDC process. */ wait_time = wait_for_completion_timeout(&qdev->ide_completion, wait_time); if (!wait_time) { netif_err(qdev, drv, qdev->ndev, "IDC Timeout.\n"); break; } /* Now examine the response from the IDC process. * We might have a good completion or a request for * more wait time. */ if (mbcp->mbox_out[0] == AEN_IDC_EXT) { netif_err(qdev, drv, qdev->ndev, "IDC Time Extension from function.\n"); wait_time += (mbcp->mbox_out[1] >> 8) & 0x0000000f; } else if (mbcp->mbox_out[0] == AEN_IDC_CMPLT) { netif_err(qdev, drv, qdev->ndev, "IDC Success.\n"); status = 0; break; } else { netif_err(qdev, drv, qdev->ndev, "IDC: Invalid State 0x%.04x.\n", mbcp->mbox_out[0]); status = -EIO; break; } } while (wait_time); return status; } int ql_mb_set_led_cfg(struct ql_adapter *qdev, u32 led_config) { struct mbox_params mbc; struct mbox_params *mbcp = &mbc; int status; memset(mbcp, 0, sizeof(struct mbox_params)); mbcp->in_count = 2; mbcp->out_count = 1; mbcp->mbox_in[0] = MB_CMD_SET_LED_CFG; mbcp->mbox_in[1] = led_config; status = ql_mailbox_command(qdev, mbcp); if (status) return status; if (mbcp->mbox_out[0] != MB_CMD_STS_GOOD) { netif_err(qdev, drv, qdev->ndev, "Failed to set LED Configuration.\n"); status = -EIO; } return status; } int ql_mb_get_led_cfg(struct ql_adapter *qdev) { struct mbox_params mbc; struct mbox_params *mbcp = &mbc; int status; memset(mbcp, 0, sizeof(struct mbox_params)); mbcp->in_count = 1; mbcp->out_count = 2; mbcp->mbox_in[0] = MB_CMD_GET_LED_CFG; status = ql_mailbox_command(qdev, mbcp); if (status) return status; if (mbcp->mbox_out[0] != MB_CMD_STS_GOOD) { netif_err(qdev, drv, qdev->ndev, "Failed to get LED Configuration.\n"); status = -EIO; } else qdev->led_config = mbcp->mbox_out[1]; return status; } int ql_mb_set_mgmnt_traffic_ctl(struct ql_adapter *qdev, u32 control) { struct mbox_params mbc; struct mbox_params *mbcp = &mbc; int status; memset(mbcp, 0, sizeof(struct mbox_params)); mbcp->in_count = 1; mbcp->out_count = 2; mbcp->mbox_in[0] = MB_CMD_SET_MGMNT_TFK_CTL; mbcp->mbox_in[1] = control; status = ql_mailbox_command(qdev, mbcp); if (status) return status; if (mbcp->mbox_out[0] == MB_CMD_STS_GOOD) return status; if (mbcp->mbox_out[0] == MB_CMD_STS_INVLD_CMD) { netif_err(qdev, drv, qdev->ndev, "Command not supported by firmware.\n"); status = -EINVAL; } else if (mbcp->mbox_out[0] == MB_CMD_STS_ERR) { /* This indicates that the firmware is * already in the state we are trying to * change it to. */ netif_err(qdev, drv, qdev->ndev, "Command parameters make no change.\n"); } return status; } /* Returns a negative error code or the mailbox command status. */ static int ql_mb_get_mgmnt_traffic_ctl(struct ql_adapter *qdev, u32 *control) { struct mbox_params mbc; struct mbox_params *mbcp = &mbc; int status; memset(mbcp, 0, sizeof(struct mbox_params)); *control = 0; mbcp->in_count = 1; mbcp->out_count = 1; mbcp->mbox_in[0] = MB_CMD_GET_MGMNT_TFK_CTL; status = ql_mailbox_command(qdev, mbcp); if (status) return status; if (mbcp->mbox_out[0] == MB_CMD_STS_GOOD) { *control = mbcp->mbox_in[1]; return status; } if (mbcp->mbox_out[0] == MB_CMD_STS_INVLD_CMD) { netif_err(qdev, drv, qdev->ndev, "Command not supported by firmware.\n"); status = -EINVAL; } else if (mbcp->mbox_out[0] == MB_CMD_STS_ERR) { netif_err(qdev, drv, qdev->ndev, "Failed to get MPI traffic control.\n"); status = -EIO; } return status; } int ql_wait_fifo_empty(struct ql_adapter *qdev) { int count = 5; u32 mgmnt_fifo_empty; u32 nic_fifo_empty; do { nic_fifo_empty = ql_read32(qdev, STS) & STS_NFE; ql_mb_get_mgmnt_traffic_ctl(qdev, &mgmnt_fifo_empty); mgmnt_fifo_empty &= MB_GET_MPI_TFK_FIFO_EMPTY; if (nic_fifo_empty && mgmnt_fifo_empty) return 0; msleep(100); } while (count-- > 0); return -ETIMEDOUT; } /* API called in work thread context to set new TX/RX * maximum frame size values to match MTU. */ static int ql_set_port_cfg(struct ql_adapter *qdev) { int status; status = ql_mb_set_port_cfg(qdev); if (status) return status; status = ql_idc_wait(qdev); return status; } /* The following routines are worker threads that process * events that may sleep waiting for completion. */ /* This thread gets the maximum TX and RX frame size values * from the firmware and, if necessary, changes them to match * the MTU setting. */ void ql_mpi_port_cfg_work(struct work_struct *work) { struct ql_adapter *qdev = container_of(work, struct ql_adapter, mpi_port_cfg_work.work); int status; status = ql_mb_get_port_cfg(qdev); if (status) { netif_err(qdev, drv, qdev->ndev, "Bug: Failed to get port config data.\n"); goto err; } if (qdev->link_config & CFG_JUMBO_FRAME_SIZE && qdev->max_frame_size == CFG_DEFAULT_MAX_FRAME_SIZE) goto end; qdev->link_config |= CFG_JUMBO_FRAME_SIZE; qdev->max_frame_size = CFG_DEFAULT_MAX_FRAME_SIZE; status = ql_set_port_cfg(qdev); if (status) { netif_err(qdev, drv, qdev->ndev, "Bug: Failed to set port config data.\n"); goto err; } end: clear_bit(QL_PORT_CFG, &qdev->flags); return; err: ql_queue_fw_error(qdev); goto end; } /* Process an inter-device request. This is issues by * the firmware in response to another function requesting * a change to the port. We set a flag to indicate a change * has been made and then send a mailbox command ACKing * the change request. */ void ql_mpi_idc_work(struct work_struct *work) { struct ql_adapter *qdev = container_of(work, struct ql_adapter, mpi_idc_work.work); int status; struct mbox_params *mbcp = &qdev->idc_mbc; u32 aen; int timeout; aen = mbcp->mbox_out[1] >> 16; timeout = (mbcp->mbox_out[1] >> 8) & 0xf; switch (aen) { default: netif_err(qdev, drv, qdev->ndev, "Bug: Unhandled IDC action.\n"); break; case MB_CMD_PORT_RESET: case MB_CMD_STOP_FW: ql_link_off(qdev); case MB_CMD_SET_PORT_CFG: /* Signal the resulting link up AEN * that the frame routing and mac addr * needs to be set. * */ set_bit(QL_CAM_RT_SET, &qdev->flags); /* Do ACK if required */ if (timeout) { status = ql_mb_idc_ack(qdev); if (status) netif_err(qdev, drv, qdev->ndev, "Bug: No pending IDC!\n"); } else { netif_printk(qdev, drv, KERN_DEBUG, qdev->ndev, "IDC ACK not required\n"); status = 0; /* success */ } break; /* These sub-commands issued by another (FCoE) * function are requesting to do an operation * on the shared resource (MPI environment). * We currently don't issue these so we just * ACK the request. */ case MB_CMD_IOP_RESTART_MPI: case MB_CMD_IOP_PREP_LINK_DOWN: /* Drop the link, reload the routing * table when link comes up. */ ql_link_off(qdev); set_bit(QL_CAM_RT_SET, &qdev->flags); /* Fall through. */ case MB_CMD_IOP_DVR_START: case MB_CMD_IOP_FLASH_ACC: case MB_CMD_IOP_CORE_DUMP_MPI: case MB_CMD_IOP_PREP_UPDATE_MPI: case MB_CMD_IOP_COMP_UPDATE_MPI: case MB_CMD_IOP_NONE: /* an IDC without params */ /* Do ACK if required */ if (timeout) { status = ql_mb_idc_ack(qdev); if (status) netif_err(qdev, drv, qdev->ndev, "Bug: No pending IDC!\n"); } else { netif_printk(qdev, drv, KERN_DEBUG, qdev->ndev, "IDC ACK not required\n"); status = 0; /* success */ } break; } } void ql_mpi_work(struct work_struct *work) { struct ql_adapter *qdev = container_of(work, struct ql_adapter, mpi_work.work); struct mbox_params mbc; struct mbox_params *mbcp = &mbc; int err = 0; mutex_lock(&qdev->mpi_mutex); /* Begin polled mode for MPI */ ql_write32(qdev, INTR_MASK, (INTR_MASK_PI << 16)); while (ql_read32(qdev, STS) & STS_PI) { memset(mbcp, 0, sizeof(struct mbox_params)); mbcp->out_count = 1; /* Don't continue if an async event * did not complete properly. */ err = ql_mpi_handler(qdev, mbcp); if (err) break; } /* End polled mode for MPI */ ql_write32(qdev, INTR_MASK, (INTR_MASK_PI << 16) | INTR_MASK_PI); mutex_unlock(&qdev->mpi_mutex); ql_enable_completion_interrupt(qdev, 0); } void ql_mpi_reset_work(struct work_struct *work) { struct ql_adapter *qdev = container_of(work, struct ql_adapter, mpi_reset_work.work); cancel_delayed_work_sync(&qdev->mpi_work); cancel_delayed_work_sync(&qdev->mpi_port_cfg_work); cancel_delayed_work_sync(&qdev->mpi_idc_work); /* If we're not the dominant NIC function, * then there is nothing to do. */ if (!ql_own_firmware(qdev)) { netif_err(qdev, drv, qdev->ndev, "Don't own firmware!\n"); return; } if (!ql_core_dump(qdev, qdev->mpi_coredump)) { netif_err(qdev, drv, qdev->ndev, "Core is dumped!\n"); qdev->core_is_dumped = 1; queue_delayed_work(qdev->workqueue, &qdev->mpi_core_to_log, 5 * HZ); } ql_soft_reset_mpi_risc(qdev); }
fbccf0a31e86571929c2ef493eb3e4e37c2aeadd
648776d3a0d9a8ca036acaf6f2f7a60dcdb45877
/tests/indent/c/cond.c
1ecb22d9892ae32ac51cdc8b844f3606c56308de
[ "Apache-2.0" ]
permissive
nvim-treesitter/nvim-treesitter
4c3c55cbe6ff73debcfaecb9b7a0d42d984be3e6
f8c2825220bff70919b527ee68fe44e7b1dae4b2
refs/heads/master
2023-08-31T20:04:23.790698
2023-08-31T09:28:16
2023-08-31T18:19:23
256,786,531
7,890
980
Apache-2.0
2023-09-14T18:07:03
2020-04-18T15:24:10
Scheme
UTF-8
C
false
false
132
c
cond.c
void foo(int x) { if (x > 10) { return; } else if (x < -10) { x = -10; } else { x = -x; } }
368242b5bb050be7ded2a74d096d788bf085b7dd
a173777f4ba02c1e683d75810fa6932487ba42cc
/2019/tokyowesterns-2019-quals/ebc/fuck.c
b601168c3c8953074246ebe0b53a37671e22165f
[]
no_license
perfectblue/ctf-writeups
ba9454ef06e1004253f004154fba6ae00d88ca09
3f2a8a2c2598d700f33cb3f39ceb515e2ba46312
refs/heads/master
2023-06-25T19:28:05.222110
2022-12-11T04:55:13
2022-12-11T04:55:13
133,306,580
606
75
null
2023-01-20T22:38:17
2018-05-14T04:53:27
Python
UTF-8
C
false
false
822
c
fuck.c
#include <stdio.h> #include <stdint.h> int main() { // stage1 // uint32_t key = 0x6d35bcd; // uint32_t offset = 0xf0c; // stage2 // uint32_t key = 0x43451b65; // uint32_t offset = 0x11d4; // stage3 // uint32_t key = 0x54aaf64b; // uint32_t offset = 0x193c; // stage4 uint32_t key = 0x52976abd; uint32_t offset = 0x2174; char buf[0x1000]; FILE* fd = fopen("ebc", "rb"); fseek(fd, offset, SEEK_SET); uint64_t len; fread(&len, 8, 1, fd); if (fread(buf, 1, len, fd) != len) perror("fread"); fclose(fd); printf("Length = 0x%lx\n", len); for (uint32_t *penis = buf; penis < buf + len; penis++) { *penis ^= key; } char filename[260]; snprintf(filename, sizeof(filename), "penis_%x.dec.bin", offset); filename[sizeof(filename)-1] = 0; fd = fopen(filename, "wb"); fwrite(buf, 1, len, fd); fclose(fd); printf("OK\n"); }
b7cf31a06cafcc3a866f9b906858f04b2e565534
07aeb5740a8dae36edf24e2686ff67e2959758fe
/programs/subprojects/doom/d_iwad.c
b52bacdc4e76371c61d0a1a8a56ba5eda9261e7c
[ "MIT" ]
permissive
codyd51/axle
59e992987bb871296aeadc69fc7244798090f3b1
96ae8852f15ad5c0a77c621c323ba47b4a7bdc69
refs/heads/paging-demo
2023-06-08T11:31:19.429032
2023-05-30T06:45:30
2023-05-30T06:45:30
58,590,685
597
61
MIT
2023-02-21T06:02:34
2016-05-11T23:41:08
C
UTF-8
C
false
false
18,917
c
d_iwad.c
// // Copyright(C) 2005-2014 Simon Howard // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // DESCRIPTION: // Search for and locate an IWAD file, and initialize according // to the IWAD type. // #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #include "config.h" #include "deh_str.h" #include "doomkeys.h" #include "d_iwad.h" #include "i_system.h" #include "m_argv.h" #include "m_config.h" #include "m_misc.h" #include "w_wad.h" #include "z_zone.h" static const iwad_t iwads[] = { { "doom2.wad", doom2, commercial, "Doom II" }, { "plutonia.wad", pack_plut, commercial, "Final Doom: Plutonia Experiment" }, { "tnt.wad", pack_tnt, commercial, "Final Doom: TNT: Evilution" }, { "/usr/doomdata/doom.wad", doom, retail, "Doom" }, { "/usr/doomdata/doom1.wad", doom, shareware, "Doom Shareware" }, { "chex.wad", pack_chex, shareware, "Chex Quest" }, { "hacx.wad", pack_hacx, commercial, "Hacx" }, { "freedm.wad", doom2, commercial, "FreeDM" }, { "freedoom2.wad", doom2, commercial, "Freedoom: Phase 2" }, { "freedoom1.wad", doom, retail, "Freedoom: Phase 1" }, { "heretic.wad", heretic, retail, "Heretic" }, { "heretic1.wad", heretic, shareware, "Heretic Shareware" }, { "hexen.wad", hexen, commercial, "Hexen" }, //{ "strife0.wad", strife, commercial, "Strife" }, // haleyjd: STRIFE-FIXME { "strife1.wad", strife, commercial, "Strife" }, }; // Array of locations to search for IWAD files // // "128 IWAD search directories should be enough for anybody". #define MAX_IWAD_DIRS 128 static boolean iwad_dirs_built = false; static char *iwad_dirs[MAX_IWAD_DIRS]; static int num_iwad_dirs = 0; static void AddIWADDir(char *dir) { if (num_iwad_dirs < MAX_IWAD_DIRS) { iwad_dirs[num_iwad_dirs] = dir; ++num_iwad_dirs; } } // This is Windows-specific code that automatically finds the location // of installed IWAD files. The registry is inspected to find special // keys installed by the Windows installers for various CD versions // of Doom. From these keys we can deduce where to find an IWAD. #if defined(_WIN32) && !defined(_WIN32_WCE) #define WIN32_LEAN_AND_MEAN #include <windows.h> typedef struct { HKEY root; char *path; char *value; } registry_value_t; #define UNINSTALLER_STRING "\\uninstl.exe /S " // Keys installed by the various CD editions. These are actually the // commands to invoke the uninstaller and look like this: // // C:\Program Files\Path\uninstl.exe /S C:\Program Files\Path // // With some munging we can find where Doom was installed. // [AlexMax] From the persepctive of a 64-bit executable, 32-bit registry // keys are located in a different spot. #if _WIN64 #define SOFTWARE_KEY "Software\\Wow6432Node" #else #define SOFTWARE_KEY "Software" #endif static registry_value_t uninstall_values[] = { // Ultimate Doom, CD version (Depths of Doom trilogy) { HKEY_LOCAL_MACHINE, SOFTWARE_KEY "\\Microsoft\\Windows\\CurrentVersion\\" "Uninstall\\Ultimate Doom for Windows 95", "UninstallString", }, // Doom II, CD version (Depths of Doom trilogy) { HKEY_LOCAL_MACHINE, SOFTWARE_KEY "\\Microsoft\\Windows\\CurrentVersion\\" "Uninstall\\Doom II for Windows 95", "UninstallString", }, // Final Doom { HKEY_LOCAL_MACHINE, SOFTWARE_KEY "\\Microsoft\\Windows\\CurrentVersion\\" "Uninstall\\Final Doom for Windows 95", "UninstallString", }, // Shareware version { HKEY_LOCAL_MACHINE, SOFTWARE_KEY "\\Microsoft\\Windows\\CurrentVersion\\" "Uninstall\\Doom Shareware for Windows 95", "UninstallString", }, }; // Value installed by the Collector's Edition when it is installed static registry_value_t collectors_edition_value = { HKEY_LOCAL_MACHINE, SOFTWARE_KEY "\\Activision\\DOOM Collector's Edition\\v1.0", "INSTALLPATH", }; // Subdirectories of the above install path, where IWADs are installed. static char *collectors_edition_subdirs[] = { "Doom2", "Final Doom", "Ultimate Doom", }; // Location where Steam is installed static registry_value_t steam_install_location = { HKEY_LOCAL_MACHINE, SOFTWARE_KEY "\\Valve\\Steam", "InstallPath", }; // Subdirs of the steam install directory where IWADs are found static char *steam_install_subdirs[] = { "steamapps\\common\\doom 2\\base", "steamapps\\common\\final doom\\base", "steamapps\\common\\ultimate doom\\base", "steamapps\\common\\heretic shadow of the serpent riders\\base", "steamapps\\common\\hexen\\base", "steamapps\\common\\hexen deathkings of the dark citadel\\base", // From Doom 3: BFG Edition: "steamapps\\common\\DOOM 3 BFG Edition\\base\\wads", }; #define STEAM_BFG_GUS_PATCHES \ "steamapps\\common\\DOOM 3 BFG Edition\\base\\classicmusic\\instruments" static char *GetRegistryString(registry_value_t *reg_val) { HKEY key; DWORD len; DWORD valtype; char *result; // Open the key (directory where the value is stored) if (RegOpenKeyEx(reg_val->root, reg_val->path, 0, KEY_READ, &key) != ERROR_SUCCESS) { return NULL; } result = NULL; // Find the type and length of the string, and only accept strings. if (RegQueryValueEx(key, reg_val->value, NULL, &valtype, NULL, &len) == ERROR_SUCCESS && valtype == REG_SZ) { // Allocate a buffer for the value and read the value result = malloc(len); if (RegQueryValueEx(key, reg_val->value, NULL, &valtype, (unsigned char *) result, &len) != ERROR_SUCCESS) { free(result); result = NULL; } } // Close the key RegCloseKey(key); return result; } // Check for the uninstall strings from the CD versions static void CheckUninstallStrings(void) { unsigned int i; for (i=0; i<arrlen(uninstall_values); ++i) { char *val; char *path; char *unstr; val = GetRegistryString(&uninstall_values[i]); if (val == NULL) { continue; } unstr = strstr(val, UNINSTALLER_STRING); if (unstr == NULL) { free(val); } else { path = unstr + strlen(UNINSTALLER_STRING); AddIWADDir(path); } } } // Check for Doom: Collector's Edition static void CheckCollectorsEdition(void) { char *install_path; char *subpath; unsigned int i; install_path = GetRegistryString(&collectors_edition_value); if (install_path == NULL) { return; } for (i=0; i<arrlen(collectors_edition_subdirs); ++i) { subpath = M_StringJoin(install_path, DIR_SEPARATOR_S, collectors_edition_subdirs[i], NULL); AddIWADDir(subpath); } free(install_path); } // Check for Doom downloaded via Steam static void CheckSteamEdition(void) { char *install_path; char *subpath; size_t i; install_path = GetRegistryString(&steam_install_location); if (install_path == NULL) { return; } for (i=0; i<arrlen(steam_install_subdirs); ++i) { subpath = M_StringJoin(install_path, DIR_SEPARATOR_S, steam_install_subdirs[i], NULL); AddIWADDir(subpath); } free(install_path); } // The BFG edition ships with a full set of GUS patches. If we find them, // we can autoconfigure to use them. static void CheckSteamGUSPatches(void) { const char *current_path; char *install_path; char *patch_path; int len; // Already configured? Don't stomp on the user's choices. current_path = M_GetStrVariable("gus_patch_path"); if (current_path != NULL && strlen(current_path) > 0) { return; } install_path = GetRegistryString(&steam_install_location); if (install_path == NULL) { return; } len = strlen(install_path) + strlen(STEAM_BFG_GUS_PATCHES) + 20; patch_path = malloc(len); M_snprintf(patch_path, len, "%s\\%s\\ACBASS.PAT", install_path, STEAM_BFG_GUS_PATCHES); // Does acbass.pat exist? If so, then set gus_patch_path. if (M_FileExists(patch_path)) { M_snprintf(patch_path, len, "%s\\%s", install_path, STEAM_BFG_GUS_PATCHES); M_SetVariable("gus_patch_path", patch_path); } free(patch_path); free(install_path); } // Default install directories for DOS Doom static void CheckDOSDefaults(void) { // These are the default install directories used by the deice // installer program: AddIWADDir("\\doom2"); // Doom II AddIWADDir("\\plutonia"); // Final Doom AddIWADDir("\\tnt"); AddIWADDir("\\doom_se"); // Ultimate Doom AddIWADDir("\\doom"); // Shareware / Registered Doom AddIWADDir("\\dooms"); // Shareware versions AddIWADDir("\\doomsw"); AddIWADDir("\\heretic"); // Heretic AddIWADDir("\\hrtic_se"); // Heretic Shareware from Quake disc AddIWADDir("\\hexen"); // Hexen AddIWADDir("\\hexendk"); // Hexen Deathkings of the Dark Citadel AddIWADDir("\\strife"); // Strife } #endif // Returns true if the specified path is a path to a file // of the specified name. static boolean DirIsFile(char *path, char *filename) { size_t path_len; size_t filename_len; path_len = strlen(path); filename_len = strlen(filename); return path_len >= filename_len + 1 && path[path_len - filename_len - 1] == DIR_SEPARATOR && !strcasecmp(&path[path_len - filename_len], filename); } // Check if the specified directory contains the specified IWAD // file, returning the full path to the IWAD if found, or NULL // if not found. static char *CheckDirectoryHasIWAD(char *dir, char *iwadname) { char *filename; // As a special case, the "directory" may refer directly to an // IWAD file if the path comes from DOOMWADDIR or DOOMWADPATH. if (DirIsFile(dir, iwadname) && M_FileExists(dir)) { return strdup(dir); } // Construct the full path to the IWAD if it is located in // this directory, and check if it exists. if (!strcmp(dir, ".")) { filename = strdup(iwadname); } else { filename = M_StringJoin(dir, DIR_SEPARATOR_S, iwadname, NULL); } printf("Trying IWAD file:%s\n", filename); if (M_FileExists(filename)) { return filename; } free(filename); return NULL; } // Search a directory to try to find an IWAD // Returns the location of the IWAD if found, otherwise NULL. static char *SearchDirectoryForIWAD(char *dir, int mask, GameMission_t *mission) { char *filename; size_t i; for (i=0; i<arrlen(iwads); ++i) { if (((1 << iwads[i].mission) & mask) == 0) { continue; } filename = CheckDirectoryHasIWAD(dir, DEH_String(iwads[i].name)); if (filename != NULL) { *mission = iwads[i].mission; return filename; } } return NULL; } // When given an IWAD with the '-iwad' parameter, // attempt to identify it by its name. static GameMission_t IdentifyIWADByName(char *name, int mask) { size_t i; GameMission_t mission; char *p; p = strrchr(name, DIR_SEPARATOR); if (p != NULL) { name = p + 1; } mission = none; for (i=0; i<arrlen(iwads); ++i) { // Check if the filename is this IWAD name. // Only use supported missions: if (((1 << iwads[i].mission) & mask) == 0) continue; // Check if it ends in this IWAD name. if (!strcasecmp(name, iwads[i].name)) { mission = iwads[i].mission; break; } } return mission; } #if ORIGCODE // // Add directories from the list in the DOOMWADPATH environment variable. // static void AddDoomWadPath(void) { char *doomwadpath; char *p; // Check the DOOMWADPATH environment variable. doomwadpath = getenv("DOOMWADPATH"); if (doomwadpath == NULL) { return; } doomwadpath = strdup(doomwadpath); // Add the initial directory AddIWADDir(doomwadpath); // Split into individual dirs within the list. p = doomwadpath; for (;;) { p = strchr(p, PATH_SEPARATOR); if (p != NULL) { // Break at the separator and store the right hand side // as another iwad dir *p = '\0'; p += 1; AddIWADDir(p); } else { break; } } } #endif // // Build a list of IWAD files // static void BuildIWADDirList(void) { #if ORIGCODE char *doomwaddir; if (iwad_dirs_built) { return; } // Look in the current directory. Doom always does this. AddIWADDir("."); // Add DOOMWADDIR if it is in the environment doomwaddir = getenv("DOOMWADDIR"); if (doomwaddir != NULL) { AddIWADDir(doomwaddir); } // Add dirs from DOOMWADPATH AddDoomWadPath(); #ifdef _WIN32 // Search the registry and find where IWADs have been installed. CheckUninstallStrings(); CheckCollectorsEdition(); CheckSteamEdition(); CheckDOSDefaults(); // Check for GUS patches installed with the BFG edition! CheckSteamGUSPatches(); #else // Standard places where IWAD files are installed under Unix. AddIWADDir("/usr/share/games/doom"); AddIWADDir("/usr/local/share/games/doom"); #endif #else AddIWADDir (FILES_DIR); // Don't run this function again. iwad_dirs_built = true; #endif } // // Searches WAD search paths for an WAD with a specific filename. // char *D_FindWADByName(char *name) { char *path; int i; // Absolute path? if (M_FileExists(name)) { return name; } BuildIWADDirList(); // Search through all IWAD paths for a file with the given name. for (i=0; i<num_iwad_dirs; ++i) { // As a special case, if this is in DOOMWADDIR or DOOMWADPATH, // the "directory" may actually refer directly to an IWAD // file. if (DirIsFile(iwad_dirs[i], name) && M_FileExists(iwad_dirs[i])) { return strdup(iwad_dirs[i]); } // Construct a string for the full path path = M_StringJoin(iwad_dirs[i], DIR_SEPARATOR_S, name, NULL); if (M_FileExists(path)) { return path; } free(path); } // File not found return NULL; } // // D_TryWADByName // // Searches for a WAD by its filename, or passes through the filename // if not found. // char *D_TryFindWADByName(char *filename) { char *result; result = D_FindWADByName(filename); if (result != NULL) { return result; } else { return filename; } } // // FindIWAD // Checks availability of IWAD files by name, // to determine whether registered/commercial features // should be executed (notably loading PWADs). // char *D_FindIWAD(int mask, GameMission_t *mission) { char *result; char *iwadfile; int iwadparm; int i; // Check for the -iwad parameter //! // Specify an IWAD file to use. // // @arg <file> // iwadparm = M_CheckParmWithArgs("-iwad", 1); if (iwadparm) { // Search through IWAD dirs for an IWAD with the given name. iwadfile = myargv[iwadparm + 1]; result = D_FindWADByName(iwadfile); if (result == NULL) { I_Error("IWAD file '%s' not found!", iwadfile); } *mission = IdentifyIWADByName(result, mask); } else { // Search through the list and look for an IWAD printf("-iwad not specified, trying a few iwad names\n"); result = NULL; BuildIWADDirList(); for (i=0; result == NULL && i<num_iwad_dirs; ++i) { result = SearchDirectoryForIWAD(iwad_dirs[i], mask, mission); } } return result; } // Find all IWADs in the IWAD search path matching the given mask. const iwad_t **D_FindAllIWADs(int mask) { const iwad_t **result; int result_len; char *filename; int i; result = malloc(sizeof(iwad_t *) * (arrlen(iwads) + 1)); result_len = 0; // Try to find all IWADs for (i=0; i<arrlen(iwads); ++i) { if (((1 << iwads[i].mission) & mask) == 0) { continue; } filename = D_FindWADByName(iwads[i].name); if (filename != NULL) { result[result_len] = &iwads[i]; ++result_len; } } // End of list result[result_len] = NULL; return result; } // // Get the IWAD name used for savegames. // char *D_SaveGameIWADName(GameMission_t gamemission) { size_t i; // Determine the IWAD name to use for savegames. // This determines the directory the savegame files get put into. // // Note that we match on gamemission rather than on IWAD name. // This ensures that doom1.wad and doom.wad saves are stored // in the same place. for (i=0; i<arrlen(iwads); ++i) { if (gamemission == iwads[i].mission) { return iwads[i].name; } } // Default fallback: return "unknown.wad"; } char *D_SuggestIWADName(GameMission_t mission, GameMode_t mode) { int i; for (i = 0; i < arrlen(iwads); ++i) { if (iwads[i].mission == mission && iwads[i].mode == mode) { return iwads[i].name; } } return "unknown.wad"; } char *D_SuggestGameName(GameMission_t mission, GameMode_t mode) { int i; for (i = 0; i < arrlen(iwads); ++i) { if (iwads[i].mission == mission && (mode == indetermined || iwads[i].mode == mode)) { return iwads[i].description; } } return "Unknown game?"; }
dde3baf39b7c9c83549297f41ebf86adce741f35
eecd5e4c50d8b78a769bcc2675250576bed34066
/src/ksp/pc/impls/hypre/hypre.c
c7c17069e88d8015dab110245a23359d141521ee
[ "BSD-2-Clause" ]
permissive
petsc/petsc
3b1a04fea71858e0292f9fd4d04ea11618c50969
9c5460f9064ca60dd71a234a1f6faf93e7a6b0c9
refs/heads/main
2023-08-17T20:51:16.507070
2023-08-17T16:08:06
2023-08-17T16:08:06
8,691,401
341
169
NOASSERTION
2023-03-29T11:02:58
2013-03-10T20:55:21
C
UTF-8
C
false
false
152,561
c
hypre.c
/* Provides an interface to the LLNL package hypre */ #include <petscpkg_version.h> #include <petsc/private/pcimpl.h> /*I "petscpc.h" I*/ /* this include is needed ONLY to allow access to the private data inside the Mat object specific to hypre */ #include <petsc/private/matimpl.h> #include <petsc/private/vecimpl.h> #include <../src/vec/vec/impls/hypre/vhyp.h> #include <../src/mat/impls/hypre/mhypre.h> #include <../src/dm/impls/da/hypre/mhyp.h> #include <_hypre_parcsr_ls.h> #include <petscmathypre.h> #if defined(PETSC_HAVE_HYPRE_DEVICE) #include <petsc/private/deviceimpl.h> #endif static PetscBool cite = PETSC_FALSE; static const char hypreCitation[] = "@manual{hypre-web-page,\n title = {{\\sl hypre}: High Performance Preconditioners},\n organization = {Lawrence Livermore National Laboratory},\n note = " "{\\url{https://www.llnl.gov/casc/hypre}}\n}\n"; /* Private context (data structure) for the preconditioner. */ typedef struct { HYPRE_Solver hsolver; Mat hpmat; /* MatHYPRE */ HYPRE_Int (*destroy)(HYPRE_Solver); HYPRE_Int (*solve)(HYPRE_Solver, HYPRE_ParCSRMatrix, HYPRE_ParVector, HYPRE_ParVector); HYPRE_Int (*setup)(HYPRE_Solver, HYPRE_ParCSRMatrix, HYPRE_ParVector, HYPRE_ParVector); MPI_Comm comm_hypre; char *hypre_type; /* options for Pilut and BoomerAMG*/ PetscInt maxiter; PetscReal tol; /* options for Pilut */ PetscInt factorrowsize; /* options for ParaSails */ PetscInt nlevels; PetscReal threshold; PetscReal filter; PetscReal loadbal; PetscInt logging; PetscInt ruse; PetscInt symt; /* options for BoomerAMG */ PetscBool printstatistics; /* options for BoomerAMG */ PetscInt cycletype; PetscInt maxlevels; PetscReal strongthreshold; PetscReal maxrowsum; PetscInt gridsweeps[3]; PetscInt coarsentype; PetscInt measuretype; PetscInt smoothtype; PetscInt smoothnumlevels; PetscInt eu_level; /* Number of levels for ILU(k) in Euclid */ PetscReal eu_droptolerance; /* Drop tolerance for ILU(k) in Euclid */ PetscInt eu_bj; /* Defines use of Block Jacobi ILU in Euclid */ PetscInt relaxtype[3]; PetscReal relaxweight; PetscReal outerrelaxweight; PetscInt relaxorder; PetscReal truncfactor; PetscBool applyrichardson; PetscInt pmax; PetscInt interptype; PetscInt maxc; PetscInt minc; #if PETSC_PKG_HYPRE_VERSION_GE(2, 23, 0) char *spgemm_type; // this is a global hypre parameter but is closely associated with BoomerAMG #endif /* GPU */ PetscBool keeptranspose; PetscInt rap2; PetscInt mod_rap2; /* AIR */ PetscInt Rtype; PetscReal Rstrongthreshold; PetscReal Rfilterthreshold; PetscInt Adroptype; PetscReal Adroptol; PetscInt agg_nl; PetscInt agg_interptype; PetscInt agg_num_paths; PetscBool nodal_relax; PetscInt nodal_relax_levels; PetscInt nodal_coarsening; PetscInt nodal_coarsening_diag; PetscInt vec_interp_variant; PetscInt vec_interp_qmax; PetscBool vec_interp_smooth; PetscInt interp_refine; /* NearNullSpace support */ VecHYPRE_IJVector *hmnull; HYPRE_ParVector *phmnull; PetscInt n_hmnull; Vec hmnull_constant; /* options for AS (Auxiliary Space preconditioners) */ PetscInt as_print; PetscInt as_max_iter; PetscReal as_tol; PetscInt as_relax_type; PetscInt as_relax_times; PetscReal as_relax_weight; PetscReal as_omega; PetscInt as_amg_alpha_opts[5]; /* AMG coarsen type, agg_levels, relax_type, interp_type, Pmax for vector Poisson (AMS) or Curl problem (ADS) */ PetscReal as_amg_alpha_theta; /* AMG strength for vector Poisson (AMS) or Curl problem (ADS) */ PetscInt as_amg_beta_opts[5]; /* AMG coarsen type, agg_levels, relax_type, interp_type, Pmax for scalar Poisson (AMS) or vector Poisson (ADS) */ PetscReal as_amg_beta_theta; /* AMG strength for scalar Poisson (AMS) or vector Poisson (ADS) */ PetscInt ams_cycle_type; PetscInt ads_cycle_type; /* additional data */ Mat G; /* MatHYPRE */ Mat C; /* MatHYPRE */ Mat alpha_Poisson; /* MatHYPRE */ Mat beta_Poisson; /* MatHYPRE */ /* extra information for AMS */ PetscInt dim; /* geometrical dimension */ VecHYPRE_IJVector coords[3]; VecHYPRE_IJVector constants[3]; VecHYPRE_IJVector interior; Mat RT_PiFull, RT_Pi[3]; Mat ND_PiFull, ND_Pi[3]; PetscBool ams_beta_is_zero; PetscBool ams_beta_is_zero_part; PetscInt ams_proj_freq; } PC_HYPRE; /* Matrices with AIJ format are created IN PLACE with using (I,J,data) from BoomerAMG. Since the data format in hypre_ParCSRMatrix is different from that used in PETSc, the original hypre_ParCSRMatrix can not be used any more after call this routine. It is used in PCHMG. Other users should avoid using this function. */ static PetscErrorCode PCGetCoarseOperators_BoomerAMG(PC pc, PetscInt *nlevels, Mat *operators[]) { PC_HYPRE *jac = (PC_HYPRE *)pc->data; PetscBool same = PETSC_FALSE; PetscInt num_levels, l; Mat *mattmp; hypre_ParCSRMatrix **A_array; PetscFunctionBegin; PetscCall(PetscStrcmp(jac->hypre_type, "boomeramg", &same)); PetscCheck(same, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_NOTSAMETYPE, "Hypre type is not BoomerAMG "); num_levels = hypre_ParAMGDataNumLevels((hypre_ParAMGData *)(jac->hsolver)); PetscCall(PetscMalloc1(num_levels, &mattmp)); A_array = hypre_ParAMGDataAArray((hypre_ParAMGData *)(jac->hsolver)); for (l = 1; l < num_levels; l++) { PetscCall(MatCreateFromParCSR(A_array[l], MATAIJ, PETSC_OWN_POINTER, &(mattmp[num_levels - 1 - l]))); /* We want to own the data, and HYPRE can not touch this matrix any more */ A_array[l] = NULL; } *nlevels = num_levels; *operators = mattmp; PetscFunctionReturn(PETSC_SUCCESS); } /* Matrices with AIJ format are created IN PLACE with using (I,J,data) from BoomerAMG. Since the data format in hypre_ParCSRMatrix is different from that used in PETSc, the original hypre_ParCSRMatrix can not be used any more after call this routine. It is used in PCHMG. Other users should avoid using this function. */ static PetscErrorCode PCGetInterpolations_BoomerAMG(PC pc, PetscInt *nlevels, Mat *interpolations[]) { PC_HYPRE *jac = (PC_HYPRE *)pc->data; PetscBool same = PETSC_FALSE; PetscInt num_levels, l; Mat *mattmp; hypre_ParCSRMatrix **P_array; PetscFunctionBegin; PetscCall(PetscStrcmp(jac->hypre_type, "boomeramg", &same)); PetscCheck(same, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_NOTSAMETYPE, "Hypre type is not BoomerAMG "); num_levels = hypre_ParAMGDataNumLevels((hypre_ParAMGData *)(jac->hsolver)); PetscCall(PetscMalloc1(num_levels, &mattmp)); P_array = hypre_ParAMGDataPArray((hypre_ParAMGData *)(jac->hsolver)); for (l = 1; l < num_levels; l++) { PetscCall(MatCreateFromParCSR(P_array[num_levels - 1 - l], MATAIJ, PETSC_OWN_POINTER, &(mattmp[l - 1]))); /* We want to own the data, and HYPRE can not touch this matrix any more */ P_array[num_levels - 1 - l] = NULL; } *nlevels = num_levels; *interpolations = mattmp; PetscFunctionReturn(PETSC_SUCCESS); } /* Resets (frees) Hypre's representation of the near null space */ static PetscErrorCode PCHYPREResetNearNullSpace_Private(PC pc) { PC_HYPRE *jac = (PC_HYPRE *)pc->data; PetscInt i; PetscFunctionBegin; for (i = 0; i < jac->n_hmnull; i++) PetscCall(VecHYPRE_IJVectorDestroy(&jac->hmnull[i])); PetscCall(PetscFree(jac->hmnull)); PetscCall(PetscFree(jac->phmnull)); PetscCall(VecDestroy(&jac->hmnull_constant)); jac->n_hmnull = 0; PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCSetUp_HYPRE(PC pc) { PC_HYPRE *jac = (PC_HYPRE *)pc->data; Mat_HYPRE *hjac; HYPRE_ParCSRMatrix hmat; HYPRE_ParVector bv, xv; PetscBool ishypre; PetscFunctionBegin; /* default type is boomerAMG */ if (!jac->hypre_type) PetscCall(PCHYPRESetType(pc, "boomeramg")); /* get hypre matrix */ if (pc->flag == DIFFERENT_NONZERO_PATTERN) PetscCall(MatDestroy(&jac->hpmat)); PetscCall(PetscObjectTypeCompare((PetscObject)pc->pmat, MATHYPRE, &ishypre)); if (!ishypre) { /* Temporary fix since we do not support MAT_REUSE_MATRIX with HYPRE device */ #if defined(PETSC_HAVE_HYPRE_DEVICE) PetscBool iscuda, iship, iskokkos; PetscCall(PetscObjectTypeCompareAny((PetscObject)pc->pmat, &iscuda, MATSEQAIJCUSPARSE, MATMPIAIJCUSPARSE, "")); PetscCall(PetscObjectTypeCompareAny((PetscObject)pc->pmat, &iship, MATSEQAIJHIPSPARSE, MATMPIAIJHIPSPARSE, "")); PetscCall(PetscObjectTypeCompareAny((PetscObject)pc->pmat, &iskokkos, MATSEQAIJKOKKOS, MATMPIAIJKOKKOS, "")); if (iscuda || iship || iskokkos) PetscCall(MatDestroy(&jac->hpmat)); #endif PetscCall(MatConvert(pc->pmat, MATHYPRE, jac->hpmat ? MAT_REUSE_MATRIX : MAT_INITIAL_MATRIX, &jac->hpmat)); } else { PetscCall(PetscObjectReference((PetscObject)pc->pmat)); PetscCall(MatDestroy(&jac->hpmat)); jac->hpmat = pc->pmat; } /* allow debug */ PetscCall(MatViewFromOptions(jac->hpmat, NULL, "-pc_hypre_mat_view")); hjac = (Mat_HYPRE *)(jac->hpmat->data); /* special case for BoomerAMG */ if (jac->setup == HYPRE_BoomerAMGSetup) { MatNullSpace mnull; PetscBool has_const; PetscInt bs, nvec, i; const Vec *vecs; PetscCall(MatGetBlockSize(pc->pmat, &bs)); if (bs > 1) PetscCallExternal(HYPRE_BoomerAMGSetNumFunctions, jac->hsolver, bs); PetscCall(MatGetNearNullSpace(pc->mat, &mnull)); if (mnull) { PetscCall(PCHYPREResetNearNullSpace_Private(pc)); PetscCall(MatNullSpaceGetVecs(mnull, &has_const, &nvec, &vecs)); PetscCall(PetscMalloc1(nvec + 1, &jac->hmnull)); PetscCall(PetscMalloc1(nvec + 1, &jac->phmnull)); for (i = 0; i < nvec; i++) { PetscCall(VecHYPRE_IJVectorCreate(vecs[i]->map, &jac->hmnull[i])); PetscCall(VecHYPRE_IJVectorCopy(vecs[i], jac->hmnull[i])); PetscCallExternal(HYPRE_IJVectorGetObject, jac->hmnull[i]->ij, (void **)&jac->phmnull[i]); } if (has_const) { PetscCall(MatCreateVecs(pc->pmat, &jac->hmnull_constant, NULL)); PetscCall(VecSet(jac->hmnull_constant, 1)); PetscCall(VecNormalize(jac->hmnull_constant, NULL)); PetscCall(VecHYPRE_IJVectorCreate(jac->hmnull_constant->map, &jac->hmnull[nvec])); PetscCall(VecHYPRE_IJVectorCopy(jac->hmnull_constant, jac->hmnull[nvec])); PetscCallExternal(HYPRE_IJVectorGetObject, jac->hmnull[nvec]->ij, (void **)&jac->phmnull[nvec]); nvec++; } PetscCallExternal(HYPRE_BoomerAMGSetInterpVectors, jac->hsolver, nvec, jac->phmnull); jac->n_hmnull = nvec; } } /* special case for AMS */ if (jac->setup == HYPRE_AMSSetup) { Mat_HYPRE *hm; HYPRE_ParCSRMatrix parcsr; if (!jac->coords[0] && !jac->constants[0] && !(jac->ND_PiFull || (jac->ND_Pi[0] && jac->ND_Pi[1]))) { SETERRQ(PetscObjectComm((PetscObject)pc), PETSC_ERR_USER, "HYPRE AMS preconditioner needs either the coordinate vectors via PCSetCoordinates() or the edge constant vectors via PCHYPRESetEdgeConstantVectors() or the interpolation matrix via PCHYPRESetInterpolations()"); } if (jac->dim) PetscCallExternal(HYPRE_AMSSetDimension, jac->hsolver, jac->dim); if (jac->constants[0]) { HYPRE_ParVector ozz, zoz, zzo = NULL; PetscCallExternal(HYPRE_IJVectorGetObject, jac->constants[0]->ij, (void **)(&ozz)); PetscCallExternal(HYPRE_IJVectorGetObject, jac->constants[1]->ij, (void **)(&zoz)); if (jac->constants[2]) PetscCallExternal(HYPRE_IJVectorGetObject, jac->constants[2]->ij, (void **)(&zzo)); PetscCallExternal(HYPRE_AMSSetEdgeConstantVectors, jac->hsolver, ozz, zoz, zzo); } if (jac->coords[0]) { HYPRE_ParVector coords[3]; coords[0] = NULL; coords[1] = NULL; coords[2] = NULL; if (jac->coords[0]) PetscCallExternal(HYPRE_IJVectorGetObject, jac->coords[0]->ij, (void **)(&coords[0])); if (jac->coords[1]) PetscCallExternal(HYPRE_IJVectorGetObject, jac->coords[1]->ij, (void **)(&coords[1])); if (jac->coords[2]) PetscCallExternal(HYPRE_IJVectorGetObject, jac->coords[2]->ij, (void **)(&coords[2])); PetscCallExternal(HYPRE_AMSSetCoordinateVectors, jac->hsolver, coords[0], coords[1], coords[2]); } PetscCheck(jac->G, PetscObjectComm((PetscObject)pc), PETSC_ERR_USER, "HYPRE AMS preconditioner needs the discrete gradient operator via PCHYPRESetDiscreteGradient"); hm = (Mat_HYPRE *)(jac->G->data); PetscCallExternal(HYPRE_IJMatrixGetObject, hm->ij, (void **)(&parcsr)); PetscCallExternal(HYPRE_AMSSetDiscreteGradient, jac->hsolver, parcsr); if (jac->alpha_Poisson) { hm = (Mat_HYPRE *)(jac->alpha_Poisson->data); PetscCallExternal(HYPRE_IJMatrixGetObject, hm->ij, (void **)(&parcsr)); PetscCallExternal(HYPRE_AMSSetAlphaPoissonMatrix, jac->hsolver, parcsr); } if (jac->ams_beta_is_zero) { PetscCallExternal(HYPRE_AMSSetBetaPoissonMatrix, jac->hsolver, NULL); } else if (jac->beta_Poisson) { hm = (Mat_HYPRE *)(jac->beta_Poisson->data); PetscCallExternal(HYPRE_IJMatrixGetObject, hm->ij, (void **)(&parcsr)); PetscCallExternal(HYPRE_AMSSetBetaPoissonMatrix, jac->hsolver, parcsr); } else if (jac->ams_beta_is_zero_part) { if (jac->interior) { HYPRE_ParVector interior = NULL; PetscCallExternal(HYPRE_IJVectorGetObject, jac->interior->ij, (void **)(&interior)); PetscCallExternal(HYPRE_AMSSetInteriorNodes, jac->hsolver, interior); } else { jac->ams_beta_is_zero_part = PETSC_FALSE; } } if (jac->ND_PiFull || (jac->ND_Pi[0] && jac->ND_Pi[1])) { PetscInt i; HYPRE_ParCSRMatrix nd_parcsrfull, nd_parcsr[3]; if (jac->ND_PiFull) { hm = (Mat_HYPRE *)(jac->ND_PiFull->data); PetscCallExternal(HYPRE_IJMatrixGetObject, hm->ij, (void **)(&nd_parcsrfull)); } else { nd_parcsrfull = NULL; } for (i = 0; i < 3; ++i) { if (jac->ND_Pi[i]) { hm = (Mat_HYPRE *)(jac->ND_Pi[i]->data); PetscCallExternal(HYPRE_IJMatrixGetObject, hm->ij, (void **)(&nd_parcsr[i])); } else { nd_parcsr[i] = NULL; } } PetscCallExternal(HYPRE_AMSSetInterpolations, jac->hsolver, nd_parcsrfull, nd_parcsr[0], nd_parcsr[1], nd_parcsr[2]); } } /* special case for ADS */ if (jac->setup == HYPRE_ADSSetup) { Mat_HYPRE *hm; HYPRE_ParCSRMatrix parcsr; if (!jac->coords[0] && !((jac->RT_PiFull || (jac->RT_Pi[0] && jac->RT_Pi[1])) && (jac->ND_PiFull || (jac->ND_Pi[0] && jac->ND_Pi[1])))) { SETERRQ(PetscObjectComm((PetscObject)pc), PETSC_ERR_USER, "HYPRE ADS preconditioner needs either the coordinate vectors via PCSetCoordinates() or the interpolation matrices via PCHYPRESetInterpolations"); } else PetscCheck(jac->coords[1] && jac->coords[2], PetscObjectComm((PetscObject)pc), PETSC_ERR_USER, "HYPRE ADS preconditioner has been designed for three dimensional problems! For two dimensional problems, use HYPRE AMS instead"); PetscCheck(jac->G, PetscObjectComm((PetscObject)pc), PETSC_ERR_USER, "HYPRE ADS preconditioner needs the discrete gradient operator via PCHYPRESetDiscreteGradient"); PetscCheck(jac->C, PetscObjectComm((PetscObject)pc), PETSC_ERR_USER, "HYPRE ADS preconditioner needs the discrete curl operator via PCHYPRESetDiscreteGradient"); if (jac->coords[0]) { HYPRE_ParVector coords[3]; coords[0] = NULL; coords[1] = NULL; coords[2] = NULL; if (jac->coords[0]) PetscCallExternal(HYPRE_IJVectorGetObject, jac->coords[0]->ij, (void **)(&coords[0])); if (jac->coords[1]) PetscCallExternal(HYPRE_IJVectorGetObject, jac->coords[1]->ij, (void **)(&coords[1])); if (jac->coords[2]) PetscCallExternal(HYPRE_IJVectorGetObject, jac->coords[2]->ij, (void **)(&coords[2])); PetscCallExternal(HYPRE_ADSSetCoordinateVectors, jac->hsolver, coords[0], coords[1], coords[2]); } hm = (Mat_HYPRE *)(jac->G->data); PetscCallExternal(HYPRE_IJMatrixGetObject, hm->ij, (void **)(&parcsr)); PetscCallExternal(HYPRE_ADSSetDiscreteGradient, jac->hsolver, parcsr); hm = (Mat_HYPRE *)(jac->C->data); PetscCallExternal(HYPRE_IJMatrixGetObject, hm->ij, (void **)(&parcsr)); PetscCallExternal(HYPRE_ADSSetDiscreteCurl, jac->hsolver, parcsr); if ((jac->RT_PiFull || (jac->RT_Pi[0] && jac->RT_Pi[1])) && (jac->ND_PiFull || (jac->ND_Pi[0] && jac->ND_Pi[1]))) { PetscInt i; HYPRE_ParCSRMatrix rt_parcsrfull, rt_parcsr[3]; HYPRE_ParCSRMatrix nd_parcsrfull, nd_parcsr[3]; if (jac->RT_PiFull) { hm = (Mat_HYPRE *)(jac->RT_PiFull->data); PetscCallExternal(HYPRE_IJMatrixGetObject, hm->ij, (void **)(&rt_parcsrfull)); } else { rt_parcsrfull = NULL; } for (i = 0; i < 3; ++i) { if (jac->RT_Pi[i]) { hm = (Mat_HYPRE *)(jac->RT_Pi[i]->data); PetscCallExternal(HYPRE_IJMatrixGetObject, hm->ij, (void **)(&rt_parcsr[i])); } else { rt_parcsr[i] = NULL; } } if (jac->ND_PiFull) { hm = (Mat_HYPRE *)(jac->ND_PiFull->data); PetscCallExternal(HYPRE_IJMatrixGetObject, hm->ij, (void **)(&nd_parcsrfull)); } else { nd_parcsrfull = NULL; } for (i = 0; i < 3; ++i) { if (jac->ND_Pi[i]) { hm = (Mat_HYPRE *)(jac->ND_Pi[i]->data); PetscCallExternal(HYPRE_IJMatrixGetObject, hm->ij, (void **)(&nd_parcsr[i])); } else { nd_parcsr[i] = NULL; } } PetscCallExternal(HYPRE_ADSSetInterpolations, jac->hsolver, rt_parcsrfull, rt_parcsr[0], rt_parcsr[1], rt_parcsr[2], nd_parcsrfull, nd_parcsr[0], nd_parcsr[1], nd_parcsr[2]); } } PetscCallExternal(HYPRE_IJMatrixGetObject, hjac->ij, (void **)&hmat); PetscCallExternal(HYPRE_IJVectorGetObject, hjac->b->ij, (void **)&bv); PetscCallExternal(HYPRE_IJVectorGetObject, hjac->x->ij, (void **)&xv); PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF)); PetscCallExternal(jac->setup, jac->hsolver, hmat, bv, xv); PetscCall(PetscFPTrapPop()); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCApply_HYPRE(PC pc, Vec b, Vec x) { PC_HYPRE *jac = (PC_HYPRE *)pc->data; Mat_HYPRE *hjac = (Mat_HYPRE *)(jac->hpmat->data); HYPRE_ParCSRMatrix hmat; HYPRE_ParVector jbv, jxv; PetscFunctionBegin; PetscCall(PetscCitationsRegister(hypreCitation, &cite)); if (!jac->applyrichardson) PetscCall(VecSet(x, 0.0)); PetscCall(VecHYPRE_IJVectorPushVecRead(hjac->b, b)); if (jac->applyrichardson) PetscCall(VecHYPRE_IJVectorPushVec(hjac->x, x)); else PetscCall(VecHYPRE_IJVectorPushVecWrite(hjac->x, x)); PetscCallExternal(HYPRE_IJMatrixGetObject, hjac->ij, (void **)&hmat); PetscCallExternal(HYPRE_IJVectorGetObject, hjac->b->ij, (void **)&jbv); PetscCallExternal(HYPRE_IJVectorGetObject, hjac->x->ij, (void **)&jxv); PetscStackCallExternalVoid( "Hypre solve", do { HYPRE_Int hierr = (*jac->solve)(jac->hsolver, hmat, jbv, jxv); if (hierr) { PetscCheck(hierr == HYPRE_ERROR_CONV, PETSC_COMM_SELF, PETSC_ERR_LIB, "Error in HYPRE solver, error code %d", (int)hierr); HYPRE_ClearAllErrors(); } } while (0)); if (jac->setup == HYPRE_AMSSetup && jac->ams_beta_is_zero_part) PetscCallExternal(HYPRE_AMSProjectOutGradients, jac->hsolver, jxv); PetscCall(VecHYPRE_IJVectorPopVec(hjac->x)); PetscCall(VecHYPRE_IJVectorPopVec(hjac->b)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCMatApply_HYPRE_BoomerAMG(PC pc, Mat B, Mat X) { PC_HYPRE *jac = (PC_HYPRE *)pc->data; Mat_HYPRE *hjac = (Mat_HYPRE *)(jac->hpmat->data); hypre_ParCSRMatrix *par_matrix; HYPRE_ParVector hb, hx; const PetscScalar *b; PetscScalar *x; PetscInt m, N, lda; hypre_Vector *x_local; PetscMemType type; PetscFunctionBegin; PetscCall(PetscCitationsRegister(hypreCitation, &cite)); PetscCallExternal(HYPRE_IJMatrixGetObject, hjac->ij, (void **)&par_matrix); PetscCall(MatGetLocalSize(B, &m, NULL)); PetscCall(MatGetSize(B, NULL, &N)); PetscCallExternal(HYPRE_ParMultiVectorCreate, hypre_ParCSRMatrixComm(par_matrix), hypre_ParCSRMatrixGlobalNumRows(par_matrix), hypre_ParCSRMatrixRowStarts(par_matrix), N, &hb); PetscCallExternal(HYPRE_ParMultiVectorCreate, hypre_ParCSRMatrixComm(par_matrix), hypre_ParCSRMatrixGlobalNumRows(par_matrix), hypre_ParCSRMatrixRowStarts(par_matrix), N, &hx); PetscCall(MatZeroEntries(X)); PetscCall(MatDenseGetArrayReadAndMemType(B, &b, &type)); PetscCall(MatDenseGetLDA(B, &lda)); PetscCheck(lda == m, PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "Cannot use a LDA different than the number of local rows: % " PetscInt_FMT " != % " PetscInt_FMT, lda, m); PetscCall(MatDenseGetLDA(X, &lda)); PetscCheck(lda == m, PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "Cannot use a LDA different than the number of local rows: % " PetscInt_FMT " != % " PetscInt_FMT, lda, m); x_local = hypre_ParVectorLocalVector(hb); PetscCallExternal(hypre_SeqVectorSetDataOwner, x_local, 0); hypre_VectorData(x_local) = (HYPRE_Complex *)b; PetscCall(MatDenseGetArrayWriteAndMemType(X, &x, NULL)); x_local = hypre_ParVectorLocalVector(hx); PetscCallExternal(hypre_SeqVectorSetDataOwner, x_local, 0); hypre_VectorData(x_local) = (HYPRE_Complex *)x; PetscCallExternal(hypre_ParVectorInitialize_v2, hb, type == PETSC_MEMTYPE_HOST ? HYPRE_MEMORY_HOST : HYPRE_MEMORY_DEVICE); PetscCallExternal(hypre_ParVectorInitialize_v2, hx, type == PETSC_MEMTYPE_HOST ? HYPRE_MEMORY_HOST : HYPRE_MEMORY_DEVICE); PetscStackCallExternalVoid( "Hypre solve", do { HYPRE_Int hierr = (*jac->solve)(jac->hsolver, par_matrix, hb, hx); if (hierr) { PetscCheck(hierr == HYPRE_ERROR_CONV, PETSC_COMM_SELF, PETSC_ERR_LIB, "Error in HYPRE solver, error code %d", (int)hierr); HYPRE_ClearAllErrors(); } } while (0)); PetscCallExternal(HYPRE_ParVectorDestroy, hb); PetscCallExternal(HYPRE_ParVectorDestroy, hx); PetscCall(MatDenseRestoreArrayReadAndMemType(B, &b)); PetscCall(MatDenseRestoreArrayWriteAndMemType(X, &x)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCReset_HYPRE(PC pc) { PC_HYPRE *jac = (PC_HYPRE *)pc->data; PetscFunctionBegin; PetscCall(MatDestroy(&jac->hpmat)); PetscCall(MatDestroy(&jac->G)); PetscCall(MatDestroy(&jac->C)); PetscCall(MatDestroy(&jac->alpha_Poisson)); PetscCall(MatDestroy(&jac->beta_Poisson)); PetscCall(MatDestroy(&jac->RT_PiFull)); PetscCall(MatDestroy(&jac->RT_Pi[0])); PetscCall(MatDestroy(&jac->RT_Pi[1])); PetscCall(MatDestroy(&jac->RT_Pi[2])); PetscCall(MatDestroy(&jac->ND_PiFull)); PetscCall(MatDestroy(&jac->ND_Pi[0])); PetscCall(MatDestroy(&jac->ND_Pi[1])); PetscCall(MatDestroy(&jac->ND_Pi[2])); PetscCall(VecHYPRE_IJVectorDestroy(&jac->coords[0])); PetscCall(VecHYPRE_IJVectorDestroy(&jac->coords[1])); PetscCall(VecHYPRE_IJVectorDestroy(&jac->coords[2])); PetscCall(VecHYPRE_IJVectorDestroy(&jac->constants[0])); PetscCall(VecHYPRE_IJVectorDestroy(&jac->constants[1])); PetscCall(VecHYPRE_IJVectorDestroy(&jac->constants[2])); PetscCall(VecHYPRE_IJVectorDestroy(&jac->interior)); PetscCall(PCHYPREResetNearNullSpace_Private(pc)); jac->ams_beta_is_zero = PETSC_FALSE; jac->ams_beta_is_zero_part = PETSC_FALSE; jac->dim = 0; PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCDestroy_HYPRE(PC pc) { PC_HYPRE *jac = (PC_HYPRE *)pc->data; PetscFunctionBegin; PetscCall(PCReset_HYPRE(pc)); if (jac->destroy) PetscCallExternal(jac->destroy, jac->hsolver); PetscCall(PetscFree(jac->hypre_type)); #if PETSC_PKG_HYPRE_VERSION_GE(2, 23, 0) PetscCall(PetscFree(jac->spgemm_type)); #endif if (jac->comm_hypre != MPI_COMM_NULL) PetscCall(PetscCommRestoreComm(PetscObjectComm((PetscObject)pc), &jac->comm_hypre)); PetscCall(PetscFree(pc->data)); PetscCall(PetscObjectChangeTypeName((PetscObject)pc, 0)); PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPRESetType_C", NULL)); PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPREGetType_C", NULL)); PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPRESetDiscreteGradient_C", NULL)); PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPRESetDiscreteCurl_C", NULL)); PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPRESetInterpolations_C", NULL)); PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPRESetConstantEdgeVectors_C", NULL)); PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPRESetPoissonMatrix_C", NULL)); PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPRESetEdgeConstantVectors_C", NULL)); PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPREAMSSetInteriorNodes_C", NULL)); PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCGetInterpolations_C", NULL)); PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCGetCoarseOperators_C", NULL)); PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCMGGalerkinSetMatProductAlgorithm_C", NULL)); PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCMGGalerkinGetMatProductAlgorithm_C", NULL)); PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCSetCoordinates_C", NULL)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCSetFromOptions_HYPRE_Pilut(PC pc, PetscOptionItems *PetscOptionsObject) { PC_HYPRE *jac = (PC_HYPRE *)pc->data; PetscBool flag; PetscFunctionBegin; PetscOptionsHeadBegin(PetscOptionsObject, "HYPRE Pilut Options"); PetscCall(PetscOptionsInt("-pc_hypre_pilut_maxiter", "Number of iterations", "None", jac->maxiter, &jac->maxiter, &flag)); if (flag) PetscCallExternal(HYPRE_ParCSRPilutSetMaxIter, jac->hsolver, jac->maxiter); PetscCall(PetscOptionsReal("-pc_hypre_pilut_tol", "Drop tolerance", "None", jac->tol, &jac->tol, &flag)); if (flag) PetscCallExternal(HYPRE_ParCSRPilutSetDropTolerance, jac->hsolver, jac->tol); PetscCall(PetscOptionsInt("-pc_hypre_pilut_factorrowsize", "FactorRowSize", "None", jac->factorrowsize, &jac->factorrowsize, &flag)); if (flag) PetscCallExternal(HYPRE_ParCSRPilutSetFactorRowSize, jac->hsolver, jac->factorrowsize); PetscOptionsHeadEnd(); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCView_HYPRE_Pilut(PC pc, PetscViewer viewer) { PC_HYPRE *jac = (PC_HYPRE *)pc->data; PetscBool iascii; PetscFunctionBegin; PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii)); if (iascii) { PetscCall(PetscViewerASCIIPrintf(viewer, " HYPRE Pilut preconditioning\n")); if (jac->maxiter != PETSC_DEFAULT) { PetscCall(PetscViewerASCIIPrintf(viewer, " maximum number of iterations %" PetscInt_FMT "\n", jac->maxiter)); } else { PetscCall(PetscViewerASCIIPrintf(viewer, " default maximum number of iterations \n")); } if (jac->tol != PETSC_DEFAULT) { PetscCall(PetscViewerASCIIPrintf(viewer, " drop tolerance %g\n", (double)jac->tol)); } else { PetscCall(PetscViewerASCIIPrintf(viewer, " default drop tolerance \n")); } if (jac->factorrowsize != PETSC_DEFAULT) { PetscCall(PetscViewerASCIIPrintf(viewer, " factor row size %" PetscInt_FMT "\n", jac->factorrowsize)); } else { PetscCall(PetscViewerASCIIPrintf(viewer, " default factor row size \n")); } } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCSetFromOptions_HYPRE_Euclid(PC pc, PetscOptionItems *PetscOptionsObject) { PC_HYPRE *jac = (PC_HYPRE *)pc->data; PetscBool flag, eu_bj = jac->eu_bj ? PETSC_TRUE : PETSC_FALSE; PetscFunctionBegin; PetscOptionsHeadBegin(PetscOptionsObject, "HYPRE Euclid Options"); PetscCall(PetscOptionsInt("-pc_hypre_euclid_level", "Factorization levels", "None", jac->eu_level, &jac->eu_level, &flag)); if (flag) PetscCallExternal(HYPRE_EuclidSetLevel, jac->hsolver, jac->eu_level); PetscCall(PetscOptionsReal("-pc_hypre_euclid_droptolerance", "Drop tolerance for ILU(k) in Euclid", "None", jac->eu_droptolerance, &jac->eu_droptolerance, &flag)); if (flag) { PetscMPIInt size; PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)pc), &size)); PetscCheck(size == 1, PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "hypre's Euclid does not support a parallel drop tolerance"); PetscCallExternal(HYPRE_EuclidSetILUT, jac->hsolver, jac->eu_droptolerance); } PetscCall(PetscOptionsBool("-pc_hypre_euclid_bj", "Use Block Jacobi for ILU in Euclid", "None", eu_bj, &eu_bj, &flag)); if (flag) { jac->eu_bj = eu_bj ? 1 : 0; PetscCallExternal(HYPRE_EuclidSetBJ, jac->hsolver, jac->eu_bj); } PetscOptionsHeadEnd(); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCView_HYPRE_Euclid(PC pc, PetscViewer viewer) { PC_HYPRE *jac = (PC_HYPRE *)pc->data; PetscBool iascii; PetscFunctionBegin; PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii)); if (iascii) { PetscCall(PetscViewerASCIIPrintf(viewer, " HYPRE Euclid preconditioning\n")); if (jac->eu_level != PETSC_DEFAULT) { PetscCall(PetscViewerASCIIPrintf(viewer, " factorization levels %" PetscInt_FMT "\n", jac->eu_level)); } else { PetscCall(PetscViewerASCIIPrintf(viewer, " default factorization levels \n")); } PetscCall(PetscViewerASCIIPrintf(viewer, " drop tolerance %g\n", (double)jac->eu_droptolerance)); PetscCall(PetscViewerASCIIPrintf(viewer, " use Block-Jacobi? %" PetscInt_FMT "\n", jac->eu_bj)); } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCApplyTranspose_HYPRE_BoomerAMG(PC pc, Vec b, Vec x) { PC_HYPRE *jac = (PC_HYPRE *)pc->data; Mat_HYPRE *hjac = (Mat_HYPRE *)(jac->hpmat->data); HYPRE_ParCSRMatrix hmat; HYPRE_ParVector jbv, jxv; PetscFunctionBegin; PetscCall(PetscCitationsRegister(hypreCitation, &cite)); PetscCall(VecSet(x, 0.0)); PetscCall(VecHYPRE_IJVectorPushVecRead(hjac->x, b)); PetscCall(VecHYPRE_IJVectorPushVecWrite(hjac->b, x)); PetscCallExternal(HYPRE_IJMatrixGetObject, hjac->ij, (void **)&hmat); PetscCallExternal(HYPRE_IJVectorGetObject, hjac->b->ij, (void **)&jbv); PetscCallExternal(HYPRE_IJVectorGetObject, hjac->x->ij, (void **)&jxv); PetscStackCallExternalVoid( "Hypre Transpose solve", do { HYPRE_Int hierr = HYPRE_BoomerAMGSolveT(jac->hsolver, hmat, jbv, jxv); if (hierr) { /* error code of 1 in BoomerAMG merely means convergence not achieved */ PetscCheck(hierr == 1, PETSC_COMM_SELF, PETSC_ERR_LIB, "Error in HYPRE solver, error code %d", (int)hierr); HYPRE_ClearAllErrors(); } } while (0)); PetscCall(VecHYPRE_IJVectorPopVec(hjac->x)); PetscCall(VecHYPRE_IJVectorPopVec(hjac->b)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCMGGalerkinSetMatProductAlgorithm_HYPRE_BoomerAMG(PC pc, const char name[]) { PC_HYPRE *jac = (PC_HYPRE *)pc->data; PetscBool flag; #if PETSC_PKG_HYPRE_VERSION_GE(2, 23, 0) PetscFunctionBegin; if (jac->spgemm_type) { PetscCall(PetscStrcmp(jac->spgemm_type, name, &flag)); PetscCheck(flag, PetscObjectComm((PetscObject)pc), PETSC_ERR_ORDER, "Cannot reset the HYPRE SpGEMM (really we can)"); PetscFunctionReturn(PETSC_SUCCESS); } else { PetscCall(PetscStrallocpy(name, &jac->spgemm_type)); } PetscCall(PetscStrcmp("cusparse", jac->spgemm_type, &flag)); if (flag) { PetscCallExternal(HYPRE_SetSpGemmUseCusparse, 1); PetscFunctionReturn(PETSC_SUCCESS); } PetscCall(PetscStrcmp("hypre", jac->spgemm_type, &flag)); if (flag) { PetscCallExternal(HYPRE_SetSpGemmUseCusparse, 0); PetscFunctionReturn(PETSC_SUCCESS); } jac->spgemm_type = NULL; SETERRQ(PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_UNKNOWN_TYPE, "Unknown HYPRE SpGEMM type %s; Choices are cusparse, hypre", name); #endif } static PetscErrorCode PCMGGalerkinGetMatProductAlgorithm_HYPRE_BoomerAMG(PC pc, const char *spgemm[]) { PC_HYPRE *jac = (PC_HYPRE *)pc->data; PetscFunctionBegin; PetscValidHeaderSpecific(pc, PC_CLASSID, 1); #if PETSC_PKG_HYPRE_VERSION_GE(2, 23, 0) *spgemm = jac->spgemm_type; #endif PetscFunctionReturn(PETSC_SUCCESS); } static const char *HYPREBoomerAMGCycleType[] = {"", "V", "W"}; static const char *HYPREBoomerAMGCoarsenType[] = {"CLJP", "Ruge-Stueben", "", "modifiedRuge-Stueben", "", "", "Falgout", "", "PMIS", "", "HMIS"}; static const char *HYPREBoomerAMGMeasureType[] = {"local", "global"}; /* The following corresponds to HYPRE_BoomerAMGSetRelaxType which has many missing numbers in the enum */ static const char *HYPREBoomerAMGSmoothType[] = {"Schwarz-smoothers", "Pilut", "ParaSails", "Euclid"}; static const char *HYPREBoomerAMGRelaxType[] = {"Jacobi", "sequential-Gauss-Seidel", "seqboundary-Gauss-Seidel", "SOR/Jacobi", "backward-SOR/Jacobi", "" /* [5] hybrid chaotic Gauss-Seidel (works only with OpenMP) */, "symmetric-SOR/Jacobi", "" /* 7 */, "l1scaled-SOR/Jacobi", "Gaussian-elimination", "" /* 10 */, "" /* 11 */, "" /* 12 */, "l1-Gauss-Seidel" /* nonsymmetric */, "backward-l1-Gauss-Seidel" /* nonsymmetric */, "CG" /* non-stationary */, "Chebyshev", "FCF-Jacobi", "l1scaled-Jacobi"}; static const char *HYPREBoomerAMGInterpType[] = {"classical", "", "", "direct", "multipass", "multipass-wts", "ext+i", "ext+i-cc", "standard", "standard-wts", "block", "block-wtd", "FF", "FF1", "ext", "ad-wts", "ext-mm", "ext+i-mm", "ext+e-mm"}; static PetscErrorCode PCSetFromOptions_HYPRE_BoomerAMG(PC pc, PetscOptionItems *PetscOptionsObject) { PC_HYPRE *jac = (PC_HYPRE *)pc->data; PetscInt bs, n, indx, level; PetscBool flg, tmp_truth; double tmpdbl, twodbl[2]; const char *symtlist[] = {"nonsymmetric", "SPD", "nonsymmetric,SPD"}; const char *PCHYPRESpgemmTypes[] = {"cusparse", "hypre"}; PetscFunctionBegin; PetscOptionsHeadBegin(PetscOptionsObject, "HYPRE BoomerAMG Options"); PetscCall(PetscOptionsEList("-pc_hypre_boomeramg_cycle_type", "Cycle type", "None", HYPREBoomerAMGCycleType + 1, 2, HYPREBoomerAMGCycleType[jac->cycletype], &indx, &flg)); if (flg) { jac->cycletype = indx + 1; PetscCallExternal(HYPRE_BoomerAMGSetCycleType, jac->hsolver, jac->cycletype); } PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_max_levels", "Number of levels (of grids) allowed", "None", jac->maxlevels, &jac->maxlevels, &flg)); if (flg) { PetscCheck(jac->maxlevels >= 2, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_OUTOFRANGE, "Number of levels %" PetscInt_FMT " must be at least two", jac->maxlevels); PetscCallExternal(HYPRE_BoomerAMGSetMaxLevels, jac->hsolver, jac->maxlevels); } PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_max_iter", "Maximum iterations used PER hypre call", "None", jac->maxiter, &jac->maxiter, &flg)); if (flg) { PetscCheck(jac->maxiter >= 1, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_OUTOFRANGE, "Number of iterations %" PetscInt_FMT " must be at least one", jac->maxiter); PetscCallExternal(HYPRE_BoomerAMGSetMaxIter, jac->hsolver, jac->maxiter); } PetscCall(PetscOptionsReal("-pc_hypre_boomeramg_tol", "Convergence tolerance PER hypre call (0.0 = use a fixed number of iterations)", "None", jac->tol, &jac->tol, &flg)); if (flg) { PetscCheck(jac->tol >= 0.0, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_OUTOFRANGE, "Tolerance %g must be greater than or equal to zero", (double)jac->tol); PetscCallExternal(HYPRE_BoomerAMGSetTol, jac->hsolver, jac->tol); } bs = 1; if (pc->pmat) PetscCall(MatGetBlockSize(pc->pmat, &bs)); PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_numfunctions", "Number of functions", "HYPRE_BoomerAMGSetNumFunctions", bs, &bs, &flg)); if (flg) PetscCallExternal(HYPRE_BoomerAMGSetNumFunctions, jac->hsolver, bs); PetscCall(PetscOptionsReal("-pc_hypre_boomeramg_truncfactor", "Truncation factor for interpolation (0=no truncation)", "None", jac->truncfactor, &jac->truncfactor, &flg)); if (flg) { PetscCheck(jac->truncfactor >= 0.0, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_OUTOFRANGE, "Truncation factor %g must be great than or equal zero", (double)jac->truncfactor); PetscCallExternal(HYPRE_BoomerAMGSetTruncFactor, jac->hsolver, jac->truncfactor); } PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_P_max", "Max elements per row for interpolation operator (0=unlimited)", "None", jac->pmax, &jac->pmax, &flg)); if (flg) { PetscCheck(jac->pmax >= 0, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_OUTOFRANGE, "P_max %" PetscInt_FMT " must be greater than or equal to zero", jac->pmax); PetscCallExternal(HYPRE_BoomerAMGSetPMaxElmts, jac->hsolver, jac->pmax); } PetscCall(PetscOptionsRangeInt("-pc_hypre_boomeramg_agg_nl", "Number of levels of aggressive coarsening", "None", jac->agg_nl, &jac->agg_nl, &flg, 0, jac->maxlevels)); if (flg) PetscCallExternal(HYPRE_BoomerAMGSetAggNumLevels, jac->hsolver, jac->agg_nl); PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_agg_num_paths", "Number of paths for aggressive coarsening", "None", jac->agg_num_paths, &jac->agg_num_paths, &flg)); if (flg) { PetscCheck(jac->agg_num_paths >= 1, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_OUTOFRANGE, "Number of paths %" PetscInt_FMT " must be greater than or equal to 1", jac->agg_num_paths); PetscCallExternal(HYPRE_BoomerAMGSetNumPaths, jac->hsolver, jac->agg_num_paths); } PetscCall(PetscOptionsReal("-pc_hypre_boomeramg_strong_threshold", "Threshold for being strongly connected", "None", jac->strongthreshold, &jac->strongthreshold, &flg)); if (flg) { PetscCheck(jac->strongthreshold >= 0.0, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_OUTOFRANGE, "Strong threshold %g must be great than or equal zero", (double)jac->strongthreshold); PetscCallExternal(HYPRE_BoomerAMGSetStrongThreshold, jac->hsolver, jac->strongthreshold); } PetscCall(PetscOptionsReal("-pc_hypre_boomeramg_max_row_sum", "Maximum row sum", "None", jac->maxrowsum, &jac->maxrowsum, &flg)); if (flg) { PetscCheck(jac->maxrowsum >= 0.0, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_OUTOFRANGE, "Maximum row sum %g must be greater than zero", (double)jac->maxrowsum); PetscCheck(jac->maxrowsum <= 1.0, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_OUTOFRANGE, "Maximum row sum %g must be less than or equal one", (double)jac->maxrowsum); PetscCallExternal(HYPRE_BoomerAMGSetMaxRowSum, jac->hsolver, jac->maxrowsum); } /* Grid sweeps */ PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_grid_sweeps_all", "Number of sweeps for the up and down grid levels", "None", jac->gridsweeps[0], &indx, &flg)); if (flg) { PetscCallExternal(HYPRE_BoomerAMGSetNumSweeps, jac->hsolver, indx); /* modify the jac structure so we can view the updated options with PC_View */ jac->gridsweeps[0] = indx; jac->gridsweeps[1] = indx; /*defaults coarse to 1 */ jac->gridsweeps[2] = 1; } PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_nodal_coarsen", "Use a nodal based coarsening 1-6", "HYPRE_BoomerAMGSetNodal", jac->nodal_coarsening, &jac->nodal_coarsening, &flg)); if (flg) PetscCallExternal(HYPRE_BoomerAMGSetNodal, jac->hsolver, jac->nodal_coarsening); PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_nodal_coarsen_diag", "Diagonal in strength matrix for nodal based coarsening 0-2", "HYPRE_BoomerAMGSetNodalDiag", jac->nodal_coarsening_diag, &jac->nodal_coarsening_diag, &flg)); if (flg) PetscCallExternal(HYPRE_BoomerAMGSetNodalDiag, jac->hsolver, jac->nodal_coarsening_diag); PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_vec_interp_variant", "Variant of algorithm 1-3", "HYPRE_BoomerAMGSetInterpVecVariant", jac->vec_interp_variant, &jac->vec_interp_variant, &flg)); if (flg) PetscCallExternal(HYPRE_BoomerAMGSetInterpVecVariant, jac->hsolver, jac->vec_interp_variant); PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_vec_interp_qmax", "Max elements per row for each Q", "HYPRE_BoomerAMGSetInterpVecQMax", jac->vec_interp_qmax, &jac->vec_interp_qmax, &flg)); if (flg) PetscCallExternal(HYPRE_BoomerAMGSetInterpVecQMax, jac->hsolver, jac->vec_interp_qmax); PetscCall(PetscOptionsBool("-pc_hypre_boomeramg_vec_interp_smooth", "Whether to smooth the interpolation vectors", "HYPRE_BoomerAMGSetSmoothInterpVectors", jac->vec_interp_smooth, &jac->vec_interp_smooth, &flg)); if (flg) PetscCallExternal(HYPRE_BoomerAMGSetSmoothInterpVectors, jac->hsolver, jac->vec_interp_smooth); PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_interp_refine", "Preprocess the interpolation matrix through iterative weight refinement", "HYPRE_BoomerAMGSetInterpRefine", jac->interp_refine, &jac->interp_refine, &flg)); if (flg) PetscCallExternal(HYPRE_BoomerAMGSetInterpRefine, jac->hsolver, jac->interp_refine); PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_grid_sweeps_down", "Number of sweeps for the down cycles", "None", jac->gridsweeps[0], &indx, &flg)); if (flg) { PetscCallExternal(HYPRE_BoomerAMGSetCycleNumSweeps, jac->hsolver, indx, 1); jac->gridsweeps[0] = indx; } PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_grid_sweeps_up", "Number of sweeps for the up cycles", "None", jac->gridsweeps[1], &indx, &flg)); if (flg) { PetscCallExternal(HYPRE_BoomerAMGSetCycleNumSweeps, jac->hsolver, indx, 2); jac->gridsweeps[1] = indx; } PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_grid_sweeps_coarse", "Number of sweeps for the coarse level", "None", jac->gridsweeps[2], &indx, &flg)); if (flg) { PetscCallExternal(HYPRE_BoomerAMGSetCycleNumSweeps, jac->hsolver, indx, 3); jac->gridsweeps[2] = indx; } /* Smooth type */ PetscCall(PetscOptionsEList("-pc_hypre_boomeramg_smooth_type", "Enable more complex smoothers", "None", HYPREBoomerAMGSmoothType, PETSC_STATIC_ARRAY_LENGTH(HYPREBoomerAMGSmoothType), HYPREBoomerAMGSmoothType[0], &indx, &flg)); if (flg) { jac->smoothtype = indx; PetscCallExternal(HYPRE_BoomerAMGSetSmoothType, jac->hsolver, indx + 6); jac->smoothnumlevels = 25; PetscCallExternal(HYPRE_BoomerAMGSetSmoothNumLevels, jac->hsolver, 25); } /* Number of smoothing levels */ PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_smooth_num_levels", "Number of levels on which more complex smoothers are used", "None", 25, &indx, &flg)); if (flg && (jac->smoothtype != -1)) { jac->smoothnumlevels = indx; PetscCallExternal(HYPRE_BoomerAMGSetSmoothNumLevels, jac->hsolver, indx); } /* Number of levels for ILU(k) for Euclid */ PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_eu_level", "Number of levels for ILU(k) in Euclid smoother", "None", 0, &indx, &flg)); if (flg && (jac->smoothtype == 3)) { jac->eu_level = indx; PetscCallExternal(HYPRE_BoomerAMGSetEuLevel, jac->hsolver, indx); } /* Filter for ILU(k) for Euclid */ double droptolerance; PetscCall(PetscOptionsReal("-pc_hypre_boomeramg_eu_droptolerance", "Drop tolerance for ILU(k) in Euclid smoother", "None", 0, &droptolerance, &flg)); if (flg && (jac->smoothtype == 3)) { jac->eu_droptolerance = droptolerance; PetscCallExternal(HYPRE_BoomerAMGSetEuLevel, jac->hsolver, droptolerance); } /* Use Block Jacobi ILUT for Euclid */ PetscCall(PetscOptionsBool("-pc_hypre_boomeramg_eu_bj", "Use Block Jacobi for ILU in Euclid smoother?", "None", PETSC_FALSE, &tmp_truth, &flg)); if (flg && (jac->smoothtype == 3)) { jac->eu_bj = tmp_truth; PetscCallExternal(HYPRE_BoomerAMGSetEuBJ, jac->hsolver, jac->eu_bj); } /* Relax type */ PetscCall(PetscOptionsEList("-pc_hypre_boomeramg_relax_type_all", "Relax type for the up and down cycles", "None", HYPREBoomerAMGRelaxType, PETSC_STATIC_ARRAY_LENGTH(HYPREBoomerAMGRelaxType), HYPREBoomerAMGRelaxType[6], &indx, &flg)); if (flg) { jac->relaxtype[0] = jac->relaxtype[1] = indx; PetscCallExternal(HYPRE_BoomerAMGSetRelaxType, jac->hsolver, indx); /* by default, coarse type set to 9 */ jac->relaxtype[2] = 9; PetscCallExternal(HYPRE_BoomerAMGSetCycleRelaxType, jac->hsolver, 9, 3); } PetscCall(PetscOptionsEList("-pc_hypre_boomeramg_relax_type_down", "Relax type for the down cycles", "None", HYPREBoomerAMGRelaxType, PETSC_STATIC_ARRAY_LENGTH(HYPREBoomerAMGRelaxType), HYPREBoomerAMGRelaxType[6], &indx, &flg)); if (flg) { jac->relaxtype[0] = indx; PetscCallExternal(HYPRE_BoomerAMGSetCycleRelaxType, jac->hsolver, indx, 1); } PetscCall(PetscOptionsEList("-pc_hypre_boomeramg_relax_type_up", "Relax type for the up cycles", "None", HYPREBoomerAMGRelaxType, PETSC_STATIC_ARRAY_LENGTH(HYPREBoomerAMGRelaxType), HYPREBoomerAMGRelaxType[6], &indx, &flg)); if (flg) { jac->relaxtype[1] = indx; PetscCallExternal(HYPRE_BoomerAMGSetCycleRelaxType, jac->hsolver, indx, 2); } PetscCall(PetscOptionsEList("-pc_hypre_boomeramg_relax_type_coarse", "Relax type on coarse grid", "None", HYPREBoomerAMGRelaxType, PETSC_STATIC_ARRAY_LENGTH(HYPREBoomerAMGRelaxType), HYPREBoomerAMGRelaxType[9], &indx, &flg)); if (flg) { jac->relaxtype[2] = indx; PetscCallExternal(HYPRE_BoomerAMGSetCycleRelaxType, jac->hsolver, indx, 3); } /* Relaxation Weight */ PetscCall(PetscOptionsReal("-pc_hypre_boomeramg_relax_weight_all", "Relaxation weight for all levels (0 = hypre estimates, -k = determined with k CG steps)", "None", jac->relaxweight, &tmpdbl, &flg)); if (flg) { PetscCallExternal(HYPRE_BoomerAMGSetRelaxWt, jac->hsolver, tmpdbl); jac->relaxweight = tmpdbl; } n = 2; twodbl[0] = twodbl[1] = 1.0; PetscCall(PetscOptionsRealArray("-pc_hypre_boomeramg_relax_weight_level", "Set the relaxation weight for a particular level (weight,level)", "None", twodbl, &n, &flg)); if (flg) { PetscCheck(n == 2, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_OUTOFRANGE, "Relax weight level: you must provide 2 values separated by a comma (and no space), you provided %" PetscInt_FMT, n); indx = (int)PetscAbsReal(twodbl[1]); PetscCallExternal(HYPRE_BoomerAMGSetLevelRelaxWt, jac->hsolver, twodbl[0], indx); } /* Outer relaxation Weight */ PetscCall(PetscOptionsReal("-pc_hypre_boomeramg_outer_relax_weight_all", "Outer relaxation weight for all levels (-k = determined with k CG steps)", "None", jac->outerrelaxweight, &tmpdbl, &flg)); if (flg) { PetscCallExternal(HYPRE_BoomerAMGSetOuterWt, jac->hsolver, tmpdbl); jac->outerrelaxweight = tmpdbl; } n = 2; twodbl[0] = twodbl[1] = 1.0; PetscCall(PetscOptionsRealArray("-pc_hypre_boomeramg_outer_relax_weight_level", "Set the outer relaxation weight for a particular level (weight,level)", "None", twodbl, &n, &flg)); if (flg) { PetscCheck(n == 2, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_OUTOFRANGE, "Relax weight outer level: You must provide 2 values separated by a comma (and no space), you provided %" PetscInt_FMT, n); indx = (int)PetscAbsReal(twodbl[1]); PetscCallExternal(HYPRE_BoomerAMGSetLevelOuterWt, jac->hsolver, twodbl[0], indx); } /* the Relax Order */ PetscCall(PetscOptionsBool("-pc_hypre_boomeramg_no_CF", "Do not use CF-relaxation", "None", PETSC_FALSE, &tmp_truth, &flg)); if (flg && tmp_truth) { jac->relaxorder = 0; PetscCallExternal(HYPRE_BoomerAMGSetRelaxOrder, jac->hsolver, jac->relaxorder); } PetscCall(PetscOptionsEList("-pc_hypre_boomeramg_measure_type", "Measure type", "None", HYPREBoomerAMGMeasureType, PETSC_STATIC_ARRAY_LENGTH(HYPREBoomerAMGMeasureType), HYPREBoomerAMGMeasureType[0], &indx, &flg)); if (flg) { jac->measuretype = indx; PetscCallExternal(HYPRE_BoomerAMGSetMeasureType, jac->hsolver, jac->measuretype); } /* update list length 3/07 */ PetscCall(PetscOptionsEList("-pc_hypre_boomeramg_coarsen_type", "Coarsen type", "None", HYPREBoomerAMGCoarsenType, PETSC_STATIC_ARRAY_LENGTH(HYPREBoomerAMGCoarsenType), HYPREBoomerAMGCoarsenType[6], &indx, &flg)); if (flg) { jac->coarsentype = indx; PetscCallExternal(HYPRE_BoomerAMGSetCoarsenType, jac->hsolver, jac->coarsentype); } PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_max_coarse_size", "Maximum size of coarsest grid", "None", jac->maxc, &jac->maxc, &flg)); if (flg) PetscCallExternal(HYPRE_BoomerAMGSetMaxCoarseSize, jac->hsolver, jac->maxc); PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_min_coarse_size", "Minimum size of coarsest grid", "None", jac->minc, &jac->minc, &flg)); if (flg) PetscCallExternal(HYPRE_BoomerAMGSetMinCoarseSize, jac->hsolver, jac->minc); #if PETSC_PKG_HYPRE_VERSION_GE(2, 23, 0) // global parameter but is closely associated with BoomerAMG PetscCall(PetscOptionsEList("-pc_mg_galerkin_mat_product_algorithm", "Type of SpGEMM to use in hypre (only for now)", "PCMGGalerkinSetMatProductAlgorithm", PCHYPRESpgemmTypes, PETSC_STATIC_ARRAY_LENGTH(PCHYPRESpgemmTypes), PCHYPRESpgemmTypes[0], &indx, &flg)); #if defined(PETSC_HAVE_HYPRE_DEVICE) if (!flg) indx = 0; PetscCall(PCMGGalerkinSetMatProductAlgorithm_HYPRE_BoomerAMG(pc, PCHYPRESpgemmTypes[indx])); #else PetscCall(PCMGGalerkinSetMatProductAlgorithm_HYPRE_BoomerAMG(pc, "hypre")); #endif #endif /* AIR */ #if PETSC_PKG_HYPRE_VERSION_GE(2, 18, 0) PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_restriction_type", "Type of AIR method (distance 1 or 2, 0 means no AIR)", "None", jac->Rtype, &jac->Rtype, NULL)); PetscCallExternal(HYPRE_BoomerAMGSetRestriction, jac->hsolver, jac->Rtype); if (jac->Rtype) { HYPRE_Int **grid_relax_points = hypre_TAlloc(HYPRE_Int *, 4, HYPRE_MEMORY_HOST); char *prerelax[256]; char *postrelax[256]; char stringF[2] = "F", stringC[2] = "C", stringA[2] = "A"; PetscInt ns_down = 256, ns_up = 256; PetscBool matchF, matchC, matchA; jac->interptype = 100; /* no way we can pass this with strings... Set it as default as in MFEM, then users can still customize it back to a different one */ PetscCall(PetscOptionsReal("-pc_hypre_boomeramg_strongthresholdR", "Threshold for R", "None", jac->Rstrongthreshold, &jac->Rstrongthreshold, NULL)); PetscCallExternal(HYPRE_BoomerAMGSetStrongThresholdR, jac->hsolver, jac->Rstrongthreshold); PetscCall(PetscOptionsReal("-pc_hypre_boomeramg_filterthresholdR", "Filter threshold for R", "None", jac->Rfilterthreshold, &jac->Rfilterthreshold, NULL)); PetscCallExternal(HYPRE_BoomerAMGSetFilterThresholdR, jac->hsolver, jac->Rfilterthreshold); PetscCall(PetscOptionsReal("-pc_hypre_boomeramg_Adroptol", "Defines the drop tolerance for the A-matrices from the 2nd level of AMG", "None", jac->Adroptol, &jac->Adroptol, NULL)); PetscCallExternal(HYPRE_BoomerAMGSetADropTol, jac->hsolver, jac->Adroptol); PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_Adroptype", "Drops the entries that are not on the diagonal and smaller than its row norm: type 1: 1-norm, 2: 2-norm, -1: infinity norm", "None", jac->Adroptype, &jac->Adroptype, NULL)); PetscCallExternal(HYPRE_BoomerAMGSetADropType, jac->hsolver, jac->Adroptype); PetscCall(PetscOptionsStringArray("-pc_hypre_boomeramg_prerelax", "Defines prerelax scheme", "None", prerelax, &ns_down, NULL)); PetscCall(PetscOptionsStringArray("-pc_hypre_boomeramg_postrelax", "Defines postrelax scheme", "None", postrelax, &ns_up, NULL)); PetscCheck(ns_down == jac->gridsweeps[0], PetscObjectComm((PetscObject)jac), PETSC_ERR_ARG_SIZ, "The number of arguments passed to -pc_hypre_boomeramg_prerelax must match the number passed to -pc_hypre_bomeramg_grid_sweeps_down"); PetscCheck(ns_up == jac->gridsweeps[1], PetscObjectComm((PetscObject)jac), PETSC_ERR_ARG_SIZ, "The number of arguments passed to -pc_hypre_boomeramg_postrelax must match the number passed to -pc_hypre_bomeramg_grid_sweeps_up"); grid_relax_points[0] = NULL; grid_relax_points[1] = hypre_TAlloc(HYPRE_Int, ns_down, HYPRE_MEMORY_HOST); grid_relax_points[2] = hypre_TAlloc(HYPRE_Int, ns_up, HYPRE_MEMORY_HOST); grid_relax_points[3] = hypre_TAlloc(HYPRE_Int, jac->gridsweeps[2], HYPRE_MEMORY_HOST); grid_relax_points[3][0] = 0; // set down relax scheme for (PetscInt i = 0; i < ns_down; i++) { PetscCall(PetscStrcasecmp(prerelax[i], stringF, &matchF)); PetscCall(PetscStrcasecmp(prerelax[i], stringC, &matchC)); PetscCall(PetscStrcasecmp(prerelax[i], stringA, &matchA)); PetscCheck(matchF || matchC || matchA, PetscObjectComm((PetscObject)jac), PETSC_ERR_ARG_WRONG, "Valid argument options for -pc_hypre_boomeramg_prerelax are C, F, and A"); if (matchF) grid_relax_points[1][i] = -1; else if (matchC) grid_relax_points[1][i] = 1; else if (matchA) grid_relax_points[1][i] = 0; } // set up relax scheme for (PetscInt i = 0; i < ns_up; i++) { PetscCall(PetscStrcasecmp(postrelax[i], stringF, &matchF)); PetscCall(PetscStrcasecmp(postrelax[i], stringC, &matchC)); PetscCall(PetscStrcasecmp(postrelax[i], stringA, &matchA)); PetscCheck(matchF || matchC || matchA, PetscObjectComm((PetscObject)jac), PETSC_ERR_ARG_WRONG, "Valid argument options for -pc_hypre_boomeramg_postrelax are C, F, and A"); if (matchF) grid_relax_points[2][i] = -1; else if (matchC) grid_relax_points[2][i] = 1; else if (matchA) grid_relax_points[2][i] = 0; } // set coarse relax scheme for (PetscInt i = 0; i < jac->gridsweeps[2]; i++) grid_relax_points[3][i] = 0; // Pass relax schemes to hypre PetscCallExternal(HYPRE_BoomerAMGSetGridRelaxPoints, jac->hsolver, grid_relax_points); // cleanup memory for (PetscInt i = 0; i < ns_down; i++) PetscCall(PetscFree(prerelax[i])); for (PetscInt i = 0; i < ns_up; i++) PetscCall(PetscFree(postrelax[i])); } #endif #if PETSC_PKG_HYPRE_VERSION_LE(9, 9, 9) PetscCheck(!jac->Rtype || !jac->agg_nl, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_INCOMP, "-pc_hypre_boomeramg_restriction_type (%" PetscInt_FMT ") and -pc_hypre_boomeramg_agg_nl (%" PetscInt_FMT ")", jac->Rtype, jac->agg_nl); #endif /* new 3/07 */ PetscCall(PetscOptionsEList("-pc_hypre_boomeramg_interp_type", "Interpolation type", "None", HYPREBoomerAMGInterpType, PETSC_STATIC_ARRAY_LENGTH(HYPREBoomerAMGInterpType), HYPREBoomerAMGInterpType[0], &indx, &flg)); if (flg || jac->Rtype) { if (flg) jac->interptype = indx; PetscCallExternal(HYPRE_BoomerAMGSetInterpType, jac->hsolver, jac->interptype); } PetscCall(PetscOptionsName("-pc_hypre_boomeramg_print_statistics", "Print statistics", "None", &flg)); if (flg) { level = 3; PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_print_statistics", "Print statistics", "None", level, &level, NULL)); jac->printstatistics = PETSC_TRUE; PetscCallExternal(HYPRE_BoomerAMGSetPrintLevel, jac->hsolver, level); } PetscCall(PetscOptionsName("-pc_hypre_boomeramg_print_debug", "Print debug information", "None", &flg)); if (flg) { level = 3; PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_print_debug", "Print debug information", "None", level, &level, NULL)); jac->printstatistics = PETSC_TRUE; PetscCallExternal(HYPRE_BoomerAMGSetDebugFlag, jac->hsolver, level); } PetscCall(PetscOptionsBool("-pc_hypre_boomeramg_nodal_relaxation", "Nodal relaxation via Schwarz", "None", PETSC_FALSE, &tmp_truth, &flg)); if (flg && tmp_truth) { PetscInt tmp_int; PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_nodal_relaxation", "Nodal relaxation via Schwarz", "None", jac->nodal_relax_levels, &tmp_int, &flg)); if (flg) jac->nodal_relax_levels = tmp_int; PetscCallExternal(HYPRE_BoomerAMGSetSmoothType, jac->hsolver, 6); PetscCallExternal(HYPRE_BoomerAMGSetDomainType, jac->hsolver, 1); PetscCallExternal(HYPRE_BoomerAMGSetOverlap, jac->hsolver, 0); PetscCallExternal(HYPRE_BoomerAMGSetSmoothNumLevels, jac->hsolver, jac->nodal_relax_levels); } PetscCall(PetscOptionsBool("-pc_hypre_boomeramg_keeptranspose", "Avoid transpose matvecs in preconditioner application", "None", jac->keeptranspose, &jac->keeptranspose, NULL)); PetscCallExternal(HYPRE_BoomerAMGSetKeepTranspose, jac->hsolver, jac->keeptranspose ? 1 : 0); /* options for ParaSails solvers */ PetscCall(PetscOptionsEList("-pc_hypre_boomeramg_parasails_sym", "Symmetry of matrix and preconditioner", "None", symtlist, PETSC_STATIC_ARRAY_LENGTH(symtlist), symtlist[0], &indx, &flg)); if (flg) { jac->symt = indx; PetscCallExternal(HYPRE_BoomerAMGSetSym, jac->hsolver, jac->symt); } PetscOptionsHeadEnd(); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCApplyRichardson_HYPRE_BoomerAMG(PC pc, Vec b, Vec y, Vec w, PetscReal rtol, PetscReal abstol, PetscReal dtol, PetscInt its, PetscBool guesszero, PetscInt *outits, PCRichardsonConvergedReason *reason) { PC_HYPRE *jac = (PC_HYPRE *)pc->data; HYPRE_Int oits; PetscFunctionBegin; PetscCall(PetscCitationsRegister(hypreCitation, &cite)); PetscCallExternal(HYPRE_BoomerAMGSetMaxIter, jac->hsolver, its * jac->maxiter); PetscCallExternal(HYPRE_BoomerAMGSetTol, jac->hsolver, rtol); jac->applyrichardson = PETSC_TRUE; PetscCall(PCApply_HYPRE(pc, b, y)); jac->applyrichardson = PETSC_FALSE; PetscCallExternal(HYPRE_BoomerAMGGetNumIterations, jac->hsolver, &oits); *outits = oits; if (oits == its) *reason = PCRICHARDSON_CONVERGED_ITS; else *reason = PCRICHARDSON_CONVERGED_RTOL; PetscCallExternal(HYPRE_BoomerAMGSetTol, jac->hsolver, jac->tol); PetscCallExternal(HYPRE_BoomerAMGSetMaxIter, jac->hsolver, jac->maxiter); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCView_HYPRE_BoomerAMG(PC pc, PetscViewer viewer) { PC_HYPRE *jac = (PC_HYPRE *)pc->data; PetscBool iascii; PetscFunctionBegin; PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii)); if (iascii) { PetscCall(PetscViewerASCIIPrintf(viewer, " HYPRE BoomerAMG preconditioning\n")); PetscCall(PetscViewerASCIIPrintf(viewer, " Cycle type %s\n", HYPREBoomerAMGCycleType[jac->cycletype])); PetscCall(PetscViewerASCIIPrintf(viewer, " Maximum number of levels %" PetscInt_FMT "\n", jac->maxlevels)); PetscCall(PetscViewerASCIIPrintf(viewer, " Maximum number of iterations PER hypre call %" PetscInt_FMT "\n", jac->maxiter)); PetscCall(PetscViewerASCIIPrintf(viewer, " Convergence tolerance PER hypre call %g\n", (double)jac->tol)); PetscCall(PetscViewerASCIIPrintf(viewer, " Threshold for strong coupling %g\n", (double)jac->strongthreshold)); PetscCall(PetscViewerASCIIPrintf(viewer, " Interpolation truncation factor %g\n", (double)jac->truncfactor)); PetscCall(PetscViewerASCIIPrintf(viewer, " Interpolation: max elements per row %" PetscInt_FMT "\n", jac->pmax)); if (jac->interp_refine) PetscCall(PetscViewerASCIIPrintf(viewer, " Interpolation: number of steps of weighted refinement %" PetscInt_FMT "\n", jac->interp_refine)); PetscCall(PetscViewerASCIIPrintf(viewer, " Number of levels of aggressive coarsening %" PetscInt_FMT "\n", jac->agg_nl)); PetscCall(PetscViewerASCIIPrintf(viewer, " Number of paths for aggressive coarsening %" PetscInt_FMT "\n", jac->agg_num_paths)); PetscCall(PetscViewerASCIIPrintf(viewer, " Maximum row sums %g\n", (double)jac->maxrowsum)); PetscCall(PetscViewerASCIIPrintf(viewer, " Sweeps down %" PetscInt_FMT "\n", jac->gridsweeps[0])); PetscCall(PetscViewerASCIIPrintf(viewer, " Sweeps up %" PetscInt_FMT "\n", jac->gridsweeps[1])); PetscCall(PetscViewerASCIIPrintf(viewer, " Sweeps on coarse %" PetscInt_FMT "\n", jac->gridsweeps[2])); PetscCall(PetscViewerASCIIPrintf(viewer, " Relax down %s\n", HYPREBoomerAMGRelaxType[jac->relaxtype[0]])); PetscCall(PetscViewerASCIIPrintf(viewer, " Relax up %s\n", HYPREBoomerAMGRelaxType[jac->relaxtype[1]])); PetscCall(PetscViewerASCIIPrintf(viewer, " Relax on coarse %s\n", HYPREBoomerAMGRelaxType[jac->relaxtype[2]])); PetscCall(PetscViewerASCIIPrintf(viewer, " Relax weight (all) %g\n", (double)jac->relaxweight)); PetscCall(PetscViewerASCIIPrintf(viewer, " Outer relax weight (all) %g\n", (double)jac->outerrelaxweight)); PetscCall(PetscViewerASCIIPrintf(viewer, " Maximum size of coarsest grid %" PetscInt_FMT "\n", jac->maxc)); PetscCall(PetscViewerASCIIPrintf(viewer, " Minimum size of coarsest grid %" PetscInt_FMT "\n", jac->minc)); if (jac->relaxorder) { PetscCall(PetscViewerASCIIPrintf(viewer, " Using CF-relaxation\n")); } else { PetscCall(PetscViewerASCIIPrintf(viewer, " Not using CF-relaxation\n")); } if (jac->smoothtype != -1) { PetscCall(PetscViewerASCIIPrintf(viewer, " Smooth type %s\n", HYPREBoomerAMGSmoothType[jac->smoothtype])); PetscCall(PetscViewerASCIIPrintf(viewer, " Smooth num levels %" PetscInt_FMT "\n", jac->smoothnumlevels)); } else { PetscCall(PetscViewerASCIIPrintf(viewer, " Not using more complex smoothers.\n")); } if (jac->smoothtype == 3) { PetscCall(PetscViewerASCIIPrintf(viewer, " Euclid ILU(k) levels %" PetscInt_FMT "\n", jac->eu_level)); PetscCall(PetscViewerASCIIPrintf(viewer, " Euclid ILU(k) drop tolerance %g\n", (double)jac->eu_droptolerance)); PetscCall(PetscViewerASCIIPrintf(viewer, " Euclid ILU use Block-Jacobi? %" PetscInt_FMT "\n", jac->eu_bj)); } PetscCall(PetscViewerASCIIPrintf(viewer, " Measure type %s\n", HYPREBoomerAMGMeasureType[jac->measuretype])); PetscCall(PetscViewerASCIIPrintf(viewer, " Coarsen type %s\n", HYPREBoomerAMGCoarsenType[jac->coarsentype])); PetscCall(PetscViewerASCIIPrintf(viewer, " Interpolation type %s\n", jac->interptype != 100 ? HYPREBoomerAMGInterpType[jac->interptype] : "1pt")); if (jac->nodal_coarsening) PetscCall(PetscViewerASCIIPrintf(viewer, " Using nodal coarsening with HYPRE_BOOMERAMGSetNodal() %" PetscInt_FMT "\n", jac->nodal_coarsening)); if (jac->vec_interp_variant) { PetscCall(PetscViewerASCIIPrintf(viewer, " HYPRE_BoomerAMGSetInterpVecVariant() %" PetscInt_FMT "\n", jac->vec_interp_variant)); PetscCall(PetscViewerASCIIPrintf(viewer, " HYPRE_BoomerAMGSetInterpVecQMax() %" PetscInt_FMT "\n", jac->vec_interp_qmax)); PetscCall(PetscViewerASCIIPrintf(viewer, " HYPRE_BoomerAMGSetSmoothInterpVectors() %d\n", jac->vec_interp_smooth)); } if (jac->nodal_relax) PetscCall(PetscViewerASCIIPrintf(viewer, " Using nodal relaxation via Schwarz smoothing on levels %" PetscInt_FMT "\n", jac->nodal_relax_levels)); #if PETSC_PKG_HYPRE_VERSION_GE(2, 23, 0) PetscCall(PetscViewerASCIIPrintf(viewer, " SpGEMM type %s\n", jac->spgemm_type)); #else PetscCall(PetscViewerASCIIPrintf(viewer, " SpGEMM type %s\n", "hypre")); #endif /* AIR */ if (jac->Rtype) { PetscCall(PetscViewerASCIIPrintf(viewer, " Using approximate ideal restriction type %" PetscInt_FMT "\n", jac->Rtype)); PetscCall(PetscViewerASCIIPrintf(viewer, " Threshold for R %g\n", (double)jac->Rstrongthreshold)); PetscCall(PetscViewerASCIIPrintf(viewer, " Filter for R %g\n", (double)jac->Rfilterthreshold)); PetscCall(PetscViewerASCIIPrintf(viewer, " A drop tolerance %g\n", (double)jac->Adroptol)); PetscCall(PetscViewerASCIIPrintf(viewer, " A drop type %" PetscInt_FMT "\n", jac->Adroptype)); } } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCSetFromOptions_HYPRE_ParaSails(PC pc, PetscOptionItems *PetscOptionsObject) { PC_HYPRE *jac = (PC_HYPRE *)pc->data; PetscInt indx; PetscBool flag; const char *symtlist[] = {"nonsymmetric", "SPD", "nonsymmetric,SPD"}; PetscFunctionBegin; PetscOptionsHeadBegin(PetscOptionsObject, "HYPRE ParaSails Options"); PetscCall(PetscOptionsInt("-pc_hypre_parasails_nlevels", "Number of number of levels", "None", jac->nlevels, &jac->nlevels, 0)); PetscCall(PetscOptionsReal("-pc_hypre_parasails_thresh", "Threshold", "None", jac->threshold, &jac->threshold, &flag)); if (flag) PetscCallExternal(HYPRE_ParaSailsSetParams, jac->hsolver, jac->threshold, jac->nlevels); PetscCall(PetscOptionsReal("-pc_hypre_parasails_filter", "filter", "None", jac->filter, &jac->filter, &flag)); if (flag) PetscCallExternal(HYPRE_ParaSailsSetFilter, jac->hsolver, jac->filter); PetscCall(PetscOptionsReal("-pc_hypre_parasails_loadbal", "Load balance", "None", jac->loadbal, &jac->loadbal, &flag)); if (flag) PetscCallExternal(HYPRE_ParaSailsSetLoadbal, jac->hsolver, jac->loadbal); PetscCall(PetscOptionsBool("-pc_hypre_parasails_logging", "Print info to screen", "None", (PetscBool)jac->logging, (PetscBool *)&jac->logging, &flag)); if (flag) PetscCallExternal(HYPRE_ParaSailsSetLogging, jac->hsolver, jac->logging); PetscCall(PetscOptionsBool("-pc_hypre_parasails_reuse", "Reuse nonzero pattern in preconditioner", "None", (PetscBool)jac->ruse, (PetscBool *)&jac->ruse, &flag)); if (flag) PetscCallExternal(HYPRE_ParaSailsSetReuse, jac->hsolver, jac->ruse); PetscCall(PetscOptionsEList("-pc_hypre_parasails_sym", "Symmetry of matrix and preconditioner", "None", symtlist, PETSC_STATIC_ARRAY_LENGTH(symtlist), symtlist[0], &indx, &flag)); if (flag) { jac->symt = indx; PetscCallExternal(HYPRE_ParaSailsSetSym, jac->hsolver, jac->symt); } PetscOptionsHeadEnd(); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCView_HYPRE_ParaSails(PC pc, PetscViewer viewer) { PC_HYPRE *jac = (PC_HYPRE *)pc->data; PetscBool iascii; const char *symt = 0; PetscFunctionBegin; PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii)); if (iascii) { PetscCall(PetscViewerASCIIPrintf(viewer, " HYPRE ParaSails preconditioning\n")); PetscCall(PetscViewerASCIIPrintf(viewer, " nlevels %" PetscInt_FMT "\n", jac->nlevels)); PetscCall(PetscViewerASCIIPrintf(viewer, " threshold %g\n", (double)jac->threshold)); PetscCall(PetscViewerASCIIPrintf(viewer, " filter %g\n", (double)jac->filter)); PetscCall(PetscViewerASCIIPrintf(viewer, " load balance %g\n", (double)jac->loadbal)); PetscCall(PetscViewerASCIIPrintf(viewer, " reuse nonzero structure %s\n", PetscBools[jac->ruse])); PetscCall(PetscViewerASCIIPrintf(viewer, " print info to screen %s\n", PetscBools[jac->logging])); if (!jac->symt) symt = "nonsymmetric matrix and preconditioner"; else if (jac->symt == 1) symt = "SPD matrix and preconditioner"; else if (jac->symt == 2) symt = "nonsymmetric matrix but SPD preconditioner"; else SETERRQ(PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_WRONG, "Unknown HYPRE ParaSails symmetric option %" PetscInt_FMT, jac->symt); PetscCall(PetscViewerASCIIPrintf(viewer, " %s\n", symt)); } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCSetFromOptions_HYPRE_AMS(PC pc, PetscOptionItems *PetscOptionsObject) { PC_HYPRE *jac = (PC_HYPRE *)pc->data; PetscInt n; PetscBool flag, flag2, flag3, flag4; PetscFunctionBegin; PetscOptionsHeadBegin(PetscOptionsObject, "HYPRE AMS Options"); PetscCall(PetscOptionsInt("-pc_hypre_ams_print_level", "Debugging output level for AMS", "None", jac->as_print, &jac->as_print, &flag)); if (flag) PetscCallExternal(HYPRE_AMSSetPrintLevel, jac->hsolver, jac->as_print); PetscCall(PetscOptionsInt("-pc_hypre_ams_max_iter", "Maximum number of AMS multigrid iterations within PCApply", "None", jac->as_max_iter, &jac->as_max_iter, &flag)); if (flag) PetscCallExternal(HYPRE_AMSSetMaxIter, jac->hsolver, jac->as_max_iter); PetscCall(PetscOptionsInt("-pc_hypre_ams_cycle_type", "Cycle type for AMS multigrid", "None", jac->ams_cycle_type, &jac->ams_cycle_type, &flag)); if (flag) PetscCallExternal(HYPRE_AMSSetCycleType, jac->hsolver, jac->ams_cycle_type); PetscCall(PetscOptionsReal("-pc_hypre_ams_tol", "Error tolerance for AMS multigrid", "None", jac->as_tol, &jac->as_tol, &flag)); if (flag) PetscCallExternal(HYPRE_AMSSetTol, jac->hsolver, jac->as_tol); PetscCall(PetscOptionsInt("-pc_hypre_ams_relax_type", "Relaxation type for AMS smoother", "None", jac->as_relax_type, &jac->as_relax_type, &flag)); PetscCall(PetscOptionsInt("-pc_hypre_ams_relax_times", "Number of relaxation steps for AMS smoother", "None", jac->as_relax_times, &jac->as_relax_times, &flag2)); PetscCall(PetscOptionsReal("-pc_hypre_ams_relax_weight", "Relaxation weight for AMS smoother", "None", jac->as_relax_weight, &jac->as_relax_weight, &flag3)); PetscCall(PetscOptionsReal("-pc_hypre_ams_omega", "SSOR coefficient for AMS smoother", "None", jac->as_omega, &jac->as_omega, &flag4)); if (flag || flag2 || flag3 || flag4) PetscCallExternal(HYPRE_AMSSetSmoothingOptions, jac->hsolver, jac->as_relax_type, jac->as_relax_times, jac->as_relax_weight, jac->as_omega); PetscCall(PetscOptionsReal("-pc_hypre_ams_amg_alpha_theta", "Threshold for strong coupling of vector Poisson AMG solver", "None", jac->as_amg_alpha_theta, &jac->as_amg_alpha_theta, &flag)); n = 5; PetscCall(PetscOptionsIntArray("-pc_hypre_ams_amg_alpha_options", "AMG options for vector Poisson", "None", jac->as_amg_alpha_opts, &n, &flag2)); if (flag || flag2) { PetscCallExternal(HYPRE_AMSSetAlphaAMGOptions, jac->hsolver, jac->as_amg_alpha_opts[0], /* AMG coarsen type */ jac->as_amg_alpha_opts[1], /* AMG agg_levels */ jac->as_amg_alpha_opts[2], /* AMG relax_type */ jac->as_amg_alpha_theta, jac->as_amg_alpha_opts[3], /* AMG interp_type */ jac->as_amg_alpha_opts[4]); /* AMG Pmax */ } PetscCall(PetscOptionsReal("-pc_hypre_ams_amg_beta_theta", "Threshold for strong coupling of scalar Poisson AMG solver", "None", jac->as_amg_beta_theta, &jac->as_amg_beta_theta, &flag)); n = 5; PetscCall(PetscOptionsIntArray("-pc_hypre_ams_amg_beta_options", "AMG options for scalar Poisson solver", "None", jac->as_amg_beta_opts, &n, &flag2)); if (flag || flag2) { PetscCallExternal(HYPRE_AMSSetBetaAMGOptions, jac->hsolver, jac->as_amg_beta_opts[0], /* AMG coarsen type */ jac->as_amg_beta_opts[1], /* AMG agg_levels */ jac->as_amg_beta_opts[2], /* AMG relax_type */ jac->as_amg_beta_theta, jac->as_amg_beta_opts[3], /* AMG interp_type */ jac->as_amg_beta_opts[4]); /* AMG Pmax */ } PetscCall(PetscOptionsInt("-pc_hypre_ams_projection_frequency", "Frequency at which a projection onto the compatible subspace for problems with zero conductivity regions is performed", "None", jac->ams_proj_freq, &jac->ams_proj_freq, &flag)); if (flag) { /* override HYPRE's default only if the options is used */ PetscCallExternal(HYPRE_AMSSetProjectionFrequency, jac->hsolver, jac->ams_proj_freq); } PetscOptionsHeadEnd(); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCView_HYPRE_AMS(PC pc, PetscViewer viewer) { PC_HYPRE *jac = (PC_HYPRE *)pc->data; PetscBool iascii; PetscFunctionBegin; PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii)); if (iascii) { PetscCall(PetscViewerASCIIPrintf(viewer, " HYPRE AMS preconditioning\n")); PetscCall(PetscViewerASCIIPrintf(viewer, " subspace iterations per application %" PetscInt_FMT "\n", jac->as_max_iter)); PetscCall(PetscViewerASCIIPrintf(viewer, " subspace cycle type %" PetscInt_FMT "\n", jac->ams_cycle_type)); PetscCall(PetscViewerASCIIPrintf(viewer, " subspace iteration tolerance %g\n", (double)jac->as_tol)); PetscCall(PetscViewerASCIIPrintf(viewer, " smoother type %" PetscInt_FMT "\n", jac->as_relax_type)); PetscCall(PetscViewerASCIIPrintf(viewer, " number of smoothing steps %" PetscInt_FMT "\n", jac->as_relax_times)); PetscCall(PetscViewerASCIIPrintf(viewer, " smoother weight %g\n", (double)jac->as_relax_weight)); PetscCall(PetscViewerASCIIPrintf(viewer, " smoother omega %g\n", (double)jac->as_omega)); if (jac->alpha_Poisson) { PetscCall(PetscViewerASCIIPrintf(viewer, " vector Poisson solver (passed in by user)\n")); } else { PetscCall(PetscViewerASCIIPrintf(viewer, " vector Poisson solver (computed) \n")); } PetscCall(PetscViewerASCIIPrintf(viewer, " boomerAMG coarsening type %" PetscInt_FMT "\n", jac->as_amg_alpha_opts[0])); PetscCall(PetscViewerASCIIPrintf(viewer, " boomerAMG levels of aggressive coarsening %" PetscInt_FMT "\n", jac->as_amg_alpha_opts[1])); PetscCall(PetscViewerASCIIPrintf(viewer, " boomerAMG relaxation type %" PetscInt_FMT "\n", jac->as_amg_alpha_opts[2])); PetscCall(PetscViewerASCIIPrintf(viewer, " boomerAMG interpolation type %" PetscInt_FMT "\n", jac->as_amg_alpha_opts[3])); PetscCall(PetscViewerASCIIPrintf(viewer, " boomerAMG max nonzero elements in interpolation rows %" PetscInt_FMT "\n", jac->as_amg_alpha_opts[4])); PetscCall(PetscViewerASCIIPrintf(viewer, " boomerAMG strength threshold %g\n", (double)jac->as_amg_alpha_theta)); if (!jac->ams_beta_is_zero) { if (jac->beta_Poisson) { PetscCall(PetscViewerASCIIPrintf(viewer, " scalar Poisson solver (passed in by user)\n")); } else { PetscCall(PetscViewerASCIIPrintf(viewer, " scalar Poisson solver (computed) \n")); } PetscCall(PetscViewerASCIIPrintf(viewer, " boomerAMG coarsening type %" PetscInt_FMT "\n", jac->as_amg_beta_opts[0])); PetscCall(PetscViewerASCIIPrintf(viewer, " boomerAMG levels of aggressive coarsening %" PetscInt_FMT "\n", jac->as_amg_beta_opts[1])); PetscCall(PetscViewerASCIIPrintf(viewer, " boomerAMG relaxation type %" PetscInt_FMT "\n", jac->as_amg_beta_opts[2])); PetscCall(PetscViewerASCIIPrintf(viewer, " boomerAMG interpolation type %" PetscInt_FMT "\n", jac->as_amg_beta_opts[3])); PetscCall(PetscViewerASCIIPrintf(viewer, " boomerAMG max nonzero elements in interpolation rows %" PetscInt_FMT "\n", jac->as_amg_beta_opts[4])); PetscCall(PetscViewerASCIIPrintf(viewer, " boomerAMG strength threshold %g\n", (double)jac->as_amg_beta_theta)); if (jac->ams_beta_is_zero_part) PetscCall(PetscViewerASCIIPrintf(viewer, " compatible subspace projection frequency %" PetscInt_FMT " (-1 HYPRE uses default)\n", jac->ams_proj_freq)); } else { PetscCall(PetscViewerASCIIPrintf(viewer, " scalar Poisson solver not used (zero-conductivity everywhere) \n")); } } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCSetFromOptions_HYPRE_ADS(PC pc, PetscOptionItems *PetscOptionsObject) { PC_HYPRE *jac = (PC_HYPRE *)pc->data; PetscInt n; PetscBool flag, flag2, flag3, flag4; PetscFunctionBegin; PetscOptionsHeadBegin(PetscOptionsObject, "HYPRE ADS Options"); PetscCall(PetscOptionsInt("-pc_hypre_ads_print_level", "Debugging output level for ADS", "None", jac->as_print, &jac->as_print, &flag)); if (flag) PetscCallExternal(HYPRE_ADSSetPrintLevel, jac->hsolver, jac->as_print); PetscCall(PetscOptionsInt("-pc_hypre_ads_max_iter", "Maximum number of ADS multigrid iterations within PCApply", "None", jac->as_max_iter, &jac->as_max_iter, &flag)); if (flag) PetscCallExternal(HYPRE_ADSSetMaxIter, jac->hsolver, jac->as_max_iter); PetscCall(PetscOptionsInt("-pc_hypre_ads_cycle_type", "Cycle type for ADS multigrid", "None", jac->ads_cycle_type, &jac->ads_cycle_type, &flag)); if (flag) PetscCallExternal(HYPRE_ADSSetCycleType, jac->hsolver, jac->ads_cycle_type); PetscCall(PetscOptionsReal("-pc_hypre_ads_tol", "Error tolerance for ADS multigrid", "None", jac->as_tol, &jac->as_tol, &flag)); if (flag) PetscCallExternal(HYPRE_ADSSetTol, jac->hsolver, jac->as_tol); PetscCall(PetscOptionsInt("-pc_hypre_ads_relax_type", "Relaxation type for ADS smoother", "None", jac->as_relax_type, &jac->as_relax_type, &flag)); PetscCall(PetscOptionsInt("-pc_hypre_ads_relax_times", "Number of relaxation steps for ADS smoother", "None", jac->as_relax_times, &jac->as_relax_times, &flag2)); PetscCall(PetscOptionsReal("-pc_hypre_ads_relax_weight", "Relaxation weight for ADS smoother", "None", jac->as_relax_weight, &jac->as_relax_weight, &flag3)); PetscCall(PetscOptionsReal("-pc_hypre_ads_omega", "SSOR coefficient for ADS smoother", "None", jac->as_omega, &jac->as_omega, &flag4)); if (flag || flag2 || flag3 || flag4) PetscCallExternal(HYPRE_ADSSetSmoothingOptions, jac->hsolver, jac->as_relax_type, jac->as_relax_times, jac->as_relax_weight, jac->as_omega); PetscCall(PetscOptionsReal("-pc_hypre_ads_ams_theta", "Threshold for strong coupling of AMS solver inside ADS", "None", jac->as_amg_alpha_theta, &jac->as_amg_alpha_theta, &flag)); n = 5; PetscCall(PetscOptionsIntArray("-pc_hypre_ads_ams_options", "AMG options for AMS solver inside ADS", "None", jac->as_amg_alpha_opts, &n, &flag2)); PetscCall(PetscOptionsInt("-pc_hypre_ads_ams_cycle_type", "Cycle type for AMS solver inside ADS", "None", jac->ams_cycle_type, &jac->ams_cycle_type, &flag3)); if (flag || flag2 || flag3) { PetscCallExternal(HYPRE_ADSSetAMSOptions, jac->hsolver, jac->ams_cycle_type, /* AMS cycle type */ jac->as_amg_alpha_opts[0], /* AMG coarsen type */ jac->as_amg_alpha_opts[1], /* AMG agg_levels */ jac->as_amg_alpha_opts[2], /* AMG relax_type */ jac->as_amg_alpha_theta, jac->as_amg_alpha_opts[3], /* AMG interp_type */ jac->as_amg_alpha_opts[4]); /* AMG Pmax */ } PetscCall(PetscOptionsReal("-pc_hypre_ads_amg_theta", "Threshold for strong coupling of vector AMG solver inside ADS", "None", jac->as_amg_beta_theta, &jac->as_amg_beta_theta, &flag)); n = 5; PetscCall(PetscOptionsIntArray("-pc_hypre_ads_amg_options", "AMG options for vector AMG solver inside ADS", "None", jac->as_amg_beta_opts, &n, &flag2)); if (flag || flag2) { PetscCallExternal(HYPRE_ADSSetAMGOptions, jac->hsolver, jac->as_amg_beta_opts[0], /* AMG coarsen type */ jac->as_amg_beta_opts[1], /* AMG agg_levels */ jac->as_amg_beta_opts[2], /* AMG relax_type */ jac->as_amg_beta_theta, jac->as_amg_beta_opts[3], /* AMG interp_type */ jac->as_amg_beta_opts[4]); /* AMG Pmax */ } PetscOptionsHeadEnd(); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCView_HYPRE_ADS(PC pc, PetscViewer viewer) { PC_HYPRE *jac = (PC_HYPRE *)pc->data; PetscBool iascii; PetscFunctionBegin; PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii)); if (iascii) { PetscCall(PetscViewerASCIIPrintf(viewer, " HYPRE ADS preconditioning\n")); PetscCall(PetscViewerASCIIPrintf(viewer, " subspace iterations per application %" PetscInt_FMT "\n", jac->as_max_iter)); PetscCall(PetscViewerASCIIPrintf(viewer, " subspace cycle type %" PetscInt_FMT "\n", jac->ads_cycle_type)); PetscCall(PetscViewerASCIIPrintf(viewer, " subspace iteration tolerance %g\n", (double)jac->as_tol)); PetscCall(PetscViewerASCIIPrintf(viewer, " smoother type %" PetscInt_FMT "\n", jac->as_relax_type)); PetscCall(PetscViewerASCIIPrintf(viewer, " number of smoothing steps %" PetscInt_FMT "\n", jac->as_relax_times)); PetscCall(PetscViewerASCIIPrintf(viewer, " smoother weight %g\n", (double)jac->as_relax_weight)); PetscCall(PetscViewerASCIIPrintf(viewer, " smoother omega %g\n", (double)jac->as_omega)); PetscCall(PetscViewerASCIIPrintf(viewer, " AMS solver using boomerAMG\n")); PetscCall(PetscViewerASCIIPrintf(viewer, " subspace cycle type %" PetscInt_FMT "\n", jac->ams_cycle_type)); PetscCall(PetscViewerASCIIPrintf(viewer, " coarsening type %" PetscInt_FMT "\n", jac->as_amg_alpha_opts[0])); PetscCall(PetscViewerASCIIPrintf(viewer, " levels of aggressive coarsening %" PetscInt_FMT "\n", jac->as_amg_alpha_opts[1])); PetscCall(PetscViewerASCIIPrintf(viewer, " relaxation type %" PetscInt_FMT "\n", jac->as_amg_alpha_opts[2])); PetscCall(PetscViewerASCIIPrintf(viewer, " interpolation type %" PetscInt_FMT "\n", jac->as_amg_alpha_opts[3])); PetscCall(PetscViewerASCIIPrintf(viewer, " max nonzero elements in interpolation rows %" PetscInt_FMT "\n", jac->as_amg_alpha_opts[4])); PetscCall(PetscViewerASCIIPrintf(viewer, " strength threshold %g\n", (double)jac->as_amg_alpha_theta)); PetscCall(PetscViewerASCIIPrintf(viewer, " vector Poisson solver using boomerAMG\n")); PetscCall(PetscViewerASCIIPrintf(viewer, " coarsening type %" PetscInt_FMT "\n", jac->as_amg_beta_opts[0])); PetscCall(PetscViewerASCIIPrintf(viewer, " levels of aggressive coarsening %" PetscInt_FMT "\n", jac->as_amg_beta_opts[1])); PetscCall(PetscViewerASCIIPrintf(viewer, " relaxation type %" PetscInt_FMT "\n", jac->as_amg_beta_opts[2])); PetscCall(PetscViewerASCIIPrintf(viewer, " interpolation type %" PetscInt_FMT "\n", jac->as_amg_beta_opts[3])); PetscCall(PetscViewerASCIIPrintf(viewer, " max nonzero elements in interpolation rows %" PetscInt_FMT "\n", jac->as_amg_beta_opts[4])); PetscCall(PetscViewerASCIIPrintf(viewer, " strength threshold %g\n", (double)jac->as_amg_beta_theta)); } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCHYPRESetDiscreteGradient_HYPRE(PC pc, Mat G) { PC_HYPRE *jac = (PC_HYPRE *)pc->data; PetscBool ishypre; PetscFunctionBegin; PetscCall(PetscObjectTypeCompare((PetscObject)G, MATHYPRE, &ishypre)); if (ishypre) { PetscCall(PetscObjectReference((PetscObject)G)); PetscCall(MatDestroy(&jac->G)); jac->G = G; } else { PetscCall(MatDestroy(&jac->G)); PetscCall(MatConvert(G, MATHYPRE, MAT_INITIAL_MATRIX, &jac->G)); } PetscFunctionReturn(PETSC_SUCCESS); } /*@ PCHYPRESetDiscreteGradient - Set discrete gradient matrix for `PCHYPRE` type of ams or ads Collective Input Parameters: + pc - the preconditioning context - G - the discrete gradient Level: intermediate Notes: G should have as many rows as the number of edges and as many columns as the number of vertices in the mesh Each row of G has 2 nonzeros, with column indexes being the global indexes of edge's endpoints: matrix entries are +1 and -1 depending on edge orientation Developer Notes: This automatically converts the matrix to `MATHYPRE` if it is not already of that type .seealso: `PCHYPRE`, `PCHYPRESetDiscreteCurl()` @*/ PetscErrorCode PCHYPRESetDiscreteGradient(PC pc, Mat G) { PetscFunctionBegin; PetscValidHeaderSpecific(pc, PC_CLASSID, 1); PetscValidHeaderSpecific(G, MAT_CLASSID, 2); PetscCheckSameComm(pc, 1, G, 2); PetscTryMethod(pc, "PCHYPRESetDiscreteGradient_C", (PC, Mat), (pc, G)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCHYPRESetDiscreteCurl_HYPRE(PC pc, Mat C) { PC_HYPRE *jac = (PC_HYPRE *)pc->data; PetscBool ishypre; PetscFunctionBegin; PetscCall(PetscObjectTypeCompare((PetscObject)C, MATHYPRE, &ishypre)); if (ishypre) { PetscCall(PetscObjectReference((PetscObject)C)); PetscCall(MatDestroy(&jac->C)); jac->C = C; } else { PetscCall(MatDestroy(&jac->C)); PetscCall(MatConvert(C, MATHYPRE, MAT_INITIAL_MATRIX, &jac->C)); } PetscFunctionReturn(PETSC_SUCCESS); } /*@ PCHYPRESetDiscreteCurl - Set discrete curl matrx for `PCHYPRE` type of ads Collective Input Parameters: + pc - the preconditioning context - C - the discrete curl Level: intermediate Notes: C should have as many rows as the number of faces and as many columns as the number of edges in the mesh Each row of G has as many nonzeros as the number of edges of a face, with column indexes being the global indexes of the corresponding edge: matrix entries are +1 and -1 depending on edge orientation with respect to the face orientation Developer Notes: This automatically converts the matrix to `MATHYPRE` if it is not already of that type If this is only for `PCHYPRE` type of ads it should be called `PCHYPREADSSetDiscreteCurl()` .seealso: `PCHYPRE`, `PCHYPRESetDiscreteGradient()` @*/ PetscErrorCode PCHYPRESetDiscreteCurl(PC pc, Mat C) { PetscFunctionBegin; PetscValidHeaderSpecific(pc, PC_CLASSID, 1); PetscValidHeaderSpecific(C, MAT_CLASSID, 2); PetscCheckSameComm(pc, 1, C, 2); PetscTryMethod(pc, "PCHYPRESetDiscreteCurl_C", (PC, Mat), (pc, C)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCHYPRESetInterpolations_HYPRE(PC pc, PetscInt dim, Mat RT_PiFull, Mat RT_Pi[], Mat ND_PiFull, Mat ND_Pi[]) { PC_HYPRE *jac = (PC_HYPRE *)pc->data; PetscBool ishypre; PetscInt i; PetscFunctionBegin; PetscCall(MatDestroy(&jac->RT_PiFull)); PetscCall(MatDestroy(&jac->ND_PiFull)); for (i = 0; i < 3; ++i) { PetscCall(MatDestroy(&jac->RT_Pi[i])); PetscCall(MatDestroy(&jac->ND_Pi[i])); } jac->dim = dim; if (RT_PiFull) { PetscCall(PetscObjectTypeCompare((PetscObject)RT_PiFull, MATHYPRE, &ishypre)); if (ishypre) { PetscCall(PetscObjectReference((PetscObject)RT_PiFull)); jac->RT_PiFull = RT_PiFull; } else { PetscCall(MatConvert(RT_PiFull, MATHYPRE, MAT_INITIAL_MATRIX, &jac->RT_PiFull)); } } if (RT_Pi) { for (i = 0; i < dim; ++i) { if (RT_Pi[i]) { PetscCall(PetscObjectTypeCompare((PetscObject)RT_Pi[i], MATHYPRE, &ishypre)); if (ishypre) { PetscCall(PetscObjectReference((PetscObject)RT_Pi[i])); jac->RT_Pi[i] = RT_Pi[i]; } else { PetscCall(MatConvert(RT_Pi[i], MATHYPRE, MAT_INITIAL_MATRIX, &jac->RT_Pi[i])); } } } } if (ND_PiFull) { PetscCall(PetscObjectTypeCompare((PetscObject)ND_PiFull, MATHYPRE, &ishypre)); if (ishypre) { PetscCall(PetscObjectReference((PetscObject)ND_PiFull)); jac->ND_PiFull = ND_PiFull; } else { PetscCall(MatConvert(ND_PiFull, MATHYPRE, MAT_INITIAL_MATRIX, &jac->ND_PiFull)); } } if (ND_Pi) { for (i = 0; i < dim; ++i) { if (ND_Pi[i]) { PetscCall(PetscObjectTypeCompare((PetscObject)ND_Pi[i], MATHYPRE, &ishypre)); if (ishypre) { PetscCall(PetscObjectReference((PetscObject)ND_Pi[i])); jac->ND_Pi[i] = ND_Pi[i]; } else { PetscCall(MatConvert(ND_Pi[i], MATHYPRE, MAT_INITIAL_MATRIX, &jac->ND_Pi[i])); } } } } PetscFunctionReturn(PETSC_SUCCESS); } /*@ PCHYPRESetInterpolations - Set interpolation matrices for `PCHYPRE` type of ams or ads Collective Input Parameters: + pc - the preconditioning context . dim - the dimension of the problem, only used in AMS . RT_PiFull - Raviart-Thomas interpolation matrix . RT_Pi - x/y/z component of Raviart-Thomas interpolation matrix . ND_PiFull - Nedelec interpolation matrix - ND_Pi - x/y/z component of Nedelec interpolation matrix Level: intermediate Notes: For AMS, only Nedelec interpolation matrices are needed, the Raviart-Thomas interpolation matrices can be set to NULL. For ADS, both type of interpolation matrices are needed. Developer Notes: This automatically converts the matrix to `MATHYPRE` if it is not already of that type .seealso: `PCHYPRE` @*/ PetscErrorCode PCHYPRESetInterpolations(PC pc, PetscInt dim, Mat RT_PiFull, Mat RT_Pi[], Mat ND_PiFull, Mat ND_Pi[]) { PetscInt i; PetscFunctionBegin; PetscValidHeaderSpecific(pc, PC_CLASSID, 1); if (RT_PiFull) { PetscValidHeaderSpecific(RT_PiFull, MAT_CLASSID, 3); PetscCheckSameComm(pc, 1, RT_PiFull, 3); } if (RT_Pi) { PetscAssertPointer(RT_Pi, 4); for (i = 0; i < dim; ++i) { if (RT_Pi[i]) { PetscValidHeaderSpecific(RT_Pi[i], MAT_CLASSID, 4); PetscCheckSameComm(pc, 1, RT_Pi[i], 4); } } } if (ND_PiFull) { PetscValidHeaderSpecific(ND_PiFull, MAT_CLASSID, 5); PetscCheckSameComm(pc, 1, ND_PiFull, 5); } if (ND_Pi) { PetscAssertPointer(ND_Pi, 6); for (i = 0; i < dim; ++i) { if (ND_Pi[i]) { PetscValidHeaderSpecific(ND_Pi[i], MAT_CLASSID, 6); PetscCheckSameComm(pc, 1, ND_Pi[i], 6); } } } PetscTryMethod(pc, "PCHYPRESetInterpolations_C", (PC, PetscInt, Mat, Mat[], Mat, Mat[]), (pc, dim, RT_PiFull, RT_Pi, ND_PiFull, ND_Pi)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCHYPRESetPoissonMatrix_HYPRE(PC pc, Mat A, PetscBool isalpha) { PC_HYPRE *jac = (PC_HYPRE *)pc->data; PetscBool ishypre; PetscFunctionBegin; PetscCall(PetscObjectTypeCompare((PetscObject)A, MATHYPRE, &ishypre)); if (ishypre) { if (isalpha) { PetscCall(PetscObjectReference((PetscObject)A)); PetscCall(MatDestroy(&jac->alpha_Poisson)); jac->alpha_Poisson = A; } else { if (A) { PetscCall(PetscObjectReference((PetscObject)A)); } else { jac->ams_beta_is_zero = PETSC_TRUE; } PetscCall(MatDestroy(&jac->beta_Poisson)); jac->beta_Poisson = A; } } else { if (isalpha) { PetscCall(MatDestroy(&jac->alpha_Poisson)); PetscCall(MatConvert(A, MATHYPRE, MAT_INITIAL_MATRIX, &jac->alpha_Poisson)); } else { if (A) { PetscCall(MatDestroy(&jac->beta_Poisson)); PetscCall(MatConvert(A, MATHYPRE, MAT_INITIAL_MATRIX, &jac->beta_Poisson)); } else { PetscCall(MatDestroy(&jac->beta_Poisson)); jac->ams_beta_is_zero = PETSC_TRUE; } } } PetscFunctionReturn(PETSC_SUCCESS); } /*@ PCHYPRESetAlphaPoissonMatrix - Set vector Poisson matrix for `PCHYPRE` of type ams Collective Input Parameters: + pc - the preconditioning context - A - the matrix Level: intermediate Note: A should be obtained by discretizing the vector valued Poisson problem with linear finite elements Developer Notes: This automatically converts the matrix to `MATHYPRE` if it is not already of that type If this is only for `PCHYPRE` type of ams it should be called `PCHYPREAMSSetAlphaPoissonMatrix()` .seealso: `PCHYPRE`, `PCHYPRESetDiscreteGradient()`, `PCHYPRESetDiscreteCurl()`, `PCHYPRESetBetaPoissonMatrix()` @*/ PetscErrorCode PCHYPRESetAlphaPoissonMatrix(PC pc, Mat A) { PetscFunctionBegin; PetscValidHeaderSpecific(pc, PC_CLASSID, 1); PetscValidHeaderSpecific(A, MAT_CLASSID, 2); PetscCheckSameComm(pc, 1, A, 2); PetscTryMethod(pc, "PCHYPRESetPoissonMatrix_C", (PC, Mat, PetscBool), (pc, A, PETSC_TRUE)); PetscFunctionReturn(PETSC_SUCCESS); } /*@ PCHYPRESetBetaPoissonMatrix - Set Poisson matrix for `PCHYPRE` of type ams Collective Input Parameters: + pc - the preconditioning context - A - the matrix, or NULL to turn it off Level: intermediate Note: A should be obtained by discretizing the Poisson problem with linear finite elements. Developer Notes: This automatically converts the matrix to `MATHYPRE` if it is not already of that type If this is only for `PCHYPRE` type of ams it should be called `PCHYPREAMSPCHYPRESetBetaPoissonMatrix()` .seealso: `PCHYPRE`, `PCHYPRESetDiscreteGradient()`, `PCHYPRESetDiscreteCurl()`, `PCHYPRESetAlphaPoissonMatrix()` @*/ PetscErrorCode PCHYPRESetBetaPoissonMatrix(PC pc, Mat A) { PetscFunctionBegin; PetscValidHeaderSpecific(pc, PC_CLASSID, 1); if (A) { PetscValidHeaderSpecific(A, MAT_CLASSID, 2); PetscCheckSameComm(pc, 1, A, 2); } PetscTryMethod(pc, "PCHYPRESetPoissonMatrix_C", (PC, Mat, PetscBool), (pc, A, PETSC_FALSE)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCHYPRESetEdgeConstantVectors_HYPRE(PC pc, Vec ozz, Vec zoz, Vec zzo) { PC_HYPRE *jac = (PC_HYPRE *)pc->data; PetscFunctionBegin; /* throw away any vector if already set */ PetscCall(VecHYPRE_IJVectorDestroy(&jac->constants[0])); PetscCall(VecHYPRE_IJVectorDestroy(&jac->constants[1])); PetscCall(VecHYPRE_IJVectorDestroy(&jac->constants[2])); PetscCall(VecHYPRE_IJVectorCreate(ozz->map, &jac->constants[0])); PetscCall(VecHYPRE_IJVectorCopy(ozz, jac->constants[0])); PetscCall(VecHYPRE_IJVectorCreate(zoz->map, &jac->constants[1])); PetscCall(VecHYPRE_IJVectorCopy(zoz, jac->constants[1])); jac->dim = 2; if (zzo) { PetscCall(VecHYPRE_IJVectorCreate(zzo->map, &jac->constants[2])); PetscCall(VecHYPRE_IJVectorCopy(zzo, jac->constants[2])); jac->dim++; } PetscFunctionReturn(PETSC_SUCCESS); } /*@ PCHYPRESetEdgeConstantVectors - Set the representation of the constant vector fields in the edge element basis for `PCHYPRE` of type ams Collective Input Parameters: + pc - the preconditioning context . ozz - vector representing (1,0,0) (or (1,0) in 2D) . zoz - vector representing (0,1,0) (or (0,1) in 2D) - zzo - vector representing (0,0,1) (use NULL in 2D) Level: intermediate Developer Notes: If this is only for `PCHYPRE` type of ams it should be called `PCHYPREAMSSetEdgeConstantVectors()` .seealso: `PCHYPRE`, `PCHYPRESetDiscreteGradient()`, `PCHYPRESetDiscreteCurl()`, `PCHYPRESetAlphaPoissonMatrix()` @*/ PetscErrorCode PCHYPRESetEdgeConstantVectors(PC pc, Vec ozz, Vec zoz, Vec zzo) { PetscFunctionBegin; PetscValidHeaderSpecific(pc, PC_CLASSID, 1); PetscValidHeaderSpecific(ozz, VEC_CLASSID, 2); PetscValidHeaderSpecific(zoz, VEC_CLASSID, 3); if (zzo) PetscValidHeaderSpecific(zzo, VEC_CLASSID, 4); PetscCheckSameComm(pc, 1, ozz, 2); PetscCheckSameComm(pc, 1, zoz, 3); if (zzo) PetscCheckSameComm(pc, 1, zzo, 4); PetscTryMethod(pc, "PCHYPRESetEdgeConstantVectors_C", (PC, Vec, Vec, Vec), (pc, ozz, zoz, zzo)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCHYPREAMSSetInteriorNodes_HYPRE(PC pc, Vec interior) { PC_HYPRE *jac = (PC_HYPRE *)pc->data; PetscFunctionBegin; PetscCall(VecHYPRE_IJVectorDestroy(&jac->interior)); PetscCall(VecHYPRE_IJVectorCreate(interior->map, &jac->interior)); PetscCall(VecHYPRE_IJVectorCopy(interior, jac->interior)); jac->ams_beta_is_zero_part = PETSC_TRUE; PetscFunctionReturn(PETSC_SUCCESS); } /*@ PCHYPREAMSSetInteriorNodes - Set the list of interior nodes to a zero-conductivity region for `PCHYPRE` of type ams Collective Input Parameters: + pc - the preconditioning context - interior - vector. node is interior if its entry in the array is 1.0. Level: intermediate Note: This calls `HYPRE_AMSSetInteriorNodes()` Developer Notes: If this is only for `PCHYPRE` type of ams it should be called `PCHYPREAMSSetInteriorNodes()` .seealso: `PCHYPRE`, `PCHYPRESetDiscreteGradient()`, `PCHYPRESetDiscreteCurl()`, `PCHYPRESetAlphaPoissonMatrix()` @*/ PetscErrorCode PCHYPREAMSSetInteriorNodes(PC pc, Vec interior) { PetscFunctionBegin; PetscValidHeaderSpecific(pc, PC_CLASSID, 1); PetscValidHeaderSpecific(interior, VEC_CLASSID, 2); PetscCheckSameComm(pc, 1, interior, 2); PetscTryMethod(pc, "PCHYPREAMSSetInteriorNodes_C", (PC, Vec), (pc, interior)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCSetCoordinates_HYPRE(PC pc, PetscInt dim, PetscInt nloc, PetscReal *coords) { PC_HYPRE *jac = (PC_HYPRE *)pc->data; Vec tv; PetscInt i; PetscFunctionBegin; /* throw away any coordinate vector if already set */ PetscCall(VecHYPRE_IJVectorDestroy(&jac->coords[0])); PetscCall(VecHYPRE_IJVectorDestroy(&jac->coords[1])); PetscCall(VecHYPRE_IJVectorDestroy(&jac->coords[2])); jac->dim = dim; /* compute IJ vector for coordinates */ PetscCall(VecCreate(PetscObjectComm((PetscObject)pc), &tv)); PetscCall(VecSetType(tv, VECSTANDARD)); PetscCall(VecSetSizes(tv, nloc, PETSC_DECIDE)); for (i = 0; i < dim; i++) { PetscScalar *array; PetscInt j; PetscCall(VecHYPRE_IJVectorCreate(tv->map, &jac->coords[i])); PetscCall(VecGetArrayWrite(tv, &array)); for (j = 0; j < nloc; j++) array[j] = coords[j * dim + i]; PetscCall(VecRestoreArrayWrite(tv, &array)); PetscCall(VecHYPRE_IJVectorCopy(tv, jac->coords[i])); } PetscCall(VecDestroy(&tv)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCHYPREGetType_HYPRE(PC pc, const char *name[]) { PC_HYPRE *jac = (PC_HYPRE *)pc->data; PetscFunctionBegin; *name = jac->hypre_type; PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCHYPRESetType_HYPRE(PC pc, const char name[]) { PC_HYPRE *jac = (PC_HYPRE *)pc->data; PetscBool flag; PetscFunctionBegin; if (jac->hypre_type) { PetscCall(PetscStrcmp(jac->hypre_type, name, &flag)); PetscCheck(flag, PetscObjectComm((PetscObject)pc), PETSC_ERR_ORDER, "Cannot reset the HYPRE preconditioner type once it has been set"); PetscFunctionReturn(PETSC_SUCCESS); } else { PetscCall(PetscStrallocpy(name, &jac->hypre_type)); } jac->maxiter = PETSC_DEFAULT; jac->tol = PETSC_DEFAULT; jac->printstatistics = PetscLogPrintInfo; PetscCall(PetscStrcmp("pilut", jac->hypre_type, &flag)); if (flag) { PetscCall(PetscCommGetComm(PetscObjectComm((PetscObject)pc), &jac->comm_hypre)); PetscCallExternal(HYPRE_ParCSRPilutCreate, jac->comm_hypre, &jac->hsolver); pc->ops->setfromoptions = PCSetFromOptions_HYPRE_Pilut; pc->ops->view = PCView_HYPRE_Pilut; jac->destroy = HYPRE_ParCSRPilutDestroy; jac->setup = HYPRE_ParCSRPilutSetup; jac->solve = HYPRE_ParCSRPilutSolve; jac->factorrowsize = PETSC_DEFAULT; PetscFunctionReturn(PETSC_SUCCESS); } PetscCall(PetscStrcmp("euclid", jac->hypre_type, &flag)); if (flag) { #if defined(PETSC_USE_64BIT_INDICES) SETERRQ(PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "Hypre Euclid does not support 64-bit indices"); #endif PetscCall(PetscCommGetComm(PetscObjectComm((PetscObject)pc), &jac->comm_hypre)); PetscCallExternal(HYPRE_EuclidCreate, jac->comm_hypre, &jac->hsolver); pc->ops->setfromoptions = PCSetFromOptions_HYPRE_Euclid; pc->ops->view = PCView_HYPRE_Euclid; jac->destroy = HYPRE_EuclidDestroy; jac->setup = HYPRE_EuclidSetup; jac->solve = HYPRE_EuclidSolve; jac->factorrowsize = PETSC_DEFAULT; jac->eu_level = PETSC_DEFAULT; /* default */ PetscFunctionReturn(PETSC_SUCCESS); } PetscCall(PetscStrcmp("parasails", jac->hypre_type, &flag)); if (flag) { PetscCall(PetscCommGetComm(PetscObjectComm((PetscObject)pc), &jac->comm_hypre)); PetscCallExternal(HYPRE_ParaSailsCreate, jac->comm_hypre, &jac->hsolver); pc->ops->setfromoptions = PCSetFromOptions_HYPRE_ParaSails; pc->ops->view = PCView_HYPRE_ParaSails; jac->destroy = HYPRE_ParaSailsDestroy; jac->setup = HYPRE_ParaSailsSetup; jac->solve = HYPRE_ParaSailsSolve; /* initialize */ jac->nlevels = 1; jac->threshold = .1; jac->filter = .1; jac->loadbal = 0; if (PetscLogPrintInfo) jac->logging = (int)PETSC_TRUE; else jac->logging = (int)PETSC_FALSE; jac->ruse = (int)PETSC_FALSE; jac->symt = 0; PetscCallExternal(HYPRE_ParaSailsSetParams, jac->hsolver, jac->threshold, jac->nlevels); PetscCallExternal(HYPRE_ParaSailsSetFilter, jac->hsolver, jac->filter); PetscCallExternal(HYPRE_ParaSailsSetLoadbal, jac->hsolver, jac->loadbal); PetscCallExternal(HYPRE_ParaSailsSetLogging, jac->hsolver, jac->logging); PetscCallExternal(HYPRE_ParaSailsSetReuse, jac->hsolver, jac->ruse); PetscCallExternal(HYPRE_ParaSailsSetSym, jac->hsolver, jac->symt); PetscFunctionReturn(PETSC_SUCCESS); } PetscCall(PetscStrcmp("boomeramg", jac->hypre_type, &flag)); if (flag) { PetscCallExternal(HYPRE_BoomerAMGCreate, &jac->hsolver); pc->ops->setfromoptions = PCSetFromOptions_HYPRE_BoomerAMG; pc->ops->view = PCView_HYPRE_BoomerAMG; pc->ops->applytranspose = PCApplyTranspose_HYPRE_BoomerAMG; pc->ops->applyrichardson = PCApplyRichardson_HYPRE_BoomerAMG; pc->ops->matapply = PCMatApply_HYPRE_BoomerAMG; PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCGetInterpolations_C", PCGetInterpolations_BoomerAMG)); PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCGetCoarseOperators_C", PCGetCoarseOperators_BoomerAMG)); jac->destroy = HYPRE_BoomerAMGDestroy; jac->setup = HYPRE_BoomerAMGSetup; jac->solve = HYPRE_BoomerAMGSolve; jac->applyrichardson = PETSC_FALSE; /* these defaults match the hypre defaults */ jac->cycletype = 1; jac->maxlevels = 25; jac->maxiter = 1; jac->tol = 0.0; /* tolerance of zero indicates use as preconditioner (suppresses convergence errors) */ jac->truncfactor = 0.0; jac->strongthreshold = .25; jac->maxrowsum = .9; jac->coarsentype = 6; jac->measuretype = 0; jac->gridsweeps[0] = jac->gridsweeps[1] = jac->gridsweeps[2] = 1; jac->smoothtype = -1; /* Not set by default */ jac->smoothnumlevels = 25; jac->eu_level = 0; jac->eu_droptolerance = 0; jac->eu_bj = 0; jac->relaxtype[0] = jac->relaxtype[1] = 6; /* Defaults to SYMMETRIC since in PETSc we are using a PC - most likely with CG */ jac->relaxtype[2] = 9; /*G.E. */ jac->relaxweight = 1.0; jac->outerrelaxweight = 1.0; jac->relaxorder = 1; jac->interptype = 0; jac->Rtype = 0; jac->Rstrongthreshold = 0.25; jac->Rfilterthreshold = 0.0; jac->Adroptype = -1; jac->Adroptol = 0.0; jac->agg_nl = 0; jac->agg_interptype = 4; jac->pmax = 0; jac->truncfactor = 0.0; jac->agg_num_paths = 1; jac->maxc = 9; jac->minc = 1; jac->nodal_coarsening = 0; jac->nodal_coarsening_diag = 0; jac->vec_interp_variant = 0; jac->vec_interp_qmax = 0; jac->vec_interp_smooth = PETSC_FALSE; jac->interp_refine = 0; jac->nodal_relax = PETSC_FALSE; jac->nodal_relax_levels = 1; jac->rap2 = 0; /* GPU defaults from https://hypre.readthedocs.io/en/latest/solvers-boomeramg.html#gpu-supported-options and /src/parcsr_ls/par_amg.c */ #if defined(PETSC_HAVE_HYPRE_DEVICE) jac->keeptranspose = PETSC_TRUE; jac->mod_rap2 = 1; jac->coarsentype = 8; jac->relaxorder = 0; jac->interptype = 6; jac->relaxtype[0] = 18; jac->relaxtype[1] = 18; jac->agg_interptype = 7; #else jac->keeptranspose = PETSC_FALSE; jac->mod_rap2 = 0; #endif PetscCallExternal(HYPRE_BoomerAMGSetCycleType, jac->hsolver, jac->cycletype); PetscCallExternal(HYPRE_BoomerAMGSetMaxLevels, jac->hsolver, jac->maxlevels); PetscCallExternal(HYPRE_BoomerAMGSetMaxIter, jac->hsolver, jac->maxiter); PetscCallExternal(HYPRE_BoomerAMGSetTol, jac->hsolver, jac->tol); PetscCallExternal(HYPRE_BoomerAMGSetTruncFactor, jac->hsolver, jac->truncfactor); PetscCallExternal(HYPRE_BoomerAMGSetStrongThreshold, jac->hsolver, jac->strongthreshold); PetscCallExternal(HYPRE_BoomerAMGSetMaxRowSum, jac->hsolver, jac->maxrowsum); PetscCallExternal(HYPRE_BoomerAMGSetCoarsenType, jac->hsolver, jac->coarsentype); PetscCallExternal(HYPRE_BoomerAMGSetMeasureType, jac->hsolver, jac->measuretype); PetscCallExternal(HYPRE_BoomerAMGSetRelaxOrder, jac->hsolver, jac->relaxorder); PetscCallExternal(HYPRE_BoomerAMGSetInterpType, jac->hsolver, jac->interptype); PetscCallExternal(HYPRE_BoomerAMGSetAggNumLevels, jac->hsolver, jac->agg_nl); PetscCallExternal(HYPRE_BoomerAMGSetAggInterpType, jac->hsolver, jac->agg_interptype); PetscCallExternal(HYPRE_BoomerAMGSetPMaxElmts, jac->hsolver, jac->pmax); PetscCallExternal(HYPRE_BoomerAMGSetNumPaths, jac->hsolver, jac->agg_num_paths); PetscCallExternal(HYPRE_BoomerAMGSetRelaxType, jac->hsolver, jac->relaxtype[0]); /* defaults coarse to 9 */ PetscCallExternal(HYPRE_BoomerAMGSetNumSweeps, jac->hsolver, jac->gridsweeps[0]); /* defaults coarse to 1 */ PetscCallExternal(HYPRE_BoomerAMGSetMaxCoarseSize, jac->hsolver, jac->maxc); PetscCallExternal(HYPRE_BoomerAMGSetMinCoarseSize, jac->hsolver, jac->minc); /* GPU */ #if PETSC_PKG_HYPRE_VERSION_GE(2, 18, 0) PetscCallExternal(HYPRE_BoomerAMGSetKeepTranspose, jac->hsolver, jac->keeptranspose ? 1 : 0); PetscCallExternal(HYPRE_BoomerAMGSetRAP2, jac->hsolver, jac->rap2); PetscCallExternal(HYPRE_BoomerAMGSetModuleRAP2, jac->hsolver, jac->mod_rap2); #endif /* AIR */ #if PETSC_PKG_HYPRE_VERSION_GE(2, 18, 0) PetscCallExternal(HYPRE_BoomerAMGSetRestriction, jac->hsolver, jac->Rtype); PetscCallExternal(HYPRE_BoomerAMGSetStrongThresholdR, jac->hsolver, jac->Rstrongthreshold); PetscCallExternal(HYPRE_BoomerAMGSetFilterThresholdR, jac->hsolver, jac->Rfilterthreshold); PetscCallExternal(HYPRE_BoomerAMGSetADropTol, jac->hsolver, jac->Adroptol); PetscCallExternal(HYPRE_BoomerAMGSetADropType, jac->hsolver, jac->Adroptype); #endif PetscFunctionReturn(PETSC_SUCCESS); } PetscCall(PetscStrcmp("ams", jac->hypre_type, &flag)); if (flag) { PetscCallExternal(HYPRE_AMSCreate, &jac->hsolver); pc->ops->setfromoptions = PCSetFromOptions_HYPRE_AMS; pc->ops->view = PCView_HYPRE_AMS; jac->destroy = HYPRE_AMSDestroy; jac->setup = HYPRE_AMSSetup; jac->solve = HYPRE_AMSSolve; jac->coords[0] = NULL; jac->coords[1] = NULL; jac->coords[2] = NULL; jac->interior = NULL; /* solver parameters: these are borrowed from mfem package, and they are not the default values from HYPRE AMS */ jac->as_print = 0; jac->as_max_iter = 1; /* used as a preconditioner */ jac->as_tol = 0.; /* used as a preconditioner */ jac->ams_cycle_type = 13; /* Smoothing options */ jac->as_relax_type = 2; jac->as_relax_times = 1; jac->as_relax_weight = 1.0; jac->as_omega = 1.0; /* Vector valued Poisson AMG solver parameters: coarsen type, agg_levels, relax_type, interp_type, Pmax */ jac->as_amg_alpha_opts[0] = 10; jac->as_amg_alpha_opts[1] = 1; jac->as_amg_alpha_opts[2] = 6; jac->as_amg_alpha_opts[3] = 6; jac->as_amg_alpha_opts[4] = 4; jac->as_amg_alpha_theta = 0.25; /* Scalar Poisson AMG solver parameters: coarsen type, agg_levels, relax_type, interp_type, Pmax */ jac->as_amg_beta_opts[0] = 10; jac->as_amg_beta_opts[1] = 1; jac->as_amg_beta_opts[2] = 6; jac->as_amg_beta_opts[3] = 6; jac->as_amg_beta_opts[4] = 4; jac->as_amg_beta_theta = 0.25; PetscCallExternal(HYPRE_AMSSetPrintLevel, jac->hsolver, jac->as_print); PetscCallExternal(HYPRE_AMSSetMaxIter, jac->hsolver, jac->as_max_iter); PetscCallExternal(HYPRE_AMSSetCycleType, jac->hsolver, jac->ams_cycle_type); PetscCallExternal(HYPRE_AMSSetTol, jac->hsolver, jac->as_tol); PetscCallExternal(HYPRE_AMSSetSmoothingOptions, jac->hsolver, jac->as_relax_type, jac->as_relax_times, jac->as_relax_weight, jac->as_omega); PetscCallExternal(HYPRE_AMSSetAlphaAMGOptions, jac->hsolver, jac->as_amg_alpha_opts[0], /* AMG coarsen type */ jac->as_amg_alpha_opts[1], /* AMG agg_levels */ jac->as_amg_alpha_opts[2], /* AMG relax_type */ jac->as_amg_alpha_theta, jac->as_amg_alpha_opts[3], /* AMG interp_type */ jac->as_amg_alpha_opts[4]); /* AMG Pmax */ PetscCallExternal(HYPRE_AMSSetBetaAMGOptions, jac->hsolver, jac->as_amg_beta_opts[0], /* AMG coarsen type */ jac->as_amg_beta_opts[1], /* AMG agg_levels */ jac->as_amg_beta_opts[2], /* AMG relax_type */ jac->as_amg_beta_theta, jac->as_amg_beta_opts[3], /* AMG interp_type */ jac->as_amg_beta_opts[4]); /* AMG Pmax */ /* Zero conductivity */ jac->ams_beta_is_zero = PETSC_FALSE; jac->ams_beta_is_zero_part = PETSC_FALSE; PetscFunctionReturn(PETSC_SUCCESS); } PetscCall(PetscStrcmp("ads", jac->hypre_type, &flag)); if (flag) { PetscCallExternal(HYPRE_ADSCreate, &jac->hsolver); pc->ops->setfromoptions = PCSetFromOptions_HYPRE_ADS; pc->ops->view = PCView_HYPRE_ADS; jac->destroy = HYPRE_ADSDestroy; jac->setup = HYPRE_ADSSetup; jac->solve = HYPRE_ADSSolve; jac->coords[0] = NULL; jac->coords[1] = NULL; jac->coords[2] = NULL; /* solver parameters: these are borrowed from mfem package, and they are not the default values from HYPRE ADS */ jac->as_print = 0; jac->as_max_iter = 1; /* used as a preconditioner */ jac->as_tol = 0.; /* used as a preconditioner */ jac->ads_cycle_type = 13; /* Smoothing options */ jac->as_relax_type = 2; jac->as_relax_times = 1; jac->as_relax_weight = 1.0; jac->as_omega = 1.0; /* AMS solver parameters: cycle_type, coarsen type, agg_levels, relax_type, interp_type, Pmax */ jac->ams_cycle_type = 14; jac->as_amg_alpha_opts[0] = 10; jac->as_amg_alpha_opts[1] = 1; jac->as_amg_alpha_opts[2] = 6; jac->as_amg_alpha_opts[3] = 6; jac->as_amg_alpha_opts[4] = 4; jac->as_amg_alpha_theta = 0.25; /* Vector Poisson AMG solver parameters: coarsen type, agg_levels, relax_type, interp_type, Pmax */ jac->as_amg_beta_opts[0] = 10; jac->as_amg_beta_opts[1] = 1; jac->as_amg_beta_opts[2] = 6; jac->as_amg_beta_opts[3] = 6; jac->as_amg_beta_opts[4] = 4; jac->as_amg_beta_theta = 0.25; PetscCallExternal(HYPRE_ADSSetPrintLevel, jac->hsolver, jac->as_print); PetscCallExternal(HYPRE_ADSSetMaxIter, jac->hsolver, jac->as_max_iter); PetscCallExternal(HYPRE_ADSSetCycleType, jac->hsolver, jac->ams_cycle_type); PetscCallExternal(HYPRE_ADSSetTol, jac->hsolver, jac->as_tol); PetscCallExternal(HYPRE_ADSSetSmoothingOptions, jac->hsolver, jac->as_relax_type, jac->as_relax_times, jac->as_relax_weight, jac->as_omega); PetscCallExternal(HYPRE_ADSSetAMSOptions, jac->hsolver, jac->ams_cycle_type, /* AMG coarsen type */ jac->as_amg_alpha_opts[0], /* AMG coarsen type */ jac->as_amg_alpha_opts[1], /* AMG agg_levels */ jac->as_amg_alpha_opts[2], /* AMG relax_type */ jac->as_amg_alpha_theta, jac->as_amg_alpha_opts[3], /* AMG interp_type */ jac->as_amg_alpha_opts[4]); /* AMG Pmax */ PetscCallExternal(HYPRE_ADSSetAMGOptions, jac->hsolver, jac->as_amg_beta_opts[0], /* AMG coarsen type */ jac->as_amg_beta_opts[1], /* AMG agg_levels */ jac->as_amg_beta_opts[2], /* AMG relax_type */ jac->as_amg_beta_theta, jac->as_amg_beta_opts[3], /* AMG interp_type */ jac->as_amg_beta_opts[4]); /* AMG Pmax */ PetscFunctionReturn(PETSC_SUCCESS); } PetscCall(PetscFree(jac->hypre_type)); jac->hypre_type = NULL; SETERRQ(PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_UNKNOWN_TYPE, "Unknown HYPRE preconditioner %s; Choices are euclid, pilut, parasails, boomeramg, ams", name); } /* It only gets here if the HYPRE type has not been set before the call to ...SetFromOptions() which actually is most of the time */ static PetscErrorCode PCSetFromOptions_HYPRE(PC pc, PetscOptionItems *PetscOptionsObject) { PetscInt indx; const char *type[] = {"euclid", "pilut", "parasails", "boomeramg", "ams", "ads"}; PetscBool flg; PetscFunctionBegin; PetscOptionsHeadBegin(PetscOptionsObject, "HYPRE preconditioner options"); PetscCall(PetscOptionsEList("-pc_hypre_type", "HYPRE preconditioner type", "PCHYPRESetType", type, PETSC_STATIC_ARRAY_LENGTH(type), "boomeramg", &indx, &flg)); if (flg) { PetscCall(PCHYPRESetType_HYPRE(pc, type[indx])); } else { PetscCall(PCHYPRESetType_HYPRE(pc, "boomeramg")); } PetscTryTypeMethod(pc, setfromoptions, PetscOptionsObject); PetscOptionsHeadEnd(); PetscFunctionReturn(PETSC_SUCCESS); } /*@C PCHYPRESetType - Sets which hypre preconditioner you wish to use Input Parameters: + pc - the preconditioner context - name - either euclid, pilut, parasails, boomeramg, ams, ads Options Database Key: . pc_hypre_type - One of euclid, pilut, parasails, boomeramg, ams, ads Level: intermediate .seealso: `PCCreate()`, `PCSetType()`, `PCType`, `PC`, `PCHYPRE` @*/ PetscErrorCode PCHYPRESetType(PC pc, const char name[]) { PetscFunctionBegin; PetscValidHeaderSpecific(pc, PC_CLASSID, 1); PetscAssertPointer(name, 2); PetscTryMethod(pc, "PCHYPRESetType_C", (PC, const char[]), (pc, name)); PetscFunctionReturn(PETSC_SUCCESS); } /*@C PCHYPREGetType - Gets which hypre preconditioner you are using Input Parameter: . pc - the preconditioner context Output Parameter: . name - either euclid, pilut, parasails, boomeramg, ams, ads Level: intermediate .seealso: `PCCreate()`, `PCHYPRESetType()`, `PCType`, `PC`, `PCHYPRE` @*/ PetscErrorCode PCHYPREGetType(PC pc, const char *name[]) { PetscFunctionBegin; PetscValidHeaderSpecific(pc, PC_CLASSID, 1); PetscAssertPointer(name, 2); PetscTryMethod(pc, "PCHYPREGetType_C", (PC, const char *[]), (pc, name)); PetscFunctionReturn(PETSC_SUCCESS); } /*@C PCMGGalerkinSetMatProductAlgorithm - Set type of SpGEMM for hypre to use on GPUs Logically Collective Input Parameters: + pc - the hypre context - name - one of 'cusparse', 'hypre' Options Database Key: . -pc_mg_galerkin_mat_product_algorithm <cusparse,hypre> - Type of SpGEMM to use in hypre Level: intermediate Developer Notes: How the name starts with `PCMG`, should it not be `PCHYPREBoomerAMG`? .seealso: `PCHYPRE`, `PCMGGalerkinGetMatProductAlgorithm()` @*/ PetscErrorCode PCMGGalerkinSetMatProductAlgorithm(PC pc, const char name[]) { PetscFunctionBegin; PetscValidHeaderSpecific(pc, PC_CLASSID, 1); PetscTryMethod(pc, "PCMGGalerkinSetMatProductAlgorithm_C", (PC, const char[]), (pc, name)); PetscFunctionReturn(PETSC_SUCCESS); } /*@C PCMGGalerkinGetMatProductAlgorithm - Get type of SpGEMM for hypre to use on GPUs Not Collective Input Parameter: . pc - the multigrid context Output Parameter: . name - one of 'cusparse', 'hypre' Level: intermediate .seealso: `PCHYPRE`, ``PCMGGalerkinSetMatProductAlgorithm()` @*/ PetscErrorCode PCMGGalerkinGetMatProductAlgorithm(PC pc, const char *name[]) { PetscFunctionBegin; PetscValidHeaderSpecific(pc, PC_CLASSID, 1); PetscTryMethod(pc, "PCMGGalerkinGetMatProductAlgorithm_C", (PC, const char *[]), (pc, name)); PetscFunctionReturn(PETSC_SUCCESS); } /*MC PCHYPRE - Allows you to use the matrix element based preconditioners in the LLNL package hypre as PETSc `PC` Options Database Keys: + -pc_hypre_type - One of `euclid`, `pilut`, `parasails`, `boomeramg`, `ams`, or `ads` . -pc_hypre_boomeramg_nodal_coarsen <n> - where n is from 1 to 6 (see `HYPRE_BOOMERAMGSetNodal()`) . -pc_hypre_boomeramg_vec_interp_variant <v> - where v is from 1 to 3 (see `HYPRE_BoomerAMGSetInterpVecVariant()`) - Many others, run with `-pc_type hypre` `-pc_hypre_type XXX` `-help` to see options for the XXX preconditioner Level: intermediate Notes: Apart from `-pc_hypre_type` (for which there is `PCHYPRESetType()`), the many hypre options can ONLY be set via the options database (e.g. the command line or with `PetscOptionsSetValue()`, there are no functions to set them) The options `-pc_hypre_boomeramg_max_iter` and `-pc_hypre_boomeramg_tol` refer to the number of iterations (V-cycles) and tolerance that boomerAMG does EACH time it is called. So for example, if `-pc_hypre_boomeramg_max_iter` is set to 2 then 2-V-cycles are being used to define the preconditioner (`-pc_hypre_boomeramg_tol` should be set to 0.0 - the default - to strictly use a fixed number of iterations per hypre call). `-ksp_max_it` and `-ksp_rtol` STILL determine the total number of iterations and tolerance for the Krylov solver. For example, if `-pc_hypre_boomeramg_max_iter` is 2 and `-ksp_max_it` is 10 then AT MOST twenty V-cycles of boomeramg will be used. Note that the option `-pc_hypre_boomeramg_relax_type_all` defaults to symmetric relaxation (symmetric-SOR/Jacobi), which is required for Krylov solvers like CG that expect symmetry. Otherwise, you may want to use `-pc_hypre_boomeramg_relax_type_all SOR/Jacobi`. `MatSetNearNullSpace()` - if you provide a near null space to your matrix it is ignored by hypre UNLESS you also use the following two options: `-pc_hypre_boomeramg_nodal_coarsen <n> -pc_hypre_boomeramg_vec_interp_variant <v>` See `PCPFMG`, `PCSMG`, and `PCSYSPFMG` for access to hypre's other (nonalgebraic) multigrid solvers For `PCHYPRE` type of `ams` or `ads` auxiliary data must be provided to the preconditioner with `PCHYPRESetDiscreteGradient()`, `PCHYPRESetDiscreteCurl()`, `PCHYPRESetInterpolations()`, `PCHYPRESetAlphaPoissonMatrix()`, `PCHYPRESetBetaPoissonMatrix()`, `PCHYPRESetEdgeConstantVectors()`, `PCHYPREAMSSetInteriorNodes()` Sometimes people want to try algebraic multigrid as a "standalone" solver, that is not accelerating it with a Krylov method. Though we generally do not recommend this since it is usually slower, one should use a `KSPType` of `KSPRICHARDSON` (or equivalently `-ksp_type richardson`) to achieve this. Using `KSPPREONLY` will not work since it only applies a single cycle of multigrid. PETSc provides its own geometric and algebraic multigrid solvers `PCMG` and `PCGAMG`, also see `PCHMG` which is useful for certain multicomponent problems GPU Notes: To configure hypre BoomerAMG so that it can utilize NVIDIA GPUs run ./configure --download-hypre --with-cuda Then pass `VECCUDA` vectors and `MATAIJCUSPARSE` matrices to the solvers and PETSc will automatically utilize hypre's GPU solvers. To configure hypre BoomerAMG so that it can utilize AMD GPUs run ./configure --download-hypre --with-hip Then pass `VECHIP` vectors to the solvers and PETSc will automatically utilize hypre's GPU solvers. .seealso: `PCCreate()`, `PCSetType()`, `PCType`, `PC`, `PCHYPRESetType()`, `PCPFMG`, `PCGAMG`, `PCSYSPFMG`, `PCSMG`, `PCHYPRESetDiscreteGradient()`, `PCHYPRESetDiscreteCurl()`, `PCHYPRESetInterpolations()`, `PCHYPRESetAlphaPoissonMatrix()`, `PCHYPRESetBetaPoissonMatrix()`, `PCHYPRESetEdgeConstantVectors()`, PCHYPREAMSSetInteriorNodes() M*/ PETSC_EXTERN PetscErrorCode PCCreate_HYPRE(PC pc) { PC_HYPRE *jac; PetscFunctionBegin; PetscCall(PetscNew(&jac)); pc->data = jac; pc->ops->reset = PCReset_HYPRE; pc->ops->destroy = PCDestroy_HYPRE; pc->ops->setfromoptions = PCSetFromOptions_HYPRE; pc->ops->setup = PCSetUp_HYPRE; pc->ops->apply = PCApply_HYPRE; jac->comm_hypre = MPI_COMM_NULL; PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPRESetType_C", PCHYPRESetType_HYPRE)); PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPREGetType_C", PCHYPREGetType_HYPRE)); PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCSetCoordinates_C", PCSetCoordinates_HYPRE)); PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPRESetDiscreteGradient_C", PCHYPRESetDiscreteGradient_HYPRE)); PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPRESetDiscreteCurl_C", PCHYPRESetDiscreteCurl_HYPRE)); PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPRESetInterpolations_C", PCHYPRESetInterpolations_HYPRE)); PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPRESetEdgeConstantVectors_C", PCHYPRESetEdgeConstantVectors_HYPRE)); PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPREAMSSetInteriorNodes_C", PCHYPREAMSSetInteriorNodes_HYPRE)); PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPRESetPoissonMatrix_C", PCHYPRESetPoissonMatrix_HYPRE)); PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCMGGalerkinSetMatProductAlgorithm_C", PCMGGalerkinSetMatProductAlgorithm_HYPRE_BoomerAMG)); PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCMGGalerkinGetMatProductAlgorithm_C", PCMGGalerkinGetMatProductAlgorithm_HYPRE_BoomerAMG)); #if defined(PETSC_HAVE_HYPRE_DEVICE) #if defined(HYPRE_USING_HIP) PetscCall(PetscDeviceInitialize(PETSC_DEVICE_HIP)); #endif #if defined(HYPRE_USING_CUDA) PetscCall(PetscDeviceInitialize(PETSC_DEVICE_CUDA)); #endif #endif PetscHYPREInitialize(); PetscFunctionReturn(PETSC_SUCCESS); } typedef struct { MPI_Comm hcomm; /* does not share comm with HYPRE_StructMatrix because need to create solver before getting matrix */ HYPRE_StructSolver hsolver; /* keep copy of PFMG options used so may view them */ PetscInt its; double tol; PetscInt relax_type; PetscInt rap_type; PetscInt num_pre_relax, num_post_relax; PetscInt max_levels; PetscInt skip_relax; PetscBool print_statistics; } PC_PFMG; static PetscErrorCode PCDestroy_PFMG(PC pc) { PC_PFMG *ex = (PC_PFMG *)pc->data; PetscFunctionBegin; if (ex->hsolver) PetscCallExternal(HYPRE_StructPFMGDestroy, ex->hsolver); PetscCall(PetscCommRestoreComm(PetscObjectComm((PetscObject)pc), &ex->hcomm)); PetscCall(PetscFree(pc->data)); PetscFunctionReturn(PETSC_SUCCESS); } static const char *PFMGRelaxType[] = {"Jacobi", "Weighted-Jacobi", "symmetric-Red/Black-Gauss-Seidel", "Red/Black-Gauss-Seidel"}; static const char *PFMGRAPType[] = {"Galerkin", "non-Galerkin"}; static PetscErrorCode PCView_PFMG(PC pc, PetscViewer viewer) { PetscBool iascii; PC_PFMG *ex = (PC_PFMG *)pc->data; PetscFunctionBegin; PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii)); if (iascii) { PetscCall(PetscViewerASCIIPrintf(viewer, " HYPRE PFMG preconditioning\n")); PetscCall(PetscViewerASCIIPrintf(viewer, " max iterations %" PetscInt_FMT "\n", ex->its)); PetscCall(PetscViewerASCIIPrintf(viewer, " tolerance %g\n", ex->tol)); PetscCall(PetscViewerASCIIPrintf(viewer, " relax type %s\n", PFMGRelaxType[ex->relax_type])); PetscCall(PetscViewerASCIIPrintf(viewer, " RAP type %s\n", PFMGRAPType[ex->rap_type])); PetscCall(PetscViewerASCIIPrintf(viewer, " number pre-relax %" PetscInt_FMT " post-relax %" PetscInt_FMT "\n", ex->num_pre_relax, ex->num_post_relax)); PetscCall(PetscViewerASCIIPrintf(viewer, " max levels %" PetscInt_FMT "\n", ex->max_levels)); PetscCall(PetscViewerASCIIPrintf(viewer, " skip relax %" PetscInt_FMT "\n", ex->skip_relax)); } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCSetFromOptions_PFMG(PC pc, PetscOptionItems *PetscOptionsObject) { PC_PFMG *ex = (PC_PFMG *)pc->data; PetscFunctionBegin; PetscOptionsHeadBegin(PetscOptionsObject, "PFMG options"); PetscCall(PetscOptionsBool("-pc_pfmg_print_statistics", "Print statistics", "HYPRE_StructPFMGSetPrintLevel", ex->print_statistics, &ex->print_statistics, NULL)); PetscCall(PetscOptionsInt("-pc_pfmg_its", "Number of iterations of PFMG to use as preconditioner", "HYPRE_StructPFMGSetMaxIter", ex->its, &ex->its, NULL)); PetscCallExternal(HYPRE_StructPFMGSetMaxIter, ex->hsolver, ex->its); PetscCall(PetscOptionsInt("-pc_pfmg_num_pre_relax", "Number of smoothing steps before coarse grid", "HYPRE_StructPFMGSetNumPreRelax", ex->num_pre_relax, &ex->num_pre_relax, NULL)); PetscCallExternal(HYPRE_StructPFMGSetNumPreRelax, ex->hsolver, ex->num_pre_relax); PetscCall(PetscOptionsInt("-pc_pfmg_num_post_relax", "Number of smoothing steps after coarse grid", "HYPRE_StructPFMGSetNumPostRelax", ex->num_post_relax, &ex->num_post_relax, NULL)); PetscCallExternal(HYPRE_StructPFMGSetNumPostRelax, ex->hsolver, ex->num_post_relax); PetscCall(PetscOptionsInt("-pc_pfmg_max_levels", "Max Levels for MG hierarchy", "HYPRE_StructPFMGSetMaxLevels", ex->max_levels, &ex->max_levels, NULL)); PetscCallExternal(HYPRE_StructPFMGSetMaxLevels, ex->hsolver, ex->max_levels); PetscCall(PetscOptionsReal("-pc_pfmg_tol", "Tolerance of PFMG", "HYPRE_StructPFMGSetTol", ex->tol, &ex->tol, NULL)); PetscCallExternal(HYPRE_StructPFMGSetTol, ex->hsolver, ex->tol); PetscCall(PetscOptionsEList("-pc_pfmg_relax_type", "Relax type for the up and down cycles", "HYPRE_StructPFMGSetRelaxType", PFMGRelaxType, PETSC_STATIC_ARRAY_LENGTH(PFMGRelaxType), PFMGRelaxType[ex->relax_type], &ex->relax_type, NULL)); PetscCallExternal(HYPRE_StructPFMGSetRelaxType, ex->hsolver, ex->relax_type); PetscCall(PetscOptionsEList("-pc_pfmg_rap_type", "RAP type", "HYPRE_StructPFMGSetRAPType", PFMGRAPType, PETSC_STATIC_ARRAY_LENGTH(PFMGRAPType), PFMGRAPType[ex->rap_type], &ex->rap_type, NULL)); PetscCallExternal(HYPRE_StructPFMGSetRAPType, ex->hsolver, ex->rap_type); PetscCall(PetscOptionsInt("-pc_pfmg_skip_relax", "Skip relaxation on certain grids for isotropic problems. This can greatly improve efficiency by eliminating unnecessary relaxations when the underlying problem is isotropic", "HYPRE_StructPFMGSetSkipRelax", ex->skip_relax, &ex->skip_relax, NULL)); PetscCallExternal(HYPRE_StructPFMGSetSkipRelax, ex->hsolver, ex->skip_relax); PetscOptionsHeadEnd(); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCApply_PFMG(PC pc, Vec x, Vec y) { PC_PFMG *ex = (PC_PFMG *)pc->data; PetscScalar *yy; const PetscScalar *xx; PetscInt ilower[3], iupper[3]; HYPRE_Int hlower[3], hupper[3]; Mat_HYPREStruct *mx = (Mat_HYPREStruct *)(pc->pmat->data); PetscFunctionBegin; PetscCall(PetscCitationsRegister(hypreCitation, &cite)); PetscCall(DMDAGetCorners(mx->da, &ilower[0], &ilower[1], &ilower[2], &iupper[0], &iupper[1], &iupper[2])); /* when HYPRE_MIXEDINT is defined, sizeof(HYPRE_Int) == 32 */ iupper[0] += ilower[0] - 1; iupper[1] += ilower[1] - 1; iupper[2] += ilower[2] - 1; hlower[0] = (HYPRE_Int)ilower[0]; hlower[1] = (HYPRE_Int)ilower[1]; hlower[2] = (HYPRE_Int)ilower[2]; hupper[0] = (HYPRE_Int)iupper[0]; hupper[1] = (HYPRE_Int)iupper[1]; hupper[2] = (HYPRE_Int)iupper[2]; /* copy x values over to hypre */ PetscCallExternal(HYPRE_StructVectorSetConstantValues, mx->hb, 0.0); PetscCall(VecGetArrayRead(x, &xx)); PetscCallExternal(HYPRE_StructVectorSetBoxValues, mx->hb, hlower, hupper, (HYPRE_Complex *)xx); PetscCall(VecRestoreArrayRead(x, &xx)); PetscCallExternal(HYPRE_StructVectorAssemble, mx->hb); PetscCallExternal(HYPRE_StructPFMGSolve, ex->hsolver, mx->hmat, mx->hb, mx->hx); /* copy solution values back to PETSc */ PetscCall(VecGetArray(y, &yy)); PetscCallExternal(HYPRE_StructVectorGetBoxValues, mx->hx, hlower, hupper, (HYPRE_Complex *)yy); PetscCall(VecRestoreArray(y, &yy)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCApplyRichardson_PFMG(PC pc, Vec b, Vec y, Vec w, PetscReal rtol, PetscReal abstol, PetscReal dtol, PetscInt its, PetscBool guesszero, PetscInt *outits, PCRichardsonConvergedReason *reason) { PC_PFMG *jac = (PC_PFMG *)pc->data; HYPRE_Int oits; PetscFunctionBegin; PetscCall(PetscCitationsRegister(hypreCitation, &cite)); PetscCallExternal(HYPRE_StructPFMGSetMaxIter, jac->hsolver, its * jac->its); PetscCallExternal(HYPRE_StructPFMGSetTol, jac->hsolver, rtol); PetscCall(PCApply_PFMG(pc, b, y)); PetscCallExternal(HYPRE_StructPFMGGetNumIterations, jac->hsolver, &oits); *outits = oits; if (oits == its) *reason = PCRICHARDSON_CONVERGED_ITS; else *reason = PCRICHARDSON_CONVERGED_RTOL; PetscCallExternal(HYPRE_StructPFMGSetTol, jac->hsolver, jac->tol); PetscCallExternal(HYPRE_StructPFMGSetMaxIter, jac->hsolver, jac->its); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCSetUp_PFMG(PC pc) { PC_PFMG *ex = (PC_PFMG *)pc->data; Mat_HYPREStruct *mx = (Mat_HYPREStruct *)(pc->pmat->data); PetscBool flg; PetscFunctionBegin; PetscCall(PetscObjectTypeCompare((PetscObject)pc->pmat, MATHYPRESTRUCT, &flg)); PetscCheck(flg, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_INCOMP, "Must use MATHYPRESTRUCT with this preconditioner"); /* create the hypre solver object and set its information */ if (ex->hsolver) PetscCallExternal(HYPRE_StructPFMGDestroy, ex->hsolver); PetscCallExternal(HYPRE_StructPFMGCreate, ex->hcomm, &ex->hsolver); // Print Hypre statistics about the solve process if (ex->print_statistics) PetscCallExternal(HYPRE_StructPFMGSetPrintLevel, ex->hsolver, 3); // The hypre options must be repeated here because the StructPFMG was destroyed and recreated PetscCallExternal(HYPRE_StructPFMGSetMaxIter, ex->hsolver, ex->its); PetscCallExternal(HYPRE_StructPFMGSetNumPreRelax, ex->hsolver, ex->num_pre_relax); PetscCallExternal(HYPRE_StructPFMGSetNumPostRelax, ex->hsolver, ex->num_post_relax); PetscCallExternal(HYPRE_StructPFMGSetMaxLevels, ex->hsolver, ex->max_levels); PetscCallExternal(HYPRE_StructPFMGSetTol, ex->hsolver, ex->tol); PetscCallExternal(HYPRE_StructPFMGSetRelaxType, ex->hsolver, ex->relax_type); PetscCallExternal(HYPRE_StructPFMGSetRAPType, ex->hsolver, ex->rap_type); PetscCallExternal(HYPRE_StructPFMGSetup, ex->hsolver, mx->hmat, mx->hb, mx->hx); PetscCallExternal(HYPRE_StructPFMGSetZeroGuess, ex->hsolver); PetscFunctionReturn(PETSC_SUCCESS); } /*MC PCPFMG - the hypre PFMG multigrid solver Options Database Keys: + -pc_pfmg_its <its> - number of iterations of PFMG to use as preconditioner . -pc_pfmg_num_pre_relax <steps> - number of smoothing steps before coarse grid solve . -pc_pfmg_num_post_relax <steps> - number of smoothing steps after coarse grid solve . -pc_pfmg_tol <tol> - tolerance of PFMG . -pc_pfmg_relax_type - relaxation type for the up and down cycles, one of Jacobi,Weighted-Jacobi,symmetric-Red/Black-Gauss-Seidel,Red/Black-Gauss-Seidel . -pc_pfmg_rap_type - type of coarse matrix generation, one of Galerkin,non-Galerkin - -pc_pfmg_skip_relax - skip relaxation on certain grids for isotropic problems. This can greatly improve efficiency by eliminating unnecessary relaxations when the underlying problem is isotropic, one of 0,1 Level: advanced Notes: This is for CELL-centered descretizations See `PCSYSPFMG` for a version suitable for systems of PDEs, and `PCSMG` See `PCHYPRE` for hypre's BoomerAMG algebraic multigrid solver This must be used with the `MATHYPRESTRUCT` matrix type. This provides only some of the functionality of PFMG, it supports only one block per process defined by a PETSc `DMDA`. .seealso: `PCMG`, `MATHYPRESTRUCT`, `PCHYPRE`, `PCGAMG`, `PCSYSPFMG`, `PCSMG` M*/ PETSC_EXTERN PetscErrorCode PCCreate_PFMG(PC pc) { PC_PFMG *ex; PetscFunctionBegin; PetscCall(PetscNew(&ex)); pc->data = ex; ex->its = 1; ex->tol = 1.e-8; ex->relax_type = 1; ex->rap_type = 0; ex->num_pre_relax = 1; ex->num_post_relax = 1; ex->max_levels = 0; ex->skip_relax = 0; ex->print_statistics = PETSC_FALSE; pc->ops->setfromoptions = PCSetFromOptions_PFMG; pc->ops->view = PCView_PFMG; pc->ops->destroy = PCDestroy_PFMG; pc->ops->apply = PCApply_PFMG; pc->ops->applyrichardson = PCApplyRichardson_PFMG; pc->ops->setup = PCSetUp_PFMG; PetscCall(PetscCommGetComm(PetscObjectComm((PetscObject)pc), &ex->hcomm)); PetscHYPREInitialize(); PetscCallExternal(HYPRE_StructPFMGCreate, ex->hcomm, &ex->hsolver); PetscFunctionReturn(PETSC_SUCCESS); } /* we know we are working with a HYPRE_SStructMatrix */ typedef struct { MPI_Comm hcomm; /* does not share comm with HYPRE_SStructMatrix because need to create solver before getting matrix */ HYPRE_SStructSolver ss_solver; /* keep copy of SYSPFMG options used so may view them */ PetscInt its; double tol; PetscInt relax_type; PetscInt num_pre_relax, num_post_relax; } PC_SysPFMG; static PetscErrorCode PCDestroy_SysPFMG(PC pc) { PC_SysPFMG *ex = (PC_SysPFMG *)pc->data; PetscFunctionBegin; if (ex->ss_solver) PetscCallExternal(HYPRE_SStructSysPFMGDestroy, ex->ss_solver); PetscCall(PetscCommRestoreComm(PetscObjectComm((PetscObject)pc), &ex->hcomm)); PetscCall(PetscFree(pc->data)); PetscFunctionReturn(PETSC_SUCCESS); } static const char *SysPFMGRelaxType[] = {"Weighted-Jacobi", "Red/Black-Gauss-Seidel"}; static PetscErrorCode PCView_SysPFMG(PC pc, PetscViewer viewer) { PetscBool iascii; PC_SysPFMG *ex = (PC_SysPFMG *)pc->data; PetscFunctionBegin; PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii)); if (iascii) { PetscCall(PetscViewerASCIIPrintf(viewer, " HYPRE SysPFMG preconditioning\n")); PetscCall(PetscViewerASCIIPrintf(viewer, " max iterations %" PetscInt_FMT "\n", ex->its)); PetscCall(PetscViewerASCIIPrintf(viewer, " tolerance %g\n", ex->tol)); PetscCall(PetscViewerASCIIPrintf(viewer, " relax type %s\n", PFMGRelaxType[ex->relax_type])); PetscCall(PetscViewerASCIIPrintf(viewer, " number pre-relax %" PetscInt_FMT " post-relax %" PetscInt_FMT "\n", ex->num_pre_relax, ex->num_post_relax)); } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCSetFromOptions_SysPFMG(PC pc, PetscOptionItems *PetscOptionsObject) { PC_SysPFMG *ex = (PC_SysPFMG *)pc->data; PetscBool flg = PETSC_FALSE; PetscFunctionBegin; PetscOptionsHeadBegin(PetscOptionsObject, "SysPFMG options"); PetscCall(PetscOptionsBool("-pc_syspfmg_print_statistics", "Print statistics", "HYPRE_SStructSysPFMGSetPrintLevel", flg, &flg, NULL)); if (flg) PetscCallExternal(HYPRE_SStructSysPFMGSetPrintLevel, ex->ss_solver, 3); PetscCall(PetscOptionsInt("-pc_syspfmg_its", "Number of iterations of SysPFMG to use as preconditioner", "HYPRE_SStructSysPFMGSetMaxIter", ex->its, &ex->its, NULL)); PetscCallExternal(HYPRE_SStructSysPFMGSetMaxIter, ex->ss_solver, ex->its); PetscCall(PetscOptionsInt("-pc_syspfmg_num_pre_relax", "Number of smoothing steps before coarse grid", "HYPRE_SStructSysPFMGSetNumPreRelax", ex->num_pre_relax, &ex->num_pre_relax, NULL)); PetscCallExternal(HYPRE_SStructSysPFMGSetNumPreRelax, ex->ss_solver, ex->num_pre_relax); PetscCall(PetscOptionsInt("-pc_syspfmg_num_post_relax", "Number of smoothing steps after coarse grid", "HYPRE_SStructSysPFMGSetNumPostRelax", ex->num_post_relax, &ex->num_post_relax, NULL)); PetscCallExternal(HYPRE_SStructSysPFMGSetNumPostRelax, ex->ss_solver, ex->num_post_relax); PetscCall(PetscOptionsReal("-pc_syspfmg_tol", "Tolerance of SysPFMG", "HYPRE_SStructSysPFMGSetTol", ex->tol, &ex->tol, NULL)); PetscCallExternal(HYPRE_SStructSysPFMGSetTol, ex->ss_solver, ex->tol); PetscCall(PetscOptionsEList("-pc_syspfmg_relax_type", "Relax type for the up and down cycles", "HYPRE_SStructSysPFMGSetRelaxType", SysPFMGRelaxType, PETSC_STATIC_ARRAY_LENGTH(SysPFMGRelaxType), SysPFMGRelaxType[ex->relax_type], &ex->relax_type, NULL)); PetscCallExternal(HYPRE_SStructSysPFMGSetRelaxType, ex->ss_solver, ex->relax_type); PetscOptionsHeadEnd(); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCApply_SysPFMG(PC pc, Vec x, Vec y) { PC_SysPFMG *ex = (PC_SysPFMG *)pc->data; PetscScalar *yy; const PetscScalar *xx; PetscInt ilower[3], iupper[3]; HYPRE_Int hlower[3], hupper[3]; Mat_HYPRESStruct *mx = (Mat_HYPRESStruct *)(pc->pmat->data); PetscInt ordering = mx->dofs_order; PetscInt nvars = mx->nvars; PetscInt part = 0; PetscInt size; PetscInt i; PetscFunctionBegin; PetscCall(PetscCitationsRegister(hypreCitation, &cite)); PetscCall(DMDAGetCorners(mx->da, &ilower[0], &ilower[1], &ilower[2], &iupper[0], &iupper[1], &iupper[2])); /* when HYPRE_MIXEDINT is defined, sizeof(HYPRE_Int) == 32 */ iupper[0] += ilower[0] - 1; iupper[1] += ilower[1] - 1; iupper[2] += ilower[2] - 1; hlower[0] = (HYPRE_Int)ilower[0]; hlower[1] = (HYPRE_Int)ilower[1]; hlower[2] = (HYPRE_Int)ilower[2]; hupper[0] = (HYPRE_Int)iupper[0]; hupper[1] = (HYPRE_Int)iupper[1]; hupper[2] = (HYPRE_Int)iupper[2]; size = 1; for (i = 0; i < 3; i++) size *= (iupper[i] - ilower[i] + 1); /* copy x values over to hypre for variable ordering */ if (ordering) { PetscCallExternal(HYPRE_SStructVectorSetConstantValues, mx->ss_b, 0.0); PetscCall(VecGetArrayRead(x, &xx)); for (i = 0; i < nvars; i++) PetscCallExternal(HYPRE_SStructVectorSetBoxValues, mx->ss_b, part, hlower, hupper, i, (HYPRE_Complex *)(xx + (size * i))); PetscCall(VecRestoreArrayRead(x, &xx)); PetscCallExternal(HYPRE_SStructVectorAssemble, mx->ss_b); PetscCallExternal(HYPRE_SStructMatrixMatvec, 1.0, mx->ss_mat, mx->ss_b, 0.0, mx->ss_x); PetscCallExternal(HYPRE_SStructSysPFMGSolve, ex->ss_solver, mx->ss_mat, mx->ss_b, mx->ss_x); /* copy solution values back to PETSc */ PetscCall(VecGetArray(y, &yy)); for (i = 0; i < nvars; i++) PetscCallExternal(HYPRE_SStructVectorGetBoxValues, mx->ss_x, part, hlower, hupper, i, (HYPRE_Complex *)(yy + (size * i))); PetscCall(VecRestoreArray(y, &yy)); } else { /* nodal ordering must be mapped to variable ordering for sys_pfmg */ PetscScalar *z; PetscInt j, k; PetscCall(PetscMalloc1(nvars * size, &z)); PetscCallExternal(HYPRE_SStructVectorSetConstantValues, mx->ss_b, 0.0); PetscCall(VecGetArrayRead(x, &xx)); /* transform nodal to hypre's variable ordering for sys_pfmg */ for (i = 0; i < size; i++) { k = i * nvars; for (j = 0; j < nvars; j++) z[j * size + i] = xx[k + j]; } for (i = 0; i < nvars; i++) PetscCallExternal(HYPRE_SStructVectorSetBoxValues, mx->ss_b, part, hlower, hupper, i, (HYPRE_Complex *)(z + (size * i))); PetscCall(VecRestoreArrayRead(x, &xx)); PetscCallExternal(HYPRE_SStructVectorAssemble, mx->ss_b); PetscCallExternal(HYPRE_SStructSysPFMGSolve, ex->ss_solver, mx->ss_mat, mx->ss_b, mx->ss_x); /* copy solution values back to PETSc */ PetscCall(VecGetArray(y, &yy)); for (i = 0; i < nvars; i++) PetscCallExternal(HYPRE_SStructVectorGetBoxValues, mx->ss_x, part, hlower, hupper, i, (HYPRE_Complex *)(z + (size * i))); /* transform hypre's variable ordering for sys_pfmg to nodal ordering */ for (i = 0; i < size; i++) { k = i * nvars; for (j = 0; j < nvars; j++) yy[k + j] = z[j * size + i]; } PetscCall(VecRestoreArray(y, &yy)); PetscCall(PetscFree(z)); } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCApplyRichardson_SysPFMG(PC pc, Vec b, Vec y, Vec w, PetscReal rtol, PetscReal abstol, PetscReal dtol, PetscInt its, PetscBool guesszero, PetscInt *outits, PCRichardsonConvergedReason *reason) { PC_SysPFMG *jac = (PC_SysPFMG *)pc->data; HYPRE_Int oits; PetscFunctionBegin; PetscCall(PetscCitationsRegister(hypreCitation, &cite)); PetscCallExternal(HYPRE_SStructSysPFMGSetMaxIter, jac->ss_solver, its * jac->its); PetscCallExternal(HYPRE_SStructSysPFMGSetTol, jac->ss_solver, rtol); PetscCall(PCApply_SysPFMG(pc, b, y)); PetscCallExternal(HYPRE_SStructSysPFMGGetNumIterations, jac->ss_solver, &oits); *outits = oits; if (oits == its) *reason = PCRICHARDSON_CONVERGED_ITS; else *reason = PCRICHARDSON_CONVERGED_RTOL; PetscCallExternal(HYPRE_SStructSysPFMGSetTol, jac->ss_solver, jac->tol); PetscCallExternal(HYPRE_SStructSysPFMGSetMaxIter, jac->ss_solver, jac->its); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCSetUp_SysPFMG(PC pc) { PC_SysPFMG *ex = (PC_SysPFMG *)pc->data; Mat_HYPRESStruct *mx = (Mat_HYPRESStruct *)(pc->pmat->data); PetscBool flg; PetscFunctionBegin; PetscCall(PetscObjectTypeCompare((PetscObject)pc->pmat, MATHYPRESSTRUCT, &flg)); PetscCheck(flg, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_INCOMP, "Must use MATHYPRESSTRUCT with this preconditioner"); /* create the hypre sstruct solver object and set its information */ if (ex->ss_solver) PetscCallExternal(HYPRE_SStructSysPFMGDestroy, ex->ss_solver); PetscCallExternal(HYPRE_SStructSysPFMGCreate, ex->hcomm, &ex->ss_solver); PetscCallExternal(HYPRE_SStructSysPFMGSetZeroGuess, ex->ss_solver); PetscCallExternal(HYPRE_SStructSysPFMGSetup, ex->ss_solver, mx->ss_mat, mx->ss_b, mx->ss_x); PetscFunctionReturn(PETSC_SUCCESS); } /*MC PCSYSPFMG - the hypre SysPFMG multigrid solver Level: advanced Options Database Keys: + -pc_syspfmg_its <its> - number of iterations of SysPFMG to use as preconditioner . -pc_syspfmg_num_pre_relax <steps> - number of smoothing steps before coarse grid . -pc_syspfmg_num_post_relax <steps> - number of smoothing steps after coarse grid . -pc_syspfmg_tol <tol> - tolerance of SysPFMG - -pc_syspfmg_relax_type <Weighted-Jacobi,Red/Black-Gauss-Seidel> - relaxation type for the up and down cycles Notes: See `PCPFMG` for hypre's PFMG that works for a scalar PDE and `PCSMG` See `PCHYPRE` for hypre's BoomerAMG algebraic multigrid solver This is for CELL-centered descretizations This must be used with the `MATHYPRESSTRUCT` matrix type. This does not give access to all the functionality of hypres SysPFMG, it supports only one part, and one block per process defined by a PETSc `DMDA`. .seealso: `PCMG`, `MATHYPRESSTRUCT`, `PCPFMG`, `PCHYPRE`, `PCGAMG`, `PCSMG` M*/ PETSC_EXTERN PetscErrorCode PCCreate_SysPFMG(PC pc) { PC_SysPFMG *ex; PetscFunctionBegin; PetscCall(PetscNew(&ex)); pc->data = ex; ex->its = 1; ex->tol = 1.e-8; ex->relax_type = 1; ex->num_pre_relax = 1; ex->num_post_relax = 1; pc->ops->setfromoptions = PCSetFromOptions_SysPFMG; pc->ops->view = PCView_SysPFMG; pc->ops->destroy = PCDestroy_SysPFMG; pc->ops->apply = PCApply_SysPFMG; pc->ops->applyrichardson = PCApplyRichardson_SysPFMG; pc->ops->setup = PCSetUp_SysPFMG; PetscCall(PetscCommGetComm(PetscObjectComm((PetscObject)pc), &ex->hcomm)); PetscHYPREInitialize(); PetscCallExternal(HYPRE_SStructSysPFMGCreate, ex->hcomm, &ex->ss_solver); PetscFunctionReturn(PETSC_SUCCESS); } /* PC SMG */ typedef struct { MPI_Comm hcomm; /* does not share comm with HYPRE_StructMatrix because need to create solver before getting matrix */ HYPRE_StructSolver hsolver; PetscInt its; /* keep copy of SMG options used so may view them */ double tol; PetscBool print_statistics; PetscInt num_pre_relax, num_post_relax; } PC_SMG; static PetscErrorCode PCDestroy_SMG(PC pc) { PC_SMG *ex = (PC_SMG *)pc->data; PetscFunctionBegin; if (ex->hsolver) PetscCallExternal(HYPRE_StructSMGDestroy, ex->hsolver); PetscCall(PetscCommRestoreComm(PetscObjectComm((PetscObject)pc), &ex->hcomm)); PetscCall(PetscFree(pc->data)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCView_SMG(PC pc, PetscViewer viewer) { PetscBool iascii; PC_SMG *ex = (PC_SMG *)pc->data; PetscFunctionBegin; PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii)); if (iascii) { PetscCall(PetscViewerASCIIPrintf(viewer, " HYPRE SMG preconditioning\n")); PetscCall(PetscViewerASCIIPrintf(viewer, " max iterations %" PetscInt_FMT "\n", ex->its)); PetscCall(PetscViewerASCIIPrintf(viewer, " tolerance %g\n", ex->tol)); PetscCall(PetscViewerASCIIPrintf(viewer, " number pre-relax %" PetscInt_FMT " post-relax %" PetscInt_FMT "\n", ex->num_pre_relax, ex->num_post_relax)); } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCSetFromOptions_SMG(PC pc, PetscOptionItems *PetscOptionsObject) { PC_SMG *ex = (PC_SMG *)pc->data; PetscFunctionBegin; PetscOptionsHeadBegin(PetscOptionsObject, "SMG options"); PetscCall(PetscOptionsInt("-pc_smg_its", "Number of iterations of SMG to use as preconditioner", "HYPRE_StructSMGSetMaxIter", ex->its, &ex->its, NULL)); PetscCall(PetscOptionsInt("-pc_smg_num_pre_relax", "Number of smoothing steps before coarse grid", "HYPRE_StructSMGSetNumPreRelax", ex->num_pre_relax, &ex->num_pre_relax, NULL)); PetscCall(PetscOptionsInt("-pc_smg_num_post_relax", "Number of smoothing steps after coarse grid", "HYPRE_StructSMGSetNumPostRelax", ex->num_post_relax, &ex->num_post_relax, NULL)); PetscCall(PetscOptionsReal("-pc_smg_tol", "Tolerance of SMG", "HYPRE_StructSMGSetTol", ex->tol, &ex->tol, NULL)); PetscOptionsHeadEnd(); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCApply_SMG(PC pc, Vec x, Vec y) { PC_SMG *ex = (PC_SMG *)pc->data; PetscScalar *yy; const PetscScalar *xx; PetscInt ilower[3], iupper[3]; HYPRE_Int hlower[3], hupper[3]; Mat_HYPREStruct *mx = (Mat_HYPREStruct *)(pc->pmat->data); PetscFunctionBegin; PetscCall(PetscCitationsRegister(hypreCitation, &cite)); PetscCall(DMDAGetCorners(mx->da, &ilower[0], &ilower[1], &ilower[2], &iupper[0], &iupper[1], &iupper[2])); /* when HYPRE_MIXEDINT is defined, sizeof(HYPRE_Int) == 32 */ iupper[0] += ilower[0] - 1; iupper[1] += ilower[1] - 1; iupper[2] += ilower[2] - 1; hlower[0] = (HYPRE_Int)ilower[0]; hlower[1] = (HYPRE_Int)ilower[1]; hlower[2] = (HYPRE_Int)ilower[2]; hupper[0] = (HYPRE_Int)iupper[0]; hupper[1] = (HYPRE_Int)iupper[1]; hupper[2] = (HYPRE_Int)iupper[2]; /* copy x values over to hypre */ PetscCallExternal(HYPRE_StructVectorSetConstantValues, mx->hb, 0.0); PetscCall(VecGetArrayRead(x, &xx)); PetscCallExternal(HYPRE_StructVectorSetBoxValues, mx->hb, hlower, hupper, (HYPRE_Complex *)xx); PetscCall(VecRestoreArrayRead(x, &xx)); PetscCallExternal(HYPRE_StructVectorAssemble, mx->hb); PetscCallExternal(HYPRE_StructSMGSolve, ex->hsolver, mx->hmat, mx->hb, mx->hx); /* copy solution values back to PETSc */ PetscCall(VecGetArray(y, &yy)); PetscCallExternal(HYPRE_StructVectorGetBoxValues, mx->hx, hlower, hupper, (HYPRE_Complex *)yy); PetscCall(VecRestoreArray(y, &yy)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCApplyRichardson_SMG(PC pc, Vec b, Vec y, Vec w, PetscReal rtol, PetscReal abstol, PetscReal dtol, PetscInt its, PetscBool guesszero, PetscInt *outits, PCRichardsonConvergedReason *reason) { PC_SMG *jac = (PC_SMG *)pc->data; HYPRE_Int oits; PetscFunctionBegin; PetscCall(PetscCitationsRegister(hypreCitation, &cite)); PetscCallExternal(HYPRE_StructSMGSetMaxIter, jac->hsolver, its * jac->its); PetscCallExternal(HYPRE_StructSMGSetTol, jac->hsolver, rtol); PetscCall(PCApply_SMG(pc, b, y)); PetscCallExternal(HYPRE_StructSMGGetNumIterations, jac->hsolver, &oits); *outits = oits; if (oits == its) *reason = PCRICHARDSON_CONVERGED_ITS; else *reason = PCRICHARDSON_CONVERGED_RTOL; PetscCallExternal(HYPRE_StructSMGSetTol, jac->hsolver, jac->tol); PetscCallExternal(HYPRE_StructSMGSetMaxIter, jac->hsolver, jac->its); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PCSetUp_SMG(PC pc) { PetscInt i, dim; PC_SMG *ex = (PC_SMG *)pc->data; Mat_HYPREStruct *mx = (Mat_HYPREStruct *)(pc->pmat->data); PetscBool flg; DMBoundaryType p[3]; PetscInt M[3]; PetscFunctionBegin; PetscCall(PetscObjectTypeCompare((PetscObject)pc->pmat, MATHYPRESTRUCT, &flg)); PetscCheck(flg, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_INCOMP, "Must use MATHYPRESTRUCT with this preconditioner"); PetscCall(DMDAGetInfo(mx->da, &dim, &M[0], &M[1], &M[2], 0, 0, 0, 0, 0, &p[0], &p[1], &p[2], 0)); // Check if power of 2 in periodic directions for (i = 0; i < dim; i++) { if (((M[i] & (M[i] - 1)) != 0) && (p[i] == DM_BOUNDARY_PERIODIC)) { SETERRQ(PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_INCOMP, "With SMG, the number of points in a periodic direction must be a power of 2, but is here %" PetscInt_FMT ".", M[i]); } } /* create the hypre solver object and set its information */ if (ex->hsolver) PetscCallExternal(HYPRE_StructSMGDestroy, (ex->hsolver)); PetscCallExternal(HYPRE_StructSMGCreate, ex->hcomm, &ex->hsolver); // The hypre options must be set here and not in SetFromOptions because it is created here! PetscCallExternal(HYPRE_StructSMGSetMaxIter, ex->hsolver, ex->its); PetscCallExternal(HYPRE_StructSMGSetNumPreRelax, ex->hsolver, ex->num_pre_relax); PetscCallExternal(HYPRE_StructSMGSetNumPostRelax, ex->hsolver, ex->num_post_relax); PetscCallExternal(HYPRE_StructSMGSetTol, ex->hsolver, ex->tol); PetscCallExternal(HYPRE_StructSMGSetup, ex->hsolver, mx->hmat, mx->hb, mx->hx); PetscCallExternal(HYPRE_StructSMGSetZeroGuess, ex->hsolver); PetscFunctionReturn(PETSC_SUCCESS); } /*MC PCSMG - the hypre (structured grid) SMG multigrid solver Level: advanced Options Database Keys: + -pc_smg_its <its> - number of iterations of SMG to use as preconditioner . -pc_smg_num_pre_relax <steps> - number of smoothing steps before coarse grid . -pc_smg_num_post_relax <steps> - number of smoothing steps after coarse grid - -pc_smg_tol <tol> - tolerance of SMG Notes: This is for CELL-centered descretizations This must be used with the `MATHYPRESTRUCT` `MatType`. This does not provide all the functionality of hypre's SMG solver, it supports only one block per process defined by a PETSc `DMDA`. See `PCSYSPFMG`, `PCSMG`, `PCPFMG`, and `PCHYPRE` for access to hypre's other preconditioners .seealso: `PCMG`, `MATHYPRESTRUCT`, `PCPFMG`, `PCSYSPFMG`, `PCHYPRE`, `PCGAMG` M*/ PETSC_EXTERN PetscErrorCode PCCreate_SMG(PC pc) { PC_SMG *ex; PetscFunctionBegin; PetscCall(PetscNew(&ex)); pc->data = ex; ex->its = 1; ex->tol = 1.e-8; ex->num_pre_relax = 1; ex->num_post_relax = 1; pc->ops->setfromoptions = PCSetFromOptions_SMG; pc->ops->view = PCView_SMG; pc->ops->destroy = PCDestroy_SMG; pc->ops->apply = PCApply_SMG; pc->ops->applyrichardson = PCApplyRichardson_SMG; pc->ops->setup = PCSetUp_SMG; PetscCall(PetscCommGetComm(PetscObjectComm((PetscObject)pc), &ex->hcomm)); PetscHYPREInitialize(); PetscCallExternal(HYPRE_StructSMGCreate, ex->hcomm, &ex->hsolver); PetscFunctionReturn(PETSC_SUCCESS); }
fd31adfb5cd939b16f83983ccceef0beed775357
3043c25a1d282c7014ca406917cac94d4304563b
/components/at/src/at_i2s.c
af262e8c6a7fe6f18a851f1d18a3360ba162ec5b
[ "LicenseRef-scancode-other-permissive", "MIT" ]
permissive
espressif/esp-at
585180f20cfc4369009d9d32de1226889b6df5f1
282a4485b9a069861681e9566274fcf3ad6cde59
refs/heads/master
2023-08-31T08:34:29.545298
2023-07-31T10:37:19
2023-07-31T10:37:19
78,652,809
584
470
NOASSERTION
2023-08-09T02:40:08
2017-01-11T15:36:52
C
UTF-8
C
false
false
2,537
c
at_i2s.c
/* * ESPRESSIF MIT License * * Copyright (c) 2020 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on ESPRESSIF SYSTEMS ESP32 only, in which case, * it is 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 <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_system.h" #include "driver/i2s.h" #if defined(CONFIG_AT_BT_COMMAND_SUPPORT) #if defined(CONFIG_AT_BT_A2DP_COMMAND_SUPPORT) void esp_at_i2s_init(void) { i2s_config_t i2s_config = { .mode = I2S_MODE_MASTER | I2S_MODE_TX, // Only TX .sample_rate = 44100, .bits_per_sample = 16, .channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT, //2-channels .communication_format = I2S_COMM_FORMAT_I2S_MSB, .dma_buf_count = 6, .dma_buf_len = 60, .intr_alloc_flags = 0, //Default interrupt priority .tx_desc_auto_clear = true //Auto clear tx descriptor on underflow }; i2s_driver_install(0, &i2s_config, 0, NULL); i2s_pin_config_t pin_config = { .bck_io_num = CONFIG_AT_I2S_BCK_PIN, .ws_io_num = CONFIG_AT_I2S_LRCK_PIN, .data_out_num = CONFIG_AT_I2S_DATA_PIN, .data_in_num = -1 //Not used }; i2s_set_pin(0, &pin_config); } #endif #endif
67efa6ac6d0ca31af9ff6932b5f38a198bf34c21
88ae8695987ada722184307301e221e1ba3cc2fa
/third_party/libaom/source/libaom/examples/photon_noise_table.c
d3a21a48ee1375eb765f2297edaa8702b920e3ee
[ "BSD-2-Clause", "Apache-2.0", "LGPL-2.0-or-later", "MIT", "GPL-1.0-or-later", "BSD-3-Clause" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C
false
false
17,345
c
photon_noise_table.c
/* * Copyright (c) 2021, Alliance for Open Media. All rights reserved * * This source code is subject to the terms of the BSD 2 Clause License and * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License * was not distributed with this source code in the LICENSE file, you can * obtain it at www.aomedia.org/license/software. If the Alliance for Open * Media Patent License 1.0 was not distributed with this source code in the * PATENTS file, you can obtain it at www.aomedia.org/license/patent. */ // This tool creates a film grain table, for use in stills and videos, // representing the noise that one would get by shooting with a digital camera // at a given light level. Much of the noise in digital images is photon shot // noise, which is due to the characteristics of photon arrival and grows in // standard deviation as the square root of the expected number of photons // captured. // https://www.photonstophotos.net/Emil%20Martinec/noise.html#shotnoise // // The proxy used by this tool for the amount of light captured is the ISO value // such that the focal plane exposure at the time of capture would have been // mapped by a 35mm camera to the output lightness observed in the image. That // is, if one were to shoot on a 35mm camera (36×24mm sensor) at the nominal // exposure for that ISO setting, the resulting image should contain noise of // the same order of magnitude as generated by this tool. // // Example usage: // // ./photon_noise_table --width=3840 --height=2160 --iso=25600 -o noise.tbl // # Then, for example: // aomenc --film-grain-table=noise.tbl ... // # Or: // avifenc -c aom -a film-grain-table=noise.tbl ... // // The (mostly) square-root relationship between light intensity and noise // amplitude holds in linear light, but AV1 streams are most often encoded // non-linearly, and the film grain is applied to those non-linear values. // Therefore, this tool must account for the non-linearity, and this is // controlled by the optional `--transfer-function` (or `-t`) parameter, which // specifies the tone response curve that will be used when encoding the actual // image. The default for this tool is sRGB, which is approximately similar to // an encoding gamma of 1/2.2 (i.e. a decoding gamma of 2.2) though not quite // identical. // // As alluded to above, the tool assumes that the image is taken from the // entirety of a 36×24mm (“35mm format”) sensor. If that assumption does not // hold, then a “35mm-equivalent ISO value” that can be passed to the tool can // be obtained by multiplying the true ISO value by the ratio of 36×24mm to the // area that was actually used. For formats that approximately share the same // aspect ratio, this is often expressed as the square of the “equivalence // ratio” which is the ratio of their diagonals. For example, APS-C (often // ~24×16mm) is said to have an equivalence ratio of 1.5 relative to the 35mm // format, and therefore ISO 1000 on APS-C and ISO 1000×1.5² = 2250 on 35mm // produce an image of the same lightness from the same amount of light spread // onto their respective surface areas (resulting in different focal plane // exposures), and those images will thus have similar amounts of noise if the // cameras are of similar technology. https://doi.org/10.1117/1.OE.57.11.110801 // // The tool needs to know the resolution of the images to which its grain tables // will be applied so that it can know how the light on the sensor was shared // between its pixels. As a general rule, while a higher pixel count will lead // to more noise per pixel, when the final image is viewed at the same physical // size, that noise will tend to “average out” to the same amount over a given // area, since there will be more pixels in it which, in aggregate, will have // received essentially as much light. Put differently, the amount of noise // depends on the scale at which it is measured, and the decision for this tool // was to make that scale relative to the image instead of its constituent // samples. For more on this, see: // // https://www.photonstophotos.net/Emil%20Martinec/noise-p3.html#pixelsize // https://www.dpreview.com/articles/5365920428/the-effect-of-pixel-and-sensor-sizes-on-noise/2 // https://www.dpreview.com/videos/7940373140/dpreview-tv-why-lower-resolution-sensors-are-not-better-in-low-light #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "aom_dsp/grain_table.h" #include "common/args.h" #include "common/tools_common.h" static const char *exec_name; static const struct arg_enum_list transfer_functions[] = { { "bt470m", AOM_CICP_TC_BT_470_M }, { "bt470bg", AOM_CICP_TC_BT_470_B_G }, { "srgb", AOM_CICP_TC_SRGB }, { "smpte2084", AOM_CICP_TC_SMPTE_2084 }, { "hlg", AOM_CICP_TC_HLG }, ARG_ENUM_LIST_END }; static arg_def_t help_arg = ARG_DEF("h", "help", 0, "Show the available options"); static arg_def_t width_arg = ARG_DEF("w", "width", 1, "Width of the image in pixels (required)"); static arg_def_t height_arg = ARG_DEF("l", "height", 1, "Height of the image in pixels (required)"); static arg_def_t iso_arg = ARG_DEF( "i", "iso", 1, "ISO setting indicative of the light level (required)"); static arg_def_t output_arg = ARG_DEF("o", "output", 1, "Output file to which to write the film grain table (required)"); static arg_def_t transfer_function_arg = ARG_DEF_ENUM("t", "transfer-function", 1, "Transfer function used by the encoded image (default = sRGB)", transfer_functions); void usage_exit(void) { fprintf(stderr, "Usage: %s [--transfer-function=<tf>] --width=<width> " "--height=<height> --iso=<iso> --output=<output.tbl>\n", exec_name); exit(EXIT_FAILURE); } typedef struct { float (*to_linear)(float); float (*from_linear)(float); // In linear output light. This would typically be 0.18 for SDR (this matches // the definition of Standard Output Sensitivity from ISO 12232:2019), but in // HDR, we certainly do not want to consider 18% of the maximum output a // “mid-tone”, as it would be e.g. 1800 cd/m² for SMPTE ST 2084 (PQ). float mid_tone; } transfer_function_t; static const transfer_function_t *find_transfer_function( aom_transfer_characteristics_t tc); typedef struct { int width; int height; int iso_setting; const transfer_function_t *transfer_function; const char *output_filename; } photon_noise_args_t; static void parse_args(int argc, char **argv, photon_noise_args_t *photon_noise_args) { static const arg_def_t *args[] = { &help_arg, &width_arg, &height_arg, &iso_arg, &output_arg, &transfer_function_arg, NULL }; struct arg arg; int width_set = 0, height_set = 0, iso_set = 0, output_set = 0, i; photon_noise_args->transfer_function = find_transfer_function(AOM_CICP_TC_SRGB); for (i = 1; i < argc; i += arg.argv_step) { arg.argv_step = 1; if (arg_match(&arg, &help_arg, argv + i)) { arg_show_usage(stdout, args); exit(EXIT_SUCCESS); } else if (arg_match(&arg, &width_arg, argv + i)) { photon_noise_args->width = arg_parse_int(&arg); width_set = 1; } else if (arg_match(&arg, &height_arg, argv + i)) { photon_noise_args->height = arg_parse_int(&arg); height_set = 1; } else if (arg_match(&arg, &iso_arg, argv + i)) { photon_noise_args->iso_setting = arg_parse_int(&arg); iso_set = 1; } else if (arg_match(&arg, &output_arg, argv + i)) { photon_noise_args->output_filename = arg.val; output_set = 1; } else if (arg_match(&arg, &transfer_function_arg, argv + i)) { const aom_transfer_characteristics_t tc = arg_parse_enum(&arg); photon_noise_args->transfer_function = find_transfer_function(tc); } else { fatal("unrecognized argument \"%s\", see --help for available options", argv[i]); } } if (!width_set) { fprintf(stderr, "Missing required parameter --width\n"); exit(EXIT_FAILURE); } if (!height_set) { fprintf(stderr, "Missing required parameter --height\n"); exit(EXIT_FAILURE); } if (!iso_set) { fprintf(stderr, "Missing required parameter --iso\n"); exit(EXIT_FAILURE); } if (!output_set) { fprintf(stderr, "Missing required parameter --output\n"); exit(EXIT_FAILURE); } } static float maxf(float a, float b) { return a > b ? a : b; } static float minf(float a, float b) { return a < b ? a : b; } static float gamma22_to_linear(float g) { return powf(g, 2.2f); } static float gamma22_from_linear(float l) { return powf(l, 1 / 2.2f); } static float gamma28_to_linear(float g) { return powf(g, 2.8f); } static float gamma28_from_linear(float l) { return powf(l, 1 / 2.8f); } static float srgb_to_linear(float srgb) { return srgb <= 0.04045f ? srgb / 12.92f : powf((srgb + 0.055f) / 1.055f, 2.4f); } static float srgb_from_linear(float linear) { return linear <= 0.0031308f ? 12.92f * linear : 1.055f * powf(linear, 1 / 2.4f) - 0.055f; } static const float kPqM1 = 2610.f / 16384; static const float kPqM2 = 128 * 2523.f / 4096; static const float kPqC1 = 3424.f / 4096; static const float kPqC2 = 32 * 2413.f / 4096; static const float kPqC3 = 32 * 2392.f / 4096; static float pq_to_linear(float pq) { const float pq_pow_inv_m2 = powf(pq, 1.f / kPqM2); return powf(maxf(0, pq_pow_inv_m2 - kPqC1) / (kPqC2 - kPqC3 * pq_pow_inv_m2), 1.f / kPqM1); } static float pq_from_linear(float linear) { const float linear_pow_m1 = powf(linear, kPqM1); return powf((kPqC1 + kPqC2 * linear_pow_m1) / (1 + kPqC3 * linear_pow_m1), kPqM2); } // Note: it is perhaps debatable whether “linear” for HLG should be scene light // or display light. Here, it is implemented in terms of display light assuming // a nominal peak display luminance of 1000 cd/m², hence the system γ of 1.2. To // make it scene light instead, the OOTF (powf(x, 1.2f)) and its inverse should // be removed from the functions below, and the .mid_tone should be replaced // with powf(26.f / 1000, 1 / 1.2f). static const float kHlgA = 0.17883277f; static const float kHlgB = 0.28466892f; static const float kHlgC = 0.55991073f; static float hlg_to_linear(float hlg) { // EOTF = OOTF ∘ OETF⁻¹ const float linear = hlg <= 0.5f ? hlg * hlg / 3 : (expf((hlg - kHlgC) / kHlgA) + kHlgB) / 12; return powf(linear, 1.2f); } static float hlg_from_linear(float linear) { // EOTF⁻¹ = OETF ∘ OOTF⁻¹ linear = powf(linear, 1.f / 1.2f); return linear <= 1.f / 12 ? sqrtf(3 * linear) : kHlgA * logf(12 * linear - kHlgB) + kHlgC; } static const transfer_function_t *find_transfer_function( aom_transfer_characteristics_t tc) { static const transfer_function_t kGamma22TransferFunction = { .to_linear = &gamma22_to_linear, .from_linear = &gamma22_from_linear, .mid_tone = 0.18f }, kGamma28TransferFunction = { .to_linear = &gamma28_to_linear, .from_linear = &gamma28_from_linear, .mid_tone = 0.18f }, kSRgbTransferFunction = { .to_linear = &srgb_to_linear, .from_linear = &srgb_from_linear, .mid_tone = 0.18f }, kPqTransferFunction = { .to_linear = &pq_to_linear, .from_linear = &pq_from_linear, // https://www.itu.int/pub/R-REP-BT.2408-4-2021 // page 6 (PDF page 8) .mid_tone = 26.f / 10000 }, kHlgTransferFunction = { .to_linear = &hlg_to_linear, .from_linear = &hlg_from_linear, .mid_tone = 26.f / 1000 }; switch (tc) { case AOM_CICP_TC_BT_470_M: return &kGamma22TransferFunction; case AOM_CICP_TC_BT_470_B_G: return &kGamma28TransferFunction; case AOM_CICP_TC_SRGB: return &kSRgbTransferFunction; case AOM_CICP_TC_SMPTE_2084: return &kPqTransferFunction; case AOM_CICP_TC_HLG: return &kHlgTransferFunction; default: fatal("unimplemented transfer function %d", tc); } } static void generate_photon_noise(const photon_noise_args_t *photon_noise_args, aom_film_grain_t *film_grain) { // Assumes a daylight-like spectrum. // https://www.strollswithmydog.com/effective-quantum-efficiency-of-sensor/#:~:text=11%2C260%20photons/um%5E2/lx-s static const float kPhotonsPerLxSPerUm2 = 11260; // Order of magnitude for cameras in the 2010-2020 decade, taking the CFA into // account. static const float kEffectiveQuantumEfficiency = 0.20f; // Also reasonable values for current cameras. The read noise is typically // higher than this at low ISO settings but it matters less there. static const float kPhotoResponseNonUniformity = 0.005f; static const float kInputReferredReadNoise = 1.5f; // Focal plane exposure for a mid-tone (typically a 18% reflectance card), in // lx·s. const float mid_tone_exposure = 10.f / photon_noise_args->iso_setting; // In microns. Assumes a 35mm sensor (36mm × 24mm). const float pixel_area_um2 = (36000 * 24000.f) / (photon_noise_args->width * photon_noise_args->height); const float mid_tone_electrons_per_pixel = kEffectiveQuantumEfficiency * kPhotonsPerLxSPerUm2 * mid_tone_exposure * pixel_area_um2; const float max_electrons_per_pixel = mid_tone_electrons_per_pixel / photon_noise_args->transfer_function->mid_tone; int i; film_grain->num_y_points = 14; for (i = 0; i < film_grain->num_y_points; ++i) { float x = i / (film_grain->num_y_points - 1.f); const float linear = photon_noise_args->transfer_function->to_linear(x); const float electrons_per_pixel = max_electrons_per_pixel * linear; // Quadrature sum of the relevant sources of noise, in electrons rms. Photon // shot noise is sqrt(electrons) so we can skip the square root and the // squaring. // https://en.wikipedia.org/wiki/Addition_in_quadrature // https://doi.org/10.1117/3.725073 const float noise_in_electrons = sqrtf(kInputReferredReadNoise * kInputReferredReadNoise + electrons_per_pixel + (kPhotoResponseNonUniformity * kPhotoResponseNonUniformity * electrons_per_pixel * electrons_per_pixel)); const float linear_noise = noise_in_electrons / max_electrons_per_pixel; const float linear_range_start = maxf(0.f, linear - 2 * linear_noise); const float linear_range_end = minf(1.f, linear + 2 * linear_noise); const float tf_slope = (photon_noise_args->transfer_function->from_linear(linear_range_end) - photon_noise_args->transfer_function->from_linear( linear_range_start)) / (linear_range_end - linear_range_start); float encoded_noise = linear_noise * tf_slope; x = roundf(255 * x); encoded_noise = minf(255.f, roundf(255 * 7.88f * encoded_noise)); film_grain->scaling_points_y[i][0] = (int)x; film_grain->scaling_points_y[i][1] = (int)encoded_noise; } film_grain->apply_grain = 1; film_grain->update_parameters = 1; film_grain->num_cb_points = 0; film_grain->num_cr_points = 0; film_grain->scaling_shift = 8; film_grain->ar_coeff_lag = 0; film_grain->ar_coeffs_cb[0] = 0; film_grain->ar_coeffs_cr[0] = 0; film_grain->ar_coeff_shift = 6; film_grain->cb_mult = 0; film_grain->cb_luma_mult = 0; film_grain->cb_offset = 0; film_grain->cr_mult = 0; film_grain->cr_luma_mult = 0; film_grain->cr_offset = 0; film_grain->overlap_flag = 1; film_grain->random_seed = 7391; film_grain->chroma_scaling_from_luma = 0; } int main(int argc, char **argv) { photon_noise_args_t photon_noise_args; aom_film_grain_table_t film_grain_table; aom_film_grain_t film_grain; struct aom_internal_error_info error_info; memset(&photon_noise_args, 0, sizeof(photon_noise_args)); memset(&film_grain_table, 0, sizeof(film_grain_table)); memset(&film_grain, 0, sizeof(film_grain)); memset(&error_info, 0, sizeof(error_info)); exec_name = argv[0]; parse_args(argc, argv, &photon_noise_args); generate_photon_noise(&photon_noise_args, &film_grain); aom_film_grain_table_append(&film_grain_table, 0, 9223372036854775807ull, &film_grain); if (aom_film_grain_table_write(&film_grain_table, photon_noise_args.output_filename, &error_info) != AOM_CODEC_OK) { aom_film_grain_table_free(&film_grain_table); fprintf(stderr, "Failed to write film grain table"); if (error_info.has_detail) { fprintf(stderr, ": %s", error_info.detail); } fprintf(stderr, "\n"); return EXIT_FAILURE; } aom_film_grain_table_free(&film_grain_table); return EXIT_SUCCESS; }
02da8857441acf20674c914acde475445a972f00
8a51a96f61699f0318315ccc89cef39f6866f2b5
/src/backend/optimizer/util/inherit.c
94de855a22787a1f67138b025fae4b44e38b9508
[ "PostgreSQL" ]
permissive
postgres/postgres
979febf2b41c00090d1256228f768f33e7ef3b6f
b5934bfd6071fed3a38cea0cfaa93afda63d9c0c
refs/heads/master
2023-08-31T00:10:01.373472
2023-08-30T23:07:48
2023-08-30T23:07:48
927,442
13,691
4,807
NOASSERTION
2023-09-09T13:59:15
2010-09-21T11:35:45
C
UTF-8
C
false
false
31,525
c
inherit.c
/*------------------------------------------------------------------------- * * inherit.c * Routines to process child relations in inheritance trees * * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * * IDENTIFICATION * src/backend/optimizer/util/inherit.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include "access/sysattr.h" #include "access/table.h" #include "catalog/partition.h" #include "catalog/pg_inherits.h" #include "catalog/pg_type.h" #include "miscadmin.h" #include "nodes/makefuncs.h" #include "optimizer/appendinfo.h" #include "optimizer/inherit.h" #include "optimizer/optimizer.h" #include "optimizer/pathnode.h" #include "optimizer/plancat.h" #include "optimizer/planmain.h" #include "optimizer/planner.h" #include "optimizer/prep.h" #include "optimizer/restrictinfo.h" #include "parser/parsetree.h" #include "parser/parse_relation.h" #include "partitioning/partdesc.h" #include "partitioning/partprune.h" #include "utils/rel.h" static void expand_partitioned_rtentry(PlannerInfo *root, RelOptInfo *relinfo, RangeTblEntry *parentrte, Index parentRTindex, Relation parentrel, Bitmapset *parent_updatedCols, PlanRowMark *top_parentrc, LOCKMODE lockmode); static void expand_single_inheritance_child(PlannerInfo *root, RangeTblEntry *parentrte, Index parentRTindex, Relation parentrel, PlanRowMark *top_parentrc, Relation childrel, RangeTblEntry **childrte_p, Index *childRTindex_p); static Bitmapset *translate_col_privs(const Bitmapset *parent_privs, List *translated_vars); static Bitmapset *translate_col_privs_multilevel(PlannerInfo *root, RelOptInfo *rel, RelOptInfo *parent_rel, Bitmapset *parent_cols); static void expand_appendrel_subquery(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte, Index rti); /* * expand_inherited_rtentry * Expand a rangetable entry that has the "inh" bit set. * * "inh" is only allowed in two cases: RELATION and SUBQUERY RTEs. * * "inh" on a plain RELATION RTE means that it is a partitioned table or the * parent of a traditional-inheritance set. In this case we must add entries * for all the interesting child tables to the query's rangetable, and build * additional planner data structures for them, including RelOptInfos, * AppendRelInfos, and possibly PlanRowMarks. * * Note that the original RTE is considered to represent the whole inheritance * set. In the case of traditional inheritance, the first of the generated * RTEs is an RTE for the same table, but with inh = false, to represent the * parent table in its role as a simple member of the inheritance set. For * partitioning, we don't need a second RTE because the partitioned table * itself has no data and need not be scanned. * * "inh" on a SUBQUERY RTE means that it's the parent of a UNION ALL group, * which is treated as an appendrel similarly to inheritance cases; however, * we already made RTEs and AppendRelInfos for the subqueries. We only need * to build RelOptInfos for them, which is done by expand_appendrel_subquery. */ void expand_inherited_rtentry(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte, Index rti) { Oid parentOID; Relation oldrelation; LOCKMODE lockmode; PlanRowMark *oldrc; bool old_isParent = false; int old_allMarkTypes = 0; Assert(rte->inh); /* else caller error */ if (rte->rtekind == RTE_SUBQUERY) { expand_appendrel_subquery(root, rel, rte, rti); return; } Assert(rte->rtekind == RTE_RELATION); parentOID = rte->relid; /* * We used to check has_subclass() here, but there's no longer any need * to, because subquery_planner already did. */ /* * The rewriter should already have obtained an appropriate lock on each * relation named in the query, so we can open the parent relation without * locking it. However, for each child relation we add to the query, we * must obtain an appropriate lock, because this will be the first use of * those relations in the parse/rewrite/plan pipeline. Child rels should * use the same lockmode as their parent. */ oldrelation = table_open(parentOID, NoLock); lockmode = rte->rellockmode; /* * If parent relation is selected FOR UPDATE/SHARE, we need to mark its * PlanRowMark as isParent = true, and generate a new PlanRowMark for each * child. */ oldrc = get_plan_rowmark(root->rowMarks, rti); if (oldrc) { old_isParent = oldrc->isParent; oldrc->isParent = true; /* Save initial value of allMarkTypes before children add to it */ old_allMarkTypes = oldrc->allMarkTypes; } /* Scan the inheritance set and expand it */ if (oldrelation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE) { RTEPermissionInfo *perminfo; perminfo = getRTEPermissionInfo(root->parse->rteperminfos, rte); /* * Partitioned table, so set up for partitioning. */ Assert(rte->relkind == RELKIND_PARTITIONED_TABLE); /* * Recursively expand and lock the partitions. While at it, also * extract the partition key columns of all the partitioned tables. */ expand_partitioned_rtentry(root, rel, rte, rti, oldrelation, perminfo->updatedCols, oldrc, lockmode); } else { /* * Ordinary table, so process traditional-inheritance children. (Note * that partitioned tables are not allowed to have inheritance * children, so it's not possible for both cases to apply.) */ List *inhOIDs; ListCell *l; /* Scan for all members of inheritance set, acquire needed locks */ inhOIDs = find_all_inheritors(parentOID, lockmode, NULL); /* * We used to special-case the situation where the table no longer has * any children, by clearing rte->inh and exiting. That no longer * works, because this function doesn't get run until after decisions * have been made that depend on rte->inh. We have to treat such * situations as normal inheritance. The table itself should always * have been found, though. */ Assert(inhOIDs != NIL); Assert(linitial_oid(inhOIDs) == parentOID); /* Expand simple_rel_array and friends to hold child objects. */ expand_planner_arrays(root, list_length(inhOIDs)); /* * Expand inheritance children in the order the OIDs were returned by * find_all_inheritors. */ foreach(l, inhOIDs) { Oid childOID = lfirst_oid(l); Relation newrelation; RangeTblEntry *childrte; Index childRTindex; /* Open rel if needed; we already have required locks */ if (childOID != parentOID) newrelation = table_open(childOID, NoLock); else newrelation = oldrelation; /* * It is possible that the parent table has children that are temp * tables of other backends. We cannot safely access such tables * (because of buffering issues), and the best thing to do seems * to be to silently ignore them. */ if (childOID != parentOID && RELATION_IS_OTHER_TEMP(newrelation)) { table_close(newrelation, lockmode); continue; } /* Create RTE and AppendRelInfo, plus PlanRowMark if needed. */ expand_single_inheritance_child(root, rte, rti, oldrelation, oldrc, newrelation, &childrte, &childRTindex); /* Create the otherrel RelOptInfo too. */ (void) build_simple_rel(root, childRTindex, rel); /* Close child relations, but keep locks */ if (childOID != parentOID) table_close(newrelation, NoLock); } } /* * Some children might require different mark types, which would've been * reported into oldrc. If so, add relevant entries to the top-level * targetlist and update parent rel's reltarget. This should match what * preprocess_targetlist() would have added if the mark types had been * requested originally. * * (Someday it might be useful to fold these resjunk columns into the * row-identity-column management used for UPDATE/DELETE. Today is not * that day, however.) */ if (oldrc) { int new_allMarkTypes = oldrc->allMarkTypes; Var *var; TargetEntry *tle; char resname[32]; List *newvars = NIL; /* Add TID junk Var if needed, unless we had it already */ if (new_allMarkTypes & ~(1 << ROW_MARK_COPY) && !(old_allMarkTypes & ~(1 << ROW_MARK_COPY))) { /* Need to fetch TID */ var = makeVar(oldrc->rti, SelfItemPointerAttributeNumber, TIDOID, -1, InvalidOid, 0); snprintf(resname, sizeof(resname), "ctid%u", oldrc->rowmarkId); tle = makeTargetEntry((Expr *) var, list_length(root->processed_tlist) + 1, pstrdup(resname), true); root->processed_tlist = lappend(root->processed_tlist, tle); newvars = lappend(newvars, var); } /* Add whole-row junk Var if needed, unless we had it already */ if ((new_allMarkTypes & (1 << ROW_MARK_COPY)) && !(old_allMarkTypes & (1 << ROW_MARK_COPY))) { var = makeWholeRowVar(planner_rt_fetch(oldrc->rti, root), oldrc->rti, 0, false); snprintf(resname, sizeof(resname), "wholerow%u", oldrc->rowmarkId); tle = makeTargetEntry((Expr *) var, list_length(root->processed_tlist) + 1, pstrdup(resname), true); root->processed_tlist = lappend(root->processed_tlist, tle); newvars = lappend(newvars, var); } /* Add tableoid junk Var, unless we had it already */ if (!old_isParent) { var = makeVar(oldrc->rti, TableOidAttributeNumber, OIDOID, -1, InvalidOid, 0); snprintf(resname, sizeof(resname), "tableoid%u", oldrc->rowmarkId); tle = makeTargetEntry((Expr *) var, list_length(root->processed_tlist) + 1, pstrdup(resname), true); root->processed_tlist = lappend(root->processed_tlist, tle); newvars = lappend(newvars, var); } /* * Add the newly added Vars to parent's reltarget. We needn't worry * about the children's reltargets, they'll be made later. */ add_vars_to_targetlist(root, newvars, bms_make_singleton(0)); } table_close(oldrelation, NoLock); } /* * expand_partitioned_rtentry * Recursively expand an RTE for a partitioned table. */ static void expand_partitioned_rtentry(PlannerInfo *root, RelOptInfo *relinfo, RangeTblEntry *parentrte, Index parentRTindex, Relation parentrel, Bitmapset *parent_updatedCols, PlanRowMark *top_parentrc, LOCKMODE lockmode) { PartitionDesc partdesc; Bitmapset *live_parts; int num_live_parts; int i; check_stack_depth(); Assert(parentrte->inh); partdesc = PartitionDirectoryLookup(root->glob->partition_directory, parentrel); /* A partitioned table should always have a partition descriptor. */ Assert(partdesc); /* * Note down whether any partition key cols are being updated. Though it's * the root partitioned table's updatedCols we are interested in, * parent_updatedCols provided by the caller contains the root partrel's * updatedCols translated to match the attribute ordering of parentrel. */ if (!root->partColsUpdated) root->partColsUpdated = has_partition_attrs(parentrel, parent_updatedCols, NULL); /* Nothing further to do here if there are no partitions. */ if (partdesc->nparts == 0) return; /* * Perform partition pruning using restriction clauses assigned to parent * relation. live_parts will contain PartitionDesc indexes of partitions * that survive pruning. Below, we will initialize child objects for the * surviving partitions. */ relinfo->live_parts = live_parts = prune_append_rel_partitions(relinfo); /* Expand simple_rel_array and friends to hold child objects. */ num_live_parts = bms_num_members(live_parts); if (num_live_parts > 0) expand_planner_arrays(root, num_live_parts); /* * We also store partition RelOptInfo pointers in the parent relation. * Since we're palloc0'ing, slots corresponding to pruned partitions will * contain NULL. */ Assert(relinfo->part_rels == NULL); relinfo->part_rels = (RelOptInfo **) palloc0(relinfo->nparts * sizeof(RelOptInfo *)); /* * Create a child RTE for each live partition. Note that unlike * traditional inheritance, we don't need a child RTE for the partitioned * table itself, because it's not going to be scanned. */ i = -1; while ((i = bms_next_member(live_parts, i)) >= 0) { Oid childOID = partdesc->oids[i]; Relation childrel; RangeTblEntry *childrte; Index childRTindex; RelOptInfo *childrelinfo; /* Open rel, acquiring required locks */ childrel = table_open(childOID, lockmode); /* * Temporary partitions belonging to other sessions should have been * disallowed at definition, but for paranoia's sake, let's double * check. */ if (RELATION_IS_OTHER_TEMP(childrel)) elog(ERROR, "temporary relation from another session found as partition"); /* Create RTE and AppendRelInfo, plus PlanRowMark if needed. */ expand_single_inheritance_child(root, parentrte, parentRTindex, parentrel, top_parentrc, childrel, &childrte, &childRTindex); /* Create the otherrel RelOptInfo too. */ childrelinfo = build_simple_rel(root, childRTindex, relinfo); relinfo->part_rels[i] = childrelinfo; relinfo->all_partrels = bms_add_members(relinfo->all_partrels, childrelinfo->relids); /* If this child is itself partitioned, recurse */ if (childrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE) { AppendRelInfo *appinfo = root->append_rel_array[childRTindex]; Bitmapset *child_updatedCols; child_updatedCols = translate_col_privs(parent_updatedCols, appinfo->translated_vars); expand_partitioned_rtentry(root, childrelinfo, childrte, childRTindex, childrel, child_updatedCols, top_parentrc, lockmode); } /* Close child relation, but keep locks */ table_close(childrel, NoLock); } } /* * expand_single_inheritance_child * Build a RangeTblEntry and an AppendRelInfo, plus maybe a PlanRowMark. * * We now expand the partition hierarchy level by level, creating a * corresponding hierarchy of AppendRelInfos and RelOptInfos, where each * partitioned descendant acts as a parent of its immediate partitions. * (This is a difference from what older versions of PostgreSQL did and what * is still done in the case of table inheritance for unpartitioned tables, * where the hierarchy is flattened during RTE expansion.) * * PlanRowMarks still carry the top-parent's RTI, and the top-parent's * allMarkTypes field still accumulates values from all descendents. * * "parentrte" and "parentRTindex" are immediate parent's RTE and * RTI. "top_parentrc" is top parent's PlanRowMark. * * The child RangeTblEntry and its RTI are returned in "childrte_p" and * "childRTindex_p" resp. */ static void expand_single_inheritance_child(PlannerInfo *root, RangeTblEntry *parentrte, Index parentRTindex, Relation parentrel, PlanRowMark *top_parentrc, Relation childrel, RangeTblEntry **childrte_p, Index *childRTindex_p) { Query *parse = root->parse; Oid parentOID = RelationGetRelid(parentrel); Oid childOID = RelationGetRelid(childrel); RangeTblEntry *childrte; Index childRTindex; AppendRelInfo *appinfo; TupleDesc child_tupdesc; List *parent_colnames; List *child_colnames; /* * Build an RTE for the child, and attach to query's rangetable list. We * copy most scalar fields of the parent's RTE, but replace relation OID, * relkind, and inh for the child. Set the child's securityQuals to * empty, because we only want to apply the parent's RLS conditions * regardless of what RLS properties individual children may have. (This * is an intentional choice to make inherited RLS work like regular * permissions checks.) The parent securityQuals will be propagated to * children along with other base restriction clauses, so we don't need to * do it here. Other infrastructure of the parent RTE has to be * translated to match the child table's column ordering, which we do * below, so a "flat" copy is sufficient to start with. */ childrte = makeNode(RangeTblEntry); memcpy(childrte, parentrte, sizeof(RangeTblEntry)); Assert(parentrte->rtekind == RTE_RELATION); /* else this is dubious */ childrte->relid = childOID; childrte->relkind = childrel->rd_rel->relkind; /* A partitioned child will need to be expanded further. */ if (childrte->relkind == RELKIND_PARTITIONED_TABLE) { Assert(childOID != parentOID); childrte->inh = true; } else childrte->inh = false; childrte->securityQuals = NIL; /* * No permission checking for the child RTE unless it's the parent * relation in its child role, which only applies to traditional * inheritance. */ if (childOID != parentOID) childrte->perminfoindex = 0; /* Link not-yet-fully-filled child RTE into data structures */ parse->rtable = lappend(parse->rtable, childrte); childRTindex = list_length(parse->rtable); *childrte_p = childrte; *childRTindex_p = childRTindex; /* * Build an AppendRelInfo struct for each parent/child pair. */ appinfo = make_append_rel_info(parentrel, childrel, parentRTindex, childRTindex); root->append_rel_list = lappend(root->append_rel_list, appinfo); /* tablesample is probably null, but copy it */ childrte->tablesample = copyObject(parentrte->tablesample); /* * Construct an alias clause for the child, which we can also use as eref. * This is important so that EXPLAIN will print the right column aliases * for child-table columns. (Since ruleutils.c doesn't have any easy way * to reassociate parent and child columns, we must get the child column * aliases right to start with. Note that setting childrte->alias forces * ruleutils.c to use these column names, which it otherwise would not.) */ child_tupdesc = RelationGetDescr(childrel); parent_colnames = parentrte->eref->colnames; child_colnames = NIL; for (int cattno = 0; cattno < child_tupdesc->natts; cattno++) { Form_pg_attribute att = TupleDescAttr(child_tupdesc, cattno); const char *attname; if (att->attisdropped) { /* Always insert an empty string for a dropped column */ attname = ""; } else if (appinfo->parent_colnos[cattno] > 0 && appinfo->parent_colnos[cattno] <= list_length(parent_colnames)) { /* Duplicate the query-assigned name for the parent column */ attname = strVal(list_nth(parent_colnames, appinfo->parent_colnos[cattno] - 1)); } else { /* New column, just use its real name */ attname = NameStr(att->attname); } child_colnames = lappend(child_colnames, makeString(pstrdup(attname))); } /* * We just duplicate the parent's table alias name for each child. If the * plan gets printed, ruleutils.c has to sort out unique table aliases to * use, which it can handle. */ childrte->alias = childrte->eref = makeAlias(parentrte->eref->aliasname, child_colnames); /* * Store the RTE and appinfo in the respective PlannerInfo arrays, which * the caller must already have allocated space for. */ Assert(childRTindex < root->simple_rel_array_size); Assert(root->simple_rte_array[childRTindex] == NULL); root->simple_rte_array[childRTindex] = childrte; Assert(root->append_rel_array[childRTindex] == NULL); root->append_rel_array[childRTindex] = appinfo; /* * Build a PlanRowMark if parent is marked FOR UPDATE/SHARE. */ if (top_parentrc) { PlanRowMark *childrc = makeNode(PlanRowMark); childrc->rti = childRTindex; childrc->prti = top_parentrc->rti; childrc->rowmarkId = top_parentrc->rowmarkId; /* Reselect rowmark type, because relkind might not match parent */ childrc->markType = select_rowmark_type(childrte, top_parentrc->strength); childrc->allMarkTypes = (1 << childrc->markType); childrc->strength = top_parentrc->strength; childrc->waitPolicy = top_parentrc->waitPolicy; /* * We mark RowMarks for partitioned child tables as parent RowMarks so * that the executor ignores them (except their existence means that * the child tables will be locked using the appropriate mode). */ childrc->isParent = (childrte->relkind == RELKIND_PARTITIONED_TABLE); /* Include child's rowmark type in top parent's allMarkTypes */ top_parentrc->allMarkTypes |= childrc->allMarkTypes; root->rowMarks = lappend(root->rowMarks, childrc); } /* * If we are creating a child of the query target relation (only possible * in UPDATE/DELETE/MERGE), add it to all_result_relids, as well as * leaf_result_relids if appropriate, and make sure that we generate * required row-identity data. */ if (bms_is_member(parentRTindex, root->all_result_relids)) { /* OK, record the child as a result rel too. */ root->all_result_relids = bms_add_member(root->all_result_relids, childRTindex); /* Non-leaf partitions don't need any row identity info. */ if (childrte->relkind != RELKIND_PARTITIONED_TABLE) { Var *rrvar; root->leaf_result_relids = bms_add_member(root->leaf_result_relids, childRTindex); /* * If we have any child target relations, assume they all need to * generate a junk "tableoid" column. (If only one child survives * pruning, we wouldn't really need this, but it's not worth * thrashing about to avoid it.) */ rrvar = makeVar(childRTindex, TableOidAttributeNumber, OIDOID, -1, InvalidOid, 0); add_row_identity_var(root, rrvar, childRTindex, "tableoid"); /* Register any row-identity columns needed by this child. */ add_row_identity_columns(root, childRTindex, childrte, childrel); } } } /* * get_rel_all_updated_cols * Returns the set of columns of a given "simple" relation that are * updated by this query. */ Bitmapset * get_rel_all_updated_cols(PlannerInfo *root, RelOptInfo *rel) { Index relid; RangeTblEntry *rte; RTEPermissionInfo *perminfo; Bitmapset *updatedCols, *extraUpdatedCols; Assert(root->parse->commandType == CMD_UPDATE); Assert(IS_SIMPLE_REL(rel)); /* * We obtain updatedCols for the query's result relation. Then, if * necessary, we map it to the column numbers of the relation for which * they were requested. */ relid = root->parse->resultRelation; rte = planner_rt_fetch(relid, root); perminfo = getRTEPermissionInfo(root->parse->rteperminfos, rte); updatedCols = perminfo->updatedCols; if (rel->relid != relid) { RelOptInfo *top_parent_rel = find_base_rel(root, relid); Assert(IS_OTHER_REL(rel)); updatedCols = translate_col_privs_multilevel(root, rel, top_parent_rel, updatedCols); } /* * Now we must check to see if there are any generated columns that depend * on the updatedCols, and add them to the result. */ extraUpdatedCols = get_dependent_generated_columns(root, rel->relid, updatedCols); return bms_union(updatedCols, extraUpdatedCols); } /* * translate_col_privs * Translate a bitmapset representing per-column privileges from the * parent rel's attribute numbering to the child's. * * The only surprise here is that we don't translate a parent whole-row * reference into a child whole-row reference. That would mean requiring * permissions on all child columns, which is overly strict, since the * query is really only going to reference the inherited columns. Instead * we set the per-column bits for all inherited columns. */ static Bitmapset * translate_col_privs(const Bitmapset *parent_privs, List *translated_vars) { Bitmapset *child_privs = NULL; bool whole_row; int attno; ListCell *lc; /* System attributes have the same numbers in all tables */ for (attno = FirstLowInvalidHeapAttributeNumber + 1; attno < 0; attno++) { if (bms_is_member(attno - FirstLowInvalidHeapAttributeNumber, parent_privs)) child_privs = bms_add_member(child_privs, attno - FirstLowInvalidHeapAttributeNumber); } /* Check if parent has whole-row reference */ whole_row = bms_is_member(InvalidAttrNumber - FirstLowInvalidHeapAttributeNumber, parent_privs); /* And now translate the regular user attributes, using the vars list */ attno = InvalidAttrNumber; foreach(lc, translated_vars) { Var *var = lfirst_node(Var, lc); attno++; if (var == NULL) /* ignore dropped columns */ continue; if (whole_row || bms_is_member(attno - FirstLowInvalidHeapAttributeNumber, parent_privs)) child_privs = bms_add_member(child_privs, var->varattno - FirstLowInvalidHeapAttributeNumber); } return child_privs; } /* * translate_col_privs_multilevel * Recursively translates the column numbers contained in 'parent_cols' * to the column numbers of a descendant relation given by 'rel' * * Note that because this is based on translate_col_privs, it will expand * a whole-row reference into all inherited columns. This is not an issue * for current usages, but beware. */ static Bitmapset * translate_col_privs_multilevel(PlannerInfo *root, RelOptInfo *rel, RelOptInfo *parent_rel, Bitmapset *parent_cols) { AppendRelInfo *appinfo; /* Fast path for easy case. */ if (parent_cols == NULL) return NULL; /* Recurse if immediate parent is not the top parent. */ if (rel->parent != parent_rel) { if (rel->parent) parent_cols = translate_col_privs_multilevel(root, rel->parent, parent_rel, parent_cols); else elog(ERROR, "rel with relid %u is not a child rel", rel->relid); } /* Now translate for this child. */ Assert(root->append_rel_array != NULL); appinfo = root->append_rel_array[rel->relid]; Assert(appinfo != NULL); return translate_col_privs(parent_cols, appinfo->translated_vars); } /* * expand_appendrel_subquery * Add "other rel" RelOptInfos for the children of an appendrel baserel * * "rel" is a subquery relation that has the rte->inh flag set, meaning it * is a UNION ALL subquery that's been flattened into an appendrel, with * child subqueries listed in root->append_rel_list. We need to build * a RelOptInfo for each child relation so that we can plan scans on them. */ static void expand_appendrel_subquery(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte, Index rti) { ListCell *l; foreach(l, root->append_rel_list) { AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l); Index childRTindex = appinfo->child_relid; RangeTblEntry *childrte; RelOptInfo *childrel; /* append_rel_list contains all append rels; ignore others */ if (appinfo->parent_relid != rti) continue; /* find the child RTE, which should already exist */ Assert(childRTindex < root->simple_rel_array_size); childrte = root->simple_rte_array[childRTindex]; Assert(childrte != NULL); /* Build the child RelOptInfo. */ childrel = build_simple_rel(root, childRTindex, rel); /* Child may itself be an inherited rel, either table or subquery. */ if (childrte->inh) expand_inherited_rtentry(root, childrel, childrte, childRTindex); } } /* * apply_child_basequals * Populate childrel's base restriction quals from parent rel's quals, * translating them using appinfo. * * If any of the resulting clauses evaluate to constant false or NULL, we * return false and don't apply any quals. Caller should mark the relation as * a dummy rel in this case, since it doesn't need to be scanned. */ bool apply_child_basequals(PlannerInfo *root, RelOptInfo *parentrel, RelOptInfo *childrel, RangeTblEntry *childRTE, AppendRelInfo *appinfo) { List *childquals; Index cq_min_security; ListCell *lc; /* * The child rel's targetlist might contain non-Var expressions, which * means that substitution into the quals could produce opportunities for * const-simplification, and perhaps even pseudoconstant quals. Therefore, * transform each RestrictInfo separately to see if it reduces to a * constant or pseudoconstant. (We must process them separately to keep * track of the security level of each qual.) */ childquals = NIL; cq_min_security = UINT_MAX; foreach(lc, parentrel->baserestrictinfo) { RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc); Node *childqual; ListCell *lc2; Assert(IsA(rinfo, RestrictInfo)); childqual = adjust_appendrel_attrs(root, (Node *) rinfo->clause, 1, &appinfo); childqual = eval_const_expressions(root, childqual); /* check for flat-out constant */ if (childqual && IsA(childqual, Const)) { if (((Const *) childqual)->constisnull || !DatumGetBool(((Const *) childqual)->constvalue)) { /* Restriction reduces to constant FALSE or NULL */ return false; } /* Restriction reduces to constant TRUE, so drop it */ continue; } /* might have gotten an AND clause, if so flatten it */ foreach(lc2, make_ands_implicit((Expr *) childqual)) { Node *onecq = (Node *) lfirst(lc2); bool pseudoconstant; /* check for pseudoconstant (no Vars or volatile functions) */ pseudoconstant = !contain_vars_of_level(onecq, 0) && !contain_volatile_functions(onecq); if (pseudoconstant) { /* tell createplan.c to check for gating quals */ root->hasPseudoConstantQuals = true; } /* reconstitute RestrictInfo with appropriate properties */ childquals = lappend(childquals, make_restrictinfo(root, (Expr *) onecq, rinfo->is_pushed_down, rinfo->has_clone, rinfo->is_clone, pseudoconstant, rinfo->security_level, NULL, NULL, NULL)); /* track minimum security level among child quals */ cq_min_security = Min(cq_min_security, rinfo->security_level); } } /* * In addition to the quals inherited from the parent, we might have * securityQuals associated with this particular child node. (Currently * this can only happen in appendrels originating from UNION ALL; * inheritance child tables don't have their own securityQuals, see * expand_single_inheritance_child().) Pull any such securityQuals up * into the baserestrictinfo for the child. This is similar to * process_security_barrier_quals() for the parent rel, except that we * can't make any general deductions from such quals, since they don't * hold for the whole appendrel. */ if (childRTE->securityQuals) { Index security_level = 0; foreach(lc, childRTE->securityQuals) { List *qualset = (List *) lfirst(lc); ListCell *lc2; foreach(lc2, qualset) { Expr *qual = (Expr *) lfirst(lc2); /* not likely that we'd see constants here, so no check */ childquals = lappend(childquals, make_restrictinfo(root, qual, true, false, false, false, security_level, NULL, NULL, NULL)); cq_min_security = Min(cq_min_security, security_level); } security_level++; } Assert(security_level <= root->qual_security_level); } /* * OK, we've got all the baserestrictinfo quals for this child. */ childrel->baserestrictinfo = childquals; childrel->baserestrict_min_security = cq_min_security; return true; }
590707a4ac990b6e327678eb0fee13918fe87796
7fcb614a59a138019b2845a6e493f9d22c44852d
/MCUME_teensy/teensypce/emu.h
ad56515cbec1fbd18b271970c14be28b12756d4a
[]
no_license
Jean-MarcHarvengt/MCUME
9180feaf8195c6a0a38eba6c12733c987fa98062
fe1280985d9a86bfb2166842a56c8eec768aa666
refs/heads/master
2023-06-09T23:11:04.216374
2023-05-28T15:24:02
2023-05-28T15:24:02
203,546,040
318
43
null
2023-03-21T13:19:51
2019-08-21T08:58:23
C
UTF-8
C
false
false
131
h
emu.h
extern void pce_Init(void); extern void pce_Step(void); extern void pce_Start(char * filename); extern void pce_Input(int click);
34ab2804c53c5a245d8dce85d86bf1cc8b98d02e
9ceacf33fd96913cac7ef15492c126d96cae6911
/sbin/isakmpd/if.c
0c6fad48d79e052a113d567bb5aa2c28350c6993
[ "BSD-3-Clause" ]
permissive
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
2,036
c
if.c
/* $OpenBSD: if.c,v 1.26 2019/06/28 13:32:44 deraadt Exp $ */ /* $EOM: if.c,v 1.12 1999/10/01 13:45:20 niklas Exp $ */ /* * Copyright (c) 1998, 1999 Niklas Hallqvist. 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 ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * This code was written under funding by Ericsson Radio Systems. */ #include <sys/ioctl.h> #include <sys/types.h> #include <sys/socket.h> #include <net/if.h> #include <stdlib.h> #include <unistd.h> #include <ifaddrs.h> #include "log.h" #include "monitor.h" #include "if.h" int if_map(int (*func)(char *, struct sockaddr *, void *), void *arg) { int err = 0; struct ifaddrs *ifap, *ifa; if (getifaddrs(&ifap) == -1) return -1; for (ifa = ifap; ifa; ifa = ifa->ifa_next) if ((*func)(ifa->ifa_name, ifa->ifa_addr, arg) == -1) err = -1; freeifaddrs(ifap); return err; }
712ff32e61651fe3a7c51830d77fdcc1b259ea16
f3878a19f8cd79cac4beb84ce73105f22bc5cc26
/src/aln_structs.h
9c697116cda1da008cd97f232d6a1aa47a6377fb
[ "Apache-2.0", "LicenseRef-scancode-proprietary-license", "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
wrpearson/fasta36
8c1a3f233de906b552e2768917cf89dc46f29f49
71b899362e2cef2f5a2c975e57f0f7995f93e3ea
refs/heads/v36.3.8
2023-06-10T12:00:55.143828
2023-05-31T23:54:18
2023-05-31T23:54:18
24,374,820
101
17
Apache-2.0
2023-05-19T16:57:44
2014-09-23T14:30:42
C
UTF-8
C
false
false
2,000
h
aln_structs.h
/* $Id: aln_structs.h 1139 2013-04-16 01:00:09Z wrp $ */ #ifndef A_STRUCT #define A_STRUCT struct a_struct { int smin0; /* coordinate of display start in seqc0 */ int smin1; /* coordinate of display start in seqc1 */ int amin0, amax0; /* coordinate of alignment start in seqc0 */ int amin1, amax1; /* coordinate of alignment start in seqc1 */ int calc_last_set; /* boolean that indicates structure was set by calc_code, calc_cons, etc */ int llen; int llcntx, llcntx_set, showall; int qlrev, qlfact; int llrev, llfact, llmult; int frame; int nident, nsim, npos, nmismatch, lc, ngap_q, ngap_l, nfs; /* number of identities, gaps in q, l */ long q_start_off, q_end_off; /* used in -m 9 calculate for full segment offset */ long l_start_off, l_end_off; long q_offset, l_offset; /* offsets that include everything */ long d_start0,d_stop0; long d_start1,d_stop1; }; struct annot_var_str { long v_pos; unsigned char o_res; unsigned char v_res; }; struct a_res_str { int sw_score; /* do_walign() score */ struct rstruct rst; int score_delta; /* variant score change */ int min0, max0; /* boundaries of alignment in aa0 */ int min1, max1; /* boundaries of alignment in aa1 */ int v_start, v_len; /* virtual start, length */ int *res; /* encoded alignment */ int nres; /* length of decoded alignment */ int mres; /* length of encoding in res[] */ int n1; /* length of library sequence used for this (sub) alignment */ struct a_res_str *next; /* pointer to next alignment */ int index; /* position in a_res chain */ /* encoded alignment/annotation information */ char *aln_code; int aln_code_n; char *annot_code; /* annotation info written by calc_code() */ int annot_code_n; char *annot_var_s; /* annotation info written by calc_cons_a() */ char *annot_var_id; /* annotation info written by calc_id() */ char *annot_var_idd; /* annotation info written by calc_idd() */ struct a_struct aln; }; #endif
8b672612d90dcbea063944e6a5497e3ae9492735
65f3405e2d3deb0e5db9cb8b26644509ac96568e
/src/Fonts/Font16.c
2f8ad464e477b78cae6a61394f341f5171cf04dc
[ "MIT" ]
permissive
m5stack/M5Stack
9830600f925026c326af4fa23823d1c7f76df9fc
1e81176b2dd9cb7839f53f5a71a8143b04794de7
refs/heads/master
2023-09-03T17:50:59.532971
2023-08-28T06:50:34
2023-08-28T06:50:34
89,710,200
1,093
489
MIT
2023-07-10T06:40:53
2017-04-28T13:47:48
C
UTF-8
C
false
false
29,204
c
Font16.c
// Font 2 // Comment out for £ sign for character 24 #define TFT_ESPI_FONT2_DOLLAR // The grave ( ` ) diacritical mark will show as a degree ( ° ) symbol // Comment out next line to return character 0x60 to the grave accent: #define TFT_ESPI_GRAVE_IS_DEGREE #include <pgmspace.h> // Width has been increased by 1 pixel so pixel lengths are calculated correctly // for the displayed string PROGMEM const unsigned char widtbl_f16[96] = // character width table { 6, 3, 4, 9, 8, 9, 9, 3, // char 32 - 39 7, 7, 8, 6, 3, 6, 5, 7, // char 40 - 47 8, 8, 8, 8, 8, 8, 8, 8, // char 48 - 55 8, 8, 3, 3, 6, 6, 6, 8, // char 56 - 63 9, 8, 8, 8, 8, 8, 8, 8, // char 64 - 71 8, 4, 8, 8, 7, 10, 8, 8, // char 72 - 79 8, 8, 8, 8, 8, 8, 8, 10, // char 80 - 87 8, 8, 8, 4, 7, 4, 7, 9, // char 88 - 95 #ifdef TFT_ESPI_GRAVE_IS_DEGREE 5, 7, 7, 7, 7, 7, 6, 7, // char 96 - 103 0x60 is degree symbol #else 4, 7, 7, 7, 7, 7, 6, 7, // char 96 - 103 0x60 is grave #endif 7, 4, 5, 6, 4, 8, 7, 8, // char 104 - 111 7, 8, 6, 6, 5, 7, 8, 8, // char 112 - 119 6, 7, 7, 5, 3, 5, 8, 6 // char 120 - 127 }; // Row format, MSB left PROGMEM const unsigned char chr_f16_20[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // row 1 - 11 0x00, 0x00, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_21[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, // row 1 - 11 0x00, 0x40, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_22[16] = // 1 unsigned char per row { 0x00, 0x00, 0xA0, 0xA0, 0xA0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // row 1 - 11 0x00, 0x00, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_23[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x24, 0x24, 0x24, 0xFF, 0x24, 0x24, 0xFF, 0x24, // row 1 - 11 0x24, 0x24, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_24[16] = // 1 unsigned char per row { #ifdef TFT_ESPI_FONT2_DOLLAR 0x00, 0x00, 0x28, 0x38, 0x6C, 0xAA, 0xA8, 0x68, 0x3C, 0x2A, 0xAA, // row 1 - 11 0x6C, 0x38, 0x28, 0x00, 0x00 // row 12 - 16 #else // GBP sign 0x00, 0x00, 0x00, 0x3C, 0x42, 0x40, 0x40, 0x70, 0x40, 0x70, 0x40, // row 1 - 11 0x40, 0xFE, 0x00, 0x00, 0x00 // row 12 - 16 #endif }; PROGMEM const unsigned char chr_f16_25[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x61, 0x91, 0x92, 0x64, 0x08, 0x10, 0x26, 0x49, // row 1 - 11 0x89, 0x86, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_26[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x20, 0x50, 0x88, 0x88, 0x50, 0x20, 0x52, 0x8C, // row 1 - 11 0x8C, 0x73, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_27[16] = // 1 unsigned char per row { 0x00, 0x00, 0x40, 0x40, 0x40, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, // row 1 - 11 0x00, 0x00, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_28[16] = // 1 unsigned char per row { 0x00, 0x0C, 0x10, 0x20, 0x40, 0x40, 0x80, 0x80, 0x80, 0x80, 0x80, // row 1 - 11 0x40, 0x40, 0x20, 0x10, 0x0C // row 12 - 16 }; PROGMEM const unsigned char chr_f16_29[16] = // 1 unsigned char per row { 0x00, 0xC0, 0x20, 0x10, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04, 0x04, // row 1 - 11 0x08, 0x08, 0x10, 0x20, 0xC0 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_2A[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x00, 0x10, 0x92, 0x54, 0x38, 0x54, 0x92, 0x10, // row 1 - 11 0x00, 0x00, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_2B[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x20, 0xF8, 0x20, 0x20, // row 1 - 11 0x00, 0x00, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_2C[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // row 1 - 11 0xC0, 0xC0, 0x40, 0x80, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_2D[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x00, 0x00, // row 1 - 11 0x00, 0x00, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_2E[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // row 1 - 11 0xC0, 0xC0, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_2F[16] = // 1 unsigned char per row { 0x00, 0x00, 0x04, 0x04, 0x08, 0x08, 0x10, 0x10, 0x20, 0x20, 0x40, // row 1 - 11 0x40, 0x80, 0x80, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_30[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x38, 0x44, 0x44, 0x82, 0x82, 0x82, 0x82, 0x44, // row 1 - 11 0x44, 0x38, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_31[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x10, 0x30, 0x50, 0x10, 0x10, 0x10, 0x10, 0x10, // row 1 - 11 0x10, 0x7C, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_32[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x38, 0x44, 0x82, 0x02, 0x04, 0x18, 0x20, 0x40, // row 1 - 11 0x80, 0xFE, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_33[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x78, 0x84, 0x02, 0x04, 0x38, 0x04, 0x02, 0x02, // row 1 - 11 0x84, 0x78, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_34[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x04, 0x0C, 0x14, 0x24, 0x44, 0x84, 0xFE, 0x04, // row 1 - 11 0x04, 0x04, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_35[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0xFC, 0x80, 0x80, 0x80, 0xF8, 0x04, 0x02, 0x02, // row 1 - 11 0x84, 0x78, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_36[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x3C, 0x40, 0x80, 0x80, 0xB8, 0xC4, 0x82, 0x82, // row 1 - 11 0x44, 0x38, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_37[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x7E, 0x02, 0x02, 0x04, 0x04, 0x08, 0x08, 0x10, // row 1 - 11 0x10, 0x10, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_38[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x38, 0x44, 0x82, 0x44, 0x38, 0x44, 0x82, 0x82, // row 1 - 11 0x44, 0x38, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_39[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x38, 0x44, 0x82, 0x82, 0x46, 0x3A, 0x02, 0x02, // row 1 - 11 0x04, 0x78, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_3A[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xC0, 0x00, 0xC0, 0xC0, // row 1 - 11 0x00, 0x00, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_3B[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xC0, 0x00, 0xC0, 0xC0, // row 1 - 11 0x40, 0x80, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_3C[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x00, 0x08, 0x10, 0x20, 0x40, 0x80, 0x40, 0x20, // row 1 - 11 0x10, 0x08, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_3D[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x00, 0xF8, 0x00, // row 1 - 11 0x00, 0x00, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_3E[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x00, 0x80, 0x40, 0x20, 0x10, 0x08, 0x10, 0x20, // row 1 - 11 0x40, 0x80, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_3F[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x38, 0x44, 0x82, 0x02, 0x04, 0x08, 0x10, 0x10, // row 1 - 11 0x00, 0x10, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_40[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x3C, 0x42, 0x99, 0xA5, 0xA5, 0xA5, 0xA5, 0x9E, // row 1 - 11 0x40, 0x3E, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_41[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x10, 0x10, 0x28, 0x28, 0x44, 0x44, 0x7C, 0x82, // row 1 - 11 0x82, 0x82, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_42[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0xF8, 0x84, 0x82, 0x84, 0xF8, 0x84, 0x82, 0x82, // row 1 - 11 0x84, 0xF8, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_43[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x3C, 0x42, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, // row 1 - 11 0x42, 0x3C, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_44[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0xF8, 0x84, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, // row 1 - 11 0x84, 0xF8, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_45[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0xFE, 0x80, 0x80, 0x80, 0xFC, 0x80, 0x80, 0x80, // row 1 - 11 0x80, 0xFE, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_46[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0xFE, 0x80, 0x80, 0x80, 0xF8, 0x80, 0x80, 0x80, // row 1 - 11 0x80, 0x80, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_47[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x3C, 0x42, 0x80, 0x80, 0x80, 0x9C, 0x82, 0x82, // row 1 - 11 0x42, 0x3C, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_48[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x84, 0x84, 0x84, 0x84, 0xFC, 0x84, 0x84, 0x84, // row 1 - 11 0x84, 0x84, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_49[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0xE0, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, // row 1 - 11 0x40, 0xE0, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_4A[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x82, // row 1 - 11 0x44, 0x38, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_4B[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x84, 0x88, 0x90, 0xA0, 0xC0, 0xA0, 0x90, 0x88, // row 1 - 11 0x84, 0x82, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_4C[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, // row 1 - 11 0x80, 0xFC, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_4D[32] = // 2 unsigned chars per row { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC1, 0x80, 0xC1, 0x80, 0xA2, 0x80, // row 1 - 6 0xA2, 0x80, 0x94, 0x80, 0x94, 0x80, 0x88, 0x80, 0x88, 0x80, 0x80, 0x80, // row 7 - 12 0x80, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // row 13 - 16 }; PROGMEM const unsigned char chr_f16_4E[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0xC2, 0xC2, 0xA2, 0xA2, 0x92, 0x92, 0x8A, 0x8A, // row 1 - 11 0x86, 0x86, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_4F[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x38, 0x44, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, // row 1 - 11 0x44, 0x38, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_50[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0xF8, 0x84, 0x82, 0x82, 0x82, 0x84, 0xF8, 0x80, // row 1 - 11 0x80, 0x80, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_51[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x38, 0x44, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, // row 1 - 11 0x44, 0x38, 0x08, 0x06, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_52[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0xF8, 0x84, 0x82, 0x82, 0x84, 0xF8, 0x90, 0x88, // row 1 - 11 0x84, 0x82, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_53[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x38, 0x44, 0x82, 0x80, 0x60, 0x1C, 0x02, 0x82, // row 1 - 11 0x44, 0x38, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_54[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0xFE, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, // row 1 - 11 0x10, 0x10, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_55[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, // row 1 - 11 0x44, 0x38, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_56[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x82, 0x82, 0x82, 0x82, 0x44, 0x44, 0x28, 0x28, // row 1 - 11 0x10, 0x10, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_57[32] = // 2 unsigned chars per row { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, // row 1 - 6 0x88, 0x80, 0x88, 0x80, 0x49, 0x00, 0x55, 0x00, 0x55, 0x00, 0x22, 0x00, // row 7 - 12 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // row 13 - 16 }; PROGMEM const unsigned char chr_f16_58[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x82, 0x82, 0x44, 0x28, 0x10, 0x10, 0x28, 0x44, // row 1 - 11 0x82, 0x82, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_59[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x82, 0x82, 0x82, 0x44, 0x28, 0x10, 0x10, 0x10, // row 1 - 11 0x10, 0x10, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_5A[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0xFE, 0x02, 0x04, 0x08, 0x10, 0x10, 0x20, 0x40, // row 1 - 11 0x80, 0xFE, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_5B[16] = // 1 unsigned char per row { 0x00, 0x00, 0xE0, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, // row 1 - 11 0x80, 0x80, 0xE0, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_5C[16] = // 1 unsigned char per row { 0x00, 0x00, 0x80, 0x80, 0x40, 0x40, 0x20, 0x20, 0x10, 0x10, 0x08, // row 1 - 11 0x08, 0x04, 0x04, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_5D[16] = // 1 unsigned char per row { 0x00, 0x00, 0xE0, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // row 1 - 11 0x20, 0x20, 0xE0, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_5E[32] = // 1 unsigned chars per row { 0x00, 0x10, 0x28, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // row 1 - 11 0x00, 0x00, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_5F[32] = // 1 unsigned chars per row { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // row 1 - 11 0x00, 0x00, 0x00, 0xFF, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_60[16] = // 1 unsigned char per row { #ifdef TFT_ESPI_GRAVE_IS_DEGREE 0x00, 0x00, 0x00, 0x60, 0x90, 0x90, 0x60, 0x00, 0x00, 0x00, 0x00, // row 1 - 11 Degree symbol 0x00, 0x00, 0x00, 0x00, 0x00 #else 0x00, 0x00, 0x00, 0x40, 0x40, 0x40, 0x20, 0x00, 0x00, 0x00, 0x00, // row 1 - 11 Grave accent 0x00, 0x00, 0x00, 0x00, 0x00 // row 12 - 16 #endif }; PROGMEM const unsigned char chr_f16_61[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, 0x08, 0x04, 0x74, 0x8C, // row 1 - 11 0x8C, 0x74, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_62[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x00, 0x80, 0x80, 0xB0, 0xC8, 0x84, 0x84, 0x84, // row 1 - 11 0xC8, 0xB0, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_63[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x44, 0x80, 0x80, 0x80, // row 1 - 11 0x44, 0x38, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_64[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x34, 0x4C, 0x84, 0x84, 0x84, // row 1 - 11 0x4C, 0x34, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_65[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x44, 0x84, 0xF8, 0x80, // row 1 - 11 0x44, 0x38, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_66[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x30, 0x48, 0x40, 0x40, 0x40, 0xE0, 0x40, 0x40, // row 1 - 11 0x40, 0x40, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_67[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x4C, 0x84, 0x84, 0x84, // row 1 - 11 0x4C, 0x34, 0x04, 0x08, 0x70 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_68[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x80, 0x80, 0x80, 0xB0, 0xC8, 0x84, 0x84, 0x84, // row 1 - 11 0x84, 0x84, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_69[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x40, 0x40, 0x40, 0x40, 0x40, // row 1 - 11 0x40, 0x40, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_6A[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x30, 0x10, 0x10, 0x10, 0x10, // row 1 - 11 0x10, 0x10, 0x10, 0x90, 0x60 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_6B[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x80, 0x80, 0x80, 0x88, 0x90, 0xA0, 0xC0, 0xA0, // row 1 - 11 0x90, 0x88, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_6C[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0xC0, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, // row 1 - 11 0x40, 0x40, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_6D[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xAC, 0xD2, 0x92, 0x92, 0x92, // row 1 - 11 0x92, 0x92, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_6E[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xB0, 0xC8, 0x84, 0x84, 0x84, // row 1 - 11 0x84, 0x84, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_6F[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x44, 0x82, 0x82, 0x82, // row 1 - 11 0x44, 0x38, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_70[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xB0, 0xC8, 0x84, 0x84, 0x84, // row 1 - 11 0xC8, 0xB0, 0x80, 0x80, 0x80 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_71[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x34, 0x4C, 0x84, 0x84, 0x84, // row 1 - 11 0x4C, 0x34, 0x04, 0x04, 0x06 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_72[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xB0, 0xC8, 0x80, 0x80, 0x80, // row 1 - 11 0x80, 0x80, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_73[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, 0x88, 0x80, 0x70, 0x08, // row 1 - 11 0x88, 0x70, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_74[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x00, 0x40, 0x40, 0xE0, 0x40, 0x40, 0x40, 0x40, // row 1 - 11 0x40, 0x30, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_75[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x84, 0x84, 0x84, 0x84, 0x84, // row 1 - 11 0x4C, 0x34, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_76[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x82, 0x82, 0x82, 0x82, 0x44, // row 1 - 11 0x28, 0x10, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_77[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x82, 0x82, 0x82, 0x92, 0x92, // row 1 - 11 0xAA, 0x44, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_78[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88, 0x50, 0x20, 0x50, // row 1 - 11 0x88, 0x88, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_79[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x84, 0x84, 0x84, 0x84, 0x84, // row 1 - 11 0x4C, 0x34, 0x04, 0x08, 0x70 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_7A[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0x04, 0x08, 0x30, 0x40, // row 1 - 11 0x80, 0xFC, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_7B[16] = // 1 unsigned char per row { 0x00, 0x10, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x40, 0x20, 0x20, // row 1 - 11 0x20, 0x20, 0x20, 0x20, 0x10 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_7C[16] = // 1 unsigned char per row { 0x00, 0x00, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, // row 1 - 11 0x40, 0x40, 0x40, 0x40, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_7D[16] = // 1 unsigned char per row { 0x00, 0x40, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x10, 0x20, 0x20, // row 1 - 11 0x20, 0x20, 0x20, 0x20, 0x40 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_7E[16] = // 1 unsigned char per row { 0x00, 0x00, 0x00, 0x32, 0x4C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // row 1 - 11 0x00, 0x00, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char chr_f16_7F[16] = // 1 unsigned char per row { 0x00, 0x00, 0x30, 0x48, 0x48, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, // row 1 - 11 0x00, 0x00, 0x00, 0x00, 0x00 // row 12 - 16 }; PROGMEM const unsigned char* const chrtbl_f16[96] = // character pointer table { chr_f16_20, chr_f16_21, chr_f16_22, chr_f16_23, chr_f16_24, chr_f16_25, chr_f16_26, chr_f16_27, chr_f16_28, chr_f16_29, chr_f16_2A, chr_f16_2B, chr_f16_2C, chr_f16_2D, chr_f16_2E, chr_f16_2F, chr_f16_30, chr_f16_31, chr_f16_32, chr_f16_33, chr_f16_34, chr_f16_35, chr_f16_36, chr_f16_37, chr_f16_38, chr_f16_39, chr_f16_3A, chr_f16_3B, chr_f16_3C, chr_f16_3D, chr_f16_3E, chr_f16_3F, chr_f16_40, chr_f16_41, chr_f16_42, chr_f16_43, chr_f16_44, chr_f16_45, chr_f16_46, chr_f16_47, chr_f16_48, chr_f16_49, chr_f16_4A, chr_f16_4B, chr_f16_4C, chr_f16_4D, chr_f16_4E, chr_f16_4F, chr_f16_50, chr_f16_51, chr_f16_52, chr_f16_53, chr_f16_54, chr_f16_55, chr_f16_56, chr_f16_57, chr_f16_58, chr_f16_59, chr_f16_5A, chr_f16_5B, chr_f16_5C, chr_f16_5D, chr_f16_5E, chr_f16_5F, chr_f16_60, chr_f16_61, chr_f16_62, chr_f16_63, chr_f16_64, chr_f16_65, chr_f16_66, chr_f16_67, chr_f16_68, chr_f16_69, chr_f16_6A, chr_f16_6B, chr_f16_6C, chr_f16_6D, chr_f16_6E, chr_f16_6F, chr_f16_70, chr_f16_71, chr_f16_72, chr_f16_73, chr_f16_74, chr_f16_75, chr_f16_76, chr_f16_77, chr_f16_78, chr_f16_79, chr_f16_7A, chr_f16_7B, chr_f16_7C, chr_f16_7D, chr_f16_7E, chr_f16_7F };
4b0c20338f30209a44459fe56186b0cc0937659f
280ce9155107a41d88167818054fca9bceda796b
/jre_emul/android/platform/libcore/ojluni/src/main/native/net_util.h
58a0c00ae8357364a4ce7f37132b226c064cdecb
[ "Classpath-exception-2.0", "GPL-2.0-only", "Apache-2.0", "SunPro", "W3C", "LicenseRef-scancode-generic-cla", "W3C-19980720", "ICU", "MIT", "BSD-3-Clause", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "APSL-1.0", "LGPL-2.0-or-later", "LicenseRef-scancode-proprietary-license", "GPL-1.0-or-later", "LicenseRef-scancode-generic-exception", "LicenseRef-scancode-red-hat-attribution", "CPL-1.0", "LicenseRef-scancode-unicode", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-other-copyleft", "NAIST-2003", "GPL-2.0-or-later", "APSL-2.0", "LicenseRef-scancode-oracle-openjdk-exception-2.0", "LicenseRef-scancode-taligent-jdk" ]
permissive
google/j2objc
bd4796cdf77459abe816ff0db6e2709c1666627c
57b9229f5c6fb9e710609d93ca49eda9fa08c0e8
refs/heads/master
2023-08-28T16:26:05.842475
2023-08-26T03:30:58
2023-08-26T03:32:25
16,389,681
5,053
1,041
Apache-2.0
2023-09-14T20:32:57
2014-01-30T20:19:56
Java
UTF-8
C
false
false
5,232
h
net_util.h
/* * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ #ifndef NET_UTILS_H #define NET_UTILS_H #include "jvm.h" #include "jni_util.h" #include "net_util_md.h" /************************************************************************ * Macros and misc constants */ #define MAX_PACKET_LEN 65536 #define IPv4 AF_INET #define IPv6 AF_INET6 #define NET_ERROR(env, ex, msg) \ { if (!(*env)->ExceptionOccurred(env)) JNU_ThrowByName(env, ex, msg); } /************************************************************************ * Cached field IDs * * The naming convention for field IDs is * <class abbrv>_<fieldName>ID * i.e. psi_timeoutID is PlainSocketImpl's timeout field's ID. */ /* J2ObjC: unused. extern jclass ia_class; extern jfieldID iac_addressID; extern jfieldID iac_familyID; extern jfieldID iac_hostNameID; extern jfieldID ia_preferIPv6AddressID; */ extern void setInetAddress_addr(JNIEnv *env, jobject iaObj, int address); extern void setInetAddress_family(JNIEnv *env, jobject iaObj, int family); extern void setInetAddress_hostName(JNIEnv *env, jobject iaObj, jobject h); extern int getInetAddress_addr(JNIEnv *env, jobject iaObj); extern int getInetAddress_family(JNIEnv *env, jobject iaObj); extern jobject getInetAddress_hostName(JNIEnv *env, jobject iaObj); /* J2ObjC: unused. extern jclass ia4_class; extern jmethodID ia4_ctrID; */ /* NetworkInterface fields */ extern jclass ni_class; extern jfieldID ni_nameID; extern jfieldID ni_indexID; extern jfieldID ni_addrsID; extern jfieldID ni_descID; extern jmethodID ni_ctrID; /* PlainSocketImpl fields */ extern jfieldID psi_timeoutID; extern jfieldID psi_fdID; extern jfieldID psi_addressID; extern jfieldID psi_portID; extern jfieldID psi_localportID; /* DatagramPacket fields */ extern jfieldID dp_addressID; extern jfieldID dp_portID; extern jfieldID dp_bufID; extern jfieldID dp_offsetID; extern jfieldID dp_lengthID; extern jfieldID dp_bufLengthID; /* Inet6Address fields */ extern jclass ia6_class; extern jfieldID ia6_ipaddressID; extern jfieldID ia6_scopeidID; extern jfieldID ia6_scopeidsetID; extern jfieldID ia6_scopeifnameID; extern jfieldID ia6_scopeifnamesetID; extern jmethodID ia6_ctrID; /************************************************************************ * Utilities */ JNIEXPORT void JNICALL NET_ThrowNew(JNIEnv *env, int errorNum, char *msg); int NET_GetError(void); void NET_ThrowCurrent(JNIEnv *env, char *msg); jfieldID NET_GetFileDescriptorID(JNIEnv *env); JNIEXPORT jint JNICALL ipv6_available(void); void NET_AllocSockaddr(struct sockaddr **him, int *len); JNIEXPORT int JNICALL NET_InetAddressToSockaddr(JNIEnv *env, jobject iaObj, int port, struct sockaddr *him, int *len, jboolean v4MappedAddress); JNIEXPORT jobject JNICALL NET_SockaddrToInetAddress(JNIEnv *env, struct sockaddr *him, int *port); void initLocalAddrTable(void); void parseExclusiveBindProperty(JNIEnv *env); void NET_SetTrafficClass(struct sockaddr *him, int trafficClass); JNIEXPORT jint JNICALL NET_GetPortFromSockaddr(struct sockaddr *him); JNIEXPORT jint JNICALL NET_SockaddrEqualsInetAddress(JNIEnv *env,struct sockaddr *him, jobject iaObj); int NET_IsIPv4Mapped(jbyte* caddr); int NET_IPv4MappedToIPv4(jbyte* caddr); int NET_IsEqual(jbyte* caddr1, jbyte* caddr2); int NET_IsZeroAddr(jbyte* caddr); /* Socket operations * * These work just like the JVM_* procedures, except that they may do some * platform-specific pre/post processing of the arguments and/or results. */ JNIEXPORT int JNICALL NET_GetSockOpt(int fd, int level, int opt, void *result, int *len); JNIEXPORT int JNICALL NET_SetSockOpt(int fd, int level, int opt, const void *arg, int len); JNIEXPORT int JNICALL NET_Bind(int fd, struct sockaddr *him, int len); JNIEXPORT int JNICALL NET_MapSocketOption(jint cmd, int *level, int *optname); JNIEXPORT int JNICALL NET_MapSocketOptionV6(jint cmd, int *level, int *optname); int getScopeID (struct sockaddr *); int cmpScopeID (unsigned int, struct sockaddr *); unsigned short in_cksum(unsigned short *addr, int len); #endif /* NET_UTILS_H */
77d5cf8da912901c1c877e08b7d7b2f4664c729c
847ebadf2b0e7c01ad33ce92b42528a1a5c4846c
/tests/test-uuid.c
3b47ab61683a1740e8b9f2092232caea6e7d1226
[ "BSD-3-Clause", "ISC", "Apache-2.0", "SISSL", "GPL-2.0-only", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
permissive
openvswitch/ovs
6f782527cf5fde4ccfd25e68d359b91ff41acf8a
bc79a7bf033fa4cda8ccfc5481db3cfccd72650c
refs/heads/master
2023-09-04T06:31:47.899017
2023-08-03T16:19:12
2023-09-01T20:15:05
18,383,364
3,366
2,259
Apache-2.0
2023-08-17T13:17:13
2014-04-02T22:15:28
C
UTF-8
C
false
false
1,163
c
test-uuid.c
/* * Copyright (c) 2009, 2014 Nicira, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <config.h> #undef NDEBUG #include "util.h" #include "uuid.h" #include <stdio.h> #include "ovstest.h" static void test_uuid_main(int argc, char *argv[]) { struct uuid uuid; if (argc == 1) { uuid_generate(&uuid); } else if (argc == 2) { if (!uuid_from_string(&uuid, argv[1])) { ovs_fatal(0, "\"%s\" is not a valid UUID", argv[1]); } } else { ovs_fatal(0, "usage: %s [UUID]", argv[0]); } printf(UUID_FMT"\n", UUID_ARGS(&uuid)); } OVSTEST_REGISTER("test-uuid", test_uuid_main);
ea7a83534e99eb878f186369e32dd4d4d242d86a
fbd6afa22568045d8806ecdda93144d1a6e44af2
/Src/Representations/Configuration/StaticJointPoses.h
548959b12fe3245b5423bfd27f87bf487592ffed
[ "BSD-2-Clause" ]
permissive
bhuman/BHumanCodeRelease
5ccbcc60b968c12f29983992d603ab464a51051b
645031c46ff88efcf32129301d21e109857cde3d
refs/heads/master
2023-05-22T09:49:04.827692
2023-03-29T15:27:24
2023-03-29T15:27:24
15,512,849
212
151
null
2018-04-12T12:36:26
2013-12-29T18:24:40
C++
UTF-8
C
false
false
577
h
StaticJointPoses.h
/** * @file StaticJointPoses.h * This representation provides some usefull static joint positions * @author Philip Reichenberg */ #pragma once #include "Math/Angle.h" #include "RobotParts/Joints.h" #include "Streaming/Enum.h" #include "Streaming/AutoStreamable.h" #include "Streaming/EnumIndexedArray.h" STREAMABLE(StaticJointPoses, { ENUM(StaticJointPoseName, {, sit, sitBack, sitFront, sitBackAfterFall, sitFrontAfterFall, }), (ENUM_INDEXED_ARRAY(ENUM_INDEXED_ARRAY(Angle, Joints::Joint), StaticJointPoses::StaticJointPoseName)) pose, });
5476874e87f89b93a1e81fae5fae6e9da8208803
ae136810cbc2345572ed899629562e8ac501039e
/async/example-buffer.c
a55778dc871271ccad61ce199580c1330955d401
[ "BSD-3-Clause" ]
permissive
naasking/async.h
a9955177e7e0d6f0fae600401aac5b707e368aa3
427bd46a1389b594f6963df38323ebb38e55e93f
refs/heads/master
2023-07-07T17:27:17.270035
2022-03-16T19:06:40
2022-03-16T19:06:40
209,800,627
660
57
BSD-3-Clause
2023-05-21T17:08:50
2019-09-20T13:45:19
C
UTF-8
C
false
false
3,772
c
example-buffer.c
/* * Copyright (c) 2004-2005, Swedish Institute of Computer Science. * 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 Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE 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 INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * This file is part of the protothreads library. * * Authors: Adam Dunkels <adam@sics.se>, Sandro Magi <naasking@gmail.com> * * $Id: example-buffer.c,v 1.5 2005/10/07 05:21:33 adam Exp $ */ #ifdef _WIN32 #include <windows.h> #else #include <unistd.h> #endif #include <stdio.h> #include "async-sem.h" #define NUM_ITEMS 32 #define BUFSIZE 8 static int buffer[BUFSIZE]; static int bufptr; static void add_to_buffer(int item) { printf("Item %d added to buffer at place %d\n", item, bufptr); buffer[bufptr] = item; bufptr = (bufptr + 1) % BUFSIZE; } static int get_from_buffer(void) { int item; item = buffer[bufptr]; printf("Item %d retrieved from buffer at place %d\n", item, bufptr); bufptr = (bufptr + 1) % BUFSIZE; return item; } static int produce_item(void) { static int item = 0; printf("Item %d produced\n", item); return item++; } static void consume_item(int item) { printf("Item %d consumed\n", item); } static struct async_sem full, empty; static async producer(struct async *pt) { static int produced; async_begin(pt); for (produced = 0; produced < NUM_ITEMS; ++produced) { await_sem(&full); add_to_buffer(produce_item()); signal_sem(&empty); } async_end; } static async consumer(struct async *pt) { static int consumed; async_begin(pt); for (consumed = 0; consumed < NUM_ITEMS; ++consumed) { await_sem(&empty); consume_item(get_from_buffer()); signal_sem(&full); } async_end; } static async driver_thread(struct async *pt) { static struct async pt_producer, pt_consumer; async_begin(pt); init_sem(&empty, 0); init_sem(&full, BUFSIZE); async_init(&pt_producer); async_init(&pt_consumer); await(producer(&pt_producer) & consumer(&pt_consumer)); async_end; } int example_buffer(void) { struct async driver_pt; async_init(&driver_pt); while (!driver_thread(&driver_pt)) { /* * When running this example on a multitasking system, we must * give other processes a chance to run too and therefore we call * usleep() resp. Sleep() here. On a dedicated embedded system, * we usually do not need to do this. */ #ifdef _WIN32 Sleep(0); #else usleep(10); #endif } return 0; }
3106592098dab3024d5aeb6d219bbe9e857d4420
9c4ec01e04f7b0a1d213e1060c6b0a008dde7cbd
/series2/etampdet/etampdet_em2/src/main_xg25.c
9c6c32631bbd7abd65c6eeed238e6cdd180d9d3d
[ "Zlib" ]
permissive
SiliconLabs/peripheral_examples
edf5ee87cd0bcb2e7ad5066e278fa1ad3b92bd35
87b252e5a1bf5b36a548c121e8ffda085d3bcbc4
refs/heads/master
2023-07-26T22:20:57.916375
2023-07-07T18:18:01
2023-07-07T18:20:16
116,865,771
326
212
NOASSERTION
2021-06-17T20:12:04
2018-01-09T20:13:39
C
UTF-8
C
false
false
12,748
c
main_xg25.c
/***************************************************************************//** * @file main_xg25.c * @brief This project demonstrates the tamper detection module for EFR32xG25. * The example uses #defines to enable the ETAMPDET peripheral's channel 0 * and/or channel 1, and requires an external jumper-wire connection between the * ETAMPIN0 <-> ETAMPOUT0 and/or ETAMPIN1 <-> ETAMPOUT1 pins, as specified * in device datasheet and README. The application is configured similarly to * the em2_dcdc peripheral example, with EM2 DCDC enabled (VSCALE0), BURTC * running on LFRCO, and RAM retention on block 0 only. When a tamper event is * detected, the ETAMPDET peripheral is disabled and BURTC interrupts are * enabled. With each BURTC compare match interrupt LED0 or LED1 will toggle to * indicate the ETAMPDET tamper event on channel 0 or channel 1, respectively. * ******************************************************************************* * # License * <b>Copyright 2022 Silicon Laboratories Inc. www.silabs.com</b> ******************************************************************************* * * SPDX-License-Identifier: Zlib * * The licensor of this software is Silicon Laboratories Inc. * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. * ******************************************************************************* * # Evaluation Quality * This code has been minimally tested to ensure that it builds and is suitable * as a demonstration for evaluation purposes only. This code will be maintained * at the sole discretion of Silicon Labs. ******************************************************************************/ #include <stdio.h> #include "em_device.h" #include "em_chip.h" #include "em_cmu.h" #include "em_emu.h" #include "em_gpio.h" #include "em_burtc.h" #include "em_core.h" #include "em_rmu.h" #include "bsp.h" #include "mx25flash_spi.h" #define POWER_DOWN_RAM (1) // This is a temporary address to workaround a bug in EMU_RamPowerDown() #define SRAM_START SRAM_BASE + 0x6001 #ifdef _SILICON_LABS_32B_SERIES_2_CONFIG_7 #define LED_OUT 0 #else #define LED_OUT 1 #endif /* * These defines can be used to enable/disable each of ETAMPDET peripherals * two tamper detection channels */ #define ETAMP_CH0_EN 1 #define ETAMP_CH1_EN 1 // Number of 32.768 KHz LFRCO clocks between BURTC interrupts #define BURTC_IRQ_PERIOD 16384 // 500 ms toggle rate volatile uint8_t tamperDetectedCh0 = 0; volatile uint8_t tamperDetectedCh1 = 0; /***************************************************************************//** * @brief * Powers down the SPI flash on the radio board * * @details * A JEDEC standard SPI flash boots up in standby mode in order to * provide immediate access, such as when used it as a boot memory. * * Typical current draw in standby mode for the MX25R8035F device used * on EFR32 radio boards is 5 µA. * * JEDEC standard SPI flash memories have a lower current deep power-down * mode, which can be entered after sending the relevant commands. This is on * the order of 0.007 µA for the MX25R8035F. ******************************************************************************/ void powerDownSpiFlash(void) { FlashStatus status; MX25_init(); MX25_RSTEN(); MX25_RST(&status); MX25_DP(); MX25_deinit(); } /**************************************************************************//** * @brief GPIO Initializer *****************************************************************************/ void initGPIO(void) { // Enable GPIO clock branch CMU_ClockEnable(cmuClock_GPIO, true); // Configure LEDs as outputs; will toggle for tamper detection GPIO_PinModeSet(BSP_GPIO_LED0_PORT, BSP_GPIO_LED0_PIN, gpioModePushPull, !LED_OUT); GPIO_PinModeSet(BSP_GPIO_LED1_PORT, BSP_GPIO_LED1_PIN, gpioModePushPull, !LED_OUT); } /**************************************************************************//** * @brief Configure BURTC to interrupt every BURTC_IRQ_PERIOD *****************************************************************************/ void initBURTC(void) { // Setup BURTC parameters BURTC_Init_TypeDef burtcInit = BURTC_INIT_DEFAULT; burtcInit.start = false; burtcInit.compare0Top = true; // reset counter when counter reaches compare value // Initialize BURTC CMU_ClockEnable(cmuClock_BURTC, true); BURTC_Reset(); BURTC_Init(&burtcInit); BURTC_CounterReset(); BURTC_CompareSet(0, BURTC_IRQ_PERIOD); // top value BURTC_Enable(true); } /**************************************************************************//** * @brief BURTC Handler *****************************************************************************/ void BURTC_IRQHandler(void) { BURTC_IntClear(BURTC_IF_COMP); // compare match // Toggle LED based on first detected tamper event if (tamperDetectedCh0 == 1) GPIO_PinOutToggle(BSP_GPIO_LED0_PORT, BSP_GPIO_LED0_PIN); if (tamperDetectedCh1 == 1) GPIO_PinOutToggle(BSP_GPIO_LED1_PORT, BSP_GPIO_LED1_PIN); } /***************************************************************************//** * @brief ETAMPDET initialization ******************************************************************************/ void initETAMPDET() { uint8_t chnl0_en, chnl1_en; chnl0_en = 0; chnl1_en = 0; #ifdef ETAMP_CH0_EN #if (ETAMP_CH0_EN == 1) chnl0_en = 1; #endif #endif #ifdef ETAMP_CH1_EN #if (ETAMP_CH1_EN == 1) chnl1_en = 1; #endif #endif // Enable register clock; ETAMPDET clock not currently defined in em_cmu.h CMU->CLKEN1_SET = CMU_CLKEN1_ETAMPDET; if (chnl0_en == 1) { // Configure GPIO for ETAMPDET channel 0 // Disable GPIO signals associated with used ETAMPER channel 0 GPIO_PinModeSet(gpioPortA, 5, gpioModeDisabled, 0); GPIO_PinModeSet(gpioPortA, 6, gpioModeDisabled, 0); } if (chnl1_en == 1) { // Configure GPIO for ETAMPDET channel 1 // Disable GPIO signals associated with used ETAMPER channel 1 GPIO_PinModeSet(gpioPortD, 5, gpioModeDisabled, 0); GPIO_PinModeSet(gpioPortD, 4, gpioModeDisabled, 0); } // Make sure module is disabled before configuring ETAMPDET->EN_CLR = ETAMPDET_EN_EN; /* * Must wait for peripheral to disable before modifying other registers; if * register write is attempted before peripheral is disabled, hard fault will * occur. */ while(ETAMPDET->EN && ETAMPDET_EN_DISABLING); // Configure upper and lower prescaler values ETAMPDET->CLKPRESCVAL = ETAMPDET_CLKPRESCVAL_LOWERPRESC_DivideBy64 | ETAMPDET_CLKPRESCVAL_UPPERPRESC_Bypass; // Load a random seed value for channel 0/1 ETAMPDET->CHNLSEEDVAL0 = 0x167DC55F; ETAMPDET->CHNLSEEDVAL1 = 0x5F04B84A; ETAMPDET->IEN_SET = (chnl0_en << _ETAMPDET_IEN_TAMPDET0_SHIFT) | (chnl1_en << _ETAMPDET_IEN_TAMPDET1_SHIFT); /* * Additional ETAMPDET configurable settings; configuring for both channels * regardless of channel enablement */ ETAMPDET->CFG_SET = ETAMPDET_CFG_CHNLTAMPDETFILTEN0 | ETAMPDET_CFG_CHNLTAMPDETFILTEN1; ETAMPDET->CNTMISMATCHMAX = ETAMPDET_CNTMISMATCHMAX_CHNLCNTMISMATCHMAX0_DetectFilterThreshold4 | ETAMPDET_CNTMISMATCHMAX_CHNLCNTMISMATCHMAX1_DetectFilterThreshold4; ETAMPDET->CHNLFILTWINSIZE = ETAMPDET_CHNLFILTWINSIZE_CHNLFILTWINSIZE0_DetectFilterMovingWinSize10 | ETAMPDET_CHNLFILTWINSIZE_CHNLFILTWINSIZE1_DetectFilterMovingWinSize10; // Channel 0/1 pad enable ETAMPDET->CFG_SET = (chnl0_en << _ETAMPDET_CFG_CHNLPADEN0_SHIFT) | (chnl1_en << _ETAMPDET_CFG_CHNLPADEN1_SHIFT); // Enable ETAMPDET module if (chnl0_en || chnl1_en) ETAMPDET->EN_SET = ETAMPDET_EN_EN; // Load channel 0/1 linear feedback shift register (LFSR) seeds ETAMPDET->CMD_SET = (chnl0_en << _ETAMPDET_CMD_CHNLLOAD0_SHIFT) | (chnl1_en << _ETAMPDET_CMD_CHNLLOAD1_SHIFT); /* * Command register writes must synchronize with the LF clock * Check the SYNCBUSY register for busy status; wait for register write */ while (ETAMPDET->SYNCBUSY != 0); // Start channel 0/1 LFSR ETAMPDET->CMD_SET = (chnl0_en << _ETAMPDET_CMD_CHNLSTART0_SHIFT) | (chnl1_en << _ETAMPDET_CMD_CHNLSTART1_SHIFT); // Wait for register write while (ETAMPDET->SYNCBUSY != 0); NVIC_ClearPendingIRQ(ETAMPDET_IRQn); NVIC_EnableIRQ(ETAMPDET_IRQn); } /***************************************************************************//** * @brief ETAMPDET Interrupt Handler ******************************************************************************/ void ETAMPDET_IRQHandler(void) { // Set the appropriate channel flag for LED indicator if ((ETAMPDET->IF & _ETAMPDET_IF_TAMPDET0_MASK) == ETAMPDET_IF_TAMPDET0) tamperDetectedCh0 = 1; else if ((ETAMPDET->IF & _ETAMPDET_IF_TAMPDET1_MASK) == ETAMPDET_IF_TAMPDET1) tamperDetectedCh1 = 1; // Disable ETAMPDET module; no longer needed in typical applications ETAMPDET->EN_CLR = ETAMPDET_EN_EN; /* * Conventionally bad practice to have a while loop within an ISR, however * further register writes to ETAMPDET peripheral cannot occur until disable * completes; BURTC interrupt is the only task at risk of a delay. */ while(ETAMPDET->EN && ETAMPDET_EN_DISABLING); ETAMPDET->IEN_CLR = _ETAMPDET_IEN_MASK; ETAMPDET->IF_CLR = _ETAMPDET_IF_MASK; // Turn on BURTC interrupts for LED toggle; BURTC already running BURTC_IntEnable(BURTC_IEN_COMP); // BURTC interrupt on compare match NVIC_EnableIRQ(BURTC_IRQn); } /**************************************************************************//** * @brief escapeHatch() * When developing or debugging code that enters EM2 or * lower, it's a good idea to have an "escape hatch" type * mechanism, e.g. a way to pause the device so that a debugger can * connect in order to erase flash, among other things. * * Before proceeding with this example, make sure PB0 is not pressed. * If the PB0 pin is low, turn on LED0 and execute the breakpoint * instruction to stop the processor in EM0 and allow a debug * connection to be made. *****************************************************************************/ void escapeHatch(void) { CMU_ClockEnable(cmuClock_GPIO, true); GPIO_PinModeSet(BSP_GPIO_PB0_PORT, BSP_GPIO_PB0_PIN, gpioModeInputPullFilter, 1); if (GPIO_PinInGet(BSP_GPIO_PB0_PORT, BSP_GPIO_PB0_PIN) == 0) { GPIO_PinModeSet(BSP_GPIO_LED0_PORT, BSP_GPIO_LED0_PIN, gpioModePushPull, LED_OUT); __BKPT(0); } // Pin not asserted, so disable input else { GPIO_PinModeSet(BSP_GPIO_PB0_PORT, BSP_GPIO_PB0_PIN, gpioModeDisabled, (!LED_OUT)); CMU_ClockEnable(cmuClock_GPIO, false); } } /***************************************************************************//** * @brief Main function ******************************************************************************/ int main(void) { // Chip errata CHIP_Init(); /* * If PB0 is depressed during MCU reset, prevents EM2 entry allowing * debug/reprogram of device */ escapeHatch(); // Initialize GPIO for LEDs initGPIO(); // Turn on DCDC regulator EMU_DCDCInit_TypeDef dcdcInit = EMU_DCDCINIT_WSTK_DEFAULT; EMU_DCDCInit(&dcdcInit); // Enable voltage downscaling in EM mode 2 (VSCALE0) EMU_EM23Init_TypeDef em23Init = EMU_EM23INIT_DEFAULT; em23Init.vScaleEM23Voltage = emuVScaleEM23_LowPower; // Initialize EM23 energy modes EMU_EM23Init(&em23Init); // Power down the SPI flash powerDownSpiFlash(); // Route desired oscillator to shared BURTC/ETAMPDET clock tree CMU_ClockSelectSet(cmuClock_EM4GRPACLK, cmuSelect_LFRCO); /* * Initialize BURTC (attempt to match EM2 datasheet spec test configuration); * Interrupt not initially enabled */ initBURTC(); // Initialize ETAMPDET peripheral initETAMPDET(); // Power down all RAM blocks except block 0 if (POWER_DOWN_RAM) { EMU_RamPowerDown(SRAM_START, 0); } while (1) { // Enter EM2 EMU_EnterEM2(false); } }
d4602002f746bfc7f07111ba5509cfcebdd5a6b5
331640994b1b6f66c1639278571ddbdc6c8c0751
/src/nxt_router_request.h
6e226bae8b877d65e2d74429be843420a9c2cb59
[ "Apache-2.0" ]
permissive
nginx/unit
eabcd067eaa60f4bdcf0cfaffe7d9932add2c66a
9b22b6957bc87b3df002d0bc691fdae6a20abdac
refs/heads/master
2023-09-04T02:02:13.581700
2023-08-30T16:07:24
2023-08-30T16:07:24
102,627,638
4,649
452
Apache-2.0
2023-09-12T01:28:22
2017-09-06T15:45:30
C
UTF-8
C
false
false
790
h
nxt_router_request.h
/* * Copyright (C) NGINX, Inc. */ #ifndef _NXT_ROUTER_REQUEST_H_INCLUDED_ #define _NXT_ROUTER_REQUEST_H_INCLUDED_ typedef struct { nxt_buf_t *buf; nxt_fd_t body_fd; uint32_t tracking_cookie; } nxt_msg_info_t; typedef enum { NXT_APR_NEW_PORT, NXT_APR_REQUEST_FAILED, NXT_APR_GOT_RESPONSE, NXT_APR_UPGRADE, NXT_APR_CLOSE, } nxt_apr_action_t; typedef struct { uint32_t stream; nxt_app_t *app; nxt_port_t *app_port; nxt_apr_action_t apr_action; nxt_http_request_t *request; nxt_msg_info_t msg_info; nxt_bool_t rpc_cancel; } nxt_request_rpc_data_t; #endif /* _NXT_ROUTER_REQUEST_H_INCLUDED_ */
6355f98780391a6f76cfab511ead291b7c746aef
5aa8006a9a48e999fa5d5092fe893b16b84b7999
/src/main/routing/address.c
728c5f83d3c7395b63f28547e5dc58397abbd0e9
[ "LicenseRef-scancode-public-domain" ]
permissive
shadow/shadow
5a18451ac5a288f82f199ea59bc5adb783de9d7d
021dbe7672dbfede4c8093ccd260c61cd3986731
refs/heads/main
2023-09-02T19:47:30.119593
2023-09-01T00:18:23
2023-09-01T00:18:23
1,759,835
1,309
252
NOASSERTION
2023-09-14T19:17:48
2011-05-17T08:18:57
Rust
UTF-8
C
false
false
3,874
c
address.c
/* * The Shadow Simulator * Copyright (c) 2010-2011, Rob Jansen * See LICENSE for licensing information */ /* * host order INADDR_LOOPBACK: 2130706433, INADDR_ANY: 0, INADDR_NONE: 4294967295, INADDR_BROADCAST: 4294967295 * network order INADDR_LOOPBACK: 16777343, INADDR_ANY: 0, INADDR_NONE: 4294967295, INADDR_BROADCAST: 4294967295 */ /* IP must be first so we can cast an Address to an in_addr_t */ #include <arpa/inet.h> #include <glib.h> #include <netinet/in.h> #include <stddef.h> #include <sys/socket.h> #include "main/routing/address.h" #include "main/utility/utility.h" struct _Address { /* the IP in network-order */ guint32 ip; /* globally unique mac address */ guint mac; /* the host-order IP in dots-and-decimals format */ gchar* ipString; /* the hostname */ gchar* name; gchar* idString; gint referenceCount; gboolean isLocal; HostId hostID; MAGIC_DECLARE; }; Address* address_new(HostId hostID, guint mac, guint32 ip, const gchar* name, gboolean isLocal) { Address* address = g_new0(Address, 1); MAGIC_INIT(address); address->hostID = hostID; address->mac = mac; address->ip = ip; address->ipString = address_ipToNewString((in_addr_t)ip); address->isLocal = isLocal; address->name = g_strdup(name); address->referenceCount = 1; GString* stringBuffer = g_string_new(NULL); g_string_printf(stringBuffer, "%s-%s (%s,mac=%i)", address->name, address->ipString, address->isLocal ? "lo" : "eth", address->mac); address->idString = g_string_free(stringBuffer, FALSE); return address; } static void _address_free(Address* address) { MAGIC_ASSERT(address); g_free(address->ipString); g_free(address->name); g_free(address->idString); MAGIC_CLEAR(address); g_free(address); } HostId address_getID(const Address* address) { MAGIC_ASSERT(address); return address->hostID; } void address_ref(Address* address) { MAGIC_ASSERT(address); address->referenceCount++; } void address_unref(Address* address) { MAGIC_ASSERT(address); address->referenceCount--; if(address->referenceCount <= 0) { _address_free(address); } } gboolean address_isLocal(const Address* address) { MAGIC_ASSERT(address); return address->isLocal; } gboolean address_isEqual(Address* a, Address* b) { if(a == NULL && b == NULL) { return TRUE; } else if(a == NULL || b == NULL) { return FALSE; } else { MAGIC_ASSERT(a); MAGIC_ASSERT(b); return a->ip == b->ip; } } guint32 address_toHostIP(const Address* address) { MAGIC_ASSERT(address); return ntohl(address->ip); } const gchar* address_toHostIPString(const Address* address) { MAGIC_ASSERT(address); return address->ipString; } guint32 address_toNetworkIP(const Address* address) { MAGIC_ASSERT(address); return address->ip; } const gchar* address_toHostName(const Address* address) { MAGIC_ASSERT(address); return address->name; } const gchar* address_toString(const Address* address) { MAGIC_ASSERT(address); return address->idString; } // Address must be in network byte order. gchar* address_ipToNewString(in_addr_t ip) { gchar* ipStringBuffer = g_malloc0(INET6_ADDRSTRLEN + 1); struct in_addr addr = {.s_addr = ip}; const gchar* ipString = inet_ntop(AF_INET, &addr, ipStringBuffer, INET6_ADDRSTRLEN); GString* result = ipString ? g_string_new(ipString) : g_string_new("NULL"); g_free(ipStringBuffer); return g_string_free(result, FALSE); } // Returned address will be in network byte order. in_addr_t address_stringToIP(const gchar* ipString) { struct in_addr inaddr; if(1 == inet_pton(AF_INET, ipString, &inaddr)) { return inaddr.s_addr; } else { return INADDR_NONE; } }
32cb88883621d133a307752ae5c493657691010d
eecd5e4c50d8b78a769bcc2675250576bed34066
/src/tao/util/tao_util.c
d9da2c129c73debf2250bac23cd0d7f33d62b60d
[ "BSD-2-Clause" ]
permissive
petsc/petsc
3b1a04fea71858e0292f9fd4d04ea11618c50969
9c5460f9064ca60dd71a234a1f6faf93e7a6b0c9
refs/heads/main
2023-08-17T20:51:16.507070
2023-08-17T16:08:06
2023-08-17T16:08:06
8,691,401
341
169
NOASSERTION
2023-03-29T11:02:58
2013-03-10T20:55:21
C
UTF-8
C
false
false
16,955
c
tao_util.c
#include <petsc/private/petscimpl.h> #include <petsctao.h> /*I "petsctao.h" I*/ #include <petscsys.h> static inline PetscReal Fischer(PetscReal a, PetscReal b) { /* Method suggested by Bob Vanderbei */ if (a + b <= 0) return PetscSqrtReal(a * a + b * b) - (a + b); return -2.0 * a * b / (PetscSqrtReal(a * a + b * b) + (a + b)); } /*@ VecFischer - Evaluates the Fischer-Burmeister function for complementarity problems. Logically Collective Input Parameters: + X - current point . F - function evaluated at x . L - lower bounds - U - upper bounds Output Parameter: . FB - The Fischer-Burmeister function vector Level: developer Notes: The Fischer-Burmeister function is defined as $ phi(a,b) := sqrt(a*a + b*b) - a - b and is used reformulate a complementarity problem as a semismooth system of equations. The result of this function is done by cases\: + l[i] == -infinity, u[i] == infinity -- fb[i] = -f[i] . l[i] == -infinity, u[i] finite -- fb[i] = phi(u[i]-x[i], -f[i]) . l[i] finite, u[i] == infinity -- fb[i] = phi(x[i]-l[i], f[i]) . l[i] finite < u[i] finite -- fb[i] = phi(x[i]-l[i], phi(u[i]-x[i], -f[u])) - otherwise l[i] == u[i] -- fb[i] = l[i] - x[i] .seealso: `Vec`, `VecSFischer()`, `MatDFischer()`, `MatDSFischer()` @*/ PetscErrorCode VecFischer(Vec X, Vec F, Vec L, Vec U, Vec FB) { const PetscScalar *x, *f, *l, *u; PetscScalar *fb; PetscReal xval, fval, lval, uval; PetscInt low[5], high[5], n, i; PetscFunctionBegin; PetscValidHeaderSpecific(X, VEC_CLASSID, 1); PetscValidHeaderSpecific(F, VEC_CLASSID, 2); if (L) PetscValidHeaderSpecific(L, VEC_CLASSID, 3); if (U) PetscValidHeaderSpecific(U, VEC_CLASSID, 4); PetscValidHeaderSpecific(FB, VEC_CLASSID, 5); if (!L && !U) { PetscCall(VecAXPBY(FB, -1.0, 0.0, F)); PetscFunctionReturn(PETSC_SUCCESS); } PetscCall(VecGetOwnershipRange(X, low, high)); PetscCall(VecGetOwnershipRange(F, low + 1, high + 1)); PetscCall(VecGetOwnershipRange(L, low + 2, high + 2)); PetscCall(VecGetOwnershipRange(U, low + 3, high + 3)); PetscCall(VecGetOwnershipRange(FB, low + 4, high + 4)); for (i = 1; i < 4; ++i) PetscCheck(low[0] == low[i] && high[0] == high[i], PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Vectors must be identically loaded over processors"); PetscCall(VecGetArrayRead(X, &x)); PetscCall(VecGetArrayRead(F, &f)); PetscCall(VecGetArrayRead(L, &l)); PetscCall(VecGetArrayRead(U, &u)); PetscCall(VecGetArray(FB, &fb)); PetscCall(VecGetLocalSize(X, &n)); for (i = 0; i < n; ++i) { xval = PetscRealPart(x[i]); fval = PetscRealPart(f[i]); lval = PetscRealPart(l[i]); uval = PetscRealPart(u[i]); if (lval <= -PETSC_INFINITY && uval >= PETSC_INFINITY) { fb[i] = -fval; } else if (lval <= -PETSC_INFINITY) { fb[i] = -Fischer(uval - xval, -fval); } else if (uval >= PETSC_INFINITY) { fb[i] = Fischer(xval - lval, fval); } else if (lval == uval) { fb[i] = lval - xval; } else { fval = Fischer(uval - xval, -fval); fb[i] = Fischer(xval - lval, fval); } } PetscCall(VecRestoreArrayRead(X, &x)); PetscCall(VecRestoreArrayRead(F, &f)); PetscCall(VecRestoreArrayRead(L, &l)); PetscCall(VecRestoreArrayRead(U, &u)); PetscCall(VecRestoreArray(FB, &fb)); PetscFunctionReturn(PETSC_SUCCESS); } static inline PetscReal SFischer(PetscReal a, PetscReal b, PetscReal c) { /* Method suggested by Bob Vanderbei */ if (a + b <= 0) return PetscSqrtReal(a * a + b * b + 2.0 * c * c) - (a + b); return 2.0 * (c * c - a * b) / (PetscSqrtReal(a * a + b * b + 2.0 * c * c) + (a + b)); } /*@ VecSFischer - Evaluates the Smoothed Fischer-Burmeister function for complementarity problems. Logically Collective Input Parameters: + X - current point . F - function evaluated at x . L - lower bounds . U - upper bounds - mu - smoothing parameter Output Parameter: . FB - The Smoothed Fischer-Burmeister function vector Notes: The Smoothed Fischer-Burmeister function is defined as $ phi(a,b) := sqrt(a*a + b*b + 2*mu*mu) - a - b and is used reformulate a complementarity problem as a semismooth system of equations. The result of this function is done by cases\: + l[i] == -infinity, u[i] == infinity -- fb[i] = -f[i] - 2*mu*x[i] . l[i] == -infinity, u[i] finite -- fb[i] = phi(u[i]-x[i], -f[i], mu) . l[i] finite, u[i] == infinity -- fb[i] = phi(x[i]-l[i], f[i], mu) . l[i] finite < u[i] finite -- fb[i] = phi(x[i]-l[i], phi(u[i]-x[i], -f[u], mu), mu) - otherwise l[i] == u[i] -- fb[i] = l[i] - x[i] Level: developer .seealso: `Vec`, `VecFischer()`, `MatDFischer()`, `MatDSFischer()` @*/ PetscErrorCode VecSFischer(Vec X, Vec F, Vec L, Vec U, PetscReal mu, Vec FB) { const PetscScalar *x, *f, *l, *u; PetscScalar *fb; PetscReal xval, fval, lval, uval; PetscInt low[5], high[5], n, i; PetscFunctionBegin; PetscValidHeaderSpecific(X, VEC_CLASSID, 1); PetscValidHeaderSpecific(F, VEC_CLASSID, 2); PetscValidHeaderSpecific(L, VEC_CLASSID, 3); PetscValidHeaderSpecific(U, VEC_CLASSID, 4); PetscValidHeaderSpecific(FB, VEC_CLASSID, 6); PetscCall(VecGetOwnershipRange(X, low, high)); PetscCall(VecGetOwnershipRange(F, low + 1, high + 1)); PetscCall(VecGetOwnershipRange(L, low + 2, high + 2)); PetscCall(VecGetOwnershipRange(U, low + 3, high + 3)); PetscCall(VecGetOwnershipRange(FB, low + 4, high + 4)); for (i = 1; i < 4; ++i) PetscCheck(low[0] == low[i] && high[0] == high[i], PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Vectors must be identically loaded over processors"); PetscCall(VecGetArrayRead(X, &x)); PetscCall(VecGetArrayRead(F, &f)); PetscCall(VecGetArrayRead(L, &l)); PetscCall(VecGetArrayRead(U, &u)); PetscCall(VecGetArray(FB, &fb)); PetscCall(VecGetLocalSize(X, &n)); for (i = 0; i < n; ++i) { xval = PetscRealPart(*x++); fval = PetscRealPart(*f++); lval = PetscRealPart(*l++); uval = PetscRealPart(*u++); if ((lval <= -PETSC_INFINITY) && (uval >= PETSC_INFINITY)) { (*fb++) = -fval - mu * xval; } else if (lval <= -PETSC_INFINITY) { (*fb++) = -SFischer(uval - xval, -fval, mu); } else if (uval >= PETSC_INFINITY) { (*fb++) = SFischer(xval - lval, fval, mu); } else if (lval == uval) { (*fb++) = lval - xval; } else { fval = SFischer(uval - xval, -fval, mu); (*fb++) = SFischer(xval - lval, fval, mu); } } x -= n; f -= n; l -= n; u -= n; fb -= n; PetscCall(VecRestoreArrayRead(X, &x)); PetscCall(VecRestoreArrayRead(F, &f)); PetscCall(VecRestoreArrayRead(L, &l)); PetscCall(VecRestoreArrayRead(U, &u)); PetscCall(VecRestoreArray(FB, &fb)); PetscFunctionReturn(PETSC_SUCCESS); } static inline PetscReal fischnorm(PetscReal a, PetscReal b) { return PetscSqrtReal(a * a + b * b); } static inline PetscReal fischsnorm(PetscReal a, PetscReal b, PetscReal c) { return PetscSqrtReal(a * a + b * b + 2.0 * c * c); } /*@ MatDFischer - Calculates an element of the B-subdifferential of the Fischer-Burmeister function for complementarity problems. Collective Input Parameters: + jac - the jacobian of `f` at `X` . X - current point . Con - constraints function evaluated at `X` . XL - lower bounds . XU - upper bounds . T1 - work vector - T2 - work vector Output Parameters: + Da - diagonal perturbation component of the result - Db - row scaling component of the result Level: developer .seealso: `Mat`, `VecFischer()`, `VecSFischer()`, `MatDSFischer()` @*/ PetscErrorCode MatDFischer(Mat jac, Vec X, Vec Con, Vec XL, Vec XU, Vec T1, Vec T2, Vec Da, Vec Db) { PetscInt i, nn; const PetscScalar *x, *f, *l, *u, *t2; PetscScalar *da, *db, *t1; PetscReal ai, bi, ci, di, ei; PetscFunctionBegin; PetscCall(VecGetLocalSize(X, &nn)); PetscCall(VecGetArrayRead(X, &x)); PetscCall(VecGetArrayRead(Con, &f)); PetscCall(VecGetArrayRead(XL, &l)); PetscCall(VecGetArrayRead(XU, &u)); PetscCall(VecGetArray(Da, &da)); PetscCall(VecGetArray(Db, &db)); PetscCall(VecGetArray(T1, &t1)); PetscCall(VecGetArrayRead(T2, &t2)); for (i = 0; i < nn; i++) { da[i] = 0.0; db[i] = 0.0; t1[i] = 0.0; if (PetscAbsScalar(f[i]) <= PETSC_MACHINE_EPSILON) { if (PetscRealPart(l[i]) > PETSC_NINFINITY && PetscAbsScalar(x[i] - l[i]) <= PETSC_MACHINE_EPSILON) { t1[i] = 1.0; da[i] = 1.0; } if (PetscRealPart(u[i]) < PETSC_INFINITY && PetscAbsScalar(u[i] - x[i]) <= PETSC_MACHINE_EPSILON) { t1[i] = 1.0; db[i] = 1.0; } } } PetscCall(VecRestoreArray(T1, &t1)); PetscCall(VecRestoreArrayRead(T2, &t2)); PetscCall(MatMult(jac, T1, T2)); PetscCall(VecGetArrayRead(T2, &t2)); for (i = 0; i < nn; i++) { if ((PetscRealPart(l[i]) <= PETSC_NINFINITY) && (PetscRealPart(u[i]) >= PETSC_INFINITY)) { da[i] = 0.0; db[i] = -1.0; } else if (PetscRealPart(l[i]) <= PETSC_NINFINITY) { if (PetscRealPart(db[i]) >= 1) { ai = fischnorm(1.0, PetscRealPart(t2[i])); da[i] = -1.0 / ai - 1.0; db[i] = -t2[i] / ai - 1.0; } else { bi = PetscRealPart(u[i]) - PetscRealPart(x[i]); ai = fischnorm(bi, PetscRealPart(f[i])); ai = PetscMax(PETSC_MACHINE_EPSILON, ai); da[i] = bi / ai - 1.0; db[i] = -f[i] / ai - 1.0; } } else if (PetscRealPart(u[i]) >= PETSC_INFINITY) { if (PetscRealPart(da[i]) >= 1) { ai = fischnorm(1.0, PetscRealPart(t2[i])); da[i] = 1.0 / ai - 1.0; db[i] = t2[i] / ai - 1.0; } else { bi = PetscRealPart(x[i]) - PetscRealPart(l[i]); ai = fischnorm(bi, PetscRealPart(f[i])); ai = PetscMax(PETSC_MACHINE_EPSILON, ai); da[i] = bi / ai - 1.0; db[i] = f[i] / ai - 1.0; } } else if (PetscRealPart(l[i]) == PetscRealPart(u[i])) { da[i] = -1.0; db[i] = 0.0; } else { if (PetscRealPart(db[i]) >= 1) { ai = fischnorm(1.0, PetscRealPart(t2[i])); ci = 1.0 / ai + 1.0; di = PetscRealPart(t2[i]) / ai + 1.0; } else { bi = PetscRealPart(x[i]) - PetscRealPart(u[i]); ai = fischnorm(bi, PetscRealPart(f[i])); ai = PetscMax(PETSC_MACHINE_EPSILON, ai); ci = bi / ai + 1.0; di = PetscRealPart(f[i]) / ai + 1.0; } if (PetscRealPart(da[i]) >= 1) { bi = ci + di * PetscRealPart(t2[i]); ai = fischnorm(1.0, bi); bi = bi / ai - 1.0; ai = 1.0 / ai - 1.0; } else { ei = Fischer(PetscRealPart(u[i]) - PetscRealPart(x[i]), -PetscRealPart(f[i])); ai = fischnorm(PetscRealPart(x[i]) - PetscRealPart(l[i]), ei); ai = PetscMax(PETSC_MACHINE_EPSILON, ai); bi = ei / ai - 1.0; ai = (PetscRealPart(x[i]) - PetscRealPart(l[i])) / ai - 1.0; } da[i] = ai + bi * ci; db[i] = bi * di; } } PetscCall(VecRestoreArray(Da, &da)); PetscCall(VecRestoreArray(Db, &db)); PetscCall(VecRestoreArrayRead(X, &x)); PetscCall(VecRestoreArrayRead(Con, &f)); PetscCall(VecRestoreArrayRead(XL, &l)); PetscCall(VecRestoreArrayRead(XU, &u)); PetscCall(VecRestoreArrayRead(T2, &t2)); PetscFunctionReturn(PETSC_SUCCESS); } /*@ MatDSFischer - Calculates an element of the B-subdifferential of the smoothed Fischer-Burmeister function for complementarity problems. Collective Input Parameters: + jac - the jacobian of f at X . X - current point . Con - constraint function evaluated at X . XL - lower bounds . XU - upper bounds . mu - smoothing parameter . T1 - work vector - T2 - work vector Output Parameters: + Da - diagonal perturbation component of the result . Db - row scaling component of the result - Dm - derivative with respect to scaling parameter Level: developer .seealso: `Mat`, `VecFischer()`, `VecDFischer()`, `MatDFischer()` @*/ PetscErrorCode MatDSFischer(Mat jac, Vec X, Vec Con, Vec XL, Vec XU, PetscReal mu, Vec T1, Vec T2, Vec Da, Vec Db, Vec Dm) { PetscInt i, nn; const PetscScalar *x, *f, *l, *u; PetscScalar *da, *db, *dm; PetscReal ai, bi, ci, di, ei, fi; PetscFunctionBegin; if (PetscAbsReal(mu) <= PETSC_MACHINE_EPSILON) { PetscCall(VecZeroEntries(Dm)); PetscCall(MatDFischer(jac, X, Con, XL, XU, T1, T2, Da, Db)); } else { PetscCall(VecGetLocalSize(X, &nn)); PetscCall(VecGetArrayRead(X, &x)); PetscCall(VecGetArrayRead(Con, &f)); PetscCall(VecGetArrayRead(XL, &l)); PetscCall(VecGetArrayRead(XU, &u)); PetscCall(VecGetArray(Da, &da)); PetscCall(VecGetArray(Db, &db)); PetscCall(VecGetArray(Dm, &dm)); for (i = 0; i < nn; ++i) { if ((PetscRealPart(l[i]) <= PETSC_NINFINITY) && (PetscRealPart(u[i]) >= PETSC_INFINITY)) { da[i] = -mu; db[i] = -1.0; dm[i] = -x[i]; } else if (PetscRealPart(l[i]) <= PETSC_NINFINITY) { bi = PetscRealPart(u[i]) - PetscRealPart(x[i]); ai = fischsnorm(bi, PetscRealPart(f[i]), mu); ai = PetscMax(PETSC_MACHINE_EPSILON, ai); da[i] = bi / ai - 1.0; db[i] = -PetscRealPart(f[i]) / ai - 1.0; dm[i] = 2.0 * mu / ai; } else if (PetscRealPart(u[i]) >= PETSC_INFINITY) { bi = PetscRealPart(x[i]) - PetscRealPart(l[i]); ai = fischsnorm(bi, PetscRealPart(f[i]), mu); ai = PetscMax(PETSC_MACHINE_EPSILON, ai); da[i] = bi / ai - 1.0; db[i] = PetscRealPart(f[i]) / ai - 1.0; dm[i] = 2.0 * mu / ai; } else if (PetscRealPart(l[i]) == PetscRealPart(u[i])) { da[i] = -1.0; db[i] = 0.0; dm[i] = 0.0; } else { bi = PetscRealPart(x[i]) - PetscRealPart(u[i]); ai = fischsnorm(bi, PetscRealPart(f[i]), mu); ai = PetscMax(PETSC_MACHINE_EPSILON, ai); ci = bi / ai + 1.0; di = PetscRealPart(f[i]) / ai + 1.0; fi = 2.0 * mu / ai; ei = SFischer(PetscRealPart(u[i]) - PetscRealPart(x[i]), -PetscRealPart(f[i]), mu); ai = fischsnorm(PetscRealPart(x[i]) - PetscRealPart(l[i]), ei, mu); ai = PetscMax(PETSC_MACHINE_EPSILON, ai); bi = ei / ai - 1.0; ei = 2.0 * mu / ei; ai = (PetscRealPart(x[i]) - PetscRealPart(l[i])) / ai - 1.0; da[i] = ai + bi * ci; db[i] = bi * di; dm[i] = ei + bi * fi; } } PetscCall(VecRestoreArrayRead(X, &x)); PetscCall(VecRestoreArrayRead(Con, &f)); PetscCall(VecRestoreArrayRead(XL, &l)); PetscCall(VecRestoreArrayRead(XU, &u)); PetscCall(VecRestoreArray(Da, &da)); PetscCall(VecRestoreArray(Db, &db)); PetscCall(VecRestoreArray(Dm, &dm)); } PetscFunctionReturn(PETSC_SUCCESS); } static inline PetscReal ST_InternalPN(PetscScalar in, PetscReal lb, PetscReal ub) { return PetscMax(0, (PetscReal)PetscRealPart(in) - ub) - PetscMax(0, -(PetscReal)PetscRealPart(in) - PetscAbsReal(lb)); } static inline PetscReal ST_InternalNN(PetscScalar in, PetscReal lb, PetscReal ub) { return PetscMax(0, (PetscReal)PetscRealPart(in) + PetscAbsReal(ub)) - PetscMax(0, -(PetscReal)PetscRealPart(in) - PetscAbsReal(lb)); } static inline PetscReal ST_InternalPP(PetscScalar in, PetscReal lb, PetscReal ub) { return PetscMax(0, (PetscReal)PetscRealPart(in) - ub) + PetscMin(0, (PetscReal)PetscRealPart(in) - lb); } /*@ TaoSoftThreshold - Calculates soft thresholding routine with input vector and given lower and upper bound and returns it to output vector. Input Parameters: + in - input vector to be thresholded . lb - lower bound - ub - upper bound Output Parameter: . out - Soft thresholded output vector Notes: Soft thresholding is defined as \[ S(input,lb,ub) = \begin{cases} input - ub \text{input > ub} \\ 0 \text{lb =< input <= ub} \\ input + lb \text{input < lb} \\ \] Level: developer .seealso: `Tao`, `Vec` @*/ PetscErrorCode TaoSoftThreshold(Vec in, PetscReal lb, PetscReal ub, Vec out) { PetscInt i, nlocal, mlocal; PetscScalar *inarray, *outarray; PetscFunctionBegin; PetscCall(VecGetArrayPair(in, out, &inarray, &outarray)); PetscCall(VecGetLocalSize(in, &nlocal)); PetscCall(VecGetLocalSize(in, &mlocal)); PetscCheck(nlocal == mlocal, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Input and output vectors need to be of same size."); PetscCheck(lb < ub, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Lower bound needs to be lower than upper bound."); if (ub >= 0 && lb < 0) { for (i = 0; i < nlocal; i++) outarray[i] = ST_InternalPN(inarray[i], lb, ub); } else if (ub < 0 && lb < 0) { for (i = 0; i < nlocal; i++) outarray[i] = ST_InternalNN(inarray[i], lb, ub); } else { for (i = 0; i < nlocal; i++) outarray[i] = ST_InternalPP(inarray[i], lb, ub); } PetscCall(VecRestoreArrayPair(in, out, &inarray, &outarray)); PetscFunctionReturn(PETSC_SUCCESS); }
bee8512596e51336367143f6d8c2f8afe9f3d7fc
de21f9075f55640514c29ef0f1fe3f0690845764
/regression/contracts-dfcc/frees-clause-and-predicates-is_freed-bad-arity/main.c
51209b124a27f6d4e349d81d0deaa7aead608ef1
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference", "BSD-4-Clause" ]
permissive
diffblue/cbmc
975a074ac445febb3b5715f8792beb545522dc18
decd2839c2f51a54b2ad0f3e89fdc1b4bf78cd16
refs/heads/develop
2023-08-31T05:52:05.342195
2023-08-30T13:31:51
2023-08-30T13:31:51
51,877,056
589
309
NOASSERTION
2023-09-14T18:49:17
2016-02-16T23:03:52
C++
UTF-8
C
false
false
242
c
main.c
#include <stdlib.h> void foo(char *arr) __CPROVER_requires(__CPROVER_is_freeable(arr)) __CPROVER_ensures(__CPROVER_was_freed(__CPROVER_old(arr), 1)) { free(arr); } int main() { size_t size; char arr[size]; foo(arr); return 0; }
9abafe37d63656c1fd971738dc5f29b23ca9b3e1
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/u-boot_new/include/configs/TOP5200.h
92128b95884247dcdb2516d97aad227f6a55a109
[ "GPL-2.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
11,927
h
TOP5200.h
/* * (C) Copyright 2003 * Wolfgang Denk, DENX Software Engineering, wd@denx.de. * * modified for TOP5200-series by Reinhard Meyer, www.emk-elektronik.de * * TOP5200 differences from IceCube: * 1 FLASH Bank for one Chip only, up to 64 MB in 16 MB Banks * bank switch controlled by TIMER_6(LSB) and TIMER_7(MSB) Pins * 1 SDRAM/DDRAM Bank up to 256 MB * local VPD I2C Bus is software driven and uses * GPIO_WKUP_6 for SDA, GPIO_WKUP_7 for SCL * FLASH is re-located at 0xff000000 * Internal regs are at 0xf0000000 * Reset jumps to 0x00000100 * * SPDX-License-Identifier: GPL-2.0+ */ #ifndef __CONFIG_H #define __CONFIG_H /* * High Level Configuration Options * (easy to change) */ #define CONFIG_MPC5200 1 /* This is a MPC5200 CPU */ #define CONFIG_TOP5200 1 /* ... on TOP5200 board - we need this for FEC.C */ /* * allowed and functional CONFIG_SYS_TEXT_BASE values: * 0xff000000 low boot at 0x00000100 (default board setting) * 0xfff00000 high boot at 0xfff00100 (board needs modification) * 0x00100000 RAM load and test */ #define CONFIG_SYS_TEXT_BASE 0xff000000 #define CONFIG_SYS_MPC5XXX_CLKIN 33000000 /* ... running at 33.000000MHz */ #define CONFIG_HIGH_BATS 1 /* High BATs supported */ /* * Serial console configuration */ #define CONFIG_PSC_CONSOLE 1 /* console is on PSC1 */ #define CONFIG_BAUDRATE 9600 /* ... at 9600 bps */ #define CONFIG_SYS_BAUDRATE_TABLE { 9600, 19200, 38400, 57600, 115200, 230400 } #if defined (CONFIG_EVAL5200) || defined (CONFIG_LITE5200) /* * PCI Mapping: * 0x40000000 - 0x4fffffff - PCI Memory * 0x50000000 - 0x50ffffff - PCI IO Space */ # define CONFIG_PCI 1 # define CONFIG_PCI_PNP 1 # define CONFIG_PCI_SCAN_SHOW 1 # define CONFIG_PCIAUTO_SKIP_HOST_BRIDGE 1 # define CONFIG_PCI_MEM_BUS 0x40000000 # define CONFIG_PCI_MEM_PHYS CONFIG_PCI_MEM_BUS # define CONFIG_PCI_MEM_SIZE 0x10000000 # define CONFIG_PCI_IO_BUS 0x50000000 # define CONFIG_PCI_IO_PHYS CONFIG_PCI_IO_BUS # define CONFIG_PCI_IO_SIZE 0x01000000 #endif /* USB */ #if defined (CONFIG_EVAL5200) || defined (CONFIG_LITE5200) # define CONFIG_USB_OHCI # define CONFIG_USB_CLOCK 0x0001bbbb # if defined (CONFIG_EVAL5200) # define CONFIG_USB_CONFIG 0x00005100 # else # define CONFIG_USB_CONFIG 0x00001000 # endif # define CONFIG_DOS_PARTITION # define CONFIG_USB_STORAGE #endif /* IDE */ #if defined (CONFIG_EVAL5200) || defined (CONFIG_LITE5200) # define CONFIG_DOS_PARTITION #endif /* * BOOTP options */ #define CONFIG_BOOTP_BOOTFILESIZE #define CONFIG_BOOTP_BOOTPATH #define CONFIG_BOOTP_GATEWAY #define CONFIG_BOOTP_HOSTNAME /* * Command line configuration. */ #include <config_cmd_default.h> #define CONFIG_CMD_ASKENV #define CONFIG_CMD_BEDBUG #define CONFIG_CMD_DATE #define CONFIG_CMD_DHCP #define CONFIG_CMD_EEPROM #define CONFIG_CMD_ELF #define CONFIG_CMD_I2C #define CONFIG_CMD_IMMAP #define CONFIG_CMD_MII #define CONFIG_CMD_REGINFO #if defined (CONFIG_EVAL5200) || defined (CONFIG_LITE5200) #define CONFIG_CMD_FAT #define CONFIG_CMD_IDE #define CONFIG_CMD_USB #define CONFIG_CMD_PCI #endif /* * MUST be low boot - HIGHBOOT is not supported anymore */ #if (CONFIG_SYS_TEXT_BASE == 0xFF000000) /* Boot low with 16 MB Flash */ # define CONFIG_SYS_LOWBOOT 1 # define CONFIG_SYS_LOWBOOT16 1 #else # error "CONFIG_SYS_TEXT_BASE must be 0xff000000" #endif /* * Autobooting */ #define CONFIG_BOOTDELAY 5 /* autoboot after 5 seconds */ #define CONFIG_PREBOOT "echo;" \ "echo Type \\\"run flash_nfs\\\" to mount root filesystem over NFS;" \ "echo" #undef CONFIG_BOOTARGS #define CONFIG_EXTRA_ENV_SETTINGS \ "netdev=eth0\0" \ "nfsargs=setenv bootargs root=/dev/nfs rw " \ "nfsroot=${serverip}:${rootpath}\0" \ "ramargs=setenv bootargs root=/dev/ram rw\0" \ "addip=setenv bootargs ${bootargs} " \ "ip=${ipaddr}:${serverip}:${gatewayip}:${netmask}" \ ":${hostname}:${netdev}:off panic=1\0" \ "flash_nfs=run nfsargs addip;" \ "bootm ${kernel_addr}\0" \ "flash_self=run ramargs addip;" \ "bootm ${kernel_addr} ${ramdisk_addr}\0" \ "net_nfs=tftp 200000 ${bootfile};run nfsargs addip;bootm\0" \ "rootpath=/opt/eldk/ppc_82xx\0" \ "bootfile=/tftpboot/MPC5200/uImage\0" \ "" #define CONFIG_BOOTCOMMAND "run flash_self" /* * IPB Bus clocking configuration. */ #undef CONFIG_SYS_IPBCLK_EQUALS_XLBCLK /* define for 133MHz speed */ /* * I2C configuration */ /* * EEPROM configuration */ #define CONFIG_SYS_EEPROM_PAGE_WRITE_BITS 3 #define CONFIG_SYS_EEPROM_PAGE_WRITE_DELAY_MS 70 #define CONFIG_SYS_I2C_EEPROM_ADDR_LEN 2 #define CONFIG_SYS_EEPROM_SIZE 0x2000 #define CONFIG_ENV_OVERWRITE #define CONFIG_MISC_INIT_R #define CONFIG_SYS_I2C_SOFT /* I2C bit-banged */ #if defined(CONFIG_SYS_I2C_SOFT) # define CONFIG_SYS_I2C # define CONFIG_SYS_I2C_SOFT_SPEED 100000 # define CONFIG_SYS_I2C_SOFT_SLAVE 0x7F /**/ # define SDA0 0x40 # define SCL0 0x80 # define GPIOE0 *((volatile uchar*)(CONFIG_SYS_MBAR+0x0c00)) # define DDR0 *((volatile uchar*)(CONFIG_SYS_MBAR+0x0c08)) # define DVO0 *((volatile uchar*)(CONFIG_SYS_MBAR+0x0c0c)) # define DVI0 *((volatile uchar*)(CONFIG_SYS_MBAR+0x0c20)) # define ODE0 *((volatile uchar*)(CONFIG_SYS_MBAR+0x0c04)) # define I2C_INIT {GPIOE0|=(SDA0|SCL0);ODE0|=(SDA0|SCL0);DVO0|=(SDA0|SCL0);DDR0|=(SDA0|SCL0);} # define I2C_READ ((DVI0&SDA0)?1:0) # define I2C_SDA(x) {if(x)DVO0|=SDA0;else DVO0&=~SDA0;} # define I2C_SCL(x) {if(x)DVO0|=SCL0;else DVO0&=~SCL0;} # define I2C_DELAY {udelay(5);} # define I2C_ACTIVE {DDR0|=SDA0;} # define I2C_TRISTATE {DDR0&=~SDA0;} #define CONFIG_SYS_I2C_EEPROM_ADDR 0x57 #define CONFIG_SYS_I2C_FACT_ADDR 0x57 #endif #if defined (CONFIG_HARD_I2C) # define CONFIG_SYS_I2C_MODULE 2 /* Select I2C module #1 or #2 */ # define CONFIG_SYS_I2C_SPEED 100000 /* 100 kHz */ # define CONFIG_SYS_I2C_SLAVE 0x7F #define CONFIG_SYS_I2C_EEPROM_ADDR 0x54 #define CONFIG_SYS_I2C_FACT_ADDR 0x54 #endif /* * Flash configuration, expect one 16 Megabyte Bank at most */ #define CONFIG_SYS_FLASH_BASE 0xff000000 #define CONFIG_SYS_FLASH_SIZE 0x01000000 #define CONFIG_SYS_MAX_FLASH_BANKS 1 /* max num of memory banks */ #define CONFIG_ENV_ADDR (CONFIG_SYS_FLASH_BASE + 0) #define CONFIG_SYS_MAX_FLASH_SECT 256 /* max num of sects on one chip */ #define CONFIG_SYS_FLASH_ERASE_TOUT 240000 /* Flash Erase Timeout (in ms) */ #define CONFIG_SYS_FLASH_WRITE_TOUT 500 /* Flash Write Timeout (in ms) */ #undef CONFIG_FLASH_16BIT /* Flash is 8-bit */ /* * DRAM configuration - will be read from VPD later... TODO! */ #if 0 /* 2x MT48LC16M16A2 - 7.0 ns SDRAMS = 64 MegaBytes Total */ #define CONFIG_SYS_DRAM_DDR 0 #define CONFIG_SYS_DRAM_EMODE 0 #define CONFIG_SYS_DRAM_MODE 0x008D #define CONFIG_SYS_DRAM_CONTROL 0x514F0000 #define CONFIG_SYS_DRAM_CONFIG1 0xC2233A00 #define CONFIG_SYS_DRAM_CONFIG2 0x88B70004 #define CONFIG_SYS_DRAM_TAP_DEL 0x08 #define CONFIG_SYS_DRAM_RAM_SIZE 0x19 #endif #if 1 /* 2x MT48LC16M16A2 - 7.5 ns SDRAMS = 64 MegaBytes Total */ #define CONFIG_SYS_DRAM_DDR 0 #define CONFIG_SYS_DRAM_EMODE 0 #define CONFIG_SYS_DRAM_MODE 0x00CD #define CONFIG_SYS_DRAM_CONTROL 0x514F0000 #define CONFIG_SYS_DRAM_CONFIG1 0xD2333A00 #define CONFIG_SYS_DRAM_CONFIG2 0x8AD70004 #define CONFIG_SYS_DRAM_TAP_DEL 0x08 #define CONFIG_SYS_DRAM_RAM_SIZE 0x19 #endif /* * Environment settings */ #define CONFIG_ENV_IS_IN_EEPROM 1 /* turn on EEPROM env feature */ #define CONFIG_ENV_OFFSET 0x1000 #define CONFIG_ENV_SIZE 0x0700 /* * VPD settings */ #define CONFIG_SYS_FACT_OFFSET 0x1800 #define CONFIG_SYS_FACT_SIZE 0x0800 /* * Memory map * * Warning!!! with the current BestComm Task, MBAR MUST BE set to 0xf0000000 */ #define CONFIG_SYS_MBAR 0xf0000000 /* DO NOT CHANGE this */ #define CONFIG_SYS_SDRAM_BASE 0x00000000 #define CONFIG_SYS_DEFAULT_MBAR 0x80000000 /* Use SRAM until RAM will be available */ #define CONFIG_SYS_INIT_RAM_ADDR MPC5XXX_SRAM #define CONFIG_SYS_INIT_RAM_SIZE MPC5XXX_SRAM_SIZE /* Size of used area in DPRAM */ #define CONFIG_SYS_GBL_DATA_OFFSET (CONFIG_SYS_INIT_RAM_SIZE - GENERATED_GBL_DATA_SIZE) #define CONFIG_SYS_INIT_SP_OFFSET CONFIG_SYS_GBL_DATA_OFFSET #define CONFIG_SYS_MONITOR_BASE CONFIG_SYS_TEXT_BASE #if (CONFIG_SYS_MONITOR_BASE < CONFIG_SYS_FLASH_BASE) # define CONFIG_SYS_RAMBOOT 1 #endif #define CONFIG_SYS_MONITOR_LEN (256 << 10) /* Reserve 256 kB for Monitor */ #define CONFIG_SYS_MALLOC_LEN (128 << 10) /* Reserve 128 kB for malloc() */ #define CONFIG_SYS_BOOTMAPSZ (8 << 20) /* Initial Memory map for Linux */ /* * Ethernet configuration */ #define CONFIG_MPC5xxx_FEC 1 #define CONFIG_MPC5xxx_FEC_MII10 /* Workaround for FEC 100Mbit problem */ #define CONFIG_PHY_ADDR 0x1f #define CONFIG_PHY_TYPE 0x79c874 /* * GPIO configuration: * PSC1,2,3 predefined as UART * PCI disabled * Ethernet 100 with MD */ #define CONFIG_SYS_GPS_PORT_CONFIG 0x00058044 /* * Miscellaneous configurable options */ #define CONFIG_SYS_LONGHELP /* undef to save memory */ #if defined(CONFIG_CMD_KGDB) # define CONFIG_SYS_CBSIZE 1024 /* Console I/O Buffer Size */ #else # define CONFIG_SYS_CBSIZE 256 /* Console I/O Buffer Size */ #endif #define CONFIG_SYS_PBSIZE (CONFIG_SYS_CBSIZE+sizeof(CONFIG_SYS_PROMPT)+16) /* Print Buffer Size */ #define CONFIG_SYS_MAXARGS 16 /* max number of command args */ #define CONFIG_SYS_BARGSIZE CONFIG_SYS_CBSIZE /* Boot Argument Buffer Size */ #define CONFIG_SYS_MEMTEST_START 0x00100000 /* memtest works on */ #define CONFIG_SYS_MEMTEST_END 0x01f00000 /* 1 ... 31 MB in DRAM */ #define CONFIG_SYS_LOAD_ADDR 0x200000 /* default load address */ #define CONFIG_SYS_CACHELINE_SIZE 32 /* For MPC5xxx CPUs */ #if defined(CONFIG_CMD_KGDB) # define CONFIG_SYS_CACHELINE_SHIFT 5 /* log base 2 of the above value */ #endif #ifdef CONFIG_EVAL5200 /* M48T08 is available with the Evaluation board only */ #define CONFIG_RTC_MK48T59 1 /* use M48T08 on EVAL5200 */ #define RTC(reg) (0xf0010000+reg) /* setup CS2 for M48T08. Must MAP 64kB */ #define CONFIG_SYS_CS2_START RTC(0) #define CONFIG_SYS_CS2_SIZE 0x10000 /* setup CS2 configuration register: */ /* WaitP = 0, WaitX = 4, MX=0, AL=1, AA=1, CE=1 */ /* AS=2, DS=0, Bank=0, WTyp=0, WS=0, RS=0, WO=0, RO=0 */ #define CONFIG_SYS_CS2_CFG 0x00047800 #else #define CONFIG_RTC_MPC5200 1 /* use internal MPC5200 RTC */ #endif /* * Various low-level settings */ #define CONFIG_SYS_HID0_INIT HID0_ICE | HID0_ICFI #define CONFIG_SYS_HID0_FINAL HID0_ICE #define CONFIG_SYS_BOOTCS_START CONFIG_SYS_FLASH_BASE #define CONFIG_SYS_BOOTCS_SIZE CONFIG_SYS_FLASH_SIZE #define CONFIG_SYS_BOOTCS_CFG 0x00047801 #define CONFIG_SYS_CS0_START CONFIG_SYS_FLASH_BASE #define CONFIG_SYS_CS0_SIZE CONFIG_SYS_FLASH_SIZE #define CONFIG_SYS_CS_BURST 0x00000000 #define CONFIG_SYS_CS_DEADCYCLE 0x33333333 #define CONFIG_SYS_RESET_ADDRESS 0x7f000000 /*----------------------------------------------------------------------- * IDE/ATA stuff Supports IDE harddisk *----------------------------------------------------------------------- */ #undef CONFIG_IDE_8xx_PCCARD /* Use IDE with PC Card Adapter */ #undef CONFIG_IDE_8xx_DIRECT /* Direct IDE not supported */ #undef CONFIG_IDE_LED /* LED for ide not supported */ #define CONFIG_IDE_RESET 1 #define CONFIG_IDE_PREINIT #define CONFIG_SYS_IDE_MAXBUS 1 /* max. 1 IDE bus */ #define CONFIG_SYS_IDE_MAXDEVICE 1 /* max. 1 drive per IDE bus */ #define CONFIG_SYS_ATA_IDE0_OFFSET 0x0000 #define CONFIG_SYS_ATA_BASE_ADDR MPC5XXX_ATA /* Offset for data I/O */ #define CONFIG_SYS_ATA_DATA_OFFSET (0x0060) /* Offset for normal register accesses */ #define CONFIG_SYS_ATA_REG_OFFSET (CONFIG_SYS_ATA_DATA_OFFSET) /* Offset for alternate registers */ #define CONFIG_SYS_ATA_ALT_OFFSET (0x005c) /* Interval between registers */ #define CONFIG_SYS_ATA_STRIDE 4 #endif /* __CONFIG_H */
566cc4b86eaedca8d3236debbbb3247fc9dccb03
5d2934b38bb87b806d5ef36f7e61cf72d4064a20
/Ports/RX/IAR/os_cpu.h
9f1c9d2a0cd31f0b9f3f6f5b4e96e7930f6843c8
[ "Apache-2.0", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-free-unknown" ]
permissive
weston-embedded/uC-OS2
83cae77ff97bb921c5fef81f827884eab405eaab
bfc6120f20cb27a927a9fc5dd667f9e455495777
refs/heads/develop
2023-01-10T09:41:16.763300
2023-01-05T18:18:13
2023-01-05T18:18:13
243,857,957
347
123
Apache-2.0
2023-01-12T22:57:11
2020-02-28T21:30:55
C
UTF-8
C
false
false
5,986
h
os_cpu.h
/* ********************************************************************************************************* * uC/OS-II * The Real-Time Kernel * * Copyright 1992-2021 Silicon Laboratories Inc. www.silabs.com * * SPDX-License-Identifier: APACHE-2.0 * * This software is subject to an open source license and is distributed by * Silicon Laboratories Inc. pursuant to the terms of the Apache License, * Version 2.0 available at www.apache.org/licenses/LICENSE-2.0. * ********************************************************************************************************* */ /* ********************************************************************************************************* * * Renesas RX Specific Code * * Filename : os_cpu.h * Version : V2.93.01 ********************************************************************************************************* * For : Renesas RX * Toolchain : IAR Embedded Workbench for Renesas RX ********************************************************************************************************* */ #ifndef _OS_CPU_H #define _OS_CPU_H #ifdef OS_CPU_GLOBALS #define OS_CPU_EXT #else #define OS_CPU_EXT extern #endif #include <cpu.h> /* ********************************************************************************************************* * DATA TYPES * (Compiler Specific) ********************************************************************************************************* */ typedef unsigned char BOOLEAN; /* 8-bit boolean or logical */ typedef unsigned char INT8U; /* 8-bit unsigned integer */ typedef signed char INT8S; /* 8-bit signed integer */ typedef unsigned short INT16U; /* 16-bit unsigned integer */ typedef signed short INT16S; /* 16-bit signed integer */ typedef unsigned long INT32U; /* 32-bit unsigned integer */ typedef signed long INT32S; /* 32-bit signed integer */ typedef float FP32; /* 32-bit floating point */ typedef double FP64; /* 64-bit floating point */ typedef unsigned long OS_STK; /* Each stack entry is 32-bit wide */ typedef unsigned long OS_CPU_SR; /* Define size of CPU status register (PSR = 32 bits) */ /* ********************************************************************************************************* * MACROS ********************************************************************************************************* */ #define OS_STK_GROWTH 1u /* Stack growth (0 == Up. 1 == Down) */ #define OS_TASK_SW() OSCtxSw() /* Context switch through pended call */ /* ********************************************************************************************************* * Critical Section Management * * Method #1: Disable/Enable interrupts using simple instructions. After critical section, interrupts * will be enabled even if they were disabled before entering the critical section. * NOT IMPLEMENTED * * Method #2: Disable/Enable interrupts by preserving the state of interrupts. In other words, if * interrupts were disabled before entering the critical section, they will be disabled when * leaving the critical section. * NOT IMPLEMENTED * * Method #3: Disable/Enable interrupts by preserving the state of interrupts. Generally speaking you * would store the state of the interrupt disable flag in the local variable 'cpu_sr' and then * disable interrupts. 'cpu_sr' is allocated in all of uC/OS-II's functions that need to * disable interrupts. You would restore the interrupt disable state by copying back 'cpu_sr' * into the CPU's status register. ********************************************************************************************************* */ #define OS_CRITICAL_METHOD 3u #if OS_CRITICAL_METHOD == 3u #ifdef CPU_CFG_KA_IPL_BOUNDARY #define OS_ENTER_CRITICAL() do { cpu_sr = __get_interrupt_level(); \ __set_interrupt_level(CPU_CFG_KA_IPL_BOUNDARY); } while (0) #else #define OS_ENTER_CRITICAL() do { cpu_sr = __get_interrupt_level(); \ __set_interrupt_level(12); } while (0) #endif /* Restore CPU status word. */ #define OS_EXIT_CRITICAL() do { __set_interrupt_level(cpu_sr); } while (0) #endif /* ********************************************************************************************************* * FUNCTION PROTOTYPES ********************************************************************************************************* */ void OSCtxSw (void); void OSIntCtxSw (void); void OSStartHighRdy (void); void OSCtxSwISR (void); #endif