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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c46af8d8b0a662601f7958d2e8d79d55a73d0dc1
|
17d7357e5c5130ace022b3c9d9f98e7b13dda0ca
|
/src/meta/ahx_keys.h
|
aa2316fe6a5869111e632610fc39b01d0b32e5bb
|
[
"ISC",
"LicenseRef-scancode-public-domain"
] |
permissive
|
vgmstream/vgmstream
|
4a7747bb75ff513f8fc8cc26f31d6e3a4150bc43
|
883d796d4b63c42810586e9f1ffbdcdd28c73ef5
|
refs/heads/master
| 2023-09-04T16:14:38.136915
| 2023-09-02T18:06:38
| 2023-09-02T18:06:38
| 5,591,410
| 762
| 137
|
NOASSERTION
| 2023-09-10T22:58:26
| 2012-08-28T20:08:24
|
C
|
UTF-8
|
C
| false
| false
| 1,505
|
h
|
ahx_keys.h
|
#ifndef _AHX_KEYS_H_
#define _AHX_KEYS_H_
#include <stdint.h>
#include <string.h>
typedef struct {
const char* key8; /* keystring used by type 8 encryption */
uint64_t key9; /* reserved (not seen) */
} ahxkey_info;
/**
* List of known keys, from exes. Generally same as ADX keys as CRI's key init seems shared.
*/
static const ahxkey_info ahxkey8_list[] = {
/* Amagami (PS2) [Enterbrain] */
{"mituba",0},
/* StormLover!! (PSP), StormLover Kai!! (PSP) [Vridge] */
{"HEXDPFMDKPQW",0},
/* Lucky Star: Net Idol Meister (PSP) [Vridge, Kadokawa Shoten] */
/* Baka to Test to Shoukanjuu Portable (PSP) */
{"JJOLIFJLE",0},
/* Ishin Renka: Ryouma Gaiden (PSP) [Vridge] */
{"LQAFJOIEJ",0},
/* Lucky Star: Ryouou Gakuen Outousai Portable (PSP) [Vridge] */
{"IUNOIRU",0},
/* Marriage Royale: Prism Story (PSP) [Vridge] */
{"ROYMAR",0},
/* Nogizaka Haruka no Himitsu: Doujinshi Hajimemashita (PSP) [Vridge] */
{"CLKMEOUHFLIE",0},
/* Nichijou: Uchuujin (PSP) [Vridge] */
{"LJLOUHIU787",0},
/* StormLover Natsu Koi!! (PSP) [Vridge] */
{"LIKDFJUIDJOQ",0},
/* Corpse Party: Book of Shadows (PSP) */
{"\x83\x76\x83\x89\x83\x60\x83\x69Lovers_Day",0}, // "プラチナLovers_Day" in SHIFT-JIS
};
static const int ahxkey8_list_count = sizeof(ahxkey8_list) / sizeof(ahxkey8_list[0]);
#endif /* _AHX_KEYS_H_ */
|
d0736e28105905842ea52ef648e79d62d3da1abf
|
e73547787354afd9b717ea57fe8dd0695d161821
|
/src/world/area_mim/common/SetupGates.inc.c
|
1155aab463222ed949d8b5d412364043a750845a
|
[] |
no_license
|
pmret/papermario
|
8b514b19653cef8d6145e47499b3636b8c474a37
|
9774b26d93f1045dd2a67e502b6efc9599fb6c31
|
refs/heads/main
| 2023-08-31T07:09:48.951514
| 2023-08-21T18:07:08
| 2023-08-21T18:07:08
| 287,151,133
| 904
| 139
| null | 2023-09-14T02:44:23
| 2020-08-13T01:22:57
|
C
|
UTF-8
|
C
| false
| false
| 1,202
|
c
|
SetupGates.inc.c
|
#include "common.h"
EvtScript N(EVS_SetupGates) = {
EVT_IF_EQ(GF_MIM_ChoosingPath, FALSE)
EVT_SET(GF_MIM_ChoosingPath, TRUE)
EVT_SET(AB_MIM_1, 2)
EVT_SET(LVar1, 2)
EVT_SET(LVar2, -10)
EVT_ELSE
EVT_SET(GF_MIM_ChoosingPath, FALSE)
EVT_SET(AB_MIM_1, 0)
EVT_SET(LVar1, 0)
EVT_SET(LVar2, 10)
EVT_END_IF
EVT_EXEC_WAIT(N(EVS_SetGateCameraZones))
EVT_EXEC(N(EVS_InitializeGates))
EVT_CALL(SetCamSpeed, CAM_DEFAULT, EVT_FLOAT(90.0))
EVT_CALL(GetPlayerPos, LVar0, LVar1, LVar2)
EVT_CALL(UseSettingsFrom, CAM_DEFAULT, LVar0, LVar1, LVar2)
EVT_CALL(SetPanTarget, CAM_DEFAULT, LVar0, LVar1, LVar2)
EVT_CALL(PanToTarget, CAM_DEFAULT, 0, 1)
EVT_WAIT(1)
EVT_CALL(PanToTarget, CAM_DEFAULT, 0, 0)
EVT_BIND_TRIGGER(EVT_PTR(N(EVS_UseGate_North)), TRIGGER_WALL_PRESS_A, COLLIDER_monn, 1, 0)
EVT_BIND_TRIGGER(EVT_PTR(N(EVS_UseGate_South)), TRIGGER_WALL_PRESS_A, COLLIDER_mons, 1, 0)
EVT_BIND_TRIGGER(EVT_PTR(N(EVS_UseGate_West)), TRIGGER_WALL_PRESS_A, COLLIDER_monw, 1, 0)
EVT_BIND_TRIGGER(EVT_PTR(N(EVS_UseGate_East)), TRIGGER_WALL_PRESS_A, COLLIDER_mone, 1, 0)
EVT_RETURN
EVT_END
};
|
7950730a0de27a5d9b9262d9684c1efbd599219d
|
984bc4181baec6e5a4b05a657e666b0e9f89f3f3
|
/3rdparty/mongo-c-driver-1.21.2/src/libmongoc/src/mongoc/mongoc-stream-buffered.c
|
605cedf373c82c48aba7c32ea356868fcd5f1829
|
[
"Apache-2.0",
"BSD-3-Clause"
] |
permissive
|
treefrogframework/treefrog-framework
|
0173245ff92162d2107af79861505981980d1eca
|
a1df97793e8cc628779378e5adae9af6987460c1
|
refs/heads/master
| 2023-08-22T03:57:58.891846
| 2023-05-18T14:00:42
| 2023-05-18T14:00:42
| 7,067,532
| 1,152
| 263
|
BSD-3-Clause
| 2023-08-08T20:25:03
| 2012-12-08T13:17:01
|
C++
|
UTF-8
|
C
| false
| false
| 9,729
|
c
|
mongoc-stream-buffered.c
|
/*
* Copyright 2013 MongoDB, 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 <errno.h>
#include "mongoc-buffer-private.h"
#include "mongoc-counters-private.h"
#include "mongoc-log.h"
#include "mongoc-stream-buffered.h"
#include "mongoc-stream-private.h"
#include "mongoc-trace-private.h"
#undef MONGOC_LOG_DOMAIN
#define MONGOC_LOG_DOMAIN "stream"
typedef struct {
mongoc_stream_t stream;
mongoc_stream_t *base_stream;
mongoc_buffer_t buffer;
} mongoc_stream_buffered_t;
/*
*--------------------------------------------------------------------------
*
* mongoc_stream_buffered_destroy --
*
* Clean up after a mongoc_stream_buffered_t. Free all allocated
* resources and release the base stream.
*
* Returns:
* None.
*
* Side effects:
* Everything.
*
*--------------------------------------------------------------------------
*/
static void
mongoc_stream_buffered_destroy (mongoc_stream_t *stream) /* IN */
{
mongoc_stream_buffered_t *buffered = (mongoc_stream_buffered_t *) stream;
BSON_ASSERT (stream);
mongoc_stream_destroy (buffered->base_stream);
buffered->base_stream = NULL;
_mongoc_buffer_destroy (&buffered->buffer);
bson_free (stream);
mongoc_counter_streams_active_dec ();
mongoc_counter_streams_disposed_inc ();
}
/*
*--------------------------------------------------------------------------
*
* mongoc_stream_buffered_failed --
*
* Called when a stream fails. Useful for streams that differnciate
* between failure and cleanup.
* Calls mongoc_stream_buffered_destroy() on the stream.
*
* Returns:
* None.
*
* Side effects:
* Everything.
*
*--------------------------------------------------------------------------
*/
static void
mongoc_stream_buffered_failed (mongoc_stream_t *stream) /* IN */
{
mongoc_stream_buffered_destroy (stream);
}
/*
*--------------------------------------------------------------------------
*
* mongoc_stream_buffered_close --
*
* Close the underlying stream. The buffered content is still
* valid.
*
* Returns:
* The return value of mongoc_stream_close() on the underlying
* stream.
*
* Side effects:
* None.
*
*--------------------------------------------------------------------------
*/
static int
mongoc_stream_buffered_close (mongoc_stream_t *stream) /* IN */
{
mongoc_stream_buffered_t *buffered = (mongoc_stream_buffered_t *) stream;
BSON_ASSERT (stream);
return mongoc_stream_close (buffered->base_stream);
}
/*
*--------------------------------------------------------------------------
*
* mongoc_stream_buffered_flush --
*
* Flushes the underlying stream.
*
* Returns:
* The result of flush on the base stream.
*
* Side effects:
* None.
*
*--------------------------------------------------------------------------
*/
static int
mongoc_stream_buffered_flush (mongoc_stream_t *stream) /* IN */
{
mongoc_stream_buffered_t *buffered = (mongoc_stream_buffered_t *) stream;
BSON_ASSERT (buffered);
return mongoc_stream_flush (buffered->base_stream);
}
/*
*--------------------------------------------------------------------------
*
* mongoc_stream_buffered_writev --
*
* Write an iovec to the underlying stream. This write is not
* buffered, it passes through to the base stream directly.
*
* timeout_msec should be the number of milliseconds to wait before
* considering the writev as failed.
*
* Returns:
* The number of bytes written or -1 on failure.
*
* Side effects:
* None.
*
*--------------------------------------------------------------------------
*/
static ssize_t
mongoc_stream_buffered_writev (mongoc_stream_t *stream, /* IN */
mongoc_iovec_t *iov, /* IN */
size_t iovcnt, /* IN */
int32_t timeout_msec) /* IN */
{
mongoc_stream_buffered_t *buffered = (mongoc_stream_buffered_t *) stream;
ssize_t ret;
ENTRY;
BSON_ASSERT (buffered);
ret =
mongoc_stream_writev (buffered->base_stream, iov, iovcnt, timeout_msec);
RETURN (ret);
}
/*
*--------------------------------------------------------------------------
*
* mongoc_stream_buffered_readv --
*
* Read from the underlying stream. The data will be buffered based
* on the buffered streams target buffer size.
*
* When reading from the underlying stream, we read at least the
* requested number of bytes, but try to also fill the stream to
* the size of the underlying buffer.
*
* Note:
* This isn't actually a huge savings since we never have more than
* one reply waiting for us, but perhaps someday that will be
* different. It should help for small replies, however that will
* reduce our read() syscalls by 50%.
*
* Returns:
* The number of bytes read or -1 on failure.
*
* Side effects:
* iov[*]->iov_base buffers are filled.
*
*--------------------------------------------------------------------------
*/
static ssize_t
mongoc_stream_buffered_readv (mongoc_stream_t *stream, /* IN */
mongoc_iovec_t *iov, /* INOUT */
size_t iovcnt, /* IN */
size_t min_bytes, /* IN */
int32_t timeout_msec) /* IN */
{
mongoc_stream_buffered_t *buffered = (mongoc_stream_buffered_t *) stream;
bson_error_t error = {0};
size_t total_bytes = 0;
size_t i;
size_t off = 0;
ENTRY;
BSON_ASSERT (buffered);
for (i = 0; i < iovcnt; i++) {
total_bytes += iov[i].iov_len;
}
if (-1 == _mongoc_buffer_fill (&buffered->buffer,
buffered->base_stream,
total_bytes,
timeout_msec,
&error)) {
MONGOC_WARNING ("%s", error.message);
RETURN (-1);
}
BSON_ASSERT (buffered->buffer.len >= total_bytes);
for (i = 0; i < iovcnt; i++) {
memcpy (iov[i].iov_base, buffered->buffer.data + off, iov[i].iov_len);
off += iov[i].iov_len;
buffered->buffer.len -= iov[i].iov_len;
}
memmove (
buffered->buffer.data, buffered->buffer.data + off, buffered->buffer.len);
RETURN (total_bytes);
}
static mongoc_stream_t *
_mongoc_stream_buffered_get_base_stream (mongoc_stream_t *stream) /* IN */
{
return ((mongoc_stream_buffered_t *) stream)->base_stream;
}
static bool
_mongoc_stream_buffered_check_closed (mongoc_stream_t *stream) /* IN */
{
mongoc_stream_buffered_t *buffered = (mongoc_stream_buffered_t *) stream;
BSON_ASSERT (stream);
return mongoc_stream_check_closed (buffered->base_stream);
}
static bool
_mongoc_stream_buffered_timed_out (mongoc_stream_t *stream) /* IN */
{
mongoc_stream_buffered_t *buffered = (mongoc_stream_buffered_t *) stream;
BSON_ASSERT (stream);
return mongoc_stream_timed_out (buffered->base_stream);
}
static bool
_mongoc_stream_buffered_should_retry (mongoc_stream_t *stream) /* IN */
{
mongoc_stream_buffered_t *buffered = (mongoc_stream_buffered_t *) stream;
BSON_ASSERT (stream);
return mongoc_stream_should_retry (buffered->base_stream);
}
/*
*--------------------------------------------------------------------------
*
* mongoc_stream_buffered_new --
*
* Creates a new mongoc_stream_buffered_t.
*
* This stream will read from an underlying stream and try to read
* more data than necessary. It can help lower the number of read()
* or recv() syscalls performed.
*
* @base_stream is considered owned by the resulting stream after
* calling this function.
*
* Returns:
* A newly allocated mongoc_stream_t.
*
* Side effects:
* None.
*
*--------------------------------------------------------------------------
*/
mongoc_stream_t *
mongoc_stream_buffered_new (mongoc_stream_t *base_stream, /* IN */
size_t buffer_size) /* IN */
{
mongoc_stream_buffered_t *stream;
BSON_ASSERT (base_stream);
stream = (mongoc_stream_buffered_t *) bson_malloc0 (sizeof *stream);
stream->stream.type = MONGOC_STREAM_BUFFERED;
stream->stream.destroy = mongoc_stream_buffered_destroy;
stream->stream.failed = mongoc_stream_buffered_failed;
stream->stream.close = mongoc_stream_buffered_close;
stream->stream.flush = mongoc_stream_buffered_flush;
stream->stream.writev = mongoc_stream_buffered_writev;
stream->stream.readv = mongoc_stream_buffered_readv;
stream->stream.get_base_stream = _mongoc_stream_buffered_get_base_stream;
stream->stream.check_closed = _mongoc_stream_buffered_check_closed;
stream->stream.timed_out = _mongoc_stream_buffered_timed_out;
stream->stream.should_retry = _mongoc_stream_buffered_should_retry;
stream->base_stream = base_stream;
_mongoc_buffer_init (&stream->buffer, NULL, buffer_size, NULL, NULL);
mongoc_counter_streams_active_inc ();
return (mongoc_stream_t *) stream;
}
|
3008ef9d631d242a6738a3eb8b83b908439effb3
|
8dbeef9c1a16a37e2fc9a07479dd79218bfd9303
|
/_includes/extend/ext/foobar.c
|
2450c7a42c15dde52ada554f81dd7f8d0be19fb5
|
[
"CC-BY-4.0"
] |
permissive
|
silverhammermba/emberb
|
b79ac8df3ee1c0eb2f8dcf0db89ff427721672ae
|
4c81c4fff0b7ffb37609b18773bd3633acc294f0
|
refs/heads/gh-pages
| 2023-09-04T11:00:47.897549
| 2023-08-22T20:57:44
| 2023-08-22T20:57:44
| 25,453,420
| 187
| 27
|
CC-BY-4.0
| 2023-08-20T23:01:42
| 2014-10-20T06:20:24
|
CSS
|
UTF-8
|
C
| false
| false
| 92
|
c
|
foobar.c
|
#include <ruby.h>
#include "extconf.h"
void Init_foobar()
{
/* code run by `require` */
}
|
4e030f7979d5d4634b1976c9c32b2f77db0c3b71
|
9c8044df21f177ad57a6c5235b5187b8a9cca55f
|
/Estruturas de Dados/Exemplos/Arvores/Arvore Binaria/arvoreBinariaEstruturada.c
|
bcc324c5a7b0bdddc5728d28075411e6f0716105
|
[] |
no_license
|
AlexGalhardo/ICMC-USP
|
48f268fe60f917d5a24921c103c8a88c790634d7
|
f43efb6afea7d92b6aaa0b48516fb89705b46f24
|
refs/heads/master
| 2018-10-08T15:45:22.434741
| 2018-10-02T17:49:25
| 2018-10-02T17:49:25
| 162,185,299
| 168
| 51
| null | null | null | null |
UTF-8
|
C
| false
| false
| 7,980
|
c
|
arvoreBinariaEstruturada.c
|
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <dos.h>
#include <math.h>
#define YES 1
#define NO 0
typedef struct no2
{
int valor;
int h, bal;
struct no2 * anterior, * proximo;
} node2;
/*****************************************************/
int QtdNo( node2 * root )
{
int retorno;
retorno = 0;
if ( root != NULL )
{ retorno = QtdNo(root->anterior)+QtdNo(root->proximo)+1; }
return( retorno );
}
/*****************************************************/
int IsAVL( node2 * root )
{
if ( root == NULL )
{ return( YES );}
else
{
if (((root->bal < -1) || (root->bal > 1 )) ||
((root->anterior != NULL) &&
(root->anterior->valor > root->valor )) ||
((root->proximo != NULL) &&
(root->proximo->valor < root->valor ))
)
{ return( NO );}
else
{ return( BalancedTree( root->anterior) &&
BalancedTree( root->proximo) );
}
}
}
/*****************************************************/
int BalancedTree( node2 * root )
{
if ( root == NULL )
{ return( YES );}
else
{
if ((root->bal < -1) || (root->bal > 1 ))
{ return( NO );}
else
{ return( BalancedTree( root->anterior) &&
BalancedTree( root->proximo) );
}
}
}
/*****************************************************/
void CalcHBal( node2 * root )
{
if (root != NULL)
{
root->bal = VoltaH( root->anterior ) -
VoltaH( root->proximo);
if (root->bal > 0 )
{ root->h = VoltaH( root->anterior )+1; }
else
{ root->h = VoltaH( root->proximo )+1; }
}
}
/*****************************************************/
int VoltaH( node2 * root )
{
if (root == NULL)
{ return( 0 );}
else
{ return( root->h ); }
}
/*****************************************************/
int VoltaBal( node2 * root )
{
if (root == NULL)
{ return( 0 );}
else
{ return( root->bal ); }
}
/*****************************************************/
void PreencheBal( node2 * root )
{ int besq, bdir;
if (root != NULL)
{
root->bal = VoltaH(root->anterior) - VoltaH(root->proximo);
PreencheBal( root->anterior );
PreencheBal( root->proximo );
}
}
/*****************************************************/
int PreencheH( node2 * root )
{ int hesq, hdir, hret;
if (root == NULL)
{
hret = 0;
}
else
{
hesq = PreencheH( root->anterior );
hdir = PreencheH( root->proximo );
if (hesq > hdir )
{
hret = hesq+1;
}
else
{
hret = hdir+1;
}
root->h = hret;
}
return( hret );
}
/*****************************************************/
node2 * CriaNode2( int value )
{
node2 * no;
// printf("\nCN\n");
no = (node2*) malloc(sizeof( node2 ) );
if (no != NULL)
{ (*no).valor = value;
(*no).proximo = NULL;
(*no).anterior = NULL;
no->h = 1;
no->bal = 0;
}
return( no );
}
/*****************************************************/
node2 * rebalancear( node2 * root )
{
node2 * aux;
// printf("\nEntrou\n");
// printf("Bals %d - %d - %d", VoltaBal(root->anterior),
// VoltaBal(root), VoltaBal(root->proximo));
if ( (VoltaBal(root) == 2) && (VoltaBal(root->anterior) == 1) )
{ //pendente pro anterior pai e filho - rodar para direita
printf("\nCaso 1\n");
aux = root;
root = root->anterior;
aux->anterior = root->proximo;
root->proximo = aux;
}
else
{
// printf("\nElse 1\n");
if ( (VoltaBal(root) == -2) && (VoltaBal(root->proximo) == -1) )
{ //pendente pro proximo pai e filho - rodar para esquerda
printf("\nCaso 2\n");
aux = root;
root = root->proximo;
aux->proximo = root->anterior;
root->anterior = aux;
/* No* b = *r;
No* a = b->esq;
b->esq = a->dir;
a->dir = b;
a->bal = 0;
b->bal = 0;
*r = a;
*/
}
else
{
printf("\nElse 2\n");
if ( (VoltaBal(root) == 2) && (VoltaBal(root->anterior) == -1) )
{ //pendente pro anterior pai e proximo filho
//rodar para esquerda e depois para direita
printf("\nCaso 3\n");
aux = root->anterior;
root->anterior = root->anterior->proximo;
aux->proximo = root->anterior->anterior;
root->anterior->anterior = aux;
aux = root;
root = root->anterior;
aux->anterior = root->proximo;
root->proximo = aux;
}
else
{ //pendente pro proximo pai e anterior filho
//rodar para direita e depois para esquerda
printf("\nCaso 4\n");
aux = root->proximo;
root->proximo = root->proximo->anterior;
aux->anterior = root->proximo->proximo;
root->proximo->proximo = aux;
aux = root;
root = root->proximo;
aux->proximo = root->anterior;
root->anterior = aux;
}
}
}
return( root );
}
/*****************************************************/
node2 * InsereBinariaOrd( node2 * root, node2 * novo )
{
if (root == NULL)
{
root = novo;
}
else
{
if( root->valor > novo->valor )
{
root->anterior = InsereBinariaOrd( root->anterior, novo );
}
else
{
root->proximo = InsereBinariaOrd( root->proximo, novo );
}
// printf("\nCalcHBal root: %d\n", root->valor);
CalcHBal( root );
if (((VoltaH( root->anterior )-VoltaH( root->proximo))>1) ||
((VoltaH( root->anterior )-VoltaH( root->proximo))<-1)
)
{
printf("\nRebalancear\n");
//rebalancear
root = rebalancear( root );
}
// printf("\nCalcHBals\n");
CalcHBal( root->anterior );
CalcHBal( root->proximo );
CalcHBal( root );
}
return( root );
}
/*****************************************************/
void PrintBinariaOrd( node2 * root )
{
if (root != NULL)
{
PrintBinariaOrd( root->anterior );
printf("val: %d h:%d b:%d\n", root->valor, root->h, root->bal );
PrintBinariaOrd( root->proximo );
}
}
/*****************************************************/
node2 * BuscaBin( node2 * root, int value )
{
node2 * retorno;
if (root == NULL)
{
retorno = NULL;
}
else
{
if (root->valor == value)
{
retorno = root;
}
else
{
if( root->valor > value )
{
retorno = BuscaBin( root->anterior, value );
}
else
{
retorno = BuscaBin( root->proximo, value );
}
}
}
return(retorno);
}
/*****************************************************/
int main(void)
{
node2 * novo2, * head2;
int contador;
/*****************************************************/
printf("\n #### Arvore Binaria ####\n" );
head2 = NULL;
for( contador = 0; contador < 5; contador++ )
{
printf("******************** %d **************\n", contador );
novo2 = CriaNode2( contador );
head2 = InsereBinariaOrd( head2, novo2 );
/* printf("###############################\n" );
PrintBinariaOrd( head2 );
printf("###############################\n" );
*/ }
// PreencheH( head2 );
// PreencheBal( head2 );
PrintBinariaOrd( head2 );
printf("\nBalanceada: %d\n", BalancedTree( head2 ));
printf("\nIsAVL: %d\n",IsAVL( head2 ));
printf("\nQtde nos: %d\n", QtdNo( head2 ));
novo2 = BuscaBin( head2, 3 );
printf("\nNo achado -> %d\n", novo2->valor );
getch();
return( 0 );
}
|
f1f72e09e5c4e0df3ed96dc235bd4da68b842399
|
05819963250c2ae0ba59ffef48d7c99a5b6b7cfd
|
/target/common/board_lcd.c
|
443601b44a8452253667c21c8394d7658798788d
|
[
"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
| 2,517
|
c
|
board_lcd.c
|
/* ----------------------------------------------------------------------------
* SAM Software Package License
* ----------------------------------------------------------------------------
* Copyright (c) 2016, 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.
* ----------------------------------------------------------------------------
*/
/*----------------------------------------------------------------------------
* Headers
*----------------------------------------------------------------------------*/
#include "board_lcd.h"
#include "display/lcdc.h"
#include "gpio/pio.h"
/*----------------------------------------------------------------------------
* Public functions
*----------------------------------------------------------------------------*/
void board_cfg_lcd(void)
{
#ifdef BOARD_LCD_PINS
const struct _pin pins_lcd[] = BOARD_LCD_PINS;
const struct _lcdc_desc lcd_desc = {
.width = BOARD_LCD_WIDTH,
.height = BOARD_LCD_HEIGHT,
.framerate = BOARD_LCD_FRAMERATE,
.timing_vfp = BOARD_LCD_TIMING_VFP,
.timing_vbp = BOARD_LCD_TIMING_VBP,
.timing_vpw = BOARD_LCD_TIMING_VPW,
.timing_hfp = BOARD_LCD_TIMING_HFP,
.timing_hbp = BOARD_LCD_TIMING_HBP,
.timing_hpw = BOARD_LCD_TIMING_HPW,
};
pio_configure(pins_lcd, ARRAY_SIZE(pins_lcd));
lcdc_configure(&lcd_desc);
#endif
}
|
cb1295f915211125854f372924af8ef37273de75
|
a1d5df246d39000f30a1d128bc53d2f0fbbb3250
|
/cd12/SETUP/TOOLS/INC/STDTYPES.H
|
93785aef4304d15b43f7780a7fd30b92a55bb15e
|
[
"MIT"
] |
permissive
|
microsoft/Microsoft-3D-Movie-Maker
|
0873a4a5bef74792f5c787b9661fe7d8d0fabe5a
|
104b2653e68046c2f6373186169f281006db35b1
|
refs/heads/main
| 2022-05-07T21:09:40.479649
| 2022-05-04T04:12:08
| 2022-05-04T04:12:08
| 481,732,253
| 3,544
| 251
| null | null | null | null |
UTF-8
|
C
| false
| false
| 11,786
|
h
|
STDTYPES.H
|
/****************************************************************************
**
** File: STDTYPES.H
** Purpose: Standard project wide include file.
** Notes:
**
****************************************************************************/
#ifndef STDTYPES_H
#define STDTYPES_H
#ifdef _WIN32
/* The windows.h for win32 used _WINDOWS_ instead of _INC_WINDOWS */
#ifdef _INC_WINDOWS
#undef _INC_WINDOWS
#endif
#define _INC_WINDOWS _WINDOWS_
#endif /* _WIN32 */
/* MAX_PATH is the Win32 define, _MAX_PATH is the MSVC define, equate them */
#ifdef MAX_PATH
#undef _MAX_PATH
#define _MAX_PATH MAX_PATH
#else
#define MAX_PATH _MAX_PATH
#endif
/* CDECL is already defined in WIN32. Undef it */
/*#undef CDECL*/
/* Rename PSZ, since it is defined in WIN32 as char*, and we want char** */
#define PSZ _PSZ
#ifdef DEBUG
#define DEVELOPER /* REVIEW: This is temporary */
#endif
/*
* Constants
*/
#define fFalse ((BOOL)0)
#define fTrue ((BOOL)1)
#define Nil 0
#define chNil '\0'
#define chEos '\0'
#define chTab '\t'
#define chEol '\n'
#define chCR '\r'
#define chCtrlZ '\x1A'
#define chSpace ' '
#define chBang '!'
#define chDblQuote '\"'
#define chDollar '$'
#define chPercent '%'
#define chSngQuote '\''
#define chStar '*'
#define chPlus '+'
#define chComma ','
#define chMinus '-'
#define chPeriod '.'
#define chSlash '/'
#define chColon ':'
#define chSemiColon ';'
#define chLftAngle '<'
#define chEquals '='
#define chRgtAngle '>'
#define chQuestionMark '?'
#define chAtSign '@'
#define chLftSqBracket '['
#define chBackSlash '\\'
#define chRgtSqBracket ']'
#define chUnderscore '_'
#define chLftBrace '{'
#define chVertical '|'
#define chRgtBrace '}'
#define chDirSep chBackSlash
#define szDirSep "\\"
#define szTab "\t"
#define cchIntMax 17 /* Maximum number of digits (_itoa) */
#define cchLongMax 33 /* Maximum number of digits (_ltoa) */
#define cchSzMax MAX_PATH /* Includes chEos */
/*
* In a windows program windows.h must be included before this file.
* If a DOS program includes ver.h, it must do so before including this
* file.
*/
#ifndef _INC_WINDOWS /* Don't declare if already declared in windows.h */
#ifndef WINAPI /* Don't declare if already declared in ver.h */
typedef int BOOL;
typedef unsigned char BYTE;
typedef unsigned int UINT;
#ifdef STRICT
typedef signed long LONG;
#else
#define LONG long
#endif
#ifndef NULL
#define NULL 0
#endif
#endif /* WINAPI */
#define VOID void
#define CDECL _cdecl
typedef void * LPVOID;
#endif /* _INC_WINDOWS */
/*
* Common definitions. See windef.h and winnt.h for these defines:
*
* VOID, NULL, CDECL, WINAPI, CALLBACK
*/
#define STATIC_FN static
#define STATIC_VAR static
#define PRIVATE WINAPI
#define PUBLIC WINAPI
#define HUGE
/*
* Standard types. See windef.h and winnt.h for these types:
*
* CHAR, UCHAR, BYTE, BOOL, USHORT, INT, UINT, WPARAM,
* LONG, ULONG, LPARAM, LRESULT
*
* Types defined in _WIN32 windef.h and winnt.h, but not WIN16 windows.h.
*
* CHAR, USHORT, ULONG
*/
#ifndef _WIN32
typedef char CHAR;
typedef unsigned short USHORT;
typedef unsigned long ULONG;
#endif /* !_WIN32 */
typedef signed char SBYTE;
typedef UINT CB;
typedef unsigned long LCB;
typedef UINT IDT; /* ID of dialog Template */
typedef UINT IDC; /* ID of dialog Control */
typedef UINT IDR; /* ID of Resource */
/*
* Standard pointer types. See windef.h and winnt.h for these types:
*
* PUSHORT, PINT, PUINT, PBOOL, PLONG, PULONG
*
* Types defined in _WIN32 windef.h and winnt.h, but not WIN16 windows.h.
*
* PBOOL, PUINT, PUSHORT, PULONG
*/
#ifndef _WIN32
typedef BOOL * PBOOL;
typedef UINT * PUINT;
typedef USHORT * PUSHORT;
typedef ULONG * PULONG;
#endif /* !_WIN32 */
typedef VOID * PV;
typedef PV * PPV;
typedef PPV * PPPV;
typedef CHAR * SZ; /* ptr to char */
typedef CHAR * const CSZ; /* constant ptr to char */
typedef const CHAR * SZC; /* ptr to constant char */
typedef const CHAR * const CSZC; /* constant ptr to constant char */
typedef SZ * RGSZ;
typedef SZ * PSZ;
typedef PSZ * PPSZ;
typedef BYTE * PB;
typedef PB * PPB;
typedef PPB * PPPB;
typedef SBYTE * PSB;
typedef PSB * PPSB;
typedef PPSB * PPPSB;
typedef PBOOL * PPBOOL;
typedef PPBOOL * PPPBOOL;
typedef BOOL * RGBOOL;
typedef RGBOOL * PRGBOOL;
typedef PRGBOOL * PPRGBOOL;
typedef PINT * PPINT;
typedef PPINT * PPPINT;
typedef PUINT * PPUINT;
typedef PPUINT * PPPUINT;
typedef UINT * RGUINT;
typedef RGUINT * PRGUINT;
typedef PRGUINT * PPRGUINT;
typedef PUSHORT * PPUSHORT;
typedef PPUSHORT * PPPUSHORT;
typedef PLONG * PPLONG;
typedef PPLONG * PPPLONG;
typedef PULONG * PPULONG;
typedef PPULONG * PPPULONG;
typedef CB * PCB;
typedef PCB * PPCB;
typedef PPCB * PPPCB;
typedef LCB * PLCB;
typedef PLCB * PPLCB;
typedef PPLCB * PPPLCB;
typedef IDT * PIDT;
typedef PIDT * PPIDT;
typedef PPIDT * PPPIDT;
typedef IDC * PIDC;
typedef PIDC * PPIDC;
typedef PPIDC * PPPIDC;
typedef IDR * PIDR;
typedef PIDR * PPIDR;
typedef PPIDR * PPPIDR;
#ifdef _INC_WINDOWS
/*
* Pointers to various Windows types.
*/
typedef FARPROC * PLPFN;
typedef DLGPROC * PDLGPROC;
typedef HACCEL * PHACCEL;
typedef HBITMAP * PHBM;
typedef HBRUSH * PHBR;
typedef HCURSOR * PHCURSOR;
typedef HDC * PHDC;
typedef HDWP * PHDWP;
typedef HFONT * PHFONT;
typedef HGDIOBJ * PHGDIOBJ;
typedef HGLOBAL * PHGLOBAL;
typedef HHOOK * PHHOOK;
typedef HICON * PHICON;
typedef HINSTANCE * PHINST;
typedef HMENU * PHMENU;
typedef HMETAFILE * PHMF;
typedef HMODULE * PHMOD;
typedef HPALETTE * PHPAL;
typedef HPEN * PHPEN;
typedef HRSRC * PHRSRC;
typedef HTASK * PHTASK;
typedef HWND * PHWND;
typedef HRGN * PHRGN;
typedef PRECT * PPRECT;
#endif /* _INC_WINDOWS */
/*
* More constants
*/
#define szNil ( (SZ) Nil )
#define pszNil ( (PSZ)Nil )
#define pbNil ( (PB) Nil )
#define pvNil ( (PV) Nil )
#define cbNil ( (CB) Nil )
#define idtNil ( (IDT)Nil )
#define idcNil ( (IDC)Nil )
#define idrNil ( (IDR)Nil )
#define cbMaxConst ( (CB) 0xffff )
#define cbError ( (CB) HFILE_ERROR )
#ifdef __cplusplus
#define pvNull 0
#define lpvoidNull 0
#define szNull 0
#define pszNull 0
#define rgszNull 0
#define cszcNull 0
#define pbNull 0
#define pcbNull 0
#define puintNull 0
#define rguintNull 0
#define prguintNull 0
#define pulongNull 0
#define lpfnNull 0
#define pfNull 0
#define rgfNull 0
#define prgfNull 0
#define pidtNull 0
#define pidcNull 0
#define pidrNull 0
#else
#define pvNull ( (PV) NULL )
#define lpvoidNull ( (LPVOID) NULL )
#define szNull ( (SZ) NULL )
#define pszNull ( (PSZ) NULL )
#define rgszNull ( (RGSZ) NULL )
#define cszcNull ( (CSZC) NULL )
#define pbNull ( (PB) NULL )
#define pcbNull ( (PCB) NULL )
#define puintNull ( (PUINT) NULL )
#define rguintNull ( (RGUINT) NULL )
#define prguintNull ( (PRGUINT)NULL )
#define pulongNull ( (PULONG) NULL )
#define lpfnNull ( NULL )
#define pfNull ( (PBOOL) NULL )
#define rgfNull ( (RGBOOL) NULL )
#define prgfNull ( (PRGBOOL)NULL )
#define pidtNull ( (PIDT) NULL )
#define pidcNull ( (PIDC) NULL )
#define pidrNull ( (PIDR) NULL )
#endif /* __cplusplus */
#ifdef _INC_WINDOWS
/*
* Null constants for various Windows types.
*/
#ifdef __cplusplus
#define dlgprocNull 0
#define haccellNull 0
#define hbmNull 0
#define hbrNull 0
#define hcursorNull 0
#define hdcNull 0
#define hdrvrNull 0
#define hdwpNull 0
#define hfontNull 0
#define hgdiobjNull 0
#define hglobalNull 0
#define hhookNull 0
#define hiconNull 0
#define hinstNull 0
#define hmenuNull 0
#define hmfNull 0
#define hmodNull 0
#define hpalNull 0
#define hpenNull 0
#define hrsrcNull 0
#define htaskNull 0
#define hwndNull 0
#define rgnNull 0
#define prectNull 0
#define plpfnNull 0
#define pdlgprocNull 0
#define phaccellNull 0
#define phbmNull 0
#define phbrNull 0
#define phcursorNull 0
#define phdcNull 0
#define phdrvrNull 0
#define phdwpNull 0
#define phfontNull 0
#define phgdiobjNull 0
#define phglobalNull 0
#define phhookNull 0
#define phiconNull 0
#define phinstNull 0
#define phmenuNull 0
#define phmfNull 0
#define phmodNull 0
#define phpalNull 0
#define phpenNull 0
#define phrsrcNull 0
#define phtaskNull 0
#define phwndNull 0
#define prgnNull 0
#define pprectNull 0
#else
#define dlgprocNull ( (DLGPROC) NULL )
#define haccellNull ( (HACCEL) NULL )
#define hbmNull ( (HBITMAP) NULL )
#define hbrNull ( (HBRUSH) NULL )
#define hcursorNull ( (HCURSOR) NULL )
#define hdcNull ( (HDC) NULL )
#define hdrvrNull ( (HDRVR) NULL )
#define hdwpNull ( (HDWP) NULL )
#define hfontNull ( (HFONT) NULL )
#define hgdiobjNull ( (HGDIOBJ) NULL )
#define hglobalNull ( (HGLOBAL) NULL )
#define hhookNull ( (HHOOK) NULL )
#define hiconNull ( (HICON) NULL )
#define hinstNull ( (HINSTANCE)NULL )
#define hmenuNull ( (HMENU) NULL )
#define hmfNull ( (HMETAFILE)NULL )
#define hmodNull ( (HMODULE) NULL )
#define hpalNull ( (HPALETTE) NULL )
#define hpenNull ( (HPEN) NULL )
#define hrsrcNull ( (HRSRC) NULL )
#define htaskNull ( (HTASK) NULL )
#define hwndNull ( (HWND) NULL )
#define rgnNull ( (HRGN) NULL )
#define prectNull ( (PRECT) NULL )
#define plpfnNull ( (PLPFN) NULL )
#define pdlgprocNull ( (PDLGPROC) NULL )
#define phaccellNull ( (PHACCEL) NULL )
#define phbmNull ( (PHBM) NULL )
#define phbrNull ( (PHBR) NULL )
#define phcursorNull ( (PHCURSOR) NULL )
#define phdcNull ( (PHDC) NULL )
#define phdrvrNull ( (PHDRVR) NULL )
#define phdwpNull ( (PHDWP) NULL )
#define phfontNull ( (PHFONT) NULL )
#define phgdiobjNull ( (PHGDIOBJ) NULL )
#define phglobalNull ( (PHGLOBAL) NULL )
#define phhookNull ( (PHHOOK) NULL )
#define phiconNull ( (PHICON) NULL )
#define phinstNull ( (PHINST) NULL )
#define phmenuNull ( (PHMENU) NULL )
#define phmfNull ( (PHMF) NULL )
#define phmodNull ( (PHMOD) NULL )
#define phpalNull ( (PHPAL) NULL )
#define phpenNull ( (PHPEN) NULL )
#define phrsrcNull ( (PHRSRC) NULL )
#define phtaskNull ( (PHTASK) NULL )
#define phwndNull ( (PHWND) NULL )
#define prgnNull ( (PHRGN) NULL )
#define pprectNull ( (PPRECT) NULL )
#endif /* __cplusplus */
#endif /* _INC_WINDOWS */
#define cbSz ( (CB)sizeof( SZ ) )
#define cbPsz ( (CB)sizeof( PSZ ) )
#define cbByte ( (CB)sizeof( BYTE ) )
#define cbPb ( (CB)sizeof( PB ) )
#define cbBool ( (CB)sizeof( BOOL ) )
#define cbPbool ( (CB)sizeof( PBOOL ) )
#define cbInt ( (CB)sizeof( INT ) )
#define cbPint ( (CB)sizeof( PINT ) )
#define cbLong ( (CB)sizeof( LONG ) )
#define cbPlong ( (CB)sizeof( PLONG ) )
#define cbCb ( (CB)sizeof( CB ) )
#define cbPcb ( (CB)sizeof( PCB ) )
#define cbPv ( (CB)sizeof( PV ) )
/*
* Useful self commenting constructs
*/
#define Unused(x) (void)(x=x)
typedef enum _OFI /* Okay/Fail/Ignore enum */
{
ofiOkay,
ofiFail,
ofiIgnore
} OFI;
typedef OFI * POFI; /* Ptr to Okay/Fail/Ignore enum */
#endif /* STDTYPES_H */
|
cb217827c38a6bdd04b1525afc49567bb7c145ab
|
7c857119fe1505b1d80d6e62969661c06dc1a2f4
|
/MdeModulePkg/Bus/Pci/PciBusDxe/PciHotPlugSupport.h
|
e97d75362db2ccb44404f6c3cc82e422c9bf7f78
|
[
"BSD-2-Clause"
] |
permissive
|
CloverHackyColor/CloverBootloader
|
7042ca7dd6b513d22be591a295e49071ae1482ee
|
2711170df4f60b2ae5aa20add3e00f35cf57b7e5
|
refs/heads/master
| 2023-08-30T22:14:34.590134
| 2023-08-27T19:14:02
| 2023-08-27T19:14:02
| 205,810,121
| 4,734
| 770
|
BSD-2-Clause
| 2023-09-03T12:41:33
| 2019-09-02T08:22:14
|
C
|
UTF-8
|
C
| false
| false
| 5,531
|
h
|
PciHotPlugSupport.h
|
/** @file
PCI Hot Plug support functions declaration for PCI Bus module.
Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#ifndef _EFI_PCI_HOT_PLUG_SUPPORT_H_
#define _EFI_PCI_HOT_PLUG_SUPPORT_H_
//
// stall 1 second, its unit is 100ns
//
#define STALL_1_SECOND 1000000
//
// PCI Hot Plug controller private data
//
typedef struct {
EFI_EVENT Event;
BOOLEAN Found;
BOOLEAN Initialized;
VOID *Padding;
} ROOT_HPC_DATA;
//
// Reference of some global variables
//
extern EFI_PCI_HOT_PLUG_INIT_PROTOCOL *gPciHotPlugInit;
extern EFI_HPC_LOCATION *gPciRootHpcPool;
extern ROOT_HPC_DATA *gPciRootHpcData;
/**
Event notification function to set Hot Plug controller status.
@param Event The event that invoke this function.
@param Context The calling context, pointer to ROOT_HPC_DATA.
**/
VOID
EFIAPI
PciHPCInitialized (
IN EFI_EVENT Event,
IN VOID *Context
);
/**
Compare two device paths to check if they are exactly same.
@param DevicePath1 A pointer to the first device path data structure.
@param DevicePath2 A pointer to the second device path data structure.
@retval TRUE They are same.
@retval FALSE They are not same.
**/
BOOLEAN
EfiCompareDevicePath (
IN EFI_DEVICE_PATH_PROTOCOL *DevicePath1,
IN EFI_DEVICE_PATH_PROTOCOL *DevicePath2
);
/**
Check hot plug support and initialize root hot plug private data.
If Hot Plug is supported by the platform, call PCI Hot Plug Init protocol
to get PCI Hot Plug controller's information and constructor the root hot plug
private data structure.
@retval EFI_SUCCESS They are same.
@retval EFI_UNSUPPORTED No PCI Hot Plug controller on the platform.
@retval EFI_OUT_OF_RESOURCES No memory to constructor root hot plug private
data structure.
**/
EFI_STATUS
InitializeHotPlugSupport (
VOID
);
/**
Test whether PCI device is hot plug bus.
@param PciIoDevice PCI device instance.
@retval TRUE PCI device is a hot plug bus.
@retval FALSE PCI device is not a hot plug bus.
**/
BOOLEAN
IsPciHotPlugBus (
PCI_IO_DEVICE *PciIoDevice
);
/**
Test whether device path is for root pci hot plug bus.
@param HpbDevicePath A pointer to device path data structure to be tested.
@param HpIndex If HpIndex is not NULL, return the index of root hot
plug in global array when TRUE is returned.
@retval TRUE The device path is for root pci hot plug bus.
@retval FALSE The device path is not for root pci hot plug bus.
**/
BOOLEAN
IsRootPciHotPlugBus (
IN EFI_DEVICE_PATH_PROTOCOL *HpbDevicePath,
OUT UINTN *HpIndex OPTIONAL
);
/**
Test whether device path is for root pci hot plug controller.
@param HpcDevicePath A pointer to device path data structure to be tested.
@param HpIndex If HpIndex is not NULL, return the index of root hot
plug in global array when TRUE is returned.
@retval TRUE The device path is for root pci hot plug controller.
@retval FALSE The device path is not for root pci hot plug controller.
**/
BOOLEAN
IsRootPciHotPlugController (
IN EFI_DEVICE_PATH_PROTOCOL *HpcDevicePath,
OUT UINTN *HpIndex
);
/**
Creating event object for PCI Hot Plug controller.
@param HpIndex Index of hot plug device in global array.
@param Event The returned event that invoke this function.
@return Status of create event.
**/
EFI_STATUS
CreateEventForHpc (
IN UINTN HpIndex,
OUT EFI_EVENT *Event
);
/**
Wait for all root PCI Hot Plug controller finished initializing.
@param TimeoutInMicroSeconds Microseconds to wait for all root HPCs' initialization.
@retval EFI_SUCCESS All HPCs initialization finished.
@retval EFI_TIMEOUT Not ALL HPCs initialization finished in Microseconds.
**/
EFI_STATUS
AllRootHPCInitialized (
IN UINTN TimeoutInMicroSeconds
);
/**
Check whether PCI-PCI bridge has PCI Hot Plug capability register block.
@param PciIoDevice A Pointer to the PCI-PCI bridge.
@retval TRUE PCI device is HPC.
@retval FALSE PCI device is not HPC.
**/
BOOLEAN
IsSHPC (
IN PCI_IO_DEVICE *PciIoDevice
);
/**
Check whether PciIoDevice supports PCIe hotplug.
This is equivalent to the following condition:
- the device is either a PCIe switch downstream port or a root port,
- and the device has the SlotImplemented bit set in its PCIe capability
register,
- and the device has the HotPlugCapable bit set in its slot capabilities
register.
@param[in] PciIoDevice The device being checked.
@retval TRUE PciIoDevice is a PCIe port that accepts a hot-plugged device.
@retval FALSE Otherwise.
**/
BOOLEAN
SupportsPcieHotplug (
IN PCI_IO_DEVICE *PciIoDevice
);
/**
Get resource padding if the specified PCI bridge is a hot plug bus.
@param PciIoDevice PCI bridge instance.
**/
VOID
GetResourcePaddingForHpb (
IN PCI_IO_DEVICE *PciIoDevice
);
#endif
|
06ade05016b49e25281ef7c73941fcb2dde745c1
|
9ceacf33fd96913cac7ef15492c126d96cae6911
|
/regress/sys/kern/dup2_accept/dup2_accept.c
|
520663b2d6f0a8224ca972714ceb786febb5f600
|
[] |
no_license
|
openbsd/src
|
ab97ef834fd2d5a7f6729814665e9782b586c130
|
9e79f3a0ebd11a25b4bff61e900cb6de9e7795e9
|
refs/heads/master
| 2023-09-02T18:54:56.624627
| 2023-09-02T15:16:12
| 2023-09-02T15:16:12
| 66,966,208
| 3,394
| 1,235
| null | 2023-08-08T02:42:25
| 2016-08-30T18:18:25
|
C
|
UTF-8
|
C
| false
| false
| 2,416
|
c
|
dup2_accept.c
|
/* $OpenBSD: dup2_accept.c,v 1.3 2018/07/10 08:08:00 mpi Exp $ */
/*
* Copyright (c) 2018 Martin Pieuchot
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <sys/socket.h>
#include <netinet/in.h>
#include <assert.h>
#include <err.h>
#include <errno.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
/*
* Listen on localhost:TEST_PORT for a connection
*/
#define TEST_PORT 9876
static void *
dupper(void *arg)
{
struct sockaddr_in addr;
int s;
sleep(1);
s = socket(PF_INET, SOCK_STREAM, 0);
if (s == -1)
err(1, "socket");
assert(s == 5);
/*
* Make sure that dup'ing a LARVAL file fails with EBUSY.
*
* Otherwise abort the program before calling connect(2),
* this was previously panic'ing the kernel.
*/
if ((dup2(0, 4) != 4) && (errno != EBUSY))
err(1, "dup2");
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
addr.sin_port = htons(TEST_PORT);
if (connect(5, (struct sockaddr *)&addr, sizeof(addr)) == -1)
err(1, "connect");
return NULL;
}
int
main(void)
{
struct sockaddr_in serv_addr;
struct sockaddr client_addr;
int error, s, len, fd;
pthread_t tr;
if ((error = pthread_create(&tr, NULL, dupper, NULL)))
errc(1, error, "pthread_create");
s = socket(PF_INET, SOCK_STREAM, 0);
if (s == -1)
err(1, "socket");
assert(s == 3);
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
serv_addr.sin_port = htons(TEST_PORT);
if (bind(s, (struct sockaddr *)&serv_addr, sizeof(serv_addr)))
err(1, "bind");
if (listen(s, 3))
err(1, "listen");
len = sizeof(client_addr);
fd = accept(s, &client_addr, &len);
return 0;
}
|
0f5cfc0d78fddfd0619577019430e39a95d98143
|
476ec976648ebb17c7e7df0e944910e3a36e4ea1
|
/effects/fill.h
|
d5c4676a06b060207899f24b7ac63c6ded63adcd
|
[] |
no_license
|
tom-2015/rpi-ws2812-server
|
dca65ea96a76301cd11a379ab7cdb4766e8aa89e
|
e76291fda909487fa199fd4129510dc3440ae4c6
|
refs/heads/master
| 2023-01-11T08:48:17.016626
| 2022-12-31T15:29:00
| 2022-12-31T15:29:00
| 30,657,642
| 161
| 44
| null | 2022-12-29T18:17:33
| 2015-02-11T16:34:19
|
C
|
UTF-8
|
C
| false
| false
| 128
|
h
|
fill.h
|
#ifndef EFFECT_FILL_H
#define EFFECT_FILL_H
#include "../ws2812svr.h"
void fill(thread_context * context, char * args);
#endif
|
0c17fa982803cb429c008dc0a53eb0cb82189006
|
ec3d500559e41b0ba0501a3cc565ce70098016c6
|
/ext/numo/narray/gen/tmpl/cast_array.c
|
4c220302d90bdbe7f0972f6316dff2365c058501
|
[
"BSD-3-Clause"
] |
permissive
|
ruby-numo/numo-narray
|
f60dcd79aaea0db6effa30e53ef67fb6ab8db8d4
|
1dd19df10045f992bda6fdca9a696fe85a90aaaf
|
refs/heads/master
| 2023-08-01T19:56:47.840328
| 2022-08-20T10:55:47
| 2022-08-20T10:55:47
| 11,340,157
| 290
| 31
|
BSD-3-Clause
| 2022-11-12T07:01:10
| 2013-07-11T11:22:52
|
C
|
UTF-8
|
C
| false
| false
| 256
|
c
|
cast_array.c
|
static VALUE
<%=c_func(:nodef)%>(VALUE rary)
{
VALUE nary;
narray_t *na;
nary = na_s_new_like(cT, rary);
GetNArray(nary,na);
if (na->size > 0) {
<%=find_tmpl("store").find("array").c_func%>(nary,rary);
}
return nary;
}
|
a920c8c48e64999a198ab1784d5c9e9f386356f9
|
f9e7d65cb784c01a0200145ba8d289afe41d4a56
|
/board/willow/board.h
|
7d70a98ca63e583c8656fd05be55edb70c9b6c35
|
[
"BSD-3-Clause"
] |
permissive
|
FrameworkComputer/EmbeddedController
|
ad7086769e87d0a4179eae96a7c9ff5e383ff54e
|
f6d6b927eed71550d3475411cfc3e59abe5cef2a
|
refs/heads/hx20-hx30
| 2023-08-08T20:45:10.621169
| 2023-05-26T07:03:59
| 2023-05-26T07:03:59
| 447,021,040
| 846
| 48
|
BSD-3-Clause
| 2023-05-26T07:04:59
| 2022-01-12T00:11:14
|
C
|
UTF-8
|
C
| false
| false
| 3,637
|
h
|
board.h
|
/* Copyright 2020 The Chromium OS Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/* Configuration for Willow */
#ifndef __CROS_EC_BOARD_H
#define __CROS_EC_BOARD_H
#define VARIANT_KUKUI_JACUZZI
#define VARIANT_KUKUI_BATTERY_SMART
#define VARIANT_KUKUI_CHARGER_ISL9238
#ifndef SECTION_IS_RW
#define VARIANT_KUKUI_NO_SENSORS
#endif /* SECTION_IS_RW */
#include "baseboard.h"
#undef CONFIG_CHIPSET_POWER_SEQ_VERSION
#define CONFIG_CHIPSET_POWER_SEQ_VERSION 1
#undef CONFIG_SYSTEM_UNLOCKED
#define CONFIG_BATTERY_HW_PRESENT_CUSTOM
#define CONFIG_CHARGER_PSYS
#define CONFIG_CHARGER_RUNTIME_CONFIG
#define CONFIG_BC12_DETECT_PI3USB9201
#define CONFIG_EXTPOWER_GPIO
#undef CONFIG_EXTPOWER_DEBOUNCE_MS
#define CONFIG_EXTPOWER_DEBOUNCE_MS 200
#define CONFIG_I2C_BITBANG
#define I2C_BITBANG_PORT_COUNT 1
#undef CONFIG_I2C_NACK_RETRY_COUNT
#define CONFIG_I2C_NACK_RETRY_COUNT 10
#define CONFIG_SMBUS_PEC
#define CONFIG_USB_PD_TCPM_FUSB302
#define CONFIG_USB_PD_DISCHARGE_GPIO
#define CONFIG_USB_PD_TCPC_LOW_POWER
#define CONFIG_USB_MUX_IT5205
/* Motion Sensors */
#ifndef VARIANT_KUKUI_NO_SENSORS
#define CONFIG_ACCEL_KX022 /* Lid accel */
#define CONFIG_ACCELGYRO_BMI160 /* Base accel */
#define CONFIG_ACCEL_INTERRUPTS
#define CONFIG_ACCELGYRO_BMI160_INT_EVENT \
TASK_EVENT_MOTION_SENSOR_INTERRUPT(BASE_ACCEL)
#define CONFIG_ALS
#define CONFIG_CMD_ACCEL_INFO
#define CONFIG_LID_ANGLE
#define CONFIG_LID_ANGLE_SENSOR_BASE BASE_ACCEL
#define CONFIG_LID_ANGLE_SENSOR_LID LID_ACCEL
#define CONFIG_ACCEL_FORCE_MODE_MASK BIT(LID_ACCEL)
#endif /* VARIANT_KUKUI_NO_SENSORS */
/* I2C ports */
#define I2C_PORT_BC12 0
#define I2C_PORT_TCPC0 0
#define I2C_PORT_USB_MUX 0
#define I2C_PORT_CHARGER board_get_charger_i2c()
#define I2C_PORT_SENSORS 1
#define I2C_PORT_IO_EXPANDER_IT8801 1
#define I2C_PORT_VIRTUAL_BATTERY I2C_PORT_BATTERY
#define I2C_PORT_BATTERY 2
/* Enable Accel over SPI */
#define CONFIG_SPI_ACCEL_PORT 0 /* The first SPI master port (SPI2) */
#define CONFIG_KEYBOARD_PROTOCOL_MKBP
#define CONFIG_MKBP_EVENT
#define CONFIG_MKBP_USE_GPIO
/* Define the MKBP events which are allowed to wakeup AP in S3. */
#define CONFIG_MKBP_HOST_EVENT_WAKEUP_MASK \
(EC_HOST_EVENT_MASK(EC_HOST_EVENT_LID_OPEN) |\
EC_HOST_EVENT_MASK(EC_HOST_EVENT_POWER_BUTTON))
#define CONFIG_LED_ONOFF_STATES
#ifndef __ASSEMBLER__
enum adc_channel {
/* Real ADC channels begin here */
ADC_BOARD_ID = 0,
ADC_EC_SKU_ID,
ADC_CH_COUNT
};
/* power signal definitions */
enum power_signal {
AP_IN_S3_L,
PMIC_PWR_GOOD,
/* Number of signals */
POWER_SIGNAL_COUNT,
};
/* Motion sensors */
enum sensor_id {
LID_ACCEL = 0,
BASE_ACCEL,
BASE_GYRO,
SENSOR_COUNT,
};
enum charge_port {
CHARGE_PORT_USB_C,
};
enum battery_type {
BATTERY_PANASONIC_AC15A3J,
BATTERY_PANASONIC_AC16L5J,
BATTERY_LGC_AC16L8J,
BATTERY_PANASONIC_AC16L5J_KT00205009,
BATTERY_LGC_AP18C8K,
BATTERY_MURATA_AP18C4K,
BATTERY_PANASONIC_AP19B5K_KT00305011,
BATTERY_LGC_AP19B8K,
BATTERY_TYPE_COUNT,
};
#include "gpio_signal.h"
#include "registers.h"
#ifdef SECTION_IS_RO
/* Interrupt handler for emmc task */
void emmc_cmd_interrupt(enum gpio_signal signal);
#endif
void bc12_interrupt(enum gpio_signal signal);
void board_reset_pd_mcu(void);
int board_get_version(void);
int board_is_sourcing_vbus(int port);
/* returns the i2c port number of charger/battery */
int board_get_charger_i2c(void);
int board_get_battery_i2c(void);
#endif /* !__ASSEMBLER__ */
#endif /* __CROS_EC_BOARD_H */
|
0465063c8360394d76a7dad6a25e71953c5b4fe9
|
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
|
/sys/arch/ia64/stand/common/bootstrap.h
|
130cc8dd6d28a155a4e04cdad3ca4b074afaf4e9
|
[] |
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
| 13,480
|
h
|
bootstrap.h
|
/* $NetBSD: bootstrap.h,v 1.10 2017/12/10 02:32:03 christos Exp $ */
/*-
* Copyright (c) 1998 Michael Smith <msmith@freebsd.org>
* 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.
*
* $FreeBSD: src/sys/boot/common/bootstrap.h,v 1.38.6.1 2004/09/03 19:25:40 iedowse Exp $
*/
#ifndef _BOOTSTRAP_H_
#define _BOOTSTRAP_H_
#include <sys/types.h>
#include <sys/queue.h>
/*
* Generic device specifier; architecture-dependent
* versions may be larger, but should be allowed to
* overlap.
*/
struct devdesc
{
struct devsw *d_dev;
int d_type;
#define DEVT_NONE 0
#define DEVT_DISK 1
#define DEVT_NET 2
#define DEVT_CD 3
};
typedef int (bootblk_cmd_t)(int argc, char *argv[]);
int command_seterr(const char *fmt, ...) __printflike(1, 2);
const char *command_geterr(void);
#define CMD_OK 0
#define CMD_ERROR 1
/* interp.c */
void interact(void);
int include(const char *filename);
/* interp_backslash.c */
char *backslash(char *str);
/* interp_parse.c */
int parse(int *argc, char ***argv, char *str);
/* interp_forth.c */
void bf_init(void);
int bf_run(char *line);
/* boot.c */
int autoboot(int timeout, char *prompt);
void autoboot_maybe(void);
int getrootmount(char *rootdev);
/* misc.c */
char *unargv(int argc, char *argv[]);
#if 0
void hexdump(void *region, size_t len);
#endif
size_t strlenout(vaddr_t str);
char *strdupout(vaddr_t str);
void kern_bzero(vaddr_t dest, size_t len);
int kern_pread(int fd, vaddr_t dest, size_t len, off_t off);
void *alloc_pread(int fd, off_t off, size_t len);
/* bcache.c */
int bcache_init(u_int nblks, size_t bsize);
void bcache_flush(void);
int bcache_strategy(void *devdata, int unit, int rw, daddr_t blk,
size_t size, char *buf, size_t *rsize);
/* strdup.c */
char *strdup(const char*);
/*
* Disk block cache
*/
struct bcache_devdata
{
int (*dv_strategy)(void *devdata, int rw, daddr_t blk, size_t size, char *buf, size_t *rsize);
void *dv_devdata;
};
/*
* Modular console support.
*/
struct console
{
const char *c_name;
const char *c_desc;
int c_flags;
#define C_PRESENTIN (1<<0)
#define C_PRESENTOUT (1<<1)
#define C_ACTIVEIN (1<<2)
#define C_ACTIVEOUT (1<<3)
void (* c_probe)(struct console *cp); /* set c_flags to match hardware */
int (* c_init)(int arg); /* reinit XXX may need more args */
void (* c_out)(int c); /* emit c */
int (* c_in)(void); /* wait for and return input */
int (* c_ready)(void); /* return nonzer if input waiting */
};
extern struct console *consoles[];
void cons_probe(void);
int ischar(void);
/*
* Plug-and-play enumerator/configurator interface.
*/
struct pnphandler
{
const char *pp_name; /* handler/bus name */
void (* pp_enumerate)(void); /* enumerate PnP devices, add to chain */
};
struct pnpident
{
char *id_ident; /* ASCII identifier, actual format varies with bus/handler */
STAILQ_ENTRY(pnpident) id_link;
};
struct pnpinfo
{
char *pi_desc; /* ASCII description, optional */
int pi_revision; /* optional revision (or -1) if not supported */
char *pi_module; /* module/args nominated to handle device */
int pi_argc; /* module arguments */
char **pi_argv;
struct pnphandler *pi_handler; /* handler which detected this device */
STAILQ_HEAD(,pnpident) pi_ident; /* list of identifiers */
STAILQ_ENTRY(pnpinfo) pi_link;
};
STAILQ_HEAD(pnpinfo_stql, pnpinfo);
extern struct pnpinfo_stql pnp_devices;
extern struct pnphandler *pnphandlers[]; /* provided by MD code */
void pnp_addident(struct pnpinfo *pi, char *ident);
struct pnpinfo *pnp_allocinfo(void);
void pnp_freeinfo(struct pnpinfo *pi);
void pnp_addinfo(struct pnpinfo *pi);
char *pnp_eisaformat(u_int8_t *data);
/*
* < 0 - No ISA in system
* == 0 - Maybe ISA, search for read data port
* > 0 - ISA in system, value is read data port address
*/
extern int isapnp_readport;
struct preloaded_file;
/*
* Preloaded file information. Depending on type, file can contain
* additional units called 'modules'.
*
* At least one file (the kernel) must be loaded in order to boot.
* The kernel is always loaded first.
*
* String fields (m_name, m_type) should be dynamically allocated.
*/
struct preloaded_file
{
char *f_name; /* file name */
char *f_type; /* verbose file type, eg 'ELF kernel', 'pnptable', etc. */
char *f_args; /* arguments for the file */
int f_loader; /* index of the loader that read the file */
vaddr_t f_addr; /* load address */
size_t f_size; /* file size */
struct preloaded_file *f_next; /* next file */
u_long marks[MARK_MAX];/* filled by loadfile() */
};
struct file_format
{
/* Load function must return EFTYPE if it can't handle the module supplied */
int (* l_load)(char *filename, u_int64_t dest, struct preloaded_file **result);
/* Only a loader that will load a kernel (first module) should have an exec handler */
int (* l_exec)(struct preloaded_file *mp);
};
extern struct file_format *file_formats[]; /* supplied by consumer */
extern struct preloaded_file *preloaded_files;
int mod_load(char *name, int argc, char *argv[]);
int mod_loadkld(const char *name, int argc, char *argv[]);
struct preloaded_file *file_alloc(void);
struct preloaded_file *file_findfile(char *name, char *type);
int file_loadkernel(char *filename, int argc, char *argv[]);
void file_discard(struct preloaded_file *fp);
int elf64_loadfile(char *filename, u_int64_t dest, struct preloaded_file **result);
/*
* Support for commands
*/
struct bootblk_command
{
const char *c_name;
const char *c_desc;
bootblk_cmd_t *c_fn;
};
/* Prototypes for the command handlers within stand/common/ */
/* command.c */
int command_help(int argc, char *argv[]) ;
int command_commandlist(int argc, char *argv[]);
int command_show(int argc, char *argv[]);
int command_set(int argc, char *argv[]);
int command_unset(int argc, char *argv[]);
int command_echo(int argc, char *argv[]);
int command_read(int argc, char *argv[]);
int command_more(int argc, char *argv[]);
int command_lsdev(int argc, char *argv[]);
/* bcache.c XXX: Fixme: Do we need the bcache ?*/
/* int command_bcache(int argc, char *argv[]); */
/* boot.c */
int command_boot(int argc, char *argv[]);
int command_autoboot(int argc, char *argv[]);
/* fileload.c */
int command_load(int argc, char *argv[]);
int command_unload(int argc, char *argv[]);
int command_lskern(int argc, char *argv[]);
/* interp.c */
int command_include(int argc, char *argv[]);
/* ls.c */
int command_ls(int argc, char *argv[]);
#define COMMAND_SET(a, b, c, d) /* nothing */
#define COMMON_COMMANDS \
/* common.c */ \
{ "help", "detailed help", command_help }, \
{ "?", "list commands", command_commandlist }, \
{ "show", "show variable(s)", command_show }, \
{ "set", "set a variable", command_set }, \
{ "unset", "unset a variable", command_unset }, \
{ "echo", "echo arguments", command_echo }, \
{ "read", "read input from the terminal", command_read }, \
{ "more", "show contents of a file", command_more }, \
{ "lsdev", "list all devices", command_lsdev }, \
\
/* bcache.c XXX: Fixme: Do we need the bcache ? */ \
\
/* { "bcachestat", "get disk block cache stats", command_bcache }, */\
\
/* boot.c */ \
\
{ "boot", "boot a file or loaded kernel", command_boot }, \
{ "autoboot", "boot automatically after a delay", command_autoboot }, \
\
/* fileload.c */ \
\
{ "load", "load a kernel", command_load }, \
{ "unload", "unload all modules", command_unload }, \
{ "lskern", "list loaded kernel", command_lskern }, \
\
/* interp.c */ \
\
{ "include", "read commands from a file", command_include }, \
\
/* ls.c */ \
\
{ "ls", "list files", command_ls }
extern struct bootblk_command commands[];
/*
* The intention of the architecture switch is to provide a convenient
* encapsulation of the interface between the bootstrap MI and MD code.
* MD code may selectively populate the switch at runtime based on the
* actual configuration of the target system.
*/
struct arch_switch
{
/* Automatically load modules as required by detected hardware */
int (*arch_autoload)(void);
/* Locate the device for (name), return pointer to tail in (*path) */
int (*arch_getdev)(void **dev, const char *name, const char **path);
/* Copy from local address space to module address space, similar to bcopy() */
ssize_t (*arch_copyin)(const void *src, vaddr_t dest,
const size_t len);
/* Copy to local address space from module address space, similar to bcopy() */
ssize_t (*arch_copyout)(const vaddr_t src, void *dest,
const size_t len);
/* Read from file to module address space, same semantics as read() */
ssize_t (*arch_readin)(const int fd, vaddr_t dest,
const size_t len);
/* Perform ISA byte port I/O (only for systems with ISA) */
int (*arch_isainb)(int port);
void (*arch_isaoutb)(int port, int value);
};
extern struct arch_switch archsw;
/* This must be provided by the MD code, but should it be in the archsw? */
void delay(int delay);
void dev_cleanup(void);
time_t time(time_t *tloc);
/* calloc.c */
void *calloc(unsigned int, unsigned int);
/* various string functions */
size_t strspn(const char *s1, const char *s2);
size_t strlen(const char *s);
char *strcpy(char * restrict dst, const char * restrict src);
char *strcat(char * restrict s, const char * restrict append);
/* pager.c */
extern void pager_open(void);
extern void pager_close(void);
extern int pager_output(const char *lines);
extern int pager_file(const char *fname);
/* environment.c */
#define EV_DYNAMIC (1<<0) /* value was dynamically allocated, free if changed/unset */
#define EV_VOLATILE (1<<1) /* value is volatile, make a copy of it */
#define EV_NOHOOK (1<<2) /* don't call hook when setting */
struct env_var;
typedef char *(ev_format_t)(struct env_var *ev);
typedef int (ev_sethook_t)(struct env_var *ev, int flags,
const void *value);
typedef int (ev_unsethook_t)(struct env_var *ev);
struct env_var
{
char *ev_name;
int ev_flags;
void *ev_value;
ev_sethook_t *ev_sethook;
ev_unsethook_t *ev_unsethook;
struct env_var *ev_next, *ev_prev;
};
extern struct env_var *environ;
extern struct env_var *env_getenv(const char *name);
extern int env_setenv(const char *name, int flags,
const void *value, ev_sethook_t sethook,
ev_unsethook_t unsethook);
extern char *getenv(const char *name);
extern int setenv(const char *name, const char *value,
int overwrite);
extern int putenv(const char *string);
extern int unsetenv(const char *name);
extern ev_sethook_t env_noset; /* refuse set operation */
extern ev_unsethook_t env_nounset; /* refuse unset operation */
/* FreeBSD wrappers */
struct dirent *readdirfd(int); /* XXX move to stand.h */
#define free(ptr) dealloc(ptr, 0) /* XXX UGLY HACK!!! This should work for just now though. See: libsa/alloc.c:free() */
/* XXX Hack Hack Hack!!! Need to update stand.h with fs_ops->fo_readdir */
#ifdef SKIFS /* defined via stand/ia64/ski/Makefile */
#define FS_READDIR(f, dirptr) skifs_readdir(f, dirptr)
#else
#define FS_READDIR(f, dirptr) efifs_readdir(f, dirptr)
#endif
/* gets.c XXX move to libsa/ */
extern int fgetstr(char *buf, int size, int fd);
extern void ngets(char *, int);
/* imports from stdlib, modified for sa */
extern long strtol(const char *, char **, int);
extern char *optarg; /* getopt(3) external variables */
extern int optind, opterr, optopt, optreset;
extern int getopt(int, char * const [], const char *);
extern long strtol(const char *, char **, int);
/* XXX: From <fcntl.h>. Its not very _STANDALONE friendly */
/* open-only flags */
#define O_RDONLY 0x00000000 /* open for reading only */
#define O_WRONLY 0x00000001 /* open for writing only */
#define O_RDWR 0x00000002 /* open for reading and writing */
#define O_ACCMODE 0x00000003 /* mask for above modes */
#define ELF64_KERNELTYPE "elf kernel"
#endif /* _BOOTSTRAP_H_ */
|
4519dcfe67762981459328cdd698c2ebbacfd48a
|
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
|
/sys/external/bsd/drm2/dist/drm/i915/gt/uc/intel_guc_ct.h
|
d2414425f183078ed2ef27c78bb6a3ba6a82685e
|
[] |
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,189
|
h
|
intel_guc_ct.h
|
/* $NetBSD: intel_guc_ct.h,v 1.2 2021/12/18 23:45:31 riastradh Exp $ */
/* SPDX-License-Identifier: MIT */
/*
* Copyright © 2016-2019 Intel Corporation
*/
#ifndef _INTEL_GUC_CT_H_
#define _INTEL_GUC_CT_H_
#include <linux/spinlock.h>
#include <linux/workqueue.h>
#include "intel_guc_fwif.h"
struct i915_vma;
struct intel_guc;
/**
* DOC: Command Transport (CT).
*
* Buffer based command transport is a replacement for MMIO based mechanism.
* It can be used to perform both host-2-guc and guc-to-host communication.
*/
/** Represents single command transport buffer.
*
* A single command transport buffer consists of two parts, the header
* record (command transport buffer descriptor) and the actual buffer which
* holds the commands.
*
* @desc: pointer to the buffer descriptor
* @cmds: pointer to the commands buffer
*/
struct intel_guc_ct_buffer {
struct guc_ct_buffer_desc *desc;
u32 *cmds;
};
/** Top-level structure for Command Transport related data
*
* Includes a pair of CT buffers for bi-directional communication and tracking
* for the H2G and G2H requests sent and received through the buffers.
*/
struct intel_guc_ct {
struct i915_vma *vma;
bool enabled;
/* buffers for sending(0) and receiving(1) commands */
struct intel_guc_ct_buffer ctbs[2];
struct {
u32 next_fence; /* fence to be used with next request to send */
spinlock_t lock; /* protects pending requests list */
struct list_head pending; /* requests waiting for response */
struct list_head incoming; /* incoming requests */
struct work_struct worker; /* handler for incoming requests */
} requests;
};
void intel_guc_ct_init_early(struct intel_guc_ct *ct);
int intel_guc_ct_init(struct intel_guc_ct *ct);
void intel_guc_ct_fini(struct intel_guc_ct *ct);
int intel_guc_ct_enable(struct intel_guc_ct *ct);
void intel_guc_ct_disable(struct intel_guc_ct *ct);
static inline bool intel_guc_ct_enabled(struct intel_guc_ct *ct)
{
return ct->enabled;
}
int intel_guc_ct_send(struct intel_guc_ct *ct, const u32 *action, u32 len,
u32 *response_buf, u32 response_buf_size);
void intel_guc_ct_event_handler(struct intel_guc_ct *ct);
#endif /* _INTEL_GUC_CT_H_ */
|
8eb002e728cdd7504a19fe0b35f928f1794b3abc
|
ea401c3e792a50364fe11f7cea0f35f99e8f4bde
|
/hackathon/zhi/NeuronStudio_zhi/image/nspixels-mpfilter.c
|
389dd8f218071064b4c47d0be4cf07c9dc1bc78f
|
[
"MIT"
] |
permissive
|
Vaa3D/vaa3d_tools
|
edb696aa3b9b59acaf83d6d27c6ae0a14bf75fe9
|
e6974d5223ae70474efaa85e1253f5df1814fae8
|
refs/heads/master
| 2023-08-03T06:12:01.013752
| 2023-08-02T07:26:01
| 2023-08-02T07:26:01
| 50,527,925
| 107
| 86
|
MIT
| 2023-05-22T23:43:48
| 2016-01-27T18:19:17
|
C++
|
UTF-8
|
C
| false
| false
| 12,004
|
c
|
nspixels-mpfilter.c
|
#include "nspixels-mpfilter.h"
#include <ext/filtermgr.h>
NS_PRIVATE NsProc _ns_pixel_proc_mp_filter;
enum
{
__PIXEL_TYPE,
__PIXELS,
__WIDTH,
__HEIGHT,
__LENGTH,
__ROW_ALIGN,
__TYPE,
__NUM_CPU,
__REGION,
__PROGRESS,
__NUM_PARAMS
};
NS_PRIVATE NsClosureValue _ns_pixel_proc_mp_filter_params[ __NUM_PARAMS ] =
{
{ "pixel_type", NS_VALUE_PIXEL_TYPE },
{ "pixels", NS_VALUE_POINTER },
{ "width", NS_VALUE_SIZE },
{ "height", NS_VALUE_SIZE },
{ "length", NS_VALUE_SIZE },
{ "row_align", NS_VALUE_SIZE },
{ "type", NS_VALUE_INT },
{ "num_cpu", NS_VALUE_SIZE },
{ "region", NS_VALUE_PIXEL_REGION },
{ "progress", NS_VALUE_PROGRESS }
};
typedef NsError ( *_NsPixelProcExtFunc )
(
NsPixelType,
nspointer,
nssize,
nssize,
nssize,
nssize,
nsint,
nssize,
const NsPixelRegion*,
NsProgress*
);
const nschar* ns_pixel_proc_mp_filter_type_to_string( nsint type )
{
switch( type )
{
case NS_PIXEL_PROC_MP_FILTER_BLUR:
return "Blur - MP";
case NS_PIXEL_PROC_MP_FILTER_MEDIAN:
return "Median - MP";
case NS_PIXEL_PROC_MP_FILTER_BLUR_MORE:
return "Blur More - MP";
case NS_PIXEL_PROC_MP_FILTER_INVERT:
return "Invert - MP";
case NS_PIXEL_PROC_MP_FILTER_Z_BLUR:
return "Z-Blur - MP";
case NS_PIXEL_PROC_MP_FILTER_LUM_U12_TO_LUM_U16:
return "12 to 16 - MP";
default:
ns_assert_not_reached();
}
return NULL;
}
NS_PRIVATE nsint _ns_pixel_proc_mp_filter_xfrm_type( nsint type )
{
switch( type )
{
case NS_PIXEL_PROC_MP_FILTER_BLUR:
type = FILTER_BLUR;
break;
case NS_PIXEL_PROC_MP_FILTER_MEDIAN:
type = FILTER_MEDIAN;
break;
case NS_PIXEL_PROC_MP_FILTER_BLUR_MORE:
type = FILTER_BLUR26;
break;
case NS_PIXEL_PROC_MP_FILTER_INVERT:
type = FILTER_INVERT;
break;
case NS_PIXEL_PROC_MP_FILTER_Z_BLUR:
type = FILTER_ZBLUR;
break;
case NS_PIXEL_PROC_MP_FILTER_LUM_U12_TO_LUM_U16:
type = FILTER_12to16;
break;
default:
ns_assert_not_reached();
}
return type;
}
NS_PRIVATE NsError _ns_pixel_proc_mp_filter_lum_u8
(
NsPixelType pixel_type,
NsPixelLumU8 *pixels,
nssize width,
nssize height,
nssize length,
nssize row_align,
nsint type,
nssize num_cpu,
const NsPixelRegion *region,
NsProgress *progress
)
{
FILTERDEFINITION fd;
NS_USE_VARIABLE( pixel_type );
NS_USE_VARIABLE( row_align );
fd.image = ( nsuchar* )pixels;
ns_assert( width <= ( nssize )NS_INT_MAX );
ns_assert( height <= ( nssize )NS_INT_MAX );
ns_assert( length <= ( nssize )NS_INT_MAX );
fd.imagexdim = ( nslong )width;
fd.imageydim = ( nslong )height;
fd.imagezdim = ( nslong )length;
fd.threads = ( nsint )NS_MAX( 1, num_cpu );
fd.filtertype = _ns_pixel_proc_mp_filter_xfrm_type( type );
fd.progress = progress;
fd.region_x = ( nslong )region->x;
fd.region_y = ( nslong )region->y;
fd.region_z = ( nslong )region->z;
fd.region_width = ( nslong )region->width;
fd.region_height = ( nslong )region->height;
fd.region_length = ( nslong )region->length;
if( NULL != progress )
ns_progress_set_title( progress, ns_pixel_proc_mp_filter_type_to_string( type ) );
return RunFilter( &fd ) ?
ns_no_error() : ns_error_nomem( NS_ERROR_LEVEL_CRITICAL, NS_MODULE );
}
NS_PRIVATE NsError _ns_pixel_proc_mp_filter_lum_u12_or_u16
(
NsPixelType pixel_type,
NsPixelLumU16 *pixels,
nssize width,
nssize height,
nssize length,
nssize row_align,
nsint type,
nssize num_cpu,
const NsPixelRegion *region,
NsProgress *progress
)
{
FILTERDEFINITION16 fd;
NS_USE_VARIABLE( pixel_type );
NS_USE_VARIABLE( row_align );
fd.image = ( nsushort* )pixels;
ns_assert( width <= ( nssize )NS_INT_MAX );
ns_assert( height <= ( nssize )NS_INT_MAX );
ns_assert( length <= ( nssize )NS_INT_MAX );
fd.imagexdim = ( nslong )width;
fd.imageydim = ( nslong )height;
fd.imagezdim = ( nslong )length;
fd.threads = ( nsint )NS_MAX( 1, num_cpu );
fd.filtertype = _ns_pixel_proc_mp_filter_xfrm_type( type );
fd.progress = progress;
fd.is12bit = ( NS_PIXEL_LUM_U12 == pixel_type );
fd.region_x = ( nslong )region->x;
fd.region_y = ( nslong )region->y;
fd.region_z = ( nslong )region->z;
fd.region_width = ( nslong )region->width;
fd.region_height = ( nslong )region->height;
fd.region_length = ( nslong )region->length;
if( NULL != progress )
ns_progress_set_title( progress, ns_pixel_proc_mp_filter_type_to_string( type ) );
return RunFilter_16bit( &fd ) ?
ns_no_error() : ns_error_nomem( NS_ERROR_LEVEL_CRITICAL, NS_MODULE );
}
NS_PRIVATE _NsPixelProcExtFunc _ns_pixel_proc_mp_filter_func( NsPixelType pixel_type, nsint type )
{
_NsPixelProcExtFunc func = NULL;
NS_USE_VARIABLE( type );
switch( pixel_type )
{
case NS_PIXEL_LUM_U8:
func = _ns_pixel_proc_mp_filter_lum_u8;
break;
case NS_PIXEL_LUM_U12:
case NS_PIXEL_LUM_U16:
func = _ns_pixel_proc_mp_filter_lum_u12_or_u16;
break;
}
if( NULL == func )
ns_warning(
NS_WARNING_LEVEL_RECOVERABLE
NS_MODULE
" Pixel format "
NS_FMT_STRING_QUOTED
" not supported for procedure "
NS_FMT_STRING_QUOTED
".",
ns_pixel_type_to_string( pixel_type ),
_ns_pixel_proc_mp_filter.name
);
return func;
}
NS_PRIVATE NsError _ns_pixel_proc_mp_filter_call
(
NsPixelType pixel_type,
nspointer pixels,
nssize width,
nssize height,
nssize length,
nssize row_align,
nsint type,
nssize num_cpu,
const NsPixelRegion *sub_region,
NsProgress *progress
)
{
_NsPixelProcExtFunc func;
NsPixelRegion full_region;
const NsPixelRegion *region;
if( NULL == ( func = _ns_pixel_proc_mp_filter_func( pixel_type, type ) ) )
return ns_error_noimp( NS_ERROR_LEVEL_CAUTION, NS_MODULE );
ns_assert( NULL != pixels );
ns_assert( 0 < width );
ns_assert( 0 < height );
ns_assert( 0 < length );
region = ns_pixel_region_extract( sub_region, &full_region, width, height, length );
ns_pixel_region_verify( region, width, height, length );
ns_log_entry(
NS_LOG_ENTRY_FUNCTION,
NS_FUNCTION
"( pixel_type=" NS_FMT_STRING_DOUBLE_QUOTED
", pixels=" NS_FMT_POINTER
", width=" NS_FMT_ULONG
", height=" NS_FMT_ULONG
", length=" NS_FMT_ULONG
", row_align=" NS_FMT_ULONG
", type=" NS_FMT_STRING_DOUBLE_QUOTED
", num_cpu=" NS_FMT_ULONG
", region={x:" NS_FMT_ULONG
",y:" NS_FMT_ULONG
",z:" NS_FMT_ULONG
",width:" NS_FMT_ULONG
",height:" NS_FMT_ULONG
",length:" NS_FMT_ULONG
"}"
", progress=" NS_FMT_POINTER
" )",
ns_pixel_type_to_string( pixel_type ),
pixels,
width,
height,
length,
row_align,
ns_pixel_proc_mp_filter_type_to_string( type ),
num_cpu,
region->x, region->y, region->z, region->width, region->height, region->length,
progress
);
return ( func )(
pixel_type,
pixels,
width,
height,
length,
row_align,
type,
num_cpu,
region,
progress
);
}
NS_PRIVATE NsError _ns_pixel_proc_mp_filter_marshal
(
NsClosure *closure,
NsValue *params,
nssize num_params,
NsValue *ret_value
)
{
NS_USE_VARIABLE( closure );
NS_USE_VARIABLE( num_params );
NS_USE_VARIABLE( ret_value );
#ifdef NS_DEBUG
/*
ns_println( NS_FMT_STRING, _ns_pixel_proc_mp_filter.title );
ns_println( NS_FMT_STRING, _ns_pixel_proc_mp_filter.author );
ns_println( NS_FMT_STRING, _ns_pixel_proc_mp_filter.version );
ns_println( NS_FMT_STRING, _ns_pixel_proc_mp_filter.copyright );
ns_println( NS_FMT_STRING, _ns_pixel_proc_mp_filter.help );
ns_println(
NS_FMT_STRING " = " NS_FMT_INT,
_ns_pixel_proc_mp_filter_params[ __PIXEL_TYPE ].name,
ns_value_get_pixel_type( params + __PIXEL_TYPE )
);
ns_println(
NS_FMT_STRING " = " NS_FMT_POINTER,
_ns_pixel_proc_mp_filter_params[ __PIXELS ].name,
ns_value_get_pointer( params + __PIXELS )
);
ns_println(
NS_FMT_STRING " = " NS_FMT_ULONG,
_ns_pixel_proc_mp_filter_params[ __WIDTH ].name,
ns_value_get_size( params + __WIDTH )
);
ns_println(
NS_FMT_STRING " = " NS_FMT_ULONG,
_ns_pixel_proc_mp_filter_params[ __HEIGHT ].name,
ns_value_get_size( params + __HEIGHT )
);
ns_println(
NS_FMT_STRING " = " NS_FMT_ULONG,
_ns_pixel_proc_mp_filter_params[ __LENGTH ].name,
ns_value_get_size( params + __LENGTH )
);
ns_println(
NS_FMT_STRING " = " NS_FMT_ULONG,
_ns_pixel_proc_mp_filter_params[ __ROW_ALIGN ].name,
ns_value_get_size( params + __ROW_ALIGN )
);
ns_println(
NS_FMT_STRING " = " NS_FMT_STRING,
_ns_pixel_proc_mp_filter_params[ __TYPE ].name,
ns_pixel_proc_mp_filter_type_to_string( ns_value_get_int( params + __TYPE ) )
);
ns_println(
NS_FMT_STRING " = " NS_FMT_ULONG,
_ns_pixel_proc_mp_filter_params[ __NUM_CPU ].name,
ns_value_get_size( params + __NUM_CPU )
);
ns_println(
NS_FMT_STRING " = " NS_FMT_POINTER,
_ns_pixel_proc_mp_filter_params[ __REGION ].name,
ns_value_get_pixel_region( params + __REGION )
);
ns_println(
NS_FMT_STRING " = " NS_FMT_POINTER,
_ns_pixel_proc_mp_filter_params[ __PROGRESS ].name,
ns_value_get_progress( params + __PROGRESS )
);
*/
#endif/* NS_DEBUG */
return _ns_pixel_proc_mp_filter_call(
ns_value_get_pixel_type( params + __PIXEL_TYPE ),
ns_value_get_pointer( params + __PIXELS ),
ns_value_get_size( params + __WIDTH ),
ns_value_get_size( params + __HEIGHT ),
ns_value_get_size( params + __LENGTH ),
ns_value_get_size( params + __ROW_ALIGN ),
ns_value_get_int( params + __TYPE ),
ns_value_get_size( params + __NUM_CPU ),
ns_value_get_pixel_region( params + __REGION ),
ns_value_get_progress( params + __PROGRESS )
);
}
NsProc* ns_pixel_proc_mp_filter( void )
{
_ns_pixel_proc_mp_filter.name = NS_PIXEL_PROC_MP_FILTER;
_ns_pixel_proc_mp_filter.version = "1.0";
_ns_pixel_proc_mp_filter.invoke_type = NS_PROC_INVOKE_MARSHAL;
_ns_pixel_proc_mp_filter.params = _ns_pixel_proc_mp_filter_params;
_ns_pixel_proc_mp_filter.num_params = NS_ARRAY_LENGTH( _ns_pixel_proc_mp_filter_params );
_ns_pixel_proc_mp_filter.marshal = _ns_pixel_proc_mp_filter_marshal;
_ns_pixel_proc_mp_filter.ret_value.name = NULL;
_ns_pixel_proc_mp_filter.ret_value.type = NS_VALUE_VOID;
return &_ns_pixel_proc_mp_filter;
}
|
5a74a156cb4c2daac3ecc905bc14236dbdd35aa0
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/include/linux/nfs_fs_i.h
|
a5c50d97341edfac63d04a0f7bad96a5f1bfd0f9
|
[
"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
| 269
|
h
|
nfs_fs_i.h
|
#ifndef _NFS_FS_I
#define _NFS_FS_I
struct nlm_lockowner;
/*
* NFS lock info
*/
struct nfs_lock_info {
u32 state;
struct nlm_lockowner *owner;
struct list_head list;
};
struct nfs4_lock_state;
struct nfs4_lock_info {
struct nfs4_lock_state *owner;
};
#endif
|
c07656b9e8ee0aebe7390f802e36d74a39885991
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/u-boot_new/arch/powerpc/include/asm/ppc4xx-i2c.h
|
09189cf19bc8f7470ee6f70dbfb764018886b4c9
|
[
"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
| 2,083
|
h
|
ppc4xx-i2c.h
|
/*
* (C) Copyright 2007-2009
* Stefan Roese, DENX Software Engineering, sr@denx.de.
*
* SPDX-License-Identifier: GPL-2.0+
*/
#ifndef _4xx_i2c_h_
#define _4xx_i2c_h_
#define IIC_OK 0
#define IIC_NOK 1
#define IIC_NOK_LA 2 /* Lost arbitration */
#define IIC_NOK_ICT 3 /* Incomplete transfer */
#define IIC_NOK_XFRA 4 /* Transfer aborted */
#define IIC_NOK_DATA 5 /* No data in buffer */
#define IIC_NOK_TOUT 6 /* Transfer timeout */
#define IIC_TIMEOUT 1 /* 1 second */
struct ppc4xx_i2c {
u8 mdbuf;
u8 res1;
u8 sdbuf;
u8 res2;
u8 lmadr;
u8 hmadr;
u8 cntl;
u8 mdcntl;
u8 sts;
u8 extsts;
u8 lsadr;
u8 hsadr;
u8 clkdiv;
u8 intrmsk;
u8 xfrcnt;
u8 xtcntlss;
u8 directcntl;
u8 intr;
};
/* MDCNTL Register Bit definition */
#define IIC_MDCNTL_HSCL 0x01
#define IIC_MDCNTL_EUBS 0x02
#define IIC_MDCNTL_EINT 0x04
#define IIC_MDCNTL_ESM 0x08
#define IIC_MDCNTL_FSM 0x10
#define IIC_MDCNTL_EGC 0x20
#define IIC_MDCNTL_FMDB 0x40
#define IIC_MDCNTL_FSDB 0x80
/* CNTL Register Bit definition */
#define IIC_CNTL_PT 0x01
#define IIC_CNTL_READ 0x02
#define IIC_CNTL_CHT 0x04
#define IIC_CNTL_RPST 0x08
/* bit 2/3 for Transfer count*/
#define IIC_CNTL_AMD 0x40
#define IIC_CNTL_HMT 0x80
/* STS Register Bit definition */
#define IIC_STS_PT 0x01
#define IIC_STS_IRQA 0x02
#define IIC_STS_ERR 0x04
#define IIC_STS_SCMP 0x08
#define IIC_STS_MDBF 0x10
#define IIC_STS_MDBS 0x20
#define IIC_STS_SLPR 0x40
#define IIC_STS_SSS 0x80
/* EXTSTS Register Bit definition */
#define IIC_EXTSTS_XFRA 0x01
#define IIC_EXTSTS_ICT 0x02
#define IIC_EXTSTS_LA 0x04
/* XTCNTLSS Register Bit definition */
#define IIC_XTCNTLSS_SRST 0x01
#define IIC_XTCNTLSS_EPI 0x02
#define IIC_XTCNTLSS_SDBF 0x04
#define IIC_XTCNTLSS_SBDD 0x08
#define IIC_XTCNTLSS_SWS 0x10
#define IIC_XTCNTLSS_SWC 0x20
#define IIC_XTCNTLSS_SRS 0x40
#define IIC_XTCNTLSS_SRC 0x80
/* IICx_DIRECTCNTL register */
#define IIC_DIRCNTL_SDAC 0x08
#define IIC_DIRCNTL_SCC 0x04
#define IIC_DIRCNTL_MSDA 0x02
#define IIC_DIRCNTL_MSC 0x01
#define DIRCTNL_FREE(v) (((v) & 0x0f) == 0x0f)
#endif
|
25b7cad088c457db7abb8535b81d729b83ab7bc7
|
99bdb3251fecee538e0630f15f6574054dfc1468
|
/bsp/yichip/yc3121-pos/Libraries/sdk/yc_gpio.c
|
ed42e2bd1170b0b77b3c0b0d33c5be4c8f5699c2
|
[
"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
| 4,706
|
c
|
yc_gpio.c
|
/*
File Name : yc_gpio.c
Author : Yichip
Version : V1.0
Date : 2019/12/03
Description : gpio encapsulation.
*/
#include "yc_gpio.h"
void GPIO_Config(GPIO_TypeDef GPIOx, uint16_t GPIO_Pin, GPIO_FunTypeDef function)
{
_ASSERT(ISGPIOGROUP(GPIOx));
_ASSERT(IS_GET_GPIO_PIN(GPIO_Pin));
int i;
for (i = 0; i < GPIO_PIN_NUM; i++)
{
if (GPIO_Pin & 1 << i)
GPIO_CONFIG(GPIOx * GPIO_PIN_NUM + i) = function;
}
}
void GPIO_Init(GPIO_TypeDef GPIOx, GPIO_InitTypeDef *GPIO_InitStruct)
{
_ASSERT(ISGPIOGROUP(GPIOx));
_ASSERT(IS_GPIO_PIN(GPIO_InitStruct->GPIO_Pin));
_ASSERT(IS_GPIO_MODE(GPIO_InitStruct->GPIO_Mode));
int i;
switch (GPIO_InitStruct->GPIO_Mode)
{
case GPIO_Mode_IN_FLOATING:
for (i = 0; i < GPIO_PIN_NUM; i++)
{
if (GPIO_InitStruct->GPIO_Pin & 1 << i)
GPIO_CONFIG(GPIOx * GPIO_PIN_NUM + i) = 0x00;
}
break;
case GPIO_Mode_IPU:
for (i = 0; i < GPIO_PIN_NUM; i++)
{
if (GPIO_InitStruct->GPIO_Pin & 1 << i)
GPIO_CONFIG(GPIOx * GPIO_PIN_NUM + i) = 0x40;
}
break;
case GPIO_Mode_IPD:
for (i = 0; i < GPIO_PIN_NUM; i++)
{
if (GPIO_InitStruct->GPIO_Pin & 1 << i)
GPIO_CONFIG(GPIOx * GPIO_PIN_NUM + i) = 0x80;
}
break;
case GPIO_Mode_AIN:
for (i = 0; i < GPIO_PIN_NUM; i++)
{
if (GPIO_InitStruct->GPIO_Pin & 1 << i)
GPIO_CONFIG(GPIOx * GPIO_PIN_NUM + i) = 0xC0;
}
break;
case GPIO_Mode_Out_PP:
for (i = 0; i < GPIO_PIN_NUM; i++)
{
if (GPIO_InitStruct->GPIO_Pin & 1 << i)
GPIO_CONFIG(GPIOx * GPIO_PIN_NUM + i) = 0x3E;
}
break;
default:
break;
}
}
void GPIO_PullUpCmd(GPIO_TypeDef GPIOx, uint16_t GPIO_Pin, FunctionalState NewState)
{
_ASSERT(ISGPIOGROUP(GPIOx));
_ASSERT(IS_GET_GPIO_PIN(GPIO_Pin));
int i;
for (i = 0; i < GPIO_PIN_NUM; i++)
{
if (GPIO_Pin & 1 << i)
{
if (NewState == ENABLE)
{
GPIO_CONFIG(GPIOx * GPIO_PIN_NUM + i) |= 1 << 6;
}
else if (NewState == DISABLE)
{
GPIO_CONFIG(GPIOx * GPIO_PIN_NUM + i) &= ~(1 << 6);
}
}
}
}
uint16_t GPIO_ReadInputData(GPIO_TypeDef GPIOx)
{
_ASSERT(ISGPIOGROUP(GPIOx));
return GPIO_IN(GPIOx);
}
uint8_t GPIO_ReadInputDataBit(GPIO_TypeDef GPIOx, uint16_t GPIO_Pin)
{
_ASSERT(ISGPIOGROUP(GPIOx));
_ASSERT(IS_GET_GPIO_PIN(GPIO_Pin));
if (GPIO_IN(GPIOx) & GPIO_Pin)
{
return (uint8_t)0x01;
}
else
{
return (uint8_t)0x00;
}
}
uint16_t GPIO_ReadOutputData(GPIO_TypeDef GPIOx)
{
_ASSERT(ISGPIOGROUP(GPIOx));
return GPIO_IN(GPIOx);
}
uint8_t GPIO_ReadOutputDataBit(GPIO_TypeDef GPIOx, uint16_t GPIO_Pin)
{
_ASSERT(ISGPIOGROUP(GPIOx));
_ASSERT(IS_GET_GPIO_PIN(GPIO_Pin));
if (GPIO_IN(GPIOx) & GPIO_Pin)
{
return (uint8_t)0x01;
}
else
{
return (uint8_t)0x00;
}
}
void GPIO_ResetBits(GPIO_TypeDef GPIOx, uint16_t GPIO_Pin)
{
_ASSERT(ISGPIOGROUP(GPIOx));
_ASSERT(IS_GET_GPIO_PIN(GPIO_Pin));
int i;
uint8_t Temp;
for (i = 0; i < GPIO_PIN_NUM; i++)
{
if (GPIO_Pin & 1 << i)
{
Temp = GPIO_CONFIG(GPIOx * GPIO_PIN_NUM + i);
Temp |= 0x3F; //00111111
Temp &= 0xFE; //11111110
GPIO_CONFIG(GPIOx * GPIO_PIN_NUM + i) = Temp;
}
}
}
void GPIO_SetBits(GPIO_TypeDef GPIOx, uint16_t GPIO_Pin)
{
_ASSERT(ISGPIOGROUP(GPIOx));
_ASSERT(IS_GET_GPIO_PIN(GPIO_Pin));
int i;
for (i = 0; i < GPIO_PIN_NUM; i++)
{
if (GPIO_Pin & 1 << i)
GPIO_CONFIG(GPIOx * GPIO_PIN_NUM + i) |= 0x3F; //00111111
}
}
void GPIO_StructInit(GPIO_InitTypeDef *GPIO_InitStruct)
{
GPIO_InitStruct->GPIO_Pin = GPIO_Pin_All;
GPIO_InitStruct->GPIO_Mode = GPIO_Mode_IN_FLOATING;
}
void GPIO_Write(GPIO_TypeDef GPIOx, uint16_t value)
{
_ASSERT(ISGPIOGROUP(GPIOx));
int i;
for (i = 0; i < GPIO_PIN_NUM; i++)
{
if (BIT_GET(value, i))
GPIO_SetBits(GPIOx, 1 << i);
else
GPIO_ResetBits(GPIOx, 1 << i);
}
}
void GPIO_WriteBit(GPIO_TypeDef GPIOx, uint16_t GPIO_Pin, BitAction BitVal)
{
_ASSERT(ISGPIOGROUP(GPIOx));
_ASSERT(IS_GET_GPIO_PIN(GPIO_Pin));
if (BitVal == Bit_SET)
GPIO_SetBits(GPIOx, GPIO_Pin);
else if (BitVal == Bit_RESET)
GPIO_ResetBits(GPIOx, GPIO_Pin);
}
|
7af9e63c3dbd68e1d431b2927ea43309e372d2b6
|
5eff7a36d9a9917dce9111f0c3074375fe6f7656
|
/lib/mesa/src/panfrost/lib/pan_encoder.h
|
68349996cded06775af3cf0f4c50230e2f20ad23
|
[] |
no_license
|
openbsd/xenocara
|
cb392d02ebba06f6ff7d826fd8a89aa3b8401779
|
a012b5de33ea0b977095d77316a521195b26cc6b
|
refs/heads/master
| 2023-08-25T12:16:58.862008
| 2023-08-12T16:16:25
| 2023-08-12T16:16:25
| 66,967,384
| 177
| 66
| null | 2023-07-22T18:12:37
| 2016-08-30T18:36:01
|
C
|
UTF-8
|
C
| false
| false
| 8,821
|
h
|
pan_encoder.h
|
/*
* Copyright (C) 2019 Collabora, Ltd.
*
* 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 (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 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.
*
* Authors (Collabora):
* Alyssa Rosenzweig <alyssa.rosenzweig@collabora.com>
*/
#ifndef __PAN_ENCODER_H
#define __PAN_ENCODER_H
#include "util/macros.h"
#include <stdbool.h>
#include "util/format/u_format.h"
#include "pan_bo.h"
#include "genxml/gen_macros.h"
#include "pan_device.h"
/* Tiler structure size computation */
unsigned
panfrost_tiler_header_size(unsigned width, unsigned height, unsigned mask, bool hierarchy);
unsigned
panfrost_tiler_full_size(unsigned width, unsigned height, unsigned mask, bool hierarchy);
unsigned
panfrost_choose_hierarchy_mask(
unsigned width, unsigned height,
unsigned vertex_count, bool hierarchy);
#if defined(PAN_ARCH) && PAN_ARCH <= 5
static inline unsigned
panfrost_tiler_get_polygon_list_size(const struct panfrost_device *dev,
unsigned fb_width, unsigned fb_height,
bool has_draws)
{
if (!has_draws)
return MALI_MIDGARD_TILER_MINIMUM_HEADER_SIZE + 4;
bool hierarchy = !dev->model->quirks.no_hierarchical_tiling;
unsigned hierarchy_mask =
panfrost_choose_hierarchy_mask(fb_width, fb_height, 1, hierarchy);
return panfrost_tiler_full_size(fb_width, fb_height, hierarchy_mask, hierarchy) +
panfrost_tiler_header_size(fb_width, fb_height, hierarchy_mask, hierarchy);
}
#endif
/* Stack sizes */
unsigned
panfrost_get_stack_shift(unsigned stack_size);
unsigned
panfrost_get_total_stack_size(
unsigned thread_size,
unsigned threads_per_core,
unsigned core_id_range);
/* Attributes / instancing */
unsigned
panfrost_padded_vertex_count(unsigned vertex_count);
unsigned
panfrost_compute_magic_divisor(unsigned hw_divisor, unsigned *o_shift, unsigned *extra_flags);
#ifdef PAN_ARCH
/* Records for gl_VertexID and gl_InstanceID use special encodings on Midgard */
#if PAN_ARCH <= 5
static inline void
panfrost_vertex_id(unsigned padded_count,
struct mali_attribute_buffer_packed *attr,
bool instanced)
{
pan_pack(attr, ATTRIBUTE_VERTEX_ID, cfg) {
if (instanced) {
cfg.divisor_r = __builtin_ctz(padded_count);
cfg.divisor_p = padded_count >> (cfg.divisor_r + 1);
} else {
/* Large values so the modulo is a no-op */
cfg.divisor_r = 0x1F;
cfg.divisor_p = 0x4;
}
}
}
static inline void
panfrost_instance_id(unsigned padded_count,
struct mali_attribute_buffer_packed *attr,
bool instanced)
{
pan_pack(attr, ATTRIBUTE_INSTANCE_ID, cfg) {
if (!instanced || padded_count <= 1) {
/* Divide by large number to force to 0 */
cfg.divisor_p = ((1u << 31) - 1);
cfg.divisor_r = 0x1F;
cfg.divisor_e = 0x1;
} else if(util_is_power_of_two_or_zero(padded_count)) {
/* Can't underflow since padded_count >= 2 */
cfg.divisor_r = __builtin_ctz(padded_count) - 1;
} else {
cfg.divisor_p =
panfrost_compute_magic_divisor(padded_count,
&cfg.divisor_r, &cfg.divisor_e);
}
}
}
#endif /* PAN_ARCH <= 5 */
/* Sampler comparison functions are flipped in OpenGL from the hardware, so we
* need to be able to flip accordingly */
static inline enum mali_func
panfrost_flip_compare_func(enum mali_func f)
{
switch (f) {
case MALI_FUNC_LESS: return MALI_FUNC_GREATER;
case MALI_FUNC_GREATER: return MALI_FUNC_LESS;
case MALI_FUNC_LEQUAL: return MALI_FUNC_GEQUAL;
case MALI_FUNC_GEQUAL: return MALI_FUNC_LEQUAL;
default: return f;
}
}
#if PAN_ARCH <= 7
/* Compute shaders are invoked with a gl_NumWorkGroups X/Y/Z triplet. Vertex
* shaders are invoked as (1, vertex_count, instance_count). Compute shaders
* also have a gl_WorkGroupSize X/Y/Z triplet. These 6 values are packed
* together in a dynamic bitfield, packed by this routine. */
static inline void
panfrost_pack_work_groups_compute(
struct mali_invocation_packed *out,
unsigned num_x, unsigned num_y, unsigned num_z,
unsigned size_x, unsigned size_y, unsigned size_z,
bool quirk_graphics, bool indirect_dispatch)
{
/* The values needing packing, in order, and the corresponding shifts.
* Indicies into shift are off-by-one to make the logic easier */
unsigned values[6] = { size_x, size_y, size_z, num_x, num_y, num_z };
unsigned shifts[7] = { 0 };
uint32_t packed = 0;
for (unsigned i = 0; i < 6; ++i) {
/* Must be positive, otherwise we underflow */
assert(values[i] >= 1);
/* OR it in, shifting as required */
packed |= ((values[i] - 1) << shifts[i]);
/* How many bits did we use? */
unsigned bit_count = util_logbase2_ceil(values[i]);
/* Set the next shift accordingly */
shifts[i + 1] = shifts[i] + bit_count;
}
pan_pack(out, INVOCATION, cfg) {
cfg.invocations = packed;
cfg.size_y_shift = shifts[1];
cfg.size_z_shift = shifts[2];
cfg.workgroups_x_shift = shifts[3];
if (!indirect_dispatch) {
/* Leave zero for the dispatch shader */
cfg.workgroups_y_shift = shifts[4];
cfg.workgroups_z_shift = shifts[5];
}
/* Quirk: for non-instanced graphics, the blob sets
* workgroups_z_shift = 32. This doesn't appear to matter to
* the hardware, but it's good to be bit-identical. */
if (quirk_graphics && (num_z <= 1))
cfg.workgroups_z_shift = 32;
/* For graphics, set to the minimum efficient value. For
* compute, must equal the workgroup X shift for barriers to
* function correctly */
cfg.thread_group_split = quirk_graphics ?
MALI_SPLIT_MIN_EFFICIENT : cfg.workgroups_x_shift;
}
}
#endif
#if PAN_ARCH >= 5
/* Format conversion */
static inline enum mali_z_internal_format
panfrost_get_z_internal_format(enum pipe_format fmt)
{
switch (fmt) {
case PIPE_FORMAT_Z16_UNORM:
case PIPE_FORMAT_Z16_UNORM_S8_UINT:
return MALI_Z_INTERNAL_FORMAT_D16;
case PIPE_FORMAT_Z24_UNORM_S8_UINT:
case PIPE_FORMAT_Z24X8_UNORM:
return MALI_Z_INTERNAL_FORMAT_D24;
case PIPE_FORMAT_Z32_FLOAT:
case PIPE_FORMAT_Z32_FLOAT_S8X24_UINT:
return MALI_Z_INTERNAL_FORMAT_D32;
default:
unreachable("Unsupported depth/stencil format.");
}
}
#endif
#endif /* PAN_ARCH */
#if PAN_ARCH >= 9
static inline void
panfrost_make_resource_table(struct panfrost_ptr base, unsigned index,
mali_ptr address, unsigned resource_count)
{
if (resource_count == 0)
return;
pan_pack(base.cpu + index * pan_size(RESOURCE), RESOURCE, cfg) {
cfg.address = address;
cfg.size = resource_count * pan_size(BUFFER);
}
}
#endif
#endif
|
f46b0372707283f5c973cdbf1ac80e94ed90f541
|
f62ddee2dcadcae0e90f969be513b04e16dabf58
|
/data/source/yaltools/mount_handle/struct-is_locked.h
|
34a35b835293e2d135908f030c27294c36f9308d
|
[
"Apache-2.0"
] |
permissive
|
libyal/libyal
|
30bccf56471dbf874292fe32d5d9173fd470df0e
|
124111953917f65782a66a80e96a502ce2331b09
|
refs/heads/main
| 2023-07-25T09:25:46.068071
| 2023-07-08T09:56:44
| 2023-07-08T09:56:44
| 23,780,738
| 196
| 30
|
Apache-2.0
| 2022-11-27T19:01:42
| 2014-09-08T05:57:58
|
C
|
UTF-8
|
C
| false
| false
| 71
|
h
|
struct-is_locked.h
|
/* Value to indicate the mount handle is locked
*/
int is_locked;
|
e8123867a35cc2bc781719abd21b23c177033b9e
|
84f1ce4838c39cec710818d69005f8919ec39994
|
/src/arch/armv8/armv8-a/inc/arch/iommu.h
|
7509697c9eb38243e3147fc5de2d2a4c07884f07
|
[
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] |
permissive
|
bao-project/bao-hypervisor
|
adb2689fdd690d10ea11fa693375c4043a9f9309
|
291cac3df9d5e0b4704006376196cd2231105704
|
refs/heads/main
| 2023-08-31T05:50:21.845457
| 2023-07-25T19:46:28
| 2023-08-22T12:09:57
| 233,099,706
| 231
| 78
|
Apache-2.0
| 2023-09-14T13:58:26
| 2020-01-10T17:42:11
|
C
|
UTF-8
|
C
| false
| false
| 770
|
h
|
iommu.h
|
/**
* SPDX-License-Identifier: Apache-2.0
* Copyright (c) Bao Project and Contributors. All rights reserved
*/
/**
* baohu separation kernel
*
* Copyright (c) Jose Martins, Sandro Pinto, David Cerdeira
*
* Authors:
* David Cerdeira <davidmcerdeira@gmail.com>
*
* baohu is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License version 2 as published by the Free
* Software Foundation, with a special exception exempting guest code from such
* license. See the COPYING file in the top-level directory for details.
*
*/
#ifndef __IOMMU_ARCH_H__
#define __IOMMU_ARCH_H__
#include <bao.h>
#include <arch/smmuv2.h>
struct iommu_vm_arch {
streamid_t global_mask;
size_t ctx_id;
};
#endif
|
b6a32b998aa7ad5ea9558b143f036d627e4bec59
|
5eff7a36d9a9917dce9111f0c3074375fe6f7656
|
/lib/mesa/src/gallium/drivers/svga/svga_draw_elements.c
|
ec7cba7588aad3d914b7ca35d05f4b3201728d48
|
[] |
no_license
|
openbsd/xenocara
|
cb392d02ebba06f6ff7d826fd8a89aa3b8401779
|
a012b5de33ea0b977095d77316a521195b26cc6b
|
refs/heads/master
| 2023-08-25T12:16:58.862008
| 2023-08-12T16:16:25
| 2023-08-12T16:16:25
| 66,967,384
| 177
| 66
| null | 2023-07-22T18:12:37
| 2016-08-30T18:36:01
|
C
|
UTF-8
|
C
| false
| false
| 13,171
|
c
|
svga_draw_elements.c
|
/**********************************************************
* Copyright 2008-2009 VMware, Inc. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, 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 "indices/u_indices.h"
#include "util/u_inlines.h"
#include "util/u_prim.h"
#include "util/u_upload_mgr.h"
#include "svga_cmd.h"
#include "svga_draw.h"
#include "svga_draw_private.h"
#include "svga_resource_buffer.h"
#include "svga_winsys.h"
#include "svga_context.h"
#include "svga_hw_reg.h"
/**
* Return a new index buffer which contains a translation of the original
* index buffer. An example of a translation is converting from QUAD
* primitives to TRIANGLE primitives. Each set of four indexes for a quad
* will be converted to six indices for two triangles.
*
* Before generating the new index buffer we'll check if the incoming
* buffer already has a translated buffer that can be re-used.
* This benefits demos like Cinebench R15 which has many
* glDrawElements(GL_QUADS) commands (we can't draw quads natively).
*
* \param offset offset in bytes to first index to translate in src buffer
* \param orig_prim original primitive type (like PIPE_PRIM_QUADS)
* \param gen_prim new/generated primitive type (like PIPE_PRIM_TRIANGLES)
* \param orig_nr number of indexes to translate in source buffer
* \param gen_nr number of indexes to write into new/dest buffer
* \param index_size bytes per index (2 or 4)
* \param translate the translation function from the u_translate module
* \param out_buf returns the new/translated index buffer
* \return error code to indicate success failure
*/
static enum pipe_error
translate_indices(struct svga_hwtnl *hwtnl,
const struct pipe_draw_info *info,
const struct pipe_draw_start_count_bias *draw,
enum pipe_prim_type gen_prim,
unsigned orig_nr, unsigned gen_nr,
unsigned gen_size,
u_translate_func translate,
struct pipe_resource **out_buf,
unsigned *out_offset)
{
struct pipe_context *pipe = &hwtnl->svga->pipe;
struct svga_screen *screen = svga_screen(pipe->screen);
struct svga_buffer *src_sbuf = NULL;
struct pipe_transfer *src_transfer = NULL;
struct pipe_transfer *dst_transfer = NULL;
const unsigned size = gen_size * gen_nr;
const unsigned offset = draw->start * info->index_size;
const void *src_map = NULL;
struct pipe_resource *dst = NULL;
void *dst_map = NULL;
assert(gen_size == 2 || gen_size == 4);
if (!info->has_user_indices)
src_sbuf = svga_buffer(info->index.resource);
/* If the draw_info provides us with a buffer rather than a
* user pointer, Check to see if we've already translated that buffer
*/
if (src_sbuf && !screen->debug.no_cache_index_buffers) {
/* Check if we already have a translated index buffer */
if (src_sbuf->translated_indices.buffer &&
src_sbuf->translated_indices.orig_prim == info->mode &&
src_sbuf->translated_indices.new_prim == gen_prim &&
src_sbuf->translated_indices.offset == offset &&
src_sbuf->translated_indices.count == orig_nr &&
src_sbuf->translated_indices.index_size == gen_size) {
pipe_resource_reference(out_buf, src_sbuf->translated_indices.buffer);
return PIPE_OK;
}
}
/* Need to trim vertex count to make sure we don't write too much data
* to the dst buffer in the translate() call.
*/
u_trim_pipe_prim(gen_prim, &gen_nr);
if (src_sbuf) {
/* If we have a source buffer, create a destination buffer in the
* hope that we can reuse the translated data later. If not,
* we'd probably be better off using the upload buffer.
*/
dst = pipe_buffer_create(pipe->screen,
PIPE_BIND_INDEX_BUFFER, PIPE_USAGE_IMMUTABLE,
size);
if (!dst)
goto fail;
dst_map = pipe_buffer_map(pipe, dst, PIPE_MAP_WRITE, &dst_transfer);
if (!dst_map)
goto fail;
*out_offset = 0;
src_map = pipe_buffer_map(pipe, info->index.resource,
PIPE_MAP_READ |
PIPE_MAP_UNSYNCHRONIZED,
&src_transfer);
if (!src_map)
goto fail;
} else {
/* Allocate upload buffer space. Align to the index size. */
u_upload_alloc(pipe->stream_uploader, 0, size, gen_size,
out_offset, &dst, &dst_map);
if (!dst)
goto fail;
src_map = info->index.user;
}
translate((const char *) src_map + offset, 0, 0, gen_nr, 0, dst_map);
if (src_transfer)
pipe_buffer_unmap(pipe, src_transfer);
if (dst_transfer)
pipe_buffer_unmap(pipe, dst_transfer);
else
u_upload_unmap(pipe->stream_uploader);
*out_buf = dst;
if (src_sbuf && !screen->debug.no_cache_index_buffers) {
/* Save the new, translated index buffer in the hope we can use it
* again in the future.
*/
pipe_resource_reference(&src_sbuf->translated_indices.buffer, dst);
src_sbuf->translated_indices.orig_prim = info->mode;
src_sbuf->translated_indices.new_prim = gen_prim;
src_sbuf->translated_indices.offset = offset;
src_sbuf->translated_indices.count = orig_nr;
src_sbuf->translated_indices.index_size = gen_size;
}
return PIPE_OK;
fail:
if (src_transfer)
pipe_buffer_unmap(pipe, src_transfer);
if (dst_transfer)
pipe_buffer_unmap(pipe, dst_transfer);
else if (dst_map)
u_upload_unmap(pipe->stream_uploader);
if (dst)
pipe_resource_reference(&dst, NULL);
return PIPE_ERROR_OUT_OF_MEMORY;
}
enum pipe_error
svga_hwtnl_simple_draw_range_elements(struct svga_hwtnl *hwtnl,
struct pipe_resource *index_buffer,
unsigned index_size, int index_bias,
unsigned min_index, unsigned max_index,
enum pipe_prim_type prim, unsigned start,
unsigned count,
unsigned start_instance,
unsigned instance_count,
ubyte vertices_per_patch)
{
SVGA3dPrimitiveRange range;
unsigned hw_prim;
unsigned hw_count;
unsigned index_offset = start * index_size;
hw_prim = svga_translate_prim(prim, count, &hw_count, vertices_per_patch);
if (hw_count == 0)
return PIPE_OK; /* nothing to draw */
range.primType = hw_prim;
range.primitiveCount = hw_count;
range.indexArray.offset = index_offset;
range.indexArray.stride = index_size;
range.indexWidth = index_size;
range.indexBias = index_bias;
return svga_hwtnl_prim(hwtnl, &range, count,
min_index, max_index, index_buffer,
start_instance, instance_count,
NULL, NULL);
}
enum pipe_error
svga_hwtnl_draw_range_elements(struct svga_hwtnl *hwtnl,
const struct pipe_draw_info *info,
const struct pipe_draw_start_count_bias *draw,
unsigned count)
{
struct pipe_context *pipe = &hwtnl->svga->pipe;
enum pipe_prim_type gen_prim;
unsigned gen_size, gen_nr;
enum indices_mode gen_type;
u_translate_func gen_func;
enum pipe_error ret = PIPE_OK;
SVGA_STATS_TIME_PUSH(svga_sws(hwtnl->svga),
SVGA_STATS_TIME_HWTNLDRAWELEMENTS);
if (svga_need_unfilled_fallback(hwtnl, info->mode)) {
gen_type = u_unfilled_translator(info->mode,
info->index_size,
count,
hwtnl->api_fillmode,
&gen_prim,
&gen_size, &gen_nr, &gen_func);
}
else {
unsigned hw_pv;
/* There is no geometry ordering with PATCH, so no need to
* consider provoking vertex mode for the translation.
* So use the same api_pv as the hw_pv.
*/
hw_pv = info->mode == PIPE_PRIM_PATCHES ? hwtnl->api_pv :
hwtnl->hw_pv;
gen_type = u_index_translator(svga_hw_prims,
info->mode,
info->index_size,
count,
hwtnl->api_pv,
hw_pv,
PR_DISABLE,
&gen_prim, &gen_size, &gen_nr, &gen_func);
}
if ((gen_type == U_TRANSLATE_MEMCPY) && (info->index_size == gen_size)) {
/* No need for translation, just pass through to hardware:
*/
unsigned start_offset = draw->start * info->index_size;
struct pipe_resource *index_buffer = NULL;
unsigned index_offset;
if (info->has_user_indices) {
u_upload_data(pipe->stream_uploader, 0, count * info->index_size,
info->index_size, (char *) info->index.user + start_offset,
&index_offset, &index_buffer);
u_upload_unmap(pipe->stream_uploader);
index_offset /= info->index_size;
} else {
pipe_resource_reference(&index_buffer, info->index.resource);
index_offset = draw->start;
}
assert(index_buffer != NULL);
ret = svga_hwtnl_simple_draw_range_elements(hwtnl, index_buffer,
info->index_size,
draw->index_bias,
info->index_bounds_valid ? info->min_index : 0,
info->index_bounds_valid ? info->max_index : ~0,
gen_prim, index_offset, count,
info->start_instance,
info->instance_count,
hwtnl->svga->patch_vertices);
pipe_resource_reference(&index_buffer, NULL);
}
else {
struct pipe_resource *gen_buf = NULL;
unsigned gen_offset = 0;
/* Need to allocate a new index buffer and run the translate
* func to populate it. Could potentially cache this translated
* index buffer with the original to avoid future
* re-translations. Not much point if we're just accelerating
* GL though, as index buffers are typically used only once
* there.
*/
ret = translate_indices(hwtnl, info, draw, gen_prim,
count, gen_nr, gen_size,
gen_func, &gen_buf, &gen_offset);
if (ret == PIPE_OK) {
gen_offset /= gen_size;
ret = svga_hwtnl_simple_draw_range_elements(hwtnl,
gen_buf,
gen_size,
draw->index_bias,
info->index_bounds_valid ? info->min_index : 0,
info->index_bounds_valid ? info->max_index : ~0,
gen_prim, gen_offset,
gen_nr,
info->start_instance,
info->instance_count,
hwtnl->svga->patch_vertices);
}
if (gen_buf) {
pipe_resource_reference(&gen_buf, NULL);
}
}
SVGA_STATS_TIME_POP(svga_sws(hwtnl->svga));
return ret;
}
|
61e694bfeaac3f026ffd26a8f3e63e629823d982
|
2d11442aa09b51e10c245ee2b64231aeb051744f
|
/platforms/Mac OS/plugins/QuicktimePlugin/sqMacQuicktimeInteface.c
|
2f4cca9ce17d57c298a565a87bd917a02737da2b
|
[
"MIT"
] |
permissive
|
OpenSmalltalk/opensmalltalk-vm
|
622b01c10017a93fdff4f1ef2188c45342384c78
|
330d6779ad2ecbce1f07131f53d75cd168165f0b
|
refs/heads/Cog
| 2023-09-04T05:36:54.320281
| 2023-08-17T11:32:52
| 2023-08-31T12:26:44
| 59,481,716
| 556
| 153
|
NOASSERTION
| 2023-06-19T19:58:13
| 2016-05-23T12:40:27
|
C
|
UTF-8
|
C
| false
| false
| 6,923
|
c
|
sqMacQuicktimeInteface.c
|
/*
* sqMacQuicktimeInteface.c
* SqueakQuicktime
*
* Created by John M McIntosh on 17/01/06.
* Copyright 2006 Corporate Smalltalk Consulting ltd. All rights reserved, published under the Squeak-L licence
*
*/
#include <Movies.h>
#include "sqMacQuicktimeInteface.h"
#include "SurfacePlugin.h"
#include "sqMemoryAccess.h"
#include "sqVirtualMachine.h"
typedef struct QuickTimeBitMapForSqueak {
int width, height, depth; /* width, height, and depth */
int rowBytes; /* how many bytes per scan line? */
MovieDrawingCompleteUPP myDrawCompleteProc;
Movie movie;
int semaIndex;
void *bits; /* where are those bits? */
} QuickTimeBitMapForSqueak;
static fn_ioRegisterSurface registerSurface = 0;
static fn_ioUnregisterSurface unregisterSurface = 0;
static fn_ioFindSurface findSurface = 0;
int QuicktimeGetSurfaceFormat(sqIntptr_t handle, int* width, int* height, int* depth, int* isMSB);
sqIntptr_t QuicktimeLockSurface(sqIntptr_t handle, int *pitch, int x, int y, int w, int h);
int QuicktimeUnlockSurface(sqIntptr_t handle, int x, int y, int w, int h);
int QuicktimeShowSurface(sqIntptr_t handle, int x, int y, int w, int h);
struct VirtualMachine *interpreterProxy;
static sqSurfaceDispatch QuicktimeTargetDispatch = {
1,
0,
(fn_getSurfaceFormat) QuicktimeGetSurfaceFormat,
(fn_lockSurface) QuicktimeLockSurface,
(fn_unlockSurface) QuicktimeUnlockSurface,
(fn_showSurface) QuicktimeShowSurface
};
static OSErr DrawCompleteProc(Movie theMovie, long refCon) {
interpreterProxy->signalSemaphoreWithIndex(refCon);
return noErr;
}
void SetupSurface() {
registerSurface = (fn_ioRegisterSurface) interpreterProxy->ioLoadFunctionFrom("ioRegisterSurface","SurfacePlugin");
unregisterSurface = (fn_ioUnregisterSurface) interpreterProxy->ioLoadFunctionFrom("ioUnregisterSurface","SurfacePlugin");
findSurface = (fn_ioFindSurface) interpreterProxy->ioLoadFunctionFrom("ioFindSurface","SurfacePlugin");
}
sqInt sqQuicktimeInitialize()
{
SetupSurface();
return true;
}
sqInt sqQuicktimeShutdown() {
return true;
}
int stQuicktimeSetSurfacewidthheightrowBytesdepthmovie(char * buffer, int width, int height, int rowBytes, int depth, void *movie)
{
QuickTimeBitMapForSqueak *bitMap;
int sqHandle;
bitMap = calloc(1, sizeof(QuickTimeBitMapForSqueak));
bitMap->width = width;
bitMap->height = height;
bitMap->depth = depth;
bitMap->rowBytes = rowBytes;
bitMap->bits = buffer;
bitMap->movie = movie;
(*registerSurface)((sqIntptr_t) bitMap, &QuicktimeTargetDispatch, &sqHandle);
return sqHandle;
}
int stQuicktimeSetToExistingSurfacegworldwidthheightrowBytesdepthmovie
(int sqHandle, char * buffer, int width, int height, int rowBytes, int depth, void *movie)
{
QuickTimeBitMapForSqueak *bitMap;
/* see if the handle really describes a MyBitmap surface */
if( ! (*findSurface)(sqHandle, &QuicktimeTargetDispatch, (sqIntptr_t*) (&bitMap)) ) {
/* i don't know what it is but certainly not MyBitmap */
return interpreterProxy->primitiveFail();
}
bitMap->width = width;
bitMap->height = height;
bitMap->depth = depth;
bitMap->rowBytes = rowBytes;
bitMap->bits = buffer;
bitMap->movie = movie;
(*registerSurface)((sqIntptr_t) bitMap, &QuicktimeTargetDispatch, &sqHandle);
return sqHandle;
}
int stQuicktimeDestroySurface(int sqHandle) {
QuickTimeBitMapForSqueak *myBM;
/* see if the handle really describes a MyBitmap surface */
if( ! (*findSurface)(sqHandle, &QuicktimeTargetDispatch, (sqIntptr_t*) (&myBM)) ) {
/* i don't know what it is but certainly not MyBitmap */
return interpreterProxy->primitiveFail();
}
/* unregister and destroy */
(*unregisterSurface)(sqHandle);
free(myBM);
}
int stQuicktimeDestroy(int sqHandle) {
QuickTimeBitMapForSqueak *myBM;
/* see if the handle really describes a MyBitmap surface */
if( ! (*findSurface)(sqHandle, &QuicktimeTargetDispatch, (sqIntptr_t*) (&myBM)) ) {
/* i don't know what it is but certainly not MyBitmap */
return interpreterProxy->primitiveFail();
}
/* unregister and destroy */
(*unregisterSurface)(sqHandle);
if (myBM->semaIndex && !((myBM->movie == nil) || (*myBM->movie == 0xFFFFFFFFU))) {
DisposeMovieDrawingCompleteUPP(myBM->myDrawCompleteProc);
SetMovieDrawingCompleteProc (myBM->movie,0,0,0);
}
myBM->semaIndex = 0;
free(myBM);
return 1;
}
int stQuicktimeSetSemaphorefor(int index, int sqHandle) {
// interpreterProxy->signalSemaphoreWithIndex(state->semaIndex);
QuickTimeBitMapForSqueak *myBM;
if( ! (*findSurface)(sqHandle, &QuicktimeTargetDispatch, (sqIntptr_t*) (&myBM)) ) {
/* i don't know what it is but certainly not MyBitmap */
return interpreterProxy->primitiveFail();
}
if ((myBM->movie == nil) || (*myBM->movie == 0xFFFFFFFFU))
return interpreterProxy->primitiveFail();
myBM->myDrawCompleteProc = NewMovieDrawingCompleteUPP(DrawCompleteProc);
SetMovieDrawingCompleteProc (myBM->movie,movieDrawingCallWhenChanged,myBM->myDrawCompleteProc,(long) index);
myBM->semaIndex = index;
return 0;
}
int stQuicktimeClearSemaphore(int sqHandle) {
QuickTimeBitMapForSqueak *myBM;
if( ! (*findSurface)(sqHandle, &QuicktimeTargetDispatch, (sqIntptr_t*) (&myBM)) ) {
/* i don't know what it is but certainly not MyBitmap */
return interpreterProxy->primitiveFail();
}
if ((myBM->movie == nil) || (*myBM->movie == 0xFFFFFFFFU))
return interpreterProxy->primitiveFail();
if (myBM->semaIndex) {
SetMovieDrawingCompleteProc (myBM->movie,0,0,0);
}
myBM->semaIndex = 0;
return 1;
}
int QuicktimeGetSurfaceFormat(sqIntptr_t handle, int *width, int *height, int *depth, int *isMSB) {
/* fill in status information */
QuickTimeBitMapForSqueak *myBM=(QuickTimeBitMapForSqueak) handle;
*width = myBM->width;
*height = myBM->height;
*depth = myBM->depth;
*isMSB = 1; /* or zero depending on platform or choice */
#warning Endeness
return 1; /* success - otherwise return zero */
}
sqIntptr_t QuicktimeLockSurface(sqIntptr_t handle, int *pitch, int x, int y, int w, int h)
{
/* lock the region x,y - (x+w),(y+h)
the area actually used is provided so that expensive
operations (like a round trip to the X-Server) can
be avoided. See SurfacePlugin.h */
/* for our simple example, only fill in the pitch. No locking is
required. */
QuickTimeBitMapForSqueak *myBM=(QuickTimeBitMapForSqueak) handle;
*pitch = myBM->rowBytes;
return (sqIntptr_t) myBM->bits; /* success */
}
int QuicktimeUnlockSurface(sqIntptr_t handle, int x, int y, int w, int h) {
/* Unlock a previously locked portion of myBM.
The area describes the 'dirty region' which might
need to be written back/flushed whatever. */
/* for the simple example do nothing */
return 1;
}
int QuicktimeShowSurface(sqIntptr_t handle, int x, int y, int w, int h) {
/* the surface represents Display - update the portion
described in x,y,w,h */
/* for our simple example we just ignore this */
return 0; /* e.g., fail */
}
|
9e4085af2d7fecdd80bc6fa61bed954aaac283ee
|
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
|
/sysutils/torque/files/patch-src-server-req_getcred.c
|
f9c9072b5cf1274c3e6d68a4b632990ba4de54e3
|
[
"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
| 306
|
c
|
patch-src-server-req_getcred.c
|
--- src/server/req_getcred.c.orig 2012-07-15 11:42:07.000000000 -0500
+++ src/server/req_getcred.c 2012-07-15 11:48:39.000000000 -0500
@@ -97,6 +97,7 @@
#include <ctype.h>
#include <netdb.h>
#include <signal.h>
+#include <netinet/in.h>
#include "libpbs.h"
#include "log.h"
#include "server_limits.h"
|
f788089e4558dac78213b98708665e293fea3f95
|
72bdf3d5a4f063734d2fa78ef0121abb1687e17a
|
/reg-lib/cpu/_reg_localTrans_regul.h
|
26e0e8f9c2136c185ab831b708ba86a85aa9000e
|
[] |
permissive
|
KCL-BMEIS/niftyreg
|
95bf0e25d5b12c29cb41f2c1943d6ae5e4a18ada
|
6db8b16c17884a9b8859c980c4f1c408f62bd9ca
|
refs/heads/master
| 2023-08-31T16:20:25.493600
| 2022-11-18T07:48:12
| 2022-11-18T07:48:12
| 134,296,286
| 103
| 41
|
BSD-3-Clause
| 2022-07-28T14:24:51
| 2018-05-21T16:34:44
|
C
|
UTF-8
|
C
| false
| false
| 7,770
|
h
|
_reg_localTrans_regul.h
|
/**
* @file _reg_localTrans_regul.h
* @brief Library that contains local deformation related functions
* @author Marc Modat
* @date 22/12/2015
*
* Copyright (c) 2015-2018, University College London
* Copyright (c) 2018, NiftyReg Developers.
* All rights reserved.
* See the LICENSE.txt file in the nifty_reg root folder
*
*/
#ifndef _REG_TRANS_REG_H
#define _REG_TRANS_REG_H
#include "_reg_splineBasis.h"
/* *************************************************************** */
/** @brief Compute and return the average bending energy computed using cubic b-spline.
* The value is approximated as the bending energy is computed at
* the control point position only.
* @param controlPointGridImage Control point grid that contains the deformation
* parametrisation
* @return The normalised bending energy. Normalised by the number of voxel
*/
extern "C++"
double reg_spline_approxBendingEnergy(nifti_image *controlPointGridImage);
/* *************************************************************** */
/** @brief Compute and return the approximated (at the control point position)
* bending energy gradient for each control point
* @param controlPointGridImage Image that contains the control point
* grid used to parametrise the transformation
* @param gradientImage Image of identical size that the control
* point grid image. The gradient of the bending-energy will be added
* at every control point position.
* @param weight Scalar which will be multiplied by the bending-energy gradient
*/
extern "C++"
void reg_spline_approxBendingEnergyGradient(nifti_image *controlPointGridImage,
nifti_image *gradientImage,
float weight
);
/* *************************************************************** */
/** @brief Compute and return the linear elastic energy terms.
* @param controlPointGridImage Image that contains the transformation
* parametrisation
* @return The normalised linear energy. Normalised by the number of voxel
*/
extern "C++"
double reg_spline_linearEnergy(nifti_image *referenceImage,
nifti_image *controlPointGridImage);
/* *************************************************************** */
/** @brief Compute and return the linear elastic energy terms approximated
* at the control point positions only.
* @param controlPointGridImage Image that contains the transformation
* parametrisation
* @return The normalised linear energy. Normalised by the number of voxel
*/
extern "C++"
double reg_spline_approxLinearEnergy(nifti_image *controlPointGridImage);
/* *************************************************************** */
/** @brief Compute the gradient of the linear elastic energy terms
* computed at all voxel position.
* @param referenceImage Image that contains the dense space
* @param controlPointGridImage Image that contains the transformation
* parametrisation
* @param gradientImage Image of similar size than the control point
* grid and that contains the gradient of the objective function.
* The gradient of the linear elasticily terms are added to the
* current values
* @param weight Weight to apply to the term of the penalty
*/
extern "C++"
void reg_spline_linearEnergyGradient(nifti_image *referenceImage,
nifti_image *controlPointGridImage,
nifti_image *gradientImage,
float weight
);
/* *************************************************************** */
/** @brief Compute the gradient of the linear elastic energy terms
* approximated at the control point positions only.
* @param controlPointGridImage Image that contains the transformation
* parametrisation
* @param gradientImage Image of similar size than the control point
* grid and that contains the gradient of the objective function.
* The gradient of the linear elasticily terms are added to the
* current values
* @param weight Weight to apply to the term of the penalty
*/
extern "C++"
void reg_spline_approxLinearEnergyGradient(nifti_image *controlPointGridImage,
nifti_image *gradientImage,
float weight
);
/* *************************************************************** */
/** @brief Compute and return the linear elastic energy terms.
* @param deformationField Image that contains the transformation.
* @return The normalised linear energy. Normalised by the number of voxel
*/
extern "C++"
double reg_defField_linearEnergy(nifti_image *deformationField);
/* *************************************************************** */
/** @brief Compute and return the linear elastic energy terms.
* @param deformationField Image that contains the transformation.
* @param weight Weight to apply to the term of the penalty
*/
extern "C++"
void reg_defField_linearEnergyGradient(nifti_image *deformationField,
nifti_image *gradientImage,
float weight);
/* *************************************************************** */
/** @Brief Compute the distance between two set of points given a
* transformation
* @param controlPointGridImage Image that contains the transformation
* parametrisation
* @param landmarkNumber Number of landmark defined in each image
* @param landmarkReference Landmark in the reference image
* @param landmarkFloating Landmark in the floating image
*/
extern "C++"
double reg_spline_getLandmarkDistance(nifti_image *controlPointImage,
size_t landmarkNumber,
float *landmarkReference,
float *landmarkFloating);
/* *************************************************************** */
/** @Brief Compute the gradient of the distance between two set of
* points given a transformation
* @param controlPointGridImage Image that contains the transformation
* parametrisation
* @param gradientImage Image that contains the gradient in the space
* of the transformation parametrisation
* @param landmarkNumber Number of landmark defined in each image
* @param landmarkReference Landmark in the reference image
* @param landmarkFloating Landmark in the floating image
* @param weight weight to apply to the gradient
*/
extern "C++"
void reg_spline_getLandmarkDistanceGradient(nifti_image *controlPointImage,
nifti_image *gradientImage,
size_t landmarkNumber,
float *landmarkReference,
float *landmarkFloating,
float weight);
/* *************************************************************** */
/** @brief Compute and return a pairwise energy.
* @param controlPointGridImage Image that contains the transformation
* parametrisation
* @return The normalised pariwise energy. Normalised by the number of voxel
*/
extern "C++"
void reg_spline_approxLinearPairwiseGradient(nifti_image *controlPointGridImage,
nifti_image *gradientImage,
float weight
);
/* *************************************************************** */
extern "C++"
double reg_spline_approxLinearPairwise(nifti_image *controlPointGridImage);
/* *************************************************************** */
#endif
|
e0b126a927571c39a8a4985c6eb9ae4c0c600cf0
|
e51d227e06363817463efa2650e97d07290aed34
|
/src/Cedar/IPsec_IKE.c
|
f5b7943e0ce2917414f65e6bc0bc38d31137b937
|
[
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] |
permissive
|
SoftEtherVPN/SoftEtherVPN_Stable
|
21426b5fdcf3b518be5d9174441192450e54e836
|
89939eb52f1f40e4f75c76e8d5eca019de103532
|
refs/heads/master
| 2023-08-08T09:51:40.139112
| 2023-06-30T03:19:06
| 2023-06-30T03:19:06
| 107,487,278
| 1,710
| 553
|
Apache-2.0
| 2023-06-24T02:56:31
| 2017-10-19T02:19:51
|
C
|
UTF-8
|
C
| false
| false
| 167,518
|
c
|
IPsec_IKE.c
|
// SoftEther VPN Source Code - Stable Edition Repository
// Cedar Communication Module
//
// SoftEther VPN Server, Client and Bridge are free software under the Apache License, Version 2.0.
//
// Copyright (c) Daiyuu Nobori.
// Copyright (c) SoftEther VPN Project, University of Tsukuba, Japan.
// Copyright (c) SoftEther Corporation.
// Copyright (c) all contributors on SoftEther VPN project in GitHub.
//
// All Rights Reserved.
//
// http://www.softether.org/
//
// This stable branch is officially managed by Daiyuu Nobori, the owner of SoftEther VPN Project.
// Pull requests should be sent to the Developer Edition Master Repository on https://github.com/SoftEtherVPN/SoftEtherVPN
//
// License: The Apache License, Version 2.0
// https://www.apache.org/licenses/LICENSE-2.0
//
// DISCLAIMER
// ==========
//
// 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.
//
// THIS SOFTWARE IS DEVELOPED IN JAPAN, AND DISTRIBUTED FROM JAPAN, UNDER
// JAPANESE LAWS. YOU MUST AGREE IN ADVANCE TO USE, COPY, MODIFY, MERGE, PUBLISH,
// DISTRIBUTE, SUBLICENSE, AND/OR SELL COPIES OF THIS SOFTWARE, THAT ANY
// JURIDICAL DISPUTES WHICH ARE CONCERNED TO THIS SOFTWARE OR ITS CONTENTS,
// AGAINST US (SOFTETHER PROJECT, SOFTETHER CORPORATION, DAIYUU NOBORI OR OTHER
// SUPPLIERS), OR ANY JURIDICAL DISPUTES AGAINST US WHICH ARE CAUSED BY ANY KIND
// OF USING, COPYING, MODIFYING, MERGING, PUBLISHING, DISTRIBUTING, SUBLICENSING,
// AND/OR SELLING COPIES OF THIS SOFTWARE SHALL BE REGARDED AS BE CONSTRUED AND
// CONTROLLED BY JAPANESE LAWS, AND YOU MUST FURTHER CONSENT TO EXCLUSIVE
// JURISDICTION AND VENUE IN THE COURTS SITTING IN TOKYO, JAPAN. YOU MUST WAIVE
// ALL DEFENSES OF LACK OF PERSONAL JURISDICTION AND FORUM NON CONVENIENS.
// PROCESS MAY BE SERVED ON EITHER PARTY IN THE MANNER AUTHORIZED BY APPLICABLE
// LAW OR COURT RULE.
//
// USE ONLY IN JAPAN. DO NOT USE THIS SOFTWARE IN ANOTHER COUNTRY UNLESS YOU HAVE
// A CONFIRMATION THAT THIS SOFTWARE DOES NOT VIOLATE ANY CRIMINAL LAWS OR CIVIL
// RIGHTS IN THAT PARTICULAR COUNTRY. USING THIS SOFTWARE IN OTHER COUNTRIES IS
// COMPLETELY AT YOUR OWN RISK. THE SOFTETHER VPN PROJECT HAS DEVELOPED AND
// DISTRIBUTED THIS SOFTWARE TO COMPLY ONLY WITH THE JAPANESE LAWS AND EXISTING
// CIVIL RIGHTS INCLUDING PATENTS WHICH ARE SUBJECTS APPLY IN JAPAN. OTHER
// COUNTRIES' LAWS OR CIVIL RIGHTS ARE NONE OF OUR CONCERNS NOR RESPONSIBILITIES.
// WE HAVE NEVER INVESTIGATED ANY CRIMINAL REGULATIONS, CIVIL LAWS OR
// INTELLECTUAL PROPERTY RIGHTS INCLUDING PATENTS IN ANY OF OTHER 200+ COUNTRIES
// AND TERRITORIES. BY NATURE, THERE ARE 200+ REGIONS IN THE WORLD, WITH
// DIFFERENT LAWS. IT IS IMPOSSIBLE TO VERIFY EVERY COUNTRIES' LAWS, REGULATIONS
// AND CIVIL RIGHTS TO MAKE THE SOFTWARE COMPLY WITH ALL COUNTRIES' LAWS BY THE
// PROJECT. EVEN IF YOU WILL BE SUED BY A PRIVATE ENTITY OR BE DAMAGED BY A
// PUBLIC SERVANT IN YOUR COUNTRY, THE DEVELOPERS OF THIS SOFTWARE WILL NEVER BE
// LIABLE TO RECOVER OR COMPENSATE SUCH DAMAGES, CRIMINAL OR CIVIL
// RESPONSIBILITIES. NOTE THAT THIS LINE IS NOT LICENSE RESTRICTION BUT JUST A
// STATEMENT FOR WARNING AND DISCLAIMER.
//
// READ AND UNDERSTAND THE 'WARNING.TXT' FILE BEFORE USING THIS SOFTWARE.
// SOME SOFTWARE PROGRAMS FROM THIRD PARTIES ARE INCLUDED ON THIS SOFTWARE WITH
// LICENSE CONDITIONS WHICH ARE DESCRIBED ON THE 'THIRD_PARTY.TXT' FILE.
//
//
// SOURCE CODE CONTRIBUTION
// ------------------------
//
// Your contribution to SoftEther VPN Project is much appreciated.
// Please send patches to us through GitHub.
// Read the SoftEther VPN Patch Acceptance Policy in advance:
// http://www.softether.org/5-download/src/9.patch
//
//
// DEAR SECURITY EXPERTS
// ---------------------
//
// If you find a bug or a security vulnerability please kindly inform us
// about the problem immediately so that we can fix the security problem
// to protect a lot of users around the world as soon as possible.
//
// Our e-mail address for security reports is:
// softether-vpn-security [at] softether.org
//
// Please note that the above e-mail address is not a technical support
// inquiry address. If you need technical assistance, please visit
// http://www.softether.org/ and ask your question on the users forum.
//
// Thank you for your cooperation.
//
//
// NO MEMORY OR RESOURCE LEAKS
// ---------------------------
//
// The memory-leaks and resource-leaks verification under the stress
// test has been passed before release this source code.
// IPsec_IKE.c
// IKE (ISAKMP) and ESP protocol stack
#include "CedarPch.h"
//#define RAW_DEBUG
// Processing of IKE received packet
void ProcIKEPacketRecv(IKE_SERVER *ike, UDPPACKET *p)
{
// Validate arguments
if (ike == NULL || p == NULL)
{
return;
}
if (p->Type == IKE_UDP_TYPE_ISAKMP)
{
// ISAKMP (IKE) packet
IKE_PACKET *header;
header = ParseIKEPacketHeader(p);
if (header == NULL)
{
return;
}
//Debug("InitiatorCookie: %I64u, ResponderCookie: %I64u\n", header->InitiatorCookie, header->ResponderCookie);
switch (header->ExchangeType)
{
case IKE_EXCHANGE_TYPE_MAIN: // Main mode
ProcIkeMainModePacketRecv(ike, p, header);
break;
case IKE_EXCHANGE_TYPE_AGGRESSIVE: // Aggressive mode
if (ike->Cedar->Server->DisableIPsecAggressiveMode == false)
{
ProcIkeAggressiveModePacketRecv(ike, p, header);
}
break;
case IKE_EXCHANGE_TYPE_QUICK: // Quick mode
ProcIkeQuickModePacketRecv(ike, p, header);
break;
case IKE_EXCHANGE_TYPE_INFORMATION: // Information exchange
ProcIkeInformationalExchangePacketRecv(ike, p, header);
break;
}
IkeFree(header);
}
else if (p->Type == IKE_UDP_TYPE_ESP)
{
// ESP packet
ProcIPsecEspPacketRecv(ike, p);
}
}
IKE_INFOMSG_QUOTA_ENTRY *IkeInfoMsgQuotaGetEntry(IKE_SERVER *ike, IP *client_ip)
{
UINT i;
IKE_INFOMSG_QUOTA_ENTRY *new_entry = NULL;
if (ike == NULL || client_ip == NULL)
{
return NULL;
}
for (i = 0;i < LIST_NUM(ike->InfoMsgQuotaList);i++)
{
IKE_INFOMSG_QUOTA_ENTRY *q = LIST_DATA(ike->InfoMsgQuotaList, i);
if (CmpIpAddr(&q->ClientIp, client_ip) == 0)
{
return q;
}
}
if (LIST_NUM(ike->InfoMsgQuotaList) >= IKE_QUOTA_MAX_INFOMSG_ENTRY_COUNT)
{
return NULL;
}
new_entry = ZeroMalloc(sizeof(IKE_INFOMSG_QUOTA_ENTRY));
CopyIP(&new_entry->ClientIp, client_ip);
Add(ike->InfoMsgQuotaList, new_entry);
return new_entry;
}
void IkeInfoMsgQuotaDeleteAll(IKE_SERVER *ike)
{
UINT i;
if (ike == NULL)
{
return;
}
for (i = 0;i < LIST_NUM(ike->InfoMsgQuotaList);i++)
{
IKE_INFOMSG_QUOTA_ENTRY *q = LIST_DATA(ike->InfoMsgQuotaList, i);
Free(q);
}
DeleteAll(ike->InfoMsgQuotaList);
}
// Send a packet via IPsec
void IPsecSendPacketByIPsecSa(IKE_SERVER *ike, IPSECSA *sa, UCHAR *data, UINT data_size, UCHAR protocol_id)
{
bool is_tunnel_mode;
IKE_CLIENT *c;
// Validate arguments
if (ike == NULL || sa == NULL || data == NULL || data_size == 0)
{
return;
}
is_tunnel_mode = IsIPsecSaTunnelMode(sa);
c = sa->IkeClient;
if (c == NULL)
{
return;
}
if (is_tunnel_mode)
{
// Add an IPv4 / IPv6 header in the case of tunnel mode
if (IsZeroIP(&c->TunnelModeClientIP) == false || IsZeroIP(&c->TunnelModeServerIP) == false)
{
BUF *b;
UCHAR esp_proto_id;
b = NewBuf();
if (IsIP4(&c->TunnelModeClientIP))
{
// IPv4 header
IPV4_HEADER h;
h.VersionAndHeaderLength = 0;
h.TypeOfService = 0;
IPV4_SET_VERSION(&h, 4);
IPV4_SET_HEADER_LEN(&h, sizeof(IPV4_HEADER) / 4);
h.TotalLength = Endian16((USHORT)(data_size + sizeof(IPV4_HEADER)));
h.Identification = Endian16(c->TunnelSendIpId++);
h.FlagsAndFlagmentOffset[0] = h.FlagsAndFlagmentOffset[1] = 0;
h.TimeToLive = DEFAULT_IP_TTL;
h.Protocol = protocol_id;
h.SrcIP = IPToUINT(&c->TunnelModeServerIP);
h.DstIP = IPToUINT(&c->TunnelModeClientIP);
h.Checksum = 0;
h.Checksum = IpChecksum(&h, sizeof(IPV4_HEADER));
WriteBuf(b, &h, sizeof(IPV4_HEADER));
esp_proto_id = IKE_PROTOCOL_ID_IPV4;
}
else
{
// IPv6 header
IPV6_HEADER h;
Zero(&h, sizeof(h));
h.VersionAndTrafficClass1 = 0;
IPV6_SET_VERSION(&h, 6);
h.TrafficClass2AndFlowLabel1 = 0;
h.FlowLabel2 = h.FlowLabel3 = 0;
h.PayloadLength = Endian16(data_size);
h.NextHeader = protocol_id;
h.HopLimit = 64;
Copy(h.SrcAddress.Value, c->TunnelModeServerIP.ipv6_addr, 16);
Copy(h.DestAddress.Value, c->TunnelModeClientIP.ipv6_addr, 16);
WriteBuf(b, &h, sizeof(IPV6_HEADER));
esp_proto_id = IKE_PROTOCOL_ID_IPV6;
}
WriteBuf(b, data, data_size);
IPsecSendPacketByIPsecSaInner(ike, sa, b->Buf, b->Size, esp_proto_id);
FreeBuf(b);
}
}
else
{
// Send as it is in the case of transport mode
IPsecSendPacketByIPsecSaInner(ike, sa, data, data_size, protocol_id);
}
}
void IPsecSendPacketByIPsecSaInner(IKE_SERVER *ike, IPSECSA *sa, UCHAR *data, UINT data_size, UCHAR protocol_id)
{
UINT esp_size;
UINT encrypted_payload_size;
UCHAR *esp;
UINT i;
UINT size_of_padding;
IKE_CRYPTO_PARAM cp;
BUF *enc;
IKE_CLIENT *c;
// Validate arguments
if (ike == NULL || sa == NULL || data == NULL || data_size == 0)
{
return;
}
c = sa->IkeClient;
if (c == NULL)
{
return;
}
// Calculate the payload size after encryption
encrypted_payload_size = data_size + 2;
if ((encrypted_payload_size % sa->TransformSetting.Crypto->BlockSize) != 0)
{
encrypted_payload_size = ((encrypted_payload_size / sa->TransformSetting.Crypto->BlockSize) + 1) * sa->TransformSetting.Crypto->BlockSize;
}
size_of_padding = encrypted_payload_size - data_size - 2;
// Calculate the size of the ESP packet
esp_size = sizeof(UINT) * 2 + sa->TransformSetting.Crypto->BlockSize + encrypted_payload_size + IKE_ESP_HASH_SIZE;
// Build the ESP packet
esp = Malloc(esp_size + IKE_MAX_HASH_SIZE);
// SPI
WRITE_UINT(esp, sa->Spi);
// Sequence number
sa->CurrentSeqNo++;
WRITE_UINT(esp + sizeof(UINT), sa->CurrentSeqNo);
// IV
Copy(esp + sizeof(UINT) * 2, sa->EspIv, sa->TransformSetting.Crypto->BlockSize);
// Payload data
Copy(esp + sizeof(UINT) * 2 + sa->TransformSetting.Crypto->BlockSize, data, data_size);
// Padding
for (i = 0;i < size_of_padding;i++)
{
esp[sizeof(UINT) * 2 + sa->TransformSetting.Crypto->BlockSize + data_size + i] = (UCHAR)(i + 1);
}
// Padding length
esp[sizeof(UINT) * 2 + sa->TransformSetting.Crypto->BlockSize + data_size + size_of_padding] = (UCHAR)size_of_padding;
// Next header number
esp[sizeof(UINT) * 2 + sa->TransformSetting.Crypto->BlockSize + data_size + size_of_padding + 1] = protocol_id;
// Encryption
Copy(cp.Iv, sa->EspIv, sa->TransformSetting.Crypto->BlockSize);
cp.Key = sa->CryptoKey;
enc = IkeEncrypt(esp + sizeof(UINT) * 2 + sa->TransformSetting.Crypto->BlockSize, encrypted_payload_size, &cp);
if (enc != NULL)
{
bool start_qm = false;
UINT server_port = c->ServerPort;
UINT client_port = c->ClientPort;
// Overwrite the encrypted result
Copy(esp + sizeof(UINT) * 2 + sa->TransformSetting.Crypto->BlockSize, enc->Buf, encrypted_payload_size);
FreeBuf(enc);
// Calculate the HMAC
IkeHMac(sa->TransformSetting.Hash,
esp + sizeof(UINT) * 2 + sa->TransformSetting.Crypto->BlockSize + encrypted_payload_size,
sa->HashKey,
sa->TransformSetting.Hash->HashSize,
esp,
sizeof(UINT) * 2 + sa->TransformSetting.Crypto->BlockSize + encrypted_payload_size);
//*(UCHAR *)(esp + sizeof(UINT) * 2 + sa->TransformSetting.Crypto->BlockSize + encrypted_payload_size) = 0xff;
if (sa->TransformSetting.CapsuleMode == IKE_P2_CAPSULE_TRANSPORT ||
sa->TransformSetting.CapsuleMode == IKE_P2_CAPSULE_TUNNEL)
{
server_port = client_port = IPSEC_PORT_IPSEC_ESP_RAW;
}
// Add the completed packet to the transmission list
IkeSendUdpPacket(ike, IKE_UDP_TYPE_ESP, &c->ServerIP, server_port, &c->ClientIP, client_port,
esp, esp_size);
// Feedback the IV
Copy(sa->EspIv, cp.NextIv, sa->TransformSetting.Crypto->BlockSize);
sa->TotalSize += esp_size;
if (sa->CurrentSeqNo >= 0xf0000000)
{
start_qm = true;
}
if (sa->TransformSetting.LifeKilobytes != 0)
{
UINT64 hard_size = (UINT64)sa->TransformSetting.LifeKilobytes * (UINT64)1000;
UINT64 soft_size = hard_size * (UINT64)2 / (UINT64)3;
if (sa->TotalSize >= soft_size)
{
start_qm = true;
}
}
if (start_qm)
{
if (sa->StartQM_FlagSet == false)
{
sa->StartQM_FlagSet = true;
c->StartQuickModeAsSoon = true;
}
}
}
else
{
// Encryption failure
Free(esp);
}
}
void IPsecSendPacketByIkeClient(IKE_SERVER *ike, IKE_CLIENT *c, UCHAR *data, UINT data_size, UCHAR protocol_id)
{
// Validate arguments
if (ike == NULL || c == NULL || data == NULL || data_size == 0)
{
return;
}
if (c->CurrentIpSecSaSend == NULL)
{
return;
}
IPsecSendPacketByIPsecSa(ike, c->CurrentIpSecSaSend, data, data_size, protocol_id);
}
// Send an UDP packet via IPsec
void IPsecSendUdpPacket(IKE_SERVER *ike, IKE_CLIENT *c, UINT src_port, UINT dst_port, UCHAR *data, UINT data_size)
{
UCHAR *udp;
UINT udp_size;
UDP_HEADER *u;
UCHAR tmp1600[1600];
bool no_free = false;
// Validate arguments
if (ike == NULL || c == NULL || data == NULL || data_size == 0)
{
return;
}
// Build an UDP packet
udp_size = sizeof(UDP_HEADER) + data_size;
if (udp_size > sizeof(tmp1600))
{
udp = Malloc(udp_size);
}
else
{
udp = tmp1600;
no_free = true;
}
// UDP header
u = (UDP_HEADER *)udp;
u->SrcPort = Endian16(src_port);
u->DstPort = Endian16(dst_port);
u->PacketLength = Endian16(udp_size);
u->Checksum = 0;
//Debug("IPsec UDP Send: %u -> %u %u\n", src_port, dst_port, data_size);
#ifdef RAW_DEBUG
IPsecIkeSendUdpForDebug(IPSEC_PORT_L2TP, 1, data, data_size);
#endif // RAW_DEBUG
// Payload
Copy(udp + sizeof(UDP_HEADER), data, data_size);
if (IsIP6(&c->ClientIP))
{
if (IsIPsecSaTunnelMode(c->CurrentIpSecSaSend) == false)
{
u->Checksum = CalcChecksumForIPv6((IPV6_ADDR *)c->TransportModeServerIP.ipv6_addr,
(IPV6_ADDR *)c->TransportModeClientIP.ipv6_addr,
IP_PROTO_UDP,
u,
udp_size, 0);
}
else
{
u->Checksum = CalcChecksumForIPv6((IPV6_ADDR *)c->TunnelModeServerIP.ipv6_addr,
(IPV6_ADDR *)c->TunnelModeClientIP.ipv6_addr,
IP_PROTO_UDP,
u,
udp_size, 0);
}
}
IPsecSendPacketByIkeClient(ike, c, udp, udp_size, IP_PROTO_UDP);
if (no_free == false)
{
Free(udp);
}
}
// Get whether the specified IPsec SA is in tunnel mode
bool IsIPsecSaTunnelMode(IPSECSA *sa)
{
// Validate arguments
if (sa == NULL)
{
return false;
}
if (sa->TransformSetting.CapsuleMode == IKE_P2_CAPSULE_TUNNEL ||
sa->TransformSetting.CapsuleMode == IKE_P2_CAPSULE_NAT_TUNNEL_1 ||
sa->TransformSetting.CapsuleMode == IKE_P2_CAPSULE_NAT_TUNNEL_2)
{
return true;
}
return false;
}
// Reception process of ESP packet
void ProcIPsecEspPacketRecv(IKE_SERVER *ike, UDPPACKET *p)
{
UCHAR *src;
UINT src_size;
UINT spi;
UINT seq;
IPSECSA *ipsec_sa;
IKE_CLIENT *c;
UINT block_size;
UINT hash_size;
bool update_status = false;
UCHAR *iv;
UCHAR *hash;
UCHAR *encrypted_payload_data;
UINT size_of_payload_data;
IKE_CRYPTO_PARAM cp;
BUF *dec;
UCHAR calced_hash[IKE_MAX_HASH_SIZE];
bool is_tunnel_mode = false;
// Validate arguments
if (ike == NULL || p == NULL)
{
return;
}
src = (UCHAR *)p->Data;
src_size = p->Size;
if (p->DestPort == IPSEC_PORT_IPSEC_ESP_RAW)
{
if (IsIP4(&p->DstIP))
{
// Skip the IP header when received in Raw mode (only in the case of IPv4)
UINT ip_header_size = GetIpHeaderSize(src, src_size);
src += ip_header_size;
src_size -= ip_header_size;
}
}
// Get the SPI
if (src_size < sizeof(UINT))
{
return;
}
spi = READ_UINT(src + 0);
if (spi == 0)
{
return;
}
// Get the sequence number
if (src_size < (sizeof(UINT) * 2))
{
return;
}
seq = READ_UINT(src + sizeof(UINT));
// Search and retrieve the IPsec SA from SPI
ipsec_sa = SearchClientToServerIPsecSaBySpi(ike, spi);
if (ipsec_sa == NULL)
{
// Invalid SPI
UINT64 init_cookie = Rand64();
UINT64 resp_cookie = 0;
IKE_CLIENT *c = NULL;
IKE_CLIENT t;
Copy(&t.ClientIP, &p->SrcIP, sizeof(IP));
t.ClientPort = p->SrcPort;
Copy(&t.ServerIP, &p->DstIP, sizeof(IP));
t.ServerPort = p->DestPort;
t.CurrentIkeSa = NULL;
if (p->DestPort == IPSEC_PORT_IPSEC_ESP_RAW)
{
t.ClientPort = t.ServerPort = IPSEC_PORT_IPSEC_ISAKMP;
}
c = Search(ike->ClientList, &t);
if (c != NULL && c->CurrentIkeSa != NULL)
{
init_cookie = c->CurrentIkeSa->InitiatorCookie;
resp_cookie = c->CurrentIkeSa->ResponderCookie;
}
SendInformationalExchangePacketEx(ike, (c == NULL ? &t : c), IkeNewNoticeErrorInvalidSpiPayload(spi), false,
init_cookie, resp_cookie);
SendDeleteIPsecSaPacket(ike, (c == NULL ? &t : c), spi);
return;
}
is_tunnel_mode = IsIPsecSaTunnelMode(ipsec_sa);
c = ipsec_sa->IkeClient;
if (c == NULL)
{
return;
}
block_size = ipsec_sa->TransformSetting.Crypto->BlockSize;
hash_size = IKE_ESP_HASH_SIZE;
// Get the IV
if (src_size < (sizeof(UINT) * 2 + block_size + hash_size + block_size))
{
return;
}
iv = src + sizeof(UINT) * 2;
// Get the hash
hash = src + src_size - hash_size;
// Inspect the HMAC
IkeHMac(ipsec_sa->TransformSetting.Hash, calced_hash, ipsec_sa->HashKey,
ipsec_sa->TransformSetting.Hash->HashSize, src, src_size - hash_size);
if (Cmp(calced_hash, hash, hash_size) != 0)
{
//Debug("IPsec SA 0x%X: Invalid HMAC Value.\n", ipsec_sa->Spi);
return;
}
// Get the payload data
encrypted_payload_data = src + sizeof(UINT) * 2 + block_size;
size_of_payload_data = src_size - hash_size - block_size - sizeof(UINT) * 2;
if (size_of_payload_data == 0 || (size_of_payload_data % block_size) != 0)
{
// Payload data don't exist or is not a multiple of block size
return;
}
// Decrypt the payload data
cp.Key = ipsec_sa->CryptoKey;
Copy(&cp.Iv, iv, block_size);
dec = IkeDecrypt(encrypted_payload_data, size_of_payload_data, &cp);
if (dec != NULL)
{
UCHAR *dec_data = dec->Buf;
UINT dec_size = dec->Size;
UCHAR size_of_padding = dec_data[dec_size - 2];
UCHAR next_header = dec_data[dec_size - 1];
if ((dec_size - 2) >= size_of_padding)
{
UINT orig_size = dec_size - 2 - size_of_padding;
ipsec_sa->TotalSize += dec_size;
if (is_tunnel_mode)
{
// Tunnel Mode
if (next_header == IKE_PROTOCOL_ID_IPV4 || next_header == IKE_PROTOCOL_ID_IPV6)
{
// Check the contents by parsing the IPv4 / IPv6 header in the case of tunnel mode
BUF *b = NewBuf();
static UCHAR src_mac_dummy[6] = {0, 0, 0, 0, 0, 0, };
static UCHAR dst_mac_dummy[6] = {0, 0, 0, 0, 0, 0, };
USHORT tpid = Endian16(next_header == IKE_PROTOCOL_ID_IPV4 ? MAC_PROTO_IPV4 : MAC_PROTO_IPV6);
PKT *pkt;
WriteBuf(b, src_mac_dummy, sizeof(src_mac_dummy));
WriteBuf(b, dst_mac_dummy, sizeof(dst_mac_dummy));
WriteBuf(b, &tpid, sizeof(tpid));
WriteBuf(b, dec_data, dec_size);
// Parse
pkt = ParsePacket(b->Buf, b->Size);
#ifdef RAW_DEBUG
IPsecIkeSendUdpForDebug(IPSEC_PORT_L2TP, 1, b->Buf, b->Size);
#endif // RAW_DEBUG
if (pkt == NULL)
{
// Parsing failure
dec_data = NULL;
dec_size = 0;
}
else
{
// Parsing success
switch (pkt->TypeL3)
{
case L3_IPV4:
// Save the internal IP address information
UINTToIP(&c->TunnelModeServerIP, pkt->L3.IPv4Header->DstIP);
UINTToIP(&c->TunnelModeClientIP, pkt->L3.IPv4Header->SrcIP);
if (IPV4_GET_OFFSET(pkt->L3.IPv4Header) == 0)
{
if ((IPV4_GET_FLAGS(pkt->L3.IPv4Header) & 0x01) == 0)
{
if (pkt->L3.IPv4Header->Protocol == IPSEC_IP_PROTO_ETHERIP)
{
// EtherIP
if (ike->IPsec->Services.EtherIP_IPsec)
{
// An EtherIP packet has been received
ProcIPsecEtherIPPacketRecv(ike, c, pkt->IPv4PayloadData, pkt->IPv4PayloadSize, true);
}
}
else if (pkt->L3.IPv4Header->Protocol == IPSEC_IP_PROTO_L2TPV3)
{
// L2TPv3
if (ike->IPsec->Services.EtherIP_IPsec)
{
// A L2TPv3 packet has been received
ProcL2TPv3PacketRecv(ike, c, pkt->IPv4PayloadData, pkt->IPv4PayloadSize, true);
}
}
}
}
break;
case L3_IPV6:
// Save the internal IP address information
SetIP6(&c->TunnelModeServerIP, pkt->IPv6HeaderPacketInfo.IPv6Header->DestAddress.Value);
SetIP6(&c->TunnelModeClientIP, pkt->IPv6HeaderPacketInfo.IPv6Header->SrcAddress.Value);
if (pkt->IPv6HeaderPacketInfo.IsFragment == false)
{
if (pkt->IPv6HeaderPacketInfo.FragmentHeader == NULL || (IPV6_GET_FLAGS(pkt->IPv6HeaderPacketInfo.FragmentHeader) & IPV6_FRAGMENT_HEADER_FLAG_MORE_FRAGMENTS) == 0)
{
if (pkt->IPv6HeaderPacketInfo.Protocol == IPSEC_IP_PROTO_ETHERIP)
{
// EtherIP
if (ike->IPsec->Services.EtherIP_IPsec)
{
// An EtherIP packet has been received
ProcIPsecEtherIPPacketRecv(ike, c, pkt->IPv6HeaderPacketInfo.Payload, pkt->IPv6HeaderPacketInfo.PayloadSize, true);
}
}
else if (pkt->IPv6HeaderPacketInfo.Protocol == IPSEC_IP_PROTO_L2TPV3)
{
// L2TPv3
if (ike->IPsec->Services.EtherIP_IPsec)
{
// A L2TPv3 packet has been received
ProcL2TPv3PacketRecv(ike, c, pkt->IPv6HeaderPacketInfo.Payload, pkt->IPv6HeaderPacketInfo.PayloadSize, true);
}
}
}
}
break;
}
FreePacket(pkt);
}
FreeBuf(b);
}
}
else
{
// Transport mode
if (next_header == IP_PROTO_UDP)
{
if (ike->IPsec->Services.L2TP_IPsec || ike->IPsec->Services.EtherIP_IPsec)
{
// An UDP packet has been received
ProcIPsecUdpPacketRecv(ike, c, dec_data, dec_size);
}
}
else if (next_header == IPSEC_IP_PROTO_ETHERIP)
{
if (ike->IPsec->Services.EtherIP_IPsec)
{
// An EtherIP packet has been received
ProcIPsecEtherIPPacketRecv(ike, c, dec_data, dec_size, false);
}
}
else if (next_header == IPSEC_IP_PROTO_L2TPV3)
{
if (ike->IPsec->Services.EtherIP_IPsec)
{
// A L2TPv3 packet has been received
ProcL2TPv3PacketRecv(ike, c, dec_data, dec_size, false);
}
}
}
update_status = true;
}
FreeBuf(dec);
}
if (update_status)
{
bool start_qm = false;
// Update the status of the client
c->CurrentIpSecSaRecv = ipsec_sa;
if (ipsec_sa->PairIPsecSa != NULL)
{
c->CurrentIpSecSaSend = ipsec_sa->PairIPsecSa;
if (p->DestPort == IPSEC_PORT_IPSEC_ESP_UDP)
{
IPSECSA *send_sa = c->CurrentIpSecSaSend;
if (send_sa->TransformSetting.CapsuleMode == IKE_P2_CAPSULE_TUNNEL)
{
send_sa->TransformSetting.CapsuleMode = IKE_P2_CAPSULE_NAT_TUNNEL_1;
}
else if (send_sa->TransformSetting.CapsuleMode == IKE_P2_CAPSULE_TRANSPORT)
{
send_sa->TransformSetting.CapsuleMode = IKE_P2_CAPSULE_NAT_TRANSPORT_1;
}
}
}
c->LastCommTick = ike->Now;
ipsec_sa->LastCommTick = ike->Now;
if (ipsec_sa->PairIPsecSa != NULL)
{
ipsec_sa->PairIPsecSa->LastCommTick = ike->Now;
}
SetIkeClientEndpoint(ike, c, &p->SrcIP, p->SrcPort, &p->DstIP, p->DestPort);
if (seq >= 0xf0000000)
{
// Execute a QuickMode forcibly since sequence number is going to exhaust
start_qm = true;
}
if (ipsec_sa->TransformSetting.LifeKilobytes != 0)
{
UINT64 hard_size = (UINT64)ipsec_sa->TransformSetting.LifeKilobytes * (UINT64)1000;
UINT64 soft_size = hard_size * (UINT64)2 / (UINT64)3;
if (ipsec_sa->TotalSize >= soft_size)
{
// Execute a QuickMode forcibly because the capacity limit is going to exceed
start_qm = true;
}
}
if (start_qm)
{
if (ipsec_sa->StartQM_FlagSet == false)
{
c->StartQuickModeAsSoon = true;
ipsec_sa->StartQM_FlagSet = true;
}
}
}
}
// Received the L2TPv3 packet via the IPsec tunnel
void ProcL2TPv3PacketRecv(IKE_SERVER *ike, IKE_CLIENT *c, UCHAR *data, UINT data_size, bool is_tunnel_mode)
{
UDPPACKET p;
// Validate arguments
if (ike == NULL || c == NULL || data == NULL || data_size == 0)
{
return;
}
c->IsL2TPOnIPsecTunnelMode = is_tunnel_mode;
IPsecIkeClientManageL2TPServer(ike, c);
// Pass the received packet to the L2TP server
p.Type = 0;
p.Data = data;
p.DestPort = IPSEC_PORT_L2TPV3_VIRTUAL;
p.Size = data_size;
if (is_tunnel_mode)
{
Copy(&p.DstIP, &c->TunnelModeServerIP, sizeof(IP));
Copy(&p.SrcIP, &c->TunnelModeClientIP, sizeof(IP));
}
else
{
Copy(&p.DstIP, &c->L2TPServerIP, sizeof(IP));
Copy(&p.SrcIP, &c->L2TPClientIP, sizeof(IP));
}
p.SrcPort = IPSEC_PORT_L2TPV3_VIRTUAL;
#ifdef RAW_DEBUG
IPsecIkeSendUdpForDebug(IPSEC_PORT_L2TP, 1, ((UCHAR *)p.Data) + 4, p.Size - 4);
#endif // RAW_DEBUG
ProcL2TPPacketRecv(c->L2TP, &p);
}
// An EtherIP packet has been received via an IPsec tunnel
void ProcIPsecEtherIPPacketRecv(IKE_SERVER *ike, IKE_CLIENT *c, UCHAR *data, UINT data_size, bool is_tunnel_mode)
{
BLOCK *b;
// Validate arguments
if (ike == NULL || c == NULL || data == NULL || data_size == 0)
{
return;
}
c->IsEtherIPOnIPsecTunnelMode = is_tunnel_mode;
IPsecIkeClientManageEtherIPServer(ike, c);
b = NewBlock(data, data_size, 0);
EtherIPProcRecvPackets(c->EtherIP, b);
Free(b);
}
// An UDP packet has been received via the IPsec tunnel
void ProcIPsecUdpPacketRecv(IKE_SERVER *ike, IKE_CLIENT *c, UCHAR *data, UINT data_size)
{
UDP_HEADER *u;
UINT payload_size;
UINT src_port, dst_port;
UINT packet_length;
// Validate arguments
if (ike == NULL || c == NULL || data == NULL || data_size == 0)
{
return;
}
if (data_size <= sizeof(UDP_HEADER))
{
// There is no UDP header or the data is 0 bytes
return;
}
// UDP header
u = (UDP_HEADER *)data;
packet_length = Endian16(u->PacketLength);
if (packet_length <= sizeof(UDP_HEADER))
{
return;
}
payload_size = packet_length - sizeof(UDP_HEADER);
if (payload_size == 0)
{
// No data
return;
}
if (data_size < (sizeof(UDP_HEADER) + payload_size))
{
// Data is not followed
return;
}
src_port = Endian16(u->SrcPort);
dst_port = Endian16(u->DstPort);
if (dst_port == IPSEC_PORT_L2TP)
{
UDPPACKET p;
// A L2TP packet has been received
IPsecIkeClientManageL2TPServer(ike, c);
// Update Port number
c->L2TPClientPort = src_port;
// Pass the received packet to the L2TP server
p.Type = 0;
p.Data = data + sizeof(UDP_HEADER);
p.DestPort = IPSEC_PORT_L2TP;
Copy(&p.DstIP, &c->L2TPServerIP, sizeof(IP));
p.Size = payload_size;
Copy(&p.SrcIP, &c->L2TPClientIP, sizeof(IP));
p.SrcPort = IPSEC_PORT_L2TP;
ProcL2TPPacketRecv(c->L2TP, &p);
//Debug("IPsec UDP Recv: %u <= %u %u\n", dst_port, src_port, p.Size);
#ifdef RAW_DEBUG
IPsecIkeSendUdpForDebug(IPSEC_PORT_L2TP, 1, p.Data, p.Size);
#endif // RAW_DEBUG
}
}
// Send a raw packet for debugging
void IPsecIkeSendUdpForDebug(UINT dst_port, UINT dst_ip, void *data, UINT size)
{
SOCK *s = NewUDP(0);
IP d;
SetIP(&d, dst_ip, dst_ip, dst_ip, dst_ip);
SendTo(s, &d, dst_port, data, size);
ReleaseSock(s);
}
// L2TP packet transmission (via IPsec SA tunnel)
void IPsecIkeClientSendL2TPPackets(IKE_SERVER *ike, IKE_CLIENT *c, L2TP_SERVER *l2tp)
{
UINT i;
// Validate arguments
if (ike == NULL || c == NULL || l2tp == NULL)
{
return;
}
for (i = 0;i < LIST_NUM(l2tp->SendPacketList);i++)
{
UDPPACKET *u = LIST_DATA(l2tp->SendPacketList, i);
if (u->SrcPort != IPSEC_PORT_L2TPV3_VIRTUAL)
{
// L2TP UDP packet transmission
IPsecSendUdpPacket(ike, c, IPSEC_PORT_L2TP, c->L2TPClientPort,
u->Data, u->Size);
}
else
{
// L2TPv3 special IP packet transmission
IPsecSendPacketByIkeClient(ike, c, u->Data, u->Size, IPSEC_IP_PROTO_L2TPV3);
#ifdef RAW_DEBUG
IPsecIkeSendUdpForDebug(IPSEC_PORT_L2TP, 1, ((UCHAR *)u->Data) + 4, u->Size - 4);
#endif // RAW_DEBUG
}
FreeUdpPacket(u);
}
DeleteAll(l2tp->SendPacketList);
}
// Manage the L2TP server that is associated with the IKE_CLIENT
void IPsecIkeClientManageL2TPServer(IKE_SERVER *ike, IKE_CLIENT *c)
{
L2TP_SERVER *l2tp;
// Validate arguments
if (ike == NULL || c == NULL)
{
return;
}
if (c->L2TP == NULL)
{
UINT crypt_block_size = IKE_MAX_BLOCK_SIZE;
if (c->CurrentIpSecSaRecv != NULL)
{
crypt_block_size = c->CurrentIpSecSaRecv->TransformSetting.Crypto->BlockSize;
}
c->L2TP = NewL2TPServerEx(ike->Cedar, ike, IsIP6(&c->ClientIP), crypt_block_size);
c->L2TP->IkeClient = c;
Copy(&c->L2TPServerIP, &c->ServerIP, sizeof(IP));
Copy(&c->L2TPClientIP, &c->ClientIP, sizeof(IP));
if (c->CurrentIpSecSaRecv != NULL)
{
Format(c->L2TP->CryptName, sizeof(c->L2TP->CryptName),
"IPsec - %s (%u bits)",
c->CurrentIpSecSaRecv->TransformSetting.Crypto->Name,
c->CurrentIpSecSaRecv->TransformSetting.CryptoKeySize * 8);
}
Debug("IKE_CLIENT 0x%X: L2TP Server Started.\n", c);
IPsecLog(ike, c, NULL, NULL, "LI_L2TP_SERVER_STARTED");
}
l2tp = c->L2TP;
if (l2tp->Interrupts == NULL)
{
l2tp->Interrupts = ike->Interrupts;
}
if (l2tp->SockEvent == NULL)
{
SetL2TPServerSockEvent(l2tp, ike->SockEvent);
}
l2tp->Now = ike->Now;
}
// Manage the EtherIP server that is associated with the IKE_CLIENT
void IPsecIkeClientManageEtherIPServer(IKE_SERVER *ike, IKE_CLIENT *c)
{
ETHERIP_SERVER *s;
// Validate arguments
if (ike == NULL || c == NULL)
{
return;
}
if (c->EtherIP == NULL)
{
char crypt_name[MAX_SIZE];
UINT crypt_block_size = IKE_MAX_BLOCK_SIZE;
Zero(crypt_name, sizeof(crypt_name));
if (c->CurrentIpSecSaRecv != NULL)
{
Format(crypt_name, sizeof(crypt_name),
"IPsec - %s (%u bits)",
c->CurrentIpSecSaRecv->TransformSetting.Crypto->Name,
c->CurrentIpSecSaRecv->TransformSetting.CryptoKeySize * 8);
crypt_block_size = c->CurrentIpSecSaRecv->TransformSetting.Crypto->BlockSize;
}
c->EtherIP = NewEtherIPServer(ike->Cedar, ike->IPsec, ike,
&c->ClientIP, c->ClientPort,
&c->ServerIP, c->ServerPort, crypt_name,
c->IsEtherIPOnIPsecTunnelMode, crypt_block_size, c->ClientId,
++ike->CurrentEtherId);
Debug("IKE_CLIENT 0x%X: EtherIP Server Started.\n", c);
IPsecLog(ike, c, NULL, NULL, NULL, "LI_ETHERIP_SERVER_STARTED", ike->CurrentEtherId);
}
else
{
StrCpy(c->EtherIP->ClientId, sizeof(c->EtherIP->ClientId), c->ClientId);
}
s = c->EtherIP;
if (s->Interrupts == NULL)
{
s->Interrupts = ike->Interrupts;
}
if (s->SockEvent == NULL)
{
SetEtherIPServerSockEvent(s, ike->SockEvent);
}
s->Now = ike->Now;
}
// EtherIP packet transmission (via IPsec SA tunnel)
void IPsecIkeClientSendEtherIPPackets(IKE_SERVER *ike, IKE_CLIENT *c, ETHERIP_SERVER *s)
{
UINT i;
// Validate arguments
if (ike == NULL || c == NULL || s == NULL)
{
return;
}
for (i = 0;i < LIST_NUM(s->SendPacketList);i++)
{
BLOCK *b = LIST_DATA(s->SendPacketList, i);
// Packet transmission
IPsecSendPacketByIkeClient(ike, c, b->Buf, b->Size, IPSEC_IP_PROTO_ETHERIP);
FreeBlock(b);
}
DeleteAll(s->SendPacketList);
}
// Handle the deletion payload
void ProcDeletePayload(IKE_SERVER *ike, IKE_CLIENT *c, IKE_PACKET_DELETE_PAYLOAD *d)
{
// Validate arguments
if (ike == NULL || c == NULL || d == NULL)
{
return;
}
if (d->ProtocolId == IKE_PROTOCOL_ID_IPSEC_ESP)
{
UINT i;
// Remove the IPsec SA
for (i = 0;i < LIST_NUM(d->SpiList);i++)
{
BUF *b = LIST_DATA(d->SpiList, i);
if (b->Size == 4)
{
UINT spi = READ_UINT(b->Buf);
MarkIPsecSaAsDeleted(ike, SearchIPsecSaBySpi(ike, c, spi));
}
}
}
else if (d->ProtocolId == IKE_PROTOCOL_ID_IKE)
{
UINT i;
// Remove the IKE SA
for (i = 0;i < LIST_NUM(d->SpiList);i++)
{
BUF *b = LIST_DATA(d->SpiList, i);
if (b->Size == 16)
{
UINT64 v1 = READ_UINT64(((UCHAR *)b->Buf) + 0);
UINT64 v2 = READ_UINT64(((UCHAR *)b->Buf) + 8);
IKE_SA *sa = FindIkeSaByResponderCookie(ike, v2);
if (sa != NULL && sa->IkeClient == c)
{
MarkIkeSaAsDeleted(ike, sa);
}
}
}
}
}
// Mark the IKE_CLIENT for deletion
void MarkIkeClientAsDeleted(IKE_SERVER *ike, IKE_CLIENT *c)
{
char client_ip_str[MAX_SIZE];
char server_ip_str[MAX_SIZE];
// Validate arguments
if (ike == NULL || c == NULL)
{
return;
}
if (c->Deleting)
{
return;
}
ike->StateHasChanged = true;
c->Deleting = true;
IPToStr(client_ip_str, sizeof(client_ip_str), &c->ClientIP);
IPToStr(server_ip_str, sizeof(server_ip_str), &c->ServerIP);
Debug("Deleting IKE_CLIENT: %p: %s:%u -> %s:%u\n", c, client_ip_str, c->ClientPort, server_ip_str, c->ServerPort);
IPsecLog(ike, c, NULL, NULL, "LI_DELETE_IKE_CLIENT");
}
// Mark the IKE SA for deletion
void MarkIkeSaAsDeleted(IKE_SERVER *ike, IKE_SA *sa)
{
// Validate arguments
if (ike == NULL || sa == NULL)
{
return;
}
if (sa->Deleting)
{
return;
}
ike->StateHasChanged = true;
sa->Deleting = true;
Debug("IKE SA %I64u - %I64u has been marked as being deleted.\n", sa->InitiatorCookie, sa->ResponderCookie);
SendDeleteIkeSaPacket(ike, sa->IkeClient, sa->InitiatorCookie, sa->ResponderCookie);
IPsecLog(ike, NULL, sa, NULL, "LI_DELETE_IKE_SA");
}
// Mark the IPsec SA for deletion
void MarkIPsecSaAsDeleted(IKE_SERVER *ike, IPSECSA *sa)
{
// Validate arguments
if (ike == NULL || sa == NULL)
{
return;
}
if (sa->Deleting)
{
return;
}
ike->StateHasChanged = true;
sa->Deleting = true;
Debug("IPsec SA 0x%X has been marked as being deleted.\n", sa->Spi);
SendDeleteIPsecSaPacket(ike, sa->IkeClient, sa->Spi);
IPsecLog(ike, NULL, NULL, sa, "LI_DELETE_IPSEC_SA");
}
// IPsec SA Deletion packet transmission process
void SendDeleteIPsecSaPacket(IKE_SERVER *ike, IKE_CLIENT *c, UINT spi)
{
IKE_PACKET_PAYLOAD *payload;
BUF *buf;
// Validate arguments
if (ike == NULL || c == NULL || spi == 0)
{
return;
}
buf = NewBuf();
WriteBufInt(buf, spi);
payload = IkeNewDeletePayload(IKE_PROTOCOL_ID_IPSEC_ESP, NewListSingle(buf));
SendInformationalExchangePacket(ike, c, payload);
}
// IKE SA deletion packet transmission process
void SendDeleteIkeSaPacket(IKE_SERVER *ike, IKE_CLIENT *c, UINT64 init_cookie, UINT64 resp_cookie)
{
IKE_PACKET_PAYLOAD *payload;
BUF *buf;
// Validate arguments
if (ike == NULL || c == NULL)
{
return;
}
buf = NewBuf();
WriteBufInt64(buf, init_cookie);
WriteBufInt64(buf, resp_cookie);
payload = IkeNewDeletePayload(IKE_PROTOCOL_ID_IKE, NewListSingle(buf));
SendInformationalExchangePacket(ike, c, payload);
}
// Information exchange packet transmission process
void SendInformationalExchangePacket(IKE_SERVER *ike, IKE_CLIENT *c, IKE_PACKET_PAYLOAD *payload)
{
SendInformationalExchangePacketEx(ike, c, payload, false, 0, 0);
}
void SendInformationalExchangePacketEx(IKE_SERVER *ike, IKE_CLIENT *c, IKE_PACKET_PAYLOAD *payload, bool force_plain, UINT64 init_cookie, UINT64 resp_cookie)
{
IKE_SA *sa;
IKE_PACKET *ps;
LIST *payload_list;
UCHAR dummy_hash_data[IKE_MAX_HASH_SIZE];
IKE_PACKET_PAYLOAD *hash_payload;
BUF *ps_buf;
UINT after_hash_offset, after_hash_size;
BUF *ps_buf_after_hash;
BUF *tmp_buf;
UCHAR hash[IKE_MAX_HASH_SIZE];
IKE_CRYPTO_PARAM cp;
IKE_INFOMSG_QUOTA_ENTRY *quota_entry;
bool plain = false;
// Validate arguments
if (ike == NULL || c == NULL || payload == NULL)
{
IkeFreePayload(payload);
return;
}
quota_entry = IkeInfoMsgQuotaGetEntry(ike, &c->ClientIP);
if (quota_entry == NULL)
{
IkeFreePayload(payload);
return;
}
quota_entry->Count++;
if (quota_entry->Count >= IKE_QUOTA_MAX_INFOMSG_SEND_PER_IP_PER_SEC)
{
IkeFreePayload(payload);
return;
}
sa = c->CurrentIkeSa;
if (sa == NULL)
{
plain = true;
}
if (force_plain)
{
plain = true;
}
if (plain && (init_cookie == 0 && resp_cookie == 0))
{
init_cookie = Rand64();
resp_cookie = 0;
}
payload_list = NewListFast(NULL);
Zero(dummy_hash_data, sizeof(dummy_hash_data));
// Hash payload
if (plain == false)
{
hash_payload = IkeNewDataPayload(IKE_PAYLOAD_HASH, dummy_hash_data, sa->HashSize);
Add(payload_list, hash_payload);
}
// Body
Add(payload_list, payload);
// Packet creation
ps = IkeNew((plain ? init_cookie : sa->InitiatorCookie), (plain ? resp_cookie : sa->ResponderCookie),
IKE_EXCHANGE_TYPE_INFORMATION, false, false, false,
GenerateNewMessageId(ike), payload_list);
if (plain == false)
{
// Build a temporary packet
ps_buf = IkeBuild(ps, NULL);
// Get the payload after the hash part
after_hash_offset = sizeof(IKE_HEADER) + hash_payload->BitArray->Size + sizeof(IKE_COMMON_HEADER);
after_hash_size = ((ps_buf->Size > after_hash_offset) ? (ps_buf->Size - after_hash_offset) : 0);
ps_buf_after_hash = MemToBuf(((UCHAR *)ps_buf->Buf) + after_hash_offset, after_hash_size);
FreeBuf(ps_buf);
// Calculate the hash
tmp_buf = NewBuf();
WriteBufInt(tmp_buf, ps->MessageId);
WriteBufBuf(tmp_buf, ps_buf_after_hash);
IkeHMac(sa->TransformSetting.Hash, hash, sa->SKEYID_a, sa->HashSize, tmp_buf->Buf, tmp_buf->Size);
FreeBuf(tmp_buf);
// Overwrite the hash
Copy(hash_payload->Payload.Hash.Data->Buf, hash, sa->HashSize);
ps->FlagEncrypted = true;
FreeBuf(ps_buf_after_hash);
}
// Packet reply
Zero(&cp, sizeof(cp));
if (plain == false)
{
cp.Key = sa->CryptoKey;
IkeCalcPhase2InitialIv(cp.Iv, sa, ps->MessageId);
}
ps_buf = IkeBuild(ps, &cp);
IkeSendUdpPacket(ike, IKE_UDP_TYPE_ISAKMP, &c->ServerIP, c->ServerPort,
&c->ClientIP, c->ClientPort,
Clone(ps_buf->Buf, ps_buf->Size), ps_buf->Size);
#ifdef RAW_DEBUG
IkeDebugUdpSendRawPacket(ps);
#endif // RAW_DEBUG
FreeBuf(ps_buf);
IkeFree(ps);
}
// Information exchange packet reception process
void ProcIkeInformationalExchangePacketRecv(IKE_SERVER *ike, UDPPACKET *p, IKE_PACKET *header)
{
IKE_CLIENT *c;
IKE_SA *ike_sa;
// Validate arguments
if (ike == NULL || p == NULL || header == NULL || header->InitiatorCookie == 0 || header->ResponderCookie == 0
|| header->MessageId == 0 || header->FlagEncrypted == false)
{
return;
}
c = SearchOrCreateNewIkeClientForIkePacket(ike, &p->SrcIP, p->SrcPort, &p->DstIP, p->DestPort, header);
if (c == NULL)
{
return;
}
ike_sa = FindIkeSaByResponderCookieAndClient(ike, header->ResponderCookie, c);
if (ike_sa != NULL && ike_sa->Established)
{
IKE_PACKET *pr;
IKE_CRYPTO_PARAM cp;
// Packet decoding
Zero(&cp, sizeof(cp));
cp.Key = ike_sa->CryptoKey;
IkeCalcPhase2InitialIv(cp.Iv, ike_sa, header->MessageId);
pr = IkeParse(p->Data, p->Size, &cp);
#ifdef RAW_DEBUG
IkeDebugUdpSendRawPacket(pr);
#endif // RAW_DEBUG
if (pr != NULL)
{
// Get the hash payload
IKE_PACKET_PAYLOAD *hash_payload;
hash_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_HASH, 0);
if (hash_payload != NULL)
{
// Get the payload after the hash
UINT header_and_hash_size = sizeof(IKE_COMMON_HEADER) + hash_payload->BitArray->Size;
void *after_hash_data = ((UCHAR *)pr->DecryptedPayload->Buf) + header_and_hash_size;
if (pr->DecryptedPayload->Size > header_and_hash_size)
{
UINT after_hash_size = pr->DecryptedPayload->Size - header_and_hash_size;
UCHAR hash1[IKE_MAX_HASH_SIZE];
BUF *hash1_buf;
hash1_buf = NewBuf();
WriteBufInt(hash1_buf, header->MessageId);
WriteBuf(hash1_buf, after_hash_data, after_hash_size);
IkeHMac(ike_sa->TransformSetting.Hash, hash1, ike_sa->SKEYID_a, ike_sa->HashSize,
hash1_buf->Buf, hash1_buf->Size);
// Compare the hash value
if (IkeCompareHash(hash_payload, hash1, ike_sa->HashSize))
{
UINT i, num;
// Handle the deletion payload
num = IkeGetPayloadNum(pr->PayloadList, IKE_PAYLOAD_DELETE);
for (i = 0;i < num;i++)
{
IKE_PACKET_PAYLOAD *payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_DELETE, i);
IKE_PACKET_DELETE_PAYLOAD *del = &payload->Payload.Delete;
ProcDeletePayload(ike, c, del);
}
num = IkeGetPayloadNum(pr->PayloadList, IKE_PAYLOAD_NOTICE);
// Handle the notification payload
for (i = 0;i < num;i++)
{
IKE_PACKET_PAYLOAD *payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NOTICE, i);
IKE_PACKET_NOTICE_PAYLOAD *n = &payload->Payload.Notice;
if (n->MessageType == IKE_NOTICE_DPD_REQUEST || n->MessageType == IKE_NOTICE_DPD_RESPONSE)
{
if (n->MessageData != NULL && n->MessageData->Size == sizeof(UINT))
{
UINT seq_no = READ_UINT(n->MessageData->Buf);
if (n->Spi->Size == (sizeof(UINT64) * 2))
{
UINT64 init_cookie = READ_UINT64(((UCHAR *)n->Spi->Buf));
UINT64 resp_cookie = READ_UINT64(((UCHAR *)n->Spi->Buf) + sizeof(UINT64));
if (init_cookie != 0 && resp_cookie != 0)
{
IKE_SA *found_ike_sa = SearchIkeSaByCookie(ike, init_cookie, resp_cookie);
if (found_ike_sa != NULL && found_ike_sa->IkeClient == c)
{
if (n->MessageType == IKE_NOTICE_DPD_REQUEST)
{
// Return the DPD Response (ACK) for the DPD Request
SendInformationalExchangePacket(ike, c,
IkeNewNoticeDpdPayload(true, init_cookie, resp_cookie,
seq_no));
}
// Update the status of the IKE SA
found_ike_sa->LastCommTick = ike->Now;
ike_sa->LastCommTick = ike->Now;
found_ike_sa->IkeClient->LastCommTick = ike->Now;
ike_sa->IkeClient->LastCommTick = ike->Now;
ike_sa->IkeClient->CurrentIkeSa = ike_sa;
}
}
}
}
}
}
}
FreeBuf(hash1_buf);
}
}
IkeFree(pr);
}
}
}
// Create a new message ID
UINT GenerateNewMessageId(IKE_SERVER *ike)
{
UINT ret;
// Validate arguments
if (ike == NULL)
{
return 0;
}
while (true)
{
ret = Rand32();
if (ret != 0 && ret != 0xffffffff)
{
UINT i;
bool ok = true;
for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
{
IPSECSA *sa = LIST_DATA(ike->IPsecSaList, i);
if (sa->MessageId == ret)
{
ok = false;
break;
}
}
if (ok)
{
return ret;
}
}
}
}
// Start the quick mode
void StartQuickMode(IKE_SERVER *ike, IKE_CLIENT *c)
{
IPSEC_SA_TRANSFORM_SETTING setting;
IKE_SA *ike_sa;
UINT message_id;
UCHAR iv[IKE_MAX_BLOCK_SIZE];
// Validate arguments
if (ike == NULL || c == NULL)
{
return;
}
if (IsZero(&c->CachedTransformSetting, sizeof(IPSEC_SA_TRANSFORM_SETTING)))
{
// Cached transform setting does not exist
Debug("Error: c->CachedTransformSetting is not existing.\n");
return;
}
ike_sa = c->CurrentIkeSa;
if (ike_sa == NULL)
{
return;
}
IPsecLog(ike, NULL, ike_sa, NULL, "LI_START_QM_FROM_SERVER");
Copy(&setting, &c->CachedTransformSetting, sizeof(IPSEC_SA_TRANSFORM_SETTING));
message_id = GenerateNewMessageId(ike);
IkeCalcPhase2InitialIv(iv, ike_sa, message_id);
#ifdef FORCE_LIFETIME_QM
setting.LifeSeconds = FORCE_LIFETIME_QM;
#endif // FORCE_LIFETIME_QM
if (true)
{
IKE_PACKET *ps;
LIST *payload_list;
IKE_PACKET_PAYLOAD *send_hash_payload;
IKE_PACKET_PAYLOAD *send_sa_payload;
IKE_PACKET_PAYLOAD *send_proposal_payload;
IKE_PACKET_PAYLOAD *send_transform_payload;
IKE_PACKET_PAYLOAD *send_rand_payload;
IKE_PACKET_PAYLOAD *send_key_payload = NULL;
IKE_PACKET_PAYLOAD *send_id_1 = NULL, *send_id_2 = NULL;
UINT shared_key_size = 0;
UCHAR *shared_key = NULL;
BUF *initiator_rand;
IPSECSA *ipsec_sa_s_c, *ipsec_sa_c_s;
BUF *ps_buf;
UINT after_hash_offset, after_hash_size;
BUF *ps_buf_after_hash;
BUF *tmp_buf;
UINT spi;
UINT spi_be;
UCHAR hash1[IKE_MAX_HASH_SIZE];
UCHAR zero = 0;
DH_CTX *dh = NULL;
UCHAR dummy_hash_data[IKE_MAX_HASH_SIZE];
initiator_rand = RandBuf(IKE_SA_RAND_SIZE);
if (setting.Dh != NULL)
{
// Generate DH
dh = IkeDhNewCtx(setting.Dh);
if (dh != NULL)
{
send_key_payload = IkeNewDataPayload(IKE_PAYLOAD_KEY_EXCHANGE,
dh->MyPublicKey->Buf, dh->MyPublicKey->Size);
}
}
Zero(dummy_hash_data, sizeof(dummy_hash_data));
// Dummy hash value
payload_list = NewListFast(NULL);
send_hash_payload = IkeNewDataPayload(IKE_PAYLOAD_HASH, dummy_hash_data, ike_sa->HashSize);
Add(payload_list, send_hash_payload);
// Determine the SPI
spi = GenerateNewIPsecSaSpi(ike, 0);
spi_be = Endian32(spi);
// SA
send_transform_payload = TransformSettingToTransformPayloadForIPsec(ike, &setting);
send_proposal_payload = IkeNewProposalPayload(1, IKE_PROTOCOL_ID_IPSEC_ESP, &spi_be, sizeof(spi_be),
NewListSingle(send_transform_payload));
send_sa_payload = IkeNewSaPayload(NewListSingle(send_proposal_payload));
Add(payload_list, send_sa_payload);
// Random number
send_rand_payload = IkeNewDataPayload(IKE_PAYLOAD_RAND, initiator_rand->Buf, initiator_rand->Size);
Add(payload_list, send_rand_payload);
// Key exchange
if (send_key_payload != NULL)
{
Add(payload_list, send_key_payload);
}
if (c->SendID1andID2)
{
// Add the ID payload
if (setting.CapsuleMode == IKE_P2_CAPSULE_NAT_TUNNEL_1 || setting.CapsuleMode == IKE_P2_CAPSULE_NAT_TUNNEL_2)
{
UCHAR zero[32];
Zero(zero, sizeof(zero));
// Tunnel Mode
send_id_1 = IkeNewIdPayload((IsIP4(&c->ServerIP) ? IKE_ID_IPV4_ADDR_SUBNET : IKE_ID_IPV6_ADDR_SUBNET),
0, 0,
zero, (IsIP4(&c->ServerIP) ? 8 : 32));
send_id_2 = IkeNewIdPayload(c->SendID1_Type,
c->SendID1_Protocol, c->SendID1_Port,
c->SendID1_Buf->Buf, c->SendID1_Buf->Size);
}
else
{
// Transport mode
// Specify in the reverse order in which the client has been specified
send_id_2 = IkeNewIdPayload(c->SendID1_Type,
c->SendID1_Protocol, c->SendID1_Port,
c->SendID1_Buf->Buf, c->SendID1_Buf->Size);
send_id_1 = IkeNewIdPayload(c->SendID2_Type,
c->SendID2_Protocol, c->SendID2_Port,
c->SendID2_Buf->Buf, c->SendID2_Buf->Size);
}
Add(payload_list, send_id_1);
Add(payload_list, send_id_2);
}
if (true)
{
// NAT-OA payload
if (c->SendNatOaDraft1)
{
Add(payload_list, IkeNewNatOaPayload(IKE_PAYLOAD_NAT_OA_DRAFT, &c->ServerIP));
}
if (c->SendNatOaDraft2)
{
Add(payload_list, IkeNewNatOaPayload(IKE_PAYLOAD_NAT_OA_DRAFT_2, &c->ServerIP));
}
if (c->SendNatOaRfc)
{
Add(payload_list, IkeNewNatOaPayload(IKE_PAYLOAD_NAT_OA, &c->ClientIP));
Add(payload_list, IkeNewNatOaPayload(IKE_PAYLOAD_NAT_OA, &c->ServerIP));
}
}
// Build a packet
ps = IkeNew(ike_sa->InitiatorCookie, ike_sa->ResponderCookie, IKE_EXCHANGE_TYPE_QUICK,
false, false, false, message_id, payload_list);
// Build a temporary packet
ps_buf = IkeBuild(ps, NULL);
// Get the payload after the hash part
after_hash_offset = sizeof(IKE_HEADER) + send_hash_payload->BitArray->Size + sizeof(IKE_COMMON_HEADER);
after_hash_size = ((ps_buf->Size > after_hash_offset) ? (ps_buf->Size - after_hash_offset) : 0);
ps_buf_after_hash = MemToBuf(((UCHAR *)ps_buf->Buf) + after_hash_offset, after_hash_size);
FreeBuf(ps_buf);
// Calculate the hash #1
tmp_buf = NewBuf();
WriteBufInt(tmp_buf, message_id);
WriteBufBuf(tmp_buf, ps_buf_after_hash);
IkeHMac(ike_sa->TransformSetting.Hash, hash1, ike_sa->SKEYID_a, ike_sa->HashSize, tmp_buf->Buf, tmp_buf->Size);
FreeBuf(tmp_buf);
// Overwrite hash #1
Copy(send_hash_payload->Payload.Hash.Data->Buf, hash1, ike_sa->HashSize);
// Create an IPsec SA
ipsec_sa_c_s = NewIPsecSa(ike, c, ike_sa, true, message_id, false, iv, spi,
initiator_rand->Buf, initiator_rand->Size, NULL, 0,
&setting, shared_key, shared_key_size);
ipsec_sa_s_c = NewIPsecSa(ike, c, ike_sa, true, message_id, true, iv, 0,
initiator_rand->Buf, initiator_rand->Size, NULL, 0,
&setting, shared_key, shared_key_size);
ipsec_sa_c_s->PairIPsecSa = ipsec_sa_s_c;
ipsec_sa_s_c->PairIPsecSa = ipsec_sa_c_s;
ipsec_sa_s_c->Dh = dh;
Insert(ike->IPsecSaList, ipsec_sa_c_s);
Insert(ike->IPsecSaList, ipsec_sa_s_c);
// Packet transmission
ps->FlagEncrypted = true;
IPsecSaSendPacket(ike, ipsec_sa_s_c, ps);
ipsec_sa_s_c->NumResends = 3;
#ifdef RAW_DEBUG
IkeDebugUdpSendRawPacket(ps);
#endif // RAW_DEBUG
IkeFree(ps);
Free(shared_key);
FreeBuf(ps_buf_after_hash);
FreeBuf(initiator_rand);
}
}
// Process the quick mode received packet
void ProcIkeQuickModePacketRecv(IKE_SERVER *ike, UDPPACKET *p, IKE_PACKET *header)
{
IKE_CLIENT *c;
IKE_SA *ike_sa;
// Validate arguments
if (ike == NULL || p == NULL || header == NULL || header->InitiatorCookie == 0 || header->ResponderCookie == 0
|| header->MessageId == 0 || header->FlagEncrypted == false)
{
return;
}
c = SearchOrCreateNewIkeClientForIkePacket(ike, &p->SrcIP, p->SrcPort, &p->DstIP, p->DestPort, header);
if (c == NULL)
{
return;
}
ike_sa = FindIkeSaByResponderCookieAndClient(ike, header->ResponderCookie, c);
if (ike_sa == NULL)
{
// IKE SA does not exist
SendInformationalExchangePacketEx(ike, c, IkeNewNoticeErrorInvalidCookiePayload(header->InitiatorCookie,
header->ResponderCookie), true, header->InitiatorCookie, header->ResponderCookie);
}
if (ike_sa != NULL && ike_sa->Established)
{
// Update the status of the IKE SA
ike_sa->LastCommTick = ike->Now;
ike_sa->IkeClient->LastCommTick = ike->Now;
ike_sa->IkeClient->CurrentIkeSa = ike_sa;
// Search whether the Message ID is already in the database
if (SearchIPsecSaByMessageId(ike, c, header->MessageId) == NULL)
{
IKE_PACKET *pr;
IKE_CRYPTO_PARAM cp;
// Message ID does not exist. Start a new Quick Mode session
Zero(&cp, sizeof(cp));
cp.Key = ike_sa->CryptoKey;
IkeCalcPhase2InitialIv(cp.Iv, ike_sa, header->MessageId);
pr = IkeParse(p->Data, p->Size, &cp);
#ifdef RAW_DEBUG
IkeDebugUdpSendRawPacket(pr);
#endif // RAW_DEBUG
if (pr != NULL)
{
// Get the hash payload
IKE_PACKET_PAYLOAD *hash_payload;
hash_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_HASH, 0);
if (hash_payload != NULL)
{
// Get the payload after the hash
UINT header_and_hash_size = sizeof(IKE_COMMON_HEADER) + hash_payload->BitArray->Size;
void *after_hash_data = ((UCHAR *)pr->DecryptedPayload->Buf) + header_and_hash_size;
if (pr->DecryptedPayload->Size > header_and_hash_size)
{
UINT after_hash_size = pr->DecryptedPayload->Size - header_and_hash_size;
UCHAR hash1[IKE_MAX_HASH_SIZE];
BUF *hash1_buf;
hash1_buf = NewBuf();
WriteBufInt(hash1_buf, header->MessageId);
WriteBuf(hash1_buf, after_hash_data, after_hash_size);
IkeHMac(ike_sa->TransformSetting.Hash, hash1, ike_sa->SKEYID_a, ike_sa->HashSize,
hash1_buf->Buf, hash1_buf->Size);
// Compare the hash value
if (IkeCompareHash(hash_payload, hash1, ike_sa->HashSize))
{
IKE_PACKET_PAYLOAD *sa_payload, *rand_payload, *key_payload, *id_payload_1, *id_payload_2;
// Get the payload of other
sa_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_SA, 0);
rand_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_RAND, 0);
key_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_KEY_EXCHANGE, 0);
id_payload_1 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_ID, 0);
id_payload_2 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_ID, 1);
if (sa_payload != NULL && rand_payload != NULL)
{
IPSEC_SA_TRANSFORM_SETTING setting;
Zero(&setting, sizeof(setting));
// Interpret the SA payload
if (GetBestTransformSettingForIPsecSa(ike, pr, &setting, &p->DstIP) && (GetNumberOfIPsecSaOfIkeClient(ike, c) <= IKE_QUOTA_MAX_SA_PER_CLIENT))
{
// Appropriate transform setting is selected
Debug("P2 Transform: %s %s %s(%u) %u %u\n",
(setting.Dh == NULL ? NULL : setting.Dh->Name), setting.Hash->Name, setting.Crypto->Name, setting.CryptoKeySize,
setting.LifeKilobytes, setting.LifeSeconds);
#ifdef FORCE_LIFETIME_QM
setting.LifeSeconds = FORCE_LIFETIME_QM;
#endif // FORCE_LIFETIME_QM
// Cache the transform attribute value
Copy(&c->CachedTransformSetting, &setting, sizeof(IPSEC_SA_TRANSFORM_SETTING));
// Check the key exchange payload if the PFS is specified
if (setting.Dh == NULL || (setting.Dh != NULL && key_payload != NULL &&
key_payload->Payload.KeyExchange.Data->Size <= setting.Dh->KeySize))
{
// Create a payload for response
IKE_PACKET *ps;
LIST *payload_list;
IKE_PACKET_PAYLOAD *send_hash_payload;
IKE_PACKET_PAYLOAD *send_sa_payload;
IKE_PACKET_PAYLOAD *send_proposal_payload;
IKE_PACKET_PAYLOAD *send_transform_payload;
IKE_PACKET_PAYLOAD *send_rand_payload;
IKE_PACKET_PAYLOAD *send_key_payload = NULL;
IKE_PACKET_PAYLOAD *send_id_1 = NULL, *send_id_2 = NULL;
UCHAR dummy_hash_data[IKE_MAX_HASH_SIZE];
DH_CTX *dh = NULL;
UINT shared_key_size = 0;
UCHAR *shared_key = NULL;
BUF *initiator_rand, *responder_rand;
IPSECSA *ipsec_sa_s_c, *ipsec_sa_c_s;
BUF *ps_buf;
UINT after_hash_offset, after_hash_size;
BUF *ps_buf_after_hash;
BUF *tmp_buf;
UINT spi;
UINT spi_be;
UCHAR hash2[IKE_MAX_HASH_SIZE];
UCHAR hash3[IKE_MAX_HASH_SIZE];
UCHAR zero = 0;
IPsecLog(ike, NULL, ike_sa, NULL, "LI_START_QM_FROM_CLIENT");
initiator_rand = CloneBuf(rand_payload->Payload.Rand.Data);
responder_rand = RandBuf(IKE_SA_RAND_SIZE);
if (setting.Dh != NULL)
{
// Calculate DH
dh = IkeDhNewCtx(setting.Dh);
shared_key_size = (dh == NULL ? 0 : dh->Size);
shared_key = ZeroMalloc(shared_key_size);
if (DhCompute(dh, shared_key, key_payload->Payload.KeyExchange.Data->Buf, key_payload->Payload.KeyExchange.Data->Size))
{
// DH calculation success
Debug("P2 DH Ok.\n");
send_key_payload = IkeNewDataPayload(IKE_PAYLOAD_KEY_EXCHANGE,
dh->MyPublicKey->Buf, dh->MyPublicKey->Size);
IkeDhFreeCtx(dh);
}
else
{
// DH calculation failure
Debug("P2 DhCompute failed.\n");
shared_key = NULL;
Free(shared_key);
shared_key_size = 0;
IPsecLog(ike, NULL, ike_sa, NULL, "LI_QM_DH_ERROR");
}
}
Zero(dummy_hash_data, sizeof(dummy_hash_data));
// Dummy hash value
payload_list = NewListFast(NULL);
send_hash_payload = IkeNewDataPayload(IKE_PAYLOAD_HASH, dummy_hash_data, ike_sa->HashSize);
Add(payload_list, send_hash_payload);
// Determine the SPI
spi = GenerateNewIPsecSaSpi(ike, setting.SpiServerToClient);
spi_be = Endian32(spi);
// SA
send_transform_payload = TransformSettingToTransformPayloadForIPsec(ike, &setting);
send_proposal_payload = IkeNewProposalPayload(1, IKE_PROTOCOL_ID_IPSEC_ESP, &spi_be, sizeof(spi_be),
NewListSingle(send_transform_payload));
send_sa_payload = IkeNewSaPayload(NewListSingle(send_proposal_payload));
Add(payload_list, send_sa_payload);
// Random number
send_rand_payload = IkeNewDataPayload(IKE_PAYLOAD_RAND, responder_rand->Buf, responder_rand->Size);
Add(payload_list, send_rand_payload);
// Key exchange
if (send_key_payload != NULL)
{
Add(payload_list, send_key_payload);
}
// ID
if (id_payload_1 != NULL && id_payload_2 != NULL)
{
send_id_1 = IkeNewIdPayload(id_payload_1->Payload.Id.Type,
id_payload_1->Payload.Id.ProtocolId, id_payload_1->Payload.Id.Port,
id_payload_1->Payload.Id.IdData->Buf, id_payload_1->Payload.Id.IdData->Size);
send_id_2 = IkeNewIdPayload(id_payload_2->Payload.Id.Type,
id_payload_2->Payload.Id.ProtocolId, id_payload_2->Payload.Id.Port,
id_payload_2->Payload.Id.IdData->Buf, id_payload_2->Payload.Id.IdData->Size);
Add(payload_list, send_id_1);
Add(payload_list, send_id_2);
if (c->SendID1_Buf != NULL)
{
FreeBuf(c->SendID1_Buf);
}
if (c->SendID2_Buf != NULL)
{
FreeBuf(c->SendID2_Buf);
}
c->SendID1_Type = id_payload_1->Payload.Id.Type;
c->SendID1_Protocol = id_payload_1->Payload.Id.ProtocolId;
c->SendID1_Port = id_payload_1->Payload.Id.Port;
c->SendID1_Buf = CloneBuf(id_payload_1->Payload.Id.IdData);
c->SendID2_Type = id_payload_2->Payload.Id.Type;
c->SendID2_Protocol = id_payload_2->Payload.Id.ProtocolId;
c->SendID2_Port = id_payload_2->Payload.Id.Port;
c->SendID2_Buf = CloneBuf(id_payload_2->Payload.Id.IdData);
c->SendID1andID2 = true;
}
else
{
c->SendID1andID2 = false;
}
if (true)
{
// Reply if NAT-OA payload is presented by the client
IKE_PACKET_PAYLOAD *nat_oa_draft1 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_OA_DRAFT, 0);
IKE_PACKET_PAYLOAD *nat_oa_draft2 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_OA_DRAFT_2, 0);
IKE_PACKET_PAYLOAD *nat_oa_rfc_0 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_OA, 0);
IKE_PACKET_PAYLOAD *nat_oa_rfc_1 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_OA, 1);
c->SendNatOaDraft1 = c->SendNatOaDraft2 = c->SendNatOaRfc = false;
c->ShouldCalcChecksumForUDP = false;
if (nat_oa_draft1 != NULL)
{
Add(payload_list, IkeNewNatOaPayload(IKE_PAYLOAD_NAT_OA_DRAFT, &c->ServerIP));
c->SendNatOaDraft1 = true;
if (IsIP4(&nat_oa_draft1->Payload.NatOa.IpAddress) == IsIP4(&c->ServerIP))
{
Copy(&c->TransportModeClientIP, &nat_oa_draft1->Payload.NatOa.IpAddress, sizeof(IP));
Copy(&c->TransportModeServerIP, &c->ServerIP, sizeof(IP));
c->ShouldCalcChecksumForUDP = true;
}
}
if (nat_oa_draft2 != NULL)
{
Add(payload_list, IkeNewNatOaPayload(IKE_PAYLOAD_NAT_OA_DRAFT_2, &c->ServerIP));
c->SendNatOaDraft2 = true;
if (IsIP4(&nat_oa_draft2->Payload.NatOa.IpAddress) == IsIP4(&c->ServerIP))
{
Copy(&c->TransportModeClientIP, &nat_oa_draft2->Payload.NatOa.IpAddress, sizeof(IP));
Copy(&c->TransportModeServerIP, &c->ServerIP, sizeof(IP));
c->ShouldCalcChecksumForUDP = true;
}
}
if (nat_oa_rfc_0 != NULL && nat_oa_rfc_1 != NULL)
{
Add(payload_list, IkeNewNatOaPayload(IKE_PAYLOAD_NAT_OA, &c->ClientIP));
Add(payload_list, IkeNewNatOaPayload(IKE_PAYLOAD_NAT_OA, &c->ServerIP));
c->SendNatOaRfc = true;
if (IsIP4(&nat_oa_rfc_0->Payload.NatOa.IpAddress) == IsIP4(&c->ServerIP))
{
Copy(&c->TransportModeClientIP, &nat_oa_rfc_0->Payload.NatOa.IpAddress, sizeof(IP));
Copy(&c->TransportModeServerIP, &c->ServerIP, sizeof(IP));
c->ShouldCalcChecksumForUDP = true;
}
}
}
// Build a packet
ps = IkeNew(ike_sa->InitiatorCookie, ike_sa->ResponderCookie, IKE_EXCHANGE_TYPE_QUICK,
false, false, false, header->MessageId, payload_list);
// Build a temporary packet
ps_buf = IkeBuild(ps, NULL);
// Get the payload after the hash part
after_hash_offset = sizeof(IKE_HEADER) + send_hash_payload->BitArray->Size + sizeof(IKE_COMMON_HEADER);
after_hash_size = ((ps_buf->Size > after_hash_offset) ? (ps_buf->Size - after_hash_offset) : 0);
ps_buf_after_hash = MemToBuf(((UCHAR *)ps_buf->Buf) + after_hash_offset, after_hash_size);
FreeBuf(ps_buf);
// Calculate the hash #2
tmp_buf = NewBuf();
WriteBufInt(tmp_buf, header->MessageId);
WriteBufBuf(tmp_buf, initiator_rand);
WriteBufBuf(tmp_buf, ps_buf_after_hash);
IkeHMac(ike_sa->TransformSetting.Hash, hash2, ike_sa->SKEYID_a, ike_sa->HashSize, tmp_buf->Buf, tmp_buf->Size);
FreeBuf(tmp_buf);
// Calculate the hash #3
tmp_buf = NewBuf();
WriteBuf(tmp_buf, &zero, 1);
WriteBufInt(tmp_buf, header->MessageId);
WriteBufBuf(tmp_buf, initiator_rand);
WriteBufBuf(tmp_buf, responder_rand);
IkeHMac(ike_sa->TransformSetting.Hash, hash3, ike_sa->SKEYID_a, ike_sa->HashSize, tmp_buf->Buf, tmp_buf->Size);
FreeBuf(tmp_buf);
// Create an IPsec SA
ipsec_sa_c_s = NewIPsecSa(ike, c, ike_sa, false, header->MessageId, false, cp.NextIv, spi,
initiator_rand->Buf, initiator_rand->Size, responder_rand->Buf, responder_rand->Size,
&setting, shared_key, shared_key_size);
ipsec_sa_s_c = NewIPsecSa(ike, c, ike_sa, false, header->MessageId, true, cp.NextIv, setting.SpiServerToClient,
initiator_rand->Buf, initiator_rand->Size, responder_rand->Buf, responder_rand->Size,
&setting, shared_key, shared_key_size);
ipsec_sa_c_s->PairIPsecSa = ipsec_sa_s_c;
ipsec_sa_s_c->PairIPsecSa = ipsec_sa_c_s;
Insert(ike->IPsecSaList, ipsec_sa_c_s);
Insert(ike->IPsecSaList, ipsec_sa_s_c);
Copy(ipsec_sa_c_s->Hash3, hash3, ike_sa->HashSize);
// Overwrite hash #2
Copy(send_hash_payload->Payload.Hash.Data->Buf, hash2, ike_sa->HashSize);
// Packet reply
ps->FlagEncrypted = true;
IPsecSaSendPacket(ike, ipsec_sa_s_c, ps);
IkeSaSendPacket(ike, ike_sa, NULL);
#ifdef RAW_DEBUG
IkeDebugUdpSendRawPacket(ps);
#endif // RAW_DEBUG
IkeFree(ps);
Free(shared_key);
FreeBuf(ps_buf_after_hash);
FreeBuf(initiator_rand);
FreeBuf(responder_rand);
}
}
else
{
// No appropriate transform setting
Debug("No Appropriate Transform was Found.\n");
IPsecLog(ike, NULL, ike_sa, NULL, "LI_IPSEC_NO_TRANSFORM");
SendInformationalExchangePacket(ike, c, IkeNewNoticeErrorNoProposalChosenPayload(true, header->InitiatorCookie, header->ResponderCookie));
}
}
}
else
{
Debug("QM-1: Hash 1 is invalid.\n");
}
FreeBuf(hash1_buf);
}
}
IkeFree(pr);
}
}
else
{
// Get the IPsec SA
IPSECSA *ipsec_sa_cs = SearchIPsecSaByMessageId(ike, c, header->MessageId);
if (ipsec_sa_cs != NULL)
{
IPSECSA *ipsec_sa_sc = ipsec_sa_cs->PairIPsecSa;
if (ipsec_sa_sc != NULL)
{
if (ipsec_sa_sc->Established == false && ipsec_sa_cs->Established == false)
{
IKE_PACKET *pr = IPsecSaRecvPacket(ike, ipsec_sa_cs, p->Data, p->Size);
#ifdef RAW_DEBUG
IkeDebugUdpSendRawPacket(pr);
#endif // RAW_DEBUG
if (pr != NULL)
{
if (ipsec_sa_cs->Initiated == false)
{
// Initiator is client-side
// Check hash3 payload
IKE_PACKET_PAYLOAD *hash_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_HASH, 0);
if (hash_payload != NULL)
{
BUF *hash_buf = hash_payload->Payload.Hash.Data;
if (hash_buf != NULL)
{
if (hash_buf->Size == ipsec_sa_cs->IkeSa->HashSize)
{
if (Cmp(hash_buf->Buf, ipsec_sa_cs->Hash3, hash_buf->Size) == 0)
{
ipsec_sa_cs->Established = ipsec_sa_sc->Established = true;
ipsec_sa_cs->EstablishedTick = ipsec_sa_sc->EstablishedTick = ike->Now;
ipsec_sa_cs->LastCommTick = ipsec_sa_sc->LastCommTick = ike->Now;
c->CurrentIpSecSaRecv = ipsec_sa_cs;
c->CurrentIpSecSaSend = ipsec_sa_sc;
Debug("IPsec SA 0x%X & 0x%X Established.\n",
ipsec_sa_cs->Spi,
ipsec_sa_sc->Spi);
IPsecLog(ike, NULL, NULL, ipsec_sa_sc, "LI_IPSEC_SA_ESTABLISHED");
IPsecSaSendPacket(ike, ipsec_sa_sc, NULL);
}
else
{
Debug("QM-3: Hash 3 is invalid.\n");
}
}
}
}
}
else
{
// Initiator is server-side
// Get hash payload
IKE_PACKET_PAYLOAD *hash_payload;
hash_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_HASH, 0);
if (hash_payload != NULL && ipsec_sa_sc->InitiatorRand != NULL)
{
// Get the payload after the hash
UINT header_and_hash_size = sizeof(IKE_COMMON_HEADER) + hash_payload->BitArray->Size;
void *after_hash_data = ((UCHAR *)pr->DecryptedPayload->Buf) + header_and_hash_size;
if (pr->DecryptedPayload->Size > header_and_hash_size)
{
UINT after_hash_size = pr->DecryptedPayload->Size - header_and_hash_size;
UCHAR hash2[IKE_MAX_HASH_SIZE];
BUF *hash2_buf;
hash2_buf = NewBuf();
WriteBufInt(hash2_buf, header->MessageId);
WriteBufBuf(hash2_buf, ipsec_sa_sc->InitiatorRand);
WriteBuf(hash2_buf, after_hash_data, after_hash_size);
IkeHMac(ipsec_sa_sc->SKEYID_Hash, hash2, ipsec_sa_sc->SKEYID_a, ipsec_sa_sc->SKEYID_Hash->HashSize,
hash2_buf->Buf, hash2_buf->Size);
FreeBuf(hash2_buf);
// Compare the hash value
if (IkeCompareHash(hash_payload, hash2, ike_sa->HashSize))
{
IKE_PACKET_PAYLOAD *sa_payload, *rand_payload, *key_payload, *id_payload_1, *id_payload_2;
// Get the payload of other
sa_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_SA, 0);
rand_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_RAND, 0);
key_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_KEY_EXCHANGE, 0);
id_payload_1 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_ID, 0);
id_payload_2 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_ID, 1);
if (sa_payload != NULL && rand_payload != NULL)
{
IPSEC_SA_TRANSFORM_SETTING setting;
// Interpret the SA payload
if (GetBestTransformSettingForIPsecSa(ike, pr, &setting, &p->DstIP))
{
// Appropriate transform setting is selected
Debug("P2 Transform: %s %s %s(%u) %u %u\n",
(setting.Dh == NULL ? NULL : setting.Dh->Name), setting.Hash->Name, setting.Crypto->Name, setting.CryptoKeySize,
setting.LifeKilobytes, setting.LifeSeconds);
#ifdef FORCE_LIFETIME_QM
setting.LifeSeconds = FORCE_LIFETIME_QM;
#endif // FORCE_LIFETIME_QM
// Check the key exchange payload if the PFS is specified
if (setting.Dh == NULL || (setting.Dh != NULL && key_payload != NULL && ipsec_sa_sc->Dh != NULL &&
key_payload->Payload.KeyExchange.Data->Size <= setting.Dh->KeySize))
{
IKE_PACKET *ps;
LIST *payload_list;
IKE_PACKET_PAYLOAD *send_hash_payload;
IKE_PACKET_PAYLOAD *send_key_payload = NULL;
IKE_PACKET_PAYLOAD *send_id_1 = NULL, *send_id_2 = NULL;
DH_CTX *dh = NULL;
UINT shared_key_size = 0;
UCHAR *shared_key = NULL;
BUF *initiator_rand, *responder_rand;
BUF *tmp_buf;
UCHAR hash3[IKE_MAX_HASH_SIZE];
char tmp[MAX_SIZE];
UCHAR zero = 0;
initiator_rand = ipsec_sa_sc->InitiatorRand;
responder_rand = CloneBuf(rand_payload->Payload.Rand.Data);
if (setting.Dh != NULL)
{
// Calculate DH
DH_CTX *dh = ipsec_sa_sc->Dh;
shared_key_size = (dh == NULL ? 0 : dh->Size);
shared_key = ZeroMalloc(shared_key_size);
if (DhCompute(dh, shared_key, key_payload->Payload.KeyExchange.Data->Buf, key_payload->Payload.KeyExchange.Data->Size))
{
// DH calculation success
Debug("P2 DH Ok.\n");
}
else
{
// DH calculation failure
Debug("P2 DhCompute failed.\n");
shared_key = NULL;
Free(shared_key);
shared_key_size = 0;
IPsecLog(ike, NULL, ike_sa, NULL, "LI_QM_DH_ERROR");
}
}
// Update the information of IPsec SA
if (shared_key != NULL)
{
ipsec_sa_sc->SharedKey = NewBuf(shared_key, shared_key_size);
ipsec_sa_cs->SharedKey = NewBuf(shared_key, shared_key_size);
}
ipsec_sa_sc->Spi = setting.SpiServerToClient;
IPsecLog(ike, NULL, NULL, ipsec_sa_sc, "LI_IPSEC_SA_SPI_SET", ipsec_sa_sc->Spi);
ike->IPsecSaList->sorted = false;
ipsec_sa_sc->ResponderRand = CloneBuf(responder_rand);
ipsec_sa_cs->ResponderRand = CloneBuf(responder_rand);
Copy(&ipsec_sa_sc->TransformSetting, &setting, sizeof(IPSEC_SA_TRANSFORM_SETTING));
Copy(&ipsec_sa_cs->TransformSetting, &setting, sizeof(IPSEC_SA_TRANSFORM_SETTING));
ipsec_sa_sc->Established = true;
ipsec_sa_cs->Established = true;
IPsecLog(ike, NULL, NULL, ipsec_sa_sc, "LI_IPSEC_SA_ESTABLISHED");
ipsec_sa_sc->LastCommTick = ike->Now;
ipsec_sa_cs->LastCommTick = ike->Now;
c->CurrentIpSecSaRecv = ipsec_sa_cs;
c->CurrentIpSecSaSend = ipsec_sa_sc;
// Calculate the KEYMAT
IPsecCalcKeymat(ike, ipsec_sa_sc->SKEYID_Hash, ipsec_sa_sc->KeyMat, sizeof(ipsec_sa_sc->KeyMat),
ipsec_sa_sc->SKEYID_d, ipsec_sa_sc->SKEYID_Hash->HashSize, IKE_PROTOCOL_ID_IPSEC_ESP,
ipsec_sa_sc->Spi, initiator_rand->Buf, initiator_rand->Size,
responder_rand->Buf, responder_rand->Size,
shared_key, shared_key_size);
IPsecCalcKeymat(ike, ipsec_sa_cs->SKEYID_Hash, ipsec_sa_cs->KeyMat, sizeof(ipsec_sa_cs->KeyMat),
ipsec_sa_cs->SKEYID_d, ipsec_sa_cs->SKEYID_Hash->HashSize, IKE_PROTOCOL_ID_IPSEC_ESP,
ipsec_sa_cs->Spi, initiator_rand->Buf, initiator_rand->Size,
responder_rand->Buf, responder_rand->Size,
shared_key, shared_key_size);
IkeFreeKey(ipsec_sa_sc->CryptoKey);
IkeFreeKey(ipsec_sa_cs->CryptoKey);
ipsec_sa_sc->CryptoKey = IkeNewKey(setting.Crypto, ipsec_sa_sc->KeyMat, setting.CryptoKeySize);
ipsec_sa_cs->CryptoKey = IkeNewKey(setting.Crypto, ipsec_sa_cs->KeyMat, setting.CryptoKeySize);
Copy(ipsec_sa_sc->HashKey, ipsec_sa_sc->KeyMat + setting.CryptoKeySize, setting.Hash->HashSize);
Copy(ipsec_sa_cs->HashKey, ipsec_sa_cs->KeyMat + setting.CryptoKeySize, setting.Hash->HashSize);
BinToStrEx(tmp, sizeof(tmp), ipsec_sa_sc->KeyMat, ipsec_sa_sc->TransformSetting.CryptoKeySize);
Debug(" KEYMAT (SC): %s\n", tmp);
BinToStrEx(tmp, sizeof(tmp), ipsec_sa_cs->KeyMat, ipsec_sa_cs->TransformSetting.CryptoKeySize);
Debug(" KEYMAT (CS): %s\n", tmp);
Debug("IPsec SA 0x%X & 0x%X Established (Server is Initiator).\n",
ipsec_sa_cs->Spi,
ipsec_sa_sc->Spi);
// Calculate the hash #3
tmp_buf = NewBuf();
WriteBuf(tmp_buf, &zero, 1);
WriteBufInt(tmp_buf, header->MessageId);
WriteBufBuf(tmp_buf, initiator_rand);
WriteBufBuf(tmp_buf, responder_rand);
IkeHMac(ipsec_sa_cs->SKEYID_Hash, hash3, ipsec_sa_cs->SKEYID_a, ipsec_sa_cs->SKEYID_Hash->HashSize, tmp_buf->Buf, tmp_buf->Size);
FreeBuf(tmp_buf);
// Return the hash #3
send_hash_payload = IkeNewDataPayload(IKE_PAYLOAD_HASH, hash3, ipsec_sa_cs->SKEYID_Hash->HashSize);
payload_list = NewListSingle(send_hash_payload);
ps = IkeNew(ike_sa->InitiatorCookie, ike_sa->ResponderCookie,
IKE_EXCHANGE_TYPE_QUICK, true, false, false, header->MessageId, payload_list);
IPsecSaSendPacket(ike, ipsec_sa_sc, ps);
#ifdef RAW_DEBUG
IkeDebugUdpSendRawPacket(ps);
#endif // RAW_DEBUG
ipsec_sa_sc->NumResends = 3;
if (false)
{
UINT i;
for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
{
IPSECSA *sa = LIST_DATA(ike->IPsecSaList, i);
if (sa != ipsec_sa_sc && sa != ipsec_sa_cs)
{
MarkIPsecSaAsDeleted(ike, sa);
}
}
}
IkeFree(ps);
// Release the memory
FreeBuf(responder_rand);
}
}
else
{
// No appropriate transform setting
Debug("No Appropriate Transform was Found.\n");
IPsecLog(ike, NULL, ike_sa, NULL, "LI_IPSEC_NO_TRANSFORM");
SendInformationalExchangePacket(ike, c, IkeNewNoticeErrorNoProposalChosenPayload(true, header->InitiatorCookie, header->ResponderCookie));
}
}
}
}
}
}
IkeFree(pr);
}
}
}
}
}
}
}
// Calculate the KEYMAT
void IPsecCalcKeymat(IKE_SERVER *ike, IKE_HASH *h, void *dst, UINT dst_size, void *skeyid_d_data, UINT skeyid_d_size, UCHAR protocol, UINT spi, void *rand_init_data, UINT rand_init_size,
void *rand_resp_data, UINT rand_resp_size, void *df_key_data, UINT df_key_size)
{
BUF *k;
BUF *ret;
// Validate arguments
if (ike == NULL || dst == NULL || h == NULL || rand_init_data == NULL || rand_resp_data == NULL||
(df_key_size != 0 && df_key_data == NULL))
{
return;
}
ret = NewBuf();
k = NULL;
while (true)
{
BUF *tmp = NewBuf();
UCHAR hash[IKE_MAX_HASH_SIZE];
if (k != NULL)
{
WriteBufBuf(tmp, k);
}
if (df_key_data != NULL)
{
WriteBuf(tmp, df_key_data, df_key_size);
}
WriteBuf(tmp, &protocol, 1);
WriteBufInt(tmp, spi);
WriteBuf(tmp, rand_init_data, rand_init_size);
WriteBuf(tmp, rand_resp_data, rand_resp_size);
if (k != NULL)
{
FreeBuf(k);
}
IkeHMac(h, hash, skeyid_d_data, skeyid_d_size, tmp->Buf, tmp->Size);
FreeBuf(tmp);
k = MemToBuf(hash, h->HashSize);
WriteBufBuf(ret, k);
if (ret->Size >= dst_size)
{
break;
}
}
Copy(dst, ret->Buf, dst_size);
FreeBuf(ret);
FreeBuf(k);
}
// Search for IPsec SA from Message ID
IPSECSA *SearchIPsecSaByMessageId(IKE_SERVER *ike, IKE_CLIENT *c, UINT message_id)
{
UINT i;
// Validate arguments
if (ike == NULL || c == NULL || message_id == 0)
{
return NULL;
}
for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
{
IPSECSA *sa = LIST_DATA(ike->IPsecSaList, i);
if (sa->IkeClient == c)
{
if (sa->MessageId == message_id)
{
if (sa->ServerToClient == false)
{
if (sa->Established == false)
{
return sa;
}
}
}
}
}
return NULL;
}
// Search for IPsec SA from SPI value
IPSECSA *SearchClientToServerIPsecSaBySpi(IKE_SERVER *ike, UINT spi)
{
IPSECSA t;
// Validate arguments
if (ike == NULL || spi == 0)
{
return NULL;
}
t.ServerToClient = false;
t.Spi = spi;
return Search(ike->IPsecSaList, &t);
}
IPSECSA *SearchIPsecSaBySpi(IKE_SERVER *ike, IKE_CLIENT *c, UINT spi)
{
UINT i;
// Validate arguments
if (ike == NULL || c == NULL || spi == 0)
{
return NULL;
}
for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
{
IPSECSA *sa = LIST_DATA(ike->IPsecSaList, i);
if (sa->Spi == spi)
{
if (sa->IkeClient == c)
{
return sa;
}
}
}
return NULL;
}
// Search an IKE SA from the value of the Cookie
IKE_SA *SearchIkeSaByCookie(IKE_SERVER *ike, UINT64 init_cookie, UINT64 resp_cookie)
{
UINT i;
// Validate arguments
if (ike == NULL)
{
return NULL;
}
for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
{
IKE_SA *sa = LIST_DATA(ike->IkeSaList, i);
if (sa->InitiatorCookie == init_cookie && sa->ResponderCookie == resp_cookie)
{
return sa;
}
}
return NULL;
}
// Generate the SPI value of new IPsec SA
UINT GenerateNewIPsecSaSpi(IKE_SERVER *ike, UINT counterpart_spi)
{
UINT ret;
// Validate arguments
if (ike == NULL)
{
return 0;
}
while (true)
{
ret = Rand32();
if (ret != counterpart_spi)
{
if (ret >= 4096 && ret != INFINITE)
{
if (SearchClientToServerIPsecSaBySpi(ike, ret) == NULL)
{
return ret;
}
}
}
}
}
// Calculate the initial IV for Phase 2
void IkeCalcPhase2InitialIv(void *iv, IKE_SA *sa, UINT message_id)
{
BUF *b;
UCHAR hash[IKE_MAX_HASH_SIZE];
// Validate arguments
if (iv == NULL || sa == NULL)
{
return;
}
message_id = Endian32(message_id);
b = NewBuf();
WriteBuf(b, sa->Iv, sa->BlockSize);
WriteBuf(b, &message_id, sizeof(UINT));
IkeHash(sa->TransformSetting.Hash, hash, b->Buf, b->Size);
Copy(iv, hash, sa->TransformSetting.Crypto->BlockSize);
FreeBuf(b);
}
// Create a new IPsec SA
IPSECSA *NewIPsecSa(IKE_SERVER *ike, IKE_CLIENT *c, IKE_SA *ike_sa, bool initiate, UINT message_id, bool server_to_client, void *iv, UINT spi, void *init_rand_data, UINT init_rand_size, void *res_rand_data, UINT res_rand_size, IPSEC_SA_TRANSFORM_SETTING *setting, void *shared_key_data, UINT shared_key_size)
{
IPSECSA *sa;
char tmp[MAX_SIZE];
UINT total_key_size;
// Validate arguments
if (ike == NULL || c == NULL || ike_sa == NULL || message_id == 0 || iv == NULL || setting == NULL ||
(shared_key_data == NULL && shared_key_size != 0))
{
return NULL;
}
sa = ZeroMalloc(sizeof(IPSECSA));
if (server_to_client == false)
{
ike->CurrentIPsecSaId++;
}
sa->Id = ike->CurrentIPsecSaId;
sa->IkeClient = c;
sa->IkeSa = ike_sa;
sa->MessageId = message_id;
sa->FirstCommTick = ike->Now;
sa->LastCommTick = ike->Now;
sa->Initiated = initiate;
sa->ServerToClient = server_to_client;
sa->Spi = spi;
sa->SKEYID_Hash = ike_sa->TransformSetting.Hash;
Copy(sa->SKEYID_a, ike_sa->SKEYID_a, sa->SKEYID_Hash->HashSize);
Copy(sa->SKEYID_d, ike_sa->SKEYID_d, sa->SKEYID_Hash->HashSize);
sa->InitiatorRand = MemToBuf(init_rand_data, init_rand_size);
if (initiate == false)
{
sa->ResponderRand = MemToBuf(res_rand_data, res_rand_size);
}
Copy(sa->Iv, iv, ike_sa->BlockSize);
Copy(&sa->TransformSetting, setting, sizeof(IPSEC_SA_TRANSFORM_SETTING));
if (shared_key_data != NULL)
{
sa->SharedKey = MemToBuf(shared_key_data, shared_key_size);
}
total_key_size = sa->TransformSetting.CryptoKeySize + sa->TransformSetting.Hash->HashSize;
if (initiate == false)
{
IPsecCalcKeymat(ike, ike_sa->TransformSetting.Hash, sa->KeyMat, total_key_size,
ike_sa->SKEYID_d, ike_sa->HashSize, IKE_PROTOCOL_ID_IPSEC_ESP, spi, sa->InitiatorRand->Buf,
sa->InitiatorRand->Size, sa->ResponderRand->Buf, sa->ResponderRand->Size,
shared_key_data, shared_key_size);
sa->CryptoKey = IkeNewKey(sa->TransformSetting.Crypto, sa->KeyMat, sa->TransformSetting.CryptoKeySize);
Copy(sa->HashKey, sa->KeyMat + sa->TransformSetting.CryptoKeySize, sa->TransformSetting.Hash->HashSize);
}
Debug("New IPsec SA (StoC = %u): 0x%X 0x%X (%s %s %s(%u) %u %u)\n",
sa->ServerToClient,
sa->MessageId,
sa->Spi,
(setting->Dh == NULL ? NULL : setting->Dh->Name), setting->Hash->Name, setting->Crypto->Name, setting->CryptoKeySize,
setting->LifeKilobytes, setting->LifeSeconds);
IPsecLog(ike, c, NULL, sa, "LI_NEW_IPSEC_SA",
(sa->ServerToClient ? _UU("LI_TAG_SERVER_TO_CLIENT") : _UU("LI_TAG_CLIENT_TO_SERVER")),
sa->Spi,
(setting->Dh == NULL ? NULL : setting->Dh->Name), setting->Hash->Name, setting->Crypto->Name, setting->CryptoKeySize * 8,
setting->LifeKilobytes, setting->LifeSeconds);
Rand(sa->EspIv, sizeof(sa->EspIv));
if (initiate == false)
{
BinToStrEx(tmp, sizeof(tmp), sa->KeyMat, sa->TransformSetting.CryptoKeySize);
Debug(" KEYMAT: %s\n", tmp);
}
// Set the expiration time
if (setting->LifeSeconds != 0)
{
UINT64 span = (UINT64)((UINT64)setting->LifeSeconds * (UINT64)1000) + (UINT64)IKE_SOFT_EXPIRES_MARGIN;
sa->ExpiresHardTick = ike->Now + span;
sa->ExpiresSoftTick = ike->Now + span;
//sa->ExpiresSoftTick = ike->Now + (UINT64)5000;
AddInterrupt(ike->Interrupts, sa->ExpiresSoftTick);
}
return sa;
}
// Treat aggressive mode packet reception
void ProcIkeAggressiveModePacketRecv(IKE_SERVER *ike, UDPPACKET *p, IKE_PACKET *header)
{
IKE_CLIENT *c;
char tmp[MAX_SIZE];
// Validate arguments
if (ike == NULL || p == NULL || header == NULL || header->InitiatorCookie == 0)
{
return;
}
c = SearchOrCreateNewIkeClientForIkePacket(ike, &p->SrcIP, p->SrcPort, &p->DstIP, p->DestPort, header);
if (c == NULL)
{
return;
}
if (header->ResponderCookie == 0)
{
// Start process of the state 1
IKE_CAPS caps;
IKE_SA *sa;
IKE_PACKET *pr = IkeParse(p->Data, p->Size, NULL);
if (pr != NULL)
{
// Determine the CAPS
IkeCheckCaps(&caps, pr);
if (caps.MS_L2TPIPSecVPNClient || caps.MS_NT5_ISAKMP_OAKLEY || caps.MS_Vid_InitialContact)
{
c->IsMicrosoft = true;
}
if ((caps.NatTraversalDraftIetf || caps.NatTraversalRfc3947) || (IsUdpPortOpened(ike->IPsec->UdpListener, &p->DstIP, IPSEC_PORT_IPSEC_ESP_RAW)))
{
sa = FindIkeSaByEndPointAndInitiatorCookie(ike, &p->DstIP, p->DestPort, &p->SrcIP, p->SrcPort, header->InitiatorCookie, IKE_SA_AGRESSIVE_MODE);
if (sa == NULL)
{
// Check whether there is acceptable SA parameters by analyzing proposed parameters
IKE_SA_TRANSFORM_SETTING setting;
if (GetBestTransformSettingForIkeSa(ike, pr, &setting) && (GetNumberOfIkeSaOfIkeClient(ike, c) <= IKE_QUOTA_MAX_SA_PER_CLIENT))
{
IKE_PACKET_PAYLOAD *tp;
IKE_PACKET_PAYLOAD *pp;
IKE_PACKET_PAYLOAD *sap;
IKE_PACKET_PAYLOAD *client_sa_payload;
IKE_PACKET_PAYLOAD *your_key_payload;
IKE_PACKET_PAYLOAD *your_rand_payload;
IKE_PACKET_PAYLOAD *your_id_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_ID, 0);
// Appropriate transform setting is selected
Debug("P1 Transform: %s %s %s(%u) %u %u\n",
setting.Dh->Name, setting.Hash->Name, setting.Crypto->Name, setting.CryptoKeySize,
setting.LifeKilobytes, setting.LifeSeconds);
// Receive a key exchange packet
your_key_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_KEY_EXCHANGE, 0);
your_rand_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_RAND, 0);
if (your_key_payload != NULL && your_rand_payload != NULL && your_id_payload != NULL)
{
// Check the key payload
BUF *your_key_buf = your_key_payload->Payload.KeyExchange.Data;
BUF *your_rand_buf = your_rand_payload->Payload.Rand.Data;
// DH generation
DH_CTX *dh = IkeDhNewCtx(setting.Dh);
UINT shared_key_size = (dh == NULL ? 0 : dh->Size);
UCHAR *shared_key = ZeroMalloc(shared_key_size);
// DH calculation
if (DhCompute(dh, shared_key, your_key_buf->Buf, your_key_buf->Size))
{
IKE_PACKET *ps;
LIST *payload_list;
IKE_PACKET_PAYLOAD *my_key_payload;
IKE_PACKET_PAYLOAD *my_rand_payload;
BUF *nat_buf1, *nat_buf2;
BUF *iv_buf;
UCHAR iv_hashed_data[IKE_MAX_HASH_SIZE];
UCHAR initiator_hash[IKE_MAX_HASH_SIZE];
BUF *b;
IKE_PACKET_PAYLOAD *my_id_payload, *my_hash_payload;
UCHAR responder_hash[IKE_MAX_HASH_SIZE];
BUF *idir_b;
IKE_PACKET_PAYLOAD *your_nat_d_1 = NULL;
IKE_PACKET_PAYLOAD *your_nat_d_2 = NULL;
// Create an IKE SA
sa = NewIkeSa(ike, c, header->InitiatorCookie, IKE_SA_AGRESSIVE_MODE, &setting);
Copy(&sa->Caps, &caps, sizeof(IKE_CAPS));
sa->State= IKE_SA_AM_STATE_1_SA;
Insert(ike->IkeSaList, sa);
sa->HashSize = sa->TransformSetting.Hash->HashSize;
sa->KeySize = sa->TransformSetting.CryptoKeySize;
sa->BlockSize = sa->TransformSetting.Crypto->BlockSize;
// Get the Caps additionally
if (sa->Caps.NatTraversalRfc3947)
{
sa->Caps.UsingNatTraversalRfc3947 = true;
your_nat_d_1 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_D, 0);
your_nat_d_2 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_D, 1);
}
else if (sa->Caps.NatTraversalDraftIetf)
{
sa->Caps.UsingNatTraversalDraftIetf = true;
your_nat_d_1 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_D_DRAFT, 0);
your_nat_d_2 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_D_DRAFT, 1);
}
// Calculation success
sa->DhSharedKey = MemToBuf(shared_key, shared_key_size);
sa->InitiatorRand = RandBuf(IKE_SA_RAND_SIZE);
sa->ResponderRand = CloneBuf(your_rand_buf);
// Save a bit array of SA payload presented by the client
client_sa_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_SA, 0);
sa->SAi_b = CloneBuf(client_sa_payload->BitArray);
// Save the ID payload presented by the client
sa->YourIDPayloadForAM = CloneBuf(your_id_payload->BitArray);
//// Assemble the SA payload
// Construct transform payload
tp = TransformSettingToTransformPayloadForIke(ike, &setting);
// Build a proposal payload
pp = IkeNewProposalPayload(1, IKE_PROTOCOL_ID_IKE, NULL, 0, NewListSingle(tp));
// Build the SA payload
sap = IkeNewSaPayload(NewListSingle(pp));
payload_list = NewListSingle(sap);
// Send a key exchange packet
my_key_payload = IkeNewDataPayload(IKE_PAYLOAD_KEY_EXCHANGE, dh->MyPublicKey->Buf, dh->MyPublicKey->Size);
my_rand_payload = IkeNewDataPayload(IKE_PAYLOAD_RAND, sa->InitiatorRand->Buf, sa->InitiatorRand->Size);
Add(payload_list, my_key_payload);
Add(payload_list, my_rand_payload);
// NAT-D Packet
// Address of the opponent. Randomize in order to be forced to use NAT
nat_buf1 = IkeCalcNatDetectHash(ike, sa->TransformSetting.Hash, Rand64(), Rand64(), &c->ClientIP, Rand16());
// My address
if (c->IsMicrosoft == false || (your_nat_d_1 == NULL || your_nat_d_2 == NULL || your_nat_d_1->BitArray == NULL))
{
// Calculate exactly
nat_buf2 = IkeCalcNatDetectHash(ike, sa->TransformSetting.Hash,
sa->InitiatorCookie, sa->ResponderCookie, &c->ServerIP, c->ServerPort);
}
else
{
// Parrot the NAT_D payload indicating myself I got from
// the other if it has connected from a Microsoft VPN Client
nat_buf2 = CloneBuf(your_nat_d_1->BitArray);
}
// Save DH information
sa->GXi = CloneBuf(your_key_buf);
sa->GXr = CloneBuf(dh->MyPublicKey);
// Calculate the key set
IkeCalcSaKeySet(ike, sa, NULL);
// Calculate the initiator side hash value
b = NewBuf();
WriteBufBuf(b, sa->GXi);
WriteBufBuf(b, sa->GXr);
WriteBufInt64(b, sa->InitiatorCookie);
WriteBufInt64(b, sa->ResponderCookie);
WriteBufBuf(b, sa->SAi_b);
WriteBufBuf(b, sa->YourIDPayloadForAM);
IkeHMac(sa->TransformSetting.Hash, initiator_hash, sa->SKEYID, sa->HashSize,
b->Buf, b->Size);
FreeBuf(b);
Copy(sa->InitiatorHashForAM, initiator_hash, sa->HashSize);
// Prepare the response ID payload
// Generate the ID payload
if (IsIP6(&sa->IkeClient->ServerIP))
{
// IPv6 address
my_id_payload = IkeNewIdPayload(IKE_ID_IPV6_ADDR, 0, 0, sa->IkeClient->ServerIP.ipv6_addr, 16);
}
else
{
// IPv4 address
my_id_payload = IkeNewIdPayload(IKE_ID_IPV4_ADDR, 0, 0, sa->IkeClient->ServerIP.addr, 4);
}
// Build the ID payload tentatively
idir_b = IkeBuildIdPayload(&my_id_payload->Payload.Id);
b = NewBuf();
WriteBufBuf(b, sa->GXr);
WriteBufBuf(b, sa->GXi);
WriteBufInt64(b, sa->ResponderCookie);
WriteBufInt64(b, sa->InitiatorCookie);
WriteBufBuf(b, sa->SAi_b);
WriteBufBuf(b, idir_b);
IkeHMac(sa->TransformSetting.Hash, responder_hash, sa->SKEYID, sa->HashSize,
b->Buf, b->Size);
FreeBuf(b);
FreeBuf(idir_b);
my_hash_payload = IkeNewDataPayload(IKE_PAYLOAD_HASH, responder_hash, sa->HashSize);
Add(payload_list, my_id_payload);
Add(payload_list, my_hash_payload);
ps = IkeNew(sa->InitiatorCookie, sa->ResponderCookie, IKE_EXCHANGE_TYPE_AGGRESSIVE,
false, false, false, 0, payload_list);
// Add the vendor ID
IkeAddVendorIdPayloads(ps);
// NAT-D related
if (sa->Caps.UsingNatTraversalRfc3947)
{
// RFC-compliant
Add(payload_list, IkeNewDataPayload(IKE_PAYLOAD_NAT_D, nat_buf1->Buf, nat_buf1->Size));
Add(payload_list, IkeNewDataPayload(IKE_PAYLOAD_NAT_D, nat_buf2->Buf, nat_buf2->Size));
}
if (sa->Caps.UsingNatTraversalDraftIetf)
{
// Draft compliant
Add(payload_list, IkeNewDataPayload(IKE_PAYLOAD_NAT_D_DRAFT, nat_buf1->Buf, nat_buf1->Size));
Add(payload_list, IkeNewDataPayload(IKE_PAYLOAD_NAT_D_DRAFT, nat_buf2->Buf, nat_buf2->Size));
}
FreeBuf(nat_buf1);
FreeBuf(nat_buf2);
StrCpy(c->ClientId, sizeof(c->ClientId), your_id_payload->Payload.Id.StrData);
Debug("Client ID = %s\n", c->ClientId);
IPsecLog(ike, c, NULL, NULL, NULL, "LI_SET_CLIENT_ID", c->ClientId);
// Initial IV setting
iv_buf = NewBuf();
WriteBuf(iv_buf, your_key_buf->Buf, your_key_buf->Size);
WriteBuf(iv_buf, dh->MyPublicKey->Buf, dh->MyPublicKey->Size);
IkeHash(sa->TransformSetting.Hash, iv_hashed_data, iv_buf->Buf, iv_buf->Size);
BinToStrEx(tmp, sizeof(tmp), iv_hashed_data, sa->BlockSize);
Debug("Initial IV: %s\n", tmp);
IkeSaUpdateIv(sa, iv_hashed_data, sa->HashSize);
FreeBuf(iv_buf);
// Transmission
IkeSaSendPacket(ike, sa, ps);
IkeFree(ps);
}
else
{
// DH calculation failure
Debug("DhCompute failed.\n");
}
Free(shared_key);
DhFree(dh);
}
}
else
{
// No appropriate transform setting
Debug("No Appropriate Transform was Found.\n");
IPsecLog(ike, c, NULL, NULL, "LI_IKE_NO_TRANSFORM");
SendInformationalExchangePacket(ike, c, IkeNewNoticeErrorNoProposalChosenPayload(false, header->InitiatorCookie, header->ResponderCookie));
}
}
}
else
{
// Client does not support NAT Traversal
Debug("Client doesn't support NAT-T.\n");
IPsecLog(ike, c, NULL, NULL, "LI_IKE_NO_NAT_T");
}
IkeFree(pr);
}
}
else
{
// Process of state 2
IKE_SA *sa;
sa = FindIkeSaByResponderCookieAndClient(ike, header->ResponderCookie, c);
if (sa == NULL)
{
SendInformationalExchangePacketEx(ike, c, IkeNewNoticeErrorInvalidCookiePayload(header->InitiatorCookie,
header->ResponderCookie), true, header->InitiatorCookie, header->ResponderCookie);
}
if (sa != NULL && sa->Mode == IKE_SA_AGRESSIVE_MODE)
{
IKE_PACKET *pr = NULL;
sa->LastCommTick = ike->Now;
switch (sa->State)
{
case IKE_SA_AM_STATE_1_SA:
pr = IkeSaRecvPacket(ike, sa, p->Data, p->Size);
if (pr != NULL)
{
IKE_PACKET_PAYLOAD *your_hash_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_HASH, 0);
if (your_hash_payload != NULL)
{
// Compare the hash
if (IkeCompareHash(your_hash_payload, sa->InitiatorHashForAM, sa->HashSize))
{
// Transit to the established state
Debug("IKE SA 0x%X Established.\n", sa);
sa->State = IKE_SA_AM_STATE_2_ESTABLISHED;
sa->EstablishedTick = ike->Now;
sa->Established = true;
c->CurrentIkeSa = sa;
c->NextDpdSendTick = ike->Now + (UINT64)IKE_INTERVAL_DPD_KEEPALIVE;
StrCpy(c->Secret, sizeof(c->Secret), sa->Secret);
IPsecLog(ike, NULL, sa, NULL, "LI_IKE_SA_ESTABLISHED");
IkeSaSendPacket(ike, sa, NULL);
}
else
{
Debug("IKE SA 0x%X Invalid Hash.\n", sa);
}
}
}
break;
}
if (pr != NULL)
{
IkeFree(pr);
}
}
}
}
// Process of the main mode packet reception
void ProcIkeMainModePacketRecv(IKE_SERVER *ike, UDPPACKET *p, IKE_PACKET *header)
{
IKE_CLIENT *c;
char tmp[MAX_SIZE];
// Validate arguments
if (ike == NULL || p == NULL || header == NULL || header->InitiatorCookie == 0)
{
return;
}
c = SearchOrCreateNewIkeClientForIkePacket(ike, &p->SrcIP, p->SrcPort, &p->DstIP, p->DestPort, header);
if (c == NULL)
{
return;
}
if (header->ResponderCookie == 0)
{
// Start process of the state 1
IKE_CAPS caps;
IKE_SA *sa;
IKE_PACKET *pr = IkeParse(p->Data, p->Size, NULL);
if (pr != NULL)
{
// Determine the CAPS
IkeCheckCaps(&caps, pr);
if (caps.MS_L2TPIPSecVPNClient || caps.MS_NT5_ISAKMP_OAKLEY || caps.MS_Vid_InitialContact)
{
c->IsMicrosoft = true;
}
if ((caps.NatTraversalDraftIetf || caps.NatTraversalRfc3947) || (IsUdpPortOpened(ike->IPsec->UdpListener, &p->DstIP, IPSEC_PORT_IPSEC_ESP_RAW)))
{
sa = FindIkeSaByEndPointAndInitiatorCookie(ike, &p->DstIP, p->DestPort, &p->SrcIP, p->SrcPort, header->InitiatorCookie, IKE_SA_MAIN_MODE);
if (sa == NULL)
{
// Check whether there is acceptable SA parameters by analyzing proposed parameters
IKE_SA_TRANSFORM_SETTING setting;
if (GetBestTransformSettingForIkeSa(ike, pr, &setting) && (GetNumberOfIkeSaOfIkeClient(ike, c) <= IKE_QUOTA_MAX_SA_PER_CLIENT))
{
IKE_PACKET *ps;
IKE_PACKET_PAYLOAD *tp;
IKE_PACKET_PAYLOAD *pp;
IKE_PACKET_PAYLOAD *sap;
LIST *payload_list;
IKE_PACKET_PAYLOAD *client_sa_payload;
// Appropriate transform setting is selected
Debug("P1 Transform: %s %s %s(%u) %u %u\n",
setting.Dh->Name, setting.Hash->Name, setting.Crypto->Name, setting.CryptoKeySize,
setting.LifeKilobytes, setting.LifeSeconds);
#ifdef FORCE_LIFETIME_MM
setting.LifeSeconds = FORCE_LIFETIME_MM;
#endif // FORCE_LIFETIME_MM
// Create an IKE SA
sa = NewIkeSa(ike, c, header->InitiatorCookie, IKE_SA_MAIN_MODE, &setting);
Copy(&sa->Caps, &caps, sizeof(IKE_CAPS));
Insert(ike->IkeSaList, sa);
// Answer the SA parameter selection results
sa->State = IKE_SA_MM_STATE_1_SA;
// Save a bit array of SA payload presented by the client
client_sa_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_SA, 0);
sa->SAi_b = CloneBuf(client_sa_payload->BitArray);
//// Assemble the SA payload
// Construct a transform payload
tp = TransformSettingToTransformPayloadForIke(ike, &setting);
// Build a proposal payload
pp = IkeNewProposalPayload(1, IKE_PROTOCOL_ID_IKE, NULL, 0, NewListSingle(tp));
// Build a SA payload
sap = IkeNewSaPayload(NewListSingle(pp));
payload_list = NewListSingle(sap);
ps = IkeNew(sa->InitiatorCookie, sa->ResponderCookie, IKE_EXCHANGE_TYPE_MAIN,
false, false, false, 0, payload_list);
// Add the vendor ID payload
IkeAddVendorIdPayloads(ps);
IkeSaSendPacket(ike, sa, ps);
sa->HashSize = sa->TransformSetting.Hash->HashSize;
sa->KeySize = sa->TransformSetting.CryptoKeySize;
sa->BlockSize = sa->TransformSetting.Crypto->BlockSize;
IkeFree(ps);
}
else
{
// No appropriate transform setting
Debug("No Appropriate Transform was Found.\n");
IPsecLog(ike, c, NULL, NULL, "LI_IKE_NO_TRANSFORM");
SendInformationalExchangePacket(ike, c, IkeNewNoticeErrorNoProposalChosenPayload(false, header->InitiatorCookie, header->ResponderCookie));
}
}
else
{
// Ignore for IKE SA which already exists (Because it's likely to be a re-transmission)
}
}
else
{
// It does not support NAT Traversal
Debug("Client doesn't support NAT-T.\n");
IPsecLog(ike, c, NULL, NULL, "LI_IKE_NO_NAT_T");
}
IkeFree(pr);
}
}
else
{
// Process of state 2 or later
IKE_SA *sa;
sa = FindIkeSaByResponderCookieAndClient(ike, header->ResponderCookie, c);
if (sa == NULL)
{
SendInformationalExchangePacketEx(ike, c, IkeNewNoticeErrorInvalidCookiePayload(header->InitiatorCookie,
header->ResponderCookie), true, header->InitiatorCookie, header->ResponderCookie);
}
if (sa != NULL && sa->Mode == IKE_SA_MAIN_MODE)
{
IKE_PACKET *pr = NULL;
sa->LastCommTick = ike->Now;
switch (sa->State)
{
case IKE_SA_MM_STATE_1_SA:
pr = IkeSaRecvPacket(ike, sa, p->Data, p->Size);
if (pr != NULL)
{
// Receive a key exchange packet
IKE_PACKET_PAYLOAD *your_key_payload;
IKE_PACKET_PAYLOAD *your_rand_payload;
IKE_PACKET_PAYLOAD *your_nat_d_1 = NULL;
IKE_PACKET_PAYLOAD *your_nat_d_2 = NULL;
your_key_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_KEY_EXCHANGE, 0);
your_rand_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_RAND, 0);
if (IkeGetPayloadNum(pr->PayloadList, IKE_PAYLOAD_NAT_D) != 0)
{
sa->Caps.UsingNatTraversalRfc3947 = true;
your_nat_d_1 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_D, 0);
your_nat_d_2 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_D, 1);
}
if (IkeGetPayloadNum(pr->PayloadList, IKE_PAYLOAD_NAT_D_DRAFT) != 0)
{
sa->Caps.UsingNatTraversalDraftIetf = true;
your_nat_d_1 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_D_DRAFT, 0);
your_nat_d_2 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_D_DRAFT, 1);
}
if (your_key_payload != NULL && your_rand_payload != NULL)
{
// Check the key payload
BUF *your_key_buf = your_key_payload->Payload.KeyExchange.Data;
BUF *your_rand_buf = your_rand_payload->Payload.Rand.Data;
// DH generation
DH_CTX *dh = IkeDhNewCtx(sa->TransformSetting.Dh);
UINT shared_key_size = (dh == NULL ? 0 : dh->Size);
UCHAR *shared_key = ZeroMalloc(shared_key_size);
// DH calculation
if (DhCompute(dh, shared_key, your_key_buf->Buf, your_key_buf->Size))
{
IKE_PACKET *ps;
LIST *payload_list;
IKE_PACKET_PAYLOAD *my_key_payload;
IKE_PACKET_PAYLOAD *my_rand_payload;
BUF *nat_buf1, *nat_buf2;
BUF *iv_buf;
UCHAR iv_hashed_data[IKE_MAX_HASH_SIZE];
// Calculation success
sa->DhSharedKey = MemToBuf(shared_key, shared_key_size);
sa->InitiatorRand = RandBuf(IKE_SA_RAND_SIZE);
sa->ResponderRand = CloneBuf(your_rand_buf);
// Send a key exchange packet
my_key_payload = IkeNewDataPayload(IKE_PAYLOAD_KEY_EXCHANGE, dh->MyPublicKey->Buf, dh->MyPublicKey->Size);
my_rand_payload = IkeNewDataPayload(IKE_PAYLOAD_RAND, sa->InitiatorRand->Buf, sa->InitiatorRand->Size);
payload_list = NewListSingle(my_key_payload);
Add(payload_list, my_rand_payload);
// NAT-D packet
// Address of the opponent. Randomize in order to be forced to use NAT
nat_buf1 = IkeCalcNatDetectHash(ike, sa->TransformSetting.Hash, Rand64(), Rand64(), &c->ClientIP, Rand16());
//nat_buf1 = IkeCalcNatDetectHash(ike, sa->TransformSetting.Hash, sa->InitiatorCookie, sa->ResponderCookie, &c->ClientIP, c->ClientPort);
// My address
if (c->IsMicrosoft == false || (your_nat_d_1 == NULL || your_nat_d_2 == NULL || your_nat_d_1->BitArray == NULL))
{
// Calculate exactly
nat_buf2 = IkeCalcNatDetectHash(ike, sa->TransformSetting.Hash,
sa->InitiatorCookie, sa->ResponderCookie, &c->ServerIP, c->ServerPort);
}
else
{
// Parrot the NAT_D payload indicating myself I got from
// the other if it has connected from a Microsoft VPN Client
nat_buf2 = CloneBuf(your_nat_d_1->BitArray);
}
if (sa->Caps.UsingNatTraversalRfc3947)
{
// RFC-compliant
Add(payload_list, IkeNewDataPayload(IKE_PAYLOAD_NAT_D, nat_buf1->Buf, nat_buf1->Size));
Add(payload_list, IkeNewDataPayload(IKE_PAYLOAD_NAT_D, nat_buf2->Buf, nat_buf2->Size));
}
if (sa->Caps.UsingNatTraversalDraftIetf)
{
// Draft compliant
Add(payload_list, IkeNewDataPayload(IKE_PAYLOAD_NAT_D_DRAFT, nat_buf1->Buf, nat_buf1->Size));
Add(payload_list, IkeNewDataPayload(IKE_PAYLOAD_NAT_D_DRAFT, nat_buf2->Buf, nat_buf2->Size));
}
FreeBuf(nat_buf1);
FreeBuf(nat_buf2);
ps = IkeNew(sa->InitiatorCookie, sa->ResponderCookie, IKE_EXCHANGE_TYPE_MAIN,
false, false, false, 0, payload_list);
// Initial IV setting
iv_buf = NewBuf();
WriteBuf(iv_buf, your_key_buf->Buf, your_key_buf->Size);
WriteBuf(iv_buf, dh->MyPublicKey->Buf, dh->MyPublicKey->Size);
IkeHash(sa->TransformSetting.Hash, iv_hashed_data, iv_buf->Buf, iv_buf->Size);
BinToStrEx(tmp, sizeof(tmp), iv_hashed_data, sa->BlockSize);
Debug("Initial IV: %s\n", tmp);
IkeSaUpdateIv(sa, iv_hashed_data, sa->HashSize);
FreeBuf(iv_buf);
// Save the DH information
sa->GXi = CloneBuf(your_key_buf);
sa->GXr = CloneBuf(dh->MyPublicKey);
// Transmission
IkeSaSendPacket(ike, sa, ps);
IkeFree(ps);
// Calculate the key set
IkeCalcSaKeySet(ike, sa, NULL);
sa->State = IKE_SA_MM_STATE_2_KEY;
}
else
{
// DH calculation failure
Debug("DhCompute failed.\n");
}
Free(shared_key);
DhFree(dh);
}
}
break;
case IKE_SA_MM_STATE_2_KEY:
pr = IkeSaRecvPacket(ike, sa, p->Data, p->Size);
if (pr != NULL && pr->FlagEncrypted)
{
// Receive an ID exchange packet
IKE_PACKET_PAYLOAD *your_id_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_ID, 0);
IKE_PACKET_PAYLOAD *your_hash_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_HASH, 0);
if (your_id_payload && your_hash_payload)
{
UCHAR initiator_hash[IKE_MAX_HASH_SIZE];
BUF *b;
// Calculate the initiator side hash value
b = NewBuf();
WriteBufBuf(b, sa->GXi);
WriteBufBuf(b, sa->GXr);
WriteBufInt64(b, sa->InitiatorCookie);
WriteBufInt64(b, sa->ResponderCookie);
WriteBufBuf(b, sa->SAi_b);
WriteBufBuf(b, your_id_payload->BitArray);
StrCpy(c->ClientId, sizeof(c->ClientId), your_id_payload->Payload.Id.StrData);
Debug("Client ID = %s\n", c->ClientId);
IPsecLog(ike, c, NULL, NULL, NULL, "LI_SET_CLIENT_ID", c->ClientId);
IkeHMac(sa->TransformSetting.Hash, initiator_hash, sa->SKEYID, sa->HashSize,
b->Buf, b->Size);
FreeBuf(b);
// Hash comparison
if (IkeCompareHash(your_hash_payload, initiator_hash, sa->HashSize))
{
// Generate a response packet
IKE_PACKET *ps;
LIST *payload_list = NewListFast(NULL);
IKE_PACKET_PAYLOAD *my_id_payload, *my_hash_payload;
UCHAR responder_hash[IKE_MAX_HASH_SIZE];
BUF *idir_b;
// Generate an ID payload
if (IsIP6(&sa->IkeClient->ServerIP))
{
// IPv6 address
my_id_payload = IkeNewIdPayload(IKE_ID_IPV6_ADDR, 0, 0, sa->IkeClient->ServerIP.ipv6_addr, 16);
}
else
{
// IPv4 address
my_id_payload = IkeNewIdPayload(IKE_ID_IPV4_ADDR, 0, 0, sa->IkeClient->ServerIP.addr, 4);
}
// Build the ID payload tentatively
idir_b = IkeBuildIdPayload(&my_id_payload->Payload.Id);
// Generate the hash payload
b = NewBuf();
WriteBufBuf(b, sa->GXr);
WriteBufBuf(b, sa->GXi);
WriteBufInt64(b, sa->ResponderCookie);
WriteBufInt64(b, sa->InitiatorCookie);
WriteBufBuf(b, sa->SAi_b);
WriteBufBuf(b, idir_b);
IkeHMac(sa->TransformSetting.Hash, responder_hash, sa->SKEYID, sa->HashSize,
b->Buf, b->Size);
FreeBuf(b);
FreeBuf(idir_b);
my_hash_payload = IkeNewDataPayload(IKE_PAYLOAD_HASH, responder_hash, sa->HashSize);
Add(payload_list, my_id_payload);
Add(payload_list, my_hash_payload);
ps = IkeNew(sa->InitiatorCookie, sa->ResponderCookie, IKE_EXCHANGE_TYPE_MAIN, true, false,
false, 0, payload_list);
// Transmission
IkeSaSendPacket(ike, sa, ps);
sa->NumResends = 3;
IkeFree(ps);
StrCpy(c->ClientId, sizeof(c->ClientId), your_id_payload->Payload.Id.StrData);
// Transit to the established state
Debug("IKE SA 0x%X Established. Client ID=%s\n", sa, c->ClientId);
sa->State = IKE_SA_MM_STATE_3_ESTABLISHED;
sa->EstablishedTick = ike->Now;
c->CurrentIkeSa = sa;
c->NextDpdSendTick = ike->Now + (UINT64)IKE_INTERVAL_DPD_KEEPALIVE;
StrCpy(c->Secret, sizeof(c->Secret), sa->Secret);
sa->Established = true;
IPsecLog(ike, NULL, sa, NULL, "LI_IKE_SA_ESTABLISHED");
}
else
{
Debug("IKE SA 0x%X Invalid Hash.\n", sa);
}
}
}
break;
}
if (pr != NULL)
{
IkeFree(pr);
}
}
}
}
// Update the IV of IPsec SA
void IPsecSaUpdateIv(IPSECSA *sa, void *iv, UINT iv_size)
{
// Validate arguments
if (sa == NULL || iv == NULL)
{
return;
}
Copy(sa->Iv, iv, MIN(sa->IkeSa->BlockSize, iv_size));
if (iv_size < sa->IkeSa->BlockSize)
{
Zero(sa->Iv + sa->IkeSa->BlockSize, sa->IkeSa->BlockSize - iv_size);
}
sa->IsIvExisting = true;
}
// Update the IV of the IKE SA
void IkeSaUpdateIv(IKE_SA *sa, void *iv, UINT iv_size)
{
// Validate arguments
if (sa == NULL || iv == NULL)
{
return;
}
Copy(sa->Iv, iv, MIN(sa->BlockSize, iv_size));
if (iv_size < sa->BlockSize)
{
Zero(sa->Iv + sa->BlockSize, sa->BlockSize - iv_size);
}
sa->IsIvExisting = true;
}
// Calculate the key set of the IKE SA
void IkeCalcSaKeySet(IKE_SERVER *ike, IKE_SA *sa, char *secret)
{
BUF *secret_buf;
BUF *rand_buf;
BUF *d_buf, *a_buf, *e_buf;
UCHAR u;
IKE_HASH *h;
char tmp[MAX_SIZE];
// Validate arguments
if (ike == NULL || sa == NULL)
{
return;
}
h = sa->TransformSetting.Hash;
// Calculation of SKEYID
StrCpy(sa->Secret, sizeof(sa->Secret), secret == NULL ? ike->Secret : secret);
secret_buf = IkeStrToPassword(sa->Secret);
rand_buf = CloneBuf(sa->ResponderRand);
SeekBufToEnd(rand_buf);
BinToStrEx(tmp, sizeof(tmp), rand_buf->Buf, rand_buf->Size);
Debug("ResponderRand: %s\n", tmp);
BinToStrEx(tmp, sizeof(tmp), sa->InitiatorRand->Buf, sa->InitiatorRand->Size);
Debug("InitiatorRand: %s\n", tmp);
WriteBufBuf(rand_buf, sa->InitiatorRand);
IkeHMacBuf(h, sa->SKEYID, secret_buf, rand_buf);
BinToStrEx(tmp, sizeof(tmp), sa->SKEYID, sa->HashSize);
Debug("SKEYID: %s\n", tmp);
// SKEYID_d
d_buf = CloneBuf(sa->DhSharedKey);
SeekBufToEnd(d_buf);
WriteBufInt64(d_buf, sa->InitiatorCookie);
WriteBufInt64(d_buf, sa->ResponderCookie);
u = 0;
WriteBuf(d_buf, &u, 1);
IkeHMac(h, sa->SKEYID_d, sa->SKEYID, sa->HashSize, d_buf->Buf, d_buf->Size);
BinToStrEx(tmp, sizeof(tmp), sa->SKEYID_d, sa->HashSize);
Debug("SKEYID_d: %s\n", tmp);
// SKEYID_a
a_buf = MemToBuf(sa->SKEYID_d, sa->HashSize);
SeekBufToEnd(a_buf);
WriteBufBuf(a_buf, sa->DhSharedKey);
WriteBufInt64(a_buf, sa->InitiatorCookie);
WriteBufInt64(a_buf, sa->ResponderCookie);
u = 1;
WriteBuf(a_buf, &u, 1);
IkeHMac(h, sa->SKEYID_a, sa->SKEYID, sa->HashSize, a_buf->Buf, a_buf->Size);
BinToStrEx(tmp, sizeof(tmp), sa->SKEYID_a, sa->HashSize);
Debug("SKEYID_a: %s\n", tmp);
// SKEYID_e
e_buf = MemToBuf(sa->SKEYID_a, sa->HashSize);
SeekBufToEnd(e_buf);
WriteBufBuf(e_buf, sa->DhSharedKey);
WriteBufInt64(e_buf, sa->InitiatorCookie);
WriteBufInt64(e_buf, sa->ResponderCookie);
u = 2;
WriteBuf(e_buf, &u, 1);
IkeHMac(h, sa->SKEYID_e, sa->SKEYID, sa->HashSize, e_buf->Buf, e_buf->Size);
BinToStrEx(tmp, sizeof(tmp), sa->SKEYID_e, sa->HashSize);
Debug("SKEYID_e: %s\n", tmp);
if (sa->CryptoKey != NULL)
{
IkeFreeKey(sa->CryptoKey);
}
sa->CryptoKey = IkeNewCryptoKeyFromK(ike, sa->SKEYID_e, sa->HashSize, sa->TransformSetting.Hash,
sa->TransformSetting.Crypto, sa->TransformSetting.CryptoKeySize);
// Release the memory
FreeBuf(secret_buf);
FreeBuf(rand_buf);
FreeBuf(d_buf);
FreeBuf(a_buf);
FreeBuf(e_buf);
}
// Extend the key size
BUF *IkeExpandKeySize(IKE_HASH *h, void *k, UINT k_size, UINT target_size)
{
BUF *b1, *b2;
UCHAR tmp[IKE_MAX_HASH_SIZE];
UINT tmp_size;
// Validate arguments
if (h == NULL || k == NULL || k_size == 0)
{
return NULL;
}
if (k_size >= target_size)
{
return MemToBuf(k, target_size);
}
tmp[0] = 0;
tmp_size = 1;
b1 = NewBuf();
do
{
IkeHMac(h, tmp, k, k_size, tmp, tmp_size);
WriteBuf(b1, tmp, h->HashSize);
tmp_size = h->HashSize;
}
while (b1->Size < target_size);
b2 = MemToBuf(b1->Buf, target_size);
FreeBuf(b1);
return b2;
}
// Generate a key from K
IKE_CRYPTO_KEY *IkeNewCryptoKeyFromK(IKE_SERVER *ike, void *k, UINT k_size, IKE_HASH *h, IKE_CRYPTO *c, UINT crypto_key_size)
{
BUF *key_buf;
IKE_CRYPTO_KEY *ret;
// Validate arguments
if (ike == NULL || k == NULL || k_size == 0 || h == NULL || c == NULL || crypto_key_size == 0)
{
return NULL;
}
key_buf = IkeExpandKeySize(h, k, k_size, crypto_key_size);
if (key_buf == NULL)
{
return NULL;
}
ret = IkeNewKey(c, key_buf->Buf, key_buf->Size);
FreeBuf(key_buf);
return ret;
}
// Generate a hash for NAT detection
BUF *IkeCalcNatDetectHash(IKE_SERVER *ike, IKE_HASH *hash, UINT64 initiator_cookie, UINT64 responder_cookie, IP *ip, UINT port)
{
BUF *b;
USHORT us;
USHORT hash_data[IKE_MAX_HASH_SIZE];
// Validate arguments
if (ike == NULL || ip == NULL || hash == NULL)
{
return NewBuf();
}
b = NewBuf();
WriteBufInt64(b, initiator_cookie);
WriteBufInt64(b, responder_cookie);
if (IsIP6(ip))
{
WriteBuf(b, ip->ipv6_addr, sizeof(ip->ipv6_addr));
}
else
{
WriteBuf(b, ip->addr, sizeof(ip->addr));
}
us = Endian16((USHORT)port);
WriteBuf(b, &us, sizeof(USHORT));
IkeHash(hash, hash_data, b->Buf, b->Size);
FreeBuf(b);
return MemToBuf(hash_data, hash->HashSize);
}
// Check the capacity of the opposite IPsec client
void IkeCheckCaps(IKE_CAPS *caps, IKE_PACKET *p)
{
// Validate arguments
if (caps == NULL || p == NULL)
{
Zero(caps, sizeof(IKE_CAPS));
return;
}
Zero(caps, sizeof(IKE_CAPS));
caps->NatTraversalRfc3947 = IkeIsVendorIdExists(p, IKE_VENDOR_ID_RFC3947_NAT_T);
caps->NatTraversalDraftIetf = IkeIsVendorIdExists(p, IKE_VENDOR_ID_IPSEC_NAT_T_IKE_03) ||
IkeIsVendorIdExists(p, IKE_VENDOR_ID_IPSEC_NAT_T_IKE_02) ||
IkeIsVendorIdExists(p, IKE_VENDOR_ID_IPSEC_NAT_T_IKE_02_2) ||
IkeIsVendorIdExists(p, IKE_VENDOR_ID_IPSEC_NAT_T_IKE_00);
caps->DpdRfc3706 = IkeIsVendorIdExists(p, IKE_VENDOR_ID_RFC3706_DPD);
caps->MS_L2TPIPSecVPNClient = IkeIsVendorIdExists(p, IKE_VENDOR_ID_MICROSOFT_L2TP);
caps->MS_NT5_ISAKMP_OAKLEY = IkeIsVendorIdExists(p, IKE_VENDOR_ID_MS_NT5_ISAKMPOAKLEY);
caps->MS_Vid_InitialContact = IkeIsVendorIdExists(p, IKE_VENDOR_ID_MS_VID_INITIALCONTACT);
}
// Check whether the specified vendor ID is contained in the packet
bool IkeIsVendorIdExists(IKE_PACKET *p, char *str)
{
BUF *buf;
UINT i, num;
bool ok = false;
// Validate arguments
if (p == NULL || str == NULL)
{
return false;
}
buf = IkeStrToVendorId(str);
if (buf == NULL)
{
return false;
}
num = IkeGetPayloadNum(p->PayloadList, IKE_PAYLOAD_VENDOR_ID);
for (i = 0;i < num;i++)
{
IKE_PACKET_PAYLOAD *payload = IkeGetPayload(p->PayloadList, IKE_PAYLOAD_VENDOR_ID, i);
if (payload == NULL)
{
break;
}
if (CompareBuf(payload->Payload.VendorId.Data, buf))
{
ok = true;
}
else
{
if (payload->Payload.VendorId.Data != NULL)
{
if (payload->Payload.VendorId.Data->Size >= buf->Size)
{
if (Cmp(payload->Payload.VendorId.Data->Buf, buf->Buf, buf->Size) == 0)
{
ok = true;
}
}
}
}
}
FreeBuf(buf);
return ok;
}
// Add the vendor ID payload list
void IkeAddVendorIdPayloads(IKE_PACKET *p)
{
// Validate arguments
if (p == NULL)
{
return;
}
IkeAddVendorId(p, IKE_VENDOR_ID_RFC3947_NAT_T);
IkeAddVendorId(p, IKE_VENDOR_ID_IPSEC_NAT_T_IKE_03);
IkeAddVendorId(p, IKE_VENDOR_ID_IPSEC_NAT_T_IKE_02);
IkeAddVendorId(p, IKE_VENDOR_ID_IPSEC_NAT_T_IKE_02_2);
IkeAddVendorId(p, IKE_VENDOR_ID_IPSEC_NAT_T_IKE_00);
IkeAddVendorId(p, IKE_VENDOR_ID_RFC3706_DPD);
}
// Add the vendor ID payload
void IkeAddVendorId(IKE_PACKET *p, char *str)
{
BUF *buf;
IKE_PACKET_PAYLOAD *payload;
// Validate arguments
if (p == NULL || str == NULL)
{
return;
}
buf = IkeStrToVendorId(str);
if (buf == NULL)
{
return;
}
payload = IkeNewDataPayload(IKE_PAYLOAD_VENDOR_ID, buf->Buf, buf->Size);
Add(p->PayloadList, payload);
FreeBuf(buf);
}
// Convert string to the vendor ID
BUF *IkeStrToVendorId(char *str)
{
// Validate arguments
if (IsEmptyStr(str))
{
return NULL;
}
if (StartWith(str, "0x"))
{
BUF *buf = StrToBin(str + 2);
if (buf == NULL || buf->Size == 0)
{
FreeBuf(buf);
return NULL;
}
return buf;
}
else
{
BUF *buf;
UCHAR hash[MD5_SIZE];
Hash(hash, str, StrLen(str), false);
buf = MemToBuf(hash, sizeof(hash));
return buf;
}
}
// Receive a packet using the IKE SA
IKE_PACKET *IkeSaRecvPacket(IKE_SERVER *ike, IKE_SA *sa, void *data, UINT size)
{
IKE_PACKET *ret;
// Validate arguments
if (ike == NULL || sa == NULL || (size != 0 && data == NULL))
{
return NULL;
}
if (sa->IsIvExisting == false || sa->CryptoKey == NULL)
{
ret = IkeParse(data, size, NULL);
}
else
{
IKE_CRYPTO_PARAM cp;
Copy(&cp.Iv, sa->Iv, sa->BlockSize);
cp.Key = sa->CryptoKey;
ret = IkeParse(data, size, &cp);
if (ret->FlagEncrypted)
{
IkeSaUpdateIv(sa, cp.NextIv, sa->BlockSize);
}
}
return ret;
}
// Receive a packet using IPsec SA (Quick Mode received)
IKE_PACKET *IPsecSaRecvPacket(IKE_SERVER *ike, IPSECSA *sa, void *data, UINT size)
{
IKE_PACKET *ret;
// Validate arguments
if (ike == NULL || sa == NULL || (size != 0 && data == NULL))
{
return NULL;
}
if (sa->IsIvExisting == false || sa->IkeSa->CryptoKey == NULL)
{
ret = IkeParse(data, size, NULL);
}
else
{
IKE_CRYPTO_PARAM cp;
Copy(&cp.Iv, sa->Iv, sa->IkeSa->BlockSize);
cp.Key = sa->IkeSa->CryptoKey;
ret = IkeParse(data, size, &cp);
if (ret->FlagEncrypted)
{
IPsecSaUpdateIv(sa, cp.NextIv, sa->IkeSa->BlockSize);
IPsecSaUpdateIv(sa->PairIPsecSa, cp.NextIv, sa->IkeSa->BlockSize);
}
}
return ret;
}
// Send a packet using IPsec SA (Quick Mode transmission)
void IPsecSaSendPacket(IKE_SERVER *ike, IPSECSA *sa, IKE_PACKET *p)
{
BUF *buf;
// Validate arguments
if (ike == NULL || sa == NULL)
{
return;
}
if (p == NULL)
{
FreeBuf(sa->SendBuffer);
sa->SendBuffer = NULL;
sa->NextSendTick = 0;
return;
}
// Build a packet
if (p->FlagEncrypted == false)
{
buf = IkeBuild(p, NULL);
}
else
{
IKE_CRYPTO_PARAM cp;
Copy(cp.Iv, sa->Iv, sa->IkeSa->BlockSize);
cp.Key = sa->IkeSa->CryptoKey;
buf = IkeBuild(p, &cp);
IPsecSaUpdateIv(sa, cp.NextIv, sa->IkeSa->BlockSize);
IPsecSaUpdateIv(sa->PairIPsecSa, cp.NextIv, sa->IkeSa->BlockSize);
}
if (buf == NULL)
{
return;
}
// Register the last packet to re-transmit
if (sa->SendBuffer != NULL)
{
FreeBuf(sa->SendBuffer);
}
sa->SendBuffer = CloneBuf(buf);
sa->NextSendTick = ike->Now + (UINT64)(IKE_SA_RESEND_INTERVAL);
AddInterrupt(ike->Interrupts, sa->NextSendTick);
IkeSendUdpPacket(ike, IKE_UDP_TYPE_ISAKMP, &sa->IkeClient->ServerIP, sa->IkeClient->ServerPort,
&sa->IkeClient->ClientIP, sa->IkeClient->ClientPort,
Clone(buf->Buf, buf->Size), buf->Size);
FreeBuf(buf);
}
// Send a packet using the IKE SA
void IkeSaSendPacket(IKE_SERVER *ike, IKE_SA *sa, IKE_PACKET *p)
{
BUF *buf;
// Validate arguments
if (ike == NULL || sa == NULL)
{
return;
}
if (p == NULL)
{
FreeBuf(sa->SendBuffer);
sa->SendBuffer = NULL;
sa->NextSendTick = 0;
return;
}
// Build a packet
if (p->FlagEncrypted == false)
{
buf = IkeBuild(p, NULL);
}
else
{
IKE_CRYPTO_PARAM cp;
Copy(cp.Iv, sa->Iv, sa->BlockSize);
cp.Key = sa->CryptoKey;
buf = IkeBuild(p, &cp);
IkeSaUpdateIv(sa, cp.NextIv, sa->BlockSize);
}
if (buf == NULL)
{
return;
}
if (p->ExchangeType != IKE_EXCHANGE_TYPE_INFORMATION)
{
// Register the last packet to re-transmit
if (sa->SendBuffer != NULL)
{
FreeBuf(sa->SendBuffer);
}
sa->SendBuffer = CloneBuf(buf);
sa->NextSendTick = ike->Now + (UINT64)(IKE_SA_RESEND_INTERVAL);
AddInterrupt(ike->Interrupts, sa->NextSendTick);
}
IkeSendUdpPacket(ike, IKE_UDP_TYPE_ISAKMP, &sa->IkeClient->ServerIP, sa->IkeClient->ServerPort,
&sa->IkeClient->ClientIP, sa->IkeClient->ClientPort,
Clone(buf->Buf, buf->Size), buf->Size);
FreeBuf(buf);
}
// Send an UDP packet
void IkeSendUdpPacket(IKE_SERVER *ike, UINT type, IP *server_ip, UINT server_port, IP *client_ip, UINT client_port, void *data, UINT size)
{
UDPPACKET *p;
// Validate arguments
if (ike == NULL || server_ip == NULL || client_ip == NULL || server_port == 0 || client_port == 0 || data == NULL || size == 0)
{
return;
}
p = NewUdpPacket(server_ip, server_port, client_ip, client_port, data, size);
p->Type = type;
Add(ike->SendPacketList, p);
}
// Create an IKE SA
IKE_SA *NewIkeSa(IKE_SERVER *ike, IKE_CLIENT *c, UINT64 init_cookie, UINT mode, IKE_SA_TRANSFORM_SETTING *setting)
{
IKE_SA *sa;
// Validate arguments
if (ike == NULL || c == NULL || init_cookie == 0 || setting == NULL)
{
return NULL;
}
sa = ZeroMalloc(sizeof(IKE_SA));
sa->Id = ++ike->CurrentIkeSaId;
sa->IkeClient = c;
sa->InitiatorCookie = init_cookie;
sa->ResponderCookie = GenerateNewResponserCookie(ike);
sa->Mode = mode;
sa->FirstCommTick = sa->LastCommTick = ike->Now;
Copy(&sa->TransformSetting, setting, sizeof(IKE_SA_TRANSFORM_SETTING));
Debug("New IKE SA (Mode = %u): %I64u <--> %I64u (%s %s %s(%u) %u %u)\n",
mode,
sa->InitiatorCookie,
sa->ResponderCookie,
setting->Dh->Name, setting->Hash->Name, setting->Crypto->Name, setting->CryptoKeySize,
setting->LifeKilobytes, setting->LifeSeconds);
IPsecLog(ike, NULL, sa, NULL, "LI_NEW_IKE_SA",
(mode == IKE_SA_MAIN_MODE ? _UU("LI_TAG_MAINMODE") : _UU("LI_TAG_AGGRESSIVE")),
sa->InitiatorCookie, sa->ResponderCookie,
setting->Dh->Name, setting->Hash->Name, setting->Crypto->Name, setting->CryptoKeySize * 8,
setting->LifeKilobytes, setting->LifeSeconds);
return sa;
}
// Search an IKE SA from the Responder Cookie
IKE_SA *FindIkeSaByResponderCookie(IKE_SERVER *ike, UINT64 responder_cookie)
{
IKE_SA t;
// Validate arguments
if (ike == NULL || responder_cookie == 0)
{
return NULL;
}
t.ResponderCookie = responder_cookie;
return Search(ike->IkeSaList, &t);
}
// Search an IKE SA from the Responder Cookie and the IKE_CLIENT
IKE_SA *FindIkeSaByResponderCookieAndClient(IKE_SERVER *ike, UINT64 responder_cookie, IKE_CLIENT *c)
{
IKE_SA *sa;
// Validate arguments
if (ike == NULL || responder_cookie == 0 || c == NULL)
{
return NULL;
}
sa = FindIkeSaByResponderCookie(ike, responder_cookie);
if (sa == NULL)
{
return NULL;
}
if (sa->IkeClient != c)
{
return NULL;
}
return sa;
}
// Search an IKE SA from the endpoint and the Initiator Cookie
IKE_SA *FindIkeSaByEndPointAndInitiatorCookie(IKE_SERVER *ike, IP *client_ip, UINT client_port, IP *server_ip, UINT server_port, UINT64 init_cookie, UINT mode)
{
UINT i;
// Validate arguments
if (ike == NULL || client_ip == NULL || server_ip == NULL || client_port == 0 || server_port == 0 || init_cookie == 0)
{
return NULL;
}
for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
{
IKE_SA *sa = LIST_DATA(ike->IkeSaList, i);
IKE_CLIENT *c;
c = sa->IkeClient;
if (CmpIpAddr(&c->ClientIP, client_ip) == 0 &&
CmpIpAddr(&c->ServerIP, server_ip) == 0 &&
c->ClientPort == client_port &&
c->ServerPort == server_port &&
sa->InitiatorCookie == init_cookie &&
sa->Mode == mode)
{
return sa;
}
}
return NULL;
}
// Get the number of IPsec SA that is associated with the IKE_CLIENT
UINT GetNumberOfIPsecSaOfIkeClient(IKE_SERVER *ike, IKE_CLIENT *c)
{
UINT num = 0, i;
// Validate arguments
if (ike == NULL || c == NULL)
{
return 0;
}
for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
{
IPSECSA *sa = LIST_DATA(ike->IPsecSaList, i);
if (sa->IkeClient == c)
{
num++;
}
}
return num;
}
// Get the number of IKE SA that is associated with the IKE_CLIENT
UINT GetNumberOfIkeSaOfIkeClient(IKE_SERVER *ike, IKE_CLIENT *c)
{
UINT num = 0, i;
// Validate arguments
if (ike == NULL || c == NULL)
{
return 0;
}
for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
{
IKE_SA *sa = LIST_DATA(ike->IkeSaList, i);
if (sa->IkeClient == c)
{
num++;
}
}
return num;
}
// Get the number of clients that are connected from the specified IP address
UINT GetNumberOfIkeClientsFromIP(IKE_SERVER *ike, IP *client_ip)
{
UINT i, num;
// Validate arguments
if (ike == NULL || client_ip == NULL)
{
return 0;
}
num = 0;
for (i = 0;i < LIST_NUM(ike->ClientList);i++)
{
IKE_CLIENT *c = LIST_DATA(ike->ClientList, i);
if (CmpIpAddr(&c->ClientIP, client_ip) == 0)
{
num++;
}
}
return num;
}
// Find the appropriate IKE client. Create if it is absent
IKE_CLIENT *SearchOrCreateNewIkeClientForIkePacket(IKE_SERVER *ike, IP *client_ip, UINT client_port, IP *server_ip, UINT server_port, IKE_PACKET *pr)
{
IKE_CLIENT *c;
// Validate arguments
if (ike == NULL || pr == NULL || client_ip == NULL || server_ip == NULL || client_port == 0 || server_port == 0 || pr == NULL)
{
return NULL;
}
c = SearchIkeClientForIkePacket(ike, client_ip, client_port, server_ip, server_port, pr);
if (c == NULL)
{
if (GetNumberOfIkeClientsFromIP(ike, client_ip) > IKE_QUOTA_MAX_NUM_CLIENTS_PER_IP ||
LIST_NUM(ike->ClientList) > IKE_QUOTA_MAX_NUM_CLIENTS)
{
return NULL;
}
c = NewIkeClient(ike, client_ip, client_port, server_ip, server_port);
Insert(ike->ClientList, c);
}
return SetIkeClientEndpoint(ike, c, client_ip, client_port, server_ip, server_port);
}
// Create an IKE client
IKE_CLIENT *NewIkeClient(IKE_SERVER *ike, IP *client_ip, UINT client_port, IP *server_ip, UINT server_port)
{
IKE_CLIENT *c;
char client_ip_str[MAX_SIZE];
char server_ip_str[MAX_SIZE];
// Validate arguments
if (ike == NULL || client_ip == NULL || server_ip == NULL || client_port == 0 || server_port == 0)
{
return NULL;
}
c = ZeroMalloc(sizeof(IKE_CLIENT));
c->Id = ++ike->CurrentIkeClientId;
Copy(&c->ClientIP, client_ip, sizeof(IP));
c->ClientPort = client_port;
Copy(&c->ServerIP, server_ip, sizeof(IP));
Copy(&c->TransportModeServerIP, server_ip, sizeof(IP));
Copy(&c->TransportModeClientIP, client_ip, sizeof(IP));
c->ServerPort = server_port;
c->LastCommTick = ike->Now;
c->FirstCommTick = ike->Now;
IPToStr(client_ip_str, sizeof(client_ip_str), client_ip);
IPToStr(server_ip_str, sizeof(server_ip_str), server_ip);
Debug("New IKE_CLIENT: %p: %s:%u -> %s:%u\n", c, client_ip_str, client_port, server_ip_str, server_port);
IPsecLog(ike, c, NULL, NULL, "LI_NEW_IKE_CLIENT");
return c;
}
// Search for the best associated IKE client when an IKE packet has been received
IKE_CLIENT *SearchIkeClientForIkePacket(IKE_SERVER *ike, IP *client_ip, UINT client_port, IP *server_ip, UINT server_port, IKE_PACKET *pr)
{
IKE_CLIENT t;
IKE_CLIENT *c = NULL;
// Validate arguments
if (ike == NULL || pr == NULL || client_ip == NULL || server_ip == NULL || client_port == 0 || server_port == 0)
{
return NULL;
}
if (true)
{
UINT i;
if (pr->InitiatorCookie != 0 && pr->ResponderCookie != 0)
{
for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
{
IKE_SA *sa = LIST_DATA(ike->IkeSaList, i);
// Extract what Cookie matches exactly
if (sa->InitiatorCookie == pr->InitiatorCookie && sa->ResponderCookie == pr->ResponderCookie)
{
IKE_CLIENT *cc = sa->IkeClient;
if (CmpIpAddr(&cc->ServerIP, server_ip) == 0 &&
CmpIpAddr(&cc->ClientIP, client_ip) == 0)
{
c = cc;
break;
}
}
}
}
}
if (c == NULL)
{
// Search by a pair of IP address and port number
Copy(&t.ClientIP, client_ip, sizeof(IP));
t.ClientPort = client_port;
Copy(&t.ServerIP, server_ip, sizeof(IP));
t.ServerPort = server_port;
c = Search(ike->ClientList, &t);
if (c != NULL)// && server_port == IPSEC_PORT_IPSEC_ISAKMP)
{
// Search that the IKE_SA that points to this IKE_CLIENT exists and match the Cookie
bool ok = false;
UINT i;
if (server_port == IPSEC_PORT_IPSEC_ESP_UDP)
{
// Regard as OK if the port number exactly match in the case of connecting to a server-side 4500
ok = true;
}
else
{
if (c->CurrentIkeSa != NULL &&
c->CurrentIkeSa->InitiatorCookie == pr->InitiatorCookie &&
c->CurrentIkeSa->ResponderCookie == pr->ResponderCookie)
{
ok = true;
}
else
{
for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
{
IKE_SA *sa = LIST_DATA(ike->IkeSaList, i);
if (sa->IkeClient == c)
{
if (sa->InitiatorCookie == pr->InitiatorCookie &&
sa->ResponderCookie == pr->ResponderCookie)
{
ok = true;
break;
}
}
}
}
}
if (ok == false)
{
// Not found
c = NULL;
}
}
}
return c;
}
// Comparison of IPsec SA
int CmpIPsecSa(void *p1, void *p2)
{
IPSECSA *sa1, *sa2;
int r;
// Validate arguments
if (p1 == NULL || p2 == NULL)
{
return 0;
}
sa1 = *(IPSECSA **)p1;
sa2 = *(IPSECSA **)p2;
if (sa1 == NULL || sa2 == NULL)
{
return 0;
}
r = COMPARE_RET(sa1->ServerToClient, sa2->ServerToClient);
if (r != 0)
{
return r;
}
r = COMPARE_RET(sa1->Spi, sa2->Spi);
return r;
}
// Comparison of IKE_SA
int CmpIkeSa(void *p1, void *p2)
{
IKE_SA *sa1, *sa2;
int r;
// Validate arguments
if (p1 == NULL || p2 == NULL)
{
return 0;
}
sa1 = *(IKE_SA **)p1;
sa2 = *(IKE_SA **)p2;
if (sa1 == NULL || sa2 == NULL)
{
return 0;
}
r = COMPARE_RET(sa1->ResponderCookie, sa2->ResponderCookie);
return r;
}
// Comparison of IKE_CLIENT
int CmpIkeClient(void *p1, void *p2)
{
IKE_CLIENT *c1, *c2;
int r;
// Validate arguments
if (p1 == NULL || p2 == NULL)
{
return 0;
}
c1 = *(IKE_CLIENT **)p1;
c2 = *(IKE_CLIENT **)p2;
if (c1 == NULL || c2 == NULL)
{
return 0;
}
r = CmpIpAddr(&c1->ClientIP, &c2->ClientIP);
if (r != 0)
{
return r;
}
r = CmpIpAddr(&c1->ServerIP, &c2->ServerIP);
if (r != 0)
{
return r;
}
r = COMPARE_RET(c1->ClientPort, c2->ClientPort);
if (r != 0)
{
return r;
}
r = COMPARE_RET(c1->ServerPort, c2->ServerPort);
if (r != 0)
{
return r;
}
return 0;
}
// Update the endpoint information of IKE_CLIENT
IKE_CLIENT *SetIkeClientEndpoint(IKE_SERVER *ike, IKE_CLIENT *c, IP *client_ip, UINT client_port, IP *server_ip, UINT server_port)
{
char client_ip_str[MAX_SIZE];
char server_ip_str[MAX_SIZE];
IKE_CLIENT *ret = c;
IKE_CLIENT *cc;
IKE_CLIENT t;
// Validate arguments
if (ike == NULL || c == NULL || client_ip == NULL || client_port == 0 || server_ip == NULL || server_port == 0)
{
return NULL;
}
if (CmpIpAddr(&c->ClientIP, client_ip) == 0 &&
CmpIpAddr(&c->ServerIP, server_ip) == 0 &&
c->ClientPort == client_port &&
c->ServerPort == server_port)
{
// No change
return ret;
}
if (IS_SPECIAL_PORT(client_port) || IS_SPECIAL_PORT(server_port))
{
// Don't change in the case of Raw socket
return ret;
}
// Search for an existing IKE_CLIENT which exactly matches to combination of the new IP address and the port number
Copy(&t.ClientIP, client_ip, sizeof(IP));
t.ClientPort = client_port;
Copy(&t.ServerIP, server_ip, sizeof(IP));
t.ServerPort = server_port;
cc = Search(ike->ClientList, &t);
if (cc != NULL && c != cc && cc->Deleting == false && c->L2TP == NULL)
{
UINT i;
// Merge into this existing IKE_CLIENT since it found
for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
{
IKE_SA *sa = LIST_DATA(ike->IkeSaList, i);
if (sa->IkeClient == c)
{
sa->IkeClient = cc;
}
}
for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
{
IPSECSA *sa = LIST_DATA(ike->IPsecSaList, i);
if (sa->IkeClient == c)
{
sa->IkeClient = cc;
}
}
if (cc->LastCommTick < c->LastCommTick)
{
StrCpy(cc->ClientId, sizeof(cc->ClientId), c->ClientId);
}
cc->FirstCommTick = MIN(cc->FirstCommTick, c->FirstCommTick);
cc->LastCommTick = MAX(cc->LastCommTick, c->LastCommTick);
ret = cc;
IPToStr(client_ip_str, sizeof(client_ip_str), client_ip);
IPToStr(server_ip_str, sizeof(server_ip_str), server_ip);
Debug("Merge IKE_CLIENT: %p->%p: %s:%u -> %s:%u\n", c, cc, client_ip_str, client_port, server_ip_str, server_port);
IPsecLog(ike, c, NULL, NULL, "LI_CLIENT_MERGE", c->Id, cc->Id, cc->Id);
// Remove old IKE_CLIENT from the list and free
Delete(ike->ClientList, c);
FreeIkeClient(ike, c);
}
else
{
// Rewrite the end point information of this IKE_CLIENT because not found
Copy(&c->ClientIP, client_ip, sizeof(IP));
Copy(&c->ServerIP, server_ip, sizeof(IP));
c->ClientPort = client_port;
c->ServerPort = server_port;
IPToStr(client_ip_str, sizeof(client_ip_str), client_ip);
IPToStr(server_ip_str, sizeof(server_ip_str), server_ip);
Debug("Update IKE_CLIENT: %p: %s:%u -> %s:%u\n", c, client_ip_str, client_port, server_ip_str, server_port);
IPsecLog(ike, c, NULL, NULL, "LI_CLIENT_UPDATE");
ike->ClientList->sorted = false;
}
return ret;
}
// Select the optimal transform setting for IPsec SA
bool GetBestTransformSettingForIPsecSa(IKE_SERVER *ike, IKE_PACKET *pr, IPSEC_SA_TRANSFORM_SETTING *setting, IP *server_ip)
{
IKE_PACKET_PAYLOAD *sa_payload;
IKE_PACKET_SA_PAYLOAD *sa;
UINT i, num;
bool ocmii_flag = false;
// Validate arguments
if (ike == NULL || pr == NULL || setting == NULL || server_ip == NULL)
{
return false;
}
Zero(setting, sizeof(IPSEC_SA_TRANSFORM_SETTING));
// Get the SA payload
sa_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_SA, 0);
if (sa_payload == NULL)
{
return false;
}
sa = &sa_payload->Payload.Sa;
// Scan all proposal payloads
num = IkeGetPayloadNum(sa->PayloadList, IKE_PAYLOAD_PROPOSAL);
for (i = 0;i < num;i++)
{
IKE_PACKET_PAYLOAD *proposal_payload = IkeGetPayload(sa->PayloadList, IKE_PAYLOAD_PROPOSAL, i);
if (proposal_payload != NULL)
{
IKE_PACKET_PROPOSAL_PAYLOAD *proposal = &proposal_payload->Payload.Proposal;
// Examine the contents of the proposal payload
if (proposal->ProtocolId == IKE_PROTOCOL_ID_IPSEC_ESP && proposal->Spi->Size == 4)
{
// Scan all transform payloads
UINT j, num2;
num2 = IkeGetPayloadNum(proposal->PayloadList, IKE_PAYLOAD_TRANSFORM);
for (j = 0;j < num2;j++)
{
IKE_PACKET_PAYLOAD *transform_payload = IkeGetPayload(proposal->PayloadList, IKE_PAYLOAD_TRANSFORM, j);
if (transform_payload != NULL)
{
IKE_PACKET_TRANSFORM_PAYLOAD *transform = &transform_payload->Payload.Transform;
IPSEC_SA_TRANSFORM_SETTING set;
Zero(&set, sizeof(set));
if (TransformPayloadToTransformSettingForIPsecSa(ike, transform, &set, server_ip))
{
Copy(setting, &set, sizeof(IPSEC_SA_TRANSFORM_SETTING));
setting->SpiServerToClient = READ_UINT(proposal->Spi->Buf);
return true;
}
else
{
if (set.OnlyCapsuleModeIsInvalid)
{
if (ocmii_flag == false)
{
Copy(setting, &set, sizeof(IPSEC_SA_TRANSFORM_SETTING));
ocmii_flag = true;
}
}
}
}
}
}
}
}
return false;
}
// Select the optimal transform settings for the IKE SA
bool GetBestTransformSettingForIkeSa(IKE_SERVER *ike, IKE_PACKET *pr, IKE_SA_TRANSFORM_SETTING *setting)
{
IKE_PACKET_PAYLOAD *sa_payload;
IKE_PACKET_SA_PAYLOAD *sa;
UINT i, num;
// Validate arguments
if (ike == NULL || pr == NULL || setting == NULL)
{
return false;
}
// Get the SA payload
sa_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_SA, 0);
if (sa_payload == NULL)
{
return false;
}
sa = &sa_payload->Payload.Sa;
// Scan all proposal payloads
num = IkeGetPayloadNum(sa->PayloadList, IKE_PAYLOAD_PROPOSAL);
for (i = 0;i < num;i++)
{
IKE_PACKET_PAYLOAD *proposal_payload = IkeGetPayload(sa->PayloadList, IKE_PAYLOAD_PROPOSAL, i);
if (proposal_payload != NULL)
{
IKE_PACKET_PROPOSAL_PAYLOAD *proposal = &proposal_payload->Payload.Proposal;
// Examine the contents of the proposal payload
if (proposal->ProtocolId == IKE_PROTOCOL_ID_IKE)
{
// Scan all transform payloads
UINT j, num2;
num2 = IkeGetPayloadNum(proposal->PayloadList, IKE_PAYLOAD_TRANSFORM);
for (j = 0;j < num2;j++)
{
IKE_PACKET_PAYLOAD *transform_payload = IkeGetPayload(proposal->PayloadList, IKE_PAYLOAD_TRANSFORM, j);
if (transform_payload != NULL)
{
IKE_PACKET_TRANSFORM_PAYLOAD *transform = &transform_payload->Payload.Transform;
if (transform->TransformId == IKE_TRANSFORM_ID_P1_KEY_IKE)
{
IKE_SA_TRANSFORM_SETTING set;
if (TransformPayloadToTransformSettingForIkeSa(ike, transform, &set))
{
Copy(setting, &set, sizeof(IKE_SA_TRANSFORM_SETTING));
return true;
}
}
}
}
}
}
}
return false;
}
// Convert a structure to the transform payload (for IPsec SA)
IKE_PACKET_PAYLOAD *TransformSettingToTransformPayloadForIPsec(IKE_SERVER *ike, IPSEC_SA_TRANSFORM_SETTING *setting)
{
LIST *value_list;
// Validate arguments
if (ike == NULL || setting == NULL)
{
return NULL;
}
value_list = NewListFast(NULL);
Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P2_HMAC, setting->HashId));
if (setting->Dh != NULL)
{
Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P2_DH_GROUP, setting->DhId));
}
if (setting->LifeSeconds != INFINITE)
{
Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P2_LIFE_TYPE, IKE_P2_LIFE_TYPE_SECONDS));
Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P2_LIFE_VALUE, setting->LifeSeconds));
}
if (setting->LifeKilobytes != INFINITE)
{
Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P2_LIFE_TYPE, IKE_P2_LIFE_TYPE_KILOBYTES));
Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P2_LIFE_VALUE, setting->LifeKilobytes));
}
if (setting->Crypto->VariableKeySize)
{
Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P2_KEY_SIZE, setting->CryptoKeySize * 8));
}
Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P2_CAPSULE, setting->CapsuleMode));
return IkeNewTransformPayload(1, setting->CryptoId, value_list);
}
// Convert a structure to the transform payload (for IKE SA)
IKE_PACKET_PAYLOAD *TransformSettingToTransformPayloadForIke(IKE_SERVER *ike, IKE_SA_TRANSFORM_SETTING *setting)
{
LIST *value_list;
// Validate arguments
if (ike == NULL || setting == NULL)
{
return NULL;
}
value_list = NewListFast(NULL);
Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P1_CRYPTO, setting->CryptoId));
Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P1_HASH, setting->HashId));
Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P1_AUTH_METHOD, IKE_P1_AUTH_METHOD_PRESHAREDKEY));
Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P1_DH_GROUP, setting->DhId));
if (setting->LifeSeconds != INFINITE)
{
Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P1_LIFE_TYPE, IKE_P1_LIFE_TYPE_SECONDS));
Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P1_LIFE_VALUE, setting->LifeSeconds));
}
if (setting->LifeKilobytes != INFINITE)
{
Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P1_LIFE_TYPE, IKE_P1_LIFE_TYPE_KILOBYTES));
Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P1_LIFE_VALUE, setting->LifeKilobytes));
}
if (setting->Crypto->VariableKeySize)
{
Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P1_KET_SIZE, setting->CryptoKeySize * 8));
}
return IkeNewTransformPayload(1, IKE_TRANSFORM_ID_P1_KEY_IKE, value_list);
}
// Convert a transform payload to a structure (for IPsec SA)
bool TransformPayloadToTransformSettingForIPsecSa(IKE_SERVER *ike, IKE_PACKET_TRANSFORM_PAYLOAD *transform, IPSEC_SA_TRANSFORM_SETTING *setting, IP *server_ip)
{
UINT i;
UINT capsule_mode;
bool is_esp_supported;
// Validate arguments
if (ike == NULL || transform == NULL || setting == NULL || server_ip == NULL)
{
return false;
}
is_esp_supported = IsUdpPortOpened(ike->IPsec->UdpListener, server_ip, IPSEC_PORT_IPSEC_ESP_RAW);
Zero(setting, sizeof(IPSEC_SA_TRANSFORM_SETTING));
setting->CryptoId = transform->TransformId;
setting->HashId = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P2_HMAC, 0);
setting->DhId = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P2_DH_GROUP, 0);
setting->LifeKilobytes = INFINITE;
setting->LifeSeconds = INFINITE;
for (i = 0;i < IkeGetTransformValueNum(transform, IKE_TRANSFORM_VALUE_P2_LIFE_TYPE);i++)
{
UINT life_type = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P2_LIFE_TYPE, i);
switch (life_type)
{
case IKE_P2_LIFE_TYPE_SECONDS: // Number of seconds
setting->LifeSeconds = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P2_LIFE_VALUE, i);
break;
case IKE_P2_LIFE_TYPE_KILOBYTES: // Kilobytes
setting->LifeKilobytes = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P2_LIFE_VALUE, i);
break;
default:
// Unsupported expiration type
return false;
}
}
setting->Crypto = GetIkeCrypto(ike->Engine, true, setting->CryptoId);
setting->Hash = GetIkeHash(ike->Engine, true, setting->HashId);
setting->Dh = GetIkeDh(ike->Engine, true, setting->DhId);
if (setting->Crypto == NULL || setting->Hash == NULL)
{
// Unsupported algorithm
return false;
}
if (setting->Crypto->VariableKeySize)
{
// Get the actual key size in the case of variable key size
setting->CryptoKeySize = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P2_KEY_SIZE, 0);
// bits -> bytes
setting->CryptoKeySize = setting->CryptoKeySize / 8;
if (setting->CryptoKeySize == 0 || IkeCheckKeySize(setting->Crypto, setting->CryptoKeySize) == false)
{
// The key size is not specified or inappropriate
return false;
}
}
else
{
// Get a fixed key length for fixed key size
setting->CryptoKeySize = setting->Crypto->KeySizes[0];
}
capsule_mode = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P2_CAPSULE, 0);
if (capsule_mode != IKE_P2_CAPSULE_NAT_TUNNEL_1 && capsule_mode != IKE_P2_CAPSULE_NAT_TUNNEL_2 &&
capsule_mode != IKE_P2_CAPSULE_NAT_TRANSPORT_1 && capsule_mode != IKE_P2_CAPSULE_NAT_TRANSPORT_2)
{
// No support for UDP encapsulation mode except for the NAT-Traversal
if (capsule_mode == IKE_P2_CAPSULE_TRANSPORT || capsule_mode == IKE_P2_CAPSULE_TUNNEL)
{
if (is_esp_supported == false)
{
setting->OnlyCapsuleModeIsInvalid = true;
return false;
}
else
{
// It is an environment that can send and receive ESP packets
}
}
else
{
return false;
}
}
setting->CapsuleMode = capsule_mode;
return true;
}
// Convert a transform payload to a structure (for IKE SA)
bool TransformPayloadToTransformSettingForIkeSa(IKE_SERVER *ike, IKE_PACKET_TRANSFORM_PAYLOAD *transform, IKE_SA_TRANSFORM_SETTING *setting)
{
UINT i;
// Validate arguments
if (ike == NULL || transform == NULL || setting == NULL)
{
return false;
}
Zero(setting, sizeof(IKE_SA_TRANSFORM_SETTING));
setting->CryptoId = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P1_CRYPTO, 0);
setting->HashId = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P1_HASH, 0);
if (IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P1_AUTH_METHOD, 0) != IKE_P1_AUTH_METHOD_PRESHAREDKEY)
{
// Only PSK authentication method is supported
return false;
}
setting->DhId = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P1_DH_GROUP, 0);
setting->LifeKilobytes = INFINITE;
setting->LifeSeconds = INFINITE;
for (i = 0;i < IkeGetTransformValueNum(transform, IKE_TRANSFORM_VALUE_P1_LIFE_TYPE);i++)
{
UINT life_type = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P1_LIFE_TYPE, i);
switch (life_type)
{
case IKE_P1_LIFE_TYPE_SECONDS: // Number of seconds
setting->LifeSeconds = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P1_LIFE_VALUE, i);
break;
case IKE_P1_LIFE_TYPE_KILOBYTES: // Kilobytes
setting->LifeKilobytes = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P1_LIFE_VALUE, i);
break;
default:
// Unsupported expiration type
return false;
}
}
setting->Crypto = GetIkeCrypto(ike->Engine, false, setting->CryptoId);
setting->Hash = GetIkeHash(ike->Engine, false, setting->HashId);
setting->Dh = GetIkeDh(ike->Engine, false, setting->DhId);
if (setting->Crypto == NULL || setting->Hash == NULL || setting->Dh == NULL)
{
// Unsupported algorithm
return false;
}
if (setting->Crypto->VariableKeySize)
{
// Get the actual key size in the case of variable key size
setting->CryptoKeySize = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P1_KET_SIZE, 0);
// bits -> bytes
setting->CryptoKeySize = setting->CryptoKeySize / 8;
if (setting->CryptoKeySize == 0 || IkeCheckKeySize(setting->Crypto, setting->CryptoKeySize) == false)
{
// The key size is not specified or inappropriate
return false;
}
}
else
{
// Get a fixed key length for fixed key size
setting->CryptoKeySize = setting->Crypto->KeySizes[0];
}
return true;
}
// Creating a new Responder Cookie
UINT64 GenerateNewResponserCookie(IKE_SERVER *ike)
{
UINT64 c;
// Validate arguments
if (ike == NULL)
{
return 0;
}
while (true)
{
bool b = false;
UINT i;
c = Rand64();
for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
{
IKE_SA *sa = LIST_DATA(ike->IkeSaList, i);
if (sa->ResponderCookie == c)
{
b = true;
break;
}
}
if (b == false)
{
return c;
}
}
}
// Parse the IKE packet header
IKE_PACKET *ParseIKEPacketHeader(UDPPACKET *p)
{
// Validate arguments
if (p == NULL)
{
return NULL;
}
return IkeParseHeader(p->Data, p->Size, NULL);
}
// Search for another IPsec SA belonging to the IKE_CLIENT which have same conditions to the specified IPsec SA
IPSECSA *GetOtherLatestIPsecSa(IKE_SERVER *ike, IPSECSA *sa)
{
UINT i;
UINT64 min_value = 0;
IPSECSA *max_sa = NULL;
// Validate arguments
if (ike == NULL || sa == NULL)
{
return NULL;
}
if (sa->IkeClient == NULL)
{
return NULL;
}
for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
{
IPSECSA *sa2 = LIST_DATA(ike->IPsecSaList, i);
if (sa2 != sa)
{
if (sa2->IkeClient == sa->IkeClient)
{
if (sa2->ServerToClient == sa->ServerToClient)
{
if (sa2->Deleting == false)
{
if (sa2->Established)
{
UINT64 last_comm_tick = sa2->LastCommTick;
if (sa2->ServerToClient)
{
if (sa2->PairIPsecSa != NULL)
{
last_comm_tick = sa2->PairIPsecSa->LastCommTick;
}
}
if (min_value < last_comm_tick)
{
min_value = last_comm_tick;
max_sa = sa2;
}
}
}
}
}
}
}
return max_sa;
}
// Search for another IKE_SA belonging to the IKE_CLIENT which have same conditions to the specified IKE_SA
IKE_SA *GetOtherLatestIkeSa(IKE_SERVER *ike, IKE_SA *sa)
{
UINT i;
UINT64 min_value = 0;
IKE_SA *max_sa = NULL;
// Validate arguments
if (ike == NULL || sa == NULL)
{
return NULL;
}
if (sa->IkeClient == NULL)
{
return NULL;
}
for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
{
IKE_SA *sa2 = LIST_DATA(ike->IkeSaList, i);
if (sa2 != sa)
{
if (sa2->IkeClient == sa->IkeClient)
{
if (sa2->Deleting == false)
{
if (sa2->Established)
{
if (min_value < sa2->LastCommTick)
{
min_value = sa2->LastCommTick;
max_sa = sa2;
}
}
}
}
}
}
return max_sa;
}
// Purge the IPsec SA
void PurgeIPsecSa(IKE_SERVER *ike, IPSECSA *sa)
{
UINT i;
IPSECSA *other_sa;
// Validate arguments
if (ike == NULL || sa == NULL)
{
return;
}
other_sa = GetOtherLatestIPsecSa(ike, sa);
// Rewrite the pairing partner by looking for IPsec SA that are paired
for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
{
IPSECSA *sa2 = LIST_DATA(ike->IPsecSaList, i);
if (sa2->PairIPsecSa == sa)
{
sa2->PairIPsecSa = other_sa;
}
}
// Rewrite the IKE_CLIENT using this IPsec SA to use alternate
for (i = 0;i < LIST_NUM(ike->ClientList);i++)
{
IKE_CLIENT *c = LIST_DATA(ike->ClientList, i);
if (c->CurrentIpSecSaRecv == sa)
{
c->CurrentIpSecSaRecv = other_sa;
}
if (c->CurrentIpSecSaSend == sa)
{
c->CurrentIpSecSaSend = other_sa;
}
}
Delete(ike->IPsecSaList, sa);
FreeIPsecSa(sa);
}
// Remove the IKE SA
void PurgeIkeSa(IKE_SERVER *ike, IKE_SA *sa)
{
IKE_SA *other_sa;
UINT i;
// Validate arguments
if (ike == NULL || sa == NULL)
{
return;
}
Debug("Purging IKE SA %I64u-%I64u\n", sa->InitiatorCookie, sa->ResponderCookie);
// Rewrite to alternative IKE_SA of all IPsec SA that are using this IKE_SA
other_sa = GetOtherLatestIkeSa(ike, sa);
for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
{
IPSECSA *ipsec_sa = LIST_DATA(ike->IPsecSaList, i);
if (ipsec_sa->IkeSa == sa)
{
if (other_sa == NULL)
{
// Remove this IPsec SA because there is no alternative IKE_SA
Debug(" Deleting IPsec SA 0x%X of this IKE SA (no alternatives)\n", ipsec_sa->Spi);
MarkIPsecSaAsDeleted(ike, ipsec_sa);
ipsec_sa->IkeSa = NULL;
}
else
{
// Replace to the alternative IKE_SA
Debug(" Replacing IKE SA of IPsec SA 0x%X from %I64u-%I64u to %I64u-%I64u\n", ipsec_sa->Spi,
sa->InitiatorCookie, sa->ResponderCookie,
other_sa->InitiatorCookie, other_sa->ResponderCookie);
ipsec_sa->IkeSa = other_sa;
}
}
}
// Substitute the IKE_SA of all IKE_CLIENT that are using this IKE_SA with alternative
for (i = 0;i < LIST_NUM(ike->ClientList);i++)
{
IKE_CLIENT *c = LIST_DATA(ike->ClientList, i);
if (c->CurrentIkeSa == sa)
{
c->CurrentIkeSa = other_sa;
}
}
Delete(ike->IkeSaList, sa);
FreeIkeSa(sa);
}
// Purge the IKE_CLIENT
void PurgeIkeClient(IKE_SERVER *ike, IKE_CLIENT *c)
{
UINT i;
// Validate arguments
if (ike == NULL || c == NULL)
{
return;
}
// Delete all of IPsec SA and IKE SA that belong to this IKE Client
for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
{
IKE_SA *sa = LIST_DATA(ike->IkeSaList, i);
if (sa->IkeClient == c)
{
MarkIkeSaAsDeleted(ike, sa);
}
}
for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
{
IPSECSA *sa = LIST_DATA(ike->IPsecSaList, i);
if (sa->IkeClient == c)
{
MarkIPsecSaAsDeleted(ike, sa);
}
}
Delete(ike->ClientList, c);
FreeIkeClient(ike, c);
}
// Remove the SA that has been marked to delete
void PurgeDeletingSAsAndClients(IKE_SERVER *ike)
{
UINT i;
LIST *o = NULL;
// Validate arguments
if (ike == NULL)
{
return;
}
for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
{
IKE_SA *sa = LIST_DATA(ike->IkeSaList, i);
if (sa->Deleting)
{
if (o == NULL)
{
o = NewListFast(NULL);
}
Add(o, sa);
}
}
for (i = 0;i < LIST_NUM(o);i++)
{
IKE_SA *sa = LIST_DATA(o, i);
PurgeIkeSa(ike, sa);
}
ReleaseList(o);
o = NULL;
for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
{
IPSECSA *sa = LIST_DATA(ike->IPsecSaList, i);
if (sa->Deleting)
{
if (o == NULL)
{
o = NewListFast(NULL);
}
Add(o, sa);
}
}
for (i = 0;i < LIST_NUM(o);i++)
{
IPSECSA *sa = LIST_DATA(o, i);
PurgeIPsecSa(ike, sa);
}
ReleaseList(o);
o = NULL;
for (i = 0;i < LIST_NUM(ike->ClientList);i++)
{
IKE_CLIENT *c = LIST_DATA(ike->ClientList, i);
if (c->Deleting)
{
if (o == NULL)
{
o = NewListFast(NULL);
}
Add(o, c);
}
}
for (i = 0;i < LIST_NUM(o);i++)
{
IKE_CLIENT *c = LIST_DATA(o, i);
PurgeIkeClient(ike, c);
}
ReleaseList(o);
}
// IKE interrupt process
void ProcessIKEInterrupts(IKE_SERVER *ike)
{
UINT i;
// Validate arguments
if (ike == NULL)
{
return;
}
for (i = 0;i < LIST_NUM(ike->ClientList);i++)
{
IKE_CLIENT *c = LIST_DATA(ike->ClientList, i);
c->CurrentExpiresSoftTick_CtoS = 0;
c->CurrentExpiresSoftTick_StoC = 0;
c->CurrentNumEstablishedIPsecSA_CtoS = 0;
c->CurrentNumEstablishedIPsecSA_StoC = 0;
c->CurrentNumHealtyIPsecSA_CtoS = 0;
c->CurrentNumHealtyIPsecSA_StoC = 0;
}
// Packet retransmission by scanning all IKE SA
for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
{
IKE_SA *sa = LIST_DATA(ike->IkeSaList, i);
if (sa->SendBuffer != NULL)
{
if (ike->Now >= sa->NextSendTick)
{
IKE_CLIENT *c = sa->IkeClient;
IkeSendUdpPacket(ike, IKE_UDP_TYPE_ISAKMP, &c->ServerIP, c->ServerPort, &c->ClientIP, c->ClientPort,
Clone(sa->SendBuffer->Buf, sa->SendBuffer->Size), sa->SendBuffer->Size);
sa->NextSendTick += (UINT64)(IKE_SA_RESEND_INTERVAL);
AddInterrupt(ike->Interrupts, sa->NextSendTick);
if (sa->NumResends != 0)
{
sa->NumResends--;
if (sa->NumResends == 0)
{
sa->NextSendTick = 0;
FreeBuf(sa->SendBuffer);
sa->SendBuffer = NULL;
}
}
}
}
// Remove those of non-communication
if (sa->IkeClient == NULL || (sa->IkeClient->CurrentIkeSa != sa))
{
// When the IKE_CLIENT don't point this
if (sa->Established == false)
{
// Make time-out in a short time when it is not established
if ((sa->LastCommTick + (UINT64)IKE_TIMEOUT_FOR_IKE_CLIENT_FOR_NOT_ESTABLISHED) <= ike->Now)
{
WHERE;
MarkIkeSaAsDeleted(ike, sa);
}
}
else
{
// Timeout in a long time in the case of established
if ((sa->LastCommTick + (UINT64)IKE_TIMEOUT_FOR_IKE_CLIENT) <= ike->Now)
{
WHERE;
MarkIkeSaAsDeleted(ike, sa);
}
}
}
}
// Packet retransmission by scanning all IPsec SA
for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
{
IPSECSA *sa = LIST_DATA(ike->IPsecSaList, i);
IKE_CLIENT *c = sa->IkeClient;
if (sa->SendBuffer != NULL)
{
if (ike->Now >= sa->NextSendTick)
{
IKE_CLIENT *c = sa->IkeClient;
IkeSendUdpPacket(ike, IKE_UDP_TYPE_ISAKMP, &c->ServerIP, c->ServerPort, &c->ClientIP, c->ClientPort,
Clone(sa->SendBuffer->Buf, sa->SendBuffer->Size), sa->SendBuffer->Size);
sa->NextSendTick += (UINT64)(IKE_SA_RESEND_INTERVAL);
AddInterrupt(ike->Interrupts, sa->NextSendTick);
if (sa->NumResends != 0)
{
sa->NumResends--;
if (sa->NumResends == 0)
{
sa->NextSendTick = 0;
FreeBuf(sa->SendBuffer);
sa->SendBuffer = NULL;
}
}
}
}
if (sa->Established && sa->Deleting == false && c != NULL)
{
// Get the flexible expiration date of SA for each IKE_CLIENT
if (sa->ServerToClient)
{
c->CurrentExpiresSoftTick_StoC = MAX(c->CurrentExpiresSoftTick_StoC, sa->ExpiresSoftTick);
c->CurrentNumEstablishedIPsecSA_StoC++;
if (sa->ExpiresSoftTick == 0 || sa->ExpiresSoftTick > ike->Now)
{
c->CurrentNumHealtyIPsecSA_StoC++;
}
}
else
{
c->CurrentExpiresSoftTick_CtoS = MAX(c->CurrentExpiresSoftTick_CtoS, sa->ExpiresSoftTick);
c->CurrentNumEstablishedIPsecSA_CtoS++;
if (sa->ExpiresSoftTick == 0 || sa->ExpiresSoftTick > ike->Now)
{
c->CurrentNumHealtyIPsecSA_CtoS++;
}
}
}
// Remove those of non-communication
if (sa->IkeClient == NULL || (sa->IkeClient->CurrentIpSecSaRecv != sa && sa->IkeClient->CurrentIpSecSaSend != sa))
{
// When the IKE_CLIENT don't point this
UINT64 last_comm_tick = sa->LastCommTick;
if (sa->ServerToClient && sa->PairIPsecSa != NULL)
{
last_comm_tick = sa->PairIPsecSa->LastCommTick;
}
if (sa->Established == false)
{
// Make time-out in a short time when it is not established
if ((last_comm_tick + (UINT64)IKE_TIMEOUT_FOR_IKE_CLIENT_FOR_NOT_ESTABLISHED) <= ike->Now)
{
WHERE;
MarkIPsecSaAsDeleted(ike, sa);
}
}
else
{
// Timeout in a long time in the case of established
if ((last_comm_tick + (UINT64)IKE_TIMEOUT_FOR_IKE_CLIENT) <= ike->Now)
{
WHERE;
MarkIPsecSaAsDeleted(ike, sa);
}
}
}
}
// IKE_CLIENT scanning process
for (i = 0;i < LIST_NUM(ike->ClientList);i++)
{
IKE_CLIENT *c = LIST_DATA(ike->ClientList, i);
UINT64 tick;
UCHAR data[1];
bool need_qm = false;
bool need_qm_hard = false;
UINT64 qm_soft_tick = 0;
// Determine whether it is necessary to start a new Quick Mode
if (c->CurrentExpiresSoftTick_StoC != 0 && ike->Now >= c->CurrentExpiresSoftTick_StoC)
{
need_qm = true;
qm_soft_tick = MAX(qm_soft_tick, c->CurrentExpiresSoftTick_StoC);
}
if (c->CurrentExpiresSoftTick_CtoS != 0 && ike->Now >= c->CurrentExpiresSoftTick_CtoS)
{
need_qm = true;
qm_soft_tick = MAX(qm_soft_tick, c->CurrentExpiresSoftTick_StoC);
}
if (c->CurrentNumHealtyIPsecSA_CtoS == 0 || c->CurrentNumHealtyIPsecSA_StoC == 0)
{
need_qm = true;
need_qm_hard = true;
}
if (c->StartQuickModeAsSoon)
{
need_qm = true;
need_qm_hard = true;
}
if (c->Deleting || c->CurrentIkeSa == NULL || c->CurrentIkeSa->Deleting)
{
need_qm = false;
need_qm_hard = true;
}
if (need_qm)
{
if (c->StartQuickModeAsSoon || ((c->LastQuickModeStartTick + (UINT64)IKE_QUICKMODE_START_INTERVAL) <= ike->Now))
{
// Start the Quick Mode
Debug("IKE_CLIENT 0x%X: Begin QuickMode\n", c);
c->StartQuickModeAsSoon = false;
c->LastQuickModeStartTick = ike->Now;
AddInterrupt(ike->Interrupts, c->LastQuickModeStartTick + (UINT64)IKE_QUICKMODE_START_INTERVAL);
StartQuickMode(ike, c);
}
}
if (need_qm_hard)
{
if (c->NeedQmBeginTick == 0)
{
c->NeedQmBeginTick = ike->Now;
}
}
else
{
c->NeedQmBeginTick = 0;
}
if (((c->LastCommTick + (UINT64)IKE_TIMEOUT_FOR_IKE_CLIENT) <= ike->Now) ||
((c->CurrentIkeSa == NULL && c->CurrentIpSecSaRecv == NULL && c->CurrentIpSecSaSend == NULL) && (c->LastCommTick + (UINT64)IKE_TIMEOUT_FOR_IKE_CLIENT_FOR_NOT_ESTABLISHED) <= ike->Now) ||
(c->NeedQmBeginTick != 0 && ((c->NeedQmBeginTick + (UINT64)IKE_QUICKMODE_FAILED_TIMEOUT) <= ike->Now)))
{
// Remove IKE_CLIENT not communicating for a certain period of time
WHERE;
MarkIkeClientAsDeleted(ike, c);
}
// L2TP processing
if (c->L2TP != NULL)
{
IPsecIkeClientManageL2TPServer(ike, c);
// Interrupt processing occurs
L2TPProcessInterrupts(c->L2TP);
// Packet transmission
IPsecIkeClientSendL2TPPackets(ike, c, c->L2TP);
}
// EtherIP processing
if (c->EtherIP != NULL)
{
IPsecIkeClientManageEtherIPServer(ike, c);
// Interrupt processing occurs
EtherIPProcInterrupts(c->EtherIP);
// Packet transmission
IPsecIkeClientSendEtherIPPackets(ike, c, c->EtherIP);
}
// KeepAlive transmission
tick = MAX(c->LastCommTick + (UINT64)IKE_INTERVAL_UDP_KEEPALIVE, c->NextKeepAliveSendTick);
if (tick <= ike->Now && c->ServerPort == IPSEC_PORT_IPSEC_ESP_UDP)
{
c->NextKeepAliveSendTick = ike->Now + (UINT64)IKE_INTERVAL_UDP_KEEPALIVE;
AddInterrupt(ike->Interrupts, c->NextKeepAliveSendTick);
Zero(data, sizeof(data));
data[0] = 0xff;
IkeSendUdpPacket(ike, IKE_UDP_KEEPALIVE, &c->ServerIP, c->ServerPort, &c->ClientIP, c->ClientPort, Clone(data, sizeof(data)), sizeof(data));
}
// DPD transmission
if (c->NextDpdSendTick == 0 || c->NextDpdSendTick <= ike->Now)
{
if (c->CurrentIkeSa != NULL && c->CurrentIkeSa->Established)
{
if (c->CurrentIkeSa->Caps.DpdRfc3706)
{
c->NextDpdSendTick = ike->Now + (UINT64)IKE_INTERVAL_DPD_KEEPALIVE;
AddInterrupt(ike->Interrupts, c->NextDpdSendTick);
SendInformationalExchangePacket(ike, c,
IkeNewNoticeDpdPayload(false, c->CurrentIkeSa->InitiatorCookie, c->CurrentIkeSa->ResponderCookie,
c->DpdSeqNo++));
}
}
}
}
do
{
ike->StateHasChanged = false;
// Deletion process
PurgeDeletingSAsAndClients(ike);
}
while (ike->StateHasChanged);
// Maintenance of the thread list
MainteThreadList(ike->ThreadList);
/*Debug("ike->ThreadList: %u\n", LIST_NUM(ike->ThreadList));
{
UINT i;
for (i = 0;i < LIST_NUM(ike->ThreadList);i++)
{
THREAD *t = LIST_DATA(ike->ThreadList, i);
Debug(" Thread %u: 0x%p ID: %u Stop: %u Ref: %u\n", i, t, t->ThreadId, t->Stopped, t->ref->c->c);
}
}*/
}
// Stop the IKE server
void StopIKEServer(IKE_SERVER *ike)
{
// Validate arguments
if (ike == NULL)
{
return;
}
}
// Set the socket events in IKE server
void SetIKEServerSockEvent(IKE_SERVER *ike, SOCK_EVENT *e)
{
// Validate arguments
if (ike == NULL)
{
return;
}
if (e != NULL)
{
AddRef(e->ref);
}
if (ike->SockEvent != NULL)
{
ReleaseSockEvent(ike->SockEvent);
}
ike->SockEvent = e;
}
// Release the IKE client
void FreeIkeClient(IKE_SERVER *ike, IKE_CLIENT *c)
{
// Validate arguments
if (c == NULL || ike == NULL)
{
return;
}
if (c->L2TP != NULL)
{
StopL2TPServer(c->L2TP, true);
FreeL2TPServer(c->L2TP);
}
if (c->EtherIP != NULL)
{
ReleaseEtherIPServer(c->EtherIP);
}
FreeBuf(c->SendID1_Buf);
FreeBuf(c->SendID2_Buf);
Free(c);
}
// Release the IPsec SA
void FreeIPsecSa(IPSECSA *sa)
{
// Validate arguments
if (sa == NULL)
{
return;
}
IkeFreeKey(sa->CryptoKey);
FreeBuf(sa->SendBuffer);
FreeBuf(sa->InitiatorRand);
FreeBuf(sa->ResponderRand);
FreeBuf(sa->SharedKey);
IkeDhFreeCtx(sa->Dh);
Free(sa);
}
// Release the IKE SA
void FreeIkeSa(IKE_SA *sa)
{
// Validate arguments
if (sa == NULL)
{
return;
}
FreeBuf(sa->SendBuffer);
FreeBuf(sa->InitiatorRand);
FreeBuf(sa->ResponderRand);
FreeBuf(sa->DhSharedKey);
FreeBuf(sa->YourIDPayloadForAM);
FreeBuf(sa->GXi);
FreeBuf(sa->GXr);
FreeBuf(sa->SAi_b);
IkeFreeKey(sa->CryptoKey);
Free(sa);
}
// Release the IKE server
void FreeIKEServer(IKE_SERVER *ike)
{
UINT i;
// Validate arguments
if (ike == NULL)
{
return;
}
IPsecLog(ike, NULL, NULL, NULL, "LI_STOPPING");
for (i = 0;i < LIST_NUM(ike->SendPacketList);i++)
{
UDPPACKET *udp = LIST_DATA(ike->SendPacketList, i);
FreeUdpPacket(udp);
}
ReleaseList(ike->SendPacketList);
Debug("Num of IPsec SAs: %u\n", LIST_NUM(ike->IPsecSaList));
IPsecLog(ike, NULL, NULL, NULL, "LI_NUM_IPSEC_SA", LIST_NUM(ike->IPsecSaList));
for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
{
IPSECSA *sa = LIST_DATA(ike->IPsecSaList, i);
FreeIPsecSa(sa);
}
ReleaseList(ike->IPsecSaList);
Debug("Num of IKE SAs: %u\n", LIST_NUM(ike->IkeSaList));
IPsecLog(ike, NULL, NULL, NULL, "LI_NUM_IKE_SA", LIST_NUM(ike->IkeSaList));
for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
{
IKE_SA *sa = LIST_DATA(ike->IkeSaList, i);
FreeIkeSa(sa);
}
ReleaseList(ike->IkeSaList);
Debug("Num of IKE_CLIENTs: %u\n", LIST_NUM(ike->ClientList));
IPsecLog(ike, NULL, NULL, NULL, "LI_NUM_IKE_CLIENTS", LIST_NUM(ike->ClientList));
for (i = 0;i < LIST_NUM(ike->ClientList);i++)
{
IKE_CLIENT *c = LIST_DATA(ike->ClientList, i);
FreeIkeClient(ike, c);
}
ReleaseList(ike->ClientList);
ReleaseSockEvent(ike->SockEvent);
IPsecLog(ike, NULL, NULL, NULL, "LI_STOP");
ReleaseCedar(ike->Cedar);
FreeIkeEngine(ike->Engine);
for (i = 0;i < LIST_NUM(ike->InfoMsgQuotaList);i++)
{
IKE_INFOMSG_QUOTA_ENTRY *q = LIST_DATA(ike->InfoMsgQuotaList, i);
Free(q);
}
ReleaseList(ike->InfoMsgQuotaList);
Debug("FreeThreadList()...\n");
FreeThreadList(ike->ThreadList);
Debug("FreeThreadList() Done.\n");
Free(ike);
}
// Create a new IKE server
IKE_SERVER *NewIKEServer(CEDAR *cedar, IPSEC_SERVER *ipsec)
{
IKE_SERVER *ike;
// Validate arguments
if (cedar == NULL)
{
return NULL;
}
ike = ZeroMalloc(sizeof(IKE_SERVER));
ike->Cedar = cedar;
AddRef(cedar->ref);
ike->IPsec = ipsec;
ike->Now = Tick64();
ike->SendPacketList = NewList(NULL);
ike->IkeSaList = NewList(CmpIkeSa);
ike->IPsecSaList = NewList(CmpIPsecSa);
ike->ClientList = NewList(CmpIkeClient);
ike->InfoMsgQuotaList = NewList(NULL);
ike->Engine = NewIkeEngine();
ike->ThreadList = NewThreadList();
IPsecLog(ike, NULL, NULL, NULL, "LI_START");
return ike;
}
|
8b45dd2c2446a246d9ea545385e6ab1fe981e6a6
|
88ae8695987ada722184307301e221e1ba3cc2fa
|
/third_party/wayland-protocols/gtk/gtk/inspector/magnifier.h
|
2dcac6fa91322549baf9df5af916cb1778a70b26
|
[
"BSD-3-Clause",
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"LGPL-2.0-only",
"LGPL-2.1-only"
] |
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
| 2,140
|
h
|
magnifier.h
|
/*
* Copyright (c) 2014 Red Hat, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _GTK_INSPECTOR_MAGNIFIER_H_
#define _GTK_INSPECTOR_MAGNIFIER_H_
#include <gtk/gtkbox.h>
#define GTK_TYPE_INSPECTOR_MAGNIFIER (gtk_inspector_magnifier_get_type())
#define GTK_INSPECTOR_MAGNIFIER(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), GTK_TYPE_INSPECTOR_MAGNIFIER, GtkInspectorMagnifier))
#define GTK_INSPECTOR_MAGNIFIER_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), GTK_TYPE_INSPECTOR_MAGNIFIER, GtkInspectorMagnifierClass))
#define GTK_INSPECTOR_IS_MAGNIFIER(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), GTK_TYPE_INSPECTOR_MAGNIFIER))
#define GTK_INSPECTOR_IS_MAGNIFIER_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), GTK_TYPE_INSPECTOR_MAGNIFIER))
#define GTK_INSPECTOR_MAGNIFIER_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), GTK_TYPE_INSPECTOR_MAGNIFIER, GtkInspectorMagnifierClass))
typedef struct _GtkInspectorMagnifierPrivate GtkInspectorMagnifierPrivate;
typedef struct _GtkInspectorMagnifier
{
GtkBox parent;
GtkInspectorMagnifierPrivate *priv;
} GtkInspectorMagnifier;
typedef struct _GtkInspectorMagnifierClass
{
GtkBoxClass parent;
} GtkInspectorMagnifierClass;
G_BEGIN_DECLS
GType gtk_inspector_magnifier_get_type (void);
void gtk_inspector_magnifier_set_object (GtkInspectorMagnifier *sl,
GObject *object);
G_END_DECLS
#endif // _GTK_INSPECTOR_MAGNIFIER_H_
// vim: set et sw=2 ts=2:
|
064a142a524bd92d4c76c8173253ae90d99308bf
|
8b98cd47f934d2a4a8d0b2842d3277b01f3fb7fa
|
/libraries/gks/drivers/sun/temp.include/gfx_hs.h
|
6b481007b3df2271ecee9b3c0d388466d318afc0
|
[] |
no_license
|
Starlink/starlink
|
1cc03b85eb78330a3622003b26b69c1733df50fe
|
2c374b3e97c9cebcc8f3bd2f8b4bb326eefe061a
|
refs/heads/master
| 2023-07-26T09:32:27.987319
| 2023-07-05T23:56:27
| 2023-07-05T23:56:27
| 5,169,323
| 139
| 45
| null | 2022-11-18T13:29:32
| 2012-07-24T18:15:25
|
Fortran
|
UTF-8
|
C
| false
| false
| 428
|
h
|
gfx_hs.h
|
/* @(#)gfx_hs.h 10.6 88/02/08 SMI */
/*
* Copyright (c) 1983 by Sun Microsystems, Inc.
*/
/*
* Include this header file to get all graphics subwindow related header files.
* Use when you are running standalone, i.e., taking over another window.
*/
#ifndef gfx_hs_defined
#define gfx_hs_defined
#include <pixrect/pixrect_hs.h>
#include <sunwindow/window_hs.h>
#include <suntool/gfxsw.h>
#endif gfx_hs_defined
|
45126c5336bd40f84cd6c952dec3983274674869
|
1ca288c3f3c54db93fe4828214a81f6687105a1e
|
/src/rsm/test/test_cxx_rsm.h
|
b06b7325eafb502a3a9f60c6ec6f6e9a996df8d7
|
[
"MIT"
] |
permissive
|
BitcoinUnlimited/BitcoinUnlimited
|
489c91a9184bdbad3824a2ce3126d2e9c0786e5d
|
05de381c02eb4bfca94957733acadfa217527f25
|
refs/heads/release
| 2023-06-01T08:11:18.920865
| 2021-03-29T15:58:02
| 2021-03-29T15:58:02
| 18,613,259
| 546
| 301
|
MIT
| 2021-01-04T01:05:24
| 2014-04-09T21:03:00
|
C++
|
UTF-8
|
C
| false
| false
| 432
|
h
|
test_cxx_rsm.h
|
// Copyright (c) 2019 Greg Griffith
// Copyright (c) 2019 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef TEST_CXX_RSM_H
#define TEST_CXX_RSM_H
struct TestSetup {
TestSetup() { /* intentionally left blank */ }
~TestSetup() { /* intentionally left blank */ }
};
#endif // TEST_CXX_RSM_H
|
44199386f722cb1a84414ca3ecd2428ac6bd11cf
|
a4515918f56dd7ab527e4999aa7fce818b6dd6f6
|
/HacktoberFestContribute/Data Structures/SelectionSort.c
|
aab01f06a3865ec6aae52b54542c3efb79d1ae78
|
[
"MIT"
] |
permissive
|
rathoresrikant/HacktoberFestContribute
|
0e2d4692a305f079e5aebcd331e8df04b90f90da
|
e2a69e284b3b1bd0c7c16ea41217cc6c2ec57592
|
refs/heads/master
| 2023-06-13T09:22:22.554887
| 2021-10-27T07:51:41
| 2021-10-27T07:51:41
| 151,832,935
| 102
| 901
|
MIT
| 2023-06-23T06:53:32
| 2018-10-06T11:23:31
|
C++
|
UTF-8
|
C
| false
| false
| 620
|
c
|
SelectionSort.c
|
#include <stdio.h>
int main()
{
int a[100], n, i, j, pos, swap;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (i=0 ; i<n ; i++ )
scanf("%d", &a[i]);
for ( i= 0 ; i<( n - 1 ) ; i++ )
{
pos = i;
for ( j=i+1 ; j<n ; j++ )
{
if ( a[pos] > a[j] )
pos = j;
}
if ( pos != i )
{
swap = a[i];
a[i] = a[pos];
a[pos] = swap;
}
}
printf("Sorted list in ascending order:\n");
for ( i=0 ; i<n ; i++ )
printf("%d ", a[i]);
return 0;
}
|
551a331228f9c9b736639d73fdd1253c60549308
|
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
|
/net/tcpmssd/files/tcpmssd.c
|
02a2a7b171aeae1dcd8b9a1777996ab847d7a410
|
[
"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
| 9,200
|
c
|
tcpmssd.c
|
/*-
* Copyright (c) 2000 Ruslan Ermilov
* 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 <sys/param.h>
#include <sys/socket.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
#include <net/route.h>
#include <netinet/in_systm.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <err.h>
#include <errno.h>
#include <paths.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
static void correct_mss(struct tcphdr *, ssize_t len, u_int16_t);
static int if_mtu(const char *, u_long *);
static void sigterm_handler(int);
static void usage(void);
static int both;
static int verbose;
char pidfilename[MAXPATHLEN];
/*-
* We are in liberal position about MSS
* (RFC 879, section 7).
*/
#define MAXMSS(mtu) (mtu - sizeof(struct ip) - sizeof(struct tcphdr))
int
main(int argc, char *argv[])
{
char pkt[IP_MAXPACKET];
ssize_t pktlen, hlen;
struct ip *pip = (struct ip *)pkt;
struct sockaddr_in sin;
socklen_t sinlen;
int s;
int mflag;
u_long mtu;
u_int16_t maxmss;
int rtsock;
int ifindex;
int pflag;
u_short port;
int ch;
fd_set fdset;
mflag = pflag = 0;
port = 0; /* XXX gcc -Wuninitialized */
ifindex = 0;
rtsock = -1;
while ((ch = getopt(argc, argv, "bi:m:p:v")) != -1)
switch (ch) {
case 'b':
both = 1;
break;
case 'i':
if (!(ifindex = if_mtu(optarg, &mtu))) {
errx(1, "unknown interface %s", optarg);
/* NOTREACHED */
}
snprintf(pidfilename, sizeof pidfilename,
"%stcpmssd.%s.pid", _PATH_VARRUN, optarg);
break;
case 'm':
if ((mtu = atoi(optarg)) < 68) {
errx(1, "invalid MTU value");
/* NOTREACHED */
}
mflag++;
break;
case 'p':
port = htons(atoi(optarg));
pflag++;
break;
case 'v':
verbose = 1;
break;
case '?':
default:
usage();
/* NOTREACHED */
}
argc -= optind;
argv += optind;
if (!(!mflag - !ifindex) || !pflag || argc) {
usage();
/* NOTREACHED */
}
#ifdef PF_DIVERT
if ((s = socket(PF_DIVERT, SOCK_RAW, 0)) == -1) {
#else
if ((s = socket(PF_INET, SOCK_RAW, IPPROTO_DIVERT)) == -1) {
#endif
err(1, "can't create divert socket");
/* NOTREACHED */
}
bzero(&sin, sizeof(sin));
sin.sin_family = PF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port = port;
if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) == -1) {
err(1, "can't bind divert socket");
/* NOTREACHED */
}
if (ifindex)
if ((rtsock = socket(PF_ROUTE, SOCK_RAW, 0)) == -1) {
err(1, "can't create routing socket");
/* NOTREACHED */
}
maxmss = MAXMSS(mtu);
if (verbose)
fprintf(stderr, "Maximum MSS: %u\n", maxmss);
if (!verbose)
if (daemon(0, 0) == -1) {
err(1, "can't daemonize");
/* NOTREACHED */
}
if (ifindex) {
FILE *pidfile;
pidfile = fopen(pidfilename, "w");
if (pidfile != NULL) {
fprintf(pidfile, "%d\n", (int)getpid());
fclose(pidfile);
if (signal(SIGTERM, sigterm_handler) == SIG_ERR) {
err(1, "can't install SIGTERM handler");
/* NOTREACHED */
}
}
}
while (1) {
FD_ZERO(&fdset);
FD_SET(s, &fdset);
if (rtsock != -1)
FD_SET(rtsock, &fdset);
if (select(32, &fdset, (fd_set *)NULL, (fd_set *)NULL, (struct timeval *)NULL) == -1) {
warn("select failed");
continue;
}
if (rtsock != -1 && FD_ISSET(rtsock, &fdset)) {
struct if_msghdr ifm;
if ((pktlen = read(rtsock, &ifm, sizeof(ifm))) == -1) {
warn("read from routing socket failed");
continue;
}
if (ifm.ifm_version != RTM_VERSION) {
if (verbose)
warnx("routing message version %d "
"not understood", ifm.ifm_version);
continue;
}
if (ifm.ifm_type != RTM_IFINFO ||
ifm.ifm_index != ifindex)
continue;
if (mtu != ifm.ifm_data.ifi_mtu) {
mtu = ifm.ifm_data.ifi_mtu;
maxmss = MAXMSS(mtu);
if (verbose)
fprintf(stderr, "Maximum MSS: %u\n", maxmss);
}
}
if (FD_ISSET(s, &fdset)) {
sinlen = sizeof(sin);
if ((pktlen = recvfrom(s, pkt, sizeof(pkt), 0,
(struct sockaddr *)&sin, &sinlen)) == -1)
if (errno != EINTR) {
warn("read from divert socket failed");
continue;
}
hlen = pip->ip_hl << 2;
/*-
* Check for MSS option only for outgoing
* TCP packets with zero fragment offset
* and correct total and header lengths.
*/
if ((both || sin.sin_addr.s_addr == INADDR_ANY) &&
pip->ip_p == IPPROTO_TCP &&
(ntohs(pip->ip_off) & IP_OFFMASK) == 0 &&
ntohs(pip->ip_len) == pktlen &&
hlen <= pktlen &&
pktlen - hlen >= sizeof(struct tcphdr))
correct_mss((struct tcphdr *)(pkt + hlen),
pktlen - hlen, maxmss);
if (sendto(s, pkt, pktlen, 0,
(struct sockaddr *)&sin, sinlen) == -1)
warn("write to divert socket failed");
}
}
}
/*-
* The following macro is used to update an
* internet checksum. "acc" is a 32-bit
* accumulation of all the changes to the
* checksum (adding in old 16-bit words and
* subtracting out new words), and "cksum"
* is the checksum value to be updated.
*/
#define ADJUST_CHECKSUM(acc, cksum) { \
acc += cksum; \
if (acc < 0) { \
acc = -acc; \
acc = (acc >> 16) + (acc & 0xffff); \
acc += acc >> 16; \
cksum = (u_short) ~acc; \
} else { \
acc = (acc >> 16) + (acc & 0xffff); \
acc += acc >> 16; \
cksum = (u_short) acc; \
} \
}
void
correct_mss(struct tcphdr *tc, ssize_t pktlen, u_int16_t maxmss)
{
int hlen, olen, optlen;
u_char *opt;
u_int16_t *mss;
int accumulate;
hlen = tc->th_off << 2;
/* Invalid header length or header without options. */
if (hlen <= sizeof(struct tcphdr) || hlen > pktlen)
return;
/* MSS option only allowed within SYN packets. */
if (!(tc->th_flags & TH_SYN))
return;
for (olen = hlen - sizeof(struct tcphdr), opt = (u_char *)(tc + 1);
olen > 0; olen -= optlen, opt += optlen) {
if (*opt == TCPOPT_EOL)
break;
else if (*opt == TCPOPT_NOP)
optlen = 1;
else {
optlen = *(opt + 1);
if (optlen <= 0 || optlen > olen)
break;
if (*opt == TCPOPT_MAXSEG) {
if (optlen != TCPOLEN_MAXSEG)
continue;
mss = (u_int16_t *)(opt + 2);
if (ntohs(*mss) > maxmss) {
if (verbose)
fprintf(stderr,
"MSS: %u -> %u\n",
ntohs(*mss), maxmss);
accumulate = *mss;
*mss = htons(maxmss);
accumulate -= *mss;
ADJUST_CHECKSUM(accumulate, tc->th_sum);
}
}
}
}
}
static int
if_mtu(const char *ifn, u_long *mtu)
{
size_t needed;
int mib[6];
char *buf, *lim, *next;
struct if_msghdr *ifm;
struct sockaddr_dl *sdl;
int ifindex;
mib[0] = CTL_NET;
mib[1] = PF_ROUTE;
mib[2] = 0;
mib[3] = AF_INET; /* Only IP addresses please. */
mib[4] = NET_RT_IFLIST;
mib[5] = 0; /* List all interfaces. */
/*
* Get interface data.
*/
if (sysctl(mib, 6, NULL, &needed, NULL, 0) == -1)
err(1, "iflist-sysctl-estimate");
if ((buf = malloc(needed)) == NULL)
errx(1, "malloc failed");
if (sysctl(mib, 6, buf, &needed, NULL, 0) == -1)
err(1, "iflist-sysctl-get");
lim = buf + needed;
/*
* Loop through interfaces until one with
* given name is found. This is done to
* find correct interface index for routing
* message processing.
*/
ifindex = 0;
next = buf;
while (next < lim) {
ifm = (struct if_msghdr *)next;
next += ifm->ifm_msglen;
if (ifm->ifm_version != RTM_VERSION) {
if (verbose)
warnx("routing message version %d "
"not understood", ifm->ifm_version);
continue;
}
if (ifm->ifm_type == RTM_IFINFO) {
sdl = (struct sockaddr_dl *)(ifm + 1);
if (strlen(ifn) == sdl->sdl_nlen &&
strncmp(ifn, sdl->sdl_data, sdl->sdl_nlen) == 0) {
*mtu = ifm->ifm_data.ifi_mtu;
ifindex = ifm->ifm_index;
break;
}
}
}
free(buf);
return (ifindex);
}
static void
sigterm_handler(int sig)
{
(void)unlink(pidfilename);
exit(0);
}
void
usage(void)
{
fprintf(stderr, "usage: tcpmssd [-v] -p port {-i iface | -m mtu}\n");
exit(1);
}
|
d20ffacc5491f59d08120f29be206ba80126fd69
|
99bdb3251fecee538e0630f15f6574054dfc1468
|
/bsp/tkm32F499/Libraries/CMSIS_and_startup/sys.c
|
5943ef909514227d2f01dd1babbf8e4ff7ef0ab5
|
[
"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
| 4,089
|
c
|
sys.c
|
#include "sys.h"
#include "HAL_misc.h"
void RemapVtorTable(void)
{
int i;
RCC->AHB1ENR |= 1<<13;//bkp clk,enable sram
//关ROM区中断
for(i = 0;i<90;i++)
{
NVIC_DisableIRQ((IRQn_Type)i);
}
SCB->VTOR = 0;
SCB->VTOR |= 0x1<<29;
for(i = 0;i < 512;i+=4)
*(u32*)(T_SRAM_BASE + i) = *(u32*)(T_SDRAM_BASE+i);
}
void AI_Responder_enable(void)
{
AI_Responder->ADDR1= 0x70807040;
// AI_Responder->ADDR0 = 0x70027080;
AI_Responder->ADDR1 = 0;
AI_Responder->CCR &= ~(0x3<<3);
AI_Responder->CCR |= 1;
while((AI_Responder->SR & 0x3) != 2);
}
void AI_Responder_disable(void)
{
AI_Responder->CCR &= ~1;
}
//外部中断配置函数
//只针对GPIOA~E
//参数:
//GPIOx:0~4,代表GPIOA~E
//BITx:需要使能的位,例如PB12,就填 12;
//TRIM:触发模式,1,下降沿;2,上升沿;3,任意电平触发
//该函数一次只能配置1个IO口,多个IO口,需多次调用
//该函数会自动开启对应中断,以及屏蔽线
void Ex_NVIC_Config(u8 GPIOx,u8 BITx,u8 TRIM)
{
u8 EXTOFFSET=(BITx%4)*4;
RCC->APB2ENR|=1<<14; //使能SYSCFG时钟
SYSCFG->EXTICR[BITx/4]&=~(0x000F<<EXTOFFSET);//清除原来设置!!!
SYSCFG->EXTICR[BITx/4]|=GPIOx<<EXTOFFSET; //EXTI.BITx映射到GPIOx.BITx
//自动设置
EXTI->IMR|=1<<BITx; //开启line BITx上的中断(如果要禁止中断,则反操作即可)
if(TRIM&0x01)EXTI->FTSR|=1<<BITx; //line BITx事件下降沿触发
if(TRIM&0x02)EXTI->RTSR|=1<<BITx; //line BITx事件上升沿触发
}
//THUMB指令不支持汇编内联
//采用如下方法实现执行汇编指令WFI
void WFI_SET(void)
{
__ASM volatile("wfi");
}
//关闭所有中断(但是不包括fault和NMI中断)
void INTX_DISABLE(void)
{
__ASM volatile("cpsid i");
}
//开启所有中断
void INTX_ENABLE(void)
{
__ASM volatile("cpsie i");
}
//设置栈顶地址 __set_MSP(0x70002000);
//进入待机模式
void Sys_Standby(void)
{
SCB->SCR|=1<<2; //使能SLEEPDEEP位 (SYS->CTRL)
RCC->APB1ENR|=1<<28;//使能电源时钟
PWR->CSR|=1<<8; //设置WKUP用于唤醒
PWR->CR|=1<<2; //清除Wake-up 标志
PWR->CR|=1<<1; //PDDS置位
WFI_SET(); //执行WFI指令,进入待机模式
}
//系统软复位
void Sys_Soft_Reset(void)
{
SCB->AIRCR =0X05FA0000|(u32)0x04;
}
// TK499_NVIC_Init(2,2,TK80_IRQn,2);
//设置NVIC
//NVIC_PreemptionPriority:抢占优先级
//NVIC_SubPriority :响应优先级
//NVIC_Channel :中断编号
//NVIC_Group :中断分组 0~4
//注意优先级不能超过设定的组的范围!否则会有意想不到的错误
//组划分:
//组0:0位抢占优先级,4位响应优先级
//组1:1位抢占优先级,3位响应优先级
//组2:2位抢占优先级,2位响应优先级
//组3:3位抢占优先级,1位响应优先级
//组4:4位抢占优先级,0位响应优先级
//NVIC_SubPriority和NVIC_PreemptionPriority的原则是,数值越小,越优先
void TK499_NVIC_Init(u8 NVIC_PreemptionPriority,u8 NVIC_SubPriority,u8 NVIC_Channel,u8 NVIC_Group)
{
u32 temp;
NVIC_SetPriorityGrouping(NVIC_Group);//设置分组
temp=NVIC_PreemptionPriority<<(4-NVIC_Group);
temp|=NVIC_SubPriority&(0x0f>>NVIC_Group);
temp&=0xf; //取低四位
NVIC->ISER[NVIC_Channel/32]|=1<<NVIC_Channel%32;//使能中断位(要清除的话,设置ICER对应位为1即可)
NVIC->IP[NVIC_Channel]|=temp<<4; //设置响应优先级和抢断优先级
}
void TK80_IRQHandler(void)
{
if(TK80->SR & 0x1)
{
}
if(TK80->SR & 0x2)
{
}
if(TK80->SR & 0x4)
{
}
if(TK80->SR & 0x8)
{
}
TK80->SR |= 0;
}
//备用函数
//#define T_SRAM_FUN1 0x20000400
//copyAtoB((u32)LCD_PutPixel&0xFFFFFFFE,T_SRAM_FUN1,800);//加载函数到SRAM
//void copyAtoB(u32 srcAdd,u32 dstAdd,u16 len)
//{
// len = (len + 3)/4;
// while(len--)
// {
// *(u32*)dstAdd = *(u32*)srcAdd;
// dstAdd += 4 ;
// srcAdd +=4 ;
// }
//}
|
ee6ef4accc1649c60aece9027d89782656a3d204
|
31f5cddb9885fc03b5c05fba5f9727b2f775cf47
|
/engine/core/script/lua/lua_doc.h
|
8647f8c9dea557144f30281ef96ebb935c7670c0
|
[
"MIT"
] |
permissive
|
timi-liuliang/echo
|
2935a34b80b598eeb2c2039d686a15d42907d6f7
|
d6e40d83c86431a819c6ef4ebb0f930c1b4d0f24
|
refs/heads/master
| 2023-08-17T05:35:08.104918
| 2023-08-11T18:10:35
| 2023-08-11T18:10:35
| 124,620,874
| 822
| 102
|
MIT
| 2021-06-11T14:29:03
| 2018-03-10T04:07:35
|
C++
|
GB18030
|
C
| false
| false
| 10,991
|
h
|
lua_doc.h
|
/*相关API:
http://pgl.yoyo.org/luai/i/_
Lua stack
You can imagine the stack as growing from the bottom, with the bottom (i.e., the first pushed) element having index 1,
then you push another element (index 2), then another one (index 3), etc.. So you have this situation:
+-----------------------+
| element with index 6 | <-- top ("relative" index -1)
+-----------------------+
| element with index 5 | <-- -2
+-----------------------+
| element with index 4 | <-- -3
+-----------------------+
| element with index 3 | <-- -4
+-----------------------+
| element with index 2 | <-- -5
+-----------------------+
| element with index 1 | <-- bottom ("relative" index -6 )
+-----------------------+
lua_createtable
原型: void lua_createtable (lua_State *L, int narr, int nrec);
描述: 创建一个新的table并将之放在栈顶.narr是该table数组部分的长度,nrec是该table hash部分的长度.
当我们确切的知道要放多少元素到table的时候,使用这个函数,lua可以预分配一些内存,提升性能.
如果不确定要存放多少元素可以使用 lua_newtable 函数来创建table.
lua_newtable
原型: void lua_newtable (lua_State *L);
描述: 创建一个新的table并将之放在栈顶. 等同于lua_createtable(L, 0, 0).
lua_getfield
原型: void lua_getfield (lua_State *L, int index, const char *k);
描述: 将t[k]元素push到栈顶. 其中t是index处的table.
这个函数可能触发index元方法.
lua_setfield
原型: void lua_setfield (lua_State *L, int index, const char *k);
描述: 为table中的key赋值. t[k] = v . 其中t是index处的table , v为栈顶元素.
这个函数可能触发newindex元方法.
调用完成后弹出栈顶元素(value).
lua_gettable
原型: void lua_gettable (lua_State *L, int index);
描述: 将t[k]元素push到栈顶. 其中t是index处的table,k为栈顶元素.
这个函数可能触发index元方法.
调用完成后弹出栈顶元素(key).
lua_rawget
原型: void lua_rawget (lua_State *L, int index);
描述: 与lua_gettable函数类似, 但是不会触发__index元方法.
lua_rawset
原型: void lua_rawset (lua_State *L, int index);
描述: 与lua_settable函数类似, 但是不会触发newindex元方法.
lua_rawgeti
原型: void lua_rawgeti (lua_State *L, int index, int n);
描述: 将t[n]元素push到栈顶.其中t是index处的table.
这个函数不会触发index元方法.
lua_rawseti
原型: void lua_rawseti (lua_State *L, int index, int n);
描述: 为table中的key赋值. t[n] = v .其中t是index处的table , v为栈顶元素.
这个函数不会触发newindex元方法.
调用完成后弹出栈顶元素.
lua_rawgetp
原型: void lua_rawgetp (lua_State *L, int index, const void *p);
描述: 将t[p]元素push到栈顶.其中t是index处的table. p是一个lightuserdata.
这个函数不会触发index元方法.
lua_rawsetp
原型: void lua_rawsetp (lua_State *L, int index, const void *p);
描述: 为table中的key赋值. t[p] = v .其中t是index处的table , p是一个lightuserdata , v为栈顶元素.
这个函数不会触发newindex元方法.
调用完成后弹出栈顶元素.
lua_getmetatable
原型: int lua_getmetatable (lua_State *L, int index);
描述: 将index处元素的元表push到栈顶. 如果该元素没有元表, 函数返回0 , 不改变栈.
lua_setmetatable
prototype : int lua_setmetatable (lua_State *L, int index);
description: Pops a table from the stack and sets it as the new metatable for the value at the given acceptable index.
lua_istable
原型: int lua_istable (lua_State *L, int index);
描述: 判断index处元素是否为一个table , 如果是返回1,否则返回0.
lua_pushglobaltable
原型: void lua_pushglobaltable (lua_State *L);
描述: 将lua的全局表放在栈顶.
luaL_newmetatable
原型: int luaL_newmetatable (lua_State *L, const char *tname);
描述: 如果注册表中已经有名为tname的key,则返回0.
否则创建一个新table作为userdata的元表. 这个元表存储在注册表中,并以tname为key. 返回1.
函数完成后将该元表置于栈顶.
luaL_getmetatable
原型: void luaL_getmetatable (lua_State *L, const char *tname);
描述: 将注册表中以tname为key的元表push到栈顶.
luaL_setmetatable
原型: void luaL_setmetatable (lua_State *L, const char *tname);
描述: 将栈顶元素存储到注册表中, 它的key为tname.
luaL_getsubtable
原型: int luaL_getsubtable (lua_State *L, int idx, const char *fname);
描述: 将 t[fname] push到栈顶, 其中t是index处的table , 并且 t[fname] 也为一个table.
如果 t[fname] 原本就存在,返回 true ,否则返回false,并且将 t[fname] 新建为一张空表.
lua_getglobal
原型: void lua_getglobal (lua_State *L, const char *name);
描述: 将 t[name] 元素push到栈顶, 其中t为全局表.
lua_setglobal
prototype : void lua_setglobal (lua_State *L, const char *name);
description: Pops a value from the stack and sets it as the new value of global name.
It is defined as a macro:
#define lua_setglobal(L,s) lua_setfield(L, LUA_GLOBALSINDEX, s)
luaL_newlibtable
原型: void luaL_newlibtable (lua_State *L, const luaL_Reg l[]);
描述: 创建一张空表, lua预先分配足够的内存用来存储我们创建的函数库.
稍后我们可以使用 luaL_setfuncs 函数注册我们的函数库.
luaL_setfuncs
原型: void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup);
描述: 将所有 luaL_Reg数组中的函数注册到栈顶的table中.
当upvalue个数不为0时,所创建的所有函数共享这些upvalue. -2到-(nup+1)的元素为要注册的upvalue.
(注意:这些upvalue是c中的upvalue,不是lua中的upvalue,可以在注册的c函数中通过 lua_upvalueindex(n)获取其值.)
调用完成后弹出栈顶的所有upvalue.
luaL_newlib
原型: void luaL_newlib (lua_State *L, const luaL_Reg *l);
描述: 创建一个新的table , 并将luaL_Reg数组中的函数注册到其中.
它是一个宏 (luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))
lua_next
原型: int lua_next (lua_State *L, int index);
描述: 该函数用来遍历一个table.
从栈顶弹出一个key , 并且push一个 key-value对(栈顶key的下一个键值对) ,到栈顶.
如果table中没有更多的元素, 函数返回0.
遍历开始时栈顶为一个nil , 函数取出第一个键值对.
通常遍历方法为:
lua_pushnil(L); // first key
while (lua_next(L, t) != 0) {
// uses 'key' (at index -2) and 'value' (at index -1)
printf("%s - %s\n",
lua_typename(L, lua_type(L, -2)),
lua_typename(L, lua_type(L, -1)));
// removes 'value'; keeps 'key' for next iteration
lua_pop(L, 1);
}
注意: 在遍历table的时候 ,除非明确的知道key为字符串,不要对栈上的key使用 lua_tolstring 函数 ,
因为这样有可能改变key的类型 , 影响下一次 lua_next调用.
lua_rawlen
原型: size_t lua_rawlen (lua_State *L, int index);
描述: 获取index处元素的长度.
对于字符串来说,返回字符串长度.
对于table来说,返回#操作符的长度. 不受元方法影响.
对于userdata来说,返回内存的大小.
其他元素返回0.
lua_len
原型: void lua_len (lua_State *L, int index);
描述: 获取index处元素#操作符的结果 , 放置在栈顶.
其他概念:
1.伪索引:
Lua栈的正常索引 从栈顶算,栈顶为-1,向栈低递减. 从栈低算,栈低为1,向栈顶递增.
伪索引是一种索引,他不在栈的位置中,通过一个宏来定义伪索引的位置.
伪索引被用来访问注册表,或者在lua_CFunction中访问upvalue.
2.注册表:
Lua的注册表是一个预定义的table, 可以提供给c api存储一切想要存储的值.
注册表通过 LUA_REGISTRYINDEX 伪索引来访问.
例如 lua_getfield 函数可以像下面这样使用来获取注册表中的一个以"hello"为key的值 :
lua_getfield( L , LUA_REGISTRYINDEX , "hello");
3. upvalue:
在使用 lua_pushcfunction 或者 luaL_setfuncs 将一个lua_CFunction 注册到Lua环境中时,
可以同时为这个函数设置一些upvalue .
而后在这些lua_CFunction 中可以使用 lua_upvalueindex(n) 函数来获取对应位置的upvalue.
lua_pushcclosure
prototype : void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);
description: Pushes a new C closure onto the stack.
When a C function is created, it is possible to associate some values with it, thus creating
a C closure (see §3.4); these values are then accessible to the function whenever it is called.
To associate values with a C function, first these values should be pushed onto the stack
(when there are multiple values, the first value is pushed first). Then lua_pushcclosure is
called to create and push the C function onto the stack, with the argument n telling how many
values should be associated with the function. lua_pushcclosure also pops these values from
the stack.
The maximum value for n is 255.
lua_gettop
prototype ; int lua_gettop (lua_State *L);
description: The lua_gettop function returns the number of elements in the stack, which is also the
index of the top element. Notice that a negative index -x is equivalent to the positive
index gettop - x + 1.
lua_settop
prototype : lua_settop( lua_State *L, int idx)
description: lua_settop sets the top (that is, the number of elements in the stack) to a specific value.
If the previous top was higher than the new one, the top values are discarded. Otherwise,
the function pushes nils on the stack to get the given size. As a particular case, lua_settop(L, 0)
empties the stack. You can also use negative indices with lua_settop; that will set the top
element to the given index. Using this facility, the API offers the following macro, which
pops n elements from the stack:
#define lua_pop(L,n) lua_settop(L, -(n)-1)
lua_pushliteral
prototype :void lua_pushliteral (lua_State *L, const char *s);
description:This macro is equivalent to lua_pushlstring, but can be used only when s is a literal string.
In these cases, it automatically provides the string length.
lua_pushvalue
prototype :void lua_pushvalue (lua_State *L, int index);
description:Pushes a copy of the element at the given valid index onto the stack
lua_settable
prototype :void lua_settable (lua_State *L, int index);
description:Does the equivalent to t[k] = v, where t is the value at the given valid index, v is the value
at the top of the stack, and k is the value just below the top.
This function pops both the key and the value from the stack. As in Lua, this function may
trigger a metamethod for the "newindex" event (see §2.8)
lua_pop
prototype :void lua_pop (lua_State *L, int n);
description:Pops n elements from the stack.
*/
|
00eb430d3bab70da8a5a06217b1896534ff41d7c
|
ae31542273a142210a1ff30fb76ed9d45d38eba9
|
/src/include/portability/instr_time.h
|
ec48f57a846240b988d0e97efa01055aaf45322c
|
[
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"PostgreSQL",
"OpenSSL",
"LicenseRef-scancode-stream-benchmark",
"ISC",
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-ssleay-windows",
"BSD-2-Clause",
"Python-2.0"
] |
permissive
|
greenplum-db/gpdb
|
8334837bceb2d5d51a684500793d11b190117c6a
|
2c0f8f0fb24a2d7a7da114dc80f5f5a2712fca50
|
refs/heads/main
| 2023-08-22T02:03:03.806269
| 2023-08-21T22:59:53
| 2023-08-22T01:17:10
| 44,781,140
| 6,417
| 2,082
|
Apache-2.0
| 2023-09-14T20:33:42
| 2015-10-23T00:25:17
|
C
|
UTF-8
|
C
| false
| false
| 7,285
|
h
|
instr_time.h
|
/*-------------------------------------------------------------------------
*
* instr_time.h
* portable high-precision interval timing
*
* This file provides an abstraction layer to hide portability issues in
* interval timing. On Unix we use clock_gettime() if available, else
* gettimeofday(). On Windows, gettimeofday() gives a low-precision result
* so we must use QueryPerformanceCounter() instead. These macros also give
* some breathing room to use other high-precision-timing APIs.
*
* The basic data type is instr_time, which all callers should treat as an
* opaque typedef. instr_time can store either an absolute time (of
* unspecified reference time) or an interval. The operations provided
* for it are:
*
* INSTR_TIME_IS_ZERO(t) is t equal to zero?
*
* INSTR_TIME_SET_ZERO(t) set t to zero (memset is acceptable too)
*
* INSTR_TIME_SET_CURRENT(t) set t to current time
*
* INSTR_TIME_SET_CURRENT_LAZY(t) set t to current time if t is zero,
* evaluates to whether t changed
*
* INSTR_TIME_ADD(x, y) x += y
*
* INSTR_TIME_SUBTRACT(x, y) x -= y
*
* INSTR_TIME_ACCUM_DIFF(x, y, z) x += (y - z)
*
* INSTR_TIME_GET_DOUBLE(t) convert t to double (in seconds)
*
* INSTR_TIME_GET_MILLISEC(t) convert t to double (in milliseconds)
*
* INSTR_TIME_GET_MICROSEC(t) convert t to uint64 (in microseconds)
*
* Note that INSTR_TIME_SUBTRACT and INSTR_TIME_ACCUM_DIFF convert
* absolute times to intervals. The INSTR_TIME_GET_xxx operations are
* only useful on intervals.
*
* When summing multiple measurements, it's recommended to leave the
* running sum in instr_time form (ie, use INSTR_TIME_ADD or
* INSTR_TIME_ACCUM_DIFF) and convert to a result format only at the end.
*
* Beware of multiple evaluations of the macro arguments.
*
*
* Copyright (c) 2001-2019, PostgreSQL Global Development Group
*
* src/include/portability/instr_time.h
*
*-------------------------------------------------------------------------
*/
#ifndef INSTR_TIME_H
#define INSTR_TIME_H
#ifndef WIN32
#ifdef HAVE_CLOCK_GETTIME
/* Use clock_gettime() */
#include <time.h>
/*
* The best clockid to use according to the POSIX spec is CLOCK_MONOTONIC,
* since that will give reliable interval timing even in the face of changes
* to the system clock. However, POSIX doesn't require implementations to
* provide anything except CLOCK_REALTIME, so fall back to that if we don't
* find CLOCK_MONOTONIC.
*
* Also, some implementations have nonstandard clockids with better properties
* than CLOCK_MONOTONIC. In particular, as of macOS 10.12, Apple provides
* CLOCK_MONOTONIC_RAW which is both faster to read and higher resolution than
* their version of CLOCK_MONOTONIC.
*/
#if defined(__darwin__) && defined(CLOCK_MONOTONIC_RAW)
#define PG_INSTR_CLOCK CLOCK_MONOTONIC_RAW
#elif defined(CLOCK_MONOTONIC)
#define PG_INSTR_CLOCK CLOCK_MONOTONIC
#else
#define PG_INSTR_CLOCK CLOCK_REALTIME
#endif
typedef struct timespec instr_time;
#define INSTR_TIME_IS_ZERO(t) ((t).tv_nsec == 0 && (t).tv_sec == 0)
#define INSTR_TIME_SET_ZERO(t) ((t).tv_sec = 0, (t).tv_nsec = 0)
#define INSTR_TIME_SET_CURRENT(t) ((void) clock_gettime(PG_INSTR_CLOCK, &(t)))
#define INSTR_TIME_ASSIGN(x,y) ((x).tv_sec = (y).tv_sec, (x).tv_nsec = (y).tv_nsec)
#define INSTR_TIME_ADD(x,y) \
do { \
(x).tv_sec += (y).tv_sec; \
(x).tv_nsec += (y).tv_nsec; \
/* Normalize */ \
while ((x).tv_nsec >= 1000000000) \
{ \
(x).tv_nsec -= 1000000000; \
(x).tv_sec++; \
} \
} while (0)
#define INSTR_TIME_SUBTRACT(x,y) \
do { \
(x).tv_sec -= (y).tv_sec; \
(x).tv_nsec -= (y).tv_nsec; \
/* Normalize */ \
while ((x).tv_nsec < 0) \
{ \
(x).tv_nsec += 1000000000; \
(x).tv_sec--; \
} \
} while (0)
#define INSTR_TIME_ACCUM_DIFF(x,y,z) \
do { \
(x).tv_sec += (y).tv_sec - (z).tv_sec; \
(x).tv_nsec += (y).tv_nsec - (z).tv_nsec; \
/* Normalize after each add to avoid overflow/underflow of tv_nsec */ \
while ((x).tv_nsec < 0) \
{ \
(x).tv_nsec += 1000000000; \
(x).tv_sec--; \
} \
while ((x).tv_nsec >= 1000000000) \
{ \
(x).tv_nsec -= 1000000000; \
(x).tv_sec++; \
} \
} while (0)
#define INSTR_TIME_GET_DOUBLE(t) \
(((double) (t).tv_sec) + ((double) (t).tv_nsec) / 1000000000.0)
#define INSTR_TIME_GET_MILLISEC(t) \
(((double) (t).tv_sec * 1000.0) + ((double) (t).tv_nsec) / 1000000.0)
#define INSTR_TIME_GET_MICROSEC(t) \
(((uint64) (t).tv_sec * (uint64) 1000000) + (uint64) ((t).tv_nsec / 1000))
#else /* !HAVE_CLOCK_GETTIME */
/* Use gettimeofday() */
#include <sys/time.h>
typedef struct timeval instr_time;
#define INSTR_TIME_IS_ZERO(t) ((t).tv_usec == 0 && (t).tv_sec == 0)
#define INSTR_TIME_SET_ZERO(t) ((t).tv_sec = 0, (t).tv_usec = 0)
#define INSTR_TIME_SET_CURRENT(t) gettimeofday(&(t), NULL)
#define INSTR_TIME_ASSIGN(x,y) ((x).tv_sec = (y).tv_sec, (x).tv_usec = (y).tv_usec)
#define INSTR_TIME_ADD(x,y) \
do { \
(x).tv_sec += (y).tv_sec; \
(x).tv_usec += (y).tv_usec; \
/* Normalize */ \
while ((x).tv_usec >= 1000000) \
{ \
(x).tv_usec -= 1000000; \
(x).tv_sec++; \
} \
} while (0)
#define INSTR_TIME_SUBTRACT(x,y) \
do { \
(x).tv_sec -= (y).tv_sec; \
(x).tv_usec -= (y).tv_usec; \
/* Normalize */ \
while ((x).tv_usec < 0) \
{ \
(x).tv_usec += 1000000; \
(x).tv_sec--; \
} \
} while (0)
#define INSTR_TIME_ACCUM_DIFF(x,y,z) \
do { \
(x).tv_sec += (y).tv_sec - (z).tv_sec; \
(x).tv_usec += (y).tv_usec - (z).tv_usec; \
/* Normalize after each add to avoid overflow/underflow of tv_usec */ \
while ((x).tv_usec < 0) \
{ \
(x).tv_usec += 1000000; \
(x).tv_sec--; \
} \
while ((x).tv_usec >= 1000000) \
{ \
(x).tv_usec -= 1000000; \
(x).tv_sec++; \
} \
} while (0)
#define INSTR_TIME_GET_DOUBLE(t) \
(((double) (t).tv_sec) + ((double) (t).tv_usec) / 1000000.0)
#define INSTR_TIME_GET_MILLISEC(t) \
(((double) (t).tv_sec * 1000.0) + ((double) (t).tv_usec) / 1000.0)
#define INSTR_TIME_GET_MICROSEC(t) \
(((uint64) (t).tv_sec * (uint64) 1000000) + (uint64) (t).tv_usec)
#endif /* HAVE_CLOCK_GETTIME */
#else /* WIN32 */
/* Use QueryPerformanceCounter() */
typedef LARGE_INTEGER instr_time;
#define INSTR_TIME_IS_ZERO(t) ((t).QuadPart == 0)
#define INSTR_TIME_SET_ZERO(t) ((t).QuadPart = 0)
#define INSTR_TIME_SET_CURRENT(t) QueryPerformanceCounter(&(t))
#define INSTR_TIME_ASSIGN(x,y) ((x).QuadPart = (y).QuadPart)
#define INSTR_TIME_ADD(x,y) \
((x).QuadPart += (y).QuadPart)
#define INSTR_TIME_SUBTRACT(x,y) \
((x).QuadPart -= (y).QuadPart)
#define INSTR_TIME_ACCUM_DIFF(x,y,z) \
((x).QuadPart += (y).QuadPart - (z).QuadPart)
#define INSTR_TIME_GET_DOUBLE(t) \
(((double) (t).QuadPart) / GetTimerFrequency())
#define INSTR_TIME_GET_MILLISEC(t) \
(((double) (t).QuadPart * 1000.0) / GetTimerFrequency())
#define INSTR_TIME_GET_MICROSEC(t) \
((uint64) (((double) (t).QuadPart * 1000000.0) / GetTimerFrequency()))
static inline double
GetTimerFrequency(void)
{
LARGE_INTEGER f;
QueryPerformanceFrequency(&f);
return (double) f.QuadPart;
}
#endif /* WIN32 */
/* same macro on all platforms */
#define INSTR_TIME_SET_CURRENT_LAZY(t) \
(INSTR_TIME_IS_ZERO(t) ? INSTR_TIME_SET_CURRENT(t), true : false)
#endif /* INSTR_TIME_H */
|
7f16b0c33a1d86cacb6b02247b24c3c7ac4f0591
|
2182f6491025ada9a1466b5033b0b18e1c27f774
|
/resend.h
|
c80658bfd96208fb98b7e3bd8b32b65cb8c4608c
|
[
"MIT"
] |
permissive
|
jech/babeld
|
b57e75d173a0dc4dc2e197b5fd5d07db9829ea48
|
3d61ea1e843e2c5f9706c74d1adad4e1d24d44b9
|
refs/heads/master
| 2023-09-06T01:05:51.319978
| 2023-07-26T13:24:39
| 2023-07-26T13:24:39
| 2,145,286
| 333
| 93
|
MIT
| 2023-07-19T01:55:00
| 2011-08-02T21:40:59
|
C
|
UTF-8
|
C
| false
| false
| 2,700
|
h
|
resend.h
|
/*
Copyright (c) 2007, 2008 by Juliusz Chroboczek
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.
*/
#define REQUEST_TIMEOUT 65000
#define RESEND_MAX 3
#define RESEND_REQUEST 1
#define RESEND_UPDATE 2
struct resend {
unsigned char kind;
unsigned char max;
unsigned short delay;
struct timeval time;
unsigned char prefix[16];
unsigned char plen;
unsigned char src_prefix[16];
unsigned char src_plen;
unsigned short seqno;
unsigned char id[8];
struct interface *ifp;
struct resend *next;
};
extern struct timeval resend_time;
void flush_resends(struct neighbour *neigh);
int record_resend(int kind, const unsigned char *prefix, unsigned char plen,
const unsigned char *src_prefix, unsigned char src_plen,
unsigned short seqno, const unsigned char *id,
struct interface *ifp, int delay);
int unsatisfied_request(const unsigned char *prefix, unsigned char plen,
const unsigned char *src_prefix, unsigned char src_plen,
unsigned short seqno, const unsigned char *id);
int request_redundant(struct interface *ifp,
const unsigned char *prefix, unsigned char plen,
const unsigned char *src_prefix, unsigned char src_plen,
unsigned short seqno, const unsigned char *id);
int satisfy_request(const unsigned char *prefix, unsigned char plen,
const unsigned char *src_prefix, unsigned char src_plen,
unsigned short seqno, const unsigned char *id,
struct interface *ifp);
void expire_resend(void);
void recompute_resend_time(void);
void do_resend(void);
|
3f505e67721183c2d4662e01bb39ecd75d9d654b
|
55540f3e86f1d5d86ef6b5d295a63518e274efe3
|
/components/platform/soc/bl808/bl808_std/BL808_BSP_Driver/StdDriver/Src/bl808_glb.c
|
b97cc9c7c612e60021366963e056c39fd3a1ccee
|
[
"Apache-2.0"
] |
permissive
|
bouffalolab/bl_iot_sdk
|
bc5eaf036b70f8c65dd389439062b169f8d09daa
|
b90664de0bd4c1897a9f1f5d9e360a9631d38b34
|
refs/heads/master
| 2023-08-31T03:38:03.369853
| 2023-08-16T08:50:33
| 2023-08-18T09:13:27
| 307,347,250
| 244
| 101
|
Apache-2.0
| 2023-08-28T06:29:02
| 2020-10-26T11:16:30
|
C
|
UTF-8
|
C
| false
| false
| 98,282
|
c
|
bl808_glb.c
|
/*
* Copyright (c) 2016-2023 Bouffalolab.
*
* This file is part of
* *** Bouffalolab Software Dev Kit ***
* (see www.bouffalolab.com).
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 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 Bouffalo Lab nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "bl808_glb.h"
#include "bl808_clock.h"
#include "bl808_glb.h"
#include "bl808_aon.h"
#include "bl808_hbn.h"
#include "bl808_pds.h"
#include "cci_reg.h"
#include "glb_reg.h"
#include "bl808.h"
#define CCI_BASE ((uint32_t)0x20008000)
//#include "bl60x_mixed.h"
//#include "bl60x_aon.h"
//#include "bl60x_hbn.h"
/** @addtogroup BL60x_Peripheral_Driver
* @{
*/
/** @addtogroup GLB
* @{
*/
/** @defgroup GLB_Private_Macros
* @{
*/
#define GLB_GPIO_Get_Reg(pin) (mmsys_misc_gpio_reg_t*)(MMSYS_MISC_BASE+GLB_GPIO_OFFSET+(pin/2)*4)
#define GLB_CLK_SET_DUMMY_WAIT {__NOP();__NOP();__NOP();__NOP();__NOP();__NOP();__NOP();__NOP();}
/* MIPI PLL Config*/
const GLB_MU_PLL_CFG_BASIC_Type ATTR_CLOCK_CONST_SECTION mipiPllBasicCfg_24M = {
.clkpllRefdivRatio = 2, /*!< pll_refdiv_ratio */
.clkpllSelSampleClk = 2, /*!< pll_sel_sample_clk */
.clkpllVcoSpeed = 5, /*!< pll_vco_speed */
.clkpllEvenDivEn = 0, /*!< pll_even_div_en */
.clkpllEvenDivRatio = 0, /*!< pll_even_div_ratio */
};
const GLB_MU_PLL_CFG_BASIC_Type ATTR_CLOCK_CONST_SECTION mipiPllBasicCfg_32M = {
.clkpllRefdivRatio = 3, /*!< pll_refdiv_ratio */
.clkpllSelSampleClk = 2, /*!< pll_sel_sample_clk */
.clkpllVcoSpeed = 5, /*!< pll_vco_speed */
.clkpllEvenDivEn = 0, /*!< pll_even_div_en */
.clkpllEvenDivRatio = 0, /*!< pll_even_div_ratio */
};
const GLB_MU_PLL_CFG_BASIC_Type ATTR_CLOCK_CONST_SECTION mipiPllBasicCfg_38P4M = {
.clkpllRefdivRatio = 3, /*!< pll_refdiv_ratio */
.clkpllSelSampleClk = 2, /*!< pll_sel_sample_clk */
.clkpllVcoSpeed = 5, /*!< pll_vco_speed */
.clkpllEvenDivEn = 0, /*!< pll_even_div_en */
.clkpllEvenDivRatio = 0, /*!< pll_even_div_ratio */
};
const GLB_MU_PLL_CFG_BASIC_Type ATTR_CLOCK_CONST_SECTION mipiPllBasicCfg_40M = {
.clkpllRefdivRatio = 3, /*!< pll_refdiv_ratio */
.clkpllSelSampleClk = 2, /*!< pll_sel_sample_clk */
.clkpllVcoSpeed = 5, /*!< pll_vco_speed */
.clkpllEvenDivEn = 0, /*!< pll_even_div_en */
.clkpllEvenDivRatio = 0, /*!< pll_even_div_ratio */
};
const GLB_MU_PLL_CFG_BASIC_Type ATTR_CLOCK_CONST_SECTION mipiPllBasicCfg_26M = {
.clkpllRefdivRatio = 2, /*!< pll_refdiv_ratio */
.clkpllSelSampleClk = 2, /*!< pll_sel_sample_clk */
.clkpllVcoSpeed = 5, /*!< pll_vco_speed */
.clkpllEvenDivEn = 0, /*!< pll_even_div_en */
.clkpllEvenDivRatio = 0, /*!< pll_even_div_ratio */
};
const GLB_MU_PLL_Cfg_Type ATTR_CLOCK_CONST_SECTION mipiPllCfg_1500M[GLB_XTAL_MAX] = {
{ NULL, 0x0 }, /*!< XTAL is None */
{ &mipiPllBasicCfg_24M, 0x3E800 }, /*!< XTAL is 24M */
{ &mipiPllBasicCfg_32M, 0x46500 }, /*!< XTAL is 32M */
{ &mipiPllBasicCfg_38P4M, 0x3A980 }, /*!< XTAL is 38.4M */
{ &mipiPllBasicCfg_40M, 0x38400 }, /*!< XTAL is 40M */
{ &mipiPllBasicCfg_26M, 0x39B13 }, /*!< XTAL is 26M */
{ &mipiPllBasicCfg_32M, 0x46500 }, /*!< XTAL is RC32M */
};
/* uhs PLL 2100 Config*/
const GLB_MU_PLL_CFG_BASIC_Type ATTR_CLOCK_CONST_SECTION uhsPll2100BasicCfg_24M = {
.clkpllRefdivRatio = 1, /*!< pll_refdiv_ratio */
.clkpllSelSampleClk = 2, /*!< pll_sel_sample_clk */
.clkpllVcoSpeed = 7, /*!< pll_vco_speed */
.clkpllEvenDivEn = 1, /*!< pll_even_div_en */
.clkpllEvenDivRatio = 2100/50, /*!< pll_even_div_ratio */
};
const GLB_MU_PLL_CFG_BASIC_Type ATTR_CLOCK_CONST_SECTION uhsPll2100BasicCfg_32M = {
.clkpllRefdivRatio = 2, /*!< pll_refdiv_ratio */
.clkpllSelSampleClk = 2, /*!< pll_sel_sample_clk */
.clkpllVcoSpeed = 7, /*!< pll_vco_speed */
.clkpllEvenDivEn = 1, /*!< pll_even_div_en */
.clkpllEvenDivRatio = 2100/50, /*!< pll_even_div_ratio */
};
const GLB_MU_PLL_CFG_BASIC_Type ATTR_CLOCK_CONST_SECTION uhsPll2100BasicCfg_38P4M = {
.clkpllRefdivRatio = 2, /*!< pll_refdiv_ratio */
.clkpllSelSampleClk = 2, /*!< pll_sel_sample_clk */
.clkpllVcoSpeed = 7, /*!< pll_vco_speed */
.clkpllEvenDivEn = 1, /*!< pll_even_div_en */
.clkpllEvenDivRatio = 2100/50, /*!< pll_even_div_ratio */
};
const GLB_MU_PLL_CFG_BASIC_Type ATTR_CLOCK_CONST_SECTION uhsPll2100BasicCfg_40M = {
.clkpllRefdivRatio = 2, /*!< pll_refdiv_ratio */
.clkpllSelSampleClk = 2, /*!< pll_sel_sample_clk */
.clkpllVcoSpeed = 7, /*!< pll_vco_speed */
.clkpllEvenDivEn = 1, /*!< pll_even_div_en */
.clkpllEvenDivRatio = 2100/50, /*!< pll_even_div_ratio */
};
const GLB_MU_PLL_CFG_BASIC_Type ATTR_CLOCK_CONST_SECTION uhsPll2100BasicCfg_26M = {
.clkpllRefdivRatio = 1, /*!< pll_refdiv_ratio */
.clkpllSelSampleClk = 2, /*!< pll_sel_sample_clk */
.clkpllVcoSpeed = 7, /*!< pll_vco_speed */
.clkpllEvenDivEn = 1, /*!< pll_even_div_en */
.clkpllEvenDivRatio = 2100/50, /*!< pll_even_div_ratio */
};
const GLB_MU_PLL_Cfg_Type ATTR_CLOCK_CONST_SECTION uhsPllCfg_2100M[GLB_XTAL_MAX] = {
{ NULL, 0x0 }, /*!< XTAL is None */
{ &uhsPll2100BasicCfg_24M, 0x2BC00 }, /*!< XTAL is 24M */
{ &uhsPll2100BasicCfg_32M, 0x41A00 }, /*!< XTAL is 32M */
{ &uhsPll2100BasicCfg_38P4M, 0x36B00 }, /*!< XTAL is 38.4M */
{ &uhsPll2100BasicCfg_40M, 0x34800 }, /*!< XTAL is 40M */
{ &uhsPll2100BasicCfg_26M, 0x28627 }, /*!< XTAL is 26M */
{ &uhsPll2100BasicCfg_32M, 0x41A00 }, /*!< XTAL is RC32M */
};
/****************************************************************************//**
* @brief get core type
*
* @param None
*
* @return core type
*
*******************************************************************************/
GLB_CORE_ID_Type ATTR_CLOCK_SECTION GLB_Get_Core_Type(void)
{
uint32_t tmpVal = 0;
tmpVal = BL_RD_WORD(CORE_ID_ADDRESS);
switch(tmpVal){
case CORE_ID_M0:
return GLB_CORE_ID_M0;
case CORE_ID_M1:
return GLB_CORE_ID_M1;
case CORE_ID_D0:
return GLB_CORE_ID_D0;
case CORE_ID_D1:
return GLB_CORE_ID_D1;
case CORE_ID_LP:
return GLB_CORE_ID_LP;
default :
return GLB_CORE_ID_INVALID;
}
return GLB_CORE_ID_INVALID;
}
static int GLB_Get_BClk_Div(GLB_PLL_CLK_Type fClk)
{
/* keep BCLK <= 80MHz */
if (fClk==GLB_PLL_CLK_160M) return 1; /* divider 2 */
if (fClk==GLB_PLL_CLK_320M) return 3; /* divider 4 */
if (fClk==GLB_PLL_CLK_400M) return 4; /* divider 5 */
return 0; /* divider 1 */
}
/****************************************************************************//**
* @brief Set System root clock
*
* @param clkSel: root clock type selection
*
* @return None
*
*******************************************************************************/
void ATTR_CLOCK_SECTION GLB_Set_Root_CLK(GLB_Root_CLK_Type clkSel)
{
uint32_t tmpVal = 0;
/* Check the parameters */
CHECK_PARAM(IS_GLB_ROOT_CLK_TYPE(clkSel));
tmpVal=BL_RD_REG(CLKRST_BASE,CLKRST_MM_CLK_CTRL_CPU);
if(clkSel==GLB_ROOT_CLK_PLL_WITH_XTAL_ON){
/* Enable PLL selection before select */
tmpVal=BL_SET_REG_BIT(tmpVal,CLKRST_REG_PLL_EN);
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,CLKRST_HBN_ROOT_CLK_SEL,clkSel);
BL_WR_REG(CLKRST_BASE,CLKRST_MM_CLK_CTRL_CPU,tmpVal);
GLB_CLK_SET_DUMMY_WAIT;
}else{
/* TODO: for the first version, pll_en must keep 1, otherwise divider
is not available(take reg_bclk_div as 0 always) */
tmpVal=BL_SET_REG_BIT(tmpVal,CLKRST_REG_PLL_EN);
/* Select RC32M and XTAL first, so there is no risk of making bclk is more than 80M
if set reg_bclk_div 0 first then set hbn_root_clk_sel ,bclk maybe 160M after bclk_div is 0 */
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,CLKRST_HBN_ROOT_CLK_SEL,clkSel);
BL_WR_REG(CLKRST_BASE,CLKRST_MM_CLK_CTRL_CPU,tmpVal);
GLB_CLK_SET_DUMMY_WAIT;
/* HCLK is RC32M or XTAL, so BCLK no need divider */
tmpVal=BL_RD_REG(CLKRST_BASE,CLKRST_MM_CLK_CPU);
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,CLKRST_REG_BCLK_DIV,0);
BL_WR_REG(CLKRST_BASE,CLKRST_MM_CLK_CPU,tmpVal);
GLB_CLK_SET_DUMMY_WAIT;
}
}
/****************************************************************************//**
* @brief Select PLL output clock
*
* @param fClk: PLL clock type selection
*
* @return None
*
*******************************************************************************/
void ATTR_CLOCK_SECTION GLB_Set_PLL_CLK(GLB_PLL_CLK_Type fClk)
{
uint32_t tmpVal;
/* Check the parameters */
CHECK_PARAM(IS_GLB_PLL_CLK_TYPE(fClk));
/* Power off PLL clk before switch */
tmpVal=BL_RD_REG(CLKRST_BASE, CLKRST_MM_CLK_CTRL_CPU);
tmpVal=BL_CLR_REG_BIT(tmpVal, CLKRST_REG_PLL_EN);
BL_WR_REG(CLKRST_BASE, CLKRST_MM_CLK_CTRL_CPU, tmpVal);
GLB_CLK_SET_DUMMY_WAIT;
/* configure and power on PLL clock */
tmpVal=BL_RD_REG(CLKRST_BASE, CLKRST_MM_CLK_CPU);
tmpVal=BL_SET_REG_BITS_VAL(tmpVal, CLKRST_REG_CPU_CLK_DIV, 0); /* CPU clock same as PLL clock */
tmpVal=BL_SET_REG_BITS_VAL(tmpVal, CLKRST_REG_BCLK_DIV, GLB_Get_BClk_Div(fClk));
BL_WR_REG(CLKRST_BASE, CLKRST_MM_CLK_CPU, tmpVal);
tmpVal=BL_RD_REG(CLKRST_BASE, CLKRST_MM_CLK_CTRL_CPU);
tmpVal=BL_SET_REG_BITS_VAL(tmpVal, CLKRST_REG_PLL_SEL, fClk);
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,CLKRST_HBN_ROOT_CLK_SEL, 2); /* TODO: root clk selet PLL */
tmpVal=BL_SET_REG_BIT(tmpVal, CLKRST_REG_PLL_EN);
BL_WR_REG(CLKRST_BASE, CLKRST_MM_CLK_CTRL_CPU, tmpVal);
GLB_CLK_SET_DUMMY_WAIT;
}
void ATTR_CLOCK_SECTION GLB_Set_System_CLK_Div(uint8_t hclkDiv,uint8_t bclkDiv)
{
uint32_t tmpVal;
tmpVal=BL_RD_REG(CLKRST_BASE, CLKRST_MM_CLK_CTRL_CPU);
tmpVal=BL_SET_REG_BITS_VAL(tmpVal, CLKRST_REG_CPU_CLK_DIV, hclkDiv);
tmpVal=BL_SET_REG_BITS_VAL(tmpVal, CLKRST_REG_BCLK_DIV, bclkDiv);
BL_WR_REG(CLKRST_BASE, CLKRST_MM_CLK_CTRL_CPU, tmpVal);
GLB_CLK_SET_DUMMY_WAIT;
}
extern uint32_t SystemCoreClock;
void ATTR_CLOCK_SECTION GLB_Set_System_CLK(GLB_PLL_CLK_Type fClk)
{
/* Before config XTAL and PLL ,make sure root clk is from RC32M */
GLB_Set_Root_CLK(GLB_ROOT_CLK_RC32M);
SystemCoreClock=32*1000*1000;
/* select PLL clock */
GLB_Set_PLL_CLK(fClk);
switch(fClk)
{
case GLB_PLL_CLK_120M:
SystemCoreClock=120*1000*1000;
break;
case GLB_PLL_CLK_160M:
SystemCoreClock=160*1000*1000;
break;
case GLB_PLL_CLK_320M:
SystemCoreClock=320*1000*1000;
break;
case GLB_PLL_CLK_400M:
SystemCoreClock=400*1000*1000;
break;
}
GLB_Set_Root_CLK(GLB_ROOT_CLK_PLL_WITH_XTAL_ON);
}
void ATTR_CLOCK_SECTION SystemCoreClockUpdate (void)
{
uint32_t tmpVal;
tmpVal = BL_RD_REG(CLKRST_BASE, CLKRST_CIP);
tmpVal = BL_SET_REG_BIT(tmpVal, CLKRST_PU_MBG);
BL_WR_REG(CLKRST_BASE, CLKRST_CIP, tmpVal);
tmpVal = BL_SET_REG_BIT(tmpVal, CLKRST_PU_SFREG);
BL_WR_REG(CLKRST_BASE, CLKRST_CIP, tmpVal);
tmpVal = BL_RD_REG(CLKRST_BASE, CLKRST_CLKIP1);
tmpVal = BL_SET_REG_BIT(tmpVal, CLKRST_CLKPLL_PPU);
tmpVal = BL_SET_REG_BIT(tmpVal, CLKRST_CLKPLL_PU);
tmpVal = BL_SET_REG_BIT(tmpVal, CLKRST_CLKPLL2_PPU);
tmpVal = BL_SET_REG_BIT(tmpVal, CLKRST_CLKPLL2_PU);
BL_WR_REG(CLKRST_BASE, CLKRST_CLKIP1, tmpVal);
tmpVal = BL_RD_REG(CLKRST_BASE, CLKRST_CLKIP2);
tmpVal = BL_SET_REG_BIT(tmpVal, CLKRST_CLKPLL_RESET);
BL_WR_REG(CLKRST_BASE, CLKRST_CLKIP2, tmpVal);
GLB_CLK_SET_DUMMY_WAIT;
tmpVal = BL_CLR_REG_BIT(tmpVal, CLKRST_CLKPLL_RESET);
BL_WR_REG(CLKRST_BASE, CLKRST_CLKIP2, tmpVal);
//GLB_Set_Fbdiv_Ratio(19); /* adjust 160M PLL to 152M */
#if CPU_CA5
GLB_Set_System_CLK(GLB_PLL_CLK_400M);
#else
GLB_Set_System_CLK(GLB_PLL_CLK_160M);
#endif
#if 0 /* adjust PLL 160M to 152M, so as to get 76M HDMI clk */
tmpVal = BL_RD_REG(CLKRST_BASE, CLKRST_CLKIP4);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CLKRST_CLKPLL2_FBDIV_RATIO, 19);
BL_WR_REG(CLKRST_BASE, CLKRST_CLKIP4, tmpVal);
#endif
}
#if 0
void GLB_Set_WiFi_Core_CLK(uint8_t clkDiv)
{
uint32_t tmpVal;
tmpVal=BL_RD_REG(CLKRST_BASE,GLB_CLK_CFG1);
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GLB_REG_WIFI_MAC_CORE_DIV,clkDiv);
BL_WR_REG(CLKRST_BASE,GLB_CLK_CFG1,tmpVal);
}
void GLB_Set_WiFi_Encrypt_CLK(uint8_t clkDiv)
{
uint32_t tmpVal;
tmpVal=BL_RD_REG(CLKRST_BASE,GLB_CLK_CFG1);
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GLB_REG_WIFI_MAC_WT_DIV,clkDiv);
BL_WR_REG(CLKRST_BASE,GLB_CLK_CFG1,tmpVal);
}
void ATTR_VRAM_SECTION GLB_Set_PSRAM_CLK(GLB_PSRAM_CLK_Type clkSel)
{
uint32_t tmpVal;
/* power off psram clk before switch */
tmpVal = BL_RD_REG(CLKRST_BASE, CLKRST_MM_CLK_CTRL_EMI);
tmpVal = BL_CLR_REG_BIT(tmpVal, CLKRST_REG_PSRAMA_CLK_EN);
tmpVal = BL_CLR_REG_BIT(tmpVal, CLKRST_REG_PSRAMB_CLK_EN);
BL_WR_REG(CLKRST_BASE, CLKRST_MM_CLK_CTRL_EMI, tmpVal);
/* configure and power on PLL clock */
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CLKRST_REG_PSRAMA_CLK_SEL, clkSel);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CLKRST_REG_PSRAMB_CLK_SEL, clkSel);
tmpVal = BL_SET_REG_BIT(tmpVal, CLKRST_REG_PSRAMA_CLK_EN);
tmpVal = BL_SET_REG_BIT(tmpVal, CLKRST_REG_PSRAMB_CLK_EN);
BL_WR_REG(CLKRST_BASE, CLKRST_MM_CLK_CTRL_EMI, tmpVal);
BL_LOGI("[Set_PSRAM_CLK] %d\r\n", clkSel);
}
void GLB_Select_Internal_Flash(void)
{
uint32_t tmpVal;
tmpVal=BL_RD_REG(CLKRST_BASE,GLB_PARM);
tmpVal=BL_SET_REG_BIT(tmpVal,GLB_SEL_EMBEDDED_SFLASH);
BL_WR_REG(CLKRST_BASE,GLB_PARM,tmpVal);
}
void GLB_Select_External_Flash(void)
{
uint32_t tmpVal;
tmpVal=BL_RD_REG(CLKRST_BASE,GLB_PARM);
tmpVal=BL_CLR_REG_BIT(tmpVal,GLB_SEL_EMBEDDED_SFLASH);
BL_WR_REG(CLKRST_BASE,GLB_PARM,tmpVal);
}
void GLB_Deswap_Flash_Pin()
{
uint32_t tmpVal;
tmpVal=BL_RD_REG(CLKRST_BASE,GLB_PARM);
tmpVal=BL_CLR_REG_BIT(tmpVal,GLB_SWAP_SFLASH_IO_3_IO_0);
BL_WR_REG(CLKRST_BASE,GLB_PARM,tmpVal);
}
void GLB_Swap_Flash_Pin()
{
uint32_t tmpVal;
tmpVal=BL_RD_REG(CLKRST_BASE,GLB_PARM);
tmpVal=BL_SET_REG_BIT(tmpVal,GLB_SWAP_SFLASH_IO_3_IO_0);
BL_WR_REG(CLKRST_BASE,GLB_PARM,tmpVal);
}
void GLB_Set_Flash_CLK(GLB_SFLASH_CLK_Type clkSel,uint8_t clkDiv)
{
MIXED_PLL_CLK_Type clk;
uint32_t tmpVal;
tmpVal=BL_RD_REG(CLKRST_BASE,GLB_CLK_CFG1);
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GLB_REG_SF_CLK_DIV,0);
BL_WR_REG(CLKRST_BASE,GLB_CLK_CFG1,tmpVal);
switch(clkSel)
{
case GLB_SFLASH_CLK_120M:
/* Flash CLK is divied by 240M */
clk=PLL_CLK_240M;
Mixed_Enable_PLL_Clk(clk);
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GLB_REG_SF_CLK_SEL,clkSel);
BL_WR_REG(CLKRST_BASE,GLB_CLK_CFG1,tmpVal);
break;
case GLB_SFLASH_CLK_80M:
/* Flash CLK is divied by 320M */
clk=PLL_CLK_320M;
Mixed_Enable_PLL_Clk(clk);
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GLB_REG_SF_CLK_SEL,clkSel);
BL_WR_REG(CLKRST_BASE,GLB_CLK_CFG1,tmpVal);
break;
case GLB_SFLASH_CLK_FDIV2:
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GLB_REG_SF_CLK_SEL,clkSel);
BL_WR_REG(CLKRST_BASE,GLB_CLK_CFG1,tmpVal);
break;
case GLB_SFLASH_CLK_96M:
clk=PLL_CLK_96M;
Mixed_Enable_PLL_Clk(clk);
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GLB_REG_SF_CLK_SEL,clkSel);
BL_WR_REG(CLKRST_BASE,GLB_CLK_CFG1,tmpVal);
break;
case GLB_SFLASH_CLK_XTAL:
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GLB_REG_SF_CLK_DIV,1);
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GLB_REG_SF_CLK_SEL,GLB_SFLASH_CLK_120M);
BL_WR_REG(CLKRST_BASE,GLB_CLK_CFG1,tmpVal);
break;
case GLB_SFLASH_CLK_50M:
clk=PLL_CLK_100M;
Mixed_Enable_PLL_Clk(clk);
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GLB_REG_SF_CLK_DIV,3);
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GLB_REG_SF_CLK_SEL,GLB_SFLASH_CLK_120M);
BL_WR_REG(CLKRST_BASE,GLB_CLK_CFG1,tmpVal);
break;
default:
/* Flash CLK is divied by 320M */
clk=PLL_CLK_320M;
Mixed_Enable_PLL_Clk(clk);
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GLB_REG_SF_CLK_SEL,clkSel);
BL_WR_REG(CLKRST_BASE,GLB_CLK_CFG1,tmpVal);
break;
}
}
#endif
void GLB_DMA_CLK_Enable(GLB_DMA_CLK_ID_Type clk)
{
uint32_t tmpVal;
uint32_t tmpVal2;
tmpVal = BL_RD_REG(MMSYS_MISC_BASE, MMSYS_MISC_DMA_CLK_CTRL);
tmpVal2 = BL_GET_REG_BITS_VAL(tmpVal, MMSYS_MISC_DMA_CLK_EN);
tmpVal2 |= (1<<clk);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MMSYS_MISC_DMA_CLK_EN, tmpVal2);
BL_WR_REG(MMSYS_MISC_BASE, MMSYS_MISC_DMA_CLK_CTRL, tmpVal);
}
void GLB_DMA_CLK_Disable(GLB_DMA_CLK_ID_Type clk)
{
uint32_t tmpVal;
uint32_t tmpVal2;
tmpVal=BL_RD_REG(MMSYS_MISC_BASE, MMSYS_MISC_DMA_CLK_CTRL);
tmpVal2 = BL_GET_REG_BITS_VAL(tmpVal, MMSYS_MISC_DMA_CLK_EN);
tmpVal2 &= (~(1<<clk));
tmpVal=BL_SET_REG_BITS_VAL(tmpVal, MMSYS_MISC_DMA_CLK_EN, tmpVal2);
BL_WR_REG(MMSYS_MISC_BASE, MMSYS_MISC_DMA_CLK_CTRL, tmpVal);
}
/****************************************************************************/ /**
* @brief set spi clock
*
* @param enable: ENABLE or DISABLE
* @param div: div
*
* @return SUCCESS or ERROR
*
*******************************************************************************/
BL_Err_Type GLB_Set_DSP_SPI_CLK(uint8_t enable, GLB_DSP_SPI_CLK_Type clkSel, uint8_t div)
{
uint32_t tmpVal = 0;
CHECK_PARAM(IS_GLB_DSP_SPI_CLK_TYPE(clkSel));
tmpVal = BL_RD_REG(MM_GLB_BASE, MM_GLB_MM_CLK_CTRL_PERI);
tmpVal = BL_CLR_REG_BIT(tmpVal, MM_GLB_REG_SPI_CLK_DIV_EN);
BL_WR_REG(MM_GLB_BASE, MM_GLB_MM_CLK_CTRL_PERI, tmpVal);
tmpVal = BL_RD_REG(MM_GLB_BASE, MM_GLB_MM_CLK_CTRL_CPU);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MM_GLB_REG_SPI_CLK_SEL, clkSel);
BL_WR_REG(MM_GLB_BASE, MM_GLB_MM_CLK_CTRL_CPU, tmpVal);
tmpVal = BL_RD_REG(MM_GLB_BASE, MM_GLB_MM_CLK_CTRL_PERI);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MM_GLB_REG_SPI_CLK_DIV, div);
if (enable) {
tmpVal = BL_SET_REG_BIT(tmpVal, MM_GLB_REG_SPI_CLK_DIV_EN);
} else {
tmpVal = BL_CLR_REG_BIT(tmpVal, MM_GLB_REG_SPI_CLK_DIV_EN);
}
BL_WR_REG(MM_GLB_BASE, MM_GLB_MM_CLK_CTRL_PERI, tmpVal);
return SUCCESS;
}
void GLB_Set_UART_CLK(BL_Fun_Type enable, GLB_UART_CLK_Type clkSel, uint8_t clkDiv)
{
uint32_t tmpVal;
if (enable) {
/* configure UART clk */
tmpVal = BL_RD_REG(CLKRST_BASE, CLKRST_MM_CLK_CTRL_CPU);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CLKRST_HBN_UART_CLK_SEL, clkSel);
BL_WR_REG(CLKRST_BASE, CLKRST_MM_CLK_CTRL_CPU, tmpVal);
/* configure clk div and power on UART clk */
tmpVal = BL_RD_REG(CLKRST_BASE, CLKRST_MM_CLK_CTRL_PERI);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CLKRST_REG_UART_CLK_DIV, clkDiv);
tmpVal = BL_SET_REG_BIT(tmpVal, CLKRST_REG_UART_CLK_DIV_EN);
} else {
tmpVal = BL_RD_REG(CLKRST_BASE, CLKRST_MM_CLK_CTRL_PERI);
tmpVal = BL_CLR_REG_BIT(tmpVal, CLKRST_REG_UART_CLK_DIV_EN);
}
BL_WR_REG(CLKRST_BASE, CLKRST_MM_CLK_CTRL_PERI, tmpVal);
}
void GLB_Set_SDH_CLK(BL_Fun_Type enable, GLB_SDH_CLK_Type clkSel)
{
uint32_t tmpVal;
tmpVal = BL_RD_REG(CLKRST_BASE, CLKRST_MM_CLK_CTRL_PERI);
if (enable) {
/* configure and power on SDH clk */
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CLKRST_REG_SDH_CLK_SEL, clkSel);
tmpVal = BL_SET_REG_BIT(tmpVal, CLKRST_REG_SDH_CLK_EN);
} else {
tmpVal = BL_CLR_REG_BIT(tmpVal, CLKRST_REG_SDH_CLK_EN);
}
BL_WR_REG(CLKRST_BASE, CLKRST_MM_CLK_CTRL_PERI, tmpVal);
}
void GLB_Set_PDM_CLK(uint8_t id, BL_Fun_Type enable, uint8_t clkDiv)
{
uint32_t tmpVal;
tmpVal=BL_RD_REG(CLKRST_BASE, CLKRST_MM_CLK_CTRL_PERI2);
if (id == 0) {
if(enable) {
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CLKRST_REG_PDM0_CLK_DIV, clkDiv);
tmpVal = BL_SET_REG_BIT(tmpVal, CLKRST_REG_PDM0_CLK_EN);
} else {
tmpVal = BL_CLR_REG_BIT(tmpVal, CLKRST_REG_PDM0_CLK_EN);
}
} else if (id == 1) {
if(enable) {
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CLKRST_REG_PDM1_CLK_DIV, clkDiv);
tmpVal = BL_SET_REG_BIT(tmpVal, CLKRST_REG_PDM1_CLK_EN);
} else {
tmpVal = BL_CLR_REG_BIT(tmpVal, CLKRST_REG_PDM1_CLK_EN);
}
}
BL_WR_REG(CLKRST_BASE, CLKRST_MM_CLK_CTRL_PERI2, tmpVal);
}
void GLB_Set_I2S_CLK(uint8_t id, BL_Fun_Type enable, uint8_t refSel, uint8_t outClkEnable, uint8_t outClkDiv)
{
uint32_t tmpVal;
tmpVal = BL_RD_REG(CLKRST_BASE, CLKRST_MM_CLK_CTRL_PERI2);
if (id == 0) {
if (enable) {
tmpVal = BL_SET_REG_BIT(tmpVal, CLKRST_REG_I2S0_CLK_EN);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CLKRST_REG_I2S0_CLK_DIV, outClkDiv);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CLKRST_REG_I2S0_REF_CLK_OE, outClkEnable);
} else {
tmpVal = BL_CLR_REG_BIT(tmpVal, CLKRST_REG_I2S0_CLK_EN);
}
} else if (id == 1) {
if (enable) {
tmpVal = BL_SET_REG_BIT(tmpVal, CLKRST_REG_I2S1_CLK_EN);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CLKRST_REG_I2S1_CLK_DIV, outClkDiv);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CLKRST_REG_I2S1_REF_CLK_OE, outClkEnable);
} else {
tmpVal = BL_CLR_REG_BIT(tmpVal, CLKRST_REG_I2S1_CLK_EN);
}
}
BL_WR_REG(CLKRST_BASE,CLKRST_MM_CLK_CTRL_PERI2,tmpVal);
}
// void GLB_Set_I2C_CLK(uint8_t id, BL_Fun_Type enable)
// {
// uint32_t tmpVal;
// tmpVal = BL_RD_REG(CLKRST_BASE, CLKRST_MM_CLK_CTRL_PERI);
// /* always use bclk as I2C source clock without clk div. Each I2C module has its own clk div */
// tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CLKRST_REG_I2C_CLK_DIV, 0);
// if (id == 0) {
// if (enable) {
// tmpVal = BL_SET_REG_BIT(tmpVal, CLKRST_REG_I2CA_CLK_EN);
// } else {
// tmpVal = BL_CLR_REG_BIT(tmpVal, CLKRST_REG_I2CA_CLK_EN);
// }
// } else if (id == 1) {
// if (enable) {
// tmpVal = BL_SET_REG_BIT(tmpVal, CLKRST_REG_I2CB_CLK_EN);
// } else {
// tmpVal = BL_CLR_REG_BIT(tmpVal, CLKRST_REG_I2CB_CLK_EN);
// }
// }
// BL_WR_REG(CLKRST_BASE, CLKRST_MM_CLK_CTRL_PERI, tmpVal);
// }
/****************************************************************************/ /**
* @brief set SPI clock
*
* @param enable: Enable or disable SPI clock
* @param clkSel: clock selection
* @param div: divider
*
* @return SUCCESS or ERROR
*
*******************************************************************************/
BL_Err_Type GLB_Set_SPI_CLK(uint8_t enable, GLB_SPI_CLK_Type clkSel, uint8_t div)
{
uint32_t tmpVal = 0;
CHECK_PARAM(IS_GLB_SPI_CLK_TYPE(clkSel));
CHECK_PARAM((div <= 0x1F));
tmpVal = BL_RD_REG(GLB_BASE, GLB_SPI_CFG0);
tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_SPI_CLK_EN);
BL_WR_REG(GLB_BASE, GLB_SPI_CFG0, tmpVal);
tmpVal = BL_RD_REG(GLB_BASE, GLB_SPI_CFG0);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SPI_CLK_DIV, div);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SPI_CLK_SEL, clkSel);
BL_WR_REG(GLB_BASE, GLB_SPI_CFG0, tmpVal);
tmpVal = BL_RD_REG(GLB_BASE, GLB_SPI_CFG0);
if (enable) {
tmpVal = BL_SET_REG_BIT(tmpVal, GLB_SPI_CLK_EN);
} else {
tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_SPI_CLK_EN);
}
BL_WR_REG(GLB_BASE, GLB_SPI_CFG0, tmpVal);
return SUCCESS;
}
BL_Err_Type GLB_Set_I2C_CLK(uint8_t enable, GLB_I2C_CLK_Type clkSel, uint8_t div)
{
uint32_t tmpVal = 0;
CHECK_PARAM(IS_GLB_I2C_CLK_TYPE(clkSel));
tmpVal = BL_RD_REG(GLB_BASE, GLB_I2C_CFG0);
tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_I2C_CLK_EN);
BL_WR_REG(GLB_BASE, GLB_I2C_CFG0, tmpVal);
tmpVal = BL_RD_REG(GLB_BASE, GLB_I2C_CFG0);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_I2C_CLK_SEL, clkSel);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_I2C_CLK_DIV, div);
BL_WR_REG(GLB_BASE, GLB_I2C_CFG0, tmpVal);
tmpVal = BL_RD_REG(GLB_BASE, GLB_I2C_CFG0);
if (enable) {
tmpVal = BL_SET_REG_BIT(tmpVal, GLB_I2C_CLK_EN);
} else {
tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_I2C_CLK_EN);
}
BL_WR_REG(GLB_BASE, GLB_I2C_CFG0, tmpVal);
return SUCCESS;
}
/****************************************************************************/ /**
* @brief reconfigure CPUPLL clock
*
* @param xtalType: XTAL frequency type
* @param pllCfg: PLL configuration
*
* @return SUCCESS or ERROR
*
*******************************************************************************/
BL_Err_Type ATTR_CLOCK_SECTION GLB_Config_CPU_PLL(GLB_XTAL_Type xtalType, const GLB_WAC_PLL_Cfg_Type * pllCfgList)
{
GLB_PLL_REF_CLK_Type refClk;
if (xtalType == GLB_XTAL_RC32M) {
refClk = GLB_PLL_REFCLK_RC32M;
} else {
refClk = GLB_PLL_REFCLK_XTAL;
}
GLB_Power_Off_WAC_PLL(GLB_WAC_PLL_CPUPLL);
GLB_WAC_PLL_Ref_Clk_Sel(GLB_WAC_PLL_CPUPLL, refClk);
GLB_Power_On_WAC_PLL(GLB_WAC_PLL_CPUPLL, &(pllCfgList[xtalType]), 1);
return SUCCESS;
}
/****************************************************************************/ /**
* @brief reconfigure MIPIPLL clock
*
* @param xtalType: XTAL frequency type
* @param pllCfg: PLL configuration
*
* @return SUCCESS or ERROR
*
*******************************************************************************/
BL_Err_Type ATTR_CLOCK_SECTION GLB_Config_MIPI_PLL(GLB_XTAL_Type xtalType, const GLB_MU_PLL_Cfg_Type * pllCfgList)
{
GLB_PLL_REF_CLK_Type refClk;
if (xtalType == GLB_XTAL_RC32M) {
refClk = GLB_PLL_REFCLK_RC32M;
} else {
refClk = GLB_PLL_REFCLK_XTAL;
}
GLB_Power_Off_MU_PLL(GLB_MU_PLL_MIPIPLL);
GLB_MU_PLL_Ref_Clk_Sel(GLB_MU_PLL_MIPIPLL, refClk);
GLB_Power_On_MU_PLL(GLB_MU_PLL_MIPIPLL, &(pllCfgList[xtalType]), 1);
return SUCCESS;
}
/****************************************************************************/ /**
* @brief reconfigure MIPIPLL clock div
*
* @param divEn: div enable
* @param divRatio: div ratio
*
* @return SUCCESS or ERROR
*
*******************************************************************************/
BL_Err_Type ATTR_CLOCK_SECTION GLB_Config_MIPI_PLL_Div(uint8_t divEn, uint8_t divRatio)
{
uint32_t REG_PLL_BASE_ADDRESS = 0;
uint32_t tmpVal = 0;
REG_PLL_BASE_ADDRESS = GLB_BASE + GLB_MIPI_PLL_CFG0_OFFSET;
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 1);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_MIPIPLL_EVEN_DIV_EN, divEn);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_MIPIPLL_EVEN_DIV_RATIO, divRatio);
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 1, tmpVal);
return SUCCESS;
}
/****************************************************************************/ /**
* @brief GLB power off mipi uhs PLL
*
* @param pllType: PLL XTAL type
*
* @return SUCCESS or ERROR
*
*******************************************************************************/
BL_Err_Type ATTR_CLOCK_SECTION GLB_Power_Off_MU_PLL(GLB_MU_PLL_Type pllType)
{
uint32_t REG_PLL_BASE_ADDRESS = 0;
uint32_t tmpVal = 0;
//CHECK_PARAM(IS_GLB_Power_Off_MU_TYPE(pllType));
switch (pllType) {
case GLB_MU_PLL_MIPIPLL:
REG_PLL_BASE_ADDRESS = GLB_BASE + GLB_MIPI_PLL_CFG0_OFFSET;
break;
case GLB_MU_PLL_UHSPLL:
REG_PLL_BASE_ADDRESS = GLB_BASE + GLB_UHS_PLL_CFG0_OFFSET;
break;
default:
REG_PLL_BASE_ADDRESS = GLB_BASE + GLB_MIPI_PLL_CFG0_OFFSET;
break;
}
/* cfg0 : pu_aupll=0 */
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 0);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_PU_AUPLL, 0);
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 0, tmpVal);
/* cfg0 : pu_aupll_sfreg=0 */
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 0);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_PU_AUPLL_SFREG, 0);
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 0, tmpVal);
return SUCCESS;
}
/****************************************************************************/ /**
* @brief GLB mipi uhs PLL ref clock select
*
* @param pllType: PLL XTAL type
* @param refClk: PLL ref clock select
*
* @return SUCCESS or ERROR
*
*******************************************************************************/
BL_Err_Type ATTR_CLOCK_SECTION GLB_MU_PLL_Ref_Clk_Sel(GLB_MU_PLL_Type pllType, GLB_PLL_REF_CLK_Type refClk)
{
uint32_t REG_PLL_BASE_ADDRESS = 0;
uint32_t tmpVal = 0;
// CHECK_PARAM(IS_GLB_WAC_PLL_TYPE(pllType));
// CHECK_PARAM(IS_GLB_PLL_REF_CLK_TYPE(refClk));
switch (pllType) {
case GLB_MU_PLL_MIPIPLL:
REG_PLL_BASE_ADDRESS = GLB_BASE + GLB_MIPI_PLL_CFG0_OFFSET;
break;
case GLB_MU_PLL_UHSPLL:
REG_PLL_BASE_ADDRESS = GLB_BASE + GLB_UHS_PLL_CFG0_OFFSET;
break;
default:
REG_PLL_BASE_ADDRESS = GLB_BASE + GLB_MIPI_PLL_CFG0_OFFSET;
break;
}
/* xxxpll_refclk_sel */
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 1);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_REFCLK_SEL, refClk);
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 1, tmpVal);
return SUCCESS;
}
/****************************************************************************/ /**
* @brief GLB power on PLL
*
* @param pllType: PLL XTAL type
* @param cfg: GLB PLL configuration
* @param waitStable: wait PLL stable
*
* @return SUCCESS or ERROR
*
*******************************************************************************/
BL_Err_Type ATTR_CLOCK_SECTION GLB_Power_On_MU_PLL(GLB_MU_PLL_Type pllType, const GLB_MU_PLL_Cfg_Type *const cfg, uint8_t waitStable)
{
uint32_t REG_PLL_BASE_ADDRESS = 0;
uint32_t tmpVal = 0;
/* unknown */
//CHECK_PARAM(IS_GLB_WAC_PLL_TYPE(pllType));
switch (pllType) {
case GLB_MU_PLL_MIPIPLL:
REG_PLL_BASE_ADDRESS = GLB_BASE + GLB_MIPI_PLL_CFG0_OFFSET;
break;
case GLB_MU_PLL_UHSPLL:
REG_PLL_BASE_ADDRESS = GLB_BASE + GLB_UHS_PLL_CFG0_OFFSET;
break;
default:
REG_PLL_BASE_ADDRESS = GLB_BASE + GLB_MIPI_PLL_CFG0_OFFSET;
break;
}
/* Step1:config parameter */
/* cfg1:Set aupll_refclk_sel and aupll_refdiv_ratio */
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 1);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_REFDIV_RATIO, cfg->basicCfg->clkpllRefdivRatio);
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 1, tmpVal);
/* cfg4:Set aupll_sel_sample_clk */
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 4);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_SEL_SAMPLE_CLK, cfg->basicCfg->clkpllSelSampleClk);
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 4, tmpVal);
/* cfg5:Set aupll_vco_speed */
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 5);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_VCO_SPEED, cfg->basicCfg->clkpllVcoSpeed);
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 5, tmpVal);
/* cfg1: uhspll_even_div_en and uhspll_even_div_ratio */
if (GLB_MU_PLL_UHSPLL == pllType) {
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 1);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_UHSPLL_EVEN_DIV_EN, cfg->basicCfg->clkpllEvenDivEn);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_UHSPLL_EVEN_DIV_RATIO, cfg->basicCfg->clkpllEvenDivRatio);
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 1, tmpVal);
}
/* cfg6:Set aupll_sdm_bypass,aupll_sdmin */
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 6);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_SDMIN, cfg->clkpllSdmin);
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 6, tmpVal);
/* Step2:config pu */
/* cfg0 : pu_aupll_sfreg=1 */
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 0);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_PU_AUPLL_SFREG, 1);
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 0, tmpVal);
/* delay > 2us */
// arch_delay_us(3);
/* cfg0 : pu_wifipll=1 */
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 0);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_PU_AUPLL, 1);
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 0, tmpVal);
/* delay > 2us */
// arch_delay_us(3);
/* toggle sdm_reset (pulse 0 > 1us) */
/* cfg0 : aupll_sdm_reset */
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 0);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_SDM_RSTB, 1);
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 0, tmpVal);
//arch_delay_us(2);
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 0);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_SDM_RSTB, 0);
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 0, tmpVal);
// arch_delay_us(2);
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 0);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_SDM_RSTB, 1);
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 0, tmpVal);
/* Step3:reset pll */
/* cfg0 : toggle aupll_reset_fbdv, pulse 0 > 1us */
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 0);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_FBDV_RSTB, 1);
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 0, tmpVal);
//arch_delay_us(2);
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 0);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_FBDV_RSTB, 0);
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 0, tmpVal);
// arch_delay_us(2);
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 0);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_FBDV_RSTB, 1);
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 0, tmpVal);
if (waitStable) {
/* Wait 1.5*30us */
// arch_delay_us(45);
}
return SUCCESS;
}
/****************************************************************************/ /**
* @brief GLB power off wifi audio cpu PLL
*
* @param pllType: PLL XTAL type
*
* @return SUCCESS or ERROR
*
*******************************************************************************/
BL_Err_Type ATTR_CLOCK_SECTION GLB_Power_Off_WAC_PLL(GLB_WAC_PLL_Type pllType)
{
uint32_t REG_PLL_BASE_ADDRESS = 0;
uint32_t tmpVal = 0;
CHECK_PARAM(IS_GLB_WAC_PLL_TYPE(pllType));
switch (pllType) {
case GLB_WAC_PLL_WIFIPLL:
REG_PLL_BASE_ADDRESS = GLB_BASE + GLB_WIFI_PLL_CFG0_OFFSET;
break;
case GLB_WAC_PLL_AUPLL:
REG_PLL_BASE_ADDRESS = CCI_BASE + CCI_AUDIO_PLL_CFG0_OFFSET;
break;
case GLB_WAC_PLL_CPUPLL:
REG_PLL_BASE_ADDRESS = CCI_BASE + CCI_CPU_PLL_CFG0_OFFSET;
break;
default:
REG_PLL_BASE_ADDRESS = CCI_BASE + CCI_AUDIO_PLL_CFG0_OFFSET;
break;
}
/* cfg0 : pu_aupll=0 */
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 0);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_PU_AUPLL, 0);
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 0, tmpVal);
/* cfg0 : pu_aupll_sfreg=0 */
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 0);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_PU_AUPLL_SFREG, 0);
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 0, tmpVal);
return SUCCESS;
}
/****************************************************************************/ /**
* @brief GLB wifi audio cpu PLL ref clock select
*
* @param pllType: PLL XTAL type
* @param refClk: PLL ref clock select
*
* @return SUCCESS or ERROR
*
*******************************************************************************/
BL_Err_Type ATTR_CLOCK_SECTION GLB_WAC_PLL_Ref_Clk_Sel(GLB_WAC_PLL_Type pllType, GLB_PLL_REF_CLK_Type refClk)
{
uint32_t REG_PLL_BASE_ADDRESS = 0;
uint32_t tmpVal = 0;
CHECK_PARAM(IS_GLB_WAC_PLL_TYPE(pllType));
CHECK_PARAM(IS_GLB_PLL_REF_CLK_TYPE(refClk));
switch (pllType) {
case GLB_WAC_PLL_WIFIPLL:
REG_PLL_BASE_ADDRESS = GLB_BASE + GLB_WIFI_PLL_CFG0_OFFSET;
break;
case GLB_WAC_PLL_AUPLL:
REG_PLL_BASE_ADDRESS = CCI_BASE + CCI_AUDIO_PLL_CFG0_OFFSET;
break;
case GLB_WAC_PLL_CPUPLL:
REG_PLL_BASE_ADDRESS = CCI_BASE + CCI_CPU_PLL_CFG0_OFFSET;
break;
default:
REG_PLL_BASE_ADDRESS = CCI_BASE + CCI_AUDIO_PLL_CFG0_OFFSET;
break;
}
/* xxxpll_refclk_sel */
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 1);
if ((GLB_WAC_PLL_WIFIPLL == pllType) && (GLB_PLL_REFCLK_XTAL == refClk)) {
/* wifipll_refclk_sel different from other's pll, 1 means xtal */
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_REFCLK_SEL, 1);
} else {
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_REFCLK_SEL, refClk);
}
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 1, tmpVal);
return SUCCESS;
}
/****************************************************************************/ /**
* @brief GLB power on PLL
*
* @param pllType: PLL XTAL type
* @param cfg: GLB PLL configuration
* @param waitStable: wait PLL clock stable
*
* @return SUCCESS or ERROR
*
*******************************************************************************/
BL_Err_Type ATTR_CLOCK_SECTION GLB_Power_On_WAC_PLL(GLB_WAC_PLL_Type pllType, const GLB_WAC_PLL_Cfg_Type *const cfg, uint8_t waitStable)
{
uint32_t REG_PLL_BASE_ADDRESS = 0;
uint32_t tmpVal = 0;
/* unknown */
CHECK_PARAM(IS_GLB_WAC_PLL_TYPE(pllType));
switch (pllType) {
case GLB_WAC_PLL_WIFIPLL:
REG_PLL_BASE_ADDRESS = GLB_BASE + GLB_WIFI_PLL_CFG0_OFFSET;
break;
case GLB_WAC_PLL_AUPLL:
REG_PLL_BASE_ADDRESS = CCI_BASE + CCI_AUDIO_PLL_CFG0_OFFSET;
break;
case GLB_WAC_PLL_CPUPLL:
REG_PLL_BASE_ADDRESS = CCI_BASE + CCI_CPU_PLL_CFG0_OFFSET;
break;
default:
REG_PLL_BASE_ADDRESS = CCI_BASE + CCI_AUDIO_PLL_CFG0_OFFSET;
break;
}
/* Step1:config parameter */
/* cfg1:Set aupll_refclk_sel and aupll_refdiv_ratio */
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 1);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_REFDIV_RATIO, cfg->basicCfg->clkpllRefdivRatio);
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 1, tmpVal);
/* cfg2:Set aupll_int_frac_sw,aupll_icp_1u,aupll_icp_5u */
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 2);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_INT_FRAC_SW, cfg->basicCfg->clkpllIntFracSw);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_ICP_1U, cfg->basicCfg->clkpllIcp1u);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_ICP_5U, cfg->basicCfg->clkpllIcp5u);
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 2, tmpVal);
/* cfg3:Set aupll_rz,aupll_cz,aupll_c3,aupll_r4_short,aupll_r4_en */
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 3);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_RZ, cfg->basicCfg->clkpllRz);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_CZ, cfg->basicCfg->clkpllCz);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_C3, cfg->basicCfg->clkpllC3);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_R4_SHORT, cfg->basicCfg->clkpllR4Short);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_C4_EN, cfg->basicCfg->clkpllC4En);
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 3, tmpVal);
/* cfg4:Set aupll_sel_sample_clk */
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 4);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_SEL_SAMPLE_CLK, cfg->basicCfg->clkpllSelSampleClk);
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 4, tmpVal);
/* cfg5:Set aupll_vco_speed */
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 5);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_VCO_SPEED, cfg->basicCfg->clkpllVcoSpeed);
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 5, tmpVal);
/* cfg6:Set aupll_sdm_bypass,aupll_sdmin */
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 6);
if (GLB_WAC_PLL_WIFIPLL == pllType) {
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_WIFIPLL_SDM_CTRL_HW, cfg->basicCfg->clkpllSdmCtrlHw);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_WIFIPLL_SDM_BYPASS, cfg->basicCfg->clkpllSdmBypass);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_WIFIPLL_SDMIN, cfg->clkpllSdmin);
} else {
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_SDM_BYPASS, cfg->basicCfg->clkpllSdmBypass);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_SDMIN, cfg->clkpllSdmin);
}
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 6, tmpVal);
/* Step2:config pu */
/* cfg0 : pu_aupll_sfreg=1 */
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 0);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_PU_AUPLL_SFREG, 1);
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 0, tmpVal);
/* delay > 2us */
// arch_delay_us(3);
/* cfg0 : pu_wifipll=1 */
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 0);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_PU_AUPLL, 1);
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 0, tmpVal);
/* delay > 2us */
//arch_delay_us(3);
/* toggle sdm_reset (pulse 0 > 1us) */
/* cfg0 : aupll_sdm_reset */
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 0);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_SDM_RSTB, 1);
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 0, tmpVal);
//arch_delay_us(2);
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 0);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_SDM_RSTB, 0);
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 0, tmpVal);
//arch_delay_us(2);
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 0);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_SDM_RSTB, 1);
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 0, tmpVal);
/* Step3:reset pll */
/* cfg0 : toggle aupll_reset_fbdv, pulse 0 > 1us */
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 0);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_FBDV_RSTB, 1);
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 0, tmpVal);
//arch_delay_us(2);
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 0);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_FBDV_RSTB, 0);
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 0, tmpVal);
//arch_delay_us(2);
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 0);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_FBDV_RSTB, 1);
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 0, tmpVal);
/* aupll : cfg1, aupll_postdiv = 0x12 or 0x14 */
if (GLB_WAC_PLL_AUPLL == pllType) {
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 1);
if ((cfg->clkpllSdmin==0x12D0E)||(cfg->clkpllSdmin==0x1C395)||(cfg->clkpllSdmin==0x17851)||(cfg->clkpllSdmin==0x16944)||(cfg->clkpllSdmin==0x115E5)) {
/* 451.548 */
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_POSTDIV, 0x14);
} else {
/* 442.368 */
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CCI_AUPLL_POSTDIV, 0x12);
}
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 1, tmpVal);
}
/* Step4:enable output clock */
/* wifipll : cfg5, wifipll_vco_div3_en=1 */
if (GLB_WAC_PLL_WIFIPLL == pllType) {
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 5);
tmpVal = BL_SET_REG_BIT(tmpVal, GLB_WIFIPLL_VCO_DIV3_EN);
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 5, tmpVal);
}
/* cfg8 : wifipll->wifipll_en_ctrl_hw=1 */
tmpVal = BL_RD_WORD(REG_PLL_BASE_ADDRESS + 4 * 8);
if (GLB_WAC_PLL_WIFIPLL == pllType) {
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_WIFIPLL_EN_CTRL_HW, 1);
}
/* cfg8 : wifipll/aupll/cpupll clock enable */
switch (pllType) {
case GLB_WAC_PLL_WIFIPLL:
tmpVal = BL_SET_REG_BIT(tmpVal, GLB_WIFIPLL_EN_DIV4);
tmpVal = BL_SET_REG_BIT(tmpVal, GLB_WIFIPLL_EN_DIV5);
tmpVal = BL_SET_REG_BIT(tmpVal, GLB_WIFIPLL_EN_DIV6);
tmpVal = BL_SET_REG_BIT(tmpVal, GLB_WIFIPLL_EN_DIV8);
tmpVal = BL_SET_REG_BIT(tmpVal, GLB_WIFIPLL_EN_DIV10);
break;
case GLB_WAC_PLL_AUPLL:
tmpVal = BL_SET_REG_BIT(tmpVal, CCI_AUPLL_EN_DIV1);
tmpVal = BL_SET_REG_BIT(tmpVal, CCI_AUPLL_EN_DIV2);
tmpVal = BL_SET_REG_BIT(tmpVal, CCI_AUPLL_EN_DIV2P5);
tmpVal = BL_SET_REG_BIT(tmpVal, CCI_AUPLL_EN_DIV5);
tmpVal = BL_SET_REG_BIT(tmpVal, CCI_AUPLL_EN_DIV6);
break;
case GLB_WAC_PLL_CPUPLL:
tmpVal = BL_SET_REG_BIT(tmpVal, CCI_CPUPLL_EN_DIV1);
tmpVal = BL_SET_REG_BIT(tmpVal, CCI_CPUPLL_EN_DIV2);
tmpVal = BL_SET_REG_BIT(tmpVal, CCI_CPUPLL_EN_DIV2P5);
tmpVal = BL_SET_REG_BIT(tmpVal, CCI_CPUPLL_EN_DIV4);
tmpVal = BL_SET_REG_BIT(tmpVal, CCI_CPUPLL_EN_DIV5);
break;
default:
break;
}
BL_WR_WORD(REG_PLL_BASE_ADDRESS + 4 * 8, tmpVal);
if (waitStable) {
/* Wait 1.5*30us */
// arch_delay_us(45);
}
return SUCCESS;
}
/****************************************************************************/ /**
* @brief GLB set display clock
*
* @param enable: ENABLE or DISABLE
* @param srcClk: source clock type
* @param evenDiv: divider in even number
*
* @return SUCCESS or ERROR
*
*******************************************************************************/
BL_Err_Type GLB_Set_Display_CLK(uint8_t enable, GLB_DISP_CLK_Type srcClk, uint8_t evenDiv)
{
uint32_t tmpVal = 0;
uint32_t evenNum = 0;
CHECK_PARAM(IS_GLB_DISP_CLK_TYPE(srcClk));
CHECK_PARAM((evenDiv <= 0x7F));
tmpVal = BL_RD_REG(GLB_BASE, GLB_MIPI_PLL_CFG1);
tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_MIPIPLL_EVEN_DIV_EN);
BL_WR_REG(GLB_BASE, GLB_MIPI_PLL_CFG1, tmpVal);
if ((evenDiv >= 8) && (evenDiv <= 126)) {
evenNum = evenDiv & ~(1 << 0);
} else {
evenNum = evenDiv;
}
tmpVal = BL_RD_REG(GLB_BASE, GLB_MIPI_PLL_CFG1);
if(enable){
tmpVal = BL_SET_REG_BIT(tmpVal, GLB_MIPIPLL_EVEN_DIV_EN);
}else{
tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_MIPIPLL_EVEN_DIV_EN);
}
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_MIPIPLL_EVEN_DIV_RATIO, evenNum);
BL_WR_REG(GLB_BASE, GLB_MIPI_PLL_CFG1, tmpVal);
return SUCCESS;
}
BL_Err_Type GLB_Set_DSP_I2C0_CLK(uint8_t enable, GLB_DSP_I2C_CLK_Type clkSel, uint8_t divEn, uint8_t div)
{
uint32_t tmpVal = 0;
CHECK_PARAM(IS_GLB_DSP_I2C_CLK_TYPE(clkSel));
tmpVal = BL_RD_REG(MM_GLB_BASE, MM_GLB_MM_CLK_CTRL_PERI);
tmpVal = BL_CLR_REG_BIT(tmpVal, MM_GLB_REG_I2C0_CLK_EN);
BL_WR_REG(MM_GLB_BASE, MM_GLB_MM_CLK_CTRL_PERI, tmpVal);
tmpVal = *(uint32_t *)0x30007000;
tmpVal = tmpVal & ~(1<<6);
*(uint32_t *)0x30007000 = tmpVal;
// tmpVal = BL_RD_REG(MM_GLB_BASE, MM_GLB_MM_CLK_CTRL_CPU);
// tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MM_GLB_REG_I2C_CLK_SEL, clkSel);
// BL_WR_REG(MM_GLB_BASE, MM_GLB_MM_CLK_CTRL_CPU, tmpVal);
tmpVal = BL_RD_REG(MM_GLB_BASE, MM_GLB_MM_CLK_CTRL_PERI);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MM_GLB_REG_I2C0_CLK_DIV, div);
if (enable) {
tmpVal = BL_SET_REG_BIT(tmpVal, MM_GLB_REG_I2C0_CLK_EN);
} else {
tmpVal = BL_CLR_REG_BIT(tmpVal, MM_GLB_REG_I2C0_CLK_EN);
}
if (divEn) {
tmpVal = BL_SET_REG_BIT(tmpVal, MM_GLB_REG_I2C0_CLK_DIV_EN);
} else {
tmpVal = BL_CLR_REG_BIT(tmpVal, MM_GLB_REG_I2C0_CLK_DIV_EN);
}
BL_WR_REG(MM_GLB_BASE, MM_GLB_MM_CLK_CTRL_PERI, tmpVal);
return SUCCESS;
}
void GLB_Set_HDMI_CLK(BL_Fun_Type enable, HDMI_CLK_SEL_E clkSel, uint8_t outClkDiv)
{
uint32_t tmpVal;
tmpVal = BL_RD_REG(CLKRST_BASE, CLKRST_ISP_DP_CLK);
if (enable) {
tmpVal = BL_SET_REG_BIT(tmpVal, CLKRST_REG_HDMI_CLK_DIV_EN);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CLKRST_REG_DISP_CLK_SEL, clkSel);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CLKRST_REG_DISP_CLK_DIV, outClkDiv);
} else {
tmpVal = BL_CLR_REG_BIT(tmpVal, CLKRST_REG_HDMI_CLK_DIV_EN);
}
BL_WR_REG(CLKRST_BASE, CLKRST_ISP_DP_CLK, tmpVal);
}
void GLB_Set_H264_CLK(BL_Fun_Type enable, H264_CLK_SEL_E clkSel, uint8_t outClkDiv)
{
uint32_t tmpVal;
tmpVal = BL_RD_REG(CLKRST_BASE, CLKRST_ISP_DP_CLK);
if (enable) {
tmpVal = BL_SET_REG_BIT(tmpVal, CLKRST_REG_H264_CLK_DIV_EN);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CLKRST_REG_H264_CLK_SEL, clkSel);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CLKRST_REG_H264_CLK_DIV, outClkDiv);
} else {
tmpVal = BL_CLR_REG_BIT(tmpVal, CLKRST_REG_H264_CLK_DIV_EN);
}
BL_WR_REG(CLKRST_BASE, CLKRST_ISP_DP_CLK, tmpVal);
}
void ATTR_CLOCK_SECTION GLB_Set_Fbdiv_Ratio(uint32_t ratio)
{
uint32_t tmpVal = BL_RD_REG(CLKRST_BASE, CLKRST_CLKIP4);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CLKRST_CLKPLL2_FBDIV_RATIO, ratio);
BL_WR_REG(CLKRST_BASE, CLKRST_CLKIP4, tmpVal);
}
void ATTR_CLOCK_SECTION GLB_Enable_PLL_CLK(GLB_PLL_CLK_EN_Type clkSel)
{
uint32_t tmpVal;
tmpVal = BL_RD_REG(CLKRST_BASE, CLKRST_CLKIP_POSTDIV);
switch (clkSel)
{
case GLB_CLKPLL_EN_25M:
tmpVal = BL_SET_REG_BIT(tmpVal, CLKRST_CLKPLL_EN_25M_CLK);
break;
case GLB_CLKPLL_EN_50M:
tmpVal = BL_SET_REG_BIT(tmpVal, CLKRST_CLKPLL_EN_50M_CLK);
break;
case GLB_CLKPLL_EN_100M:
tmpVal = BL_SET_REG_BIT(tmpVal, CLKRST_CLKPLL_EN_100M_CLK);
break;
case GLB_CLKPLL_EN_120M:
tmpVal = BL_SET_REG_BIT(tmpVal, CLKRST_CLKPLL_EN_120M_CLK);
break;
case GLB_CLKPLL_EN_160M:
tmpVal = BL_SET_REG_BIT(tmpVal, CLKRST_CLKPLL_EN_160M_CLK);
break;
case GLB_CLKPLL_EN_192M:
tmpVal = BL_SET_REG_BIT(tmpVal, CLKRST_CLKPLL_EN_192M_CLK);
break;
case GLB_CLKPLL_EN_240M:
tmpVal = BL_SET_REG_BIT(tmpVal, CLKRST_CLKPLL_EN_240M_CLK);
break;
case GLB_CLKPLL_EN_267M:
tmpVal = BL_SET_REG_BIT(tmpVal, CLKRST_CLKPLL_EN_267M_CLK);
break;
case GLB_CLKPLL_EN_320M:
tmpVal = BL_SET_REG_BIT(tmpVal, CLKRST_CLKPLL_EN_320M_CLK);
break;
case GLB_CLKPLL_EN_400M:
tmpVal = BL_SET_REG_BIT(tmpVal, CLKRST_CLKPLL_EN_400M_CLK);
break;
}
BL_WR_REG(CLKRST_BASE, CLKRST_CLKIP_POSTDIV, tmpVal);
}
/****************************************************************************//**
* @brief Power on audio PLL function
*
* @param clkType: Audio PLL clock type
* @param posDivCount: Audio MCLK divider
*
* @return None
*
*******************************************************************************/
void GLB_Power_On_Audio_PLL(uint32_t audClk)
{
uint32_t tmpVal = 0;
uint32_t fXtal = 38.4*1000000;
uint32_t aupllSdmin;
uint8_t postDiv;
uint8_t refDiv;
/* f_audio_pll_out = f_xtal * aupll_sdmin_real / aupll_postdiv / aupll_refdiv_ratio */
tmpVal = BL_RD_REG(CLKRST_BASE, CLKRST_CLKIP_AUPLL1);
refDiv = BL_GET_REG_BITS_VAL(tmpVal, CLKRST_AUPLL_REFDIV_RATIO);
aupllSdmin = BL_RD_REG(CLKRST_BASE, CLKRST_CLKIP_AUPLL2);
postDiv = ((fXtal / 100000) * aupllSdmin / (audClk / 100000) / refDiv) >> 17;
tmpVal=BL_RD_REG(CLKRST_BASE, CLKRST_CLKIP_AUPLL3);
tmpVal=BL_SET_REG_BITS_VAL(tmpVal, CLKRST_AUPLL_POSTDIV, postDiv&0x7F);
tmpVal=BL_SET_REG_BIT(tmpVal, CLKRST_AUPLL_PU);
BL_WR_REG(CLKRST_BASE, CLKRST_CLKIP_AUPLL3, tmpVal);
tmpVal=BL_RD_REG(CLKRST_BASE, CLKRST_MM_CLK_CTRL_PERI2);
tmpVal=BL_CLR_REG_BIT(tmpVal, CLKRST_REG_I2S0_REF_CLK_OE);
tmpVal=BL_SET_REG_BIT(tmpVal, CLKRST_REG_I2S0_CLK_EN);
BL_WR_REG(CLKRST_BASE, CLKRST_MM_CLK_CTRL_PERI2, tmpVal);
#if 0
/*enable I2S mclk output*/
tmpVal=BL_RD_REG(MMSYS_MISC_BASE, MMSYS_MISC_GPIO_CTL);
tmpVal=BL_SET_REG_BIT(tmpVal, MMSYS_MISC_REG_DEBUG_OE);
BL_WR_REG(CLKRST_BASE, MMSYS_MISC_GPIO_CTL, tmpVal);
tmpVal=BL_RD_REG(MMSYS_MISC_BASE, MMSYS_MISC_REG_DBG_LL_CTRL);
tmpVal=BL_SET_REG_BITS_VAL(tmpVal, MMSYS_MISC_REG_DBG_LL, 0xC0000008);
BL_WR_REG(MMSYS_MISC_BASE, MMSYS_MISC_REG_DBG_LL_CTRL, tmpVal);
#endif
}
void GLB_Set_Cam_Ref_CLK(BL_Fun_Type enable, uint8_t clkSel, uint8_t clkDiv)
{
uint32_t tmpVal;
tmpVal=BL_RD_REG(GLB_BASE,GLB_CAM_CFG0);
if(enable){
tmpVal=BL_SET_REG_BIT(tmpVal,GLB_REG_CAM_REF_CLK_EN);
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GLB_REG_CAM_REF_CLK_SRC_SEL, clkSel);
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GLB_REG_CAM_REF_CLK_DIV,clkDiv);
}else{
tmpVal=BL_CLR_REG_BIT(tmpVal,GLB_REG_CAM_REF_CLK_EN);
}
BL_WR_REG(GLB_BASE,GLB_CAM_CFG0,tmpVal);
}
void GLB_Set_ClkOutSel(uint8_t clkout_num, uint8_t val)
{
uint32_t tmpVal;
tmpVal=BL_RD_REG(GLB_BASE,GLB_DIG_CLK_CFG2);
switch (clkout_num)
{
case 0:
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GLB_CHIP_CLK_OUT_0_SEL, val);
break;
case 1:
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GLB_CHIP_CLK_OUT_1_SEL, val);
break;
case 2:
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GLB_CHIP_CLK_OUT_2_SEL, val);
break;
case 3:
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GLB_CHIP_CLK_OUT_3_SEL, val);
break;
}
BL_WR_REG(GLB_BASE,GLB_DIG_CLK_CFG2,tmpVal);
}
#if 0
void GLB_Set_SSP_CLK(BL_Fun_Type enable,uint8_t clkDiv)
{
uint32_t tmpVal;
tmpVal=BL_RD_REG(CLKRST_BASE,GLB_I2C_SSP_CLK_CTRL);
if(enable){
tmpVal=BL_SET_REG_BIT(tmpVal,GLB_REG_SSP_CLK_EN);
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GLB_REG_SSP_CLK_DIV,clkDiv);
BL_WR_REG(CLKRST_BASE,GLB_I2C_SSP_CLK_CTRL,tmpVal);
}else{
tmpVal=BL_CLR_REG_BIT(tmpVal,GLB_REG_SSP_CLK_EN);
BL_WR_REG(CLKRST_BASE,GLB_I2C_SSP_CLK_CTRL,tmpVal);
}
}
void GLB_Enable_Dig32K_CLK(void)
{
uint32_t tmpVal;
tmpVal=BL_RD_REG(CLKRST_BASE,GLB_WIFI_LP32K_WAKEUP_CTRL);
tmpVal=BL_SET_REG_BIT(tmpVal,GLB_REG_EN_DIG_32K_GEN);
BL_WR_REG(CLKRST_BASE,GLB_WIFI_LP32K_WAKEUP_CTRL,tmpVal);
}
void GLB_Disable_Dig32K_CLK(void)
{
uint32_t tmpVal;
tmpVal=BL_RD_REG(CLKRST_BASE,GLB_WIFI_LP32K_WAKEUP_CTRL);
tmpVal=BL_CLR_REG_BIT(tmpVal,GLB_REG_EN_DIG_32K_GEN);
BL_WR_REG(CLKRST_BASE,GLB_WIFI_LP32K_WAKEUP_CTRL,tmpVal);
}
void GLB_Set_DAC_CLK(BL_Fun_Type enable,GLB_DAC_CLK_Type clk)
{
uint32_t tmpVal;
tmpVal=BL_RD_REG(CLKRST_BASE,GLB_WIFI_LP32K_WAKEUP_CTRL);
if(enable){
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GLB_REG_512K_SEL,clk);
tmpVal=BL_SET_REG_BIT(tmpVal,GLB_REG_EN_DIG_32K_GEN);
}else{
tmpVal=BL_CLR_REG_BIT(tmpVal,GLB_REG_EN_DIG_32K_GEN);
}
BL_WR_REG(CLKRST_BASE,GLB_WIFI_LP32K_WAKEUP_CTRL,tmpVal);
}
void GLB_Sleep_CLK_Gate_Enable()
{
uint32_t tmpVal;
tmpVal=BL_RD_REG(CLKRST_BASE,GLB_CLK_CFG1);
tmpVal=BL_CLR_REG_BIT(tmpVal,GLB_CM4_GATEHCLK_DIS);
BL_WR_REG(CLKRST_BASE,GLB_CLK_CFG1,tmpVal);
}
void GLB_Sleep_CLK_Gate_Disable()
{
uint32_t tmpVal;
tmpVal=BL_RD_REG(CLKRST_BASE,GLB_CLK_CFG1);
tmpVal=BL_SET_REG_BIT(tmpVal,GLB_CM4_GATEHCLK_DIS);
BL_WR_REG(CLKRST_BASE,GLB_CLK_CFG1,tmpVal);
}
void GLB_AHB_Slave0_Reset(BL_AHB_Slave0_Type slave)
{
uint32_t tmpVal;
tmpVal=BL_RD_REG(CLKRST_BASE,GLB_SWRST_S0);
tmpVal |= (1<<slave);
BL_WR_REG(CLKRST_BASE,GLB_SWRST_S0,tmpVal);
tmpVal &= (~(1<<slave));
BL_WR_REG(CLKRST_BASE,GLB_SWRST_S0,tmpVal);
}
void GLB_AHB_Slave1_Reset(BL_AHB_Slave1_Type slave)
{
uint32_t tmpVal;
tmpVal=BL_RD_REG(CLKRST_BASE,GLB_SWRST_S1);
tmpVal |= (1<<slave);
BL_WR_REG(CLKRST_BASE,GLB_SWRST_S1,tmpVal);
tmpVal &= (~(1<<slave));
BL_WR_REG(CLKRST_BASE,GLB_SWRST_S1,tmpVal);
}
void GLB_AHB_Slave2_Reset(BL_AHB_Slave2_Type slave)
{
uint32_t tmpVal;
tmpVal=BL_RD_REG(CLKRST_BASE,GLB_SWRST_S2);
tmpVal |= (1<<slave);
BL_WR_REG(CLKRST_BASE,GLB_SWRST_S2,tmpVal);
tmpVal &= (~(1<<slave));
BL_WR_REG(CLKRST_BASE,GLB_SWRST_S2,tmpVal);
}
void GLB_AHB_Slave3_Reset(BL_AHB_Slave3_Type slave)
{
uint32_t tmpVal;
tmpVal=BL_RD_REG(CLKRST_BASE,GLB_SWRST_S3);
tmpVal |= (1<<slave);
BL_WR_REG(CLKRST_BASE,GLB_SWRST_S3,tmpVal);
tmpVal &= (~(1<<slave));
BL_WR_REG(CLKRST_BASE,GLB_SWRST_S3,tmpVal);
}
void GLB_SW_POR_Reset()
{
uint32_t tmpVal;
GLB_Set_Root_CLK(GLB_ROOT_CLK_RC32M);
tmpVal=BL_RD_REG(CLKRST_BASE,GLB_SWRST_GLB);
tmpVal=BL_CLR_REG_BIT(CLKRST_BASE,GLB_REG_CTRL_PWRON_RST);
BL_WR_REG(CLKRST_BASE,GLB_SWRST_GLB,tmpVal);
tmpVal=BL_SET_REG_BIT(CLKRST_BASE,GLB_REG_CTRL_PWRON_RST);
BL_WR_REG(CLKRST_BASE,GLB_SWRST_GLB,tmpVal);
/* POR reset is ASYN ,waiting for reset */
while(1){
BL60X_Delay_US(10);
}
}
#endif
void GLB_SW_CPU_Reset(GLB_CPU_SEL_Type cpu)
{
uint32_t tmpVal;
tmpVal = BL_RD_REG(CLKRST_BASE, CLKRST_MM_SW_SYS_RESET);
if (cpu == GLB_CPU_CM4) {
tmpVal = BL_CLR_REG_BIT(CLKRST_BASE, CLKRST_REG_CTRL_CPU_RESET);
BL_WR_REG(CLKRST_BASE, CLKRST_MM_SW_SYS_RESET, tmpVal);
tmpVal = BL_SET_REG_BIT(CLKRST_BASE, CLKRST_REG_CTRL_CPU_RESET);
BL_WR_REG(CLKRST_BASE, CLKRST_MM_SW_SYS_RESET, tmpVal);
} else if (cpu == GLB_CPU_CA5) {
tmpVal = BL_CLR_REG_BIT(CLKRST_BASE, CLKRST_REG_CTRL_A5_CPU_RESET);
BL_WR_REG(CLKRST_BASE, CLKRST_MM_SW_SYS_RESET, tmpVal);
tmpVal = BL_SET_REG_BIT(CLKRST_BASE, CLKRST_REG_CTRL_A5_CPU_RESET);
BL_WR_REG(CLKRST_BASE, CLKRST_MM_SW_SYS_RESET, tmpVal);
}
}
void GLB_SW_System_Reset(void)
{
uint32_t tmpVal;
tmpVal = BL_RD_REG(CLKRST_BASE, CLKRST_MM_SW_SYS_RESET);
tmpVal = BL_CLR_REG_BIT(CLKRST_BASE, CLKRST_REG_CTRL_SYS_RESET);
BL_WR_REG(CLKRST_BASE, CLKRST_MM_SW_SYS_RESET, tmpVal);
tmpVal = BL_SET_REG_BIT(CLKRST_BASE, CLKRST_REG_CTRL_SYS_RESET);
BL_WR_REG(CLKRST_BASE, CLKRST_MM_SW_SYS_RESET, tmpVal);
}
#if 0
void GLB_Uart_Fun_Sel(GLB_UART_SIG_Type sig,GLB_UART_SIG_FUN_Type fun)
{
uint32_t sig_pos=0;
uint32_t tmpVal;
if(sig<=GLB_UART_SIG_7){
tmpVal=BL_RD_REG(CLKRST_BASE,GLB_UART_SIG_SEL_0);
sig_pos=(sig*4);
/* Clear original val */
tmpVal &= (~(0xf<<sig_pos));
/* Set new value */
tmpVal |= (fun<<sig_pos);
BL_WR_REG(CLKRST_BASE,GLB_UART_SIG_SEL_0,tmpVal);
}else{
tmpVal=BL_RD_REG(CLKRST_BASE,GLB_UART_SIG_SEL_1);
sig -= GLB_UART_SIG_8;
sig_pos=(sig*4);
/* Clear original val*/
tmpVal &= (~(0xf<<sig_pos));
/* Set new value */
tmpVal |= (fun<<sig_pos);
BL_WR_REG(CLKRST_BASE,GLB_UART_SIG_SEL_1,tmpVal);
}
}
void GLB_L2C_Hit_Count_Get(uint32_t *hitCountLow,uint32_t *hitCountHigh)
{
*hitCountLow=BL_RD_REG(MMSYS_MISC_BASE,GLB_L2C_HIT_CNT_LSB);
*hitCountHigh=BL_RD_REG(MMSYS_MISC_BASE,GLB_L2C_HIT_CNT_MSB);
}
uint32_t GLB_L2C_Miss_Count_Get(void)
{
return BL_RD_REG(MMSYS_MISC_BASE,GLB_L2C_MISS_CNT);
}
#endif
#if 0
BL_Err_Type ATTR_TCM_SECTION GLB_GPIO_Init(GLB_GPIO_Cfg_Type *cfg)
{
uint8_t gpioPin = cfg->gpioPin;
uint32_t gpioCfgAddress;
uint32_t tmpVal;
/* drive strength(drive) = 0 <=> 8.0mA @ 3.3V */
/* drive strength(drive) = 1 <=> 9.6mA @ 3.3V */
/* drive strength(drive) = 2 <=> 11.2mA @ 3.3V */
/* drive strength(drive) = 3 <=> 12.8mA @ 3.3V */
gpioCfgAddress = GLB_BASE + GLB_GPIO_CFG0_OFFSET + (gpioPin << 2);
/* Disable output anyway*/
tmpVal = BL_RD_WORD(gpioCfgAddress);
tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_OE);
BL_WR_WORD(gpioCfgAddress, tmpVal);
/* input/output, pull up/down, drive, smt, function */
tmpVal = BL_RD_WORD(gpioCfgAddress);
if (cfg->gpioMode != GPIO_MODE_ANALOG) {
/* not analog mode */
if (cfg->gpioMode == GPIO_MODE_OUTPUT) {
tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_IE);
tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_0_OE);
} else {
tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_0_IE);
tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_OE);
}
if (cfg->pullType == GPIO_PULL_UP) {
tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_0_PU);
tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_PD);
} else if (cfg->pullType == GPIO_PULL_DOWN) {
tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_PU);
tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_0_PD);
} else {
tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_PU);
tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_PD);
}
} else {
/* analog mode */
/* clear ie && oe */
tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_IE);
tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_OE);
/* clear pu && pd */
tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_PU);
tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_PD);
}
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_0_DRV, cfg->drive);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_0_SMT, cfg->smtCtrl);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_0_FUNC_SEL, cfg->gpioFun);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_0_MODE, cfg->outputMode);
BL_WR_WORD(gpioCfgAddress, tmpVal);
return SUCCESS;
}
uint8_t GLB_GPIO_Get_Fun(GLB_GPIO_Type gpioPin)
{
uint32_t tmpVal;
tmpVal=BL_RD_WORD(MMSYS_MISC_BASE+MMSYS_MISC_GPIO_OFFSET+gpioPin/2*4);
if(gpioPin%2==0){
return BL_GET_REG_BITS_VAL(tmpVal, MMSYS_MISC_REG_GPIO_0_FUNC_SEL);
}else{
return BL_GET_REG_BITS_VAL(tmpVal, MMSYS_MISC_REG_GPIO_1_FUNC_SEL);
}
}
BL_Err_Type GLB_GPIO_Write(GLB_GPIO_Type gpioPin,uint32_t val)
{
uint32_t *pOut=(uint32_t *)(MMSYS_MISC_BASE+MMSYS_MISC_GPIO_OUTPUT_OFFSET+((gpioPin>>5)<<2));
uint32_t pos=gpioPin%32;
uint32_t tmpOut;
tmpOut=*pOut;
if(val>0){
tmpOut |= (1<<pos);
}else{
tmpOut &= (~(1<<pos));
}
*pOut=tmpOut;
return SUCCESS;
}
uint32_t GLB_GPIO_Read(GLB_GPIO_Type gpioPin)
{
uint32_t *p=(uint32_t *)(MMSYS_MISC_BASE+MMSYS_MISC_GPIO_INPUT_OFFSET+((gpioPin>>5)<<2));
uint32_t pos=gpioPin%32;
if((*p)&(1<<pos)){
return 1;
}else{
return 0;
}
}
#endif
/****************************************************************************//**
* @brief get DSP0 DSP1 root clock
*
* @param None
*
* @return mm glb root clock type
*
*******************************************************************************/
GLB_DSP_ROOT_CLK_Type ATTR_CLOCK_SECTION GLB_Get_DSP_ROOT_CLK_Sel(void)
{
uint32_t tmpVal = 0;
tmpVal = BL_RD_REG(MM_GLB_BASE,MM_GLB_MM_CLK_CTRL_CPU);
switch(BL_GET_REG_BITS_VAL(tmpVal,MM_GLB_HBN_ROOT_CLK_SEL)){
case 0:
return GLB_DSP_ROOT_CLK_RC32M;
case 1:
return GLB_DSP_ROOT_CLK_XTAL;
case 2:
return GLB_DSP_ROOT_CLK_PLL;
case 3:
return GLB_DSP_ROOT_CLK_PLL;
default :
return GLB_DSP_ROOT_CLK_RC32M;
}
}
/****************************************************************************//**
* @brief get xclk clock source Select
*
* @param None
*
* @return xclk clock type selection
*
*******************************************************************************/
GLB_DSP_XCLK_Type ATTR_CLOCK_SECTION GLB_Get_DSP_XCLK_Sel(void)
{
uint32_t tmpVal;
tmpVal=BL_RD_REG(MM_GLB_BASE,MM_GLB_MM_CLK_CTRL_CPU);
tmpVal=BL_GET_REG_BITS_VAL(tmpVal,MM_GLB_HBN_ROOT_CLK_SEL);
return (GLB_DSP_XCLK_Type)(tmpVal&0x1);
}
/****************************************************************************//**
* @brief select DSP0 DSP1 root clock
*
* @param rootClk: mm glb root clock type
*
* @return SUCCESS or ERROR
*
*******************************************************************************/
BL_Err_Type ATTR_CLOCK_SECTION GLB_Set_DSP_ROOT_CLK_Sel(GLB_DSP_ROOT_CLK_Type rootClk)
{
uint32_t tmpVal;
uint32_t tmpVal2;
CHECK_PARAM(IS_GLB_DSP_ROOT_CLK_TYPE(rootClk));
tmpVal=BL_RD_REG(MM_GLB_BASE,MM_GLB_MM_CLK_CTRL_CPU);
tmpVal2=BL_GET_REG_BITS_VAL(tmpVal,MM_GLB_HBN_ROOT_CLK_SEL);
switch(rootClk){
case GLB_DSP_ROOT_CLK_RC32M:
tmpVal2=0x0;
break;
case GLB_DSP_ROOT_CLK_XTAL:
tmpVal2=0x1;
break;
case GLB_DSP_ROOT_CLK_PLL:
tmpVal2|=(1<<1);
break;
default :
break;
}
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,MM_GLB_HBN_ROOT_CLK_SEL,tmpVal2);
BL_WR_REG(MM_GLB_BASE,MM_GLB_MM_CLK_CTRL_CPU,tmpVal);
GLB_CLK_SET_DUMMY_WAIT;
return SUCCESS;
}
/****************************************************************************//**
* @brief Select xclk clock source
*
* @param xclk: xclk clock type selection
*
* @return SUCCESS or ERROR
*
*******************************************************************************/
BL_Err_Type ATTR_CLOCK_SECTION GLB_Set_DSP_XCLK_Sel(GLB_DSP_XCLK_Type xclk)
{
uint32_t tmpVal;
uint32_t tmpVal2;
CHECK_PARAM(IS_GLB_DSP_XCLK_TYPE(xclk));
tmpVal=BL_RD_REG(MM_GLB_BASE,MM_GLB_MM_CLK_CTRL_CPU);
tmpVal2=BL_GET_REG_BITS_VAL(tmpVal,MM_GLB_HBN_ROOT_CLK_SEL);
switch(xclk){
case GLB_DSP_XCLK_RC32M:
tmpVal2&=(~(1<<0));
break;
case GLB_DSP_XCLK_XTAL:
tmpVal2|=(1<<0);
break;
default :
break;
}
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,MM_GLB_HBN_ROOT_CLK_SEL,tmpVal2);
BL_WR_REG(MM_GLB_BASE,MM_GLB_MM_CLK_CTRL_CPU,tmpVal);
GLB_CLK_SET_DUMMY_WAIT;
return SUCCESS;
}
BL_Err_Type GLB_Set_CAM_CLK(uint8_t enable, GLB_CAM_CLK_Type clkSel, uint8_t div)
{
uint32_t tmpVal = 0;
CHECK_PARAM(IS_GLB_CAM_CLK_TYPE(clkSel));
CHECK_PARAM((div <= 0x3));
tmpVal = BL_RD_REG(GLB_BASE, GLB_CAM_CFG0);
tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CAM_REF_CLK_EN);
BL_WR_REG(GLB_BASE, GLB_CAM_CFG0, tmpVal);
tmpVal = BL_RD_REG(GLB_BASE, GLB_CAM_CFG0);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_CAM_REF_CLK_SRC_SEL, clkSel);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_CAM_REF_CLK_DIV, div);
BL_WR_REG(GLB_BASE, GLB_CAM_CFG0, tmpVal);
tmpVal = BL_RD_REG(GLB_BASE, GLB_CAM_CFG0);
if (enable) {
tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_CAM_REF_CLK_EN);
} else {
tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CAM_REF_CLK_EN);
}
BL_WR_REG(GLB_BASE, GLB_CAM_CFG0, tmpVal);
return SUCCESS;
}
/****************************************************************************//**
* @brief set muxpll 320M selection
*
* @param clkSel: clock selection
*
* @return SUCCESS or ERROR
*
*******************************************************************************/
BL_Err_Type ATTR_CLOCK_SECTION GLB_Set_Muxpll_320M_Sel(GLB_MUXPLL_320M_CLK_SEL_Type clkSel)
{
uint32_t tmpVal;
CHECK_PARAM(IS_GLB_MUXPLL_320M_CLK_SEL_TYPE(clkSel));
tmpVal=BL_RD_REG(GLB_BASE,GLB_DIG_CLK_CFG1);
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GLB_REG_MUXPLL_320M_SEL,clkSel);
BL_WR_REG(GLB_BASE,GLB_DIG_CLK_CFG1,tmpVal);
return SUCCESS;
}
/****************************************************************************//**
* @brief gate slave3 clock or not
*
* @param enable: ENABLE or DISABLE
* @param slave3: slave3 num
*
* @return SUCCESS or ERROR
*
*******************************************************************************/
BL_Err_Type ATTR_CLOCK_SECTION GLB_AHB_Slave3_Clock_Gate(uint8_t enable,BL_AHB_Slave3_Type slave3)
{
uint32_t tmpVal = 0;
CHECK_PARAM(IS_BL_AHB_SLAVE3_TYPE(slave3));
if(slave3>=BL_AHB_SLAVE3_MAX){
return ERROR;
}
tmpVal=BL_RD_REG(GLB_BASE,GLB_CGEN_CFG3);
if(enable){
/* clear bit means clock gate */
tmpVal &=(~(1<<slave3));
}else{
/* set bit means clock pass */
tmpVal |=(1<<slave3);
}
BL_WR_REG(GLB_BASE,GLB_CGEN_CFG3,tmpVal);
return SUCCESS;
}
/****************************************************************************//**
* @brief select DSP0 DSP1 pll clock
*
* @param pllClk: mm glb pll clock type
*
* @return SUCCESS or ERROR
*
*******************************************************************************/
BL_Err_Type ATTR_CLOCK_SECTION GLB_Set_DSP_PLL_CLK_Sel(GLB_DSP_PLL_CLK_Type pllClk)
{
uint32_t tmpVal = 0;
CHECK_PARAM(IS_GLB_DSP_PLL_CLK_TYPE(pllClk));
tmpVal = BL_RD_REG(MM_GLB_BASE,MM_GLB_MM_CLK_CTRL_CPU);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal,MM_GLB_REG_CPU_CLK_SEL,pllClk);
BL_WR_REG(MM_GLB_BASE,MM_GLB_MM_CLK_CTRL_CPU,tmpVal);
return SUCCESS;
}
/****************************************************************************//**
* @brief set muxpll 240M selection
*
* @param clkSel: clock selection
*
* @return SUCCESS or ERROR
*
*******************************************************************************/
BL_Err_Type ATTR_CLOCK_SECTION GLB_Set_Muxpll_240M_Sel(GLB_MUXPLL_240M_CLK_SEL_Type clkSel)
{
uint32_t tmpVal;
CHECK_PARAM(IS_GLB_MUXPLL_240M_CLK_SEL_TYPE(clkSel));
if(clkSel==GLB_MUXPLL_SEL_240M_WIFIPLL){
GLB_AHB_Slave3_Clock_Gate(DISABLE,BL_AHB_SLAVE3_WIFIPLL_240M);
}
tmpVal=BL_RD_REG(GLB_BASE,GLB_DIG_CLK_CFG1);
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GLB_REG_MUXPLL_240M_SEL,clkSel);
BL_WR_REG(GLB_BASE,GLB_DIG_CLK_CFG1,tmpVal);
return SUCCESS;
}
/****************************************************************************//**
* @brief Set System clock divider
*
* @param hclkDiv: HCLK divider
* @param mcuBclkDiv: MCU BCLK divider
* @param periBclkDiv: BCLK divider
* @param lpDiv: LP clock divider
*
* @return SUCCESS or ERROR
*
*******************************************************************************/
BL_Err_Type ATTR_CLOCK_SECTION GLB_Set_MCU_System_CLK_Div(uint8_t hclkDiv,uint8_t mcuBclkDiv,uint8_t periBclkDiv,uint8_t lpDiv)
{
uint32_t tmpVal;
HBN_MCU_XCLK_Type xclkSel;
HBN_MCU_ROOT_CLK_Type rootClkSel;
/* get root clock */
xclkSel = HBN_Get_MCU_XCLK_Sel();
rootClkSel = HBN_Get_MCU_Root_CLK_Sel();
if(rootClkSel!=HBN_MCU_ROOT_CLK_RC32M){
HBN_Set_MCU_Root_CLK_Sel(HBN_MCU_ROOT_CLK_RC32M);
}
/* config hclk_div=0 */
tmpVal=BL_RD_REG(GLB_BASE,GLB_SYS_CFG0);
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GLB_REG_HCLK_DIV,0);
BL_WR_REG(GLB_BASE,GLB_SYS_CFG0,tmpVal);
/* config mcu_bclk_div=0 */
tmpVal=BL_RD_REG(GLB_BASE,GLB_SYS_CFG0);
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GLB_REG_MCU_BCLK_DIV,0);
BL_WR_REG(GLB_BASE,GLB_SYS_CFG0,tmpVal);
/* config bclk_div=0 */
tmpVal=BL_RD_REG(GLB_BASE,GLB_SYS_CFG0);
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GLB_REG_BCLK_DIV,0);
BL_WR_REG(GLB_BASE,GLB_SYS_CFG0,tmpVal);
/* config lp clock div=1 */
tmpVal = BL_RD_REG(PDS_BASE,PDS_CPU_CORE_CFG7);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal,PDS_REG_PICO_DIV,1);
BL_WR_REG(PDS_BASE,PDS_CPU_CORE_CFG7,tmpVal);
/* config hclk_div=hclkDiv */
tmpVal=BL_RD_REG(GLB_BASE,GLB_SYS_CFG0);
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GLB_REG_HCLK_DIV,hclkDiv);
BL_WR_REG(GLB_BASE,GLB_SYS_CFG0,tmpVal);
/* config mcu_bclk_div=mcuBclkDiv */
tmpVal=BL_RD_REG(GLB_BASE,GLB_SYS_CFG0);
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GLB_REG_MCU_BCLK_DIV,mcuBclkDiv);
BL_WR_REG(GLB_BASE,GLB_SYS_CFG0,tmpVal);
/* config bclk_div=periBclkDiv */
tmpVal=BL_RD_REG(GLB_BASE,GLB_SYS_CFG0);
tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GLB_REG_BCLK_DIV,periBclkDiv);
BL_WR_REG(GLB_BASE,GLB_SYS_CFG0,tmpVal);
/* config lp clock div=lpDiv */
tmpVal = BL_RD_REG(PDS_BASE,PDS_CPU_CORE_CFG7);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal,PDS_REG_PICO_DIV,lpDiv);
BL_WR_REG(PDS_BASE,PDS_CPU_CORE_CFG7,tmpVal);
/* recover root clock */
HBN_Set_MCU_XCLK_Sel(xclkSel);
HBN_Set_MCU_Root_CLK_Sel(rootClkSel);
GLB_CLK_SET_DUMMY_WAIT;
return SUCCESS;
}
/****************************************************************************//**
* @brief Set mcu System clock
*
* @param clkFreq: mcu system clock type
*
* @return SUCCESS or ERROR
*
*******************************************************************************/
BL_Err_Type ATTR_CLOCK_SECTION GLB_Set_MCU_System_CLK(GLB_MCU_SYS_CLK_Type clkFreq)
{
uint32_t tmpVal;
HBN_MCU_XCLK_Type mcuXclkSel;
CHECK_PARAM(IS_GLB_MCU_SYS_CLK_TYPE(clkFreq));
/* get xclk&&rootclk clock */
mcuXclkSel = HBN_Get_MCU_XCLK_Sel();
/* change root clock to rc32m */
HBN_Set_MCU_Root_CLK_Sel(HBN_MCU_ROOT_CLK_RC32M);
GLB_Set_MCU_System_CLK_Div(0,0,0,0);
/* select pll output clock before select root clock */
tmpVal = BL_RD_REG(PDS_BASE,PDS_CPU_CORE_CFG1);
if(GLB_MCU_SYS_CLK_300M_CPUPLL==clkFreq){
tmpVal = BL_SET_REG_BITS_VAL(tmpVal,PDS_REG_PLL_SEL,GLB_MCU_SYS_CLK_320M_ETHPLL-GLB_MCU_SYS_CLK_160M_WIFIPLL);
}else if(clkFreq>=GLB_MCU_SYS_CLK_160M_WIFIPLL){
tmpVal = BL_SET_REG_BITS_VAL(tmpVal,PDS_REG_PLL_SEL,clkFreq-GLB_MCU_SYS_CLK_160M_WIFIPLL);
}
BL_WR_REG(PDS_BASE,PDS_CPU_CORE_CFG1,tmpVal);
/* select root clock */
switch(clkFreq){
case GLB_MCU_SYS_CLK_RC32M:
HBN_Set_MCU_Root_CLK_Sel(HBN_MCU_ROOT_CLK_RC32M);
break;
case GLB_MCU_SYS_CLK_XTAL:
HBN_Set_MCU_Root_CLK_Sel(HBN_MCU_ROOT_CLK_XTAL);
break;
case GLB_MCU_SYS_CLK_160M_WIFIPLL:
/* For high speed, set DIV first */
GLB_Set_MCU_System_CLK_Div(0,1,1,0);
/* unuseful for mcu, useful for dsp, just for safe */
GLB_AHB_Slave3_Clock_Gate(DISABLE,BL_AHB_SLAVE3_WIFIPLL_240M);
HBN_Set_MCU_Root_CLK_Sel(HBN_MCU_ROOT_CLK_PLL);
/* recover xclk */
HBN_Set_MCU_XCLK_Sel(mcuXclkSel);
break;
case GLB_MCU_SYS_CLK_192M_WIFIPLL:
/* For high speed, set DIV first */
GLB_Set_MCU_System_CLK_Div(0,1,1,1);
/* unuseful for mcu, useful for dsp, just for safe */
GLB_AHB_Slave3_Clock_Gate(DISABLE,BL_AHB_SLAVE3_WIFIPLL_240M);
HBN_Set_MCU_Root_CLK_Sel(HBN_MCU_ROOT_CLK_PLL);
/* recover xclk */
HBN_Set_MCU_XCLK_Sel(mcuXclkSel);
break;
case GLB_MCU_SYS_CLK_240M_WIFIPLL:
/* For high speed, set DIV first */
GLB_Set_MCU_System_CLK_Div(0,1,1,1);
/* unuseful for mcu, useful for dsp, just for safe */
GLB_AHB_Slave3_Clock_Gate(DISABLE,BL_AHB_SLAVE3_WIFIPLL_240M);
HBN_Set_MCU_Root_CLK_Sel(HBN_MCU_ROOT_CLK_PLL);
/* recover xclk */
HBN_Set_MCU_XCLK_Sel(mcuXclkSel);
break;
case GLB_MCU_SYS_CLK_320M_ETHPLL:
/* For high speed, set DIV first */
GLB_Set_MCU_System_CLK_Div(0,1,1,1);
GLB_Set_Muxpll_320M_Sel(GLB_MUXPLL_SEL_320M_ETHPLL);
HBN_Set_MCU_Root_CLK_Sel(HBN_MCU_ROOT_CLK_PLL);
/* recover xclk */
HBN_Set_MCU_XCLK_Sel(mcuXclkSel);
break;
case GLB_MCU_SYS_CLK_300M_CPUPLL:
/* For high speed, set DIV first */
GLB_Set_MCU_System_CLK_Div(0,1,1,1);
GLB_Set_Muxpll_320M_Sel(GLB_MUXPLL_SEL_300M_CPUPLL);
HBN_Set_MCU_Root_CLK_Sel(HBN_MCU_ROOT_CLK_PLL);
/* recover xclk */
HBN_Set_MCU_XCLK_Sel(mcuXclkSel);
break;
default :
break;
}
GLB_CLK_SET_DUMMY_WAIT;
return SUCCESS;
}
/****************************************************************************//**
* @brief select DSP0 DSP1 clock div
*
* @param cpuDiv: mm glb bclk1x div
* @param dspBclkDiv: mm glb bclk2x div
* @param mmBclkDiv: mm glb cpu div
*
* @return SUCCESS or ERROR
*
*******************************************************************************/
BL_Err_Type ATTR_CLOCK_SECTION GLB_Set_DSP_System_CLK_Div(uint8_t cpuDiv,uint8_t dspBclkDiv,uint8_t mmBclkDiv)
{
uint32_t tmpVal = 0;
GLB_DSP_XCLK_Type dspXclkSel;
GLB_DSP_ROOT_CLK_Type dspRootClkSel;
/* get root clock */
dspXclkSel = GLB_Get_DSP_XCLK_Sel();
dspRootClkSel = GLB_Get_DSP_ROOT_CLK_Sel();
/* change root clock to rc32m */
if(dspRootClkSel!=GLB_DSP_ROOT_CLK_RC32M){
GLB_Set_DSP_ROOT_CLK_Sel(GLB_DSP_ROOT_CLK_RC32M);
}
/* div=0 */
tmpVal = BL_RD_REG(MM_GLB_BASE,MM_GLB_MM_CLK_CPU);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal,MM_GLB_REG_BCLK1X_DIV,0);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal,MM_GLB_REG_BCLK2X_DIV,0);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal,MM_GLB_REG_CPU_CLK_DIV,0);
BL_WR_REG(MM_GLB_BASE,MM_GLB_MM_CLK_CPU,tmpVal);
/* set div */
tmpVal = BL_RD_REG(MM_GLB_BASE,MM_GLB_MM_CLK_CPU);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal,MM_GLB_REG_BCLK1X_DIV,mmBclkDiv);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal,MM_GLB_REG_BCLK2X_DIV,dspBclkDiv);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal,MM_GLB_REG_CPU_CLK_DIV,cpuDiv);
BL_WR_REG(MM_GLB_BASE,MM_GLB_MM_CLK_CPU,tmpVal);
/* recover root clock */
GLB_Set_DSP_XCLK_Sel(dspXclkSel);
GLB_Set_DSP_ROOT_CLK_Sel(dspRootClkSel);
return SUCCESS;
}
/****************************************************************************//**
* @brief Set dsp System clock
*
* @param clkFreq: dsp system clock type
*
* @return SUCCESS or ERROR
*
*******************************************************************************/
BL_Err_Type ATTR_CLOCK_SECTION GLB_Set_DSP_System_CLK(GLB_DSP_SYS_CLK_Type clkFreq)
{
GLB_DSP_XCLK_Type dspXclkSel;
CHECK_PARAM(IS_GLB_DSP_SYS_CLK_TYPE(clkFreq));
/* get root clock */
dspXclkSel = GLB_Get_DSP_XCLK_Sel();
/* Before config XTAL and PLL ,make sure root clk is from RC32M */
GLB_Set_DSP_ROOT_CLK_Sel(GLB_DSP_ROOT_CLK_RC32M);
GLB_Set_DSP_System_CLK_Div(0,0,0);
/* select pll output clock before select root clock */
if(GLB_DSP_SYS_CLK_240M_CPUPLL==clkFreq){
GLB_Set_DSP_PLL_CLK_Sel(GLB_DSP_SYS_CLK_240M_WIFIPLL-GLB_DSP_SYS_CLK_240M_WIFIPLL);
}else if(GLB_DSP_SYS_CLK_300M_CPUPLL==clkFreq){
GLB_Set_DSP_PLL_CLK_Sel(GLB_DSP_SYS_CLK_320M_ETHPLL-GLB_DSP_SYS_CLK_240M_WIFIPLL);
}else if(clkFreq>=GLB_DSP_SYS_CLK_240M_WIFIPLL){
GLB_Set_DSP_PLL_CLK_Sel(clkFreq-GLB_DSP_SYS_CLK_240M_WIFIPLL);
}
/* select root clock */
switch(clkFreq){
case GLB_DSP_SYS_CLK_RC32M:
GLB_Set_DSP_System_CLK_Div(0,0,0);
GLB_Set_DSP_ROOT_CLK_Sel(HBN_MCU_ROOT_CLK_RC32M);
break;
case GLB_DSP_SYS_CLK_XTAL:
GLB_Set_DSP_System_CLK_Div(0,0,0);
GLB_Set_DSP_ROOT_CLK_Sel(HBN_MCU_ROOT_CLK_XTAL);
break;
case GLB_DSP_SYS_CLK_240M_WIFIPLL:
GLB_Set_DSP_System_CLK_Div(0,1,1);
/* unuseful for mcu, useful for dsp, just for safe */
GLB_AHB_Slave3_Clock_Gate(DISABLE,BL_AHB_SLAVE3_WIFIPLL_240M);
GLB_Set_Muxpll_240M_Sel(GLB_MUXPLL_SEL_240M_WIFIPLL);
GLB_Set_DSP_ROOT_CLK_Sel(HBN_MCU_ROOT_CLK_PLL);
/* recover xclk */
GLB_Set_DSP_XCLK_Sel(dspXclkSel);
break;
case GLB_DSP_SYS_CLK_320M_ETHPLL:
GLB_Set_DSP_System_CLK_Div(0,1,1);
GLB_Set_Muxpll_320M_Sel(GLB_MUXPLL_SEL_320M_ETHPLL);
GLB_Set_DSP_ROOT_CLK_Sel(HBN_MCU_ROOT_CLK_PLL);
/* recover xclk */
GLB_Set_DSP_XCLK_Sel(dspXclkSel);
break;
case GLB_DSP_SYS_CLK_400M_ETHPLL:
GLB_Set_DSP_System_CLK_Div(0,1,1);
GLB_Set_DSP_ROOT_CLK_Sel(HBN_MCU_ROOT_CLK_PLL);
/* recover xclk */
GLB_Set_DSP_XCLK_Sel(dspXclkSel);
break;
case GLB_DSP_SYS_CLK_640M_CPUPLL:
GLB_Set_DSP_System_CLK_Div(0,1,1);
GLB_Set_DSP_ROOT_CLK_Sel(HBN_MCU_ROOT_CLK_PLL);
/* recover xclk */
GLB_Set_DSP_XCLK_Sel(dspXclkSel);
break;
case GLB_DSP_SYS_CLK_240M_CPUPLL:
GLB_Set_DSP_System_CLK_Div(0,1,1);
GLB_Set_Muxpll_240M_Sel(GLB_MUXPLL_SEL_240M_CPUPLL);
GLB_Set_DSP_ROOT_CLK_Sel(HBN_MCU_ROOT_CLK_PLL);
/* recover xclk */
GLB_Set_DSP_XCLK_Sel(dspXclkSel);
break;
case GLB_DSP_SYS_CLK_300M_CPUPLL:
GLB_Set_DSP_System_CLK_Div(0,1,1);
GLB_Set_Muxpll_320M_Sel(GLB_MUXPLL_SEL_300M_CPUPLL);
GLB_Set_DSP_ROOT_CLK_Sel(HBN_MCU_ROOT_CLK_PLL);
/* recover xclk */
GLB_Set_DSP_XCLK_Sel(dspXclkSel);
break;
default :
break;
}
GLB_CLK_SET_DUMMY_WAIT;
return SUCCESS;
}
/****************************************************************************/ /**
* @brief swap UART gpio pins sig function
*
* @param group: UART swap set group
* @param swap: swap or no swap
*
* @return SUCCESS or ERROR
*
*******************************************************************************/
BL_Err_Type GLB_UART_Sig_Swap_Set(GLB_UART_SIG_SWAP_GRP_Type group, uint8_t swap)
{
uint32_t tmpVal = 0;
uint32_t tmpVal2 = 0;
CHECK_PARAM(IS_GLB_UART_SIG_SWAP_GRP_TYPE(group));
tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM_CFG0);
tmpVal2 = BL_GET_REG_BITS_VAL(tmpVal, GLB_UART_SWAP_SET);
if (swap) {
tmpVal2 |= (1 << group);
} else {
tmpVal2 &= ~(1 << group);
}
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_UART_SWAP_SET, tmpVal2);
BL_WR_REG(GLB_BASE, GLB_PARM_CFG0, tmpVal);
return SUCCESS;
}
/****************************************************************************/ /**
* @brief Select UART signal function
*
* @param sig: UART signal
* @param fun: UART function
*
* @return SUCCESS or ERROR
*
*******************************************************************************/
BL_Err_Type GLB_UART_Fun_Sel(GLB_UART_SIG_Type sig, GLB_UART_SIG_FUN_Type fun)
{
uint32_t sig_pos = 0;
uint32_t tmpVal = 0;
CHECK_PARAM(IS_GLB_UART_SIG_TYPE(sig));
CHECK_PARAM(IS_GLB_UART_SIG_FUN_TYPE(fun));
if (sig < GLB_UART_SIG_8) {
tmpVal = BL_RD_REG(GLB_BASE, GLB_UART_CFG1);
sig_pos = (sig * 4);
/* Clear original val */
tmpVal &= (~(0xf << sig_pos));
/* Set new value */
tmpVal |= (fun << sig_pos);
BL_WR_REG(GLB_BASE, GLB_UART_CFG1, tmpVal);
} else {
tmpVal = BL_RD_REG(GLB_BASE, GLB_UART_CFG2);
sig_pos = ((sig - 8) * 4);
/* Clear original val */
tmpVal &= (~(0xf << sig_pos));
/* Set new value */
tmpVal |= (fun << sig_pos);
BL_WR_REG(GLB_BASE, GLB_UART_CFG2, tmpVal);
}
return SUCCESS;
}
/****************************************************************************/ /**
* @brief Select DSP SPI_0 act mode
*
* @param mod: SPI work mode
*
* @return SUCCESS or ERROR
*
*******************************************************************************/
BL_Err_Type GLB_Set_DSP_SPI_0_ACT_MOD_Sel(GLB_SPI_PAD_ACT_AS_Type mod)
{
uint32_t tmpVal;
CHECK_PARAM(IS_GLB_SPI_PAD_ACT_AS_TYPE(mod));
tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM_CFG0);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_MM_SPI_MASTER_MODE, mod);
BL_WR_REG(GLB_BASE, GLB_PARM_CFG0, tmpVal);
return SUCCESS;
}
/****************************************************************************/ /**
* @brief Select SPI_0 act mode
*
* @param mod: SPI work mode
*
* @return SUCCESS or ERROR
*
*******************************************************************************/
BL_Err_Type GLB_Set_MCU_SPI_0_ACT_MOD_Sel(GLB_SPI_PAD_ACT_AS_Type mod)
{
uint32_t tmpVal;
CHECK_PARAM(IS_GLB_SPI_PAD_ACT_AS_TYPE(mod));
tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM_CFG0);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_SPI_0_MASTER_MODE, mod);
BL_WR_REG(GLB_BASE, GLB_PARM_CFG0, tmpVal);
return SUCCESS;
}
/****************************************************************************/ /**
* @brief software reset
*
* @param swrst: reset num
*
* @return SUCCESS or ERROR
*
*******************************************************************************/
BL_Err_Type GLB_AHB_MCU_Software_Reset(GLB_AHB_MCU_SW_Type swrst)
{
uint32_t tmpVal = 0;
uint32_t bit = 0;
uint32_t regAddr = 0;
CHECK_PARAM(IS_GLB_AHB_MCU_SW_TYPE(swrst));
if (swrst < 32) {
bit = swrst;
regAddr = GLB_BASE + GLB_SWRST_CFG0_OFFSET;
} else if (swrst < 64) {
bit = swrst - 32;
regAddr = GLB_BASE + GLB_SWRST_CFG1_OFFSET;
} else if (swrst < 96) {
bit = swrst - 64;
regAddr = GLB_BASE + GLB_SWRST_CFG2_OFFSET;
}
tmpVal = BL_RD_WORD(regAddr);
tmpVal &= ~(1 << bit);
BL_WR_WORD(regAddr, tmpVal);
BL_DRV_DUMMY;
tmpVal = BL_RD_WORD(regAddr);
tmpVal |= (1 << bit);
BL_WR_WORD(regAddr, tmpVal);
BL_DRV_DUMMY;
tmpVal = BL_RD_WORD(regAddr);
tmpVal &= ~(1 << bit);
BL_WR_WORD(regAddr, tmpVal);
return SUCCESS;
}
/****************************************************************************/ /**
* @brief get first 1 from u64, then clear it
*
* @param val: target value
* @param bit: first 1 in bit
*
* @return SUCCESS or ERROR
*
*******************************************************************************/
static BL_Err_Type GLB_Get_And_Clr_First_Set_From_U64(uint64_t *val, uint32_t *bit)
{
if (!*val) {
return ERROR;
}
for (uint8_t i = 0; i < 64; i++) {
if ((*val) & ((uint64_t)1 << i)) {
*bit = i;
(*val) &= ~((uint64_t)1 << i);
break;
}
}
return SUCCESS;
}
/****************************************************************************/ /**
* @brief release IPs clock
*
* @param ips: GLB_AHB_CLOCK_xxx | GLB_AHB_CLOCK_xxx | ...... (not GLB_AHB_CLOCK_IP_xxx)
*
* @return SUCCESS or ERROR
*
*******************************************************************************/
BL_Err_Type GLB_PER_Clock_UnGate(uint64_t ips)
{
/* api request from cjy */
uint32_t tmpValCfg0 = 0;
uint32_t tmpValCfg1 = 0;
uint32_t tmpValCfg2 = 0;
uint32_t bitfield = 0;
tmpValCfg0 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG0);
tmpValCfg1 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1);
tmpValCfg2 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG2);
while (ips) {
if (SUCCESS == GLB_Get_And_Clr_First_Set_From_U64(&ips, &bitfield)) {
switch (bitfield) {
case GLB_AHB_CLOCK_IP_CPU:
tmpValCfg0 |= (1 << 0);
break;
case GLB_AHB_CLOCK_IP_SDU:
tmpValCfg0 |= (1 << 1);
break;
case GLB_AHB_CLOCK_IP_SEC:
tmpValCfg0 |= (1 << 2);
tmpValCfg1 |= (1 << 3);
tmpValCfg1 |= (1 << 4);
break;
case GLB_AHB_CLOCK_IP_DMA_0:
tmpValCfg0 |= (1 << 3);
tmpValCfg1 |= (1 << 12);
break;
case GLB_AHB_CLOCK_IP_DMA_1:
tmpValCfg0 |= (1 << 3);
break;
case GLB_AHB_CLOCK_IP_DMA_2:
tmpValCfg0 |= (1 << 3);
tmpValCfg2 |= (1 << 24);
break;
case GLB_AHB_CLOCK_IP_CCI:
tmpValCfg0 |= (1 << 4);
break;
case GLB_AHB_CLOCK_IP_RF_TOP:
tmpValCfg1 |= (1 << 1);
break;
case GLB_AHB_CLOCK_IP_GPIP:
tmpValCfg1 |= (1 << 2);
break;
case GLB_AHB_CLOCK_IP_TZC:
tmpValCfg1 |= (1 << 5);
break;
case GLB_AHB_CLOCK_IP_EF_CTRL:
tmpValCfg1 |= (1 << 7);
break;
case GLB_AHB_CLOCK_IP_SF_CTRL:
tmpValCfg1 |= (1 << 11);
break;
case GLB_AHB_CLOCK_IP_EMAC:
tmpValCfg2 |= (1 << 19);
tmpValCfg2 |= (1 << 23);
break;
case GLB_AHB_CLOCK_IP_UART0:
tmpValCfg1 |= (1 << 16);
break;
case GLB_AHB_CLOCK_IP_UART1:
tmpValCfg1 |= (1 << 17);
break;
case GLB_AHB_CLOCK_IP_UART2:
tmpValCfg1 |= (1 << 26);
break;
case GLB_AHB_CLOCK_IP_UART3:
break;
case GLB_AHB_CLOCK_IP_UART4:
break;
case GLB_AHB_CLOCK_IP_SPI:
tmpValCfg1 |= (1 << 18);
break;
case GLB_AHB_CLOCK_IP_I2C:
tmpValCfg1 |= (1 << 19);
break;
case GLB_AHB_CLOCK_IP_PWM:
tmpValCfg1 |= (1 << 20);
break;
case GLB_AHB_CLOCK_IP_TIMER:
tmpValCfg1 |= (1 << 21);
break;
case GLB_AHB_CLOCK_IP_IR:
tmpValCfg1 |= (1 << 22);
break;
case GLB_AHB_CLOCK_IP_CHECKSUM:
tmpValCfg1 |= (1 << 23);
break;
case GLB_AHB_CLOCK_IP_QDEC:
break;
case GLB_AHB_CLOCK_IP_KYS:
break;
case GLB_AHB_CLOCK_IP_I2S:
tmpValCfg1 |= (1 << 23);
break;
case GLB_AHB_CLOCK_IP_USB11:
break;
case GLB_AHB_CLOCK_IP_CAM:
break;
case GLB_AHB_CLOCK_IP_MJPEG:
break;
case GLB_AHB_CLOCK_IP_BT_BLE_NORMAL:
tmpValCfg2 |= (1 << 8);
break;
case GLB_AHB_CLOCK_IP_BT_BLE_LP:
break;
case GLB_AHB_CLOCK_IP_ZB_NORMAL:
tmpValCfg2 |= (1 << 9);
break;
case GLB_AHB_CLOCK_IP_ZB_LP:
break;
case GLB_AHB_CLOCK_IP_WIFI_NORMAL:
tmpValCfg2 |= (1 << 4);
break;
case GLB_AHB_CLOCK_IP_WIFI_LP:
break;
case GLB_AHB_CLOCK_IP_BT_BLE_2_NORMAL:
tmpValCfg2 |= (1 << 10);
break;
case GLB_AHB_CLOCK_IP_BT_BLE_2_LP:
break;
case GLB_AHB_CLOCK_IP_EMI_MISC:
tmpValCfg2 |= (1 << 16);
break;
case GLB_AHB_CLOCK_IP_PSRAM0_CTRL:
tmpValCfg2 |= (1 << 17);
break;
case GLB_AHB_CLOCK_IP_PSRAM1_CTRL:
tmpValCfg2 |= (1 << 18);
break;
case GLB_AHB_CLOCK_IP_USB20:
tmpValCfg1 |= (1 << 13);
break;
case GLB_AHB_CLOCK_IP_MIX2:
tmpValCfg2 |= (1 << 20);
break;
case GLB_AHB_CLOCK_IP_AUDIO:
tmpValCfg2 |= (1 << 21);
break;
case GLB_AHB_CLOCK_IP_SDH:
tmpValCfg2 |= (1 << 22);
break;
case GLB_AHB_CLOCK_IP_ZB2_NORMAL:
tmpValCfg2 |= (1 << 11);
break;
case GLB_AHB_CLOCK_IP_ZB2_LP:
break;
case GLB_AHB_CLOCK_IP_I2C1:
tmpValCfg1 |= (1 << 25);
break;
case GLB_AHB_CLOCK_IP_WIFI_PHY:
tmpValCfg0 |= (1 << 7);
break;
case GLB_AHB_CLOCK_IP_WIFI_MAC_PHY:
tmpValCfg0 |= (1 << 6);
break;
case GLB_AHB_CLOCK_IP_WIFI_PLATFORM:
tmpValCfg0 |= (1 << 5);
break;
case GLB_AHB_CLOCK_IP_LZ4:
tmpValCfg1 |= (1 << 29);
break;
case GLB_AHB_CLOCK_IP_AUPDM:
tmpValCfg1 |= (1 << 28);
break;
case GLB_AHB_CLOCK_IP_GAUGE:
tmpValCfg1 |= (1 << 0);
break;
default:
break;
}
}
}
BL_WR_REG(GLB_BASE, GLB_CGEN_CFG0, tmpValCfg0);
BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpValCfg1);
BL_WR_REG(GLB_BASE, GLB_CGEN_CFG2, tmpValCfg2);
return SUCCESS;
}
/****************************************************************************/ /**
* @brief software reset
*
* @param swrst: reset num
*
* @return SUCCESS or ERROR
*
*******************************************************************************/
BL_Err_Type GLB_AHB_DSP_Software_Reset(GLB_AHB_DSP_SW_Type swrst)
{
uint32_t tmpVal = 0;
uint32_t bit = 0;
uint32_t regAddr = 0;
CHECK_PARAM(IS_GLB_AHB_DSP_SW_TYPE(swrst));
if (swrst < 32) {
bit = swrst;
regAddr = MM_GLB_BASE + MM_GLB_MM_SW_SYS_RESET_OFFSET;
} else if (swrst < 64) {
bit = swrst - 32;
regAddr = MM_GLB_BASE + MM_GLB_SW_RESET_MM_PERI_OFFSET;
} else if (swrst < 96) {
bit = swrst - 64;
regAddr = MM_GLB_BASE + MM_GLB_SW_RESET_ISP_SUB_OFFSET;
} else if (swrst < 128) {
bit = swrst - 96;
regAddr = MM_GLB_BASE + MM_GLB_SW_RESET_CODEC_SUB_OFFSET;
} else if (swrst < 160) {
bit = swrst - 128;
regAddr = MM_GLB_BASE + MM_GLB_IMAGE_SENSOR_CTRL_OFFSET;
}
tmpVal = BL_RD_WORD(regAddr);
tmpVal &= ~(1 << bit);
BL_WR_WORD(regAddr, tmpVal);
BL_DRV_DUMMY;
tmpVal = BL_RD_WORD(regAddr);
tmpVal |= (1 << bit);
BL_WR_WORD(regAddr, tmpVal);
BL_DRV_DUMMY;
tmpVal = BL_RD_WORD(regAddr);
tmpVal &= ~(1 << bit);
BL_WR_WORD(regAddr, tmpVal);
return SUCCESS;
}
/****************************************************************************/ /**
* @brief set ldo15cis vout select
*
* @param ldoLevel: ldo level
*
* @return SUCCESS or ERROR
*
*******************************************************************************/
BL_Err_Type GLB_Set_Ldo15cis_Vout(GLB_LDO15CIS_LEVEL_Type ldoLevel)
{
uint32_t tmpVal;
CHECK_PARAM(IS_GLB_LDO15CIS_LEVEL_TYPE(ldoLevel));
tmpVal = BL_RD_REG(GLB_BASE, GLB_LDO15CIS);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_LDO15CIS_VOUT_SEL, ldoLevel);
BL_WR_REG(GLB_BASE, GLB_LDO15CIS, tmpVal);
return SUCCESS;
}
/****************************************************************************/ /**
* @brief config mipipll for CSI
*
* @param postDivSel: mipipll post div sel
* @param sdmin: mipipll sdmin
*
* @return SUCCESS or ERROR
*
*******************************************************************************/
BL_Err_Type GLB_CSI_Config_MIPIPLL(uint8_t postDivSel, uint32_t sdmin)
{
uint32_t tmpVal;
tmpVal = BL_RD_REG(GLB_BASE, GLB_MIPI_PLL_CFG5);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_MIPIPLL_VCO_POSTDIV_SEL, postDivSel);
BL_WR_REG(GLB_BASE, GLB_MIPI_PLL_CFG5, tmpVal);
tmpVal = BL_RD_REG(GLB_BASE, GLB_MIPI_PLL_CFG6);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_MIPIPLL_SDMIN, sdmin);
BL_WR_REG(GLB_BASE, GLB_MIPI_PLL_CFG6, tmpVal);
return SUCCESS;
}
/****************************************************************************/ /**
* @brief power up mipipll for CSI
*
* @param None
*
* @return SUCCESS or ERROR
*
*******************************************************************************/
BL_Err_Type GLB_CSI_Power_Up_MIPIPLL(void)
{
uint32_t tmpVal;
tmpVal = BL_RD_REG(GLB_BASE, GLB_MIPI_PLL_CFG0);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PU_MIPIPLL_SFREG, 1);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PU_MIPIPLL, 1);
BL_WR_REG(GLB_BASE, GLB_MIPI_PLL_CFG0, tmpVal);
tmpVal = BL_RD_REG(GLB_BASE, GLB_MIPI_PLL_CFG0);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_MIPIPLL_FBDV_RSTB, 1);
BL_WR_REG(GLB_BASE, GLB_MIPI_PLL_CFG0, tmpVal);
ARCH_Delay_US(2);
tmpVal = BL_RD_REG(GLB_BASE, GLB_MIPI_PLL_CFG0);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_MIPIPLL_FBDV_RSTB, 0);
BL_WR_REG(GLB_BASE, GLB_MIPI_PLL_CFG0, tmpVal);
ARCH_Delay_US(2);
tmpVal = BL_RD_REG(GLB_BASE, GLB_MIPI_PLL_CFG0);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_MIPIPLL_FBDV_RSTB, 1);
BL_WR_REG(GLB_BASE, GLB_MIPI_PLL_CFG0, tmpVal);
return SUCCESS;
}
/*@} end of group GLB_Public_Functions */
/*@} end of group GLB */
/*@} end of group BL60x_Peripheral_Driver */
|
d11cfaa16579951bdfd889eb884c72478d59a4e8
|
9ceacf33fd96913cac7ef15492c126d96cae6911
|
/lib/libcrypto/hidden/openssl/hmac.h
|
ecf8aa999727789e057cb32e492d7f32302a9888
|
[] |
no_license
|
openbsd/src
|
ab97ef834fd2d5a7f6729814665e9782b586c130
|
9e79f3a0ebd11a25b4bff61e900cb6de9e7795e9
|
refs/heads/master
| 2023-09-02T18:54:56.624627
| 2023-09-02T15:16:12
| 2023-09-02T15:16:12
| 66,966,208
| 3,394
| 1,235
| null | 2023-08-08T02:42:25
| 2016-08-30T18:18:25
|
C
|
UTF-8
|
C
| false
| false
| 1,387
|
h
|
hmac.h
|
/* $OpenBSD: hmac.h,v 1.2 2023/07/05 21:14:54 bcook Exp $ */
/*
* Copyright (c) 2016 Philip Guenther <guenther@openbsd.org>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef _LIBCRYPTO_HMAC_H_
#define _LIBCRYPTO_HMAC_H_
#ifndef _MSC_VER
#include_next <openssl/hmac.h>
#else
#include "../include/openssl/hmac.h"
#endif
#include "crypto_namespace.h"
LCRYPTO_USED(HMAC_CTX_new);
LCRYPTO_USED(HMAC_CTX_free);
LCRYPTO_UNUSED(HMAC_CTX_reset);
LCRYPTO_UNUSED(HMAC_Init);
LCRYPTO_USED(HMAC_Init_ex);
LCRYPTO_USED(HMAC_Update);
LCRYPTO_USED(HMAC_Final);
LCRYPTO_USED(HMAC);
LCRYPTO_USED(HMAC_CTX_copy);
LCRYPTO_USED(HMAC_CTX_set_flags);
LCRYPTO_USED(HMAC_CTX_get_md);
#endif /* _LIBCRYPTO_HMAC_H_ */
|
70f5e3d65fcbf4a75145dce24f5a478c31067020
|
747ccf5228020fe3018ae4411add6d54aed84603
|
/graphics/deko3d/deko_console/source/main.c
|
71b60a986c134a7a110b4e2a9aea94f5fb5b0601
|
[
"CC-PDDC",
"LicenseRef-scancode-public-domain"
] |
permissive
|
switchbrew/switch-examples
|
ba8a9987537c33f386b76ec2586ec99f8eddcfcc
|
455ad6732c0f007b97463ae8204e41c0471dc206
|
refs/heads/master
| 2023-09-02T05:08:55.663095
| 2023-06-21T01:35:14
| 2023-07-04T21:17:34
| 103,796,153
| 549
| 162
| null | 2023-07-04T21:17:35
| 2017-09-17T02:01:40
|
C
|
UTF-8
|
C
| false
| false
| 2,460
|
c
|
main.c
|
#include <string.h>
#include <stdio.h>
#include <switch.h>
int main(int argc, char **argv)
{
consoleInit(NULL);
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
PadState pad;
padInitializeDefault(&pad);
// clear screen and home cursor
printf( CONSOLE_ESC(2J) );
// Set print co-ordinates
// /x1b[row;columnH
printf(CONSOLE_ESC(42;37m));
printf(CONSOLE_ESC( 7;4H) "%s", " _ _ ____ _ ");
printf(CONSOLE_ESC( 8;4H) "%s", " | | | | |___ \\ | |");
printf(CONSOLE_ESC( 9;4H) "%s", " __| | ___| | _____ __) | __| |");
printf(CONSOLE_ESC(10;4H) "%s", " / _` |/ _ \\ |/ / _ \\|__ < / _` |");
printf(CONSOLE_ESC(11;4H) "%s", "| (_| | __/ < (_) |__) | (_| |");
printf(CONSOLE_ESC(12;4H) "%s", " \\__,_|\\___|_|\\_\\___/____/ \\__,_|");
printf(CONSOLE_ESC(0m));
// move cursor up
// /x1b[linesA
printf(CONSOLE_ESC(10A)"Line 0");
// move cursor left
// /x1b[columnsD
printf(CONSOLE_ESC(28D)"Column 0");
// move cursor down
// /x1b[linesB
printf(CONSOLE_ESC(19B)"Line 19");
// move cursor right
// /x1b[columnsC
printf(CONSOLE_ESC(5C)"Column 20");
printf("\n");
// Color codes and attributes
for(int i=0; i<8; i++)
{
printf( CONSOLE_ESC(%1$dm) /* Set color */
"Default "
CONSOLE_ESC(1m) "Bold "
CONSOLE_ESC(7m) "Reversed "
CONSOLE_ESC(0m) /* revert attributes*/
CONSOLE_ESC(%1$dm)
CONSOLE_ESC(2m) "Light "
CONSOLE_ESC(7m) "Reversed "
"\n"
CONSOLE_ESC(0m) /* revert attributes*/
, i + 30);
}
// Main loop
while(appletMainLoop())
{
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// Your code goes here
// padGetButtonsDown returns the set of buttons that have been newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & HidNpadButton_Plus) break; // break in order to return to hbmenu
consoleUpdate(NULL);
}
consoleExit(NULL);
return 0;
}
|
910d2713eb2930850efc0ce41a705a961269680d
|
0744dcc5394cebf57ebcba343747af6871b67017
|
/external/esp_idf_port/include/soc/i2s_reg.h
|
0f08104fe2afc63730009ae1ae47ddea4a414835
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
Samsung/TizenRT
|
96abf62f1853f61fcf91ff14671a5e0c6ca48fdb
|
1a5c2e00a4b1bbf4c505bbf5cc6a8259e926f686
|
refs/heads/master
| 2023-08-31T08:59:33.327998
| 2023-08-08T06:09:20
| 2023-08-31T04:38:20
| 82,517,252
| 590
| 719
|
Apache-2.0
| 2023-09-14T06:54:49
| 2017-02-20T04:38:30
|
C
|
UTF-8
|
C
| false
| false
| 60,277
|
h
|
i2s_reg.h
|
/******************************************************************
*
* Copyright 2019 Samsung Electronics All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************/
// 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 _SOC_I2S_REG_H_
#define _SOC_I2S_REG_H_
#include "esp32_soc.h"
#define REG_I2S_BASE( i ) ( DR_REG_I2S_BASE + ((i)*0x1E000))
#define I2S_CONF_REG(i) (REG_I2S_BASE(i) + 0x0008)
/* I2S_SIG_LOOPBACK : R/W ;bitpos:[18] ;default: 1'b0 ; */
/*description: */
#define I2S_SIG_LOOPBACK (BIT(18))
#define I2S_SIG_LOOPBACK_M (BIT(18))
#define I2S_SIG_LOOPBACK_V 0x1
#define I2S_SIG_LOOPBACK_S 18
/* I2S_RX_MSB_RIGHT : R/W ;bitpos:[17] ;default: 1'b1 ; */
/*description: */
#define I2S_RX_MSB_RIGHT (BIT(17))
#define I2S_RX_MSB_RIGHT_M (BIT(17))
#define I2S_RX_MSB_RIGHT_V 0x1
#define I2S_RX_MSB_RIGHT_S 17
/* I2S_TX_MSB_RIGHT : R/W ;bitpos:[16] ;default: 1'b1 ; */
/*description: */
#define I2S_TX_MSB_RIGHT (BIT(16))
#define I2S_TX_MSB_RIGHT_M (BIT(16))
#define I2S_TX_MSB_RIGHT_V 0x1
#define I2S_TX_MSB_RIGHT_S 16
/* I2S_RX_MONO : R/W ;bitpos:[15] ;default: 1'b0 ; */
/*description: */
#define I2S_RX_MONO (BIT(15))
#define I2S_RX_MONO_M (BIT(15))
#define I2S_RX_MONO_V 0x1
#define I2S_RX_MONO_S 15
/* I2S_TX_MONO : R/W ;bitpos:[14] ;default: 1'b0 ; */
/*description: */
#define I2S_TX_MONO (BIT(14))
#define I2S_TX_MONO_M (BIT(14))
#define I2S_TX_MONO_V 0x1
#define I2S_TX_MONO_S 14
/* I2S_RX_SHORT_SYNC : R/W ;bitpos:[13] ;default: 1'b0 ; */
/*description: */
#define I2S_RX_SHORT_SYNC (BIT(13))
#define I2S_RX_SHORT_SYNC_M (BIT(13))
#define I2S_RX_SHORT_SYNC_V 0x1
#define I2S_RX_SHORT_SYNC_S 13
/* I2S_TX_SHORT_SYNC : R/W ;bitpos:[12] ;default: 1'b0 ; */
/*description: */
#define I2S_TX_SHORT_SYNC (BIT(12))
#define I2S_TX_SHORT_SYNC_M (BIT(12))
#define I2S_TX_SHORT_SYNC_V 0x1
#define I2S_TX_SHORT_SYNC_S 12
/* I2S_RX_MSB_SHIFT : R/W ;bitpos:[11] ;default: 1'b0 ; */
/*description: */
#define I2S_RX_MSB_SHIFT (BIT(11))
#define I2S_RX_MSB_SHIFT_M (BIT(11))
#define I2S_RX_MSB_SHIFT_V 0x1
#define I2S_RX_MSB_SHIFT_S 11
/* I2S_TX_MSB_SHIFT : R/W ;bitpos:[10] ;default: 1'b0 ; */
/*description: */
#define I2S_TX_MSB_SHIFT (BIT(10))
#define I2S_TX_MSB_SHIFT_M (BIT(10))
#define I2S_TX_MSB_SHIFT_V 0x1
#define I2S_TX_MSB_SHIFT_S 10
/* I2S_RX_RIGHT_FIRST : R/W ;bitpos:[9] ;default: 1'b1 ; */
/*description: */
#define I2S_RX_RIGHT_FIRST (BIT(9))
#define I2S_RX_RIGHT_FIRST_M (BIT(9))
#define I2S_RX_RIGHT_FIRST_V 0x1
#define I2S_RX_RIGHT_FIRST_S 9
/* I2S_TX_RIGHT_FIRST : R/W ;bitpos:[8] ;default: 1'b1 ; */
/*description: */
#define I2S_TX_RIGHT_FIRST (BIT(8))
#define I2S_TX_RIGHT_FIRST_M (BIT(8))
#define I2S_TX_RIGHT_FIRST_V 0x1
#define I2S_TX_RIGHT_FIRST_S 8
/* I2S_RX_SLAVE_MOD : R/W ;bitpos:[7] ;default: 1'b0 ; */
/*description: */
#define I2S_RX_SLAVE_MOD (BIT(7))
#define I2S_RX_SLAVE_MOD_M (BIT(7))
#define I2S_RX_SLAVE_MOD_V 0x1
#define I2S_RX_SLAVE_MOD_S 7
/* I2S_TX_SLAVE_MOD : R/W ;bitpos:[6] ;default: 1'b0 ; */
/*description: */
#define I2S_TX_SLAVE_MOD (BIT(6))
#define I2S_TX_SLAVE_MOD_M (BIT(6))
#define I2S_TX_SLAVE_MOD_V 0x1
#define I2S_TX_SLAVE_MOD_S 6
/* I2S_RX_START : R/W ;bitpos:[5] ;default: 1'b0 ; */
/*description: */
#define I2S_RX_START (BIT(5))
#define I2S_RX_START_M (BIT(5))
#define I2S_RX_START_V 0x1
#define I2S_RX_START_S 5
/* I2S_TX_START : R/W ;bitpos:[4] ;default: 1'b0 ; */
/*description: */
#define I2S_TX_START (BIT(4))
#define I2S_TX_START_M (BIT(4))
#define I2S_TX_START_V 0x1
#define I2S_TX_START_S 4
/* I2S_RX_FIFO_RESET : R/W ;bitpos:[3] ;default: 1'b0 ; */
/*description: */
#define I2S_RX_FIFO_RESET (BIT(3))
#define I2S_RX_FIFO_RESET_M (BIT(3))
#define I2S_RX_FIFO_RESET_V 0x1
#define I2S_RX_FIFO_RESET_S 3
/* I2S_TX_FIFO_RESET : R/W ;bitpos:[2] ;default: 1'b0 ; */
/*description: */
#define I2S_TX_FIFO_RESET (BIT(2))
#define I2S_TX_FIFO_RESET_M (BIT(2))
#define I2S_TX_FIFO_RESET_V 0x1
#define I2S_TX_FIFO_RESET_S 2
/* I2S_RX_RESET : R/W ;bitpos:[1] ;default: 1'b0 ; */
/*description: */
#define I2S_RX_RESET (BIT(1))
#define I2S_RX_RESET_M (BIT(1))
#define I2S_RX_RESET_V 0x1
#define I2S_RX_RESET_S 1
/* I2S_TX_RESET : R/W ;bitpos:[0] ;default: 1'b0 ; */
/*description: */
#define I2S_TX_RESET (BIT(0))
#define I2S_TX_RESET_M (BIT(0))
#define I2S_TX_RESET_V 0x1
#define I2S_TX_RESET_S 0
#define I2S_INT_RAW_REG(i) (REG_I2S_BASE(i) + 0x000c)
/* I2S_OUT_TOTAL_EOF_INT_RAW : RO ;bitpos:[16] ;default: 1'b0 ; */
/*description: */
#define I2S_OUT_TOTAL_EOF_INT_RAW (BIT(16))
#define I2S_OUT_TOTAL_EOF_INT_RAW_M (BIT(16))
#define I2S_OUT_TOTAL_EOF_INT_RAW_V 0x1
#define I2S_OUT_TOTAL_EOF_INT_RAW_S 16
/* I2S_IN_DSCR_EMPTY_INT_RAW : RO ;bitpos:[15] ;default: 1'b0 ; */
/*description: */
#define I2S_IN_DSCR_EMPTY_INT_RAW (BIT(15))
#define I2S_IN_DSCR_EMPTY_INT_RAW_M (BIT(15))
#define I2S_IN_DSCR_EMPTY_INT_RAW_V 0x1
#define I2S_IN_DSCR_EMPTY_INT_RAW_S 15
/* I2S_OUT_DSCR_ERR_INT_RAW : RO ;bitpos:[14] ;default: 1'b0 ; */
/*description: */
#define I2S_OUT_DSCR_ERR_INT_RAW (BIT(14))
#define I2S_OUT_DSCR_ERR_INT_RAW_M (BIT(14))
#define I2S_OUT_DSCR_ERR_INT_RAW_V 0x1
#define I2S_OUT_DSCR_ERR_INT_RAW_S 14
/* I2S_IN_DSCR_ERR_INT_RAW : RO ;bitpos:[13] ;default: 1'b0 ; */
/*description: */
#define I2S_IN_DSCR_ERR_INT_RAW (BIT(13))
#define I2S_IN_DSCR_ERR_INT_RAW_M (BIT(13))
#define I2S_IN_DSCR_ERR_INT_RAW_V 0x1
#define I2S_IN_DSCR_ERR_INT_RAW_S 13
/* I2S_OUT_EOF_INT_RAW : RO ;bitpos:[12] ;default: 1'b0 ; */
/*description: */
#define I2S_OUT_EOF_INT_RAW (BIT(12))
#define I2S_OUT_EOF_INT_RAW_M (BIT(12))
#define I2S_OUT_EOF_INT_RAW_V 0x1
#define I2S_OUT_EOF_INT_RAW_S 12
/* I2S_OUT_DONE_INT_RAW : RO ;bitpos:[11] ;default: 1'b0 ; */
/*description: */
#define I2S_OUT_DONE_INT_RAW (BIT(11))
#define I2S_OUT_DONE_INT_RAW_M (BIT(11))
#define I2S_OUT_DONE_INT_RAW_V 0x1
#define I2S_OUT_DONE_INT_RAW_S 11
/* I2S_IN_ERR_EOF_INT_RAW : RO ;bitpos:[10] ;default: 1'b0 ; */
/*description: */
#define I2S_IN_ERR_EOF_INT_RAW (BIT(10))
#define I2S_IN_ERR_EOF_INT_RAW_M (BIT(10))
#define I2S_IN_ERR_EOF_INT_RAW_V 0x1
#define I2S_IN_ERR_EOF_INT_RAW_S 10
/* I2S_IN_SUC_EOF_INT_RAW : RO ;bitpos:[9] ;default: 1'b0 ; */
/*description: */
#define I2S_IN_SUC_EOF_INT_RAW (BIT(9))
#define I2S_IN_SUC_EOF_INT_RAW_M (BIT(9))
#define I2S_IN_SUC_EOF_INT_RAW_V 0x1
#define I2S_IN_SUC_EOF_INT_RAW_S 9
/* I2S_IN_DONE_INT_RAW : RO ;bitpos:[8] ;default: 1'b0 ; */
/*description: */
#define I2S_IN_DONE_INT_RAW (BIT(8))
#define I2S_IN_DONE_INT_RAW_M (BIT(8))
#define I2S_IN_DONE_INT_RAW_V 0x1
#define I2S_IN_DONE_INT_RAW_S 8
/* I2S_TX_HUNG_INT_RAW : RO ;bitpos:[7] ;default: 1'b0 ; */
/*description: */
#define I2S_TX_HUNG_INT_RAW (BIT(7))
#define I2S_TX_HUNG_INT_RAW_M (BIT(7))
#define I2S_TX_HUNG_INT_RAW_V 0x1
#define I2S_TX_HUNG_INT_RAW_S 7
/* I2S_RX_HUNG_INT_RAW : RO ;bitpos:[6] ;default: 1'b0 ; */
/*description: */
#define I2S_RX_HUNG_INT_RAW (BIT(6))
#define I2S_RX_HUNG_INT_RAW_M (BIT(6))
#define I2S_RX_HUNG_INT_RAW_V 0x1
#define I2S_RX_HUNG_INT_RAW_S 6
/* I2S_TX_REMPTY_INT_RAW : RO ;bitpos:[5] ;default: 1'b0 ; */
/*description: */
#define I2S_TX_REMPTY_INT_RAW (BIT(5))
#define I2S_TX_REMPTY_INT_RAW_M (BIT(5))
#define I2S_TX_REMPTY_INT_RAW_V 0x1
#define I2S_TX_REMPTY_INT_RAW_S 5
/* I2S_TX_WFULL_INT_RAW : RO ;bitpos:[4] ;default: 1'b0 ; */
/*description: */
#define I2S_TX_WFULL_INT_RAW (BIT(4))
#define I2S_TX_WFULL_INT_RAW_M (BIT(4))
#define I2S_TX_WFULL_INT_RAW_V 0x1
#define I2S_TX_WFULL_INT_RAW_S 4
/* I2S_RX_REMPTY_INT_RAW : RO ;bitpos:[3] ;default: 1'b0 ; */
/*description: */
#define I2S_RX_REMPTY_INT_RAW (BIT(3))
#define I2S_RX_REMPTY_INT_RAW_M (BIT(3))
#define I2S_RX_REMPTY_INT_RAW_V 0x1
#define I2S_RX_REMPTY_INT_RAW_S 3
/* I2S_RX_WFULL_INT_RAW : RO ;bitpos:[2] ;default: 1'b0 ; */
/*description: */
#define I2S_RX_WFULL_INT_RAW (BIT(2))
#define I2S_RX_WFULL_INT_RAW_M (BIT(2))
#define I2S_RX_WFULL_INT_RAW_V 0x1
#define I2S_RX_WFULL_INT_RAW_S 2
/* I2S_TX_PUT_DATA_INT_RAW : RO ;bitpos:[1] ;default: 1'b0 ; */
/*description: */
#define I2S_TX_PUT_DATA_INT_RAW (BIT(1))
#define I2S_TX_PUT_DATA_INT_RAW_M (BIT(1))
#define I2S_TX_PUT_DATA_INT_RAW_V 0x1
#define I2S_TX_PUT_DATA_INT_RAW_S 1
/* I2S_RX_TAKE_DATA_INT_RAW : RO ;bitpos:[0] ;default: 1'b0 ; */
/*description: */
#define I2S_RX_TAKE_DATA_INT_RAW (BIT(0))
#define I2S_RX_TAKE_DATA_INT_RAW_M (BIT(0))
#define I2S_RX_TAKE_DATA_INT_RAW_V 0x1
#define I2S_RX_TAKE_DATA_INT_RAW_S 0
#define I2S_INT_ST_REG(i) (REG_I2S_BASE(i) + 0x0010)
/* I2S_OUT_TOTAL_EOF_INT_ST : RO ;bitpos:[16] ;default: 1'b0 ; */
/*description: */
#define I2S_OUT_TOTAL_EOF_INT_ST (BIT(16))
#define I2S_OUT_TOTAL_EOF_INT_ST_M (BIT(16))
#define I2S_OUT_TOTAL_EOF_INT_ST_V 0x1
#define I2S_OUT_TOTAL_EOF_INT_ST_S 16
/* I2S_IN_DSCR_EMPTY_INT_ST : RO ;bitpos:[15] ;default: 1'b0 ; */
/*description: */
#define I2S_IN_DSCR_EMPTY_INT_ST (BIT(15))
#define I2S_IN_DSCR_EMPTY_INT_ST_M (BIT(15))
#define I2S_IN_DSCR_EMPTY_INT_ST_V 0x1
#define I2S_IN_DSCR_EMPTY_INT_ST_S 15
/* I2S_OUT_DSCR_ERR_INT_ST : RO ;bitpos:[14] ;default: 1'b0 ; */
/*description: */
#define I2S_OUT_DSCR_ERR_INT_ST (BIT(14))
#define I2S_OUT_DSCR_ERR_INT_ST_M (BIT(14))
#define I2S_OUT_DSCR_ERR_INT_ST_V 0x1
#define I2S_OUT_DSCR_ERR_INT_ST_S 14
/* I2S_IN_DSCR_ERR_INT_ST : RO ;bitpos:[13] ;default: 1'b0 ; */
/*description: */
#define I2S_IN_DSCR_ERR_INT_ST (BIT(13))
#define I2S_IN_DSCR_ERR_INT_ST_M (BIT(13))
#define I2S_IN_DSCR_ERR_INT_ST_V 0x1
#define I2S_IN_DSCR_ERR_INT_ST_S 13
/* I2S_OUT_EOF_INT_ST : RO ;bitpos:[12] ;default: 1'b0 ; */
/*description: */
#define I2S_OUT_EOF_INT_ST (BIT(12))
#define I2S_OUT_EOF_INT_ST_M (BIT(12))
#define I2S_OUT_EOF_INT_ST_V 0x1
#define I2S_OUT_EOF_INT_ST_S 12
/* I2S_OUT_DONE_INT_ST : RO ;bitpos:[11] ;default: 1'b0 ; */
/*description: */
#define I2S_OUT_DONE_INT_ST (BIT(11))
#define I2S_OUT_DONE_INT_ST_M (BIT(11))
#define I2S_OUT_DONE_INT_ST_V 0x1
#define I2S_OUT_DONE_INT_ST_S 11
/* I2S_IN_ERR_EOF_INT_ST : RO ;bitpos:[10] ;default: 1'b0 ; */
/*description: */
#define I2S_IN_ERR_EOF_INT_ST (BIT(10))
#define I2S_IN_ERR_EOF_INT_ST_M (BIT(10))
#define I2S_IN_ERR_EOF_INT_ST_V 0x1
#define I2S_IN_ERR_EOF_INT_ST_S 10
/* I2S_IN_SUC_EOF_INT_ST : RO ;bitpos:[9] ;default: 1'b0 ; */
/*description: */
#define I2S_IN_SUC_EOF_INT_ST (BIT(9))
#define I2S_IN_SUC_EOF_INT_ST_M (BIT(9))
#define I2S_IN_SUC_EOF_INT_ST_V 0x1
#define I2S_IN_SUC_EOF_INT_ST_S 9
/* I2S_IN_DONE_INT_ST : RO ;bitpos:[8] ;default: 1'b0 ; */
/*description: */
#define I2S_IN_DONE_INT_ST (BIT(8))
#define I2S_IN_DONE_INT_ST_M (BIT(8))
#define I2S_IN_DONE_INT_ST_V 0x1
#define I2S_IN_DONE_INT_ST_S 8
/* I2S_TX_HUNG_INT_ST : RO ;bitpos:[7] ;default: 1'b0 ; */
/*description: */
#define I2S_TX_HUNG_INT_ST (BIT(7))
#define I2S_TX_HUNG_INT_ST_M (BIT(7))
#define I2S_TX_HUNG_INT_ST_V 0x1
#define I2S_TX_HUNG_INT_ST_S 7
/* I2S_RX_HUNG_INT_ST : RO ;bitpos:[6] ;default: 1'b0 ; */
/*description: */
#define I2S_RX_HUNG_INT_ST (BIT(6))
#define I2S_RX_HUNG_INT_ST_M (BIT(6))
#define I2S_RX_HUNG_INT_ST_V 0x1
#define I2S_RX_HUNG_INT_ST_S 6
/* I2S_TX_REMPTY_INT_ST : RO ;bitpos:[5] ;default: 1'b0 ; */
/*description: */
#define I2S_TX_REMPTY_INT_ST (BIT(5))
#define I2S_TX_REMPTY_INT_ST_M (BIT(5))
#define I2S_TX_REMPTY_INT_ST_V 0x1
#define I2S_TX_REMPTY_INT_ST_S 5
/* I2S_TX_WFULL_INT_ST : RO ;bitpos:[4] ;default: 1'b0 ; */
/*description: */
#define I2S_TX_WFULL_INT_ST (BIT(4))
#define I2S_TX_WFULL_INT_ST_M (BIT(4))
#define I2S_TX_WFULL_INT_ST_V 0x1
#define I2S_TX_WFULL_INT_ST_S 4
/* I2S_RX_REMPTY_INT_ST : RO ;bitpos:[3] ;default: 1'b0 ; */
/*description: */
#define I2S_RX_REMPTY_INT_ST (BIT(3))
#define I2S_RX_REMPTY_INT_ST_M (BIT(3))
#define I2S_RX_REMPTY_INT_ST_V 0x1
#define I2S_RX_REMPTY_INT_ST_S 3
/* I2S_RX_WFULL_INT_ST : RO ;bitpos:[2] ;default: 1'b0 ; */
/*description: */
#define I2S_RX_WFULL_INT_ST (BIT(2))
#define I2S_RX_WFULL_INT_ST_M (BIT(2))
#define I2S_RX_WFULL_INT_ST_V 0x1
#define I2S_RX_WFULL_INT_ST_S 2
/* I2S_TX_PUT_DATA_INT_ST : RO ;bitpos:[1] ;default: 1'b0 ; */
/*description: */
#define I2S_TX_PUT_DATA_INT_ST (BIT(1))
#define I2S_TX_PUT_DATA_INT_ST_M (BIT(1))
#define I2S_TX_PUT_DATA_INT_ST_V 0x1
#define I2S_TX_PUT_DATA_INT_ST_S 1
/* I2S_RX_TAKE_DATA_INT_ST : RO ;bitpos:[0] ;default: 1'b0 ; */
/*description: */
#define I2S_RX_TAKE_DATA_INT_ST (BIT(0))
#define I2S_RX_TAKE_DATA_INT_ST_M (BIT(0))
#define I2S_RX_TAKE_DATA_INT_ST_V 0x1
#define I2S_RX_TAKE_DATA_INT_ST_S 0
#define I2S_INT_ENA_REG(i) (REG_I2S_BASE(i) + 0x0014)
/* I2S_OUT_TOTAL_EOF_INT_ENA : R/W ;bitpos:[16] ;default: 1'b0 ; */
/*description: */
#define I2S_OUT_TOTAL_EOF_INT_ENA (BIT(16))
#define I2S_OUT_TOTAL_EOF_INT_ENA_M (BIT(16))
#define I2S_OUT_TOTAL_EOF_INT_ENA_V 0x1
#define I2S_OUT_TOTAL_EOF_INT_ENA_S 16
/* I2S_IN_DSCR_EMPTY_INT_ENA : R/W ;bitpos:[15] ;default: 1'b0 ; */
/*description: */
#define I2S_IN_DSCR_EMPTY_INT_ENA (BIT(15))
#define I2S_IN_DSCR_EMPTY_INT_ENA_M (BIT(15))
#define I2S_IN_DSCR_EMPTY_INT_ENA_V 0x1
#define I2S_IN_DSCR_EMPTY_INT_ENA_S 15
/* I2S_OUT_DSCR_ERR_INT_ENA : R/W ;bitpos:[14] ;default: 1'b0 ; */
/*description: */
#define I2S_OUT_DSCR_ERR_INT_ENA (BIT(14))
#define I2S_OUT_DSCR_ERR_INT_ENA_M (BIT(14))
#define I2S_OUT_DSCR_ERR_INT_ENA_V 0x1
#define I2S_OUT_DSCR_ERR_INT_ENA_S 14
/* I2S_IN_DSCR_ERR_INT_ENA : R/W ;bitpos:[13] ;default: 1'b0 ; */
/*description: */
#define I2S_IN_DSCR_ERR_INT_ENA (BIT(13))
#define I2S_IN_DSCR_ERR_INT_ENA_M (BIT(13))
#define I2S_IN_DSCR_ERR_INT_ENA_V 0x1
#define I2S_IN_DSCR_ERR_INT_ENA_S 13
/* I2S_OUT_EOF_INT_ENA : R/W ;bitpos:[12] ;default: 1'b0 ; */
/*description: */
#define I2S_OUT_EOF_INT_ENA (BIT(12))
#define I2S_OUT_EOF_INT_ENA_M (BIT(12))
#define I2S_OUT_EOF_INT_ENA_V 0x1
#define I2S_OUT_EOF_INT_ENA_S 12
/* I2S_OUT_DONE_INT_ENA : R/W ;bitpos:[11] ;default: 1'b0 ; */
/*description: */
#define I2S_OUT_DONE_INT_ENA (BIT(11))
#define I2S_OUT_DONE_INT_ENA_M (BIT(11))
#define I2S_OUT_DONE_INT_ENA_V 0x1
#define I2S_OUT_DONE_INT_ENA_S 11
/* I2S_IN_ERR_EOF_INT_ENA : R/W ;bitpos:[10] ;default: 1'b0 ; */
/*description: */
#define I2S_IN_ERR_EOF_INT_ENA (BIT(10))
#define I2S_IN_ERR_EOF_INT_ENA_M (BIT(10))
#define I2S_IN_ERR_EOF_INT_ENA_V 0x1
#define I2S_IN_ERR_EOF_INT_ENA_S 10
/* I2S_IN_SUC_EOF_INT_ENA : R/W ;bitpos:[9] ;default: 1'b0 ; */
/*description: */
#define I2S_IN_SUC_EOF_INT_ENA (BIT(9))
#define I2S_IN_SUC_EOF_INT_ENA_M (BIT(9))
#define I2S_IN_SUC_EOF_INT_ENA_V 0x1
#define I2S_IN_SUC_EOF_INT_ENA_S 9
/* I2S_IN_DONE_INT_ENA : R/W ;bitpos:[8] ;default: 1'b0 ; */
/*description: */
#define I2S_IN_DONE_INT_ENA (BIT(8))
#define I2S_IN_DONE_INT_ENA_M (BIT(8))
#define I2S_IN_DONE_INT_ENA_V 0x1
#define I2S_IN_DONE_INT_ENA_S 8
/* I2S_TX_HUNG_INT_ENA : R/W ;bitpos:[7] ;default: 1'b0 ; */
/*description: */
#define I2S_TX_HUNG_INT_ENA (BIT(7))
#define I2S_TX_HUNG_INT_ENA_M (BIT(7))
#define I2S_TX_HUNG_INT_ENA_V 0x1
#define I2S_TX_HUNG_INT_ENA_S 7
/* I2S_RX_HUNG_INT_ENA : R/W ;bitpos:[6] ;default: 1'b0 ; */
/*description: */
#define I2S_RX_HUNG_INT_ENA (BIT(6))
#define I2S_RX_HUNG_INT_ENA_M (BIT(6))
#define I2S_RX_HUNG_INT_ENA_V 0x1
#define I2S_RX_HUNG_INT_ENA_S 6
/* I2S_TX_REMPTY_INT_ENA : R/W ;bitpos:[5] ;default: 1'b0 ; */
/*description: */
#define I2S_TX_REMPTY_INT_ENA (BIT(5))
#define I2S_TX_REMPTY_INT_ENA_M (BIT(5))
#define I2S_TX_REMPTY_INT_ENA_V 0x1
#define I2S_TX_REMPTY_INT_ENA_S 5
/* I2S_TX_WFULL_INT_ENA : R/W ;bitpos:[4] ;default: 1'b0 ; */
/*description: */
#define I2S_TX_WFULL_INT_ENA (BIT(4))
#define I2S_TX_WFULL_INT_ENA_M (BIT(4))
#define I2S_TX_WFULL_INT_ENA_V 0x1
#define I2S_TX_WFULL_INT_ENA_S 4
/* I2S_RX_REMPTY_INT_ENA : R/W ;bitpos:[3] ;default: 1'b0 ; */
/*description: */
#define I2S_RX_REMPTY_INT_ENA (BIT(3))
#define I2S_RX_REMPTY_INT_ENA_M (BIT(3))
#define I2S_RX_REMPTY_INT_ENA_V 0x1
#define I2S_RX_REMPTY_INT_ENA_S 3
/* I2S_RX_WFULL_INT_ENA : R/W ;bitpos:[2] ;default: 1'b0 ; */
/*description: */
#define I2S_RX_WFULL_INT_ENA (BIT(2))
#define I2S_RX_WFULL_INT_ENA_M (BIT(2))
#define I2S_RX_WFULL_INT_ENA_V 0x1
#define I2S_RX_WFULL_INT_ENA_S 2
/* I2S_TX_PUT_DATA_INT_ENA : R/W ;bitpos:[1] ;default: 1'b0 ; */
/*description: */
#define I2S_TX_PUT_DATA_INT_ENA (BIT(1))
#define I2S_TX_PUT_DATA_INT_ENA_M (BIT(1))
#define I2S_TX_PUT_DATA_INT_ENA_V 0x1
#define I2S_TX_PUT_DATA_INT_ENA_S 1
/* I2S_RX_TAKE_DATA_INT_ENA : R/W ;bitpos:[0] ;default: 1'b0 ; */
/*description: */
#define I2S_RX_TAKE_DATA_INT_ENA (BIT(0))
#define I2S_RX_TAKE_DATA_INT_ENA_M (BIT(0))
#define I2S_RX_TAKE_DATA_INT_ENA_V 0x1
#define I2S_RX_TAKE_DATA_INT_ENA_S 0
#define I2S_INT_CLR_REG(i) (REG_I2S_BASE(i) + 0x0018)
/* I2S_OUT_TOTAL_EOF_INT_CLR : WO ;bitpos:[16] ;default: 1'b0 ; */
/*description: */
#define I2S_OUT_TOTAL_EOF_INT_CLR (BIT(16))
#define I2S_OUT_TOTAL_EOF_INT_CLR_M (BIT(16))
#define I2S_OUT_TOTAL_EOF_INT_CLR_V 0x1
#define I2S_OUT_TOTAL_EOF_INT_CLR_S 16
/* I2S_IN_DSCR_EMPTY_INT_CLR : WO ;bitpos:[15] ;default: 1'b0 ; */
/*description: */
#define I2S_IN_DSCR_EMPTY_INT_CLR (BIT(15))
#define I2S_IN_DSCR_EMPTY_INT_CLR_M (BIT(15))
#define I2S_IN_DSCR_EMPTY_INT_CLR_V 0x1
#define I2S_IN_DSCR_EMPTY_INT_CLR_S 15
/* I2S_OUT_DSCR_ERR_INT_CLR : WO ;bitpos:[14] ;default: 1'b0 ; */
/*description: */
#define I2S_OUT_DSCR_ERR_INT_CLR (BIT(14))
#define I2S_OUT_DSCR_ERR_INT_CLR_M (BIT(14))
#define I2S_OUT_DSCR_ERR_INT_CLR_V 0x1
#define I2S_OUT_DSCR_ERR_INT_CLR_S 14
/* I2S_IN_DSCR_ERR_INT_CLR : WO ;bitpos:[13] ;default: 1'b0 ; */
/*description: */
#define I2S_IN_DSCR_ERR_INT_CLR (BIT(13))
#define I2S_IN_DSCR_ERR_INT_CLR_M (BIT(13))
#define I2S_IN_DSCR_ERR_INT_CLR_V 0x1
#define I2S_IN_DSCR_ERR_INT_CLR_S 13
/* I2S_OUT_EOF_INT_CLR : WO ;bitpos:[12] ;default: 1'b0 ; */
/*description: */
#define I2S_OUT_EOF_INT_CLR (BIT(12))
#define I2S_OUT_EOF_INT_CLR_M (BIT(12))
#define I2S_OUT_EOF_INT_CLR_V 0x1
#define I2S_OUT_EOF_INT_CLR_S 12
/* I2S_OUT_DONE_INT_CLR : WO ;bitpos:[11] ;default: 1'b0 ; */
/*description: */
#define I2S_OUT_DONE_INT_CLR (BIT(11))
#define I2S_OUT_DONE_INT_CLR_M (BIT(11))
#define I2S_OUT_DONE_INT_CLR_V 0x1
#define I2S_OUT_DONE_INT_CLR_S 11
/* I2S_IN_ERR_EOF_INT_CLR : WO ;bitpos:[10] ;default: 1'b0 ; */
/*description: */
#define I2S_IN_ERR_EOF_INT_CLR (BIT(10))
#define I2S_IN_ERR_EOF_INT_CLR_M (BIT(10))
#define I2S_IN_ERR_EOF_INT_CLR_V 0x1
#define I2S_IN_ERR_EOF_INT_CLR_S 10
/* I2S_IN_SUC_EOF_INT_CLR : WO ;bitpos:[9] ;default: 1'b0 ; */
/*description: */
#define I2S_IN_SUC_EOF_INT_CLR (BIT(9))
#define I2S_IN_SUC_EOF_INT_CLR_M (BIT(9))
#define I2S_IN_SUC_EOF_INT_CLR_V 0x1
#define I2S_IN_SUC_EOF_INT_CLR_S 9
/* I2S_IN_DONE_INT_CLR : WO ;bitpos:[8] ;default: 1'b0 ; */
/*description: */
#define I2S_IN_DONE_INT_CLR (BIT(8))
#define I2S_IN_DONE_INT_CLR_M (BIT(8))
#define I2S_IN_DONE_INT_CLR_V 0x1
#define I2S_IN_DONE_INT_CLR_S 8
/* I2S_TX_HUNG_INT_CLR : WO ;bitpos:[7] ;default: 1'b0 ; */
/*description: */
#define I2S_TX_HUNG_INT_CLR (BIT(7))
#define I2S_TX_HUNG_INT_CLR_M (BIT(7))
#define I2S_TX_HUNG_INT_CLR_V 0x1
#define I2S_TX_HUNG_INT_CLR_S 7
/* I2S_RX_HUNG_INT_CLR : WO ;bitpos:[6] ;default: 1'b0 ; */
/*description: */
#define I2S_RX_HUNG_INT_CLR (BIT(6))
#define I2S_RX_HUNG_INT_CLR_M (BIT(6))
#define I2S_RX_HUNG_INT_CLR_V 0x1
#define I2S_RX_HUNG_INT_CLR_S 6
/* I2S_TX_REMPTY_INT_CLR : WO ;bitpos:[5] ;default: 1'b0 ; */
/*description: */
#define I2S_TX_REMPTY_INT_CLR (BIT(5))
#define I2S_TX_REMPTY_INT_CLR_M (BIT(5))
#define I2S_TX_REMPTY_INT_CLR_V 0x1
#define I2S_TX_REMPTY_INT_CLR_S 5
/* I2S_TX_WFULL_INT_CLR : WO ;bitpos:[4] ;default: 1'b0 ; */
/*description: */
#define I2S_TX_WFULL_INT_CLR (BIT(4))
#define I2S_TX_WFULL_INT_CLR_M (BIT(4))
#define I2S_TX_WFULL_INT_CLR_V 0x1
#define I2S_TX_WFULL_INT_CLR_S 4
/* I2S_RX_REMPTY_INT_CLR : WO ;bitpos:[3] ;default: 1'b0 ; */
/*description: */
#define I2S_RX_REMPTY_INT_CLR (BIT(3))
#define I2S_RX_REMPTY_INT_CLR_M (BIT(3))
#define I2S_RX_REMPTY_INT_CLR_V 0x1
#define I2S_RX_REMPTY_INT_CLR_S 3
/* I2S_RX_WFULL_INT_CLR : WO ;bitpos:[2] ;default: 1'b0 ; */
/*description: */
#define I2S_RX_WFULL_INT_CLR (BIT(2))
#define I2S_RX_WFULL_INT_CLR_M (BIT(2))
#define I2S_RX_WFULL_INT_CLR_V 0x1
#define I2S_RX_WFULL_INT_CLR_S 2
/* I2S_PUT_DATA_INT_CLR : WO ;bitpos:[1] ;default: 1'b0 ; */
/*description: */
#define I2S_PUT_DATA_INT_CLR (BIT(1))
#define I2S_PUT_DATA_INT_CLR_M (BIT(1))
#define I2S_PUT_DATA_INT_CLR_V 0x1
#define I2S_PUT_DATA_INT_CLR_S 1
/* I2S_TAKE_DATA_INT_CLR : WO ;bitpos:[0] ;default: 1'b0 ; */
/*description: */
#define I2S_TAKE_DATA_INT_CLR (BIT(0))
#define I2S_TAKE_DATA_INT_CLR_M (BIT(0))
#define I2S_TAKE_DATA_INT_CLR_V 0x1
#define I2S_TAKE_DATA_INT_CLR_S 0
#define I2S_TIMING_REG(i) (REG_I2S_BASE(i) + 0x001c)
/* I2S_TX_BCK_IN_INV : R/W ;bitpos:[24] ;default: 1'b0 ; */
/*description: */
#define I2S_TX_BCK_IN_INV (BIT(24))
#define I2S_TX_BCK_IN_INV_M (BIT(24))
#define I2S_TX_BCK_IN_INV_V 0x1
#define I2S_TX_BCK_IN_INV_S 24
/* I2S_DATA_ENABLE_DELAY : R/W ;bitpos:[23:22] ;default: 2'b0 ; */
/*description: */
#define I2S_DATA_ENABLE_DELAY 0x00000003
#define I2S_DATA_ENABLE_DELAY_M ((I2S_DATA_ENABLE_DELAY_V)<<(I2S_DATA_ENABLE_DELAY_S))
#define I2S_DATA_ENABLE_DELAY_V 0x3
#define I2S_DATA_ENABLE_DELAY_S 22
/* I2S_RX_DSYNC_SW : R/W ;bitpos:[21] ;default: 1'b0 ; */
/*description: */
#define I2S_RX_DSYNC_SW (BIT(21))
#define I2S_RX_DSYNC_SW_M (BIT(21))
#define I2S_RX_DSYNC_SW_V 0x1
#define I2S_RX_DSYNC_SW_S 21
/* I2S_TX_DSYNC_SW : R/W ;bitpos:[20] ;default: 1'b0 ; */
/*description: */
#define I2S_TX_DSYNC_SW (BIT(20))
#define I2S_TX_DSYNC_SW_M (BIT(20))
#define I2S_TX_DSYNC_SW_V 0x1
#define I2S_TX_DSYNC_SW_S 20
/* I2S_RX_BCK_OUT_DELAY : R/W ;bitpos:[19:18] ;default: 2'b0 ; */
/*description: */
#define I2S_RX_BCK_OUT_DELAY 0x00000003
#define I2S_RX_BCK_OUT_DELAY_M ((I2S_RX_BCK_OUT_DELAY_V)<<(I2S_RX_BCK_OUT_DELAY_S))
#define I2S_RX_BCK_OUT_DELAY_V 0x3
#define I2S_RX_BCK_OUT_DELAY_S 18
/* I2S_RX_WS_OUT_DELAY : R/W ;bitpos:[17:16] ;default: 2'b0 ; */
/*description: */
#define I2S_RX_WS_OUT_DELAY 0x00000003
#define I2S_RX_WS_OUT_DELAY_M ((I2S_RX_WS_OUT_DELAY_V)<<(I2S_RX_WS_OUT_DELAY_S))
#define I2S_RX_WS_OUT_DELAY_V 0x3
#define I2S_RX_WS_OUT_DELAY_S 16
/* I2S_TX_SD_OUT_DELAY : R/W ;bitpos:[15:14] ;default: 2'b0 ; */
/*description: */
#define I2S_TX_SD_OUT_DELAY 0x00000003
#define I2S_TX_SD_OUT_DELAY_M ((I2S_TX_SD_OUT_DELAY_V)<<(I2S_TX_SD_OUT_DELAY_S))
#define I2S_TX_SD_OUT_DELAY_V 0x3
#define I2S_TX_SD_OUT_DELAY_S 14
/* I2S_TX_WS_OUT_DELAY : R/W ;bitpos:[13:12] ;default: 2'b0 ; */
/*description: */
#define I2S_TX_WS_OUT_DELAY 0x00000003
#define I2S_TX_WS_OUT_DELAY_M ((I2S_TX_WS_OUT_DELAY_V)<<(I2S_TX_WS_OUT_DELAY_S))
#define I2S_TX_WS_OUT_DELAY_V 0x3
#define I2S_TX_WS_OUT_DELAY_S 12
/* I2S_TX_BCK_OUT_DELAY : R/W ;bitpos:[11:10] ;default: 2'b0 ; */
/*description: */
#define I2S_TX_BCK_OUT_DELAY 0x00000003
#define I2S_TX_BCK_OUT_DELAY_M ((I2S_TX_BCK_OUT_DELAY_V)<<(I2S_TX_BCK_OUT_DELAY_S))
#define I2S_TX_BCK_OUT_DELAY_V 0x3
#define I2S_TX_BCK_OUT_DELAY_S 10
/* I2S_RX_SD_IN_DELAY : R/W ;bitpos:[9:8] ;default: 2'b0 ; */
/*description: */
#define I2S_RX_SD_IN_DELAY 0x00000003
#define I2S_RX_SD_IN_DELAY_M ((I2S_RX_SD_IN_DELAY_V)<<(I2S_RX_SD_IN_DELAY_S))
#define I2S_RX_SD_IN_DELAY_V 0x3
#define I2S_RX_SD_IN_DELAY_S 8
/* I2S_RX_WS_IN_DELAY : R/W ;bitpos:[7:6] ;default: 2'b0 ; */
/*description: */
#define I2S_RX_WS_IN_DELAY 0x00000003
#define I2S_RX_WS_IN_DELAY_M ((I2S_RX_WS_IN_DELAY_V)<<(I2S_RX_WS_IN_DELAY_S))
#define I2S_RX_WS_IN_DELAY_V 0x3
#define I2S_RX_WS_IN_DELAY_S 6
/* I2S_RX_BCK_IN_DELAY : R/W ;bitpos:[5:4] ;default: 2'b0 ; */
/*description: */
#define I2S_RX_BCK_IN_DELAY 0x00000003
#define I2S_RX_BCK_IN_DELAY_M ((I2S_RX_BCK_IN_DELAY_V)<<(I2S_RX_BCK_IN_DELAY_S))
#define I2S_RX_BCK_IN_DELAY_V 0x3
#define I2S_RX_BCK_IN_DELAY_S 4
/* I2S_TX_WS_IN_DELAY : R/W ;bitpos:[3:2] ;default: 2'b0 ; */
/*description: */
#define I2S_TX_WS_IN_DELAY 0x00000003
#define I2S_TX_WS_IN_DELAY_M ((I2S_TX_WS_IN_DELAY_V)<<(I2S_TX_WS_IN_DELAY_S))
#define I2S_TX_WS_IN_DELAY_V 0x3
#define I2S_TX_WS_IN_DELAY_S 2
/* I2S_TX_BCK_IN_DELAY : R/W ;bitpos:[1:0] ;default: 2'b0 ; */
/*description: */
#define I2S_TX_BCK_IN_DELAY 0x00000003
#define I2S_TX_BCK_IN_DELAY_M ((I2S_TX_BCK_IN_DELAY_V)<<(I2S_TX_BCK_IN_DELAY_S))
#define I2S_TX_BCK_IN_DELAY_V 0x3
#define I2S_TX_BCK_IN_DELAY_S 0
#define I2S_FIFO_CONF_REG(i) (REG_I2S_BASE(i) + 0x0020)
/* I2S_RX_FIFO_MOD_FORCE_EN : R/W ;bitpos:[20] ;default: 1'b0 ; */
/*description: */
#define I2S_RX_FIFO_MOD_FORCE_EN (BIT(20))
#define I2S_RX_FIFO_MOD_FORCE_EN_M (BIT(20))
#define I2S_RX_FIFO_MOD_FORCE_EN_V 0x1
#define I2S_RX_FIFO_MOD_FORCE_EN_S 20
/* I2S_TX_FIFO_MOD_FORCE_EN : R/W ;bitpos:[19] ;default: 1'b0 ; */
/*description: */
#define I2S_TX_FIFO_MOD_FORCE_EN (BIT(19))
#define I2S_TX_FIFO_MOD_FORCE_EN_M (BIT(19))
#define I2S_TX_FIFO_MOD_FORCE_EN_V 0x1
#define I2S_TX_FIFO_MOD_FORCE_EN_S 19
/* I2S_RX_FIFO_MOD : R/W ;bitpos:[18:16] ;default: 3'b0 ; */
/*description: */
#define I2S_RX_FIFO_MOD 0x00000007
#define I2S_RX_FIFO_MOD_M ((I2S_RX_FIFO_MOD_V)<<(I2S_RX_FIFO_MOD_S))
#define I2S_RX_FIFO_MOD_V 0x7
#define I2S_RX_FIFO_MOD_S 16
/* I2S_TX_FIFO_MOD : R/W ;bitpos:[15:13] ;default: 3'b0 ; */
/*description: */
#define I2S_TX_FIFO_MOD 0x00000007
#define I2S_TX_FIFO_MOD_M ((I2S_TX_FIFO_MOD_V)<<(I2S_TX_FIFO_MOD_S))
#define I2S_TX_FIFO_MOD_V 0x7
#define I2S_TX_FIFO_MOD_S 13
/* I2S_DSCR_EN : R/W ;bitpos:[12] ;default: 1'd1 ; */
/*description: */
#define I2S_DSCR_EN (BIT(12))
#define I2S_DSCR_EN_M (BIT(12))
#define I2S_DSCR_EN_V 0x1
#define I2S_DSCR_EN_S 12
/* I2S_TX_DATA_NUM : R/W ;bitpos:[11:6] ;default: 6'd32 ; */
/*description: */
#define I2S_TX_DATA_NUM 0x0000003F
#define I2S_TX_DATA_NUM_M ((I2S_TX_DATA_NUM_V)<<(I2S_TX_DATA_NUM_S))
#define I2S_TX_DATA_NUM_V 0x3F
#define I2S_TX_DATA_NUM_S 6
/* I2S_RX_DATA_NUM : R/W ;bitpos:[5:0] ;default: 6'd32 ; */
/*description: */
#define I2S_RX_DATA_NUM 0x0000003F
#define I2S_RX_DATA_NUM_M ((I2S_RX_DATA_NUM_V)<<(I2S_RX_DATA_NUM_S))
#define I2S_RX_DATA_NUM_V 0x3F
#define I2S_RX_DATA_NUM_S 0
#define I2S_RXEOF_NUM_REG(i) (REG_I2S_BASE(i) + 0x0024)
/* I2S_RX_EOF_NUM : R/W ;bitpos:[31:0] ;default: 32'd64 ; */
/*description: */
#define I2S_RX_EOF_NUM 0xFFFFFFFF
#define I2S_RX_EOF_NUM_M ((I2S_RX_EOF_NUM_V)<<(I2S_RX_EOF_NUM_S))
#define I2S_RX_EOF_NUM_V 0xFFFFFFFF
#define I2S_RX_EOF_NUM_S 0
#define I2S_CONF_SIGLE_DATA_REG(i) (REG_I2S_BASE(i) + 0x0028)
/* I2S_SIGLE_DATA : R/W ;bitpos:[31:0] ;default: 32'd0 ; */
/*description: */
#define I2S_SIGLE_DATA 0xFFFFFFFF
#define I2S_SIGLE_DATA_M ((I2S_SIGLE_DATA_V)<<(I2S_SIGLE_DATA_S))
#define I2S_SIGLE_DATA_V 0xFFFFFFFF
#define I2S_SIGLE_DATA_S 0
#define I2S_CONF_CHAN_REG(i) (REG_I2S_BASE(i) + 0x002c)
/* I2S_RX_CHAN_MOD : R/W ;bitpos:[4:3] ;default: 2'b0 ; */
/*description: */
#define I2S_RX_CHAN_MOD 0x00000003
#define I2S_RX_CHAN_MOD_M ((I2S_RX_CHAN_MOD_V)<<(I2S_RX_CHAN_MOD_S))
#define I2S_RX_CHAN_MOD_V 0x3
#define I2S_RX_CHAN_MOD_S 3
/* I2S_TX_CHAN_MOD : R/W ;bitpos:[2:0] ;default: 3'b0 ; */
/*description: */
#define I2S_TX_CHAN_MOD 0x00000007
#define I2S_TX_CHAN_MOD_M ((I2S_TX_CHAN_MOD_V)<<(I2S_TX_CHAN_MOD_S))
#define I2S_TX_CHAN_MOD_V 0x7
#define I2S_TX_CHAN_MOD_S 0
#define I2S_OUT_LINK_REG(i) (REG_I2S_BASE(i) + 0x0030)
/* I2S_OUTLINK_PARK : RO ;bitpos:[31] ;default: 1'h0 ; */
/*description: */
#define I2S_OUTLINK_PARK (BIT(31))
#define I2S_OUTLINK_PARK_M (BIT(31))
#define I2S_OUTLINK_PARK_V 0x1
#define I2S_OUTLINK_PARK_S 31
/* I2S_OUTLINK_RESTART : R/W ;bitpos:[30] ;default: 1'b0 ; */
/*description: */
#define I2S_OUTLINK_RESTART (BIT(30))
#define I2S_OUTLINK_RESTART_M (BIT(30))
#define I2S_OUTLINK_RESTART_V 0x1
#define I2S_OUTLINK_RESTART_S 30
/* I2S_OUTLINK_START : R/W ;bitpos:[29] ;default: 1'b0 ; */
/*description: */
#define I2S_OUTLINK_START (BIT(29))
#define I2S_OUTLINK_START_M (BIT(29))
#define I2S_OUTLINK_START_V 0x1
#define I2S_OUTLINK_START_S 29
/* I2S_OUTLINK_STOP : R/W ;bitpos:[28] ;default: 1'b0 ; */
/*description: */
#define I2S_OUTLINK_STOP (BIT(28))
#define I2S_OUTLINK_STOP_M (BIT(28))
#define I2S_OUTLINK_STOP_V 0x1
#define I2S_OUTLINK_STOP_S 28
/* I2S_OUTLINK_ADDR : R/W ;bitpos:[19:0] ;default: 20'h0 ; */
/*description: */
#define I2S_OUTLINK_ADDR 0x000FFFFF
#define I2S_OUTLINK_ADDR_M ((I2S_OUTLINK_ADDR_V)<<(I2S_OUTLINK_ADDR_S))
#define I2S_OUTLINK_ADDR_V 0xFFFFF
#define I2S_OUTLINK_ADDR_S 0
#define I2S_IN_LINK_REG(i) (REG_I2S_BASE(i) + 0x0034)
/* I2S_INLINK_PARK : RO ;bitpos:[31] ;default: 1'h0 ; */
/*description: */
#define I2S_INLINK_PARK (BIT(31))
#define I2S_INLINK_PARK_M (BIT(31))
#define I2S_INLINK_PARK_V 0x1
#define I2S_INLINK_PARK_S 31
/* I2S_INLINK_RESTART : R/W ;bitpos:[30] ;default: 1'b0 ; */
/*description: */
#define I2S_INLINK_RESTART (BIT(30))
#define I2S_INLINK_RESTART_M (BIT(30))
#define I2S_INLINK_RESTART_V 0x1
#define I2S_INLINK_RESTART_S 30
/* I2S_INLINK_START : R/W ;bitpos:[29] ;default: 1'b0 ; */
/*description: */
#define I2S_INLINK_START (BIT(29))
#define I2S_INLINK_START_M (BIT(29))
#define I2S_INLINK_START_V 0x1
#define I2S_INLINK_START_S 29
/* I2S_INLINK_STOP : R/W ;bitpos:[28] ;default: 1'b0 ; */
/*description: */
#define I2S_INLINK_STOP (BIT(28))
#define I2S_INLINK_STOP_M (BIT(28))
#define I2S_INLINK_STOP_V 0x1
#define I2S_INLINK_STOP_S 28
/* I2S_INLINK_ADDR : R/W ;bitpos:[19:0] ;default: 20'h0 ; */
/*description: */
#define I2S_INLINK_ADDR 0x000FFFFF
#define I2S_INLINK_ADDR_M ((I2S_INLINK_ADDR_V)<<(I2S_INLINK_ADDR_S))
#define I2S_INLINK_ADDR_V 0xFFFFF
#define I2S_INLINK_ADDR_S 0
#define I2S_OUT_EOF_DES_ADDR_REG(i) (REG_I2S_BASE(i) + 0x0038)
/* I2S_OUT_EOF_DES_ADDR : RO ;bitpos:[31:0] ;default: 32'h0 ; */
/*description: */
#define I2S_OUT_EOF_DES_ADDR 0xFFFFFFFF
#define I2S_OUT_EOF_DES_ADDR_M ((I2S_OUT_EOF_DES_ADDR_V)<<(I2S_OUT_EOF_DES_ADDR_S))
#define I2S_OUT_EOF_DES_ADDR_V 0xFFFFFFFF
#define I2S_OUT_EOF_DES_ADDR_S 0
#define I2S_IN_EOF_DES_ADDR_REG(i) (REG_I2S_BASE(i) + 0x003c)
/* I2S_IN_SUC_EOF_DES_ADDR : RO ;bitpos:[31:0] ;default: 32'h0 ; */
/*description: */
#define I2S_IN_SUC_EOF_DES_ADDR 0xFFFFFFFF
#define I2S_IN_SUC_EOF_DES_ADDR_M ((I2S_IN_SUC_EOF_DES_ADDR_V)<<(I2S_IN_SUC_EOF_DES_ADDR_S))
#define I2S_IN_SUC_EOF_DES_ADDR_V 0xFFFFFFFF
#define I2S_IN_SUC_EOF_DES_ADDR_S 0
#define I2S_OUT_EOF_BFR_DES_ADDR_REG(i) (REG_I2S_BASE(i) + 0x0040)
/* I2S_OUT_EOF_BFR_DES_ADDR : RO ;bitpos:[31:0] ;default: 32'h0 ; */
/*description: */
#define I2S_OUT_EOF_BFR_DES_ADDR 0xFFFFFFFF
#define I2S_OUT_EOF_BFR_DES_ADDR_M ((I2S_OUT_EOF_BFR_DES_ADDR_V)<<(I2S_OUT_EOF_BFR_DES_ADDR_S))
#define I2S_OUT_EOF_BFR_DES_ADDR_V 0xFFFFFFFF
#define I2S_OUT_EOF_BFR_DES_ADDR_S 0
#define I2S_AHB_TEST_REG(i) (REG_I2S_BASE(i) + 0x0044)
/* I2S_AHB_TESTADDR : R/W ;bitpos:[5:4] ;default: 2'b0 ; */
/*description: */
#define I2S_AHB_TESTADDR 0x00000003
#define I2S_AHB_TESTADDR_M ((I2S_AHB_TESTADDR_V)<<(I2S_AHB_TESTADDR_S))
#define I2S_AHB_TESTADDR_V 0x3
#define I2S_AHB_TESTADDR_S 4
/* I2S_AHB_TESTMODE : R/W ;bitpos:[2:0] ;default: 3'b0 ; */
/*description: */
#define I2S_AHB_TESTMODE 0x00000007
#define I2S_AHB_TESTMODE_M ((I2S_AHB_TESTMODE_V)<<(I2S_AHB_TESTMODE_S))
#define I2S_AHB_TESTMODE_V 0x7
#define I2S_AHB_TESTMODE_S 0
#define I2S_INLINK_DSCR_REG(i) (REG_I2S_BASE(i) + 0x0048)
/* I2S_INLINK_DSCR : RO ;bitpos:[31:0] ;default: 32'b0 ; */
/*description: */
#define I2S_INLINK_DSCR 0xFFFFFFFF
#define I2S_INLINK_DSCR_M ((I2S_INLINK_DSCR_V)<<(I2S_INLINK_DSCR_S))
#define I2S_INLINK_DSCR_V 0xFFFFFFFF
#define I2S_INLINK_DSCR_S 0
#define I2S_INLINK_DSCR_BF0_REG(i) (REG_I2S_BASE(i) + 0x004C)
/* I2S_INLINK_DSCR_BF0 : RO ;bitpos:[31:0] ;default: 32'b0 ; */
/*description: */
#define I2S_INLINK_DSCR_BF0 0xFFFFFFFF
#define I2S_INLINK_DSCR_BF0_M ((I2S_INLINK_DSCR_BF0_V)<<(I2S_INLINK_DSCR_BF0_S))
#define I2S_INLINK_DSCR_BF0_V 0xFFFFFFFF
#define I2S_INLINK_DSCR_BF0_S 0
#define I2S_INLINK_DSCR_BF1_REG(i) (REG_I2S_BASE(i) + 0x0050)
/* I2S_INLINK_DSCR_BF1 : RO ;bitpos:[31:0] ;default: 32'b0 ; */
/*description: */
#define I2S_INLINK_DSCR_BF1 0xFFFFFFFF
#define I2S_INLINK_DSCR_BF1_M ((I2S_INLINK_DSCR_BF1_V)<<(I2S_INLINK_DSCR_BF1_S))
#define I2S_INLINK_DSCR_BF1_V 0xFFFFFFFF
#define I2S_INLINK_DSCR_BF1_S 0
#define I2S_OUTLINK_DSCR_REG(i) (REG_I2S_BASE(i) + 0x0054)
/* I2S_OUTLINK_DSCR : RO ;bitpos:[31:0] ;default: 32'b0 ; */
/*description: */
#define I2S_OUTLINK_DSCR 0xFFFFFFFF
#define I2S_OUTLINK_DSCR_M ((I2S_OUTLINK_DSCR_V)<<(I2S_OUTLINK_DSCR_S))
#define I2S_OUTLINK_DSCR_V 0xFFFFFFFF
#define I2S_OUTLINK_DSCR_S 0
#define I2S_OUTLINK_DSCR_BF0_REG(i) (REG_I2S_BASE(i) + 0x0058)
/* I2S_OUTLINK_DSCR_BF0 : RO ;bitpos:[31:0] ;default: 32'b0 ; */
/*description: */
#define I2S_OUTLINK_DSCR_BF0 0xFFFFFFFF
#define I2S_OUTLINK_DSCR_BF0_M ((I2S_OUTLINK_DSCR_BF0_V)<<(I2S_OUTLINK_DSCR_BF0_S))
#define I2S_OUTLINK_DSCR_BF0_V 0xFFFFFFFF
#define I2S_OUTLINK_DSCR_BF0_S 0
#define I2S_OUTLINK_DSCR_BF1_REG(i) (REG_I2S_BASE(i) + 0x005C)
/* I2S_OUTLINK_DSCR_BF1 : RO ;bitpos:[31:0] ;default: 32'b0 ; */
/*description: */
#define I2S_OUTLINK_DSCR_BF1 0xFFFFFFFF
#define I2S_OUTLINK_DSCR_BF1_M ((I2S_OUTLINK_DSCR_BF1_V)<<(I2S_OUTLINK_DSCR_BF1_S))
#define I2S_OUTLINK_DSCR_BF1_V 0xFFFFFFFF
#define I2S_OUTLINK_DSCR_BF1_S 0
#define I2S_LC_CONF_REG(i) (REG_I2S_BASE(i) + 0x0060)
/* I2S_MEM_TRANS_EN : R/W ;bitpos:[13] ;default: 1'b0 ; */
/*description: */
#define I2S_MEM_TRANS_EN (BIT(13))
#define I2S_MEM_TRANS_EN_M (BIT(13))
#define I2S_MEM_TRANS_EN_V 0x1
#define I2S_MEM_TRANS_EN_S 13
/* I2S_CHECK_OWNER : R/W ;bitpos:[12] ;default: 1'b0 ; */
/*description: */
#define I2S_CHECK_OWNER (BIT(12))
#define I2S_CHECK_OWNER_M (BIT(12))
#define I2S_CHECK_OWNER_V 0x1
#define I2S_CHECK_OWNER_S 12
/* I2S_OUT_DATA_BURST_EN : R/W ;bitpos:[11] ;default: 1'b0 ; */
/*description: */
#define I2S_OUT_DATA_BURST_EN (BIT(11))
#define I2S_OUT_DATA_BURST_EN_M (BIT(11))
#define I2S_OUT_DATA_BURST_EN_V 0x1
#define I2S_OUT_DATA_BURST_EN_S 11
/* I2S_INDSCR_BURST_EN : R/W ;bitpos:[10] ;default: 1'b0 ; */
/*description: */
#define I2S_INDSCR_BURST_EN (BIT(10))
#define I2S_INDSCR_BURST_EN_M (BIT(10))
#define I2S_INDSCR_BURST_EN_V 0x1
#define I2S_INDSCR_BURST_EN_S 10
/* I2S_OUTDSCR_BURST_EN : R/W ;bitpos:[9] ;default: 1'b0 ; */
/*description: */
#define I2S_OUTDSCR_BURST_EN (BIT(9))
#define I2S_OUTDSCR_BURST_EN_M (BIT(9))
#define I2S_OUTDSCR_BURST_EN_V 0x1
#define I2S_OUTDSCR_BURST_EN_S 9
/* I2S_OUT_EOF_MODE : R/W ;bitpos:[8] ;default: 1'b1 ; */
/*description: */
#define I2S_OUT_EOF_MODE (BIT(8))
#define I2S_OUT_EOF_MODE_M (BIT(8))
#define I2S_OUT_EOF_MODE_V 0x1
#define I2S_OUT_EOF_MODE_S 8
/* I2S_OUT_NO_RESTART_CLR : R/W ;bitpos:[7] ;default: 1'b0 ; */
/*description: */
#define I2S_OUT_NO_RESTART_CLR (BIT(7))
#define I2S_OUT_NO_RESTART_CLR_M (BIT(7))
#define I2S_OUT_NO_RESTART_CLR_V 0x1
#define I2S_OUT_NO_RESTART_CLR_S 7
/* I2S_OUT_AUTO_WRBACK : R/W ;bitpos:[6] ;default: 1'b0 ; */
/*description: */
#define I2S_OUT_AUTO_WRBACK (BIT(6))
#define I2S_OUT_AUTO_WRBACK_M (BIT(6))
#define I2S_OUT_AUTO_WRBACK_V 0x1
#define I2S_OUT_AUTO_WRBACK_S 6
/* I2S_IN_LOOP_TEST : R/W ;bitpos:[5] ;default: 1'b0 ; */
/*description: */
#define I2S_IN_LOOP_TEST (BIT(5))
#define I2S_IN_LOOP_TEST_M (BIT(5))
#define I2S_IN_LOOP_TEST_V 0x1
#define I2S_IN_LOOP_TEST_S 5
/* I2S_OUT_LOOP_TEST : R/W ;bitpos:[4] ;default: 1'b0 ; */
/*description: */
#define I2S_OUT_LOOP_TEST (BIT(4))
#define I2S_OUT_LOOP_TEST_M (BIT(4))
#define I2S_OUT_LOOP_TEST_V 0x1
#define I2S_OUT_LOOP_TEST_S 4
/* I2S_AHBM_RST : R/W ;bitpos:[3] ;default: 1'b0 ; */
/*description: */
#define I2S_AHBM_RST (BIT(3))
#define I2S_AHBM_RST_M (BIT(3))
#define I2S_AHBM_RST_V 0x1
#define I2S_AHBM_RST_S 3
/* I2S_AHBM_FIFO_RST : R/W ;bitpos:[2] ;default: 1'b0 ; */
/*description: */
#define I2S_AHBM_FIFO_RST (BIT(2))
#define I2S_AHBM_FIFO_RST_M (BIT(2))
#define I2S_AHBM_FIFO_RST_V 0x1
#define I2S_AHBM_FIFO_RST_S 2
/* I2S_OUT_RST : R/W ;bitpos:[1] ;default: 1'b0 ; */
/*description: */
#define I2S_OUT_RST (BIT(1))
#define I2S_OUT_RST_M (BIT(1))
#define I2S_OUT_RST_V 0x1
#define I2S_OUT_RST_S 1
/* I2S_IN_RST : R/W ;bitpos:[0] ;default: 1'h0 ; */
/*description: */
#define I2S_IN_RST (BIT(0))
#define I2S_IN_RST_M (BIT(0))
#define I2S_IN_RST_V 0x1
#define I2S_IN_RST_S 0
#define I2S_OUTFIFO_PUSH_REG(i) (REG_I2S_BASE(i) + 0x0064)
/* I2S_OUTFIFO_PUSH : R/W ;bitpos:[16] ;default: 1'h0 ; */
/*description: */
#define I2S_OUTFIFO_PUSH (BIT(16))
#define I2S_OUTFIFO_PUSH_M (BIT(16))
#define I2S_OUTFIFO_PUSH_V 0x1
#define I2S_OUTFIFO_PUSH_S 16
/* I2S_OUTFIFO_WDATA : R/W ;bitpos:[8:0] ;default: 9'h0 ; */
/*description: */
#define I2S_OUTFIFO_WDATA 0x000001FF
#define I2S_OUTFIFO_WDATA_M ((I2S_OUTFIFO_WDATA_V)<<(I2S_OUTFIFO_WDATA_S))
#define I2S_OUTFIFO_WDATA_V 0x1FF
#define I2S_OUTFIFO_WDATA_S 0
#define I2S_INFIFO_POP_REG(i) (REG_I2S_BASE(i) + 0x0068)
/* I2S_INFIFO_POP : R/W ;bitpos:[16] ;default: 1'h0 ; */
/*description: */
#define I2S_INFIFO_POP (BIT(16))
#define I2S_INFIFO_POP_M (BIT(16))
#define I2S_INFIFO_POP_V 0x1
#define I2S_INFIFO_POP_S 16
/* I2S_INFIFO_RDATA : RO ;bitpos:[11:0] ;default: 12'h0 ; */
/*description: */
#define I2S_INFIFO_RDATA 0x00000FFF
#define I2S_INFIFO_RDATA_M ((I2S_INFIFO_RDATA_V)<<(I2S_INFIFO_RDATA_S))
#define I2S_INFIFO_RDATA_V 0xFFF
#define I2S_INFIFO_RDATA_S 0
#define I2S_LC_STATE0_REG(i) (REG_I2S_BASE(i) + 0x006C)
/* I2S_LC_STATE0 : RO ;bitpos:[31:0] ;default: 32'h0 ; */
/*description: */
#define I2S_LC_STATE0 0xFFFFFFFF
#define I2S_LC_STATE0_M ((I2S_LC_STATE0_V)<<(I2S_LC_STATE0_S))
#define I2S_LC_STATE0_V 0xFFFFFFFF
#define I2S_LC_STATE0_S 0
#define I2S_LC_STATE1_REG(i) (REG_I2S_BASE(i) + 0x0070)
/* I2S_LC_STATE1 : RO ;bitpos:[31:0] ;default: 32'h0 ; */
/*description: */
#define I2S_LC_STATE1 0xFFFFFFFF
#define I2S_LC_STATE1_M ((I2S_LC_STATE1_V)<<(I2S_LC_STATE1_S))
#define I2S_LC_STATE1_V 0xFFFFFFFF
#define I2S_LC_STATE1_S 0
#define I2S_LC_HUNG_CONF_REG(i) (REG_I2S_BASE(i) + 0x0074)
/* I2S_LC_FIFO_TIMEOUT_ENA : R/W ;bitpos:[11] ;default: 1'b1 ; */
/*description: */
#define I2S_LC_FIFO_TIMEOUT_ENA (BIT(11))
#define I2S_LC_FIFO_TIMEOUT_ENA_M (BIT(11))
#define I2S_LC_FIFO_TIMEOUT_ENA_V 0x1
#define I2S_LC_FIFO_TIMEOUT_ENA_S 11
/* I2S_LC_FIFO_TIMEOUT_SHIFT : R/W ;bitpos:[10:8] ;default: 3'b0 ; */
/*description: */
#define I2S_LC_FIFO_TIMEOUT_SHIFT 0x00000007
#define I2S_LC_FIFO_TIMEOUT_SHIFT_M ((I2S_LC_FIFO_TIMEOUT_SHIFT_V)<<(I2S_LC_FIFO_TIMEOUT_SHIFT_S))
#define I2S_LC_FIFO_TIMEOUT_SHIFT_V 0x7
#define I2S_LC_FIFO_TIMEOUT_SHIFT_S 8
/* I2S_LC_FIFO_TIMEOUT : R/W ;bitpos:[7:0] ;default: 8'h10 ; */
/*description: */
#define I2S_LC_FIFO_TIMEOUT 0x000000FF
#define I2S_LC_FIFO_TIMEOUT_M ((I2S_LC_FIFO_TIMEOUT_V)<<(I2S_LC_FIFO_TIMEOUT_S))
#define I2S_LC_FIFO_TIMEOUT_V 0xFF
#define I2S_LC_FIFO_TIMEOUT_S 0
#define I2S_CVSD_CONF0_REG(i) (REG_I2S_BASE(i) + 0x0080)
/* I2S_CVSD_Y_MIN : R/W ;bitpos:[31:16] ;default: 16'h8000 ; */
/*description: */
#define I2S_CVSD_Y_MIN 0x0000FFFF
#define I2S_CVSD_Y_MIN_M ((I2S_CVSD_Y_MIN_V)<<(I2S_CVSD_Y_MIN_S))
#define I2S_CVSD_Y_MIN_V 0xFFFF
#define I2S_CVSD_Y_MIN_S 16
/* I2S_CVSD_Y_MAX : R/W ;bitpos:[15:0] ;default: 16'h7fff ; */
/*description: */
#define I2S_CVSD_Y_MAX 0x0000FFFF
#define I2S_CVSD_Y_MAX_M ((I2S_CVSD_Y_MAX_V)<<(I2S_CVSD_Y_MAX_S))
#define I2S_CVSD_Y_MAX_V 0xFFFF
#define I2S_CVSD_Y_MAX_S 0
#define I2S_CVSD_CONF1_REG(i) (REG_I2S_BASE(i) + 0x0084)
/* I2S_CVSD_SIGMA_MIN : R/W ;bitpos:[31:16] ;default: 16'd10 ; */
/*description: */
#define I2S_CVSD_SIGMA_MIN 0x0000FFFF
#define I2S_CVSD_SIGMA_MIN_M ((I2S_CVSD_SIGMA_MIN_V)<<(I2S_CVSD_SIGMA_MIN_S))
#define I2S_CVSD_SIGMA_MIN_V 0xFFFF
#define I2S_CVSD_SIGMA_MIN_S 16
/* I2S_CVSD_SIGMA_MAX : R/W ;bitpos:[15:0] ;default: 16'd1280 ; */
/*description: */
#define I2S_CVSD_SIGMA_MAX 0x0000FFFF
#define I2S_CVSD_SIGMA_MAX_M ((I2S_CVSD_SIGMA_MAX_V)<<(I2S_CVSD_SIGMA_MAX_S))
#define I2S_CVSD_SIGMA_MAX_V 0xFFFF
#define I2S_CVSD_SIGMA_MAX_S 0
#define I2S_CVSD_CONF2_REG(i) (REG_I2S_BASE(i) + 0x0088)
/* I2S_CVSD_H : R/W ;bitpos:[18:16] ;default: 3'd5 ; */
/*description: */
#define I2S_CVSD_H 0x00000007
#define I2S_CVSD_H_M ((I2S_CVSD_H_V)<<(I2S_CVSD_H_S))
#define I2S_CVSD_H_V 0x7
#define I2S_CVSD_H_S 16
/* I2S_CVSD_BETA : R/W ;bitpos:[15:6] ;default: 10'd10 ; */
/*description: */
#define I2S_CVSD_BETA 0x000003FF
#define I2S_CVSD_BETA_M ((I2S_CVSD_BETA_V)<<(I2S_CVSD_BETA_S))
#define I2S_CVSD_BETA_V 0x3FF
#define I2S_CVSD_BETA_S 6
/* I2S_CVSD_J : R/W ;bitpos:[5:3] ;default: 3'h4 ; */
/*description: */
#define I2S_CVSD_J 0x00000007
#define I2S_CVSD_J_M ((I2S_CVSD_J_V)<<(I2S_CVSD_J_S))
#define I2S_CVSD_J_V 0x7
#define I2S_CVSD_J_S 3
/* I2S_CVSD_K : R/W ;bitpos:[2:0] ;default: 3'h4 ; */
/*description: */
#define I2S_CVSD_K 0x00000007
#define I2S_CVSD_K_M ((I2S_CVSD_K_V)<<(I2S_CVSD_K_S))
#define I2S_CVSD_K_V 0x7
#define I2S_CVSD_K_S 0
#define I2S_PLC_CONF0_REG(i) (REG_I2S_BASE(i) + 0x008C)
/* I2S_N_MIN_ERR : R/W ;bitpos:[27:25] ;default: 3'd4 ; */
/*description: */
#define I2S_N_MIN_ERR 0x00000007
#define I2S_N_MIN_ERR_M ((I2S_N_MIN_ERR_V)<<(I2S_N_MIN_ERR_S))
#define I2S_N_MIN_ERR_V 0x7
#define I2S_N_MIN_ERR_S 25
/* I2S_PACK_LEN_8K : R/W ;bitpos:[24:20] ;default: 5'd10 ; */
/*description: */
#define I2S_PACK_LEN_8K 0x0000001F
#define I2S_PACK_LEN_8K_M ((I2S_PACK_LEN_8K_V)<<(I2S_PACK_LEN_8K_S))
#define I2S_PACK_LEN_8K_V 0x1F
#define I2S_PACK_LEN_8K_S 20
/* I2S_MAX_SLIDE_SAMPLE : R/W ;bitpos:[19:12] ;default: 8'd128 ; */
/*description: */
#define I2S_MAX_SLIDE_SAMPLE 0x000000FF
#define I2S_MAX_SLIDE_SAMPLE_M ((I2S_MAX_SLIDE_SAMPLE_V)<<(I2S_MAX_SLIDE_SAMPLE_S))
#define I2S_MAX_SLIDE_SAMPLE_V 0xFF
#define I2S_MAX_SLIDE_SAMPLE_S 12
/* I2S_SHIFT_RATE : R/W ;bitpos:[11:9] ;default: 3'h1 ; */
/*description: */
#define I2S_SHIFT_RATE 0x00000007
#define I2S_SHIFT_RATE_M ((I2S_SHIFT_RATE_V)<<(I2S_SHIFT_RATE_S))
#define I2S_SHIFT_RATE_V 0x7
#define I2S_SHIFT_RATE_S 9
/* I2S_N_ERR_SEG : R/W ;bitpos:[8:6] ;default: 3'h4 ; */
/*description: */
#define I2S_N_ERR_SEG 0x00000007
#define I2S_N_ERR_SEG_M ((I2S_N_ERR_SEG_V)<<(I2S_N_ERR_SEG_S))
#define I2S_N_ERR_SEG_V 0x7
#define I2S_N_ERR_SEG_S 6
/* I2S_GOOD_PACK_MAX : R/W ;bitpos:[5:0] ;default: 6'h39 ; */
/*description: */
#define I2S_GOOD_PACK_MAX 0x0000003F
#define I2S_GOOD_PACK_MAX_M ((I2S_GOOD_PACK_MAX_V)<<(I2S_GOOD_PACK_MAX_S))
#define I2S_GOOD_PACK_MAX_V 0x3F
#define I2S_GOOD_PACK_MAX_S 0
#define I2S_PLC_CONF1_REG(i) (REG_I2S_BASE(i) + 0x0090)
/* I2S_SLIDE_WIN_LEN : R/W ;bitpos:[31:24] ;default: 8'd160 ; */
/*description: */
#define I2S_SLIDE_WIN_LEN 0x000000FF
#define I2S_SLIDE_WIN_LEN_M ((I2S_SLIDE_WIN_LEN_V)<<(I2S_SLIDE_WIN_LEN_S))
#define I2S_SLIDE_WIN_LEN_V 0xFF
#define I2S_SLIDE_WIN_LEN_S 24
/* I2S_BAD_OLA_WIN2_PARA : R/W ;bitpos:[23:16] ;default: 8'd23 ; */
/*description: */
#define I2S_BAD_OLA_WIN2_PARA 0x000000FF
#define I2S_BAD_OLA_WIN2_PARA_M ((I2S_BAD_OLA_WIN2_PARA_V)<<(I2S_BAD_OLA_WIN2_PARA_S))
#define I2S_BAD_OLA_WIN2_PARA_V 0xFF
#define I2S_BAD_OLA_WIN2_PARA_S 16
/* I2S_BAD_OLA_WIN2_PARA_SHIFT : R/W ;bitpos:[15:12] ;default: 4'd8 ; */
/*description: */
#define I2S_BAD_OLA_WIN2_PARA_SHIFT 0x0000000F
#define I2S_BAD_OLA_WIN2_PARA_SHIFT_M ((I2S_BAD_OLA_WIN2_PARA_SHIFT_V)<<(I2S_BAD_OLA_WIN2_PARA_SHIFT_S))
#define I2S_BAD_OLA_WIN2_PARA_SHIFT_V 0xF
#define I2S_BAD_OLA_WIN2_PARA_SHIFT_S 12
/* I2S_BAD_CEF_ATTEN_PARA_SHIFT : R/W ;bitpos:[11:8] ;default: 4'd10 ; */
/*description: */
#define I2S_BAD_CEF_ATTEN_PARA_SHIFT 0x0000000F
#define I2S_BAD_CEF_ATTEN_PARA_SHIFT_M ((I2S_BAD_CEF_ATTEN_PARA_SHIFT_V)<<(I2S_BAD_CEF_ATTEN_PARA_SHIFT_S))
#define I2S_BAD_CEF_ATTEN_PARA_SHIFT_V 0xF
#define I2S_BAD_CEF_ATTEN_PARA_SHIFT_S 8
/* I2S_BAD_CEF_ATTEN_PARA : R/W ;bitpos:[7:0] ;default: 8'd5 ; */
/*description: */
#define I2S_BAD_CEF_ATTEN_PARA 0x000000FF
#define I2S_BAD_CEF_ATTEN_PARA_M ((I2S_BAD_CEF_ATTEN_PARA_V)<<(I2S_BAD_CEF_ATTEN_PARA_S))
#define I2S_BAD_CEF_ATTEN_PARA_V 0xFF
#define I2S_BAD_CEF_ATTEN_PARA_S 0
#define I2S_PLC_CONF2_REG(i) (REG_I2S_BASE(i) + 0x0094)
/* I2S_MIN_PERIOD : R/W ;bitpos:[6:2] ;default: 5'd10 ; */
/*description: */
#define I2S_MIN_PERIOD 0x0000001F
#define I2S_MIN_PERIOD_M ((I2S_MIN_PERIOD_V)<<(I2S_MIN_PERIOD_S))
#define I2S_MIN_PERIOD_V 0x1F
#define I2S_MIN_PERIOD_S 2
/* I2S_CVSD_SEG_MOD : R/W ;bitpos:[1:0] ;default: 2'd0 ; */
/*description: */
#define I2S_CVSD_SEG_MOD 0x00000003
#define I2S_CVSD_SEG_MOD_M ((I2S_CVSD_SEG_MOD_V)<<(I2S_CVSD_SEG_MOD_S))
#define I2S_CVSD_SEG_MOD_V 0x3
#define I2S_CVSD_SEG_MOD_S 0
#define I2S_ESCO_CONF0_REG(i) (REG_I2S_BASE(i) + 0x0098)
/* I2S_PLC2DMA_EN : R/W ;bitpos:[12] ;default: 1'b0 ; */
/*description: */
#define I2S_PLC2DMA_EN (BIT(12))
#define I2S_PLC2DMA_EN_M (BIT(12))
#define I2S_PLC2DMA_EN_V 0x1
#define I2S_PLC2DMA_EN_S 12
/* I2S_PLC_EN : R/W ;bitpos:[11] ;default: 1'b0 ; */
/*description: */
#define I2S_PLC_EN (BIT(11))
#define I2S_PLC_EN_M (BIT(11))
#define I2S_PLC_EN_V 0x1
#define I2S_PLC_EN_S 11
/* I2S_CVSD_DEC_RESET : R/W ;bitpos:[10] ;default: 1'b0 ; */
/*description: */
#define I2S_CVSD_DEC_RESET (BIT(10))
#define I2S_CVSD_DEC_RESET_M (BIT(10))
#define I2S_CVSD_DEC_RESET_V 0x1
#define I2S_CVSD_DEC_RESET_S 10
/* I2S_CVSD_DEC_START : R/W ;bitpos:[9] ;default: 1'b0 ; */
/*description: */
#define I2S_CVSD_DEC_START (BIT(9))
#define I2S_CVSD_DEC_START_M (BIT(9))
#define I2S_CVSD_DEC_START_V 0x1
#define I2S_CVSD_DEC_START_S 9
/* I2S_ESCO_CVSD_INF_EN : R/W ;bitpos:[8] ;default: 1'b0 ; */
/*description: */
#define I2S_ESCO_CVSD_INF_EN (BIT(8))
#define I2S_ESCO_CVSD_INF_EN_M (BIT(8))
#define I2S_ESCO_CVSD_INF_EN_V 0x1
#define I2S_ESCO_CVSD_INF_EN_S 8
/* I2S_ESCO_CVSD_PACK_LEN_8K : R/W ;bitpos:[7:3] ;default: 5'b0 ; */
/*description: */
#define I2S_ESCO_CVSD_PACK_LEN_8K 0x0000001F
#define I2S_ESCO_CVSD_PACK_LEN_8K_M ((I2S_ESCO_CVSD_PACK_LEN_8K_V)<<(I2S_ESCO_CVSD_PACK_LEN_8K_S))
#define I2S_ESCO_CVSD_PACK_LEN_8K_V 0x1F
#define I2S_ESCO_CVSD_PACK_LEN_8K_S 3
/* I2S_ESCO_CVSD_DEC_PACK_ERR : R/W ;bitpos:[2] ;default: 1'b0 ; */
/*description: */
#define I2S_ESCO_CVSD_DEC_PACK_ERR (BIT(2))
#define I2S_ESCO_CVSD_DEC_PACK_ERR_M (BIT(2))
#define I2S_ESCO_CVSD_DEC_PACK_ERR_V 0x1
#define I2S_ESCO_CVSD_DEC_PACK_ERR_S 2
/* I2S_ESCO_CHAN_MOD : R/W ;bitpos:[1] ;default: 1'd0 ; */
/*description: */
#define I2S_ESCO_CHAN_MOD (BIT(1))
#define I2S_ESCO_CHAN_MOD_M (BIT(1))
#define I2S_ESCO_CHAN_MOD_V 0x1
#define I2S_ESCO_CHAN_MOD_S 1
/* I2S_ESCO_EN : R/W ;bitpos:[0] ;default: 1'd0 ; */
/*description: */
#define I2S_ESCO_EN (BIT(0))
#define I2S_ESCO_EN_M (BIT(0))
#define I2S_ESCO_EN_V 0x1
#define I2S_ESCO_EN_S 0
#define I2S_SCO_CONF0_REG(i) (REG_I2S_BASE(i) + 0x009c)
/* I2S_CVSD_ENC_RESET : R/W ;bitpos:[3] ;default: 1'd0 ; */
/*description: */
#define I2S_CVSD_ENC_RESET (BIT(3))
#define I2S_CVSD_ENC_RESET_M (BIT(3))
#define I2S_CVSD_ENC_RESET_V 0x1
#define I2S_CVSD_ENC_RESET_S 3
/* I2S_CVSD_ENC_START : R/W ;bitpos:[2] ;default: 1'd0 ; */
/*description: */
#define I2S_CVSD_ENC_START (BIT(2))
#define I2S_CVSD_ENC_START_M (BIT(2))
#define I2S_CVSD_ENC_START_V 0x1
#define I2S_CVSD_ENC_START_S 2
/* I2S_SCO_NO_I2S_EN : R/W ;bitpos:[1] ;default: 1'd0 ; */
/*description: */
#define I2S_SCO_NO_I2S_EN (BIT(1))
#define I2S_SCO_NO_I2S_EN_M (BIT(1))
#define I2S_SCO_NO_I2S_EN_V 0x1
#define I2S_SCO_NO_I2S_EN_S 1
/* I2S_SCO_WITH_I2S_EN : R/W ;bitpos:[0] ;default: 1'd0 ; */
/*description: */
#define I2S_SCO_WITH_I2S_EN (BIT(0))
#define I2S_SCO_WITH_I2S_EN_M (BIT(0))
#define I2S_SCO_WITH_I2S_EN_V 0x1
#define I2S_SCO_WITH_I2S_EN_S 0
#define I2S_CONF1_REG(i) (REG_I2S_BASE(i) + 0x00a0)
/* I2S_TX_ZEROS_RM_EN : R/W ;bitpos:[9] ;default: 1'd0 ; */
/*description: */
#define I2S_TX_ZEROS_RM_EN (BIT(9))
#define I2S_TX_ZEROS_RM_EN_M (BIT(9))
#define I2S_TX_ZEROS_RM_EN_V 0x1
#define I2S_TX_ZEROS_RM_EN_S 9
/* I2S_TX_STOP_EN : R/W ;bitpos:[8] ;default: 1'd0 ; */
/*description: */
#define I2S_TX_STOP_EN (BIT(8))
#define I2S_TX_STOP_EN_M (BIT(8))
#define I2S_TX_STOP_EN_V 0x1
#define I2S_TX_STOP_EN_S 8
/* I2S_RX_PCM_BYPASS : R/W ;bitpos:[7] ;default: 1'h1 ; */
/*description: */
#define I2S_RX_PCM_BYPASS (BIT(7))
#define I2S_RX_PCM_BYPASS_M (BIT(7))
#define I2S_RX_PCM_BYPASS_V 0x1
#define I2S_RX_PCM_BYPASS_S 7
/* I2S_RX_PCM_CONF : R/W ;bitpos:[6:4] ;default: 3'h0 ; */
/*description: */
#define I2S_RX_PCM_CONF 0x00000007
#define I2S_RX_PCM_CONF_M ((I2S_RX_PCM_CONF_V)<<(I2S_RX_PCM_CONF_S))
#define I2S_RX_PCM_CONF_V 0x7
#define I2S_RX_PCM_CONF_S 4
/* I2S_TX_PCM_BYPASS : R/W ;bitpos:[3] ;default: 1'h1 ; */
/*description: */
#define I2S_TX_PCM_BYPASS (BIT(3))
#define I2S_TX_PCM_BYPASS_M (BIT(3))
#define I2S_TX_PCM_BYPASS_V 0x1
#define I2S_TX_PCM_BYPASS_S 3
/* I2S_TX_PCM_CONF : R/W ;bitpos:[2:0] ;default: 3'h1 ; */
/*description: */
#define I2S_TX_PCM_CONF 0x00000007
#define I2S_TX_PCM_CONF_M ((I2S_TX_PCM_CONF_V)<<(I2S_TX_PCM_CONF_S))
#define I2S_TX_PCM_CONF_V 0x7
#define I2S_TX_PCM_CONF_S 0
#define I2S_PD_CONF_REG(i) (REG_I2S_BASE(i) + 0x00a4)
/* I2S_PLC_MEM_FORCE_PU : R/W ;bitpos:[3] ;default: 1'h1 ; */
/*description: */
#define I2S_PLC_MEM_FORCE_PU (BIT(3))
#define I2S_PLC_MEM_FORCE_PU_M (BIT(3))
#define I2S_PLC_MEM_FORCE_PU_V 0x1
#define I2S_PLC_MEM_FORCE_PU_S 3
/* I2S_PLC_MEM_FORCE_PD : R/W ;bitpos:[2] ;default: 1'h0 ; */
/*description: */
#define I2S_PLC_MEM_FORCE_PD (BIT(2))
#define I2S_PLC_MEM_FORCE_PD_M (BIT(2))
#define I2S_PLC_MEM_FORCE_PD_V 0x1
#define I2S_PLC_MEM_FORCE_PD_S 2
/* I2S_FIFO_FORCE_PU : R/W ;bitpos:[1] ;default: 1'h1 ; */
/*description: */
#define I2S_FIFO_FORCE_PU (BIT(1))
#define I2S_FIFO_FORCE_PU_M (BIT(1))
#define I2S_FIFO_FORCE_PU_V 0x1
#define I2S_FIFO_FORCE_PU_S 1
/* I2S_FIFO_FORCE_PD : R/W ;bitpos:[0] ;default: 1'h0 ; */
/*description: */
#define I2S_FIFO_FORCE_PD (BIT(0))
#define I2S_FIFO_FORCE_PD_M (BIT(0))
#define I2S_FIFO_FORCE_PD_V 0x1
#define I2S_FIFO_FORCE_PD_S 0
#define I2S_CONF2_REG(i) (REG_I2S_BASE(i) + 0x00a8)
/* I2S_INTER_VALID_EN : R/W ;bitpos:[7] ;default: 1'b0 ; */
/*description: */
#define I2S_INTER_VALID_EN (BIT(7))
#define I2S_INTER_VALID_EN_M (BIT(7))
#define I2S_INTER_VALID_EN_V 0x1
#define I2S_INTER_VALID_EN_S 7
/* I2S_EXT_ADC_START_EN : R/W ;bitpos:[6] ;default: 1'b0 ; */
/*description: */
#define I2S_EXT_ADC_START_EN (BIT(6))
#define I2S_EXT_ADC_START_EN_M (BIT(6))
#define I2S_EXT_ADC_START_EN_V 0x1
#define I2S_EXT_ADC_START_EN_S 6
/* I2S_LCD_EN : R/W ;bitpos:[5] ;default: 1'b0 ; */
/*description: */
#define I2S_LCD_EN (BIT(5))
#define I2S_LCD_EN_M (BIT(5))
#define I2S_LCD_EN_V 0x1
#define I2S_LCD_EN_S 5
/* I2S_DATA_ENABLE : R/W ;bitpos:[4] ;default: 1'h0 ; */
/*description: */
#define I2S_DATA_ENABLE (BIT(4))
#define I2S_DATA_ENABLE_M (BIT(4))
#define I2S_DATA_ENABLE_V 0x1
#define I2S_DATA_ENABLE_S 4
/* I2S_DATA_ENABLE_TEST_EN : R/W ;bitpos:[3] ;default: 1'h0 ; */
/*description: */
#define I2S_DATA_ENABLE_TEST_EN (BIT(3))
#define I2S_DATA_ENABLE_TEST_EN_M (BIT(3))
#define I2S_DATA_ENABLE_TEST_EN_V 0x1
#define I2S_DATA_ENABLE_TEST_EN_S 3
/* I2S_LCD_TX_SDX2_EN : R/W ;bitpos:[2] ;default: 1'h0 ; */
/*description: */
#define I2S_LCD_TX_SDX2_EN (BIT(2))
#define I2S_LCD_TX_SDX2_EN_M (BIT(2))
#define I2S_LCD_TX_SDX2_EN_V 0x1
#define I2S_LCD_TX_SDX2_EN_S 2
/* I2S_LCD_TX_WRX2_EN : R/W ;bitpos:[1] ;default: 1'h0 ; */
/*description: */
#define I2S_LCD_TX_WRX2_EN (BIT(1))
#define I2S_LCD_TX_WRX2_EN_M (BIT(1))
#define I2S_LCD_TX_WRX2_EN_V 0x1
#define I2S_LCD_TX_WRX2_EN_S 1
/* I2S_CAMERA_EN : R/W ;bitpos:[0] ;default: 1'h0 ; */
/*description: */
#define I2S_CAMERA_EN (BIT(0))
#define I2S_CAMERA_EN_M (BIT(0))
#define I2S_CAMERA_EN_V 0x1
#define I2S_CAMERA_EN_S 0
#define I2S_CLKM_CONF_REG(i) (REG_I2S_BASE(i) + 0x00ac)
/* I2S_CLKA_ENA : R/W ;bitpos:[21] ;default: 1'b0 ; */
/*description: */
#define I2S_CLKA_ENA (BIT(21))
#define I2S_CLKA_ENA_M (BIT(21))
#define I2S_CLKA_ENA_V 0x1
#define I2S_CLKA_ENA_S 21
/* I2S_CLK_EN : R/W ;bitpos:[20] ;default: 1'b0 ; */
/*description: */
#define I2S_CLK_EN (BIT(20))
#define I2S_CLK_EN_M (BIT(20))
#define I2S_CLK_EN_V 0x1
#define I2S_CLK_EN_S 20
/* I2S_CLKM_DIV_A : R/W ;bitpos:[19:14] ;default: 6'h0 ; */
/*description: */
#define I2S_CLKM_DIV_A 0x0000003F
#define I2S_CLKM_DIV_A_M ((I2S_CLKM_DIV_A_V)<<(I2S_CLKM_DIV_A_S))
#define I2S_CLKM_DIV_A_V 0x3F
#define I2S_CLKM_DIV_A_S 14
/* I2S_CLKM_DIV_B : R/W ;bitpos:[13:8] ;default: 6'h0 ; */
/*description: */
#define I2S_CLKM_DIV_B 0x0000003F
#define I2S_CLKM_DIV_B_M ((I2S_CLKM_DIV_B_V)<<(I2S_CLKM_DIV_B_S))
#define I2S_CLKM_DIV_B_V 0x3F
#define I2S_CLKM_DIV_B_S 8
/* I2S_CLKM_DIV_NUM : R/W ;bitpos:[7:0] ;default: 8'd4 ; */
/*description: */
#define I2S_CLKM_DIV_NUM 0x000000FF
#define I2S_CLKM_DIV_NUM_M ((I2S_CLKM_DIV_NUM_V)<<(I2S_CLKM_DIV_NUM_S))
#define I2S_CLKM_DIV_NUM_V 0xFF
#define I2S_CLKM_DIV_NUM_S 0
#define I2S_SAMPLE_RATE_CONF_REG(i) (REG_I2S_BASE(i) + 0x00b0)
/* I2S_RX_BITS_MOD : R/W ;bitpos:[23:18] ;default: 6'd16 ; */
/*description: */
#define I2S_RX_BITS_MOD 0x0000003F
#define I2S_RX_BITS_MOD_M ((I2S_RX_BITS_MOD_V)<<(I2S_RX_BITS_MOD_S))
#define I2S_RX_BITS_MOD_V 0x3F
#define I2S_RX_BITS_MOD_S 18
/* I2S_TX_BITS_MOD : R/W ;bitpos:[17:12] ;default: 6'd16 ; */
/*description: */
#define I2S_TX_BITS_MOD 0x0000003F
#define I2S_TX_BITS_MOD_M ((I2S_TX_BITS_MOD_V)<<(I2S_TX_BITS_MOD_S))
#define I2S_TX_BITS_MOD_V 0x3F
#define I2S_TX_BITS_MOD_S 12
/* I2S_RX_BCK_DIV_NUM : R/W ;bitpos:[11:6] ;default: 6'd6 ; */
/*description: */
#define I2S_RX_BCK_DIV_NUM 0x0000003F
#define I2S_RX_BCK_DIV_NUM_M ((I2S_RX_BCK_DIV_NUM_V)<<(I2S_RX_BCK_DIV_NUM_S))
#define I2S_RX_BCK_DIV_NUM_V 0x3F
#define I2S_RX_BCK_DIV_NUM_S 6
/* I2S_TX_BCK_DIV_NUM : R/W ;bitpos:[5:0] ;default: 6'd6 ; */
/*description: */
#define I2S_TX_BCK_DIV_NUM 0x0000003F
#define I2S_TX_BCK_DIV_NUM_M ((I2S_TX_BCK_DIV_NUM_V)<<(I2S_TX_BCK_DIV_NUM_S))
#define I2S_TX_BCK_DIV_NUM_V 0x3F
#define I2S_TX_BCK_DIV_NUM_S 0
#define I2S_PDM_CONF_REG(i) (REG_I2S_BASE(i) + 0x00b4)
/* I2S_TX_PDM_HP_BYPASS : R/W ;bitpos:[25] ;default: 1'h0 ; */
/*description: */
#define I2S_TX_PDM_HP_BYPASS (BIT(25))
#define I2S_TX_PDM_HP_BYPASS_M (BIT(25))
#define I2S_TX_PDM_HP_BYPASS_V 0x1
#define I2S_TX_PDM_HP_BYPASS_S 25
/* I2S_RX_PDM_SINC_DSR_16_EN : R/W ;bitpos:[24] ;default: 1'h1 ; */
/*description: */
#define I2S_RX_PDM_SINC_DSR_16_EN (BIT(24))
#define I2S_RX_PDM_SINC_DSR_16_EN_M (BIT(24))
#define I2S_RX_PDM_SINC_DSR_16_EN_V 0x1
#define I2S_RX_PDM_SINC_DSR_16_EN_S 24
/* I2S_TX_PDM_SIGMADELTA_IN_SHIFT : R/W ;bitpos:[23:22] ;default: 2'h1 ; */
/*description: */
#define I2S_TX_PDM_SIGMADELTA_IN_SHIFT 0x00000003
#define I2S_TX_PDM_SIGMADELTA_IN_SHIFT_M ((I2S_TX_PDM_SIGMADELTA_IN_SHIFT_V)<<(I2S_TX_PDM_SIGMADELTA_IN_SHIFT_S))
#define I2S_TX_PDM_SIGMADELTA_IN_SHIFT_V 0x3
#define I2S_TX_PDM_SIGMADELTA_IN_SHIFT_S 22
/* I2S_TX_PDM_SINC_IN_SHIFT : R/W ;bitpos:[21:20] ;default: 2'h1 ; */
/*description: */
#define I2S_TX_PDM_SINC_IN_SHIFT 0x00000003
#define I2S_TX_PDM_SINC_IN_SHIFT_M ((I2S_TX_PDM_SINC_IN_SHIFT_V)<<(I2S_TX_PDM_SINC_IN_SHIFT_S))
#define I2S_TX_PDM_SINC_IN_SHIFT_V 0x3
#define I2S_TX_PDM_SINC_IN_SHIFT_S 20
/* I2S_TX_PDM_LP_IN_SHIFT : R/W ;bitpos:[19:18] ;default: 2'h1 ; */
/*description: */
#define I2S_TX_PDM_LP_IN_SHIFT 0x00000003
#define I2S_TX_PDM_LP_IN_SHIFT_M ((I2S_TX_PDM_LP_IN_SHIFT_V)<<(I2S_TX_PDM_LP_IN_SHIFT_S))
#define I2S_TX_PDM_LP_IN_SHIFT_V 0x3
#define I2S_TX_PDM_LP_IN_SHIFT_S 18
/* I2S_TX_PDM_HP_IN_SHIFT : R/W ;bitpos:[17:16] ;default: 2'h1 ; */
/*description: */
#define I2S_TX_PDM_HP_IN_SHIFT 0x00000003
#define I2S_TX_PDM_HP_IN_SHIFT_M ((I2S_TX_PDM_HP_IN_SHIFT_V)<<(I2S_TX_PDM_HP_IN_SHIFT_S))
#define I2S_TX_PDM_HP_IN_SHIFT_V 0x3
#define I2S_TX_PDM_HP_IN_SHIFT_S 16
/* I2S_TX_PDM_PRESCALE : R/W ;bitpos:[15:8] ;default: 8'h0 ; */
/*description: */
#define I2S_TX_PDM_PRESCALE 0x000000FF
#define I2S_TX_PDM_PRESCALE_M ((I2S_TX_PDM_PRESCALE_V)<<(I2S_TX_PDM_PRESCALE_S))
#define I2S_TX_PDM_PRESCALE_V 0xFF
#define I2S_TX_PDM_PRESCALE_S 8
/* I2S_TX_PDM_SINC_OSR2 : R/W ;bitpos:[7:4] ;default: 4'h2 ; */
/*description: */
#define I2S_TX_PDM_SINC_OSR2 0x0000000F
#define I2S_TX_PDM_SINC_OSR2_M ((I2S_TX_PDM_SINC_OSR2_V)<<(I2S_TX_PDM_SINC_OSR2_S))
#define I2S_TX_PDM_SINC_OSR2_V 0xF
#define I2S_TX_PDM_SINC_OSR2_S 4
/* I2S_PDM2PCM_CONV_EN : R/W ;bitpos:[3] ;default: 1'h0 ; */
/*description: */
#define I2S_PDM2PCM_CONV_EN (BIT(3))
#define I2S_PDM2PCM_CONV_EN_M (BIT(3))
#define I2S_PDM2PCM_CONV_EN_V 0x1
#define I2S_PDM2PCM_CONV_EN_S 3
/* I2S_PCM2PDM_CONV_EN : R/W ;bitpos:[2] ;default: 1'h0 ; */
/*description: */
#define I2S_PCM2PDM_CONV_EN (BIT(2))
#define I2S_PCM2PDM_CONV_EN_M (BIT(2))
#define I2S_PCM2PDM_CONV_EN_V 0x1
#define I2S_PCM2PDM_CONV_EN_S 2
/* I2S_RX_PDM_EN : R/W ;bitpos:[1] ;default: 1'h0 ; */
/*description: */
#define I2S_RX_PDM_EN (BIT(1))
#define I2S_RX_PDM_EN_M (BIT(1))
#define I2S_RX_PDM_EN_V 0x1
#define I2S_RX_PDM_EN_S 1
/* I2S_TX_PDM_EN : R/W ;bitpos:[0] ;default: 1'h0 ; */
/*description: */
#define I2S_TX_PDM_EN (BIT(0))
#define I2S_TX_PDM_EN_M (BIT(0))
#define I2S_TX_PDM_EN_V 0x1
#define I2S_TX_PDM_EN_S 0
#define I2S_PDM_FREQ_CONF_REG(i) (REG_I2S_BASE(i) + 0x00b8)
/* I2S_TX_PDM_FP : R/W ;bitpos:[19:10] ;default: 10'd960 ; */
/*description: */
#define I2S_TX_PDM_FP 0x000003FF
#define I2S_TX_PDM_FP_M ((I2S_TX_PDM_FP_V)<<(I2S_TX_PDM_FP_S))
#define I2S_TX_PDM_FP_V 0x3FF
#define I2S_TX_PDM_FP_S 10
/* I2S_TX_PDM_FS : R/W ;bitpos:[9:0] ;default: 10'd480 ; */
/*description: */
#define I2S_TX_PDM_FS 0x000003FF
#define I2S_TX_PDM_FS_M ((I2S_TX_PDM_FS_V)<<(I2S_TX_PDM_FS_S))
#define I2S_TX_PDM_FS_V 0x3FF
#define I2S_TX_PDM_FS_S 0
#define I2S_STATE_REG(i) (REG_I2S_BASE(i) + 0x00bc)
/* I2S_RX_FIFO_RESET_BACK : RO ;bitpos:[2] ;default: 1'b1 ; */
/*description: */
#define I2S_RX_FIFO_RESET_BACK (BIT(2))
#define I2S_RX_FIFO_RESET_BACK_M (BIT(2))
#define I2S_RX_FIFO_RESET_BACK_V 0x1
#define I2S_RX_FIFO_RESET_BACK_S 2
/* I2S_TX_FIFO_RESET_BACK : RO ;bitpos:[1] ;default: 1'b1 ; */
/*description: */
#define I2S_TX_FIFO_RESET_BACK (BIT(1))
#define I2S_TX_FIFO_RESET_BACK_M (BIT(1))
#define I2S_TX_FIFO_RESET_BACK_V 0x1
#define I2S_TX_FIFO_RESET_BACK_S 1
/* I2S_TX_IDLE : RO ;bitpos:[0] ;default: 1'b1 ; */
/*description: */
#define I2S_TX_IDLE (BIT(0))
#define I2S_TX_IDLE_M (BIT(0))
#define I2S_TX_IDLE_V 0x1
#define I2S_TX_IDLE_S 0
#define I2S_DATE_REG(i) (REG_I2S_BASE(i) + 0x00fc)
/* I2S_I2SDATE : R/W ;bitpos:[31:0] ;default: 32'h1604201 ; */
/*description: */
#define I2S_I2SDATE 0xFFFFFFFF
#define I2S_I2SDATE_M ((I2S_I2SDATE_V)<<(I2S_I2SDATE_S))
#define I2S_I2SDATE_V 0xFFFFFFFF
#define I2S_I2SDATE_S 0
#endif /*_SOC_I2S_REG_H_ */
|
97e45409b8eeabf70d844128a8bdc6f9cf2ff695
|
8a51a96f61699f0318315ccc89cef39f6866f2b5
|
/src/backend/utils/adt/acl.c
|
27eabb80abcbd0334bbbeedb709610aefd3d4393
|
[
"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
| 142,320
|
c
|
acl.c
|
/*-------------------------------------------------------------------------
*
* acl.c
* Basic access control list data structures manipulation routines.
*
* Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* src/backend/utils/adt/acl.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include <ctype.h>
#include "access/htup_details.h"
#include "catalog/catalog.h"
#include "catalog/namespace.h"
#include "catalog/pg_auth_members.h"
#include "catalog/pg_authid.h"
#include "catalog/pg_class.h"
#include "catalog/pg_database.h"
#include "catalog/pg_foreign_data_wrapper.h"
#include "catalog/pg_foreign_server.h"
#include "catalog/pg_language.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_parameter_acl.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_tablespace.h"
#include "catalog/pg_type.h"
#include "commands/dbcommands.h"
#include "commands/proclang.h"
#include "commands/tablespace.h"
#include "common/hashfn.h"
#include "foreign/foreign.h"
#include "funcapi.h"
#include "lib/qunique.h"
#include "miscadmin.h"
#include "utils/acl.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
#include "utils/guc.h"
#include "utils/inval.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/syscache.h"
#include "utils/varlena.h"
typedef struct
{
const char *name;
AclMode value;
} priv_map;
/*
* We frequently need to test whether a given role is a member of some other
* role. In most of these tests the "given role" is the same, namely the
* active current user. So we can optimize it by keeping cached lists of all
* the roles the "given role" is a member of, directly or indirectly.
*
* Possibly this mechanism should be generalized to allow caching membership
* info for multiple roles?
*
* Each element of cached_roles is an OID list of constituent roles for the
* corresponding element of cached_role (always including the cached_role
* itself). There's a separate cache for each RoleRecurseType, with the
* corresponding semantics.
*/
enum RoleRecurseType
{
ROLERECURSE_MEMBERS = 0, /* recurse unconditionally */
ROLERECURSE_PRIVS = 1, /* recurse through inheritable grants */
ROLERECURSE_SETROLE = 2 /* recurse through grants with set_option */
};
static Oid cached_role[] = {InvalidOid, InvalidOid, InvalidOid};
static List *cached_roles[] = {NIL, NIL, NIL};
static uint32 cached_db_hash;
static const char *getid(const char *s, char *n, Node *escontext);
static void putid(char *p, const char *s);
static Acl *allocacl(int n);
static void check_acl(const Acl *acl);
static const char *aclparse(const char *s, AclItem *aip, Node *escontext);
static bool aclitem_match(const AclItem *a1, const AclItem *a2);
static int aclitemComparator(const void *arg1, const void *arg2);
static void check_circularity(const Acl *old_acl, const AclItem *mod_aip,
Oid ownerId);
static Acl *recursive_revoke(Acl *acl, Oid grantee, AclMode revoke_privs,
Oid ownerId, DropBehavior behavior);
static AclMode convert_any_priv_string(text *priv_type_text,
const priv_map *privileges);
static Oid convert_table_name(text *tablename);
static AclMode convert_table_priv_string(text *priv_type_text);
static AclMode convert_sequence_priv_string(text *priv_type_text);
static AttrNumber convert_column_name(Oid tableoid, text *column);
static AclMode convert_column_priv_string(text *priv_type_text);
static Oid convert_database_name(text *databasename);
static AclMode convert_database_priv_string(text *priv_type_text);
static Oid convert_foreign_data_wrapper_name(text *fdwname);
static AclMode convert_foreign_data_wrapper_priv_string(text *priv_type_text);
static Oid convert_function_name(text *functionname);
static AclMode convert_function_priv_string(text *priv_type_text);
static Oid convert_language_name(text *languagename);
static AclMode convert_language_priv_string(text *priv_type_text);
static Oid convert_schema_name(text *schemaname);
static AclMode convert_schema_priv_string(text *priv_type_text);
static Oid convert_server_name(text *servername);
static AclMode convert_server_priv_string(text *priv_type_text);
static Oid convert_tablespace_name(text *tablespacename);
static AclMode convert_tablespace_priv_string(text *priv_type_text);
static Oid convert_type_name(text *typename);
static AclMode convert_type_priv_string(text *priv_type_text);
static AclMode convert_parameter_priv_string(text *priv_text);
static AclMode convert_role_priv_string(text *priv_type_text);
static AclResult pg_role_aclcheck(Oid role_oid, Oid roleid, AclMode mode);
static void RoleMembershipCacheCallback(Datum arg, int cacheid, uint32 hashvalue);
/*
* getid
* Consumes the first alphanumeric string (identifier) found in string
* 's', ignoring any leading white space. If it finds a double quote
* it returns the word inside the quotes.
*
* RETURNS:
* the string position in 's' that points to the next non-space character
* in 's', after any quotes. Also:
* - loads the identifier into 'n'. (If no identifier is found, 'n'
* contains an empty string.) 'n' must be NAMEDATALEN bytes.
*
* Errors are reported via ereport, unless escontext is an ErrorSaveData node,
* in which case we log the error there and return NULL.
*/
static const char *
getid(const char *s, char *n, Node *escontext)
{
int len = 0;
bool in_quotes = false;
Assert(s && n);
while (isspace((unsigned char) *s))
s++;
/* This code had better match what putid() does, below */
for (;
*s != '\0' &&
(isalnum((unsigned char) *s) ||
*s == '_' ||
*s == '"' ||
in_quotes);
s++)
{
if (*s == '"')
{
/* safe to look at next char (could be '\0' though) */
if (*(s + 1) != '"')
{
in_quotes = !in_quotes;
continue;
}
/* it's an escaped double quote; skip the escaping char */
s++;
}
/* Add the character to the string */
if (len >= NAMEDATALEN - 1)
ereturn(escontext, NULL,
(errcode(ERRCODE_NAME_TOO_LONG),
errmsg("identifier too long"),
errdetail("Identifier must be less than %d characters.",
NAMEDATALEN)));
n[len++] = *s;
}
n[len] = '\0';
while (isspace((unsigned char) *s))
s++;
return s;
}
/*
* Write a role name at *p, adding double quotes if needed.
* There must be at least (2*NAMEDATALEN)+2 bytes available at *p.
* This needs to be kept in sync with dequoteAclUserName in pg_dump/dumputils.c
*/
static void
putid(char *p, const char *s)
{
const char *src;
bool safe = true;
for (src = s; *src; src++)
{
/* This test had better match what getid() does, above */
if (!isalnum((unsigned char) *src) && *src != '_')
{
safe = false;
break;
}
}
if (!safe)
*p++ = '"';
for (src = s; *src; src++)
{
/* A double quote character in a username is encoded as "" */
if (*src == '"')
*p++ = '"';
*p++ = *src;
}
if (!safe)
*p++ = '"';
*p = '\0';
}
/*
* aclparse
* Consumes and parses an ACL specification of the form:
* [group|user] [A-Za-z0-9]*=[rwaR]*
* from string 's', ignoring any leading white space or white space
* between the optional id type keyword (group|user) and the actual
* ACL specification.
*
* The group|user decoration is unnecessary in the roles world,
* but we still accept it for backward compatibility.
*
* This routine is called by the parser as well as aclitemin(), hence
* the added generality.
*
* RETURNS:
* the string position in 's' immediately following the ACL
* specification. Also:
* - loads the structure pointed to by 'aip' with the appropriate
* UID/GID, id type identifier and mode type values.
*
* Errors are reported via ereport, unless escontext is an ErrorSaveData node,
* in which case we log the error there and return NULL.
*/
static const char *
aclparse(const char *s, AclItem *aip, Node *escontext)
{
AclMode privs,
goption,
read;
char name[NAMEDATALEN];
char name2[NAMEDATALEN];
Assert(s && aip);
s = getid(s, name, escontext);
if (s == NULL)
return NULL;
if (*s != '=')
{
/* we just read a keyword, not a name */
if (strcmp(name, "group") != 0 && strcmp(name, "user") != 0)
ereturn(escontext, NULL,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("unrecognized key word: \"%s\"", name),
errhint("ACL key word must be \"group\" or \"user\".")));
/* move s to the name beyond the keyword */
s = getid(s, name, escontext);
if (s == NULL)
return NULL;
if (name[0] == '\0')
ereturn(escontext, NULL,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("missing name"),
errhint("A name must follow the \"group\" or \"user\" key word.")));
}
if (*s != '=')
ereturn(escontext, NULL,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("missing \"=\" sign")));
privs = goption = ACL_NO_RIGHTS;
for (++s, read = 0; isalpha((unsigned char) *s) || *s == '*'; s++)
{
switch (*s)
{
case '*':
goption |= read;
break;
case ACL_INSERT_CHR:
read = ACL_INSERT;
break;
case ACL_SELECT_CHR:
read = ACL_SELECT;
break;
case ACL_UPDATE_CHR:
read = ACL_UPDATE;
break;
case ACL_DELETE_CHR:
read = ACL_DELETE;
break;
case ACL_TRUNCATE_CHR:
read = ACL_TRUNCATE;
break;
case ACL_REFERENCES_CHR:
read = ACL_REFERENCES;
break;
case ACL_TRIGGER_CHR:
read = ACL_TRIGGER;
break;
case ACL_EXECUTE_CHR:
read = ACL_EXECUTE;
break;
case ACL_USAGE_CHR:
read = ACL_USAGE;
break;
case ACL_CREATE_CHR:
read = ACL_CREATE;
break;
case ACL_CREATE_TEMP_CHR:
read = ACL_CREATE_TEMP;
break;
case ACL_CONNECT_CHR:
read = ACL_CONNECT;
break;
case ACL_SET_CHR:
read = ACL_SET;
break;
case ACL_ALTER_SYSTEM_CHR:
read = ACL_ALTER_SYSTEM;
break;
case 'R': /* ignore old RULE privileges */
read = 0;
break;
default:
ereturn(escontext, NULL,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("invalid mode character: must be one of \"%s\"",
ACL_ALL_RIGHTS_STR)));
}
privs |= read;
}
if (name[0] == '\0')
aip->ai_grantee = ACL_ID_PUBLIC;
else
{
aip->ai_grantee = get_role_oid(name, true);
if (!OidIsValid(aip->ai_grantee))
ereturn(escontext, NULL,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("role \"%s\" does not exist", name)));
}
/*
* XXX Allow a degree of backward compatibility by defaulting the grantor
* to the superuser.
*/
if (*s == '/')
{
s = getid(s + 1, name2, escontext);
if (s == NULL)
return NULL;
if (name2[0] == '\0')
ereturn(escontext, NULL,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("a name must follow the \"/\" sign")));
aip->ai_grantor = get_role_oid(name2, true);
if (!OidIsValid(aip->ai_grantor))
ereturn(escontext, NULL,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("role \"%s\" does not exist", name2)));
}
else
{
aip->ai_grantor = BOOTSTRAP_SUPERUSERID;
ereport(WARNING,
(errcode(ERRCODE_INVALID_GRANTOR),
errmsg("defaulting grantor to user ID %u",
BOOTSTRAP_SUPERUSERID)));
}
ACLITEM_SET_PRIVS_GOPTIONS(*aip, privs, goption);
return s;
}
/*
* allocacl
* Allocates storage for a new Acl with 'n' entries.
*
* RETURNS:
* the new Acl
*/
static Acl *
allocacl(int n)
{
Acl *new_acl;
Size size;
if (n < 0)
elog(ERROR, "invalid size: %d", n);
size = ACL_N_SIZE(n);
new_acl = (Acl *) palloc0(size);
SET_VARSIZE(new_acl, size);
new_acl->ndim = 1;
new_acl->dataoffset = 0; /* we never put in any nulls */
new_acl->elemtype = ACLITEMOID;
ARR_LBOUND(new_acl)[0] = 1;
ARR_DIMS(new_acl)[0] = n;
return new_acl;
}
/*
* Create a zero-entry ACL
*/
Acl *
make_empty_acl(void)
{
return allocacl(0);
}
/*
* Copy an ACL
*/
Acl *
aclcopy(const Acl *orig_acl)
{
Acl *result_acl;
result_acl = allocacl(ACL_NUM(orig_acl));
memcpy(ACL_DAT(result_acl),
ACL_DAT(orig_acl),
ACL_NUM(orig_acl) * sizeof(AclItem));
return result_acl;
}
/*
* Concatenate two ACLs
*
* This is a bit cheesy, since we may produce an ACL with redundant entries.
* Be careful what the result is used for!
*/
Acl *
aclconcat(const Acl *left_acl, const Acl *right_acl)
{
Acl *result_acl;
result_acl = allocacl(ACL_NUM(left_acl) + ACL_NUM(right_acl));
memcpy(ACL_DAT(result_acl),
ACL_DAT(left_acl),
ACL_NUM(left_acl) * sizeof(AclItem));
memcpy(ACL_DAT(result_acl) + ACL_NUM(left_acl),
ACL_DAT(right_acl),
ACL_NUM(right_acl) * sizeof(AclItem));
return result_acl;
}
/*
* Merge two ACLs
*
* This produces a properly merged ACL with no redundant entries.
* Returns NULL on NULL input.
*/
Acl *
aclmerge(const Acl *left_acl, const Acl *right_acl, Oid ownerId)
{
Acl *result_acl;
AclItem *aip;
int i,
num;
/* Check for cases where one or both are empty/null */
if (left_acl == NULL || ACL_NUM(left_acl) == 0)
{
if (right_acl == NULL || ACL_NUM(right_acl) == 0)
return NULL;
else
return aclcopy(right_acl);
}
else
{
if (right_acl == NULL || ACL_NUM(right_acl) == 0)
return aclcopy(left_acl);
}
/* Merge them the hard way, one item at a time */
result_acl = aclcopy(left_acl);
aip = ACL_DAT(right_acl);
num = ACL_NUM(right_acl);
for (i = 0; i < num; i++, aip++)
{
Acl *tmp_acl;
tmp_acl = aclupdate(result_acl, aip, ACL_MODECHG_ADD,
ownerId, DROP_RESTRICT);
pfree(result_acl);
result_acl = tmp_acl;
}
return result_acl;
}
/*
* Sort the items in an ACL (into an arbitrary but consistent order)
*/
void
aclitemsort(Acl *acl)
{
if (acl != NULL && ACL_NUM(acl) > 1)
qsort(ACL_DAT(acl), ACL_NUM(acl), sizeof(AclItem), aclitemComparator);
}
/*
* Check if two ACLs are exactly equal
*
* This will not detect equality if the two arrays contain the same items
* in different orders. To handle that case, sort both inputs first,
* using aclitemsort().
*/
bool
aclequal(const Acl *left_acl, const Acl *right_acl)
{
/* Check for cases where one or both are empty/null */
if (left_acl == NULL || ACL_NUM(left_acl) == 0)
{
if (right_acl == NULL || ACL_NUM(right_acl) == 0)
return true;
else
return false;
}
else
{
if (right_acl == NULL || ACL_NUM(right_acl) == 0)
return false;
}
if (ACL_NUM(left_acl) != ACL_NUM(right_acl))
return false;
if (memcmp(ACL_DAT(left_acl),
ACL_DAT(right_acl),
ACL_NUM(left_acl) * sizeof(AclItem)) == 0)
return true;
return false;
}
/*
* Verify that an ACL array is acceptable (one-dimensional and has no nulls)
*/
static void
check_acl(const Acl *acl)
{
if (ARR_ELEMTYPE(acl) != ACLITEMOID)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("ACL array contains wrong data type")));
if (ARR_NDIM(acl) != 1)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("ACL arrays must be one-dimensional")));
if (ARR_HASNULL(acl))
ereport(ERROR,
(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
errmsg("ACL arrays must not contain null values")));
}
/*
* aclitemin
* Allocates storage for, and fills in, a new AclItem given a string
* 's' that contains an ACL specification. See aclparse for details.
*
* RETURNS:
* the new AclItem
*/
Datum
aclitemin(PG_FUNCTION_ARGS)
{
const char *s = PG_GETARG_CSTRING(0);
Node *escontext = fcinfo->context;
AclItem *aip;
aip = (AclItem *) palloc(sizeof(AclItem));
s = aclparse(s, aip, escontext);
if (s == NULL)
PG_RETURN_NULL();
while (isspace((unsigned char) *s))
++s;
if (*s)
ereturn(escontext, (Datum) 0,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("extra garbage at the end of the ACL specification")));
PG_RETURN_ACLITEM_P(aip);
}
/*
* aclitemout
* Allocates storage for, and fills in, a new null-delimited string
* containing a formatted ACL specification. See aclparse for details.
*
* RETURNS:
* the new string
*/
Datum
aclitemout(PG_FUNCTION_ARGS)
{
AclItem *aip = PG_GETARG_ACLITEM_P(0);
char *p;
char *out;
HeapTuple htup;
unsigned i;
out = palloc(strlen("=/") +
2 * N_ACL_RIGHTS +
2 * (2 * NAMEDATALEN + 2) +
1);
p = out;
*p = '\0';
if (aip->ai_grantee != ACL_ID_PUBLIC)
{
htup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(aip->ai_grantee));
if (HeapTupleIsValid(htup))
{
putid(p, NameStr(((Form_pg_authid) GETSTRUCT(htup))->rolname));
ReleaseSysCache(htup);
}
else
{
/* Generate numeric OID if we don't find an entry */
sprintf(p, "%u", aip->ai_grantee);
}
}
while (*p)
++p;
*p++ = '=';
for (i = 0; i < N_ACL_RIGHTS; ++i)
{
if (ACLITEM_GET_PRIVS(*aip) & (UINT64CONST(1) << i))
*p++ = ACL_ALL_RIGHTS_STR[i];
if (ACLITEM_GET_GOPTIONS(*aip) & (UINT64CONST(1) << i))
*p++ = '*';
}
*p++ = '/';
*p = '\0';
htup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(aip->ai_grantor));
if (HeapTupleIsValid(htup))
{
putid(p, NameStr(((Form_pg_authid) GETSTRUCT(htup))->rolname));
ReleaseSysCache(htup);
}
else
{
/* Generate numeric OID if we don't find an entry */
sprintf(p, "%u", aip->ai_grantor);
}
PG_RETURN_CSTRING(out);
}
/*
* aclitem_match
* Two AclItems are considered to match iff they have the same
* grantee and grantor; the privileges are ignored.
*/
static bool
aclitem_match(const AclItem *a1, const AclItem *a2)
{
return a1->ai_grantee == a2->ai_grantee &&
a1->ai_grantor == a2->ai_grantor;
}
/*
* aclitemComparator
* qsort comparison function for AclItems
*/
static int
aclitemComparator(const void *arg1, const void *arg2)
{
const AclItem *a1 = (const AclItem *) arg1;
const AclItem *a2 = (const AclItem *) arg2;
if (a1->ai_grantee > a2->ai_grantee)
return 1;
if (a1->ai_grantee < a2->ai_grantee)
return -1;
if (a1->ai_grantor > a2->ai_grantor)
return 1;
if (a1->ai_grantor < a2->ai_grantor)
return -1;
if (a1->ai_privs > a2->ai_privs)
return 1;
if (a1->ai_privs < a2->ai_privs)
return -1;
return 0;
}
/*
* aclitem equality operator
*/
Datum
aclitem_eq(PG_FUNCTION_ARGS)
{
AclItem *a1 = PG_GETARG_ACLITEM_P(0);
AclItem *a2 = PG_GETARG_ACLITEM_P(1);
bool result;
result = a1->ai_privs == a2->ai_privs &&
a1->ai_grantee == a2->ai_grantee &&
a1->ai_grantor == a2->ai_grantor;
PG_RETURN_BOOL(result);
}
/*
* aclitem hash function
*
* We make aclitems hashable not so much because anyone is likely to hash
* them, as because we want array equality to work on aclitem arrays, and
* with the typcache mechanism we must have a hash or btree opclass.
*/
Datum
hash_aclitem(PG_FUNCTION_ARGS)
{
AclItem *a = PG_GETARG_ACLITEM_P(0);
/* not very bright, but avoids any issue of padding in struct */
PG_RETURN_UINT32((uint32) (a->ai_privs + a->ai_grantee + a->ai_grantor));
}
/*
* 64-bit hash function for aclitem.
*
* Similar to hash_aclitem, but accepts a seed and returns a uint64 value.
*/
Datum
hash_aclitem_extended(PG_FUNCTION_ARGS)
{
AclItem *a = PG_GETARG_ACLITEM_P(0);
uint64 seed = PG_GETARG_INT64(1);
uint32 sum = (uint32) (a->ai_privs + a->ai_grantee + a->ai_grantor);
return (seed == 0) ? UInt64GetDatum(sum) : hash_uint32_extended(sum, seed);
}
/*
* acldefault() --- create an ACL describing default access permissions
*
* Change this routine if you want to alter the default access policy for
* newly-created objects (or any object with a NULL acl entry). When
* you make a change here, don't forget to update the GRANT man page,
* which explains all the default permissions.
*
* Note that these are the hard-wired "defaults" that are used in the
* absence of any pg_default_acl entry.
*/
Acl *
acldefault(ObjectType objtype, Oid ownerId)
{
AclMode world_default;
AclMode owner_default;
int nacl;
Acl *acl;
AclItem *aip;
switch (objtype)
{
case OBJECT_COLUMN:
/* by default, columns have no extra privileges */
world_default = ACL_NO_RIGHTS;
owner_default = ACL_NO_RIGHTS;
break;
case OBJECT_TABLE:
world_default = ACL_NO_RIGHTS;
owner_default = ACL_ALL_RIGHTS_RELATION;
break;
case OBJECT_SEQUENCE:
world_default = ACL_NO_RIGHTS;
owner_default = ACL_ALL_RIGHTS_SEQUENCE;
break;
case OBJECT_DATABASE:
/* for backwards compatibility, grant some rights by default */
world_default = ACL_CREATE_TEMP | ACL_CONNECT;
owner_default = ACL_ALL_RIGHTS_DATABASE;
break;
case OBJECT_FUNCTION:
/* Grant EXECUTE by default, for now */
world_default = ACL_EXECUTE;
owner_default = ACL_ALL_RIGHTS_FUNCTION;
break;
case OBJECT_LANGUAGE:
/* Grant USAGE by default, for now */
world_default = ACL_USAGE;
owner_default = ACL_ALL_RIGHTS_LANGUAGE;
break;
case OBJECT_LARGEOBJECT:
world_default = ACL_NO_RIGHTS;
owner_default = ACL_ALL_RIGHTS_LARGEOBJECT;
break;
case OBJECT_SCHEMA:
world_default = ACL_NO_RIGHTS;
owner_default = ACL_ALL_RIGHTS_SCHEMA;
break;
case OBJECT_TABLESPACE:
world_default = ACL_NO_RIGHTS;
owner_default = ACL_ALL_RIGHTS_TABLESPACE;
break;
case OBJECT_FDW:
world_default = ACL_NO_RIGHTS;
owner_default = ACL_ALL_RIGHTS_FDW;
break;
case OBJECT_FOREIGN_SERVER:
world_default = ACL_NO_RIGHTS;
owner_default = ACL_ALL_RIGHTS_FOREIGN_SERVER;
break;
case OBJECT_DOMAIN:
case OBJECT_TYPE:
world_default = ACL_USAGE;
owner_default = ACL_ALL_RIGHTS_TYPE;
break;
case OBJECT_PARAMETER_ACL:
world_default = ACL_NO_RIGHTS;
owner_default = ACL_ALL_RIGHTS_PARAMETER_ACL;
break;
default:
elog(ERROR, "unrecognized object type: %d", (int) objtype);
world_default = ACL_NO_RIGHTS; /* keep compiler quiet */
owner_default = ACL_NO_RIGHTS;
break;
}
nacl = 0;
if (world_default != ACL_NO_RIGHTS)
nacl++;
if (owner_default != ACL_NO_RIGHTS)
nacl++;
acl = allocacl(nacl);
aip = ACL_DAT(acl);
if (world_default != ACL_NO_RIGHTS)
{
aip->ai_grantee = ACL_ID_PUBLIC;
aip->ai_grantor = ownerId;
ACLITEM_SET_PRIVS_GOPTIONS(*aip, world_default, ACL_NO_RIGHTS);
aip++;
}
/*
* Note that the owner's entry shows all ordinary privileges but no grant
* options. This is because his grant options come "from the system" and
* not from his own efforts. (The SQL spec says that the owner's rights
* come from a "_SYSTEM" authid.) However, we do consider that the
* owner's ordinary privileges are self-granted; this lets him revoke
* them. We implement the owner's grant options without any explicit
* "_SYSTEM"-like ACL entry, by internally special-casing the owner
* wherever we are testing grant options.
*/
if (owner_default != ACL_NO_RIGHTS)
{
aip->ai_grantee = ownerId;
aip->ai_grantor = ownerId;
ACLITEM_SET_PRIVS_GOPTIONS(*aip, owner_default, ACL_NO_RIGHTS);
}
return acl;
}
/*
* SQL-accessible version of acldefault(). Hackish mapping from "char" type to
* OBJECT_* values.
*/
Datum
acldefault_sql(PG_FUNCTION_ARGS)
{
char objtypec = PG_GETARG_CHAR(0);
Oid owner = PG_GETARG_OID(1);
ObjectType objtype = 0;
switch (objtypec)
{
case 'c':
objtype = OBJECT_COLUMN;
break;
case 'r':
objtype = OBJECT_TABLE;
break;
case 's':
objtype = OBJECT_SEQUENCE;
break;
case 'd':
objtype = OBJECT_DATABASE;
break;
case 'f':
objtype = OBJECT_FUNCTION;
break;
case 'l':
objtype = OBJECT_LANGUAGE;
break;
case 'L':
objtype = OBJECT_LARGEOBJECT;
break;
case 'n':
objtype = OBJECT_SCHEMA;
break;
case 'p':
objtype = OBJECT_PARAMETER_ACL;
break;
case 't':
objtype = OBJECT_TABLESPACE;
break;
case 'F':
objtype = OBJECT_FDW;
break;
case 'S':
objtype = OBJECT_FOREIGN_SERVER;
break;
case 'T':
objtype = OBJECT_TYPE;
break;
default:
elog(ERROR, "unrecognized object type abbreviation: %c", objtypec);
}
PG_RETURN_ACL_P(acldefault(objtype, owner));
}
/*
* Update an ACL array to add or remove specified privileges.
*
* old_acl: the input ACL array
* mod_aip: defines the privileges to be added, removed, or substituted
* modechg: ACL_MODECHG_ADD, ACL_MODECHG_DEL, or ACL_MODECHG_EQL
* ownerId: Oid of object owner
* behavior: RESTRICT or CASCADE behavior for recursive removal
*
* ownerid and behavior are only relevant when the update operation specifies
* deletion of grant options.
*
* The result is a modified copy; the input object is not changed.
*
* NB: caller is responsible for having detoasted the input ACL, if needed.
*/
Acl *
aclupdate(const Acl *old_acl, const AclItem *mod_aip,
int modechg, Oid ownerId, DropBehavior behavior)
{
Acl *new_acl = NULL;
AclItem *old_aip,
*new_aip = NULL;
AclMode old_rights,
old_goptions,
new_rights,
new_goptions;
int dst,
num;
/* Caller probably already checked old_acl, but be safe */
check_acl(old_acl);
/* If granting grant options, check for circularity */
if (modechg != ACL_MODECHG_DEL &&
ACLITEM_GET_GOPTIONS(*mod_aip) != ACL_NO_RIGHTS)
check_circularity(old_acl, mod_aip, ownerId);
num = ACL_NUM(old_acl);
old_aip = ACL_DAT(old_acl);
/*
* Search the ACL for an existing entry for this grantee and grantor. If
* one exists, just modify the entry in-place (well, in the same position,
* since we actually return a copy); otherwise, insert the new entry at
* the end.
*/
for (dst = 0; dst < num; ++dst)
{
if (aclitem_match(mod_aip, old_aip + dst))
{
/* found a match, so modify existing item */
new_acl = allocacl(num);
new_aip = ACL_DAT(new_acl);
memcpy(new_acl, old_acl, ACL_SIZE(old_acl));
break;
}
}
if (dst == num)
{
/* need to append a new item */
new_acl = allocacl(num + 1);
new_aip = ACL_DAT(new_acl);
memcpy(new_aip, old_aip, num * sizeof(AclItem));
/* initialize the new entry with no permissions */
new_aip[dst].ai_grantee = mod_aip->ai_grantee;
new_aip[dst].ai_grantor = mod_aip->ai_grantor;
ACLITEM_SET_PRIVS_GOPTIONS(new_aip[dst],
ACL_NO_RIGHTS, ACL_NO_RIGHTS);
num++; /* set num to the size of new_acl */
}
old_rights = ACLITEM_GET_RIGHTS(new_aip[dst]);
old_goptions = ACLITEM_GET_GOPTIONS(new_aip[dst]);
/* apply the specified permissions change */
switch (modechg)
{
case ACL_MODECHG_ADD:
ACLITEM_SET_RIGHTS(new_aip[dst],
old_rights | ACLITEM_GET_RIGHTS(*mod_aip));
break;
case ACL_MODECHG_DEL:
ACLITEM_SET_RIGHTS(new_aip[dst],
old_rights & ~ACLITEM_GET_RIGHTS(*mod_aip));
break;
case ACL_MODECHG_EQL:
ACLITEM_SET_RIGHTS(new_aip[dst],
ACLITEM_GET_RIGHTS(*mod_aip));
break;
}
new_rights = ACLITEM_GET_RIGHTS(new_aip[dst]);
new_goptions = ACLITEM_GET_GOPTIONS(new_aip[dst]);
/*
* If the adjusted entry has no permissions, delete it from the list.
*/
if (new_rights == ACL_NO_RIGHTS)
{
memmove(new_aip + dst,
new_aip + dst + 1,
(num - dst - 1) * sizeof(AclItem));
/* Adjust array size to be 'num - 1' items */
ARR_DIMS(new_acl)[0] = num - 1;
SET_VARSIZE(new_acl, ACL_N_SIZE(num - 1));
}
/*
* Remove abandoned privileges (cascading revoke). Currently we can only
* handle this when the grantee is not PUBLIC.
*/
if ((old_goptions & ~new_goptions) != 0)
{
Assert(mod_aip->ai_grantee != ACL_ID_PUBLIC);
new_acl = recursive_revoke(new_acl, mod_aip->ai_grantee,
(old_goptions & ~new_goptions),
ownerId, behavior);
}
return new_acl;
}
/*
* Update an ACL array to reflect a change of owner to the parent object
*
* old_acl: the input ACL array (must not be NULL)
* oldOwnerId: Oid of the old object owner
* newOwnerId: Oid of the new object owner
*
* The result is a modified copy; the input object is not changed.
*
* NB: caller is responsible for having detoasted the input ACL, if needed.
*/
Acl *
aclnewowner(const Acl *old_acl, Oid oldOwnerId, Oid newOwnerId)
{
Acl *new_acl;
AclItem *new_aip;
AclItem *old_aip;
AclItem *dst_aip;
AclItem *src_aip;
AclItem *targ_aip;
bool newpresent = false;
int dst,
src,
targ,
num;
check_acl(old_acl);
/*
* Make a copy of the given ACL, substituting new owner ID for old
* wherever it appears as either grantor or grantee. Also note if the new
* owner ID is already present.
*/
num = ACL_NUM(old_acl);
old_aip = ACL_DAT(old_acl);
new_acl = allocacl(num);
new_aip = ACL_DAT(new_acl);
memcpy(new_aip, old_aip, num * sizeof(AclItem));
for (dst = 0, dst_aip = new_aip; dst < num; dst++, dst_aip++)
{
if (dst_aip->ai_grantor == oldOwnerId)
dst_aip->ai_grantor = newOwnerId;
else if (dst_aip->ai_grantor == newOwnerId)
newpresent = true;
if (dst_aip->ai_grantee == oldOwnerId)
dst_aip->ai_grantee = newOwnerId;
else if (dst_aip->ai_grantee == newOwnerId)
newpresent = true;
}
/*
* If the old ACL contained any references to the new owner, then we may
* now have generated an ACL containing duplicate entries. Find them and
* merge them so that there are not duplicates. (This is relatively
* expensive since we use a stupid O(N^2) algorithm, but it's unlikely to
* be the normal case.)
*
* To simplify deletion of duplicate entries, we temporarily leave them in
* the array but set their privilege masks to zero; when we reach such an
* entry it's just skipped. (Thus, a side effect of this code will be to
* remove privilege-free entries, should there be any in the input.) dst
* is the next output slot, targ is the currently considered input slot
* (always >= dst), and src scans entries to the right of targ looking for
* duplicates. Once an entry has been emitted to dst it is known
* duplicate-free and need not be considered anymore.
*/
if (newpresent)
{
dst = 0;
for (targ = 0, targ_aip = new_aip; targ < num; targ++, targ_aip++)
{
/* ignore if deleted in an earlier pass */
if (ACLITEM_GET_RIGHTS(*targ_aip) == ACL_NO_RIGHTS)
continue;
/* find and merge any duplicates */
for (src = targ + 1, src_aip = targ_aip + 1; src < num;
src++, src_aip++)
{
if (ACLITEM_GET_RIGHTS(*src_aip) == ACL_NO_RIGHTS)
continue;
if (aclitem_match(targ_aip, src_aip))
{
ACLITEM_SET_RIGHTS(*targ_aip,
ACLITEM_GET_RIGHTS(*targ_aip) |
ACLITEM_GET_RIGHTS(*src_aip));
/* mark the duplicate deleted */
ACLITEM_SET_RIGHTS(*src_aip, ACL_NO_RIGHTS);
}
}
/* and emit to output */
new_aip[dst] = *targ_aip;
dst++;
}
/* Adjust array size to be 'dst' items */
ARR_DIMS(new_acl)[0] = dst;
SET_VARSIZE(new_acl, ACL_N_SIZE(dst));
}
return new_acl;
}
/*
* When granting grant options, we must disallow attempts to set up circular
* chains of grant options. Suppose A (the object owner) grants B some
* privileges with grant option, and B re-grants them to C. If C could
* grant the privileges to B as well, then A would be unable to effectively
* revoke the privileges from B, since recursive_revoke would consider that
* B still has 'em from C.
*
* We check for this by recursively deleting all grant options belonging to
* the target grantee, and then seeing if the would-be grantor still has the
* grant option or not.
*/
static void
check_circularity(const Acl *old_acl, const AclItem *mod_aip,
Oid ownerId)
{
Acl *acl;
AclItem *aip;
int i,
num;
AclMode own_privs;
check_acl(old_acl);
/*
* For now, grant options can only be granted to roles, not PUBLIC.
* Otherwise we'd have to work a bit harder here.
*/
Assert(mod_aip->ai_grantee != ACL_ID_PUBLIC);
/* The owner always has grant options, no need to check */
if (mod_aip->ai_grantor == ownerId)
return;
/* Make a working copy */
acl = allocacl(ACL_NUM(old_acl));
memcpy(acl, old_acl, ACL_SIZE(old_acl));
/* Zap all grant options of target grantee, plus what depends on 'em */
cc_restart:
num = ACL_NUM(acl);
aip = ACL_DAT(acl);
for (i = 0; i < num; i++)
{
if (aip[i].ai_grantee == mod_aip->ai_grantee &&
ACLITEM_GET_GOPTIONS(aip[i]) != ACL_NO_RIGHTS)
{
Acl *new_acl;
/* We'll actually zap ordinary privs too, but no matter */
new_acl = aclupdate(acl, &aip[i], ACL_MODECHG_DEL,
ownerId, DROP_CASCADE);
pfree(acl);
acl = new_acl;
goto cc_restart;
}
}
/* Now we can compute grantor's independently-derived privileges */
own_privs = aclmask(acl,
mod_aip->ai_grantor,
ownerId,
ACL_GRANT_OPTION_FOR(ACLITEM_GET_GOPTIONS(*mod_aip)),
ACLMASK_ALL);
own_privs = ACL_OPTION_TO_PRIVS(own_privs);
if ((ACLITEM_GET_GOPTIONS(*mod_aip) & ~own_privs) != 0)
ereport(ERROR,
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("grant options cannot be granted back to your own grantor")));
pfree(acl);
}
/*
* Ensure that no privilege is "abandoned". A privilege is abandoned
* if the user that granted the privilege loses the grant option. (So
* the chain through which it was granted is broken.) Either the
* abandoned privileges are revoked as well, or an error message is
* printed, depending on the drop behavior option.
*
* acl: the input ACL list
* grantee: the user from whom some grant options have been revoked
* revoke_privs: the grant options being revoked
* ownerId: Oid of object owner
* behavior: RESTRICT or CASCADE behavior for recursive removal
*
* The input Acl object is pfree'd if replaced.
*/
static Acl *
recursive_revoke(Acl *acl,
Oid grantee,
AclMode revoke_privs,
Oid ownerId,
DropBehavior behavior)
{
AclMode still_has;
AclItem *aip;
int i,
num;
check_acl(acl);
/* The owner can never truly lose grant options, so short-circuit */
if (grantee == ownerId)
return acl;
/* The grantee might still have some grant options via another grantor */
still_has = aclmask(acl, grantee, ownerId,
ACL_GRANT_OPTION_FOR(revoke_privs),
ACLMASK_ALL);
revoke_privs &= ~ACL_OPTION_TO_PRIVS(still_has);
if (revoke_privs == ACL_NO_RIGHTS)
return acl;
restart:
num = ACL_NUM(acl);
aip = ACL_DAT(acl);
for (i = 0; i < num; i++)
{
if (aip[i].ai_grantor == grantee
&& (ACLITEM_GET_PRIVS(aip[i]) & revoke_privs) != 0)
{
AclItem mod_acl;
Acl *new_acl;
if (behavior == DROP_RESTRICT)
ereport(ERROR,
(errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
errmsg("dependent privileges exist"),
errhint("Use CASCADE to revoke them too.")));
mod_acl.ai_grantor = grantee;
mod_acl.ai_grantee = aip[i].ai_grantee;
ACLITEM_SET_PRIVS_GOPTIONS(mod_acl,
revoke_privs,
revoke_privs);
new_acl = aclupdate(acl, &mod_acl, ACL_MODECHG_DEL,
ownerId, behavior);
pfree(acl);
acl = new_acl;
goto restart;
}
}
return acl;
}
/*
* aclmask --- compute bitmask of all privileges held by roleid.
*
* When 'how' = ACLMASK_ALL, this simply returns the privilege bits
* held by the given roleid according to the given ACL list, ANDed
* with 'mask'. (The point of passing 'mask' is to let the routine
* exit early if all privileges of interest have been found.)
*
* When 'how' = ACLMASK_ANY, returns as soon as any bit in the mask
* is known true. (This lets us exit soonest in cases where the
* caller is only going to test for zero or nonzero result.)
*
* Usage patterns:
*
* To see if any of a set of privileges are held:
* if (aclmask(acl, roleid, ownerId, privs, ACLMASK_ANY) != 0)
*
* To see if all of a set of privileges are held:
* if (aclmask(acl, roleid, ownerId, privs, ACLMASK_ALL) == privs)
*
* To determine exactly which of a set of privileges are held:
* heldprivs = aclmask(acl, roleid, ownerId, privs, ACLMASK_ALL);
*/
AclMode
aclmask(const Acl *acl, Oid roleid, Oid ownerId,
AclMode mask, AclMaskHow how)
{
AclMode result;
AclMode remaining;
AclItem *aidat;
int i,
num;
/*
* Null ACL should not happen, since caller should have inserted
* appropriate default
*/
if (acl == NULL)
elog(ERROR, "null ACL");
check_acl(acl);
/* Quick exit for mask == 0 */
if (mask == 0)
return 0;
result = 0;
/* Owner always implicitly has all grant options */
if ((mask & ACLITEM_ALL_GOPTION_BITS) &&
has_privs_of_role(roleid, ownerId))
{
result = mask & ACLITEM_ALL_GOPTION_BITS;
if ((how == ACLMASK_ALL) ? (result == mask) : (result != 0))
return result;
}
num = ACL_NUM(acl);
aidat = ACL_DAT(acl);
/*
* Check privileges granted directly to roleid or to public
*/
for (i = 0; i < num; i++)
{
AclItem *aidata = &aidat[i];
if (aidata->ai_grantee == ACL_ID_PUBLIC ||
aidata->ai_grantee == roleid)
{
result |= aidata->ai_privs & mask;
if ((how == ACLMASK_ALL) ? (result == mask) : (result != 0))
return result;
}
}
/*
* Check privileges granted indirectly via role memberships. We do this in
* a separate pass to minimize expensive indirect membership tests. In
* particular, it's worth testing whether a given ACL entry grants any
* privileges still of interest before we perform the has_privs_of_role
* test.
*/
remaining = mask & ~result;
for (i = 0; i < num; i++)
{
AclItem *aidata = &aidat[i];
if (aidata->ai_grantee == ACL_ID_PUBLIC ||
aidata->ai_grantee == roleid)
continue; /* already checked it */
if ((aidata->ai_privs & remaining) &&
has_privs_of_role(roleid, aidata->ai_grantee))
{
result |= aidata->ai_privs & mask;
if ((how == ACLMASK_ALL) ? (result == mask) : (result != 0))
return result;
remaining = mask & ~result;
}
}
return result;
}
/*
* aclmask_direct --- compute bitmask of all privileges held by roleid.
*
* This is exactly like aclmask() except that we consider only privileges
* held *directly* by roleid, not those inherited via role membership.
*/
static AclMode
aclmask_direct(const Acl *acl, Oid roleid, Oid ownerId,
AclMode mask, AclMaskHow how)
{
AclMode result;
AclItem *aidat;
int i,
num;
/*
* Null ACL should not happen, since caller should have inserted
* appropriate default
*/
if (acl == NULL)
elog(ERROR, "null ACL");
check_acl(acl);
/* Quick exit for mask == 0 */
if (mask == 0)
return 0;
result = 0;
/* Owner always implicitly has all grant options */
if ((mask & ACLITEM_ALL_GOPTION_BITS) &&
roleid == ownerId)
{
result = mask & ACLITEM_ALL_GOPTION_BITS;
if ((how == ACLMASK_ALL) ? (result == mask) : (result != 0))
return result;
}
num = ACL_NUM(acl);
aidat = ACL_DAT(acl);
/*
* Check privileges granted directly to roleid (and not to public)
*/
for (i = 0; i < num; i++)
{
AclItem *aidata = &aidat[i];
if (aidata->ai_grantee == roleid)
{
result |= aidata->ai_privs & mask;
if ((how == ACLMASK_ALL) ? (result == mask) : (result != 0))
return result;
}
}
return result;
}
/*
* aclmembers
* Find out all the roleids mentioned in an Acl.
* Note that we do not distinguish grantors from grantees.
*
* *roleids is set to point to a palloc'd array containing distinct OIDs
* in sorted order. The length of the array is the function result.
*/
int
aclmembers(const Acl *acl, Oid **roleids)
{
Oid *list;
const AclItem *acldat;
int i,
j;
if (acl == NULL || ACL_NUM(acl) == 0)
{
*roleids = NULL;
return 0;
}
check_acl(acl);
/* Allocate the worst-case space requirement */
list = palloc(ACL_NUM(acl) * 2 * sizeof(Oid));
acldat = ACL_DAT(acl);
/*
* Walk the ACL collecting mentioned RoleIds.
*/
j = 0;
for (i = 0; i < ACL_NUM(acl); i++)
{
const AclItem *ai = &acldat[i];
if (ai->ai_grantee != ACL_ID_PUBLIC)
list[j++] = ai->ai_grantee;
/* grantor is currently never PUBLIC, but let's check anyway */
if (ai->ai_grantor != ACL_ID_PUBLIC)
list[j++] = ai->ai_grantor;
}
/* Sort the array */
qsort(list, j, sizeof(Oid), oid_cmp);
/*
* We could repalloc the array down to minimum size, but it's hardly worth
* it since it's only transient memory.
*/
*roleids = list;
/* Remove duplicates from the array */
return qunique(list, j, sizeof(Oid), oid_cmp);
}
/*
* aclinsert (exported function)
*/
Datum
aclinsert(PG_FUNCTION_ARGS)
{
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("aclinsert is no longer supported")));
PG_RETURN_NULL(); /* keep compiler quiet */
}
Datum
aclremove(PG_FUNCTION_ARGS)
{
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("aclremove is no longer supported")));
PG_RETURN_NULL(); /* keep compiler quiet */
}
Datum
aclcontains(PG_FUNCTION_ARGS)
{
Acl *acl = PG_GETARG_ACL_P(0);
AclItem *aip = PG_GETARG_ACLITEM_P(1);
AclItem *aidat;
int i,
num;
check_acl(acl);
num = ACL_NUM(acl);
aidat = ACL_DAT(acl);
for (i = 0; i < num; ++i)
{
if (aip->ai_grantee == aidat[i].ai_grantee &&
aip->ai_grantor == aidat[i].ai_grantor &&
(ACLITEM_GET_RIGHTS(*aip) & ACLITEM_GET_RIGHTS(aidat[i])) == ACLITEM_GET_RIGHTS(*aip))
PG_RETURN_BOOL(true);
}
PG_RETURN_BOOL(false);
}
Datum
makeaclitem(PG_FUNCTION_ARGS)
{
Oid grantee = PG_GETARG_OID(0);
Oid grantor = PG_GETARG_OID(1);
text *privtext = PG_GETARG_TEXT_PP(2);
bool goption = PG_GETARG_BOOL(3);
AclItem *result;
AclMode priv;
static const priv_map any_priv_map[] = {
{"SELECT", ACL_SELECT},
{"INSERT", ACL_INSERT},
{"UPDATE", ACL_UPDATE},
{"DELETE", ACL_DELETE},
{"TRUNCATE", ACL_TRUNCATE},
{"REFERENCES", ACL_REFERENCES},
{"TRIGGER", ACL_TRIGGER},
{"EXECUTE", ACL_EXECUTE},
{"USAGE", ACL_USAGE},
{"CREATE", ACL_CREATE},
{"TEMP", ACL_CREATE_TEMP},
{"TEMPORARY", ACL_CREATE_TEMP},
{"CONNECT", ACL_CONNECT},
{"SET", ACL_SET},
{"ALTER SYSTEM", ACL_ALTER_SYSTEM},
{"RULE", 0}, /* ignore old RULE privileges */
{NULL, 0}
};
priv = convert_any_priv_string(privtext, any_priv_map);
result = (AclItem *) palloc(sizeof(AclItem));
result->ai_grantee = grantee;
result->ai_grantor = grantor;
ACLITEM_SET_PRIVS_GOPTIONS(*result, priv,
(goption ? priv : ACL_NO_RIGHTS));
PG_RETURN_ACLITEM_P(result);
}
/*
* convert_any_priv_string: recognize privilege strings for has_foo_privilege
*
* We accept a comma-separated list of case-insensitive privilege names,
* producing a bitmask of the OR'd privilege bits. We are liberal about
* whitespace between items, not so much about whitespace within items.
* The allowed privilege names are given as an array of priv_map structs,
* terminated by one with a NULL name pointer.
*/
static AclMode
convert_any_priv_string(text *priv_type_text,
const priv_map *privileges)
{
AclMode result = 0;
char *priv_type = text_to_cstring(priv_type_text);
char *chunk;
char *next_chunk;
/* We rely on priv_type being a private, modifiable string */
for (chunk = priv_type; chunk; chunk = next_chunk)
{
int chunk_len;
const priv_map *this_priv;
/* Split string at commas */
next_chunk = strchr(chunk, ',');
if (next_chunk)
*next_chunk++ = '\0';
/* Drop leading/trailing whitespace in this chunk */
while (*chunk && isspace((unsigned char) *chunk))
chunk++;
chunk_len = strlen(chunk);
while (chunk_len > 0 && isspace((unsigned char) chunk[chunk_len - 1]))
chunk_len--;
chunk[chunk_len] = '\0';
/* Match to the privileges list */
for (this_priv = privileges; this_priv->name; this_priv++)
{
if (pg_strcasecmp(this_priv->name, chunk) == 0)
{
result |= this_priv->value;
break;
}
}
if (!this_priv->name)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("unrecognized privilege type: \"%s\"", chunk)));
}
pfree(priv_type);
return result;
}
static const char *
convert_aclright_to_string(int aclright)
{
switch (aclright)
{
case ACL_INSERT:
return "INSERT";
case ACL_SELECT:
return "SELECT";
case ACL_UPDATE:
return "UPDATE";
case ACL_DELETE:
return "DELETE";
case ACL_TRUNCATE:
return "TRUNCATE";
case ACL_REFERENCES:
return "REFERENCES";
case ACL_TRIGGER:
return "TRIGGER";
case ACL_EXECUTE:
return "EXECUTE";
case ACL_USAGE:
return "USAGE";
case ACL_CREATE:
return "CREATE";
case ACL_CREATE_TEMP:
return "TEMPORARY";
case ACL_CONNECT:
return "CONNECT";
case ACL_SET:
return "SET";
case ACL_ALTER_SYSTEM:
return "ALTER SYSTEM";
default:
elog(ERROR, "unrecognized aclright: %d", aclright);
return NULL;
}
}
/*----------
* Convert an aclitem[] to a table.
*
* Example:
*
* aclexplode('{=r/joe,foo=a*w/joe}'::aclitem[])
*
* returns the table
*
* {{ OID(joe), 0::OID, 'SELECT', false },
* { OID(joe), OID(foo), 'INSERT', true },
* { OID(joe), OID(foo), 'UPDATE', false }}
*----------
*/
Datum
aclexplode(PG_FUNCTION_ARGS)
{
Acl *acl = PG_GETARG_ACL_P(0);
FuncCallContext *funcctx;
int *idx;
AclItem *aidat;
if (SRF_IS_FIRSTCALL())
{
TupleDesc tupdesc;
MemoryContext oldcontext;
check_acl(acl);
funcctx = SRF_FIRSTCALL_INIT();
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
/*
* build tupdesc for result tuples (matches out parameters in pg_proc
* entry)
*/
tupdesc = CreateTemplateTupleDesc(4);
TupleDescInitEntry(tupdesc, (AttrNumber) 1, "grantor",
OIDOID, -1, 0);
TupleDescInitEntry(tupdesc, (AttrNumber) 2, "grantee",
OIDOID, -1, 0);
TupleDescInitEntry(tupdesc, (AttrNumber) 3, "privilege_type",
TEXTOID, -1, 0);
TupleDescInitEntry(tupdesc, (AttrNumber) 4, "is_grantable",
BOOLOID, -1, 0);
funcctx->tuple_desc = BlessTupleDesc(tupdesc);
/* allocate memory for user context */
idx = (int *) palloc(sizeof(int[2]));
idx[0] = 0; /* ACL array item index */
idx[1] = -1; /* privilege type counter */
funcctx->user_fctx = (void *) idx;
MemoryContextSwitchTo(oldcontext);
}
funcctx = SRF_PERCALL_SETUP();
idx = (int *) funcctx->user_fctx;
aidat = ACL_DAT(acl);
/* need test here in case acl has no items */
while (idx[0] < ACL_NUM(acl))
{
AclItem *aidata;
AclMode priv_bit;
idx[1]++;
if (idx[1] == N_ACL_RIGHTS)
{
idx[1] = 0;
idx[0]++;
if (idx[0] >= ACL_NUM(acl)) /* done */
break;
}
aidata = &aidat[idx[0]];
priv_bit = UINT64CONST(1) << idx[1];
if (ACLITEM_GET_PRIVS(*aidata) & priv_bit)
{
Datum result;
Datum values[4];
bool nulls[4] = {0};
HeapTuple tuple;
values[0] = ObjectIdGetDatum(aidata->ai_grantor);
values[1] = ObjectIdGetDatum(aidata->ai_grantee);
values[2] = CStringGetTextDatum(convert_aclright_to_string(priv_bit));
values[3] = BoolGetDatum((ACLITEM_GET_GOPTIONS(*aidata) & priv_bit) != 0);
tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
result = HeapTupleGetDatum(tuple);
SRF_RETURN_NEXT(funcctx, result);
}
}
SRF_RETURN_DONE(funcctx);
}
/*
* has_table_privilege variants
* These are all named "has_table_privilege" at the SQL level.
* They take various combinations of relation name, relation OID,
* user name, user OID, or implicit user = current_user.
*
* The result is a boolean value: true if user has the indicated
* privilege, false if not. The variants that take a relation OID
* return NULL if the OID doesn't exist (rather than failing, as
* they did before Postgres 8.4).
*/
/*
* has_table_privilege_name_name
* Check user privileges on a table given
* name username, text tablename, and text priv name.
*/
Datum
has_table_privilege_name_name(PG_FUNCTION_ARGS)
{
Name rolename = PG_GETARG_NAME(0);
text *tablename = PG_GETARG_TEXT_PP(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid roleid;
Oid tableoid;
AclMode mode;
AclResult aclresult;
roleid = get_role_oid_or_public(NameStr(*rolename));
tableoid = convert_table_name(tablename);
mode = convert_table_priv_string(priv_type_text);
aclresult = pg_class_aclcheck(tableoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_table_privilege_name
* Check user privileges on a table given
* text tablename and text priv name.
* current_user is assumed
*/
Datum
has_table_privilege_name(PG_FUNCTION_ARGS)
{
text *tablename = PG_GETARG_TEXT_PP(0);
text *priv_type_text = PG_GETARG_TEXT_PP(1);
Oid roleid;
Oid tableoid;
AclMode mode;
AclResult aclresult;
roleid = GetUserId();
tableoid = convert_table_name(tablename);
mode = convert_table_priv_string(priv_type_text);
aclresult = pg_class_aclcheck(tableoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_table_privilege_name_id
* Check user privileges on a table given
* name usename, table oid, and text priv name.
*/
Datum
has_table_privilege_name_id(PG_FUNCTION_ARGS)
{
Name username = PG_GETARG_NAME(0);
Oid tableoid = PG_GETARG_OID(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid roleid;
AclMode mode;
AclResult aclresult;
roleid = get_role_oid_or_public(NameStr(*username));
mode = convert_table_priv_string(priv_type_text);
if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(tableoid)))
PG_RETURN_NULL();
aclresult = pg_class_aclcheck(tableoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_table_privilege_id
* Check user privileges on a table given
* table oid, and text priv name.
* current_user is assumed
*/
Datum
has_table_privilege_id(PG_FUNCTION_ARGS)
{
Oid tableoid = PG_GETARG_OID(0);
text *priv_type_text = PG_GETARG_TEXT_PP(1);
Oid roleid;
AclMode mode;
AclResult aclresult;
roleid = GetUserId();
mode = convert_table_priv_string(priv_type_text);
if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(tableoid)))
PG_RETURN_NULL();
aclresult = pg_class_aclcheck(tableoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_table_privilege_id_name
* Check user privileges on a table given
* roleid, text tablename, and text priv name.
*/
Datum
has_table_privilege_id_name(PG_FUNCTION_ARGS)
{
Oid roleid = PG_GETARG_OID(0);
text *tablename = PG_GETARG_TEXT_PP(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid tableoid;
AclMode mode;
AclResult aclresult;
tableoid = convert_table_name(tablename);
mode = convert_table_priv_string(priv_type_text);
aclresult = pg_class_aclcheck(tableoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_table_privilege_id_id
* Check user privileges on a table given
* roleid, table oid, and text priv name.
*/
Datum
has_table_privilege_id_id(PG_FUNCTION_ARGS)
{
Oid roleid = PG_GETARG_OID(0);
Oid tableoid = PG_GETARG_OID(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
AclMode mode;
AclResult aclresult;
mode = convert_table_priv_string(priv_type_text);
if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(tableoid)))
PG_RETURN_NULL();
aclresult = pg_class_aclcheck(tableoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* Support routines for has_table_privilege family.
*/
/*
* Given a table name expressed as a string, look it up and return Oid
*/
static Oid
convert_table_name(text *tablename)
{
RangeVar *relrv;
relrv = makeRangeVarFromNameList(textToQualifiedNameList(tablename));
/* We might not even have permissions on this relation; don't lock it. */
return RangeVarGetRelid(relrv, NoLock, false);
}
/*
* convert_table_priv_string
* Convert text string to AclMode value.
*/
static AclMode
convert_table_priv_string(text *priv_type_text)
{
static const priv_map table_priv_map[] = {
{"SELECT", ACL_SELECT},
{"SELECT WITH GRANT OPTION", ACL_GRANT_OPTION_FOR(ACL_SELECT)},
{"INSERT", ACL_INSERT},
{"INSERT WITH GRANT OPTION", ACL_GRANT_OPTION_FOR(ACL_INSERT)},
{"UPDATE", ACL_UPDATE},
{"UPDATE WITH GRANT OPTION", ACL_GRANT_OPTION_FOR(ACL_UPDATE)},
{"DELETE", ACL_DELETE},
{"DELETE WITH GRANT OPTION", ACL_GRANT_OPTION_FOR(ACL_DELETE)},
{"TRUNCATE", ACL_TRUNCATE},
{"TRUNCATE WITH GRANT OPTION", ACL_GRANT_OPTION_FOR(ACL_TRUNCATE)},
{"REFERENCES", ACL_REFERENCES},
{"REFERENCES WITH GRANT OPTION", ACL_GRANT_OPTION_FOR(ACL_REFERENCES)},
{"TRIGGER", ACL_TRIGGER},
{"TRIGGER WITH GRANT OPTION", ACL_GRANT_OPTION_FOR(ACL_TRIGGER)},
{"RULE", 0}, /* ignore old RULE privileges */
{"RULE WITH GRANT OPTION", 0},
{NULL, 0}
};
return convert_any_priv_string(priv_type_text, table_priv_map);
}
/*
* has_sequence_privilege variants
* These are all named "has_sequence_privilege" at the SQL level.
* They take various combinations of relation name, relation OID,
* user name, user OID, or implicit user = current_user.
*
* The result is a boolean value: true if user has the indicated
* privilege, false if not. The variants that take a relation OID
* return NULL if the OID doesn't exist.
*/
/*
* has_sequence_privilege_name_name
* Check user privileges on a sequence given
* name username, text sequencename, and text priv name.
*/
Datum
has_sequence_privilege_name_name(PG_FUNCTION_ARGS)
{
Name rolename = PG_GETARG_NAME(0);
text *sequencename = PG_GETARG_TEXT_PP(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid roleid;
Oid sequenceoid;
AclMode mode;
AclResult aclresult;
roleid = get_role_oid_or_public(NameStr(*rolename));
mode = convert_sequence_priv_string(priv_type_text);
sequenceoid = convert_table_name(sequencename);
if (get_rel_relkind(sequenceoid) != RELKIND_SEQUENCE)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is not a sequence",
text_to_cstring(sequencename))));
aclresult = pg_class_aclcheck(sequenceoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_sequence_privilege_name
* Check user privileges on a sequence given
* text sequencename and text priv name.
* current_user is assumed
*/
Datum
has_sequence_privilege_name(PG_FUNCTION_ARGS)
{
text *sequencename = PG_GETARG_TEXT_PP(0);
text *priv_type_text = PG_GETARG_TEXT_PP(1);
Oid roleid;
Oid sequenceoid;
AclMode mode;
AclResult aclresult;
roleid = GetUserId();
mode = convert_sequence_priv_string(priv_type_text);
sequenceoid = convert_table_name(sequencename);
if (get_rel_relkind(sequenceoid) != RELKIND_SEQUENCE)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is not a sequence",
text_to_cstring(sequencename))));
aclresult = pg_class_aclcheck(sequenceoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_sequence_privilege_name_id
* Check user privileges on a sequence given
* name usename, sequence oid, and text priv name.
*/
Datum
has_sequence_privilege_name_id(PG_FUNCTION_ARGS)
{
Name username = PG_GETARG_NAME(0);
Oid sequenceoid = PG_GETARG_OID(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid roleid;
AclMode mode;
AclResult aclresult;
char relkind;
roleid = get_role_oid_or_public(NameStr(*username));
mode = convert_sequence_priv_string(priv_type_text);
relkind = get_rel_relkind(sequenceoid);
if (relkind == '\0')
PG_RETURN_NULL();
else if (relkind != RELKIND_SEQUENCE)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is not a sequence",
get_rel_name(sequenceoid))));
aclresult = pg_class_aclcheck(sequenceoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_sequence_privilege_id
* Check user privileges on a sequence given
* sequence oid, and text priv name.
* current_user is assumed
*/
Datum
has_sequence_privilege_id(PG_FUNCTION_ARGS)
{
Oid sequenceoid = PG_GETARG_OID(0);
text *priv_type_text = PG_GETARG_TEXT_PP(1);
Oid roleid;
AclMode mode;
AclResult aclresult;
char relkind;
roleid = GetUserId();
mode = convert_sequence_priv_string(priv_type_text);
relkind = get_rel_relkind(sequenceoid);
if (relkind == '\0')
PG_RETURN_NULL();
else if (relkind != RELKIND_SEQUENCE)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is not a sequence",
get_rel_name(sequenceoid))));
aclresult = pg_class_aclcheck(sequenceoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_sequence_privilege_id_name
* Check user privileges on a sequence given
* roleid, text sequencename, and text priv name.
*/
Datum
has_sequence_privilege_id_name(PG_FUNCTION_ARGS)
{
Oid roleid = PG_GETARG_OID(0);
text *sequencename = PG_GETARG_TEXT_PP(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid sequenceoid;
AclMode mode;
AclResult aclresult;
mode = convert_sequence_priv_string(priv_type_text);
sequenceoid = convert_table_name(sequencename);
if (get_rel_relkind(sequenceoid) != RELKIND_SEQUENCE)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is not a sequence",
text_to_cstring(sequencename))));
aclresult = pg_class_aclcheck(sequenceoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_sequence_privilege_id_id
* Check user privileges on a sequence given
* roleid, sequence oid, and text priv name.
*/
Datum
has_sequence_privilege_id_id(PG_FUNCTION_ARGS)
{
Oid roleid = PG_GETARG_OID(0);
Oid sequenceoid = PG_GETARG_OID(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
AclMode mode;
AclResult aclresult;
char relkind;
mode = convert_sequence_priv_string(priv_type_text);
relkind = get_rel_relkind(sequenceoid);
if (relkind == '\0')
PG_RETURN_NULL();
else if (relkind != RELKIND_SEQUENCE)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is not a sequence",
get_rel_name(sequenceoid))));
aclresult = pg_class_aclcheck(sequenceoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* convert_sequence_priv_string
* Convert text string to AclMode value.
*/
static AclMode
convert_sequence_priv_string(text *priv_type_text)
{
static const priv_map sequence_priv_map[] = {
{"USAGE", ACL_USAGE},
{"USAGE WITH GRANT OPTION", ACL_GRANT_OPTION_FOR(ACL_USAGE)},
{"SELECT", ACL_SELECT},
{"SELECT WITH GRANT OPTION", ACL_GRANT_OPTION_FOR(ACL_SELECT)},
{"UPDATE", ACL_UPDATE},
{"UPDATE WITH GRANT OPTION", ACL_GRANT_OPTION_FOR(ACL_UPDATE)},
{NULL, 0}
};
return convert_any_priv_string(priv_type_text, sequence_priv_map);
}
/*
* has_any_column_privilege variants
* These are all named "has_any_column_privilege" at the SQL level.
* They take various combinations of relation name, relation OID,
* user name, user OID, or implicit user = current_user.
*
* The result is a boolean value: true if user has the indicated
* privilege for any column of the table, false if not. The variants
* that take a relation OID return NULL if the OID doesn't exist.
*/
/*
* has_any_column_privilege_name_name
* Check user privileges on any column of a table given
* name username, text tablename, and text priv name.
*/
Datum
has_any_column_privilege_name_name(PG_FUNCTION_ARGS)
{
Name rolename = PG_GETARG_NAME(0);
text *tablename = PG_GETARG_TEXT_PP(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid roleid;
Oid tableoid;
AclMode mode;
AclResult aclresult;
roleid = get_role_oid_or_public(NameStr(*rolename));
tableoid = convert_table_name(tablename);
mode = convert_column_priv_string(priv_type_text);
/* First check at table level, then examine each column if needed */
aclresult = pg_class_aclcheck(tableoid, roleid, mode);
if (aclresult != ACLCHECK_OK)
aclresult = pg_attribute_aclcheck_all(tableoid, roleid, mode,
ACLMASK_ANY);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_any_column_privilege_name
* Check user privileges on any column of a table given
* text tablename and text priv name.
* current_user is assumed
*/
Datum
has_any_column_privilege_name(PG_FUNCTION_ARGS)
{
text *tablename = PG_GETARG_TEXT_PP(0);
text *priv_type_text = PG_GETARG_TEXT_PP(1);
Oid roleid;
Oid tableoid;
AclMode mode;
AclResult aclresult;
roleid = GetUserId();
tableoid = convert_table_name(tablename);
mode = convert_column_priv_string(priv_type_text);
/* First check at table level, then examine each column if needed */
aclresult = pg_class_aclcheck(tableoid, roleid, mode);
if (aclresult != ACLCHECK_OK)
aclresult = pg_attribute_aclcheck_all(tableoid, roleid, mode,
ACLMASK_ANY);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_any_column_privilege_name_id
* Check user privileges on any column of a table given
* name usename, table oid, and text priv name.
*/
Datum
has_any_column_privilege_name_id(PG_FUNCTION_ARGS)
{
Name username = PG_GETARG_NAME(0);
Oid tableoid = PG_GETARG_OID(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid roleid;
AclMode mode;
AclResult aclresult;
roleid = get_role_oid_or_public(NameStr(*username));
mode = convert_column_priv_string(priv_type_text);
if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(tableoid)))
PG_RETURN_NULL();
/* First check at table level, then examine each column if needed */
aclresult = pg_class_aclcheck(tableoid, roleid, mode);
if (aclresult != ACLCHECK_OK)
aclresult = pg_attribute_aclcheck_all(tableoid, roleid, mode,
ACLMASK_ANY);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_any_column_privilege_id
* Check user privileges on any column of a table given
* table oid, and text priv name.
* current_user is assumed
*/
Datum
has_any_column_privilege_id(PG_FUNCTION_ARGS)
{
Oid tableoid = PG_GETARG_OID(0);
text *priv_type_text = PG_GETARG_TEXT_PP(1);
Oid roleid;
AclMode mode;
AclResult aclresult;
roleid = GetUserId();
mode = convert_column_priv_string(priv_type_text);
if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(tableoid)))
PG_RETURN_NULL();
/* First check at table level, then examine each column if needed */
aclresult = pg_class_aclcheck(tableoid, roleid, mode);
if (aclresult != ACLCHECK_OK)
aclresult = pg_attribute_aclcheck_all(tableoid, roleid, mode,
ACLMASK_ANY);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_any_column_privilege_id_name
* Check user privileges on any column of a table given
* roleid, text tablename, and text priv name.
*/
Datum
has_any_column_privilege_id_name(PG_FUNCTION_ARGS)
{
Oid roleid = PG_GETARG_OID(0);
text *tablename = PG_GETARG_TEXT_PP(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid tableoid;
AclMode mode;
AclResult aclresult;
tableoid = convert_table_name(tablename);
mode = convert_column_priv_string(priv_type_text);
/* First check at table level, then examine each column if needed */
aclresult = pg_class_aclcheck(tableoid, roleid, mode);
if (aclresult != ACLCHECK_OK)
aclresult = pg_attribute_aclcheck_all(tableoid, roleid, mode,
ACLMASK_ANY);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_any_column_privilege_id_id
* Check user privileges on any column of a table given
* roleid, table oid, and text priv name.
*/
Datum
has_any_column_privilege_id_id(PG_FUNCTION_ARGS)
{
Oid roleid = PG_GETARG_OID(0);
Oid tableoid = PG_GETARG_OID(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
AclMode mode;
AclResult aclresult;
mode = convert_column_priv_string(priv_type_text);
if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(tableoid)))
PG_RETURN_NULL();
/* First check at table level, then examine each column if needed */
aclresult = pg_class_aclcheck(tableoid, roleid, mode);
if (aclresult != ACLCHECK_OK)
aclresult = pg_attribute_aclcheck_all(tableoid, roleid, mode,
ACLMASK_ANY);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_column_privilege variants
* These are all named "has_column_privilege" at the SQL level.
* They take various combinations of relation name, relation OID,
* column name, column attnum, user name, user OID, or
* implicit user = current_user.
*
* The result is a boolean value: true if user has the indicated
* privilege, false if not. The variants that take a relation OID
* return NULL (rather than throwing an error) if that relation OID
* doesn't exist. Likewise, the variants that take an integer attnum
* return NULL (rather than throwing an error) if there is no such
* pg_attribute entry. All variants return NULL if an attisdropped
* column is selected. These rules are meant to avoid unnecessary
* failures in queries that scan pg_attribute.
*/
/*
* column_privilege_check: check column privileges, but don't throw an error
* for dropped column or table
*
* Returns 1 if have the privilege, 0 if not, -1 if dropped column/table.
*/
static int
column_privilege_check(Oid tableoid, AttrNumber attnum,
Oid roleid, AclMode mode)
{
AclResult aclresult;
bool is_missing = false;
/*
* If convert_column_name failed, we can just return -1 immediately.
*/
if (attnum == InvalidAttrNumber)
return -1;
/*
* Check for column-level privileges first. This serves in part as a check
* on whether the column even exists, so we need to do it before checking
* table-level privilege.
*/
aclresult = pg_attribute_aclcheck_ext(tableoid, attnum, roleid,
mode, &is_missing);
if (aclresult == ACLCHECK_OK)
return 1;
else if (is_missing)
return -1;
/* Next check if we have the privilege at the table level */
aclresult = pg_class_aclcheck_ext(tableoid, roleid, mode, &is_missing);
if (aclresult == ACLCHECK_OK)
return 1;
else if (is_missing)
return -1;
else
return 0;
}
/*
* has_column_privilege_name_name_name
* Check user privileges on a column given
* name username, text tablename, text colname, and text priv name.
*/
Datum
has_column_privilege_name_name_name(PG_FUNCTION_ARGS)
{
Name rolename = PG_GETARG_NAME(0);
text *tablename = PG_GETARG_TEXT_PP(1);
text *column = PG_GETARG_TEXT_PP(2);
text *priv_type_text = PG_GETARG_TEXT_PP(3);
Oid roleid;
Oid tableoid;
AttrNumber colattnum;
AclMode mode;
int privresult;
roleid = get_role_oid_or_public(NameStr(*rolename));
tableoid = convert_table_name(tablename);
colattnum = convert_column_name(tableoid, column);
mode = convert_column_priv_string(priv_type_text);
privresult = column_privilege_check(tableoid, colattnum, roleid, mode);
if (privresult < 0)
PG_RETURN_NULL();
PG_RETURN_BOOL(privresult);
}
/*
* has_column_privilege_name_name_attnum
* Check user privileges on a column given
* name username, text tablename, int attnum, and text priv name.
*/
Datum
has_column_privilege_name_name_attnum(PG_FUNCTION_ARGS)
{
Name rolename = PG_GETARG_NAME(0);
text *tablename = PG_GETARG_TEXT_PP(1);
AttrNumber colattnum = PG_GETARG_INT16(2);
text *priv_type_text = PG_GETARG_TEXT_PP(3);
Oid roleid;
Oid tableoid;
AclMode mode;
int privresult;
roleid = get_role_oid_or_public(NameStr(*rolename));
tableoid = convert_table_name(tablename);
mode = convert_column_priv_string(priv_type_text);
privresult = column_privilege_check(tableoid, colattnum, roleid, mode);
if (privresult < 0)
PG_RETURN_NULL();
PG_RETURN_BOOL(privresult);
}
/*
* has_column_privilege_name_id_name
* Check user privileges on a column given
* name username, table oid, text colname, and text priv name.
*/
Datum
has_column_privilege_name_id_name(PG_FUNCTION_ARGS)
{
Name username = PG_GETARG_NAME(0);
Oid tableoid = PG_GETARG_OID(1);
text *column = PG_GETARG_TEXT_PP(2);
text *priv_type_text = PG_GETARG_TEXT_PP(3);
Oid roleid;
AttrNumber colattnum;
AclMode mode;
int privresult;
roleid = get_role_oid_or_public(NameStr(*username));
colattnum = convert_column_name(tableoid, column);
mode = convert_column_priv_string(priv_type_text);
privresult = column_privilege_check(tableoid, colattnum, roleid, mode);
if (privresult < 0)
PG_RETURN_NULL();
PG_RETURN_BOOL(privresult);
}
/*
* has_column_privilege_name_id_attnum
* Check user privileges on a column given
* name username, table oid, int attnum, and text priv name.
*/
Datum
has_column_privilege_name_id_attnum(PG_FUNCTION_ARGS)
{
Name username = PG_GETARG_NAME(0);
Oid tableoid = PG_GETARG_OID(1);
AttrNumber colattnum = PG_GETARG_INT16(2);
text *priv_type_text = PG_GETARG_TEXT_PP(3);
Oid roleid;
AclMode mode;
int privresult;
roleid = get_role_oid_or_public(NameStr(*username));
mode = convert_column_priv_string(priv_type_text);
privresult = column_privilege_check(tableoid, colattnum, roleid, mode);
if (privresult < 0)
PG_RETURN_NULL();
PG_RETURN_BOOL(privresult);
}
/*
* has_column_privilege_id_name_name
* Check user privileges on a column given
* oid roleid, text tablename, text colname, and text priv name.
*/
Datum
has_column_privilege_id_name_name(PG_FUNCTION_ARGS)
{
Oid roleid = PG_GETARG_OID(0);
text *tablename = PG_GETARG_TEXT_PP(1);
text *column = PG_GETARG_TEXT_PP(2);
text *priv_type_text = PG_GETARG_TEXT_PP(3);
Oid tableoid;
AttrNumber colattnum;
AclMode mode;
int privresult;
tableoid = convert_table_name(tablename);
colattnum = convert_column_name(tableoid, column);
mode = convert_column_priv_string(priv_type_text);
privresult = column_privilege_check(tableoid, colattnum, roleid, mode);
if (privresult < 0)
PG_RETURN_NULL();
PG_RETURN_BOOL(privresult);
}
/*
* has_column_privilege_id_name_attnum
* Check user privileges on a column given
* oid roleid, text tablename, int attnum, and text priv name.
*/
Datum
has_column_privilege_id_name_attnum(PG_FUNCTION_ARGS)
{
Oid roleid = PG_GETARG_OID(0);
text *tablename = PG_GETARG_TEXT_PP(1);
AttrNumber colattnum = PG_GETARG_INT16(2);
text *priv_type_text = PG_GETARG_TEXT_PP(3);
Oid tableoid;
AclMode mode;
int privresult;
tableoid = convert_table_name(tablename);
mode = convert_column_priv_string(priv_type_text);
privresult = column_privilege_check(tableoid, colattnum, roleid, mode);
if (privresult < 0)
PG_RETURN_NULL();
PG_RETURN_BOOL(privresult);
}
/*
* has_column_privilege_id_id_name
* Check user privileges on a column given
* oid roleid, table oid, text colname, and text priv name.
*/
Datum
has_column_privilege_id_id_name(PG_FUNCTION_ARGS)
{
Oid roleid = PG_GETARG_OID(0);
Oid tableoid = PG_GETARG_OID(1);
text *column = PG_GETARG_TEXT_PP(2);
text *priv_type_text = PG_GETARG_TEXT_PP(3);
AttrNumber colattnum;
AclMode mode;
int privresult;
colattnum = convert_column_name(tableoid, column);
mode = convert_column_priv_string(priv_type_text);
privresult = column_privilege_check(tableoid, colattnum, roleid, mode);
if (privresult < 0)
PG_RETURN_NULL();
PG_RETURN_BOOL(privresult);
}
/*
* has_column_privilege_id_id_attnum
* Check user privileges on a column given
* oid roleid, table oid, int attnum, and text priv name.
*/
Datum
has_column_privilege_id_id_attnum(PG_FUNCTION_ARGS)
{
Oid roleid = PG_GETARG_OID(0);
Oid tableoid = PG_GETARG_OID(1);
AttrNumber colattnum = PG_GETARG_INT16(2);
text *priv_type_text = PG_GETARG_TEXT_PP(3);
AclMode mode;
int privresult;
mode = convert_column_priv_string(priv_type_text);
privresult = column_privilege_check(tableoid, colattnum, roleid, mode);
if (privresult < 0)
PG_RETURN_NULL();
PG_RETURN_BOOL(privresult);
}
/*
* has_column_privilege_name_name
* Check user privileges on a column given
* text tablename, text colname, and text priv name.
* current_user is assumed
*/
Datum
has_column_privilege_name_name(PG_FUNCTION_ARGS)
{
text *tablename = PG_GETARG_TEXT_PP(0);
text *column = PG_GETARG_TEXT_PP(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid roleid;
Oid tableoid;
AttrNumber colattnum;
AclMode mode;
int privresult;
roleid = GetUserId();
tableoid = convert_table_name(tablename);
colattnum = convert_column_name(tableoid, column);
mode = convert_column_priv_string(priv_type_text);
privresult = column_privilege_check(tableoid, colattnum, roleid, mode);
if (privresult < 0)
PG_RETURN_NULL();
PG_RETURN_BOOL(privresult);
}
/*
* has_column_privilege_name_attnum
* Check user privileges on a column given
* text tablename, int attnum, and text priv name.
* current_user is assumed
*/
Datum
has_column_privilege_name_attnum(PG_FUNCTION_ARGS)
{
text *tablename = PG_GETARG_TEXT_PP(0);
AttrNumber colattnum = PG_GETARG_INT16(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid roleid;
Oid tableoid;
AclMode mode;
int privresult;
roleid = GetUserId();
tableoid = convert_table_name(tablename);
mode = convert_column_priv_string(priv_type_text);
privresult = column_privilege_check(tableoid, colattnum, roleid, mode);
if (privresult < 0)
PG_RETURN_NULL();
PG_RETURN_BOOL(privresult);
}
/*
* has_column_privilege_id_name
* Check user privileges on a column given
* table oid, text colname, and text priv name.
* current_user is assumed
*/
Datum
has_column_privilege_id_name(PG_FUNCTION_ARGS)
{
Oid tableoid = PG_GETARG_OID(0);
text *column = PG_GETARG_TEXT_PP(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid roleid;
AttrNumber colattnum;
AclMode mode;
int privresult;
roleid = GetUserId();
colattnum = convert_column_name(tableoid, column);
mode = convert_column_priv_string(priv_type_text);
privresult = column_privilege_check(tableoid, colattnum, roleid, mode);
if (privresult < 0)
PG_RETURN_NULL();
PG_RETURN_BOOL(privresult);
}
/*
* has_column_privilege_id_attnum
* Check user privileges on a column given
* table oid, int attnum, and text priv name.
* current_user is assumed
*/
Datum
has_column_privilege_id_attnum(PG_FUNCTION_ARGS)
{
Oid tableoid = PG_GETARG_OID(0);
AttrNumber colattnum = PG_GETARG_INT16(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid roleid;
AclMode mode;
int privresult;
roleid = GetUserId();
mode = convert_column_priv_string(priv_type_text);
privresult = column_privilege_check(tableoid, colattnum, roleid, mode);
if (privresult < 0)
PG_RETURN_NULL();
PG_RETURN_BOOL(privresult);
}
/*
* Support routines for has_column_privilege family.
*/
/*
* Given a table OID and a column name expressed as a string, look it up
* and return the column number. Returns InvalidAttrNumber in cases
* where caller should return NULL instead of failing.
*/
static AttrNumber
convert_column_name(Oid tableoid, text *column)
{
char *colname;
HeapTuple attTuple;
AttrNumber attnum;
colname = text_to_cstring(column);
/*
* We don't use get_attnum() here because it will report that dropped
* columns don't exist. We need to treat dropped columns differently from
* nonexistent columns.
*/
attTuple = SearchSysCache2(ATTNAME,
ObjectIdGetDatum(tableoid),
CStringGetDatum(colname));
if (HeapTupleIsValid(attTuple))
{
Form_pg_attribute attributeForm;
attributeForm = (Form_pg_attribute) GETSTRUCT(attTuple);
/* We want to return NULL for dropped columns */
if (attributeForm->attisdropped)
attnum = InvalidAttrNumber;
else
attnum = attributeForm->attnum;
ReleaseSysCache(attTuple);
}
else
{
char *tablename = get_rel_name(tableoid);
/*
* If the table OID is bogus, or it's just been dropped, we'll get
* NULL back. In such cases we want has_column_privilege to return
* NULL too, so just return InvalidAttrNumber.
*/
if (tablename != NULL)
{
/* tableoid exists, colname does not, so throw error */
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_COLUMN),
errmsg("column \"%s\" of relation \"%s\" does not exist",
colname, tablename)));
}
/* tableoid doesn't exist, so act like attisdropped case */
attnum = InvalidAttrNumber;
}
pfree(colname);
return attnum;
}
/*
* convert_column_priv_string
* Convert text string to AclMode value.
*/
static AclMode
convert_column_priv_string(text *priv_type_text)
{
static const priv_map column_priv_map[] = {
{"SELECT", ACL_SELECT},
{"SELECT WITH GRANT OPTION", ACL_GRANT_OPTION_FOR(ACL_SELECT)},
{"INSERT", ACL_INSERT},
{"INSERT WITH GRANT OPTION", ACL_GRANT_OPTION_FOR(ACL_INSERT)},
{"UPDATE", ACL_UPDATE},
{"UPDATE WITH GRANT OPTION", ACL_GRANT_OPTION_FOR(ACL_UPDATE)},
{"REFERENCES", ACL_REFERENCES},
{"REFERENCES WITH GRANT OPTION", ACL_GRANT_OPTION_FOR(ACL_REFERENCES)},
{NULL, 0}
};
return convert_any_priv_string(priv_type_text, column_priv_map);
}
/*
* has_database_privilege variants
* These are all named "has_database_privilege" at the SQL level.
* They take various combinations of database name, database OID,
* user name, user OID, or implicit user = current_user.
*
* The result is a boolean value: true if user has the indicated
* privilege, false if not, or NULL if object doesn't exist.
*/
/*
* has_database_privilege_name_name
* Check user privileges on a database given
* name username, text databasename, and text priv name.
*/
Datum
has_database_privilege_name_name(PG_FUNCTION_ARGS)
{
Name username = PG_GETARG_NAME(0);
text *databasename = PG_GETARG_TEXT_PP(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid roleid;
Oid databaseoid;
AclMode mode;
AclResult aclresult;
roleid = get_role_oid_or_public(NameStr(*username));
databaseoid = convert_database_name(databasename);
mode = convert_database_priv_string(priv_type_text);
aclresult = object_aclcheck(DatabaseRelationId, databaseoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_database_privilege_name
* Check user privileges on a database given
* text databasename and text priv name.
* current_user is assumed
*/
Datum
has_database_privilege_name(PG_FUNCTION_ARGS)
{
text *databasename = PG_GETARG_TEXT_PP(0);
text *priv_type_text = PG_GETARG_TEXT_PP(1);
Oid roleid;
Oid databaseoid;
AclMode mode;
AclResult aclresult;
roleid = GetUserId();
databaseoid = convert_database_name(databasename);
mode = convert_database_priv_string(priv_type_text);
aclresult = object_aclcheck(DatabaseRelationId, databaseoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_database_privilege_name_id
* Check user privileges on a database given
* name usename, database oid, and text priv name.
*/
Datum
has_database_privilege_name_id(PG_FUNCTION_ARGS)
{
Name username = PG_GETARG_NAME(0);
Oid databaseoid = PG_GETARG_OID(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid roleid;
AclMode mode;
AclResult aclresult;
roleid = get_role_oid_or_public(NameStr(*username));
mode = convert_database_priv_string(priv_type_text);
if (!SearchSysCacheExists1(DATABASEOID, ObjectIdGetDatum(databaseoid)))
PG_RETURN_NULL();
aclresult = object_aclcheck(DatabaseRelationId, databaseoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_database_privilege_id
* Check user privileges on a database given
* database oid, and text priv name.
* current_user is assumed
*/
Datum
has_database_privilege_id(PG_FUNCTION_ARGS)
{
Oid databaseoid = PG_GETARG_OID(0);
text *priv_type_text = PG_GETARG_TEXT_PP(1);
Oid roleid;
AclMode mode;
AclResult aclresult;
roleid = GetUserId();
mode = convert_database_priv_string(priv_type_text);
if (!SearchSysCacheExists1(DATABASEOID, ObjectIdGetDatum(databaseoid)))
PG_RETURN_NULL();
aclresult = object_aclcheck(DatabaseRelationId, databaseoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_database_privilege_id_name
* Check user privileges on a database given
* roleid, text databasename, and text priv name.
*/
Datum
has_database_privilege_id_name(PG_FUNCTION_ARGS)
{
Oid roleid = PG_GETARG_OID(0);
text *databasename = PG_GETARG_TEXT_PP(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid databaseoid;
AclMode mode;
AclResult aclresult;
databaseoid = convert_database_name(databasename);
mode = convert_database_priv_string(priv_type_text);
aclresult = object_aclcheck(DatabaseRelationId, databaseoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_database_privilege_id_id
* Check user privileges on a database given
* roleid, database oid, and text priv name.
*/
Datum
has_database_privilege_id_id(PG_FUNCTION_ARGS)
{
Oid roleid = PG_GETARG_OID(0);
Oid databaseoid = PG_GETARG_OID(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
AclMode mode;
AclResult aclresult;
mode = convert_database_priv_string(priv_type_text);
if (!SearchSysCacheExists1(DATABASEOID, ObjectIdGetDatum(databaseoid)))
PG_RETURN_NULL();
aclresult = object_aclcheck(DatabaseRelationId, databaseoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* Support routines for has_database_privilege family.
*/
/*
* Given a database name expressed as a string, look it up and return Oid
*/
static Oid
convert_database_name(text *databasename)
{
char *dbname = text_to_cstring(databasename);
return get_database_oid(dbname, false);
}
/*
* convert_database_priv_string
* Convert text string to AclMode value.
*/
static AclMode
convert_database_priv_string(text *priv_type_text)
{
static const priv_map database_priv_map[] = {
{"CREATE", ACL_CREATE},
{"CREATE WITH GRANT OPTION", ACL_GRANT_OPTION_FOR(ACL_CREATE)},
{"TEMPORARY", ACL_CREATE_TEMP},
{"TEMPORARY WITH GRANT OPTION", ACL_GRANT_OPTION_FOR(ACL_CREATE_TEMP)},
{"TEMP", ACL_CREATE_TEMP},
{"TEMP WITH GRANT OPTION", ACL_GRANT_OPTION_FOR(ACL_CREATE_TEMP)},
{"CONNECT", ACL_CONNECT},
{"CONNECT WITH GRANT OPTION", ACL_GRANT_OPTION_FOR(ACL_CONNECT)},
{NULL, 0}
};
return convert_any_priv_string(priv_type_text, database_priv_map);
}
/*
* has_foreign_data_wrapper_privilege variants
* These are all named "has_foreign_data_wrapper_privilege" at the SQL level.
* They take various combinations of foreign-data wrapper name,
* fdw OID, user name, user OID, or implicit user = current_user.
*
* The result is a boolean value: true if user has the indicated
* privilege, false if not.
*/
/*
* has_foreign_data_wrapper_privilege_name_name
* Check user privileges on a foreign-data wrapper given
* name username, text fdwname, and text priv name.
*/
Datum
has_foreign_data_wrapper_privilege_name_name(PG_FUNCTION_ARGS)
{
Name username = PG_GETARG_NAME(0);
text *fdwname = PG_GETARG_TEXT_PP(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid roleid;
Oid fdwid;
AclMode mode;
AclResult aclresult;
roleid = get_role_oid_or_public(NameStr(*username));
fdwid = convert_foreign_data_wrapper_name(fdwname);
mode = convert_foreign_data_wrapper_priv_string(priv_type_text);
aclresult = object_aclcheck(ForeignDataWrapperRelationId, fdwid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_foreign_data_wrapper_privilege_name
* Check user privileges on a foreign-data wrapper given
* text fdwname and text priv name.
* current_user is assumed
*/
Datum
has_foreign_data_wrapper_privilege_name(PG_FUNCTION_ARGS)
{
text *fdwname = PG_GETARG_TEXT_PP(0);
text *priv_type_text = PG_GETARG_TEXT_PP(1);
Oid roleid;
Oid fdwid;
AclMode mode;
AclResult aclresult;
roleid = GetUserId();
fdwid = convert_foreign_data_wrapper_name(fdwname);
mode = convert_foreign_data_wrapper_priv_string(priv_type_text);
aclresult = object_aclcheck(ForeignDataWrapperRelationId, fdwid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_foreign_data_wrapper_privilege_name_id
* Check user privileges on a foreign-data wrapper given
* name usename, foreign-data wrapper oid, and text priv name.
*/
Datum
has_foreign_data_wrapper_privilege_name_id(PG_FUNCTION_ARGS)
{
Name username = PG_GETARG_NAME(0);
Oid fdwid = PG_GETARG_OID(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid roleid;
AclMode mode;
AclResult aclresult;
roleid = get_role_oid_or_public(NameStr(*username));
mode = convert_foreign_data_wrapper_priv_string(priv_type_text);
if (!SearchSysCacheExists1(FOREIGNDATAWRAPPEROID, ObjectIdGetDatum(fdwid)))
PG_RETURN_NULL();
aclresult = object_aclcheck(ForeignDataWrapperRelationId, fdwid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_foreign_data_wrapper_privilege_id
* Check user privileges on a foreign-data wrapper given
* foreign-data wrapper oid, and text priv name.
* current_user is assumed
*/
Datum
has_foreign_data_wrapper_privilege_id(PG_FUNCTION_ARGS)
{
Oid fdwid = PG_GETARG_OID(0);
text *priv_type_text = PG_GETARG_TEXT_PP(1);
Oid roleid;
AclMode mode;
AclResult aclresult;
roleid = GetUserId();
mode = convert_foreign_data_wrapper_priv_string(priv_type_text);
if (!SearchSysCacheExists1(FOREIGNDATAWRAPPEROID, ObjectIdGetDatum(fdwid)))
PG_RETURN_NULL();
aclresult = object_aclcheck(ForeignDataWrapperRelationId, fdwid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_foreign_data_wrapper_privilege_id_name
* Check user privileges on a foreign-data wrapper given
* roleid, text fdwname, and text priv name.
*/
Datum
has_foreign_data_wrapper_privilege_id_name(PG_FUNCTION_ARGS)
{
Oid roleid = PG_GETARG_OID(0);
text *fdwname = PG_GETARG_TEXT_PP(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid fdwid;
AclMode mode;
AclResult aclresult;
fdwid = convert_foreign_data_wrapper_name(fdwname);
mode = convert_foreign_data_wrapper_priv_string(priv_type_text);
aclresult = object_aclcheck(ForeignDataWrapperRelationId, fdwid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_foreign_data_wrapper_privilege_id_id
* Check user privileges on a foreign-data wrapper given
* roleid, fdw oid, and text priv name.
*/
Datum
has_foreign_data_wrapper_privilege_id_id(PG_FUNCTION_ARGS)
{
Oid roleid = PG_GETARG_OID(0);
Oid fdwid = PG_GETARG_OID(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
AclMode mode;
AclResult aclresult;
mode = convert_foreign_data_wrapper_priv_string(priv_type_text);
if (!SearchSysCacheExists1(FOREIGNDATAWRAPPEROID, ObjectIdGetDatum(fdwid)))
PG_RETURN_NULL();
aclresult = object_aclcheck(ForeignDataWrapperRelationId, fdwid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* Support routines for has_foreign_data_wrapper_privilege family.
*/
/*
* Given a FDW name expressed as a string, look it up and return Oid
*/
static Oid
convert_foreign_data_wrapper_name(text *fdwname)
{
char *fdwstr = text_to_cstring(fdwname);
return get_foreign_data_wrapper_oid(fdwstr, false);
}
/*
* convert_foreign_data_wrapper_priv_string
* Convert text string to AclMode value.
*/
static AclMode
convert_foreign_data_wrapper_priv_string(text *priv_type_text)
{
static const priv_map foreign_data_wrapper_priv_map[] = {
{"USAGE", ACL_USAGE},
{"USAGE WITH GRANT OPTION", ACL_GRANT_OPTION_FOR(ACL_USAGE)},
{NULL, 0}
};
return convert_any_priv_string(priv_type_text, foreign_data_wrapper_priv_map);
}
/*
* has_function_privilege variants
* These are all named "has_function_privilege" at the SQL level.
* They take various combinations of function name, function OID,
* user name, user OID, or implicit user = current_user.
*
* The result is a boolean value: true if user has the indicated
* privilege, false if not, or NULL if object doesn't exist.
*/
/*
* has_function_privilege_name_name
* Check user privileges on a function given
* name username, text functionname, and text priv name.
*/
Datum
has_function_privilege_name_name(PG_FUNCTION_ARGS)
{
Name username = PG_GETARG_NAME(0);
text *functionname = PG_GETARG_TEXT_PP(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid roleid;
Oid functionoid;
AclMode mode;
AclResult aclresult;
roleid = get_role_oid_or_public(NameStr(*username));
functionoid = convert_function_name(functionname);
mode = convert_function_priv_string(priv_type_text);
aclresult = object_aclcheck(ProcedureRelationId, functionoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_function_privilege_name
* Check user privileges on a function given
* text functionname and text priv name.
* current_user is assumed
*/
Datum
has_function_privilege_name(PG_FUNCTION_ARGS)
{
text *functionname = PG_GETARG_TEXT_PP(0);
text *priv_type_text = PG_GETARG_TEXT_PP(1);
Oid roleid;
Oid functionoid;
AclMode mode;
AclResult aclresult;
roleid = GetUserId();
functionoid = convert_function_name(functionname);
mode = convert_function_priv_string(priv_type_text);
aclresult = object_aclcheck(ProcedureRelationId, functionoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_function_privilege_name_id
* Check user privileges on a function given
* name usename, function oid, and text priv name.
*/
Datum
has_function_privilege_name_id(PG_FUNCTION_ARGS)
{
Name username = PG_GETARG_NAME(0);
Oid functionoid = PG_GETARG_OID(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid roleid;
AclMode mode;
AclResult aclresult;
roleid = get_role_oid_or_public(NameStr(*username));
mode = convert_function_priv_string(priv_type_text);
if (!SearchSysCacheExists1(PROCOID, ObjectIdGetDatum(functionoid)))
PG_RETURN_NULL();
aclresult = object_aclcheck(ProcedureRelationId, functionoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_function_privilege_id
* Check user privileges on a function given
* function oid, and text priv name.
* current_user is assumed
*/
Datum
has_function_privilege_id(PG_FUNCTION_ARGS)
{
Oid functionoid = PG_GETARG_OID(0);
text *priv_type_text = PG_GETARG_TEXT_PP(1);
Oid roleid;
AclMode mode;
AclResult aclresult;
roleid = GetUserId();
mode = convert_function_priv_string(priv_type_text);
if (!SearchSysCacheExists1(PROCOID, ObjectIdGetDatum(functionoid)))
PG_RETURN_NULL();
aclresult = object_aclcheck(ProcedureRelationId, functionoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_function_privilege_id_name
* Check user privileges on a function given
* roleid, text functionname, and text priv name.
*/
Datum
has_function_privilege_id_name(PG_FUNCTION_ARGS)
{
Oid roleid = PG_GETARG_OID(0);
text *functionname = PG_GETARG_TEXT_PP(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid functionoid;
AclMode mode;
AclResult aclresult;
functionoid = convert_function_name(functionname);
mode = convert_function_priv_string(priv_type_text);
aclresult = object_aclcheck(ProcedureRelationId, functionoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_function_privilege_id_id
* Check user privileges on a function given
* roleid, function oid, and text priv name.
*/
Datum
has_function_privilege_id_id(PG_FUNCTION_ARGS)
{
Oid roleid = PG_GETARG_OID(0);
Oid functionoid = PG_GETARG_OID(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
AclMode mode;
AclResult aclresult;
mode = convert_function_priv_string(priv_type_text);
if (!SearchSysCacheExists1(PROCOID, ObjectIdGetDatum(functionoid)))
PG_RETURN_NULL();
aclresult = object_aclcheck(ProcedureRelationId, functionoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* Support routines for has_function_privilege family.
*/
/*
* Given a function name expressed as a string, look it up and return Oid
*/
static Oid
convert_function_name(text *functionname)
{
char *funcname = text_to_cstring(functionname);
Oid oid;
oid = DatumGetObjectId(DirectFunctionCall1(regprocedurein,
CStringGetDatum(funcname)));
if (!OidIsValid(oid))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_FUNCTION),
errmsg("function \"%s\" does not exist", funcname)));
return oid;
}
/*
* convert_function_priv_string
* Convert text string to AclMode value.
*/
static AclMode
convert_function_priv_string(text *priv_type_text)
{
static const priv_map function_priv_map[] = {
{"EXECUTE", ACL_EXECUTE},
{"EXECUTE WITH GRANT OPTION", ACL_GRANT_OPTION_FOR(ACL_EXECUTE)},
{NULL, 0}
};
return convert_any_priv_string(priv_type_text, function_priv_map);
}
/*
* has_language_privilege variants
* These are all named "has_language_privilege" at the SQL level.
* They take various combinations of language name, language OID,
* user name, user OID, or implicit user = current_user.
*
* The result is a boolean value: true if user has the indicated
* privilege, false if not, or NULL if object doesn't exist.
*/
/*
* has_language_privilege_name_name
* Check user privileges on a language given
* name username, text languagename, and text priv name.
*/
Datum
has_language_privilege_name_name(PG_FUNCTION_ARGS)
{
Name username = PG_GETARG_NAME(0);
text *languagename = PG_GETARG_TEXT_PP(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid roleid;
Oid languageoid;
AclMode mode;
AclResult aclresult;
roleid = get_role_oid_or_public(NameStr(*username));
languageoid = convert_language_name(languagename);
mode = convert_language_priv_string(priv_type_text);
aclresult = object_aclcheck(LanguageRelationId, languageoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_language_privilege_name
* Check user privileges on a language given
* text languagename and text priv name.
* current_user is assumed
*/
Datum
has_language_privilege_name(PG_FUNCTION_ARGS)
{
text *languagename = PG_GETARG_TEXT_PP(0);
text *priv_type_text = PG_GETARG_TEXT_PP(1);
Oid roleid;
Oid languageoid;
AclMode mode;
AclResult aclresult;
roleid = GetUserId();
languageoid = convert_language_name(languagename);
mode = convert_language_priv_string(priv_type_text);
aclresult = object_aclcheck(LanguageRelationId, languageoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_language_privilege_name_id
* Check user privileges on a language given
* name usename, language oid, and text priv name.
*/
Datum
has_language_privilege_name_id(PG_FUNCTION_ARGS)
{
Name username = PG_GETARG_NAME(0);
Oid languageoid = PG_GETARG_OID(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid roleid;
AclMode mode;
AclResult aclresult;
roleid = get_role_oid_or_public(NameStr(*username));
mode = convert_language_priv_string(priv_type_text);
if (!SearchSysCacheExists1(LANGOID, ObjectIdGetDatum(languageoid)))
PG_RETURN_NULL();
aclresult = object_aclcheck(LanguageRelationId, languageoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_language_privilege_id
* Check user privileges on a language given
* language oid, and text priv name.
* current_user is assumed
*/
Datum
has_language_privilege_id(PG_FUNCTION_ARGS)
{
Oid languageoid = PG_GETARG_OID(0);
text *priv_type_text = PG_GETARG_TEXT_PP(1);
Oid roleid;
AclMode mode;
AclResult aclresult;
roleid = GetUserId();
mode = convert_language_priv_string(priv_type_text);
if (!SearchSysCacheExists1(LANGOID, ObjectIdGetDatum(languageoid)))
PG_RETURN_NULL();
aclresult = object_aclcheck(LanguageRelationId, languageoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_language_privilege_id_name
* Check user privileges on a language given
* roleid, text languagename, and text priv name.
*/
Datum
has_language_privilege_id_name(PG_FUNCTION_ARGS)
{
Oid roleid = PG_GETARG_OID(0);
text *languagename = PG_GETARG_TEXT_PP(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid languageoid;
AclMode mode;
AclResult aclresult;
languageoid = convert_language_name(languagename);
mode = convert_language_priv_string(priv_type_text);
aclresult = object_aclcheck(LanguageRelationId, languageoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_language_privilege_id_id
* Check user privileges on a language given
* roleid, language oid, and text priv name.
*/
Datum
has_language_privilege_id_id(PG_FUNCTION_ARGS)
{
Oid roleid = PG_GETARG_OID(0);
Oid languageoid = PG_GETARG_OID(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
AclMode mode;
AclResult aclresult;
mode = convert_language_priv_string(priv_type_text);
if (!SearchSysCacheExists1(LANGOID, ObjectIdGetDatum(languageoid)))
PG_RETURN_NULL();
aclresult = object_aclcheck(LanguageRelationId, languageoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* Support routines for has_language_privilege family.
*/
/*
* Given a language name expressed as a string, look it up and return Oid
*/
static Oid
convert_language_name(text *languagename)
{
char *langname = text_to_cstring(languagename);
return get_language_oid(langname, false);
}
/*
* convert_language_priv_string
* Convert text string to AclMode value.
*/
static AclMode
convert_language_priv_string(text *priv_type_text)
{
static const priv_map language_priv_map[] = {
{"USAGE", ACL_USAGE},
{"USAGE WITH GRANT OPTION", ACL_GRANT_OPTION_FOR(ACL_USAGE)},
{NULL, 0}
};
return convert_any_priv_string(priv_type_text, language_priv_map);
}
/*
* has_schema_privilege variants
* These are all named "has_schema_privilege" at the SQL level.
* They take various combinations of schema name, schema OID,
* user name, user OID, or implicit user = current_user.
*
* The result is a boolean value: true if user has the indicated
* privilege, false if not, or NULL if object doesn't exist.
*/
/*
* has_schema_privilege_name_name
* Check user privileges on a schema given
* name username, text schemaname, and text priv name.
*/
Datum
has_schema_privilege_name_name(PG_FUNCTION_ARGS)
{
Name username = PG_GETARG_NAME(0);
text *schemaname = PG_GETARG_TEXT_PP(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid roleid;
Oid schemaoid;
AclMode mode;
AclResult aclresult;
roleid = get_role_oid_or_public(NameStr(*username));
schemaoid = convert_schema_name(schemaname);
mode = convert_schema_priv_string(priv_type_text);
aclresult = object_aclcheck(NamespaceRelationId, schemaoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_schema_privilege_name
* Check user privileges on a schema given
* text schemaname and text priv name.
* current_user is assumed
*/
Datum
has_schema_privilege_name(PG_FUNCTION_ARGS)
{
text *schemaname = PG_GETARG_TEXT_PP(0);
text *priv_type_text = PG_GETARG_TEXT_PP(1);
Oid roleid;
Oid schemaoid;
AclMode mode;
AclResult aclresult;
roleid = GetUserId();
schemaoid = convert_schema_name(schemaname);
mode = convert_schema_priv_string(priv_type_text);
aclresult = object_aclcheck(NamespaceRelationId, schemaoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_schema_privilege_name_id
* Check user privileges on a schema given
* name usename, schema oid, and text priv name.
*/
Datum
has_schema_privilege_name_id(PG_FUNCTION_ARGS)
{
Name username = PG_GETARG_NAME(0);
Oid schemaoid = PG_GETARG_OID(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid roleid;
AclMode mode;
AclResult aclresult;
roleid = get_role_oid_or_public(NameStr(*username));
mode = convert_schema_priv_string(priv_type_text);
if (!SearchSysCacheExists1(NAMESPACEOID, ObjectIdGetDatum(schemaoid)))
PG_RETURN_NULL();
aclresult = object_aclcheck(NamespaceRelationId, schemaoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_schema_privilege_id
* Check user privileges on a schema given
* schema oid, and text priv name.
* current_user is assumed
*/
Datum
has_schema_privilege_id(PG_FUNCTION_ARGS)
{
Oid schemaoid = PG_GETARG_OID(0);
text *priv_type_text = PG_GETARG_TEXT_PP(1);
Oid roleid;
AclMode mode;
AclResult aclresult;
roleid = GetUserId();
mode = convert_schema_priv_string(priv_type_text);
if (!SearchSysCacheExists1(NAMESPACEOID, ObjectIdGetDatum(schemaoid)))
PG_RETURN_NULL();
aclresult = object_aclcheck(NamespaceRelationId, schemaoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_schema_privilege_id_name
* Check user privileges on a schema given
* roleid, text schemaname, and text priv name.
*/
Datum
has_schema_privilege_id_name(PG_FUNCTION_ARGS)
{
Oid roleid = PG_GETARG_OID(0);
text *schemaname = PG_GETARG_TEXT_PP(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid schemaoid;
AclMode mode;
AclResult aclresult;
schemaoid = convert_schema_name(schemaname);
mode = convert_schema_priv_string(priv_type_text);
aclresult = object_aclcheck(NamespaceRelationId, schemaoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_schema_privilege_id_id
* Check user privileges on a schema given
* roleid, schema oid, and text priv name.
*/
Datum
has_schema_privilege_id_id(PG_FUNCTION_ARGS)
{
Oid roleid = PG_GETARG_OID(0);
Oid schemaoid = PG_GETARG_OID(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
AclMode mode;
AclResult aclresult;
mode = convert_schema_priv_string(priv_type_text);
if (!SearchSysCacheExists1(NAMESPACEOID, ObjectIdGetDatum(schemaoid)))
PG_RETURN_NULL();
aclresult = object_aclcheck(NamespaceRelationId, schemaoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* Support routines for has_schema_privilege family.
*/
/*
* Given a schema name expressed as a string, look it up and return Oid
*/
static Oid
convert_schema_name(text *schemaname)
{
char *nspname = text_to_cstring(schemaname);
return get_namespace_oid(nspname, false);
}
/*
* convert_schema_priv_string
* Convert text string to AclMode value.
*/
static AclMode
convert_schema_priv_string(text *priv_type_text)
{
static const priv_map schema_priv_map[] = {
{"CREATE", ACL_CREATE},
{"CREATE WITH GRANT OPTION", ACL_GRANT_OPTION_FOR(ACL_CREATE)},
{"USAGE", ACL_USAGE},
{"USAGE WITH GRANT OPTION", ACL_GRANT_OPTION_FOR(ACL_USAGE)},
{NULL, 0}
};
return convert_any_priv_string(priv_type_text, schema_priv_map);
}
/*
* has_server_privilege variants
* These are all named "has_server_privilege" at the SQL level.
* They take various combinations of foreign server name,
* server OID, user name, user OID, or implicit user = current_user.
*
* The result is a boolean value: true if user has the indicated
* privilege, false if not.
*/
/*
* has_server_privilege_name_name
* Check user privileges on a foreign server given
* name username, text servername, and text priv name.
*/
Datum
has_server_privilege_name_name(PG_FUNCTION_ARGS)
{
Name username = PG_GETARG_NAME(0);
text *servername = PG_GETARG_TEXT_PP(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid roleid;
Oid serverid;
AclMode mode;
AclResult aclresult;
roleid = get_role_oid_or_public(NameStr(*username));
serverid = convert_server_name(servername);
mode = convert_server_priv_string(priv_type_text);
aclresult = object_aclcheck(ForeignServerRelationId, serverid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_server_privilege_name
* Check user privileges on a foreign server given
* text servername and text priv name.
* current_user is assumed
*/
Datum
has_server_privilege_name(PG_FUNCTION_ARGS)
{
text *servername = PG_GETARG_TEXT_PP(0);
text *priv_type_text = PG_GETARG_TEXT_PP(1);
Oid roleid;
Oid serverid;
AclMode mode;
AclResult aclresult;
roleid = GetUserId();
serverid = convert_server_name(servername);
mode = convert_server_priv_string(priv_type_text);
aclresult = object_aclcheck(ForeignServerRelationId, serverid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_server_privilege_name_id
* Check user privileges on a foreign server given
* name usename, foreign server oid, and text priv name.
*/
Datum
has_server_privilege_name_id(PG_FUNCTION_ARGS)
{
Name username = PG_GETARG_NAME(0);
Oid serverid = PG_GETARG_OID(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid roleid;
AclMode mode;
AclResult aclresult;
roleid = get_role_oid_or_public(NameStr(*username));
mode = convert_server_priv_string(priv_type_text);
if (!SearchSysCacheExists1(FOREIGNSERVEROID, ObjectIdGetDatum(serverid)))
PG_RETURN_NULL();
aclresult = object_aclcheck(ForeignServerRelationId, serverid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_server_privilege_id
* Check user privileges on a foreign server given
* server oid, and text priv name.
* current_user is assumed
*/
Datum
has_server_privilege_id(PG_FUNCTION_ARGS)
{
Oid serverid = PG_GETARG_OID(0);
text *priv_type_text = PG_GETARG_TEXT_PP(1);
Oid roleid;
AclMode mode;
AclResult aclresult;
roleid = GetUserId();
mode = convert_server_priv_string(priv_type_text);
if (!SearchSysCacheExists1(FOREIGNSERVEROID, ObjectIdGetDatum(serverid)))
PG_RETURN_NULL();
aclresult = object_aclcheck(ForeignServerRelationId, serverid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_server_privilege_id_name
* Check user privileges on a foreign server given
* roleid, text servername, and text priv name.
*/
Datum
has_server_privilege_id_name(PG_FUNCTION_ARGS)
{
Oid roleid = PG_GETARG_OID(0);
text *servername = PG_GETARG_TEXT_PP(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid serverid;
AclMode mode;
AclResult aclresult;
serverid = convert_server_name(servername);
mode = convert_server_priv_string(priv_type_text);
aclresult = object_aclcheck(ForeignServerRelationId, serverid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_server_privilege_id_id
* Check user privileges on a foreign server given
* roleid, server oid, and text priv name.
*/
Datum
has_server_privilege_id_id(PG_FUNCTION_ARGS)
{
Oid roleid = PG_GETARG_OID(0);
Oid serverid = PG_GETARG_OID(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
AclMode mode;
AclResult aclresult;
mode = convert_server_priv_string(priv_type_text);
if (!SearchSysCacheExists1(FOREIGNSERVEROID, ObjectIdGetDatum(serverid)))
PG_RETURN_NULL();
aclresult = object_aclcheck(ForeignServerRelationId, serverid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* Support routines for has_server_privilege family.
*/
/*
* Given a server name expressed as a string, look it up and return Oid
*/
static Oid
convert_server_name(text *servername)
{
char *serverstr = text_to_cstring(servername);
return get_foreign_server_oid(serverstr, false);
}
/*
* convert_server_priv_string
* Convert text string to AclMode value.
*/
static AclMode
convert_server_priv_string(text *priv_type_text)
{
static const priv_map server_priv_map[] = {
{"USAGE", ACL_USAGE},
{"USAGE WITH GRANT OPTION", ACL_GRANT_OPTION_FOR(ACL_USAGE)},
{NULL, 0}
};
return convert_any_priv_string(priv_type_text, server_priv_map);
}
/*
* has_tablespace_privilege variants
* These are all named "has_tablespace_privilege" at the SQL level.
* They take various combinations of tablespace name, tablespace OID,
* user name, user OID, or implicit user = current_user.
*
* The result is a boolean value: true if user has the indicated
* privilege, false if not.
*/
/*
* has_tablespace_privilege_name_name
* Check user privileges on a tablespace given
* name username, text tablespacename, and text priv name.
*/
Datum
has_tablespace_privilege_name_name(PG_FUNCTION_ARGS)
{
Name username = PG_GETARG_NAME(0);
text *tablespacename = PG_GETARG_TEXT_PP(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid roleid;
Oid tablespaceoid;
AclMode mode;
AclResult aclresult;
roleid = get_role_oid_or_public(NameStr(*username));
tablespaceoid = convert_tablespace_name(tablespacename);
mode = convert_tablespace_priv_string(priv_type_text);
aclresult = object_aclcheck(TableSpaceRelationId, tablespaceoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_tablespace_privilege_name
* Check user privileges on a tablespace given
* text tablespacename and text priv name.
* current_user is assumed
*/
Datum
has_tablespace_privilege_name(PG_FUNCTION_ARGS)
{
text *tablespacename = PG_GETARG_TEXT_PP(0);
text *priv_type_text = PG_GETARG_TEXT_PP(1);
Oid roleid;
Oid tablespaceoid;
AclMode mode;
AclResult aclresult;
roleid = GetUserId();
tablespaceoid = convert_tablespace_name(tablespacename);
mode = convert_tablespace_priv_string(priv_type_text);
aclresult = object_aclcheck(TableSpaceRelationId, tablespaceoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_tablespace_privilege_name_id
* Check user privileges on a tablespace given
* name usename, tablespace oid, and text priv name.
*/
Datum
has_tablespace_privilege_name_id(PG_FUNCTION_ARGS)
{
Name username = PG_GETARG_NAME(0);
Oid tablespaceoid = PG_GETARG_OID(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid roleid;
AclMode mode;
AclResult aclresult;
roleid = get_role_oid_or_public(NameStr(*username));
mode = convert_tablespace_priv_string(priv_type_text);
if (!SearchSysCacheExists1(TABLESPACEOID, ObjectIdGetDatum(tablespaceoid)))
PG_RETURN_NULL();
aclresult = object_aclcheck(TableSpaceRelationId, tablespaceoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_tablespace_privilege_id
* Check user privileges on a tablespace given
* tablespace oid, and text priv name.
* current_user is assumed
*/
Datum
has_tablespace_privilege_id(PG_FUNCTION_ARGS)
{
Oid tablespaceoid = PG_GETARG_OID(0);
text *priv_type_text = PG_GETARG_TEXT_PP(1);
Oid roleid;
AclMode mode;
AclResult aclresult;
roleid = GetUserId();
mode = convert_tablespace_priv_string(priv_type_text);
if (!SearchSysCacheExists1(TABLESPACEOID, ObjectIdGetDatum(tablespaceoid)))
PG_RETURN_NULL();
aclresult = object_aclcheck(TableSpaceRelationId, tablespaceoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_tablespace_privilege_id_name
* Check user privileges on a tablespace given
* roleid, text tablespacename, and text priv name.
*/
Datum
has_tablespace_privilege_id_name(PG_FUNCTION_ARGS)
{
Oid roleid = PG_GETARG_OID(0);
text *tablespacename = PG_GETARG_TEXT_PP(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid tablespaceoid;
AclMode mode;
AclResult aclresult;
tablespaceoid = convert_tablespace_name(tablespacename);
mode = convert_tablespace_priv_string(priv_type_text);
aclresult = object_aclcheck(TableSpaceRelationId, tablespaceoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_tablespace_privilege_id_id
* Check user privileges on a tablespace given
* roleid, tablespace oid, and text priv name.
*/
Datum
has_tablespace_privilege_id_id(PG_FUNCTION_ARGS)
{
Oid roleid = PG_GETARG_OID(0);
Oid tablespaceoid = PG_GETARG_OID(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
AclMode mode;
AclResult aclresult;
mode = convert_tablespace_priv_string(priv_type_text);
if (!SearchSysCacheExists1(TABLESPACEOID, ObjectIdGetDatum(tablespaceoid)))
PG_RETURN_NULL();
aclresult = object_aclcheck(TableSpaceRelationId, tablespaceoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* Support routines for has_tablespace_privilege family.
*/
/*
* Given a tablespace name expressed as a string, look it up and return Oid
*/
static Oid
convert_tablespace_name(text *tablespacename)
{
char *spcname = text_to_cstring(tablespacename);
return get_tablespace_oid(spcname, false);
}
/*
* convert_tablespace_priv_string
* Convert text string to AclMode value.
*/
static AclMode
convert_tablespace_priv_string(text *priv_type_text)
{
static const priv_map tablespace_priv_map[] = {
{"CREATE", ACL_CREATE},
{"CREATE WITH GRANT OPTION", ACL_GRANT_OPTION_FOR(ACL_CREATE)},
{NULL, 0}
};
return convert_any_priv_string(priv_type_text, tablespace_priv_map);
}
/*
* has_type_privilege variants
* These are all named "has_type_privilege" at the SQL level.
* They take various combinations of type name, type OID,
* user name, user OID, or implicit user = current_user.
*
* The result is a boolean value: true if user has the indicated
* privilege, false if not, or NULL if object doesn't exist.
*/
/*
* has_type_privilege_name_name
* Check user privileges on a type given
* name username, text typename, and text priv name.
*/
Datum
has_type_privilege_name_name(PG_FUNCTION_ARGS)
{
Name username = PG_GETARG_NAME(0);
text *typename = PG_GETARG_TEXT_PP(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid roleid;
Oid typeoid;
AclMode mode;
AclResult aclresult;
roleid = get_role_oid_or_public(NameStr(*username));
typeoid = convert_type_name(typename);
mode = convert_type_priv_string(priv_type_text);
aclresult = object_aclcheck(TypeRelationId, typeoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_type_privilege_name
* Check user privileges on a type given
* text typename and text priv name.
* current_user is assumed
*/
Datum
has_type_privilege_name(PG_FUNCTION_ARGS)
{
text *typename = PG_GETARG_TEXT_PP(0);
text *priv_type_text = PG_GETARG_TEXT_PP(1);
Oid roleid;
Oid typeoid;
AclMode mode;
AclResult aclresult;
roleid = GetUserId();
typeoid = convert_type_name(typename);
mode = convert_type_priv_string(priv_type_text);
aclresult = object_aclcheck(TypeRelationId, typeoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_type_privilege_name_id
* Check user privileges on a type given
* name usename, type oid, and text priv name.
*/
Datum
has_type_privilege_name_id(PG_FUNCTION_ARGS)
{
Name username = PG_GETARG_NAME(0);
Oid typeoid = PG_GETARG_OID(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid roleid;
AclMode mode;
AclResult aclresult;
roleid = get_role_oid_or_public(NameStr(*username));
mode = convert_type_priv_string(priv_type_text);
if (!SearchSysCacheExists1(TYPEOID, ObjectIdGetDatum(typeoid)))
PG_RETURN_NULL();
aclresult = object_aclcheck(TypeRelationId, typeoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_type_privilege_id
* Check user privileges on a type given
* type oid, and text priv name.
* current_user is assumed
*/
Datum
has_type_privilege_id(PG_FUNCTION_ARGS)
{
Oid typeoid = PG_GETARG_OID(0);
text *priv_type_text = PG_GETARG_TEXT_PP(1);
Oid roleid;
AclMode mode;
AclResult aclresult;
roleid = GetUserId();
mode = convert_type_priv_string(priv_type_text);
if (!SearchSysCacheExists1(TYPEOID, ObjectIdGetDatum(typeoid)))
PG_RETURN_NULL();
aclresult = object_aclcheck(TypeRelationId, typeoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_type_privilege_id_name
* Check user privileges on a type given
* roleid, text typename, and text priv name.
*/
Datum
has_type_privilege_id_name(PG_FUNCTION_ARGS)
{
Oid roleid = PG_GETARG_OID(0);
text *typename = PG_GETARG_TEXT_PP(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid typeoid;
AclMode mode;
AclResult aclresult;
typeoid = convert_type_name(typename);
mode = convert_type_priv_string(priv_type_text);
aclresult = object_aclcheck(TypeRelationId, typeoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* has_type_privilege_id_id
* Check user privileges on a type given
* roleid, type oid, and text priv name.
*/
Datum
has_type_privilege_id_id(PG_FUNCTION_ARGS)
{
Oid roleid = PG_GETARG_OID(0);
Oid typeoid = PG_GETARG_OID(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
AclMode mode;
AclResult aclresult;
mode = convert_type_priv_string(priv_type_text);
if (!SearchSysCacheExists1(TYPEOID, ObjectIdGetDatum(typeoid)))
PG_RETURN_NULL();
aclresult = object_aclcheck(TypeRelationId, typeoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* Support routines for has_type_privilege family.
*/
/*
* Given a type name expressed as a string, look it up and return Oid
*/
static Oid
convert_type_name(text *typename)
{
char *typname = text_to_cstring(typename);
Oid oid;
oid = DatumGetObjectId(DirectFunctionCall1(regtypein,
CStringGetDatum(typname)));
if (!OidIsValid(oid))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("type \"%s\" does not exist", typname)));
return oid;
}
/*
* convert_type_priv_string
* Convert text string to AclMode value.
*/
static AclMode
convert_type_priv_string(text *priv_type_text)
{
static const priv_map type_priv_map[] = {
{"USAGE", ACL_USAGE},
{"USAGE WITH GRANT OPTION", ACL_GRANT_OPTION_FOR(ACL_USAGE)},
{NULL, 0}
};
return convert_any_priv_string(priv_type_text, type_priv_map);
}
/*
* has_parameter_privilege variants
* These are all named "has_parameter_privilege" at the SQL level.
* They take various combinations of parameter name with
* user name, user OID, or implicit user = current_user.
*
* The result is a boolean value: true if user has been granted
* the indicated privilege or false if not.
*/
/*
* has_param_priv_byname
*
* Helper function to check user privileges on a parameter given the
* role by Oid, parameter by text name, and privileges as AclMode.
*/
static bool
has_param_priv_byname(Oid roleid, const text *parameter, AclMode priv)
{
char *paramstr = text_to_cstring(parameter);
return pg_parameter_aclcheck(paramstr, roleid, priv) == ACLCHECK_OK;
}
/*
* has_parameter_privilege_name_name
* Check user privileges on a parameter given name username, text
* parameter, and text priv name.
*/
Datum
has_parameter_privilege_name_name(PG_FUNCTION_ARGS)
{
Name username = PG_GETARG_NAME(0);
text *parameter = PG_GETARG_TEXT_PP(1);
AclMode priv = convert_parameter_priv_string(PG_GETARG_TEXT_PP(2));
Oid roleid = get_role_oid_or_public(NameStr(*username));
PG_RETURN_BOOL(has_param_priv_byname(roleid, parameter, priv));
}
/*
* has_parameter_privilege_name
* Check user privileges on a parameter given text parameter and text priv
* name. current_user is assumed
*/
Datum
has_parameter_privilege_name(PG_FUNCTION_ARGS)
{
text *parameter = PG_GETARG_TEXT_PP(0);
AclMode priv = convert_parameter_priv_string(PG_GETARG_TEXT_PP(1));
PG_RETURN_BOOL(has_param_priv_byname(GetUserId(), parameter, priv));
}
/*
* has_parameter_privilege_id_name
* Check user privileges on a parameter given roleid, text parameter, and
* text priv name.
*/
Datum
has_parameter_privilege_id_name(PG_FUNCTION_ARGS)
{
Oid roleid = PG_GETARG_OID(0);
text *parameter = PG_GETARG_TEXT_PP(1);
AclMode priv = convert_parameter_priv_string(PG_GETARG_TEXT_PP(2));
PG_RETURN_BOOL(has_param_priv_byname(roleid, parameter, priv));
}
/*
* Support routines for has_parameter_privilege family.
*/
/*
* convert_parameter_priv_string
* Convert text string to AclMode value.
*/
static AclMode
convert_parameter_priv_string(text *priv_text)
{
static const priv_map parameter_priv_map[] = {
{"SET", ACL_SET},
{"SET WITH GRANT OPTION", ACL_GRANT_OPTION_FOR(ACL_SET)},
{"ALTER SYSTEM", ACL_ALTER_SYSTEM},
{"ALTER SYSTEM WITH GRANT OPTION", ACL_GRANT_OPTION_FOR(ACL_ALTER_SYSTEM)},
{NULL, 0}
};
return convert_any_priv_string(priv_text, parameter_priv_map);
}
/*
* pg_has_role variants
* These are all named "pg_has_role" at the SQL level.
* They take various combinations of role name, role OID,
* user name, user OID, or implicit user = current_user.
*
* The result is a boolean value: true if user has the indicated
* privilege, false if not.
*/
/*
* pg_has_role_name_name
* Check user privileges on a role given
* name username, name rolename, and text priv name.
*/
Datum
pg_has_role_name_name(PG_FUNCTION_ARGS)
{
Name username = PG_GETARG_NAME(0);
Name rolename = PG_GETARG_NAME(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid roleid;
Oid roleoid;
AclMode mode;
AclResult aclresult;
roleid = get_role_oid(NameStr(*username), false);
roleoid = get_role_oid(NameStr(*rolename), false);
mode = convert_role_priv_string(priv_type_text);
aclresult = pg_role_aclcheck(roleoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* pg_has_role_name
* Check user privileges on a role given
* name rolename and text priv name.
* current_user is assumed
*/
Datum
pg_has_role_name(PG_FUNCTION_ARGS)
{
Name rolename = PG_GETARG_NAME(0);
text *priv_type_text = PG_GETARG_TEXT_PP(1);
Oid roleid;
Oid roleoid;
AclMode mode;
AclResult aclresult;
roleid = GetUserId();
roleoid = get_role_oid(NameStr(*rolename), false);
mode = convert_role_priv_string(priv_type_text);
aclresult = pg_role_aclcheck(roleoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* pg_has_role_name_id
* Check user privileges on a role given
* name usename, role oid, and text priv name.
*/
Datum
pg_has_role_name_id(PG_FUNCTION_ARGS)
{
Name username = PG_GETARG_NAME(0);
Oid roleoid = PG_GETARG_OID(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid roleid;
AclMode mode;
AclResult aclresult;
roleid = get_role_oid(NameStr(*username), false);
mode = convert_role_priv_string(priv_type_text);
aclresult = pg_role_aclcheck(roleoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* pg_has_role_id
* Check user privileges on a role given
* role oid, and text priv name.
* current_user is assumed
*/
Datum
pg_has_role_id(PG_FUNCTION_ARGS)
{
Oid roleoid = PG_GETARG_OID(0);
text *priv_type_text = PG_GETARG_TEXT_PP(1);
Oid roleid;
AclMode mode;
AclResult aclresult;
roleid = GetUserId();
mode = convert_role_priv_string(priv_type_text);
aclresult = pg_role_aclcheck(roleoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* pg_has_role_id_name
* Check user privileges on a role given
* roleid, name rolename, and text priv name.
*/
Datum
pg_has_role_id_name(PG_FUNCTION_ARGS)
{
Oid roleid = PG_GETARG_OID(0);
Name rolename = PG_GETARG_NAME(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
Oid roleoid;
AclMode mode;
AclResult aclresult;
roleoid = get_role_oid(NameStr(*rolename), false);
mode = convert_role_priv_string(priv_type_text);
aclresult = pg_role_aclcheck(roleoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* pg_has_role_id_id
* Check user privileges on a role given
* roleid, role oid, and text priv name.
*/
Datum
pg_has_role_id_id(PG_FUNCTION_ARGS)
{
Oid roleid = PG_GETARG_OID(0);
Oid roleoid = PG_GETARG_OID(1);
text *priv_type_text = PG_GETARG_TEXT_PP(2);
AclMode mode;
AclResult aclresult;
mode = convert_role_priv_string(priv_type_text);
aclresult = pg_role_aclcheck(roleoid, roleid, mode);
PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}
/*
* Support routines for pg_has_role family.
*/
/*
* convert_role_priv_string
* Convert text string to AclMode value.
*
* We use USAGE to denote whether the privileges of the role are accessible
* (has_privs_of_role), MEMBER to denote is_member, and MEMBER WITH GRANT
* (or ADMIN) OPTION to denote is_admin. There is no ACL bit corresponding
* to MEMBER so we cheat and use ACL_CREATE for that. This convention
* is shared only with pg_role_aclcheck, below.
*/
static AclMode
convert_role_priv_string(text *priv_type_text)
{
static const priv_map role_priv_map[] = {
{"USAGE", ACL_USAGE},
{"MEMBER", ACL_CREATE},
{"SET", ACL_SET},
{"USAGE WITH GRANT OPTION", ACL_GRANT_OPTION_FOR(ACL_CREATE)},
{"USAGE WITH ADMIN OPTION", ACL_GRANT_OPTION_FOR(ACL_CREATE)},
{"MEMBER WITH GRANT OPTION", ACL_GRANT_OPTION_FOR(ACL_CREATE)},
{"MEMBER WITH ADMIN OPTION", ACL_GRANT_OPTION_FOR(ACL_CREATE)},
{"SET WITH GRANT OPTION", ACL_GRANT_OPTION_FOR(ACL_CREATE)},
{"SET WITH ADMIN OPTION", ACL_GRANT_OPTION_FOR(ACL_CREATE)},
{NULL, 0}
};
return convert_any_priv_string(priv_type_text, role_priv_map);
}
/*
* pg_role_aclcheck
* Quick-and-dirty support for pg_has_role
*/
static AclResult
pg_role_aclcheck(Oid role_oid, Oid roleid, AclMode mode)
{
if (mode & ACL_GRANT_OPTION_FOR(ACL_CREATE))
{
if (is_admin_of_role(roleid, role_oid))
return ACLCHECK_OK;
}
if (mode & ACL_CREATE)
{
if (is_member_of_role(roleid, role_oid))
return ACLCHECK_OK;
}
if (mode & ACL_USAGE)
{
if (has_privs_of_role(roleid, role_oid))
return ACLCHECK_OK;
}
if (mode & ACL_SET)
{
if (member_can_set_role(roleid, role_oid))
return ACLCHECK_OK;
}
return ACLCHECK_NO_PRIV;
}
/*
* initialization function (called by InitPostgres)
*/
void
initialize_acl(void)
{
if (!IsBootstrapProcessingMode())
{
cached_db_hash =
GetSysCacheHashValue1(DATABASEOID,
ObjectIdGetDatum(MyDatabaseId));
/*
* In normal mode, set a callback on any syscache invalidation of rows
* of pg_auth_members (for roles_is_member_of()) pg_database (for
* roles_is_member_of())
*/
CacheRegisterSyscacheCallback(AUTHMEMROLEMEM,
RoleMembershipCacheCallback,
(Datum) 0);
CacheRegisterSyscacheCallback(AUTHOID,
RoleMembershipCacheCallback,
(Datum) 0);
CacheRegisterSyscacheCallback(DATABASEOID,
RoleMembershipCacheCallback,
(Datum) 0);
}
}
/*
* RoleMembershipCacheCallback
* Syscache inval callback function
*/
static void
RoleMembershipCacheCallback(Datum arg, int cacheid, uint32 hashvalue)
{
if (cacheid == DATABASEOID &&
hashvalue != cached_db_hash &&
hashvalue != 0)
{
return; /* ignore pg_database changes for other DBs */
}
/* Force membership caches to be recomputed on next use */
cached_role[ROLERECURSE_MEMBERS] = InvalidOid;
cached_role[ROLERECURSE_PRIVS] = InvalidOid;
cached_role[ROLERECURSE_SETROLE] = InvalidOid;
}
/*
* Get a list of roles that the specified roleid is a member of
*
* Type ROLERECURSE_MEMBERS recurses through all grants; ROLERECURSE_PRIVS
* recurses only through inheritable grants; and ROLERECURSE_SETROLE recurses
* only through grants with set_option.
*
* Since indirect membership testing is relatively expensive, we cache
* a list of memberships. Hence, the result is only guaranteed good until
* the next call of roles_is_member_of()!
*
* For the benefit of select_best_grantor, the result is defined to be
* in breadth-first order, ie, closer relationships earlier.
*
* If admin_of is not InvalidOid, this function sets *admin_role, either
* to the OID of the first role in the result list that directly possesses
* ADMIN OPTION on the role corresponding to admin_of, or to InvalidOid if
* there is no such role.
*/
static List *
roles_is_member_of(Oid roleid, enum RoleRecurseType type,
Oid admin_of, Oid *admin_role)
{
Oid dba;
List *roles_list;
ListCell *l;
List *new_cached_roles;
MemoryContext oldctx;
Assert(OidIsValid(admin_of) == PointerIsValid(admin_role));
if (admin_role != NULL)
*admin_role = InvalidOid;
/* If cache is valid and ADMIN OPTION not sought, just return the list */
if (cached_role[type] == roleid && !OidIsValid(admin_of) &&
OidIsValid(cached_role[type]))
return cached_roles[type];
/*
* Role expansion happens in a non-database backend when guc.c checks
* ROLE_PG_READ_ALL_SETTINGS for a physical walsender SHOW command. In
* that case, no role gets pg_database_owner.
*/
if (!OidIsValid(MyDatabaseId))
dba = InvalidOid;
else
{
HeapTuple dbtup;
dbtup = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
if (!HeapTupleIsValid(dbtup))
elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
dba = ((Form_pg_database) GETSTRUCT(dbtup))->datdba;
ReleaseSysCache(dbtup);
}
/*
* Find all the roles that roleid is a member of, including multi-level
* recursion. The role itself will always be the first element of the
* resulting list.
*
* Each element of the list is scanned to see if it adds any indirect
* memberships. We can use a single list as both the record of
* already-found memberships and the agenda of roles yet to be scanned.
* This is a bit tricky but works because the foreach() macro doesn't
* fetch the next list element until the bottom of the loop.
*/
roles_list = list_make1_oid(roleid);
foreach(l, roles_list)
{
Oid memberid = lfirst_oid(l);
CatCList *memlist;
int i;
/* Find roles that memberid is directly a member of */
memlist = SearchSysCacheList1(AUTHMEMMEMROLE,
ObjectIdGetDatum(memberid));
for (i = 0; i < memlist->n_members; i++)
{
HeapTuple tup = &memlist->members[i]->tuple;
Form_pg_auth_members form = (Form_pg_auth_members) GETSTRUCT(tup);
Oid otherid = form->roleid;
/*
* While otherid==InvalidOid shouldn't appear in the catalog, the
* OidIsValid() avoids crashing if that arises.
*/
if (otherid == admin_of && form->admin_option &&
OidIsValid(admin_of) && !OidIsValid(*admin_role))
*admin_role = memberid;
/* If we're supposed to ignore non-heritable grants, do so. */
if (type == ROLERECURSE_PRIVS && !form->inherit_option)
continue;
/* If we're supposed to ignore non-SET grants, do so. */
if (type == ROLERECURSE_SETROLE && !form->set_option)
continue;
/*
* Even though there shouldn't be any loops in the membership
* graph, we must test for having already seen this role. It is
* legal for instance to have both A->B and A->C->B.
*/
roles_list = list_append_unique_oid(roles_list, otherid);
}
ReleaseSysCacheList(memlist);
/* implement pg_database_owner implicit membership */
if (memberid == dba && OidIsValid(dba))
roles_list = list_append_unique_oid(roles_list,
ROLE_PG_DATABASE_OWNER);
}
/*
* Copy the completed list into TopMemoryContext so it will persist.
*/
oldctx = MemoryContextSwitchTo(TopMemoryContext);
new_cached_roles = list_copy(roles_list);
MemoryContextSwitchTo(oldctx);
list_free(roles_list);
/*
* Now safe to assign to state variable
*/
cached_role[type] = InvalidOid; /* just paranoia */
list_free(cached_roles[type]);
cached_roles[type] = new_cached_roles;
cached_role[type] = roleid;
/* And now we can return the answer */
return cached_roles[type];
}
/*
* Does member have the privileges of role (directly or indirectly)?
*
* This is defined not to recurse through grants that are not inherited,
* and only inherited grants confer the associated privileges automatically.
*
* See also member_can_set_role, below.
*/
bool
has_privs_of_role(Oid member, Oid role)
{
/* Fast path for simple case */
if (member == role)
return true;
/* Superusers have every privilege, so are part of every role */
if (superuser_arg(member))
return true;
/*
* Find all the roles that member has the privileges of, including
* multi-level recursion, then see if target role is any one of them.
*/
return list_member_oid(roles_is_member_of(member, ROLERECURSE_PRIVS,
InvalidOid, NULL),
role);
}
/*
* Can member use SET ROLE to this role?
*
* There must be a chain of grants from 'member' to 'role' each of which
* permits SET ROLE; that is, each of which has set_option = true.
*
* It doesn't matter whether the grants are inheritable. That's a separate
* question; see has_privs_of_role.
*
* This function should be used to determine whether the session user can
* use SET ROLE to become the target user. We also use it to determine whether
* the session user can change an existing object to be owned by the target
* user, or create new objects owned by the target user.
*/
bool
member_can_set_role(Oid member, Oid role)
{
/* Fast path for simple case */
if (member == role)
return true;
/* Superusers have every privilege, so can always SET ROLE */
if (superuser_arg(member))
return true;
/*
* Find all the roles that member can access via SET ROLE, including
* multi-level recursion, then see if target role is any one of them.
*/
return list_member_oid(roles_is_member_of(member, ROLERECURSE_SETROLE,
InvalidOid, NULL),
role);
}
/*
* Permission violation error unless able to SET ROLE to target role.
*/
void
check_can_set_role(Oid member, Oid role)
{
if (!member_can_set_role(member, role))
ereport(ERROR,
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("must be able to SET ROLE \"%s\"",
GetUserNameFromId(role, false))));
}
/*
* Is member a member of role (directly or indirectly)?
*
* This is defined to recurse through grants whether they are inherited or not.
*
* Do not use this for privilege checking, instead use has_privs_of_role().
* Don't use it for determining whether it's possible to SET ROLE to some
* other role; for that, use member_can_set_role(). And don't use it for
* determining whether it's OK to create an object owned by some other role:
* use member_can_set_role() for that, too.
*
* In short, calling this function is the wrong thing to do nearly everywhere.
*/
bool
is_member_of_role(Oid member, Oid role)
{
/* Fast path for simple case */
if (member == role)
return true;
/* Superusers have every privilege, so are part of every role */
if (superuser_arg(member))
return true;
/*
* Find all the roles that member is a member of, including multi-level
* recursion, then see if target role is any one of them.
*/
return list_member_oid(roles_is_member_of(member, ROLERECURSE_MEMBERS,
InvalidOid, NULL),
role);
}
/*
* Is member a member of role, not considering superuserness?
*
* This is identical to is_member_of_role except we ignore superuser
* status.
*
* Do not use this for privilege checking, instead use has_privs_of_role()
*/
bool
is_member_of_role_nosuper(Oid member, Oid role)
{
/* Fast path for simple case */
if (member == role)
return true;
/*
* Find all the roles that member is a member of, including multi-level
* recursion, then see if target role is any one of them.
*/
return list_member_oid(roles_is_member_of(member, ROLERECURSE_MEMBERS,
InvalidOid, NULL),
role);
}
/*
* Is member an admin of role? That is, is member the role itself (subject to
* restrictions below), a member (directly or indirectly) WITH ADMIN OPTION,
* or a superuser?
*/
bool
is_admin_of_role(Oid member, Oid role)
{
Oid admin_role;
if (superuser_arg(member))
return true;
/* By policy, a role cannot have WITH ADMIN OPTION on itself. */
if (member == role)
return false;
(void) roles_is_member_of(member, ROLERECURSE_MEMBERS, role, &admin_role);
return OidIsValid(admin_role);
}
/*
* Find a role whose privileges "member" inherits which has ADMIN OPTION
* on "role", ignoring super-userness.
*
* There might be more than one such role; prefer one which involves fewer
* hops. That is, if member has ADMIN OPTION, prefer that over all other
* options; if not, prefer a role from which member inherits more directly
* over more indirect inheritance.
*/
Oid
select_best_admin(Oid member, Oid role)
{
Oid admin_role;
/* By policy, a role cannot have WITH ADMIN OPTION on itself. */
if (member == role)
return InvalidOid;
(void) roles_is_member_of(member, ROLERECURSE_PRIVS, role, &admin_role);
return admin_role;
}
/* does what it says ... */
static int
count_one_bits(AclMode mask)
{
int nbits = 0;
/* this code relies on AclMode being an unsigned type */
while (mask)
{
if (mask & 1)
nbits++;
mask >>= 1;
}
return nbits;
}
/*
* Select the effective grantor ID for a GRANT or REVOKE operation.
*
* The grantor must always be either the object owner or some role that has
* been explicitly granted grant options. This ensures that all granted
* privileges appear to flow from the object owner, and there are never
* multiple "original sources" of a privilege. Therefore, if the would-be
* grantor is a member of a role that has the needed grant options, we have
* to do the grant as that role instead.
*
* It is possible that the would-be grantor is a member of several roles
* that have different subsets of the desired grant options, but no one
* role has 'em all. In this case we pick a role with the largest number
* of desired options. Ties are broken in favor of closer ancestors.
*
* roleId: the role attempting to do the GRANT/REVOKE
* privileges: the privileges to be granted/revoked
* acl: the ACL of the object in question
* ownerId: the role owning the object in question
* *grantorId: receives the OID of the role to do the grant as
* *grantOptions: receives the grant options actually held by grantorId
*
* If no grant options exist, we set grantorId to roleId, grantOptions to 0.
*/
void
select_best_grantor(Oid roleId, AclMode privileges,
const Acl *acl, Oid ownerId,
Oid *grantorId, AclMode *grantOptions)
{
AclMode needed_goptions = ACL_GRANT_OPTION_FOR(privileges);
List *roles_list;
int nrights;
ListCell *l;
/*
* The object owner is always treated as having all grant options, so if
* roleId is the owner it's easy. Also, if roleId is a superuser it's
* easy: superusers are implicitly members of every role, so they act as
* the object owner.
*/
if (roleId == ownerId || superuser_arg(roleId))
{
*grantorId = ownerId;
*grantOptions = needed_goptions;
return;
}
/*
* Otherwise we have to do a careful search to see if roleId has the
* privileges of any suitable role. Note: we can hang onto the result of
* roles_is_member_of() throughout this loop, because aclmask_direct()
* doesn't query any role memberships.
*/
roles_list = roles_is_member_of(roleId, ROLERECURSE_PRIVS,
InvalidOid, NULL);
/* initialize candidate result as default */
*grantorId = roleId;
*grantOptions = ACL_NO_RIGHTS;
nrights = 0;
foreach(l, roles_list)
{
Oid otherrole = lfirst_oid(l);
AclMode otherprivs;
otherprivs = aclmask_direct(acl, otherrole, ownerId,
needed_goptions, ACLMASK_ALL);
if (otherprivs == needed_goptions)
{
/* Found a suitable grantor */
*grantorId = otherrole;
*grantOptions = otherprivs;
return;
}
/*
* If it has just some of the needed privileges, remember best
* candidate.
*/
if (otherprivs != ACL_NO_RIGHTS)
{
int nnewrights = count_one_bits(otherprivs);
if (nnewrights > nrights)
{
*grantorId = otherrole;
*grantOptions = otherprivs;
nrights = nnewrights;
}
}
}
}
/*
* get_role_oid - Given a role name, look up the role's OID.
*
* If missing_ok is false, throw an error if role name not found. If
* true, just return InvalidOid.
*/
Oid
get_role_oid(const char *rolname, bool missing_ok)
{
Oid oid;
oid = GetSysCacheOid1(AUTHNAME, Anum_pg_authid_oid,
CStringGetDatum(rolname));
if (!OidIsValid(oid) && !missing_ok)
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("role \"%s\" does not exist", rolname)));
return oid;
}
/*
* get_role_oid_or_public - As above, but return ACL_ID_PUBLIC if the
* role name is "public".
*/
Oid
get_role_oid_or_public(const char *rolname)
{
if (strcmp(rolname, "public") == 0)
return ACL_ID_PUBLIC;
return get_role_oid(rolname, false);
}
/*
* Given a RoleSpec node, return the OID it corresponds to. If missing_ok is
* true, return InvalidOid if the role does not exist.
*
* PUBLIC is always disallowed here. Routines wanting to handle the PUBLIC
* case must check the case separately.
*/
Oid
get_rolespec_oid(const RoleSpec *role, bool missing_ok)
{
Oid oid;
switch (role->roletype)
{
case ROLESPEC_CSTRING:
Assert(role->rolename);
oid = get_role_oid(role->rolename, missing_ok);
break;
case ROLESPEC_CURRENT_ROLE:
case ROLESPEC_CURRENT_USER:
oid = GetUserId();
break;
case ROLESPEC_SESSION_USER:
oid = GetSessionUserId();
break;
case ROLESPEC_PUBLIC:
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("role \"%s\" does not exist", "public")));
oid = InvalidOid; /* make compiler happy */
break;
default:
elog(ERROR, "unexpected role type %d", role->roletype);
}
return oid;
}
/*
* Given a RoleSpec node, return the pg_authid HeapTuple it corresponds to.
* Caller must ReleaseSysCache when done with the result tuple.
*/
HeapTuple
get_rolespec_tuple(const RoleSpec *role)
{
HeapTuple tuple;
switch (role->roletype)
{
case ROLESPEC_CSTRING:
Assert(role->rolename);
tuple = SearchSysCache1(AUTHNAME, CStringGetDatum(role->rolename));
if (!HeapTupleIsValid(tuple))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("role \"%s\" does not exist", role->rolename)));
break;
case ROLESPEC_CURRENT_ROLE:
case ROLESPEC_CURRENT_USER:
tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(GetUserId()));
if (!HeapTupleIsValid(tuple))
elog(ERROR, "cache lookup failed for role %u", GetUserId());
break;
case ROLESPEC_SESSION_USER:
tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(GetSessionUserId()));
if (!HeapTupleIsValid(tuple))
elog(ERROR, "cache lookup failed for role %u", GetSessionUserId());
break;
case ROLESPEC_PUBLIC:
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("role \"%s\" does not exist", "public")));
tuple = NULL; /* make compiler happy */
break;
default:
elog(ERROR, "unexpected role type %d", role->roletype);
}
return tuple;
}
/*
* Given a RoleSpec, returns a palloc'ed copy of the corresponding role's name.
*/
char *
get_rolespec_name(const RoleSpec *role)
{
HeapTuple tp;
Form_pg_authid authForm;
char *rolename;
tp = get_rolespec_tuple(role);
authForm = (Form_pg_authid) GETSTRUCT(tp);
rolename = pstrdup(NameStr(authForm->rolname));
ReleaseSysCache(tp);
return rolename;
}
/*
* Given a RoleSpec, throw an error if the name is reserved, using detail_msg,
* if provided (which must be already translated).
*
* If node is NULL, no error is thrown. If detail_msg is NULL then no detail
* message is provided.
*/
void
check_rolespec_name(const RoleSpec *role, const char *detail_msg)
{
if (!role)
return;
if (role->roletype != ROLESPEC_CSTRING)
return;
if (IsReservedName(role->rolename))
{
if (detail_msg)
ereport(ERROR,
(errcode(ERRCODE_RESERVED_NAME),
errmsg("role name \"%s\" is reserved",
role->rolename),
errdetail_internal("%s", detail_msg)));
else
ereport(ERROR,
(errcode(ERRCODE_RESERVED_NAME),
errmsg("role name \"%s\" is reserved",
role->rolename)));
}
}
|
01cfcc727cbd4d1d06f6df99cb0c6de1c557322e
|
9ceacf33fd96913cac7ef15492c126d96cae6911
|
/sys/arch/octeon/dev/cn30xxpip.c
|
5f7e472f83ca98f9fc1b51ea435d61282af2e8a2
|
[] |
no_license
|
openbsd/src
|
ab97ef834fd2d5a7f6729814665e9782b586c130
|
9e79f3a0ebd11a25b4bff61e900cb6de9e7795e9
|
refs/heads/master
| 2023-09-02T18:54:56.624627
| 2023-09-02T15:16:12
| 2023-09-02T15:16:12
| 66,966,208
| 3,394
| 1,235
| null | 2023-08-08T02:42:25
| 2016-08-30T18:18:25
|
C
|
UTF-8
|
C
| false
| false
| 6,908
|
c
|
cn30xxpip.c
|
/* $OpenBSD: cn30xxpip.c,v 1.11 2022/12/28 01:39:21 yasuoka Exp $ */
/*
* Copyright (c) 2007 Internet Initiative Japan, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS 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 AUTHORS 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/systm.h>
#include <sys/malloc.h>
#include <sys/socket.h>
#include <sys/syslog.h>
#include <sys/time.h>
#include <net/if.h>
#include <net/if_var.h>
#include <machine/octeonvar.h>
#include <octeon/dev/cn30xxgmxreg.h>
#include <octeon/dev/cn30xxpipreg.h>
#include <octeon/dev/cn30xxpipvar.h>
/* XXX */
void
cn30xxpip_init(struct cn30xxpip_attach_args *aa,
struct cn30xxpip_softc **rsc)
{
struct cn30xxpip_softc *sc;
int status;
sc = malloc(sizeof(*sc), M_DEVBUF, M_WAITOK | M_ZERO);
if (sc == NULL)
panic("can't allocate memory: %s", __func__);
sc->sc_port = aa->aa_port;
sc->sc_regt = aa->aa_regt;
sc->sc_tag_type = aa->aa_tag_type;
sc->sc_receive_group = aa->aa_receive_group;
sc->sc_ip_offset = aa->aa_ip_offset;
status = bus_space_map(sc->sc_regt, PIP_BASE, PIP_SIZE, 0,
&sc->sc_regh);
if (status != 0)
panic("can't map %s space", "pip register");
status = bus_space_subregion(sc->sc_regt, sc->sc_regh,
PIP_STAT_BASE(sc->sc_port), PIP_STAT_SIZE, &sc->sc_regh_stat);
if (status != 0)
panic("can't map stat register space");
*rsc = sc;
}
#define _PIP_RD8(sc, off) \
bus_space_read_8((sc)->sc_regt, (sc)->sc_regh, (off))
#define _PIP_WR8(sc, off, v) \
bus_space_write_8((sc)->sc_regt, (sc)->sc_regh, (off), (v))
#define _PIP_STAT_RD8(sc, off) \
bus_space_read_8((sc)->sc_regt, (sc)->sc_regh_stat, (off))
#define _PIP_STAT_WR8(sc, off, v) \
bus_space_write_8((sc)->sc_regt, (sc)->sc_regh_stat, (off), (v))
int
cn30xxpip_port_config(struct cn30xxpip_softc *sc)
{
uint64_t prt_cfg;
uint64_t prt_tag;
uint64_t ip_offset;
/*
* Process the headers and place the IP header in the work queue
*/
prt_cfg = 0;
/* RAWDRP=0; don't allow raw packet drop */
/* TAGINC=0 */
/* DYN_RS=0; disable dynamic short buffering */
/* INST_HDR=0 */
/* GRP_WAT=0 */
SET(prt_cfg, (sc->sc_port << 24) & PIP_PRT_CFGN_QOS);
/* QOS_WAT=0 */
/* SPARE=0 */
/* QOS_DIFF=0 */
/* QOS_VLAN=0 */
SET(prt_cfg, PIP_PRT_CFGN_CRC_EN);
SET(prt_cfg, (PIP_PORT_CFG_MODE_L2) & PIP_PRT_CFGN_MODE);
/* SKIP=0 */
prt_tag = 0;
SET(prt_tag, PIP_PRT_TAGN_INC_PRT);
CLR(prt_tag, PIP_PRT_TAGN_IP6_DPRT);
CLR(prt_tag, PIP_PRT_TAGN_IP4_DPRT);
CLR(prt_tag, PIP_PRT_TAGN_IP6_SPRT);
CLR(prt_tag, PIP_PRT_TAGN_IP4_SPRT);
CLR(prt_tag, PIP_PRT_TAGN_IP6_NXTH);
CLR(prt_tag, PIP_PRT_TAGN_IP4_PCTL);
CLR(prt_tag, PIP_PRT_TAGN_IP6_DST);
CLR(prt_tag, PIP_PRT_TAGN_IP4_SRC);
CLR(prt_tag, PIP_PRT_TAGN_IP6_SRC);
CLR(prt_tag, PIP_PRT_TAGN_IP4_DST);
SET(prt_tag, PIP_PRT_TAGN_TCP6_TAG_ORDERED);
SET(prt_tag, PIP_PRT_TAGN_TCP4_TAG_ORDERED);
SET(prt_tag, PIP_PRT_TAGN_IP6_TAG_ORDERED);
SET(prt_tag, PIP_PRT_TAGN_IP4_TAG_ORDERED);
SET(prt_tag, PIP_PRT_TAGN_NON_TAG_ORDERED);
SET(prt_tag, sc->sc_receive_group & PIP_PRT_TAGN_GRP);
ip_offset = 0;
SET(ip_offset, (sc->sc_ip_offset / 8) & PIP_IP_OFFSET_MASK_OFFSET);
_PIP_WR8(sc, PIP_PRT_CFG0_OFFSET + (8 * sc->sc_port), prt_cfg);
_PIP_WR8(sc, PIP_PRT_TAG0_OFFSET + (8 * sc->sc_port), prt_tag);
_PIP_WR8(sc, PIP_IP_OFFSET_OFFSET, ip_offset);
return 0;
}
void
cn30xxpip_prt_cfg_enable(struct cn30xxpip_softc *sc, uint64_t prt_cfg,
int enable)
{
uint64_t tmp;
tmp = _PIP_RD8(sc, PIP_PRT_CFG0_OFFSET + (8 * sc->sc_port));
if (enable)
tmp |= prt_cfg;
else
tmp &= ~prt_cfg;
_PIP_WR8(sc, PIP_PRT_CFG0_OFFSET + (8 * sc->sc_port), tmp);
}
void
cn30xxpip_stats_init(struct cn30xxpip_softc *sc)
{
/* XXX */
_PIP_WR8(sc, PIP_STAT_CTL_OFFSET, 1);
_PIP_STAT_WR8(sc, PIP_STAT0_PRT, 0);
_PIP_STAT_WR8(sc, PIP_STAT1_PRT, 0);
_PIP_STAT_WR8(sc, PIP_STAT2_PRT, 0);
_PIP_STAT_WR8(sc, PIP_STAT3_PRT, 0);
_PIP_STAT_WR8(sc, PIP_STAT4_PRT, 0);
_PIP_STAT_WR8(sc, PIP_STAT5_PRT, 0);
_PIP_STAT_WR8(sc, PIP_STAT6_PRT, 0);
_PIP_STAT_WR8(sc, PIP_STAT7_PRT, 0);
_PIP_STAT_WR8(sc, PIP_STAT8_PRT, 0);
_PIP_STAT_WR8(sc, PIP_STAT9_PRT, 0);
}
#if NKSTAT > 0
void
cn30xxpip_kstat_read(struct cn30xxpip_softc *sc, struct kstat_kv *kvs)
{
uint64_t val;
val = _PIP_STAT_RD8(sc, PIP_STAT0_PRT);
kstat_kv_u64(&kvs[cnmac_stat_rx_qdpo]) += (uint32_t)val;
kstat_kv_u64(&kvs[cnmac_stat_rx_qdpp]) += val >> 32;
val = _PIP_STAT_RD8(sc, PIP_STAT1_PRT);
kstat_kv_u64(&kvs[cnmac_stat_rx_toto_pip]) += (uint32_t)val;
val = _PIP_STAT_RD8(sc, PIP_STAT2_PRT);
kstat_kv_u64(&kvs[cnmac_stat_rx_raw]) += (uint32_t)val;
kstat_kv_u64(&kvs[cnmac_stat_rx_totp_pip]) += val >> 32;
val = _PIP_STAT_RD8(sc, PIP_STAT3_PRT);
kstat_kv_u64(&kvs[cnmac_stat_rx_mcast]) += (uint32_t)val;
kstat_kv_u64(&kvs[cnmac_stat_rx_bcast]) += val >> 32;
val = _PIP_STAT_RD8(sc, PIP_STAT4_PRT);
kstat_kv_u64(&kvs[cnmac_stat_rx_h64]) += (uint32_t)val;
kstat_kv_u64(&kvs[cnmac_stat_rx_h127]) += val >> 32;
val = _PIP_STAT_RD8(sc, PIP_STAT5_PRT);
kstat_kv_u64(&kvs[cnmac_stat_rx_h255]) += (uint32_t)val;
kstat_kv_u64(&kvs[cnmac_stat_rx_h511]) += val >> 32;
val = _PIP_STAT_RD8(sc, PIP_STAT6_PRT);
kstat_kv_u64(&kvs[cnmac_stat_rx_h1023]) += (uint32_t)val;
kstat_kv_u64(&kvs[cnmac_stat_rx_h1518]) += val >> 32;
val = _PIP_STAT_RD8(sc, PIP_STAT7_PRT);
kstat_kv_u64(&kvs[cnmac_stat_rx_hmax]) += (uint32_t)val;
kstat_kv_u64(&kvs[cnmac_stat_rx_fcs]) += val >> 32;
val = _PIP_STAT_RD8(sc, PIP_STAT8_PRT);
kstat_kv_u64(&kvs[cnmac_stat_rx_undersz]) += (uint32_t)val;
kstat_kv_u64(&kvs[cnmac_stat_rx_frag]) += val >> 32;
val = _PIP_STAT_RD8(sc, PIP_STAT9_PRT);
kstat_kv_u64(&kvs[cnmac_stat_rx_oversz]) += (uint32_t)val;
kstat_kv_u64(&kvs[cnmac_stat_rx_jabber]) += val >> 32;
}
#endif
|
be8ec4052ce1f4f435378c5551bf1f41a3ba587d
|
19a9f2c19bcb81c4a14ba17831d3098de7731fb5
|
/ni/src/lib/hlu/DataItem.h
|
e886b6adbb8cea43cacd6fa1cddbe3e680ebb4c4
|
[
"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
| 1,564
|
h
|
DataItem.h
|
/*
* $Id: DataItem.h,v 1.10 2004-07-23 21:24:55 dbrown Exp $
*/
/************************************************************************
* *
* Copyright (C) 1993 *
* University Corporation for Atmospheric Research *
* All Rights Reserved *
* *
************************************************************************/
/*
* File: DataItem.h
*
* Author: Jeff W. Boote
* National Center for Atmospheric Research
* PO 3000, Boulder, Colorado
*
* Date: Thu Jun 24 10:18:42 MDT 1993
*
* Description: Public declarations of the DataItem class.
*/
#ifndef _NDataItem_h
#define _NDataItem_h
#include <ncarg/hlu/Base.h>
#include <ncarg/hlu/DataMgr.h>
/*
* This type applies to 2D (or maybe eventually 3D .. nD) coordinate arrays,
* (superceded by the TransObj type NhlGridType - so this is deprecated now)
*/
typedef enum _NhldiGridType {
NhlBASICGRID,
NhlSPHERICALGRID,
NhlMESHGRID,
NhlCELLGRID,
NhlSEAMGRID
} NhldiGridType;
#define NhlTdiGridType "diGridType"
/*
* These resources are not actually in the DataItem record, but the
* names should be standardized so the names are defined here. The
* reason they are not in the DataItem record is that they don't necessarily
* apply to all DataItem's.
*/
#define NhlNdiUserData "diUserData"
#define NhlCdiUserData "DiUserData"
#define NhlCdiCopyData "DiCopyData"
#define NhlCdiMissingValue "DiMissingValue"
extern NhlBoolean NhlIsDataItem(
#if NhlNeedProto
int pid
#endif
);
extern NhlClass NhldataItemClass;
#endif /*_NDataItem_h */
|
89e165fe032d12f3c7e47babb086a507733c2107
|
0cc16f6dd7a4c1d0d225264268a1a8b13c4d82c0
|
/zathura/completion.c
|
029ccca717104b9db3031fb1d7b8e2ac1f1cf7c8
|
[
"Zlib"
] |
permissive
|
pwmt/zathura
|
da54551e7cb885861878e1e1586aaa6e22508dd2
|
c7baa2f68b4d4cd3ca8d4f879489396c05467f6b
|
refs/heads/develop
| 2023-08-31T21:40:59.783936
| 2023-07-27T16:37:18
| 2023-07-27T16:37:18
| 14,088,804
| 1,629
| 182
|
Zlib
| 2022-12-11T11:56:15
| 2013-11-03T16:35:51
|
C
|
UTF-8
|
C
| false
| false
| 11,283
|
c
|
completion.c
|
/* SPDX-License-Identifier: Zlib */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <libgen.h>
#include <glib/gi18n.h>
#include "bookmarks.h"
#include "document.h"
#include "completion.h"
#include "utils.h"
#include "page.h"
#include "database.h"
#include <girara/session.h>
#include <girara/settings.h>
#include <girara/completion.h>
#include <girara/utils.h>
#include <girara/datastructures.h>
static int
compare_case_insensitive(const char* str1, const char* str2)
{
char* ustr1 = g_utf8_casefold(str1, -1);
char* ustr2 = g_utf8_casefold(str2, -1);
int res = g_utf8_collate(ustr1, ustr2);
g_free(ustr1);
g_free(ustr2);
return res;
}
static girara_list_t*
list_files(zathura_t* zathura, const char* current_path, const char* current_file,
size_t current_file_length, bool is_dir, bool check_file_ext)
{
if (zathura == NULL || zathura->ui.session == NULL || current_path == NULL) {
return NULL;
}
girara_debug("checking files in %s", current_path);
/* read directory */
GDir* dir = g_dir_open(current_path, 0, NULL);
if (dir == NULL) {
return NULL;
}
girara_list_t* res = girara_sorted_list_new2((girara_compare_function_t)compare_case_insensitive,
(girara_free_function_t)g_free);
bool show_hidden = false;
girara_setting_get(zathura->ui.session, "show-hidden", &show_hidden);
bool show_directories = true;
girara_setting_get(zathura->ui.session, "show-directories", &show_directories);
/* read files */
const char* name = NULL;
while ((name = g_dir_read_name(dir)) != NULL) {
char* e_name = g_filename_display_name(name);
if (e_name == NULL) {
goto error_free;
}
size_t e_length = strlen(e_name);
if (show_hidden == false && e_name[0] == '.') {
g_free(e_name);
continue;
}
if ((current_file_length > e_length) || strncmp(current_file, e_name, current_file_length)) {
g_free(e_name);
continue;
}
char* tmp = "/";
if (is_dir == true || g_strcmp0(current_path, "/") == 0) {
tmp = "";
}
char* full_path = g_strdup_printf("%s%s%s", current_path, tmp, e_name);
g_free(e_name);
if (g_file_test(full_path, G_FILE_TEST_IS_DIR) == true) {
if (show_directories == false) {
girara_debug("ignoring %s (directory)", full_path);
g_free(full_path);
continue;
}
girara_debug("adding %s (directory)", full_path);
girara_list_append(res, full_path);
} else if (check_file_ext == false || file_valid_extension(zathura, full_path) == true) {
girara_debug("adding %s (file)", full_path);
girara_list_append(res, full_path);
} else {
girara_debug("ignoring %s (file)", full_path);
g_free(full_path);
}
}
g_dir_close(dir);
if (girara_list_size(res) == 1) {
char* path = girara_list_nth(res, 0);
if (g_file_test(path, G_FILE_TEST_IS_DIR) == true) {
girara_debug("changing to directory %s", path);
char* newpath = g_strdup_printf("%s/", path);
girara_list_clear(res);
girara_list_append(res, newpath);
}
}
return res;
error_free:
g_dir_close(dir);
girara_list_free(res);
return NULL;
}
static void
group_add_element(void* data, void* userdata)
{
const char* element = data;
girara_completion_group_t* group = userdata;
girara_completion_group_add_element(group, element, NULL);
}
static girara_completion_t*
list_files_for_cc(zathura_t* zathura, const char* input, bool check_file_ext, int show_recent)
{
girara_completion_t* completion = girara_completion_init();
girara_completion_group_t* group = girara_completion_group_create(zathura->ui.session, "files");
girara_completion_group_t* history_group = NULL;
gchar* path = NULL;
gchar* current_path = NULL;
if (show_recent > 0) {
history_group = girara_completion_group_create(zathura->ui.session, "recent files");
}
if (completion == NULL || group == NULL || (show_recent > 0 && history_group == NULL)) {
goto error_free;
}
path = girara_fix_path(input);
if (path == NULL) {
goto error_free;
}
/* If the path does not begin with a slash we update the path with the current
* working directory */
if (strlen(path) == 0 || path[0] != '/') {
char* cwd = g_get_current_dir();
if (cwd == NULL) {
goto error_free;
}
char* tmp_path = g_strdup_printf("%s/%s", cwd, path);
g_free(cwd);
if (tmp_path == NULL) {
goto error_free;
}
g_free(path);
path = tmp_path;
}
/* Append a slash if the given argument is a directory */
bool is_dir = (path[strlen(path) - 1] == '/') ? true : false;
if ((g_file_test(path, G_FILE_TEST_IS_DIR) == TRUE) && is_dir == false) {
char* tmp_path = g_strdup_printf("%s/", path);
g_free(path);
path = tmp_path;
is_dir = true;
}
/* get current path */
current_path = is_dir ? g_strdup(path) : g_path_get_dirname(path);
/* get current file */
gchar* current_file = is_dir ? "" : basename(path);
const size_t current_file_length = strlen(current_file);
/* read directory */
if (g_file_test(current_path, G_FILE_TEST_IS_DIR) == TRUE) {
girara_list_t* names = list_files(zathura, current_path, current_file, current_file_length, is_dir, check_file_ext);
if (names == NULL) {
goto error_free;
}
girara_list_foreach(names, group_add_element, group);
girara_list_free(names);
}
if (show_recent > 0 && zathura->database != NULL) {
girara_list_t* recent_files = zathura_db_get_recent_files(zathura->database, show_recent, path);
if (recent_files == NULL) {
goto error_free;
}
if (girara_list_size(recent_files) != 0) {
girara_list_foreach(recent_files, group_add_element, history_group);
girara_list_free(recent_files);
} else {
girara_completion_group_free(history_group);
history_group = NULL;
}
}
g_free(path);
g_free(current_path);
if (history_group != NULL) {
girara_completion_add_group(completion, history_group);
}
girara_completion_add_group(completion, group);
return completion;
error_free:
if (completion) {
girara_completion_free(completion);
}
if (history_group) {
girara_completion_group_free(history_group);
}
if (group) {
girara_completion_group_free(group);
}
g_free(current_path);
g_free(path);
return NULL;
}
girara_completion_t*
cc_open(girara_session_t* session, const char* input)
{
g_return_val_if_fail(session != NULL, NULL);
g_return_val_if_fail(session->global.data != NULL, NULL);
zathura_t* zathura = session->global.data;
int show_recent = 0;
girara_setting_get(zathura->ui.session, "show-recent", &show_recent);
return list_files_for_cc(zathura, input, true, show_recent);
}
girara_completion_t*
cc_write(girara_session_t* session, const char* input)
{
g_return_val_if_fail(session != NULL, NULL);
g_return_val_if_fail(session->global.data != NULL, NULL);
zathura_t* zathura = session->global.data;
return list_files_for_cc(zathura, input, false, false);
}
girara_completion_t*
cc_bookmarks(girara_session_t* session, const char* input)
{
if (input == NULL) {
return NULL;
}
g_return_val_if_fail(session != NULL, NULL);
g_return_val_if_fail(session->global.data != NULL, NULL);
zathura_t* zathura = session->global.data;
girara_completion_t* completion = girara_completion_init();
girara_completion_group_t* group = girara_completion_group_create(session, NULL);
if (completion == NULL || group == NULL) {
goto error_free;
}
const size_t input_length = strlen(input);
GIRARA_LIST_FOREACH_BODY(zathura->bookmarks.bookmarks, zathura_bookmark_t*, bookmark,
if (input_length <= strlen(bookmark->id) && !strncmp(input, bookmark->id, input_length)) {
gchar* paged = g_strdup_printf(_("Page %d"), bookmark->page);
girara_completion_group_add_element(group, bookmark->id, paged);
g_free(paged);
}
);
girara_completion_add_group(completion, group);
return completion;
error_free:
if (completion != NULL) {
girara_completion_free(completion);
}
if (group != NULL) {
girara_completion_group_free(group);
}
return NULL;
}
girara_completion_t*
cc_export(girara_session_t* session, const char* input)
{
g_return_val_if_fail(session != NULL, NULL);
g_return_val_if_fail(session->global.data != NULL, NULL);
zathura_t* zathura = session->global.data;
if (input == NULL || zathura->document == NULL) {
goto error_ret;
}
girara_completion_t* completion = NULL;
girara_completion_group_t* attachment_group = NULL;
girara_completion_group_t* image_group = NULL;
completion = girara_completion_init();
if (completion == NULL) {
goto error_free;
}
attachment_group = girara_completion_group_create(session, _("Attachments"));
if (attachment_group == NULL) {
goto error_free;
}
/* add attachments */
const size_t input_length = strlen(input);
girara_list_t* attachments = zathura_document_attachments_get(zathura->document, NULL);
if (attachments != NULL) {
bool added = false;
GIRARA_LIST_FOREACH_BODY(attachments, const char*, attachment,
if (input_length <= strlen(attachment) && !strncmp(input, attachment, input_length)) {
char* attachment_string = g_strdup_printf("attachment-%s", attachment);
girara_completion_group_add_element(attachment_group, attachment_string, NULL);
g_free(attachment_string);
added = true;
}
);
if (added == true) {
girara_completion_add_group(completion, attachment_group);
} else {
girara_completion_group_free(attachment_group);
attachment_group = NULL;
}
girara_list_free(attachments);
}
/* add images */
image_group = girara_completion_group_create(session, _("Images"));
if (image_group == NULL) {
goto error_free;
}
bool added = false;
unsigned int number_of_pages = zathura_document_get_number_of_pages(zathura->document);
for (unsigned int page_id = 0; page_id < number_of_pages; page_id++) {
zathura_page_t* page = zathura_document_get_page(zathura->document, page_id);
if (page == NULL) {
continue;
}
girara_list_t* images = zathura_page_images_get(page, NULL);
if (images != NULL) {
unsigned int image_number = 1;
GIRARA_LIST_FOREACH_BODY(images, zathura_image_t*, UNUSED(image),
char* image_string = g_strdup_printf("image-p%d-%d", page_id + 1, image_number);
girara_completion_group_add_element(image_group, image_string, NULL);
g_free(image_string);
added = true;
image_number++;
);
girara_list_free(images);
}
}
if (added == true) {
girara_completion_add_group(completion, image_group);
} else {
girara_completion_group_free(image_group);
image_group = NULL;
}
return completion;
error_free:
if (completion != NULL) {
girara_completion_free(completion);
}
if (attachment_group != NULL) {
girara_completion_group_free(attachment_group);
}
if (image_group != NULL) {
girara_completion_group_free(image_group);
}
error_ret:
return NULL;
}
|
17fa47c07b95791e797e2a5b67382a2fedc7516b
|
64aad94dcbb4e1704b754840ab00b6d4b1795f39
|
/src/fonts/lcdnums14x24.h
|
c6452b8d1a742d9dac15ce075c020882ccbb9a50
|
[
"MIT"
] |
permissive
|
greiman/SSD1306Ascii
|
43067efdc97adfc205de9dc3668206118c454a30
|
c43eaa9db195d17277ffc3d1ec11e3b21ba37775
|
refs/heads/master
| 2023-04-27T05:46:15.308107
| 2023-02-13T16:08:43
| 2023-02-13T16:08:43
| 38,971,157
| 464
| 124
|
MIT
| 2023-04-20T12:31:38
| 2015-07-12T17:38:58
|
C
|
UTF-8
|
C
| false
| false
| 4,645
|
h
|
lcdnums14x24.h
|
/*
* Fixed width font for numbers that looks like LCD panel digits
* This font including pad pixels, will render 14x24 pixels on the display
*
* This font is very useful when using overstrike as all characters & numbers
* are all the same width.
*
* This font is not a complete character set. The font only contains
* the characters: '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '9', ':'
*
* This font is nice for certain applications like clocks, signed values or decimal point values.
*
*/
GLCDFONTDECL(lcdnums14x24) =
{
0x0, 0x0, // size of zero indicates fixed width font
13, // width (will be 14 with pad pixel on right)
23, // height (will be 24 with pad pixel on bottom)
'+', // first char
16, // char count
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x10, 0x38, 0x38, 0x38, 0xff, 0xff, 0x38, 0x38, 0x38, 0x10, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, // +
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0x78, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00, // ,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x10, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x10, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // -
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0xe0, 0xe0, 0x40, 0x00, 0x00, 0x00, 0x00, // .
0x00, 0x00, 0x02, 0x06, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0x06, 0x02, 0x00,
0x00, 0x00, 0x10, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x10, 0x00,
0x00, 0x00, 0x80, 0xc0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xc0, 0x80, 0x00, // /
0x00, 0xfc, 0xfa, 0xf6, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0xf6, 0xfa, 0xfc,
0x00, 0xef, 0xc7, 0x83, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x83, 0xc7, 0xef,
0x00, 0x7f, 0xbf, 0xdf, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xdf, 0xbf, 0x7f, // 0
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xf8, 0xfc,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x83, 0xc7, 0xef,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x3f, 0x7f, // 1
0x00, 0x00, 0x02, 0x06, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0xf6, 0xfa, 0xfc,
0x00, 0xe0, 0xd0, 0xb8, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x3b, 0x17, 0x0f,
0x00, 0x7f, 0xbf, 0xdf, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xc0, 0x80, 0x00, // 2
0x00, 0x00, 0x02, 0x06, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0xf6, 0xfa, 0xfc,
0x00, 0x00, 0x10, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0xbb, 0xd7, 0xef,
0x00, 0x00, 0x80, 0xc0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xdf, 0xbf, 0x7f, // 3
0x00, 0xfc, 0xf8, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xf8, 0xfc,
0x00, 0x0f, 0x17, 0x3b, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0xbb, 0xd7, 0xef,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x3f, 0x7f, // 4
0x00, 0xfc, 0xfa, 0xf6, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0x06, 0x02, 0x00,
0x00, 0x0f, 0x17, 0x3b, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0xb8, 0xd0, 0xe0,
0x00, 0x00, 0x80, 0xc0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xdf, 0xbf, 0x7f, // 5
0x00, 0xfc, 0xfa, 0xf6, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0x06, 0x02, 0x00,
0x00, 0xef, 0xd7, 0xbb, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0xb8, 0xd0, 0xe0,
0x00, 0x7f, 0xbf, 0xdf, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xdf, 0xbf, 0x7f, // 6
0x00, 0x00, 0x02, 0x06, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0xf6, 0xfa, 0xfc,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x83, 0xc7, 0xef,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x3f, 0x7f, // 7
0x00, 0xfc, 0xfa, 0xf6, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0xf6, 0xfa, 0xfc,
0x00, 0xef, 0xd7, 0xbb, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0xbb, 0xd7, 0xef,
0x00, 0x7f, 0xbf, 0xdf, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xdf, 0xbf, 0x7f, // 8
0x00, 0xfc, 0xfa, 0xf6, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0xf6, 0xfa, 0xfc,
0x00, 0x0f, 0x17, 0x3b, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0xbb, 0xd7, 0xef,
0x00, 0x00, 0x80, 0xc0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xdf, 0xbf, 0x7f, // 9
0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xc0, 0xc0, 0x80, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, // :
0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x0e, 0x0e, 0x04, 0x00, 0x00, 0x00, 0x00
};
|
0863087e1684d219fe4925fa7b6b3caac9e687b6
|
fbef550c1f0206aac0582a58f7e3db945f442a9a
|
/Pods/Headers/Private/Sentry/SentryHub+Private.h
|
893a2d0891747aed49d56aefd3259f87f4c89799
|
[
"MIT"
] |
permissive
|
Hammerspoon/hammerspoon
|
0f03b4dd2ef3b44ea4c0a1cd0b94fcb513b5f2b7
|
0ccc9d07641a660140d1d2f05b76f682b501a0e8
|
refs/heads/master
| 2023-08-19T01:26:41.898873
| 2023-06-20T22:52:50
| 2023-06-20T22:52:50
| 24,956,772
| 11,379
| 676
|
MIT
| 2023-06-09T02:51:33
| 2014-10-08T19:24:44
|
Objective-C
|
UTF-8
|
C
| false
| false
| 58
|
h
|
SentryHub+Private.h
|
../../../Sentry/Sources/Sentry/include/SentryHub+Private.h
|
e5d962a180eba73c5bdf3d20abf14fe14653b931
|
9ceacf33fd96913cac7ef15492c126d96cae6911
|
/sys/dev/pci/cmpcivar.h
|
17d8dcdafedf7765cc2abb5f53511bbdc346f01c
|
[] |
no_license
|
openbsd/src
|
ab97ef834fd2d5a7f6729814665e9782b586c130
|
9e79f3a0ebd11a25b4bff61e900cb6de9e7795e9
|
refs/heads/master
| 2023-09-02T18:54:56.624627
| 2023-09-02T15:16:12
| 2023-09-02T15:16:12
| 66,966,208
| 3,394
| 1,235
| null | 2023-08-08T02:42:25
| 2016-08-30T18:18:25
|
C
|
UTF-8
|
C
| false
| false
| 8,496
|
h
|
cmpcivar.h
|
/* $OpenBSD: cmpcivar.h,v 1.7 2010/10/08 14:01:07 jakemsr Exp $ */
/* $NetBSD: cmpcivar.h,v 1.9 2005/12/11 12:22:48 christos Exp $ */
/*
* Copyright (c) 2000, 2001 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Takuya SHIOZAKI <tshiozak@NetBSD.org> .
*
* This code is derived from software contributed to The NetBSD Foundation
* by ITOH Yasufumi.
*
* 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.
*
*/
/* C-Media CMI8x38 Audio Chip Support */
#ifndef _DEV_PCI_CMPCIVAR_H_
#define _DEV_PCI_CMPCIVAR_H_
/*
* DMA pool
*/
struct cmpci_dmanode {
bus_dma_tag_t cd_tag;
int cd_nsegs;
bus_dma_segment_t cd_segs[1];
bus_dmamap_t cd_map;
caddr_t cd_addr;
size_t cd_size;
struct cmpci_dmanode *cd_next;
};
typedef struct cmpci_dmanode *cmpci_dmapool_t;
#define KVADDR(dma) ((void *)(dma)->cd_addr)
#define DMAADDR(dma) ((dma)->cd_map->dm_segs[0].ds_addr)
/*
* Mixer device
*
* Note that cmpci_query_devinfo() is optimized depending on
* the order of this. Be careful if you change the values.
*/
#define CMPCI_DAC_VOL 0 /* inputs.dac */
#define CMPCI_FM_VOL 1 /* inputs.fmsynth */
#define CMPCI_CD_VOL 2 /* inputs.cd */
#define CMPCI_LINE_IN_VOL 3 /* inputs.line */
#define CMPCI_AUX_IN_VOL 4 /* inputs.aux */
#define CMPCI_MIC_VOL 5 /* inputs.mic */
#define CMPCI_DAC_MUTE 6 /* inputs.dac.mute */
#define CMPCI_FM_MUTE 7 /* inputs.fmsynth.mute */
#define CMPCI_CD_MUTE 8 /* inputs.cd.mute */
#define CMPCI_LINE_IN_MUTE 9 /* inputs.line.mute */
#define CMPCI_AUX_IN_MUTE 10 /* inputs.aux.mute */
#define CMPCI_MIC_MUTE 11 /* inputs.mic.mute */
#define CMPCI_MIC_PREAMP 12 /* inputs.mic.preamp */
#define CMPCI_PCSPEAKER 13 /* inputs.speaker */
#define CMPCI_RECORD_SOURCE 14 /* record.source */
#define CMPCI_MIC_RECVOL 15 /* record.mic */
#define CMPCI_PLAYBACK_MODE 16 /* playback.mode */
#define CMPCI_SPDIF_IN_SELECT 17 /* spdif.input */
#define CMPCI_SPDIF_IN_PHASE 18 /* spdif.input.phase */
#define CMPCI_SPDIF_LOOP 19 /* spdif.output */
#define CMPCI_SPDIF_OUT_PLAYBACK 20 /* spdif.output.playback */
#define CMPCI_SPDIF_OUT_VOLTAGE 21 /* spdif.output.voltage */
#define CMPCI_MONITOR_DAC 22 /* spdif.monitor */
#define CMPCI_MASTER_VOL 23 /* outputs.master */
#define CMPCI_REAR 24 /* outputs.rear */
#define CMPCI_INDIVIDUAL 25 /* outputs.rear.individual */
#define CMPCI_REVERSE 26 /* outputs.rear.reverse */
#define CMPCI_SURROUND 27 /* outputs.surround */
#define CMPCI_NDEVS 28
#define CMPCI_INPUT_CLASS 28
#define CMPCI_OUTPUT_CLASS 29
#define CMPCI_RECORD_CLASS 30
#define CMPCI_PLAYBACK_CLASS 31
#define CMPCI_SPDIF_CLASS 32
#define CmpciNspdif "spdif"
#define CmpciCspdif "spdif"
#define CmpciNspdin "spdin"
#define CmpciNspdin1 "spdin1"
#define CmpciNspdin2 "spdin2"
#define CmpciNspdout "spdout"
#define CmpciNplayback "playback"
#define CmpciCplayback "playback"
#define CmpciNlegacy "legacy"
#define CmpciNvoltage "voltage"
#define CmpciNphase "phase"
#define CmpciNpositive "positive"
#define CmpciNnegative "negative"
#define CmpciNrear "rear"
#define CmpciNindividual "individual"
#define CmpciNreverse "reverse"
#define CmpciNhigh_v "5V"
#define CmpciNlow_v "0.5V"
#define CmpciNsurround "surround"
/* record.source bitmap (see cmpci_set_in_ports()) */
#define CMPCI_RECORD_SOURCE_MIC CMPCI_SB16_MIXER_MIC_SRC /* mic */
#define CMPCI_RECORD_SOURCE_CD CMPCI_SB16_MIXER_CD_SRC_R /* cd */
#define CMPCI_RECORD_SOURCE_LINE_IN CMPCI_SB16_MIXER_LINE_SRC_R /* line */
#define CMPCI_RECORD_SOURCE_AUX_IN (1 << 8) /* aux */
#define CMPCI_RECORD_SOURCE_WAVE (1 << 9) /* wave */
#define CMPCI_RECORD_SOURCE_FM CMPCI_SB16_MIXER_FM_SRC_R /* fmsynth*/
#define CMPCI_RECORD_SOURCE_SPDIF (1 << 10) /* spdif */
/* playback.mode */
#define CMPCI_PLAYBACK_MODE_WAVE 0 /* dac */
#define CMPCI_PLAYBACK_MODE_SPDIF 1 /* spdif */
/* spdif.input */
#define CMPCI_SPDIFIN_SPDIFIN2 0x01
#define CMPCI_SPDIFIN_SPDIFOUT 0x02
#define CMPCI_SPDIF_IN_SPDIN1 0 /* spdin1 */
#define CMPCI_SPDIF_IN_SPDIN2 CMPCI_SPDIFIN_SPDIFIN2 /* spdin2 */
#define CMPCI_SPDIF_IN_SPDOUT (CMPCI_SPDIFIN_SPDIFIN2|CMPCI_SPDIFIN_SPDIFOUT)
/* spdout */
/* spdif.input.phase */
#define CMPCI_SPDIF_IN_PHASE_POSITIVE 0 /* positive */
#define CMPCI_SPDIF_IN_PHASE_NEGATIVE 1 /* negative */
/* spdif.output */
#define CMPCI_SPDIF_LOOP_OFF 0 /* playback */
#define CMPCI_SPDIF_LOOP_ON 1 /* spdin */
/* spdif.output.playback */
#define CMPCI_SPDIF_OUT_PLAYBACK_WAVE 0 /* wave */
#define CMPCI_SPDIF_OUT_PLAYBACK_LEGACY 1 /* legacy */
/* spdif.output.voltage */
#define CMPCI_SPDIF_OUT_VOLTAGE_HIGH 0 /* 5V */
#define CMPCI_SPDIF_OUT_VOLTAGE_LOW 1 /* 0.5V */
/* spdif.monitor */
#define CMPCI_MONDAC_ENABLE 0x01
#define CMPCI_MONDAC_SPDOUT 0x02
#define CMPCI_MONITOR_DAC_OFF 0 /* off */
#define CMPCI_MONITOR_DAC_SPDIN CMPCI_MONDAC_ENABLE /* spdin */
#define CMPCI_MONITOR_DAC_SPDOUT (CMPCI_MONDAC_ENABLE | CMPCI_MONDAC_SPDOUT)
/* spdout */
/*
* softc
*/
/* each channel */
struct cmpci_channel {
void (*intr)(void *);
void *intr_arg;
int md_divide;
int bps;
int blksize;
int nblocks;
int swpos;
};
struct cmpci_softc {
struct device sc_dev;
/* model/rev */
uint32_t sc_id;
uint32_t sc_class;
uint32_t sc_capable;
#define CMPCI_CAP_SPDIN 0x00000001
#define CMPCI_CAP_SPDOUT 0x00000002
#define CMPCI_CAP_SPDLOOP 0x00000004
#define CMPCI_CAP_SPDLEGACY 0x00000008
#define CMPCI_CAP_SPDIN_MONITOR 0x00000010
#define CMPCI_CAP_XSPDOUT 0x00000020
#define CMPCI_CAP_SPDOUT_VOLTAGE 0x00000040
#define CMPCI_CAP_SPDOUT_48K 0x00000080
#define CMPCI_CAP_SURROUND 0x00000100
#define CMPCI_CAP_REAR 0x00000200
#define CMPCI_CAP_INDIVIDUAL_REAR 0x00000400
#define CMPCI_CAP_REVERSE_FR 0x00000800
#define CMPCI_CAP_SPDIN_PHASE 0x00001000
#define CMPCI_CAP_2ND_SPDIN 0x00002000
#define CMPCI_CAP_4CH 0x00004000
#define CMPCI_CAP_6CH 0x00008000
#define CMPCI_CAP_8CH 0x00010000
#define CMPCI_CAP_CMI8338 (CMPCI_CAP_SPDIN | CMPCI_CAP_SPDOUT | \
CMPCI_CAP_SPDLOOP | CMPCI_CAP_SPDLEGACY)
#define CMPCI_CAP_CMI8738 (CMPCI_CAP_CMI8338 | \
CMPCI_CAP_SPDIN_MONITOR | \
CMPCI_CAP_XSPDOUT | \
CMPCI_CAP_SPDOUT_VOLTAGE | \
CMPCI_CAP_SPDOUT_48K | CMPCI_CAP_SURROUND |\
CMPCI_CAP_REAR | \
CMPCI_CAP_INDIVIDUAL_REAR | \
CMPCI_CAP_REVERSE_FR | \
CMPCI_CAP_SPDIN_PHASE | \
CMPCI_CAP_2ND_SPDIN /* XXX 6ch only */)
#define CMPCI_ISCAP(sc, name) (sc->sc_capable & CMPCI_CAP_ ## name)
/* I/O Base device */
bus_space_tag_t sc_iot;
bus_space_handle_t sc_ioh;
bus_space_handle_t sc_mpu_ioh;
struct device *sc_mpudev;
/* intr handle */
pci_intr_handle_t *sc_ih;
/* DMA */
bus_dma_tag_t sc_dmat;
cmpci_dmapool_t sc_dmap;
/* each channel */
struct cmpci_channel sc_ch0, sc_ch1;
/* which channel is used for playback */
uint32_t sc_play_channel;
/* value of CMPCI_REG_MISC register */
uint32_t sc_reg_misc;
/* chip version */
uint32_t sc_version;
/* mixer */
uint8_t sc_gain[CMPCI_NDEVS][2];
#define CMPCI_LEFT 0
#define CMPCI_RIGHT 1
#define CMPCI_LR 0
uint16_t sc_in_mask;
};
#endif /* _DEV_PCI_CMPCIVAR_H_ */
/* end of file */
|
e34b0f61e807f42726d8f520b1cee77ee7ddc518
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/drivers/gpu/drm/nouveau/core/engine/disp/nv50.h
|
1ae6ceb5670403b0150f931f2cb01815a4a56569
|
[
"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
| 4,745
|
h
|
nv50.h
|
#ifndef __NV50_DISP_H__
#define __NV50_DISP_H__
#include <core/parent.h>
#include <core/namedb.h>
#include <core/engctx.h>
#include <core/ramht.h>
#include <core/event.h>
#include <engine/dmaobj.h>
#include <engine/disp.h>
#include "dport.h"
struct nv50_disp_priv {
struct nouveau_disp base;
struct nouveau_oclass *sclass;
struct work_struct supervisor;
u32 super;
struct {
int nr;
} head;
struct {
int nr;
int (*power)(struct nv50_disp_priv *, int dac, u32 data);
int (*sense)(struct nv50_disp_priv *, int dac, u32 load);
} dac;
struct {
int nr;
int (*power)(struct nv50_disp_priv *, int sor, u32 data);
int (*hda_eld)(struct nv50_disp_priv *, int sor, u8 *, u32);
int (*hdmi)(struct nv50_disp_priv *, int head, int sor, u32);
u32 lvdsconf;
const struct nouveau_dp_func *dp;
} sor;
struct {
int nr;
int (*power)(struct nv50_disp_priv *, int ext, u32 data);
u8 type[3];
const struct nouveau_dp_func *dp;
} pior;
};
#define DAC_MTHD(n) (n), (n) + 0x03
int nv50_dac_mthd(struct nouveau_object *, u32, void *, u32);
int nv50_dac_power(struct nv50_disp_priv *, int, u32);
int nv50_dac_sense(struct nv50_disp_priv *, int, u32);
#define SOR_MTHD(n) (n), (n) + 0x3f
int nva3_hda_eld(struct nv50_disp_priv *, int, u8 *, u32);
int nvd0_hda_eld(struct nv50_disp_priv *, int, u8 *, u32);
int nv84_hdmi_ctrl(struct nv50_disp_priv *, int, int, u32);
int nva3_hdmi_ctrl(struct nv50_disp_priv *, int, int, u32);
int nvd0_hdmi_ctrl(struct nv50_disp_priv *, int, int, u32);
int nv50_sor_mthd(struct nouveau_object *, u32, void *, u32);
int nv50_sor_power(struct nv50_disp_priv *, int, u32);
int nv94_sor_dp_train_init(struct nv50_disp_priv *, int, int, int, u16, u16,
u32, struct dcb_output *);
int nv94_sor_dp_train_fini(struct nv50_disp_priv *, int, int, int, u16, u16,
u32, struct dcb_output *);
int nv94_sor_dp_train(struct nv50_disp_priv *, int, int, u16, u16, u32,
struct dcb_output *);
int nv94_sor_dp_lnkctl(struct nv50_disp_priv *, int, int, int, u16, u16, u32,
struct dcb_output *);
int nv94_sor_dp_drvctl(struct nv50_disp_priv *, int, int, int, u16, u16, u32,
struct dcb_output *);
int nvd0_sor_dp_train(struct nv50_disp_priv *, int, int, u16, u16, u32,
struct dcb_output *);
int nvd0_sor_dp_lnkctl(struct nv50_disp_priv *, int, int, int, u16, u16, u32,
struct dcb_output *);
int nvd0_sor_dp_drvctl(struct nv50_disp_priv *, int, int, int, u16, u16, u32,
struct dcb_output *);
#define PIOR_MTHD(n) (n), (n) + 0x03
int nv50_pior_mthd(struct nouveau_object *, u32, void *, u32);
int nv50_pior_power(struct nv50_disp_priv *, int, u32);
struct nv50_disp_base {
struct nouveau_parent base;
struct nouveau_ramht *ramht;
u32 chan;
};
struct nv50_disp_chan {
struct nouveau_namedb base;
int chid;
};
int nv50_disp_chan_create_(struct nouveau_object *, struct nouveau_object *,
struct nouveau_oclass *, int, int, void **);
void nv50_disp_chan_destroy(struct nv50_disp_chan *);
u32 nv50_disp_chan_rd32(struct nouveau_object *, u64);
void nv50_disp_chan_wr32(struct nouveau_object *, u64, u32);
#define nv50_disp_chan_init(a) \
nouveau_namedb_init(&(a)->base)
#define nv50_disp_chan_fini(a,b) \
nouveau_namedb_fini(&(a)->base, (b))
int nv50_disp_dmac_create_(struct nouveau_object *, struct nouveau_object *,
struct nouveau_oclass *, u32, int, int, void **);
void nv50_disp_dmac_dtor(struct nouveau_object *);
struct nv50_disp_dmac {
struct nv50_disp_chan base;
struct nouveau_dmaobj *pushdma;
u32 push;
};
struct nv50_disp_pioc {
struct nv50_disp_chan base;
};
extern struct nouveau_ofuncs nv50_disp_mast_ofuncs;
extern struct nouveau_ofuncs nv50_disp_sync_ofuncs;
extern struct nouveau_ofuncs nv50_disp_ovly_ofuncs;
extern struct nouveau_ofuncs nv50_disp_oimm_ofuncs;
extern struct nouveau_ofuncs nv50_disp_curs_ofuncs;
extern struct nouveau_ofuncs nv50_disp_base_ofuncs;
extern struct nouveau_oclass nv50_disp_cclass;
void nv50_disp_intr_supervisor(struct work_struct *);
void nv50_disp_intr(struct nouveau_subdev *);
extern struct nouveau_omthds nv84_disp_base_omthds[];
extern struct nouveau_omthds nva3_disp_base_omthds[];
extern struct nouveau_ofuncs nvd0_disp_mast_ofuncs;
extern struct nouveau_ofuncs nvd0_disp_sync_ofuncs;
extern struct nouveau_ofuncs nvd0_disp_ovly_ofuncs;
extern struct nouveau_ofuncs nvd0_disp_oimm_ofuncs;
extern struct nouveau_ofuncs nvd0_disp_curs_ofuncs;
extern struct nouveau_ofuncs nvd0_disp_base_ofuncs;
extern struct nouveau_oclass nvd0_disp_cclass;
void nvd0_disp_intr_supervisor(struct work_struct *);
void nvd0_disp_intr(struct nouveau_subdev *);
#endif
|
21bd582019aa2b4dcd942239534393d2f6d22033
|
e7e2ee02a1cd3e0229346855c9aa6d931e3ca1c4
|
/src/worker/worker.h
|
d9ddda64b57f98eaedfcd35eb49711bcf1f48905
|
[
"BSD-3-Clause"
] |
permissive
|
danielealbano/cachegrand
|
7c2dd00424596796e52b62ca2e9eb107d06e0e5b
|
eb2df00feab7639a0327492c11a334a22dec7e60
|
refs/heads/main
| 2023-08-19T11:04:18.418711
| 2023-06-11T22:44:49
| 2023-06-11T22:44:49
| 125,234,630
| 904
| 33
|
BSD-3-Clause
| 2023-06-11T22:44:51
| 2018-03-14T15:33:02
|
C
|
UTF-8
|
C
| false
| false
| 1,175
|
h
|
worker.h
|
#ifndef CACHEGRAND_WORKER_H
#define CACHEGRAND_WORKER_H
#ifdef __cplusplus
extern "C" {
#endif
#define WORKER_LOG_PRODUCER_PREFIX_FORMAT_STRING "[worker][id: %02u][cpu: %02d]"
char* worker_log_producer_set_early_prefix_thread(
worker_context_t *worker_context);
void worker_setup_context(
worker_context_t *worker_context,
timespec_t *started_on_timestamp,
uint32_t workers_count,
uint32_t worker_index,
bool_volatile_t *terminate_event_loop,
bool_volatile_t *storage_db_loaded,
config_t *config,
storage_db_t *db);
bool worker_should_terminate(
worker_context_t *worker_context);
void worker_request_terminate(
worker_context_t *worker_context);
uint32_t worker_thread_set_affinity(
uint32_t worker_index);
void worker_wait_running(
worker_context_t *worker_context);
void worker_set_running(
worker_context_t *worker_context,
bool running);
void worker_set_aborted(
worker_context_t *worker_context,
bool aborted);
void* worker_thread_func(
void* user_data);
#ifdef __cplusplus
}
#endif
#endif //CACHEGRAND_WORKER_H
|
74c432dd016a23acf401cdf3e90905edb7d283b5
|
aa3befea459382dc5c01c925653d54f435b3fb0f
|
/arch/arm/src/lc823450/lc823450_sdc.c
|
bde7d69c3eed7352241ded4e46a9e81e368d3ae5
|
[
"MIT-open-group",
"BSD-3-Clause",
"HPND-sell-variant",
"BSD-4-Clause-UC",
"LicenseRef-scancode-warranty-disclaimer",
"MIT-0",
"LicenseRef-scancode-bsd-atmel",
"LicenseRef-scancode-gary-s-brown",
"LicenseRef-scancode-proprietary-license",
"SunPro",
"MIT",
"LicenseRef-scancode-public-domain-disclaimer",
"LicenseRef-scancode-other-permissive",
"HPND",
"ISC",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"GPL-1.0-or-later",
"CC-BY-2.0",
"CC-BY-4.0"
] |
permissive
|
apache/nuttx
|
14519a7bff4a87935d94fb8fb2b19edb501c7cec
|
606b6d9310fb25c7d92c6f95bf61737e3c79fa0f
|
refs/heads/master
| 2023-08-25T06:55:45.822534
| 2023-08-23T16:03:31
| 2023-08-24T21:25:47
| 228,103,273
| 407
| 241
|
Apache-2.0
| 2023-09-14T18:26:05
| 2019-12-14T23:27:55
|
C
|
UTF-8
|
C
| false
| false
| 18,050
|
c
|
lc823450_sdc.c
|
/****************************************************************************
* arch/arm/src/lc823450/lc823450_sdc.c
*
* Copyright (C) 2014-2015 ON Semiconductor. All rights reserved.
* Copyright 2014,2015,2016,2017 Sony Video & Sound Products Inc.
* Author: Masayuki Ishikawa <Masayuki.Ishikawa@jp.sony.com>
* Author: Masatoshi Tateishi <Masatoshi.Tateishi@jp.sony.com>
* Author: Nobutaka Toyoshima <Nobutaka.Toyoshima@jp.sony.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 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 NuttX 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.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <sys/types.h>
#include <assert.h>
#include <errno.h>
#include <debug.h>
#include <nuttx/clock.h>
#include <nuttx/arch.h>
#include <nuttx/mutex.h>
#include <nuttx/kthread.h>
#include <arch/board/board.h>
#include <inttypes.h>
#include <stdio.h>
#include <string.h>
#include "chip.h"
#include "arm_internal.h"
#include "lc823450_sddrv_if.h"
#include "lc823450_sdc.h"
#include "lc823450_syscontrol.h"
#include "lc823450_clockconfig.h"
#ifdef CONFIG_LED_ACCLED_SDIF
# include <nuttx/led.h>
#endif
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
#define SDIF0_BASE (0x4004A000)
#define SDIF1_BASE (0x4004B000)
#define DET_TIME (10000) /* 10ms */
/****************************************************************************
* Private Data
****************************************************************************/
static mutex_t _sdc_lock[2] =
{
NXMUTEX_INITIALIZER,
NXMUTEX_INITIALIZER,
};
static struct sddrcfg_s _sdch0;
static struct sddrcfg_s _sdch1;
static struct sddrcfg_s *_cfg[2] =
{
&_sdch0,
&_sdch1
};
static unsigned long _work0[512 / 4];
#ifdef CONFIG_LC823450_SDIF_SDC
static unsigned long _work1[512 / 4];
#endif
#ifdef CONFIG_LC823450_SDC_CACHE
static uint8_t _sec_cache_enabled;
static uint32_t _sec_cache[512 / 4];
static uint32_t _sec_cache_add = 0xffffffff;
#endif
/****************************************************************************
* Public Data
****************************************************************************/
/* ROM symbol address */
extern uint8_t cpu_ver;
extern SINT_T sddep0_hw_init(struct sddrcfg_s *);
extern SINT_T sddep0_hw_exit(struct sddrcfg_s *);
extern SINT_T sddep1_hw_init(struct sddrcfg_s *);
extern SINT_T sddep1_hw_exit(struct sddrcfg_s *);
extern SINT_T sddep_os_init(struct sddrcfg_s *);
extern SINT_T sddep_os_exit(struct sddrcfg_s *);
extern void sddep_voltage_switch(struct sddrcfg_s *cfg);
extern void sddep_set_clk(struct sddrcfg_s *);
extern SINT_T sddep_wait(UI_32, struct sddrcfg_s *);
extern SINT_T sddep_wait_status(UI_32 req, UI_32 *status,
struct sddrcfg_s *cfg);
extern SINT_T sddep_read(void *src, void *dst, UI_32 size, SINT_T type,
struct sddrcfg_s *cfg);
extern SINT_T sddep_write(void *src, void *dst, UI_32 size, SINT_T type,
struct sddrcfg_s *cfg);
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Name: _lc823450_sdc_support_trim
****************************************************************************/
static int _lc823450_sdc_support_trim(struct sddrcfg_s *cf)
{
/* NOTE: to avoid conflicts, SDDR_SUPPORT_TRIM() macro is not used here */
int ret = ((sddr_refmediatype(cf) == SDDR_MEDIA_TYPE_MMC) ?
(((cf)->ex.mmc.extcsd_sec_feature_support & (1UL << 4)) ?
1 : 0) : 0);
return ret;
}
/****************************************************************************
* Name: lc823450_sdc_access_led
****************************************************************************/
#ifdef CONFIG_LED_ACCLED_SDIF
static void lc823450_sdc_access_led(uint32_t ch, unsigned long sector)
{
if (ch == 0)
{
if (sector >= CONFIG_MTD_CP_STARTBLOCK)
{
led_start_accled(false);
}
}
else
{
led_start_accled(false);
}
}
#else
# define lc823450_sdc_access_led(a,b)
#endif
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: lc823450_sdc_clearcardinfo
****************************************************************************/
int lc823450_sdc_clearcardinfo(uint32_t ch)
{
int ret;
mcinfo("++++ start\n");
ret = nxmutex_lock(&_sdc_lock[ch]);
if (ret < 0)
{
return ret;
}
ret = sddr_clearcardinfo(_cfg[ch]);
#ifdef CONFIG_LC823450_SDC_CACHE
if (ch)
{
_sec_cache_enabled = 0;
_sec_cache_add = 0xffffffff; /* invalid */
}
#endif
nxmutex_unlock(&_sdc_lock[ch]);
mcinfo("---- end ret=%d\n", ret);
return ret;
}
/****************************************************************************
* Name: lc823450_sdc_initialize
****************************************************************************/
int lc823450_sdc_initialize(uint32_t ch)
{
int ret;
/* Only ES2 is supported */
DEBUGASSERT(1 == cpu_ver);
struct sddrcfg_s *psd = _cfg[ch];
psd->sysclk = lc823450_get_systemfreq();
psd->detecttime = DET_TIME;
#ifdef CONFIG_LC823450_SDC_UHS1
psd->setting = SDDR_SD_SWITCH_18V;
#endif
psd->deposinit = sddep_os_init;
psd->deposexit = sddep_os_exit;
psd->depsetclk = sddep_set_clk;
psd->depwait = sddep_wait;
psd->depwaitstatus = sddep_wait_status;
psd->depreaddata = sddep_read;
psd->depwritedata = sddep_write;
psd->depvoltageswitch = sddep_voltage_switch;
switch (ch)
{
case 0:
psd->dephwinit = sddep0_hw_init;
psd->dephwexit = sddep0_hw_exit;
psd->regbase = SDIF0_BASE;
psd->workbuf = _work0;
break;
#ifdef CONFIG_LC823450_SDIF_SDC
case 1:
psd->dephwinit = sddep1_hw_init;
psd->dephwexit = sddep1_hw_exit;
psd->regbase = SDIF1_BASE;
psd->workbuf = _work1;
break;
#endif
default:
DEBUGPANIC();
}
mcinfo("++++ start\n");
ret = nxmutex_lock(&_sdc_lock[ch]);
if (ret >= 0)
{
ret = sddr_initialize(_cfg[ch]);
nxmutex_unlock(&_sdc_lock[ch]);
mcinfo("---- end ret=%d\n", ret);
}
return ret;
}
/****************************************************************************
* Name: lc823450_sdc_finalize
****************************************************************************/
int lc823450_sdc_finalize(uint32_t ch)
{
int ret;
mcinfo("++++ start ch=%" PRId32 "\n", ch);
ret = nxmutex_lock(&_sdc_lock[ch]);
if (ret >= 0)
{
ret = sddr_finalize(_cfg[ch]);
nxmutex_unlock(&_sdc_lock[ch]);
mcinfo("---- end ret=%d\n", ret);
}
return ret;
}
/****************************************************************************
* Name: lc823450_sdc_identifycard
****************************************************************************/
int lc823450_sdc_identifycard(uint32_t ch)
{
int ret;
mcinfo("++++ start\n");
ret = nxmutex_lock(&_sdc_lock[ch]);
if (ret < 0)
{
return ret;
}
ret = sddr_identifycard(_cfg[ch]);
#ifdef CONFIG_LC823450_SDC_CACHE
if (ch)
{
_sec_cache_enabled = 0;
_sec_cache_add = 0xffffffff; /* invalid */
}
#endif
nxmutex_unlock(&_sdc_lock[ch]);
mcinfo("---- end ret=%d\n", ret);
return ret;
}
/****************************************************************************
* Name: lc823450_sdc_setclock
****************************************************************************/
int lc823450_sdc_setclock(uint32_t ch, uint32_t limitclk, uint32_t sysclk)
{
int ret;
mcinfo("++++ start ch=%" PRId32 " limitClk=%" PRId32
" sysClk=%" PRId32 "\n", ch, limitclk, sysclk);
ret = nxmutex_lock(&_sdc_lock[ch]);
if (ret >= 0)
{
ret = sddr_setclock(limitclk, sysclk, _cfg[ch]);
nxmutex_unlock(&_sdc_lock[ch]);
mcinfo("---- end ret=%d\n", ret);
}
return ret;
}
/****************************************************************************
* Name: lc823450_sdc_refmediatype
*
* Returned Value:
* 0(sd), 1(emmc)
*
****************************************************************************/
int lc823450_sdc_refmediatype(uint32_t ch)
{
int ret;
mcinfo("++++ start\n");
ret = nxmutex_lock(&_sdc_lock[ch]);
if (ret >= 0)
{
ret = sddr_refmediatype(_cfg[ch]);
nxmutex_unlock(&_sdc_lock[ch]);
mcinfo("---- end ret=%d\n", ret);
}
return ret;
}
/****************************************************************************
* Name: lc823450_sdc_getcardsize
****************************************************************************/
int lc823450_sdc_getcardsize(uint32_t ch,
unsigned long *psecnum, unsigned long *psecsize)
{
int ret;
mcinfo("++++ start\n");
ret = nxmutex_lock(&_sdc_lock[ch]);
if (ret >= 0)
{
ret = sddr_getcardsize(psecnum, psecsize, _cfg[ch]);
nxmutex_unlock(&_sdc_lock[ch]);
mcinfo("---- end ret=%d\n", ret);
}
return ret;
}
/****************************************************************************
* Name: lc823450_sdc_readsector
****************************************************************************/
int lc823450_sdc_readsector(uint32_t ch,
unsigned long addr, unsigned short cnt,
void *pbuf, unsigned long type)
{
int ret;
int i = 0;
ret = nxmutex_lock(&_sdc_lock[ch]);
if (ret < 0)
{
return ret;
}
#ifdef CONFIG_LC823450_SDC_LOG
mcinfo("++++ start ch=%d, addr=%ld, cnt=%d\n", ch, addr, cnt);
#endif
#ifdef CONFIG_LC823450_SDC_CACHE
if (ch && _sec_cache_enabled && 1 == cnt && addr == _sec_cache_add)
{
memcpy(pbuf, _sec_cache, sizeof(_sec_cache));
goto errout_with_lock;
}
#endif
lc823450_sdc_access_led(ch, addr);
#ifdef CONFIG_SCHED_INSTRUMENTATION_IO
sched_add_bi((uint64_t)cnt);
#endif
for (i = 0; i < 5; i++)
{
#ifdef CONFIG_LC823450_SDIF_PATCH
ret = fixed_sddr_readsector(addr, cnt, pbuf, type, _cfg[ch]);
#else
ret = sddr_readsector(addr, cnt, pbuf, type, _cfg[ch]);
#endif
if (0 == ret)
{
break;
}
mcinfo("ret=%d ch=%" PRId32 " add=%ld cnt=%d i=%d\n",
ret, ch, addr, cnt, i);
}
#ifdef CONFIG_LC823450_SDC_CACHE
if (ch)
{
if (0 == addr)
{
uint8_t *p = (pbuf + 0x1c2); /* partition id */
if (0x7 == *p)
{
mcinfo("exFAT (NTFS) detected\n");
_sec_cache_enabled = 1;
}
}
if (_sec_cache_enabled)
{
if (1 == cnt && 0 == ret)
{
memcpy(_sec_cache, pbuf, sizeof(_sec_cache));
_sec_cache_add = addr;
}
else
{
_sec_cache_add = 0xffffffff; /* invalid */
}
}
}
errout_with_lock:
#endif
nxmutex_unlock(&_sdc_lock[ch]);
mcinfo("---- end ret=%d\n", ret);
return ret;
}
/****************************************************************************
* name: lc823450_sdc_writesector
****************************************************************************/
int lc823450_sdc_writesector(uint32_t ch,
unsigned long addr, unsigned short cnt,
void *pbuf, unsigned long type)
{
int ret;
ret = nxmutex_lock(&_sdc_lock[ch]);
if (ret < 0)
{
return ret;
}
#ifdef CONFIG_LC823450_SDC_LOG
mcinfo("++++ start ch=%d, addr=%ld, cnt=%d\n", ch, addr, cnt);
#endif
#ifdef CONFIG_LC823450_SDC_CACHE
if (1 == ch && _sec_cache_enabled)
{
_sec_cache_add = 0xffffffff; /* invalid */
}
#endif
lc823450_sdc_access_led(ch, addr);
#ifdef CONFIG_SCHED_INSTRUMENTATION_IO
sched_add_bo((uint64_t)cnt);
#endif
ret = sddr_writesector(addr, cnt, pbuf, type, _cfg[ch]);
if (0 > ret)
{
mcinfo("ret=%d ch=%" PRId32 " add=%ld cnt=%d\n", ret, ch, addr, cnt);
}
nxmutex_unlock(&_sdc_lock[ch]);
mcinfo("---- end ret=%d\n", ret);
return ret;
}
/****************************************************************************
* Name: lc823450_sdc_checktrim
****************************************************************************/
int lc823450_sdc_checktrim(uint32_t ch)
{
return _lc823450_sdc_support_trim(_cfg[ch]);
}
/****************************************************************************
* Name: lc823450_sdc_trimsector
****************************************************************************/
int lc823450_sdc_trimsector(uint32_t ch, unsigned long addr,
unsigned short cnt)
{
int ret;
ret = nxmutex_lock(&_sdc_lock[ch]);
if (ret < 0)
{
return ret;
}
#ifdef CONFIG_LC823450_SDC_LOG
mcinfo("++++ start ch=%d, addr=%ld, cnt=%d\n", ch, addr, cnt);
#endif
lc823450_sdc_access_led(ch, addr);
#ifdef CONFIG_SCHED_INSTRUMENTATION_IO
sched_add_bt((uint64_t)cnt);
#endif
ret = sddr_eraseseq(0x00000001, addr, cnt, _cfg[ch]);
if (0 > ret)
{
mcinfo("ret=%d ch=%" PRId32 " add=%ld cnt=%d\n", ret, ch, addr, cnt);
}
nxmutex_unlock(&_sdc_lock[ch]);
mcinfo("---- end ret=%d\n", ret);
return ret;
}
/****************************************************************************
* Name: lc823450_sdc_cachectl
****************************************************************************/
int lc823450_sdc_cachectl(uint32_t ch, int ctrl)
{
int ret;
mcinfo("++++ ch=%" PRId32 ", ctrl=%d\n", ch, ctrl);
ret = nxmutex_lock(&_sdc_lock[ch]);
if (ret >= 0)
{
ret = sddr_cachectrl(ctrl, _cfg[ch]);
nxmutex_unlock(&_sdc_lock[ch]);
mcinfo("---- end ret=%d\n", ret);
}
return ret;
}
/****************************************************************************
* Name: lc823450_sdc_changespeedmode
****************************************************************************/
int lc823450_sdc_changespeedmode(uint32_t ch, int mode)
{
int ret;
mcinfo("++++ ch=%" PRId32 ", mode=%d\n", ch, mode);
ret = nxmutex_lock(&_sdc_lock[ch]);
if (ret < 0)
{
return ret;
}
ret = sddr_changespeedmode(mode, _cfg[ch]);
if (0 == ret)
{
switch (mode)
{
case 1: /* High Speed */
modifyreg32(SDCTL,
SDCTL_ACSMODE0_MASK << (ch * 8),
SDCTL_ACSMODE0_HS << (ch * 8));
break;
case 4: /* DDR */
modifyreg32(SDCTL,
SDCTL_ACSMODE0_MASK << (ch * 8),
SDCTL_ACSMODE0_MMCDDR << (ch * 8));
break;
}
}
nxmutex_unlock(&_sdc_lock[ch]);
mcinfo("---- end ret=%d\n", ret);
return ret;
}
/****************************************************************************
* Name: lc823450_sdc_getcid
****************************************************************************/
int lc823450_sdc_getcid(uint32_t ch, char *cidstr, int length)
{
uint8_t cid[16];
int ret;
mcinfo("++++ ch=%" PRId32 "\n", ch);
ret = nxmutex_lock(&_sdc_lock[ch]);
if (ret < 0)
{
return ret;
}
ret = sddr_getcid((UI_32 *)cid, _cfg[ch]);
if (0 == ret && length >= (2 * sizeof(cid) + 1))
{
int i;
for (i = 15; i >= 0; i--)
{
snprintf(cidstr, 3, "%02x", cid[i]);
cidstr += 2;
}
*cidstr = '\0';
}
nxmutex_unlock(&_sdc_lock[ch]);
mcinfo("---- end ret=%d\n", ret);
return ret;
}
/****************************************************************************
* Name: lc823450_sdc_locked
****************************************************************************/
int lc823450_sdc_locked(void)
{
int ret;
int i;
ret = 0;
for (i = 0; i < 2; i++)
{
if (nxmutex_is_locked(&_sdc_lock[i]))
{
ret = 1;
break;
}
}
return ret;
}
|
858f00a81c3fe101822ff9d72d8bdfeba873d541
|
dbc5fd6f0b741d07aca08cff31fe88d2f62e8483
|
/tools/clang/test/zapcc/multi/destructor-operatordelete/f.h
|
be942e67ed81b622393170fccc048816ac5c11e7
|
[
"LicenseRef-scancode-unknown-license-reference",
"NCSA"
] |
permissive
|
yrnkrn/zapcc
|
647246a2ed860f73adb49fa1bd21333d972ff76b
|
c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50
|
refs/heads/master
| 2023-03-08T22:55:12.842122
| 2020-07-21T10:21:59
| 2020-07-21T10:21:59
| 137,340,494
| 1,255
| 88
|
NOASSERTION
| 2020-07-21T10:22:01
| 2018-06-14T10:00:31
|
C++
|
UTF-8
|
C
| false
| false
| 184
|
h
|
f.h
|
#pragma once
struct Bug451Value {
virtual ~Bug451Value() {}
void operator delete(void *);
};
struct Bug451ConstantExpr : Bug451Value {
Bug451ConstantExpr() : Bug451Value() {}
};
|
de1e54f7b08931a97c895361c4dfbca771a1ec25
|
321d11eaee885ceb3a74db0a062f9bbdf282148c
|
/crypto/pkcs12/p12_asn.c
|
caae639f8835fef029df7436f3f75ff14ebd33bb
|
[
"Apache-2.0",
"OpenSSL",
"LicenseRef-scancode-proprietary-license"
] |
permissive
|
openssl/openssl
|
75691ebaae957793f2ff0673f77545277dfb3988
|
5318c012885a5382eadbf95aa9c1d35664bca819
|
refs/heads/master
| 2023-09-03T15:22:52.727123
| 2023-09-01T07:10:49
| 2023-09-02T14:30:01
| 7,634,677
| 24,148
| 11,569
|
Apache-2.0
| 2023-09-14T19:48:11
| 2013-01-15T22:34:48
|
C
|
UTF-8
|
C
| false
| false
| 3,479
|
c
|
p12_asn.c
|
/*
* Copyright 2000-2018 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/asn1t.h>
#include <openssl/pkcs12.h>
#include "p12_local.h"
#include "crypto/pkcs7.h"
/* PKCS#12 ASN1 module */
ASN1_SEQUENCE(PKCS12) = {
ASN1_SIMPLE(PKCS12, version, ASN1_INTEGER),
ASN1_SIMPLE(PKCS12, authsafes, PKCS7),
ASN1_OPT(PKCS12, mac, PKCS12_MAC_DATA)
} ASN1_SEQUENCE_END(PKCS12)
IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(PKCS12, PKCS12, PKCS12)
PKCS12 *PKCS12_new(void)
{
return (PKCS12 *)ASN1_item_new(ASN1_ITEM_rptr(PKCS12));
}
void PKCS12_free(PKCS12 *p12)
{
if (p12 != NULL && p12->authsafes != NULL) {
OPENSSL_free(p12->authsafes->ctx.propq);
p12->authsafes->ctx.propq = NULL;
}
ASN1_item_free((ASN1_VALUE *)p12, ASN1_ITEM_rptr(PKCS12));
}
ASN1_SEQUENCE(PKCS12_MAC_DATA) = {
ASN1_SIMPLE(PKCS12_MAC_DATA, dinfo, X509_SIG),
ASN1_SIMPLE(PKCS12_MAC_DATA, salt, ASN1_OCTET_STRING),
ASN1_OPT(PKCS12_MAC_DATA, iter, ASN1_INTEGER)
} ASN1_SEQUENCE_END(PKCS12_MAC_DATA)
IMPLEMENT_ASN1_FUNCTIONS(PKCS12_MAC_DATA)
ASN1_ADB_TEMPLATE(bag_default) = ASN1_EXP(PKCS12_BAGS, value.other, ASN1_ANY, 0);
ASN1_ADB(PKCS12_BAGS) = {
ADB_ENTRY(NID_x509Certificate, ASN1_EXP(PKCS12_BAGS, value.x509cert, ASN1_OCTET_STRING, 0)),
ADB_ENTRY(NID_x509Crl, ASN1_EXP(PKCS12_BAGS, value.x509crl, ASN1_OCTET_STRING, 0)),
ADB_ENTRY(NID_sdsiCertificate, ASN1_EXP(PKCS12_BAGS, value.sdsicert, ASN1_IA5STRING, 0)),
} ASN1_ADB_END(PKCS12_BAGS, 0, type, 0, &bag_default_tt, NULL);
ASN1_SEQUENCE(PKCS12_BAGS) = {
ASN1_SIMPLE(PKCS12_BAGS, type, ASN1_OBJECT),
ASN1_ADB_OBJECT(PKCS12_BAGS),
} ASN1_SEQUENCE_END(PKCS12_BAGS)
IMPLEMENT_ASN1_FUNCTIONS(PKCS12_BAGS)
ASN1_ADB_TEMPLATE(safebag_default) = ASN1_EXP(PKCS12_SAFEBAG, value.other, ASN1_ANY, 0);
ASN1_ADB(PKCS12_SAFEBAG) = {
ADB_ENTRY(NID_keyBag, ASN1_EXP(PKCS12_SAFEBAG, value.keybag, PKCS8_PRIV_KEY_INFO, 0)),
ADB_ENTRY(NID_pkcs8ShroudedKeyBag, ASN1_EXP(PKCS12_SAFEBAG, value.shkeybag, X509_SIG, 0)),
ADB_ENTRY(NID_safeContentsBag, ASN1_EXP_SEQUENCE_OF(PKCS12_SAFEBAG, value.safes, PKCS12_SAFEBAG, 0)),
ADB_ENTRY(NID_certBag, ASN1_EXP(PKCS12_SAFEBAG, value.bag, PKCS12_BAGS, 0)),
ADB_ENTRY(NID_crlBag, ASN1_EXP(PKCS12_SAFEBAG, value.bag, PKCS12_BAGS, 0)),
ADB_ENTRY(NID_secretBag, ASN1_EXP(PKCS12_SAFEBAG, value.bag, PKCS12_BAGS, 0))
} ASN1_ADB_END(PKCS12_SAFEBAG, 0, type, 0, &safebag_default_tt, NULL);
ASN1_SEQUENCE(PKCS12_SAFEBAG) = {
ASN1_SIMPLE(PKCS12_SAFEBAG, type, ASN1_OBJECT),
ASN1_ADB_OBJECT(PKCS12_SAFEBAG),
ASN1_SET_OF_OPT(PKCS12_SAFEBAG, attrib, X509_ATTRIBUTE)
} ASN1_SEQUENCE_END(PKCS12_SAFEBAG)
IMPLEMENT_ASN1_FUNCTIONS(PKCS12_SAFEBAG)
/* SEQUENCE OF SafeBag */
ASN1_ITEM_TEMPLATE(PKCS12_SAFEBAGS) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, PKCS12_SAFEBAGS, PKCS12_SAFEBAG)
ASN1_ITEM_TEMPLATE_END(PKCS12_SAFEBAGS)
/* Authsafes: SEQUENCE OF PKCS7 */
ASN1_ITEM_TEMPLATE(PKCS12_AUTHSAFES) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, PKCS12_AUTHSAFES, PKCS7)
ASN1_ITEM_TEMPLATE_END(PKCS12_AUTHSAFES)
|
7611abd7f208beb7e40a91aae29bfa8a2008823b
|
de21f9075f55640514c29ef0f1fe3f0690845764
|
/regression/cbmc/Function_Pointer_Init_Two_Candidates/main.c
|
d9b7869bc7ccc1e1300c2474faf4e883cbbe1944
|
[
"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
| 489
|
c
|
main.c
|
#include <assert.h>
int identity(int n)
{
return n;
}
int increment(int n)
{
return n + 1;
}
typedef int (*other_function_type)(int n);
void foo(other_function_type other_function)
{
// the following assertion is reachable and should fail (because of the identity case)
assert(other_function(4) == 5);
// the following assertion should succeed (satisfied by both candidates)
assert(other_function(4) >= 4);
}
int main()
{
foo(&identity);
foo(&increment);
return 0;
}
|
597cf6c92e1bf87aed6b4bcdbe0c7c2db4950f0e
|
eecd5e4c50d8b78a769bcc2675250576bed34066
|
/include/petsc/private/snesimpl.h
|
18459f7b3317295bfa7a8ae89c62c91f30a3b80d
|
[
"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
| 17,345
|
h
|
snesimpl.h
|
#ifndef __SNESIMPL_H
#define __SNESIMPL_H
#include <petscsnes.h>
#include <petsc/private/petscimpl.h>
PETSC_EXTERN PetscBool SNESRegisterAllCalled;
PETSC_EXTERN PetscErrorCode SNESRegisterAll(void);
typedef struct _SNESOps *SNESOps;
struct _SNESOps {
PetscErrorCode (*computeinitialguess)(SNES, Vec, void *);
PetscErrorCode (*computescaling)(Vec, Vec, void *);
PetscErrorCode (*update)(SNES, PetscInt); /* General purpose function for update */
PetscErrorCode (*converged)(SNES, PetscInt, PetscReal, PetscReal, PetscReal, SNESConvergedReason *, void *);
PetscErrorCode (*convergeddestroy)(void *);
PetscErrorCode (*setup)(SNES); /* routine to set up the nonlinear solver */
PetscErrorCode (*solve)(SNES); /* actual nonlinear solver */
PetscErrorCode (*view)(SNES, PetscViewer);
PetscErrorCode (*setfromoptions)(SNES, PetscOptionItems *); /* sets options from database */
PetscErrorCode (*destroy)(SNES);
PetscErrorCode (*reset)(SNES);
PetscErrorCode (*usercompute)(SNES, void **);
PetscErrorCode (*userdestroy)(void **);
PetscErrorCode (*computevariablebounds)(SNES, Vec, Vec); /* user provided routine to set box constrained variable bounds */
PetscErrorCode (*computepfunction)(SNES, Vec, Vec, void *);
PetscErrorCode (*computepjacobian)(SNES, Vec, Mat, Mat, void *);
PetscErrorCode (*load)(SNES, PetscViewer);
};
/*
Nonlinear solver context
*/
#define MAXSNESMONITORS 5
#define MAXSNESREASONVIEWS 5
struct _p_SNES {
PETSCHEADER(struct _SNESOps);
DM dm;
PetscBool dmAuto; /* SNES created currently used DM automatically */
SNES npc;
PCSide npcside;
PetscBool usesnpc; /* type can use a nonlinear preconditioner */
/* ------------------------ User-provided stuff -------------------------------*/
void *user; /* user-defined context */
Vec vec_rhs; /* If non-null, solve F(x) = rhs */
Vec vec_sol; /* pointer to solution */
Vec vec_func; /* pointer to function */
Mat jacobian; /* Jacobian matrix */
Mat jacobian_pre; /* preconditioner matrix */
Mat picard; /* copy of preconditioner matrix needed for Picard with -snes_mf_operator */
void *initialguessP; /* user-defined initial guess context */
KSP ksp; /* linear solver context */
SNESLineSearch linesearch; /* line search context */
PetscBool usesksp;
MatStructure matstruct; /* Used by Picard solver */
Vec vec_sol_update; /* pointer to solution update */
Vec scaling; /* scaling vector */
void *scaP; /* scaling context */
PetscReal precheck_picard_angle; /* For use with SNESLineSearchPreCheckPicard */
/* ------------------------Time stepping hooks-----------------------------------*/
/* ---------------- PETSc-provided (or user-provided) stuff ---------------------*/
PetscErrorCode (*monitor[MAXSNESMONITORS])(SNES, PetscInt, PetscReal, void *); /* monitor routine */
PetscErrorCode (*monitordestroy[MAXSNESMONITORS])(void **); /* monitor context destroy routine */
void *monitorcontext[MAXSNESMONITORS]; /* monitor context */
PetscInt numbermonitors; /* number of monitors */
PetscBool pauseFinal; /* pause all drawing monitor at the final iterate */
void *cnvP; /* convergence context */
SNESConvergedReason reason; /* converged reason */
PetscErrorCode (*reasonview[MAXSNESREASONVIEWS])(SNES, void *); /* snes converged reason view */
PetscErrorCode (*reasonviewdestroy[MAXSNESREASONVIEWS])(void **); /* reason view context destroy routine */
void *reasonviewcontext[MAXSNESREASONVIEWS]; /* reason view context */
PetscInt numberreasonviews; /* number of reason views */
PetscBool errorifnotconverged;
/* --- Routines and data that are unique to each particular solver --- */
PetscBool setupcalled; /* true if setup has been called */
void *data; /* implementation-specific data */
/* -------------------------- Parameters -------------------------------------- */
PetscInt max_its; /* max number of iterations */
PetscInt max_funcs; /* max number of function evals */
PetscInt nfuncs; /* number of function evaluations */
PetscInt iter; /* global iteration number */
PetscInt linear_its; /* total number of linear solver iterations */
PetscReal norm; /* residual norm of current iterate */
PetscReal ynorm; /* update norm of current iterate */
PetscReal xnorm; /* solution norm of current iterate */
PetscReal rtol; /* relative tolerance */
PetscReal divtol; /* relative divergence tolerance */
PetscReal abstol; /* absolute tolerance */
PetscReal stol; /* step length tolerance*/
PetscReal deltatol; /* trust region convergence tolerance */
PetscBool forceiteration; /* Force SNES to take at least one iteration regardless of the initial residual norm */
PetscInt lagpreconditioner; /* SNESSetLagPreconditioner() */
PetscInt lagjacobian; /* SNESSetLagJacobian() */
PetscInt jac_iter; /* The present iteration of the Jacobian lagging */
PetscBool lagjac_persist; /* The jac_iter persists until reset */
PetscInt pre_iter; /* The present iteration of the Preconditioner lagging */
PetscBool lagpre_persist; /* The pre_iter persists until reset */
PetscInt gridsequence; /* number of grid sequence steps to take; defaults to zero */
PetscBool tolerancesset; /* SNESSetTolerances() called and tolerances should persist through SNESCreate_XXX()*/
PetscBool vec_func_init_set; /* the initial function has been set */
SNESNormSchedule normschedule; /* Norm computation type for SNES instance */
SNESFunctionType functype; /* Function type for the SNES instance */
/* ------------------------ Default work-area management ---------------------- */
PetscInt nwork;
Vec *work;
/* ------------------------- Miscellaneous Information ------------------------ */
PetscInt setfromoptionscalled;
PetscReal *conv_hist; /* If !0, stores function norm (or
gradient norm) at each iteration */
PetscInt *conv_hist_its; /* linear iterations for each Newton step */
size_t conv_hist_len; /* size of convergence history array */
size_t conv_hist_max; /* actual amount of data in conv_history */
PetscBool conv_hist_reset; /* reset counter for each new SNES solve */
PetscBool conv_hist_alloc;
PetscBool counters_reset; /* reset counter for each new SNES solve */
/* the next two are used for failures in the line search; they should be put elsewhere */
PetscInt numFailures; /* number of unsuccessful step attempts */
PetscInt maxFailures; /* maximum number of unsuccessful step attempts */
PetscInt numLinearSolveFailures;
PetscInt maxLinearSolveFailures;
PetscBool domainerror; /* set with SNESSetFunctionDomainError() */
PetscBool jacobiandomainerror; /* set with SNESSetJacobianDomainError() */
PetscBool checkjacdomainerror; /* if or not check Jacobian domain error after Jacobian evaluations */
PetscBool ksp_ewconv; /* flag indicating use of Eisenstat-Walker KSP convergence criteria */
void *kspconvctx; /* Eisenstat-Walker KSP convergence context */
/* SNESConvergedDefault context: split it off into a separate var/struct to be passed as context to SNESConvergedDefault? */
PetscReal ttol; /* rtol*initial_residual_norm */
PetscReal rnorm0; /* initial residual norm (used for divergence testing) */
Vec *vwork; /* more work vectors for Jacobian approx */
PetscInt nvwork;
PetscBool mf; /* -snes_mf was used on this snes */
PetscBool mf_operator; /* -snes_mf_operator was used on this snes */
PetscInt mf_version; /* The version of snes_mf used */
PetscReal vizerotolerance; /* tolerance for considering an x[] value to be on the bound */
Vec xl, xu; /* upper and lower bounds for box constrained VI problems */
PetscInt ntruebounds; /* number of non-infinite bounds set for VI box constraints */
PetscBool usersetbounds; /* bounds have been set via SNESVISetVariableBounds(), rather than via computevariablebounds() callback. */
PetscBool alwayscomputesfinalresidual; /* Does SNESSolve_XXX always compute the value of the residual at the final
* solution and put it in vec_func? Used inside SNESSolve_FAS to determine
* if the final residual must be computed before restricting or prolonging
* it. */
};
typedef struct _p_DMSNES *DMSNES;
typedef struct _DMSNESOps *DMSNESOps;
struct _DMSNESOps {
PetscErrorCode (*computefunction)(SNES, Vec, Vec, void *);
PetscErrorCode (*computemffunction)(SNES, Vec, Vec, void *);
PetscErrorCode (*computejacobian)(SNES, Vec, Mat, Mat, void *);
/* objective */
PetscErrorCode (*computeobjective)(SNES, Vec, PetscReal *, void *);
/* Picard iteration functions */
PetscErrorCode (*computepfunction)(SNES, Vec, Vec, void *);
PetscErrorCode (*computepjacobian)(SNES, Vec, Mat, Mat, void *);
/* User-defined smoother */
PetscErrorCode (*computegs)(SNES, Vec, Vec, void *);
PetscErrorCode (*destroy)(DMSNES);
PetscErrorCode (*duplicate)(DMSNES, DMSNES);
};
struct _p_DMSNES {
PETSCHEADER(struct _DMSNESOps);
PetscContainer functionctxcontainer;
PetscContainer jacobianctxcontainer;
void *mffunctionctx;
void *gsctx;
void *pctx;
void *objectivectx;
void *data;
/* This is NOT reference counted. The DM on which this context was first created is cached here to implement one-way
* copy-on-write. When DMGetDMSNESWrite() sees a request using a different DM, it makes a copy. Thus, if a user
* only interacts directly with one level, e.g., using SNESSetFunction(), then SNESSetUp_FAS() is called to build
* coarse levels, then the user changes the routine with another call to SNESSetFunction(), it automatically
* propagates to all the levels. If instead, they get out a specific level and set the function on that level,
* subsequent changes to the original level will no longer propagate to that level.
*/
DM originaldm;
};
PETSC_EXTERN PetscErrorCode DMGetDMSNES(DM, DMSNES *);
PETSC_EXTERN PetscErrorCode DMSNESView(DMSNES, PetscViewer);
PETSC_EXTERN PetscErrorCode DMSNESLoad(DMSNES, PetscViewer);
PETSC_EXTERN PetscErrorCode DMGetDMSNESWrite(DM, DMSNES *);
/* Context for Eisenstat-Walker convergence criteria for KSP solvers */
typedef struct {
PetscInt version; /* flag indicating version (1,2,3 or 4) */
PetscReal rtol_0; /* initial rtol */
PetscReal rtol_last; /* last rtol */
PetscReal rtol_max; /* maximum rtol */
PetscReal gamma; /* mult. factor for version 2 rtol computation */
PetscReal alpha; /* power for version 2 rtol computation */
PetscReal alpha2; /* power for safeguard */
PetscReal threshold; /* threshold for imposing safeguard */
PetscReal lresid_last; /* linear residual from last iteration */
PetscReal norm_last; /* function norm from last iteration */
PetscReal norm_first; /* function norm from the beginning of the first iteration. */
PetscReal rtol_last_2, rk_last, rk_last_2;
PetscReal v4_p1, v4_p2, v4_p3, v4_m1, v4_m2, v4_m3, v4_m4;
} SNESKSPEW;
static inline PetscErrorCode SNESLogConvergenceHistory(SNES snes, PetscReal res, PetscInt its)
{
PetscFunctionBegin;
PetscCall(PetscObjectSAWsTakeAccess((PetscObject)snes));
if (snes->conv_hist && snes->conv_hist_max > snes->conv_hist_len) {
if (snes->conv_hist) snes->conv_hist[snes->conv_hist_len] = res;
if (snes->conv_hist_its) snes->conv_hist_its[snes->conv_hist_len] = its;
snes->conv_hist_len++;
}
PetscCall(PetscObjectSAWsGrantAccess((PetscObject)snes));
PetscFunctionReturn(PETSC_SUCCESS);
}
PETSC_EXTERN PetscErrorCode SNESVIProjectOntoBounds(SNES, Vec);
PETSC_INTERN PetscErrorCode SNESVICheckLocalMin_Private(SNES, Mat, Vec, Vec, PetscReal, PetscBool *);
PETSC_INTERN PetscErrorCode SNESReset_VI(SNES);
PETSC_INTERN PetscErrorCode SNESDestroy_VI(SNES);
PETSC_INTERN PetscErrorCode SNESView_VI(SNES, PetscViewer);
PETSC_INTERN PetscErrorCode SNESSetFromOptions_VI(SNES, PetscOptionItems *);
PETSC_INTERN PetscErrorCode SNESSetUp_VI(SNES);
PETSC_EXTERN_TYPEDEF typedef PetscErrorCode (*SNESVIComputeVariableBoundsFunction)(SNES, Vec, Vec);
PETSC_INTERN PetscErrorCode SNESVISetComputeVariableBounds_VI(SNES, SNESVIComputeVariableBoundsFunction);
PETSC_INTERN PetscErrorCode SNESVISetVariableBounds_VI(SNES, Vec, Vec);
PETSC_INTERN PetscErrorCode SNESConvergedDefault_VI(SNES, PetscInt, PetscReal, PetscReal, PetscReal, SNESConvergedReason *, void *);
PETSC_EXTERN PetscErrorCode DMSNESUnsetFunctionContext_Internal(DM);
PETSC_EXTERN PetscErrorCode DMSNESUnsetJacobianContext_Internal(DM);
PETSC_EXTERN PetscErrorCode DMSNESCheck_Internal(SNES, DM, Vec);
PETSC_EXTERN PetscLogEvent SNES_Solve;
PETSC_EXTERN PetscLogEvent SNES_SetUp;
PETSC_EXTERN PetscLogEvent SNES_LineSearch;
PETSC_EXTERN PetscLogEvent SNES_FunctionEval;
PETSC_EXTERN PetscLogEvent SNES_JacobianEval;
PETSC_EXTERN PetscLogEvent SNES_NGSEval;
PETSC_EXTERN PetscLogEvent SNES_NGSFuncEval;
PETSC_EXTERN PetscLogEvent SNES_NPCSolve;
PETSC_EXTERN PetscLogEvent SNES_ObjectiveEval;
PETSC_INTERN PetscBool SNEScite;
PETSC_INTERN const char SNESCitation[];
/* Used by TAOBNK solvers */
PETSC_EXTERN PetscErrorCode KSPPostSolve_SNESEW(KSP, Vec, Vec, SNES);
PETSC_EXTERN PetscErrorCode KSPPreSolve_SNESEW(KSP, Vec, Vec, SNES);
PETSC_EXTERN PetscErrorCode SNESEWSetFromOptions_Private(SNESKSPEW *, PetscBool, MPI_Comm, const char *);
/*
Either generate an error or mark as diverged when a real from a SNES function norm is Nan or Inf.
domainerror is reset here, once reason is set, to allow subsequent iterations to be feasible (e.g. line search).
*/
#define SNESCheckFunctionNorm(snes, beta) \
do { \
if (PetscIsInfOrNanReal(beta)) { \
PetscCheck(!snes->errorifnotconverged, PetscObjectComm((PetscObject)snes), PETSC_ERR_NOT_CONVERGED, "SNESSolve has not converged due to Nan or Inf norm"); \
{ \
PetscBool domainerror; \
PetscCall(MPIU_Allreduce(&snes->domainerror, &domainerror, 1, MPIU_BOOL, MPI_LOR, PetscObjectComm((PetscObject)snes))); \
if (domainerror) { \
snes->reason = SNES_DIVERGED_FUNCTION_DOMAIN; \
snes->domainerror = PETSC_FALSE; \
} else snes->reason = SNES_DIVERGED_FNORM_NAN; \
PetscFunctionReturn(PETSC_SUCCESS); \
} \
} \
} while (0)
#define SNESCheckJacobianDomainerror(snes) \
do { \
if (snes->checkjacdomainerror) { \
PetscBool domainerror; \
PetscCall(MPIU_Allreduce(&snes->jacobiandomainerror, &domainerror, 1, MPIU_BOOL, MPI_LOR, PetscObjectComm((PetscObject)snes))); \
if (domainerror) { \
snes->reason = SNES_DIVERGED_JACOBIAN_DOMAIN; \
snes->jacobiandomainerror = PETSC_FALSE; \
PetscCheck(!snes->errorifnotconverged, PetscObjectComm((PetscObject)snes), PETSC_ERR_NOT_CONVERGED, "SNESSolve has not converged due to Jacobian domain error"); \
PetscFunctionReturn(PETSC_SUCCESS); \
} \
} \
} while (0)
#define SNESCheckKSPSolve(snes) \
do { \
KSPConvergedReason kspreason; \
PetscInt lits; \
PetscCall(KSPGetIterationNumber(snes->ksp, &lits)); \
snes->linear_its += lits; \
PetscCall(KSPGetConvergedReason(snes->ksp, &kspreason)); \
if (kspreason < 0) { \
if (kspreason == KSP_DIVERGED_NANORINF) { \
PetscBool domainerror; \
PetscCall(MPIU_Allreduce(&snes->domainerror, &domainerror, 1, MPIU_BOOL, MPI_LOR, PetscObjectComm((PetscObject)snes))); \
if (domainerror) snes->reason = SNES_DIVERGED_FUNCTION_DOMAIN; \
else snes->reason = SNES_DIVERGED_LINEAR_SOLVE; \
PetscFunctionReturn(PETSC_SUCCESS); \
} else { \
if (++snes->numLinearSolveFailures >= snes->maxLinearSolveFailures) { \
PetscCall(PetscInfo(snes, "iter=%" PetscInt_FMT ", number linear solve failures %" PetscInt_FMT " greater than current SNES allowed %" PetscInt_FMT ", stopping solve\n", snes->iter, snes->numLinearSolveFailures, snes->maxLinearSolveFailures)); \
snes->reason = SNES_DIVERGED_LINEAR_SOLVE; \
PetscFunctionReturn(PETSC_SUCCESS); \
} \
} \
} \
} while (0)
#define SNESNeedNorm_Private(snes, iter) \
(((iter) == (snes)->max_its && ((snes)->normschedule == SNES_NORM_FINAL_ONLY || (snes)->normschedule == SNES_NORM_INITIAL_FINAL_ONLY)) || ((iter) == 0 && ((snes)->normschedule == SNES_NORM_INITIAL_ONLY || (snes)->normschedule == SNES_NORM_INITIAL_FINAL_ONLY)) || \
(snes)->normschedule == SNES_NORM_ALWAYS)
#endif
|
83654f687fd0c30d1ad1caf8e44992d936257089
|
72f6d3ad72b2a4a9b6c5f93c5d1b744e2940b884
|
/deps/mruby/src/opcode.h
|
fe4d17a2183ddade2b8c8cbecef066f2292f3fb9
|
[
"MIT"
] |
permissive
|
h2o/h2o
|
70012b6527ceb54e9e2819c9c75242b18e381485
|
b165770ce704c782ddee7428ea4a0b23c8bb7894
|
refs/heads/master
| 2023-08-16T13:16:35.018003
| 2023-08-16T03:56:28
| 2023-08-16T03:56:28
| 23,029,617
| 9,377
| 983
|
MIT
| 2023-09-12T04:49:14
| 2014-08-16T23:59:03
|
C
|
UTF-8
|
C
| false
| false
| 72
|
h
|
opcode.h
|
/* this header file is to be removed soon. */
#include <mruby/opcode.h>
|
f798ed4ab08ab8e427e5fe9fa4c27eb4fc89d745
|
39568e19301a7a112398be542154950af25591de
|
/sw/device/silicon_creator/rom/keys/real/rsa/earlgrey_a0_test_1.h
|
ccf10624b52c8a9a21e36278333f7edf10f90bb9
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
lowRISC/opentitan
|
493995bc7cf7cb3aee486a5203af3fd62bba3bfc
|
51f6017b8425b14d5a4aa9abace8fe5a25ef08c8
|
refs/heads/master
| 2023-08-31T22:05:09.425796
| 2023-08-14T14:52:15
| 2023-08-31T20:31:13
| 204,516,692
| 2,077
| 634
|
Apache-2.0
| 2023-09-14T21:16:21
| 2019-08-26T16:30:16
|
SystemVerilog
|
UTF-8
|
C
| false
| false
| 2,558
|
h
|
earlgrey_a0_test_1.h
|
// Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
#ifndef OPENTITAN_SW_DEVICE_SILICON_CREATOR_ROM_KEYS_REAL_RSA_EARLGREY_A0_TEST_1_H_
#define OPENTITAN_SW_DEVICE_SILICON_CREATOR_ROM_KEYS_REAL_RSA_EARLGREY_A0_TEST_1_H_
#define EARLGREY_A0_TEST_1 \
{ \
.n = \
{{ \
0x5b0036ff, 0xe4b9e817, 0x6e0d7a11, 0xea2ac57f, 0x898f21a5, \
0x33bfdf8d, 0xb40cb11b, 0x2c33bae9, 0x684e160f, 0x0777c279, \
0x6631d0c7, 0x221ce779, 0x56563c02, 0x8da8dc3c, 0x5b7ca97f, \
0x5b2c44e8, 0x5567dea8, 0xdffc0957, 0xdedc5934, 0x4cc3328c, \
0x0cbfe887, 0x04774953, 0xd067f92b, 0x6fd1b53c, 0xaff7ef99, \
0x64150738, 0xf30fdcdf, 0xaae64b83, 0x44dcd0ea, 0x5a688fb1, \
0x2f302ff8, 0x1ddbdbe6, 0x4b837fe6, 0x1c0f781c, 0x3b23758e, \
0x7b6208cc, 0x6ef6661a, 0x6c6fe4ce, 0xed5ad275, 0xe452b710, \
0xd984bf48, 0x10d7bb7f, 0xe1f5f7b9, 0xae6adfaa, 0xdce57d65, \
0xbf0681e4, 0x0bdd3fd2, 0x96bfaf68, 0x3761af8b, 0x8ad4401d, \
0xc03bf5b6, 0x6ea7b391, 0xdbf81c84, 0x4f32ae7f, 0xb12419c7, \
0xfc56c3b4, 0x20fc1f44, 0x95ed0301, 0xec7cf38f, 0xd9f54c50, \
0xb2d83d7a, 0xf930cae8, 0xf2217e62, 0x9abc29ff, 0x22709fa7, \
0x768ddf8a, 0xf321b5a4, 0xec8789d1, 0x87ec0b5d, 0x1a872448, \
0x7249a808, 0x34abbef1, 0x0900a051, 0x89c1bb28, 0xddea762d, \
0x3c1425b7, 0xca77789f, 0x98e8ea48, 0xf9fa79c4, 0x71cd0dc8, \
0x3dd10a4a, 0xb2b98079, 0x23a85455, 0xffd61602, 0x601455c5, \
0xe0f1373c, 0xccbf52b9, 0x711d8924, 0x4aeaac31, 0x990c5d66, \
0xf2525c8b, 0xfda3b948, 0x0c7ba5cf, 0x843d477b, 0x7a572ab2, \
0xaffe802f, \
}}, \
.n0_inv = { \
0x4dd13701, 0xa6af0c5c, 0xf9383743, 0x4e235dcc, \
0xa86b704b, 0x469891fb, 0x9f3e99c4, 0xb8bedf22, \
}, \
}
#endif // OPENTITAN_SW_DEVICE_SILICON_CREATOR_ROM_KEYS_REAL_RSA_EARLGREY_A0_TEST_1_H_
|
22f847eb272cd762f858b7ad27d7b24818981a3f
|
4c1a9887afb2a62b862ae954158ced183199a30e
|
/src/stlink-lib/chipid.h
|
6726a7420b8e2cd6c8a34cacae272a666631fea3
|
[
"BSD-3-Clause"
] |
permissive
|
stlink-org/stlink
|
503957cfa50e6c53d8e597fe4bc6564307f7fa9f
|
f3fcaf2553e5d99a8cc40dca55fae500cbb42050
|
refs/heads/develop
| 2023-09-04T07:06:51.760213
| 2023-09-01T20:50:35
| 2023-09-01T20:50:35
| 1,253,879
| 1,706
| 450
|
BSD-3-Clause
| 2023-09-04T14:26:31
| 2011-01-14T09:19:12
|
C
|
UTF-8
|
C
| false
| false
| 713
|
h
|
chipid.h
|
/*
* File: chipid.h
*
* Chip-ID parametres
*/
#ifndef CHIPID_H
#define CHIPID_H
/* Chipid parametres */
struct stlink_chipid_params {
char *dev_type;
char *ref_manual_id;
uint32_t chip_id;
enum stm32_flash_type flash_type;
uint32_t flash_size_reg;
uint32_t flash_pagesize;
uint32_t sram_size;
uint32_t bootrom_base;
uint32_t bootrom_size;
uint32_t option_base;
uint32_t option_size;
uint32_t flags;
struct stlink_chipid_params *next;
};
struct stlink_chipid_params *stlink_chipid_get_params(uint32_t chipid);
void dump_a_chip(struct stlink_chipid_params *dev);
void process_chipfile(char *fname);
void init_chipids(char *dir_to_scan);
#endif // CHIPID_H
|
66f4f9cd4ca7ee06762761ccbe95448f495a9f94
|
2d5743a0cc3b0ca82856d12e5576949868630031
|
/lbs-dynamodb/metadata.c
|
5fbb58896350dd699800a8fb6c4832ec5ca75d7a
|
[
"BSD-2-Clause"
] |
permissive
|
Tarsnap/kivaloo
|
20dfd70438375c7b8f8ea00a928b87c9299ae8be
|
1b4fffe65e8bdc789cb47a6191b4df33613a98e0
|
refs/heads/master
| 2023-09-03T01:26:01.625376
| 2023-08-26T18:52:14
| 2023-08-26T18:52:14
| 36,057,493
| 207
| 22
|
NOASSERTION
| 2023-08-29T18:49:29
| 2015-05-22T07:05:37
|
C
|
UTF-8
|
C
| false
| false
| 10,157
|
c
|
metadata.c
|
#include <assert.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "entropy.h"
#include "events.h"
#include "proto_dynamodb_kv.h"
#include "sysendian.h"
#include "warnp.h"
#include "metadata.h"
/* Metadata tuple. */
struct mtuple {
uint64_t nextblk;
uint64_t deletedto;
uint64_t generation;
uint64_t lastblk;
int (* callback_state)(void *);
void * cookie_state;
};
/* Internal state. */
struct metadata {
struct wire_requestqueue * Q;
struct mtuple M_stored;
struct mtuple M_storing;
struct mtuple M_latest;
uint8_t process_id[32];
int (* callback_deletedto)(void *);
void * cookie_deletedto;
int write_inprogress;
int write_wanted;
int init_done;
int init_lostrace;
uint64_t itemsz;
uint8_t tableid[32];
};
static int callback_readmetadata(void *, int, const uint8_t *, size_t);
static int callback_claimmetadata(void *, int);
static int callback_writemetadata(void *, int);
static int
callback_readmetadata(void * cookie, int status,
const uint8_t * buf, size_t len)
{
struct metadata * M = cookie;
uint8_t nbuf[104];
/* Failures are bad. */
if (status == 1)
goto err0;
/* Did the item exist? */
if (status == 2) {
warnp("metadata table is not initialized");
goto err0;
}
/* We should have 104 bytes. */
if (len != 104) {
warn0("metadata has incorrect size: %zu", len);
goto err0;
}
/* Parse it. */
M->M_stored.nextblk = be64dec(&buf[0]);
M->M_stored.deletedto = be64dec(&buf[8]);
M->M_stored.generation = be64dec(&buf[16]);
M->M_stored.lastblk = be64dec(&buf[24]);
M->itemsz = be64dec(&buf[64]);
memcpy(M->tableid, &buf[72], 32);
/* Generate a random process ID. */
if (entropy_read(M->process_id, 32)) {
warn0("Failed to generate random process ID");
goto err0;
}
/* Write new metadata back. */
memcpy(nbuf, buf, 104);
memcpy(&nbuf[32], M->process_id, 32);
if (proto_dynamodb_kv_request_icas(M->Q, "metadata", buf, 104,
nbuf, 104, callback_claimmetadata, M))
goto err0;
/* Success! */
return (0);
err0:
/* Failure! */
return (-1);
}
static int
callback_claimmetadata(void * _m, int status)
{
struct metadata * M = _m;
/* Did we succeed? */
switch (status) {
case 0:
/* Request succeeded and we won the race. */
M->init_lostrace = 0;
break;
case 1:
/* Request failed. This is bad. */
warn0("Failed to claim ownership of metadata!");
goto err0;
case 2:
/* We lost the race. */
M->init_lostrace = 1;
break;
}
/* We're done. */
M->init_done = 1;
/* Success! */
return (0);
err0:
/* Failure! */
return (-1);
}
static int
writemetadata(struct metadata * M)
{
uint8_t obuf[104];
uint8_t buf[104];
/* Is a write already in progress? */
if (M->write_inprogress == 1) {
M->write_wanted = 1;
return (0);
}
/* We're going to start a write now. */
M->write_inprogress = 1;
M->write_wanted = 0;
/* We're going to store the latest metadata values. */
M->M_storing = M->M_latest;
/* The requested callback will be performed when the store completes. */
M->M_latest.callback_state = NULL;
/* Increment metadata generation for the next metadata stored. */
M->M_latest.generation++;
/* Encode metadata. */
be64enc(&obuf[0], M->M_stored.nextblk);
be64enc(&obuf[8], M->M_stored.deletedto);
be64enc(&obuf[16], M->M_stored.generation);
be64enc(&obuf[24], M->M_stored.lastblk);
memcpy(&obuf[32], M->process_id, 32);
be64enc(&obuf[64], M->itemsz);
memcpy(&obuf[72], M->tableid, 32);
be64enc(&buf[0], M->M_storing.nextblk);
be64enc(&buf[8], M->M_storing.deletedto);
be64enc(&buf[16], M->M_storing.generation);
be64enc(&buf[24], M->M_storing.lastblk);
memcpy(&buf[32], M->process_id, 32);
be64enc(&buf[64], M->itemsz);
memcpy(&buf[72], M->tableid, 32);
/* Write metadata. */
if (proto_dynamodb_kv_request_icas(M->Q, "metadata", obuf, 104,
buf, 104, callback_writemetadata, M))
goto err0;
/* Success! */
return (0);
err0:
/* Failure! */
return (-1);
}
static int
callback_writemetadata(void * _m, int status)
{
struct metadata * M = _m;
int (* callback)(void *);
void * cookie;
int rc = 0;
int rc2;
/* Sanity-check. */
assert(M->write_inprogress);
/* Did we succeed? */
switch (status) {
case 0:
/* Request succeeded. */
break;
case 1:
/* Request failed. This is bad. */
warn0("Failed to store metadata to DynamoDB!");
goto err0;
case 2:
/* Another process stole the metadata from us. */
warn0("Lost ownership of metadata in DynamoDB!");
/*
* We could error out here, but it's safer to just abort;
* another process stealing our metadata tells us that we
* should not do anything else at all.
*/
_exit(0);
}
/* We're no longer storing metadata. */
M->write_inprogress = 0;
/* The values we were storing have now been stored. */
M->M_stored = M->M_storing;
/* Perform callbacks as appropriate. */
if (M->M_stored.callback_state != NULL) {
callback = M->M_stored.callback_state;
cookie = M->M_stored.cookie_state;
if ((rc2 = (callback)(cookie)) != 0)
rc = rc2;
}
if (M->callback_deletedto != NULL) {
callback = M->callback_deletedto;
cookie = M->cookie_deletedto;
if ((rc2 = (callback)(cookie)) != 0)
rc = rc2;
}
/* Start another write if needed. */
if (M->write_wanted) {
if ((rc2 = writemetadata(M)) != 0)
rc = rc2;
}
/* Return status from callbacks or writemetadata. */
return (rc);
err0:
/* Failure! */
return (-1);
}
/**
* metadata_init(Q, itemsz, tableid):
* Prepare for metadata operations using the queue ${Q}, and take ownership of
* the metadata item. This function may call events_run() internally. Return
* the DynamoDB item size via ${itemsz} and the table ID via ${tableid}.
*/
struct metadata *
metadata_init(struct wire_requestqueue * Q, uint64_t * itemsz,
uint8_t * tableid)
{
struct metadata * M;
/* Bake a cookie. */
if ((M = malloc(sizeof(struct metadata))) == NULL)
goto err0;
M->Q = Q;
/* Read metadata and take ownership. */
tryagain:
M->init_done = 0;
if (proto_dynamodb_kv_request_getc(Q, "metadata",
callback_readmetadata, M)) {
warnp("Error reading LBS metadata");
goto err1;
}
if (events_spin(&M->init_done)) {
warnp("Error claiming ownership of LBS metadata");
goto err1;
}
/* Did we lose a race trying to claim the metadata? */
if (M->init_lostrace) {
warn0("Lost race claiming metadata; trying again...");
goto tryagain;
}
/* The next metadata will be the same except one higher generation. */
M->M_latest = M->M_stored;
M->M_latest.generation++;
/* Nothing in progress yet. */
M->M_latest.callback_state = NULL;
M->M_latest.cookie_state = NULL;
M->callback_deletedto = NULL;
M->cookie_deletedto = NULL;
M->write_inprogress = 0;
M->write_wanted = 0;
/* Return the item size and table ID. */
*itemsz = M->itemsz;
memcpy(tableid, M->tableid, 32);
/* Success! */
return (M);
err1:
free(M);
err0:
/* Failure! */
return (NULL);
}
/**
* metadata_nextblk_read(M):
* Return the "nextblk" value.
*/
uint64_t
metadata_nextblk_read(struct metadata * M)
{
/* Return currently stored value. */
return (M->M_stored.nextblk);
}
/**
* metadata_nextblk_write(M, nextblk, callback, cookie):
* Store "nextblk" value. Invoke ${callback}(${cookie}) on success.
*/
int
metadata_nextblk_write(struct metadata * M, uint64_t nextblk,
int (*callback)(void *), void * cookie)
{
/* We shouldn't have a callback already. */
assert(M->M_latest.callback_state == NULL);
/* Record the new value and callback parameters. */
M->M_latest.nextblk = nextblk;
M->M_latest.callback_state = callback;
M->M_latest.cookie_state = cookie;
/* We want to write metadata as soon as possible. */
if (writemetadata(M))
goto err0;
/* Success! */
return (0);
err0:
/* Failure! */
return (-1);
}
/**
* metadata_lastblk_read(M):
* Return the "lastblk" value.
*/
uint64_t
metadata_lastblk_read(struct metadata * M)
{
/* Return currently stored value. */
return (M->M_stored.lastblk);
}
/**
* metadata_lastblk_write(M, lastblk, callback, cookie):
* Store "lastblk" value. Invoke ${callback}(${cookie}) on success.
*/
int
metadata_lastblk_write(struct metadata * M, uint64_t lastblk,
int (*callback)(void *), void * cookie)
{
/* We shouldn't have a callback already. */
assert(M->M_latest.callback_state == NULL);
/* Record the new value and callback parameters. */
M->M_latest.lastblk = lastblk;
M->M_latest.callback_state = callback;
M->M_latest.cookie_state = cookie;
/* We want to write metadata as soon as possible. */
if (writemetadata(M))
goto err0;
/* Success! */
return (0);
err0:
/* Failure! */
return (-1);
}
/**
* metadata_deletedto_read(M):
* Return the "deletedto" value.
*/
uint64_t
metadata_deletedto_read(struct metadata * M)
{
/* Return currently stored value. */
return (M->M_stored.deletedto);
}
/**
* metadata_deletedto_write(M, deletedto):
* Store "deletedto" value.
*/
void
metadata_deletedto_write(struct metadata * M, uint64_t deletedto)
{
/* Record the new value. */
M->M_latest.deletedto = deletedto;
}
/**
* metadata_deletedto_register(M, callback, cookie):
* Register ${callback}(${cookie}) to be called every time metadata is stored.
* This API exists for the benefit of the deletedto code; only one callback can
* be registered in this manner at once, and the callback must be reset to NULL
* before metadata_free is called.
*/
void
metadata_deletedto_register(struct metadata * M,
int (*callback)(void *), void * cookie)
{
/* Record the callback and cookie. */
M->callback_deletedto = callback;
M->cookie_deletedto = cookie;
}
/**
* metadata_flush(M):
* Trigger a flush of pending metadata updates.
*/
int
metadata_flush(struct metadata * M)
{
/* We want to write metadata as soon as possible. */
return (writemetadata(M));
}
/**
* metadata_free(M):
* Stop metadata operations.
*/
void
metadata_free(struct metadata * M)
{
/* Behave consistently with free(NULL). */
if (M == NULL)
return;
/* We shouldn't have any updates or callbacks in flight. */
assert(M->M_latest.callback_state == NULL);
assert(M->callback_deletedto == NULL);
/* Free our structure. */
free(M);
}
|
d3cac263947c3daa84c77c3f8e3e4a612daebbbd
|
676acab8ff535019faff7da3afb8eecc3fa127f5
|
/src/lib/micro-xrce-dds-client/src/c/profile/transport/ip/udp/udp_transport.c
|
a056a3f19267248ee49870d99129ec4509cd1301
|
[
"Apache-2.0"
] |
permissive
|
Firmament-Autopilot/FMT-Firmware
|
f8c324577245bd7e91af436954b4ce9421acbb41
|
0212fe89820376bfbedaded519552f6b011a7b8a
|
refs/heads/master
| 2023-09-01T11:37:46.194145
| 2023-08-29T06:33:10
| 2023-08-29T06:33:10
| 402,557,689
| 351
| 143
|
Apache-2.0
| 2023-09-12T05:28:39
| 2021-09-02T20:42:56
|
C
|
UTF-8
|
C
| false
| false
| 3,009
|
c
|
udp_transport.c
|
#include "udp_transport_internal.h"
/*******************************************************************************
* Static members.
*******************************************************************************/
static uint8_t error_code;
/*******************************************************************************
* Private function declarations.
*******************************************************************************/
static bool send_udp_msg(void* instance, const uint8_t* buf, size_t len);
static bool recv_udp_msg(void* instance, uint8_t** buf, size_t* len, int timeout);
static uint8_t get_udp_error(void);
/*******************************************************************************
* Private function definitions.
*******************************************************************************/
static bool send_udp_msg(void* instance, const uint8_t* buf, size_t len)
{
bool rv = false;
uxrUDPTransport* transport = (uxrUDPTransport*)instance;
uint8_t errcode;
size_t bytes_sent = uxr_write_udp_data_platform(transport->platform, buf, len, &errcode);
if (0 < bytes_sent) {
rv = (bytes_sent == len);
} else {
error_code = errcode;
}
return rv;
}
static bool recv_udp_msg(void* instance, uint8_t** buf, size_t* len, int timeout)
{
bool rv = false;
uxrUDPTransport* transport = (uxrUDPTransport*)instance;
uint8_t errcode;
size_t bytes_received = uxr_read_udp_data_platform(transport->platform,
transport->buffer,
sizeof(transport->buffer),
timeout,
&errcode);
if (0 < bytes_received) {
*buf = transport->buffer;
*len = bytes_received;
rv = true;
} else {
error_code = errcode;
}
return rv;
}
static uint8_t get_udp_error(void)
{
return error_code;
}
/*******************************************************************************
* Public function definitions.
*******************************************************************************/
bool uxr_init_udp_transport(
uxrUDPTransport* transport,
struct uxrUDPPlatform* platform,
uxrIpProtocol ip_protocol,
const char* ip,
const char* port)
{
bool rv = false;
if (uxr_init_udp_platform(platform, ip_protocol, ip, port)) {
/* Setup platform. */
transport->platform = platform;
/* Setup interface. */
transport->comm.instance = (void*)transport;
transport->comm.send_msg = send_udp_msg;
transport->comm.recv_msg = recv_udp_msg;
transport->comm.comm_error = get_udp_error;
transport->comm.mtu = UXR_CONFIG_UDP_TRANSPORT_MTU;
rv = true;
}
return rv;
}
bool uxr_close_udp_transport(uxrUDPTransport* transport)
{
return uxr_close_udp_platform(transport->platform);
}
|
f772e9e414cf7b770dfb0d4c5f6bd03df31ac662
|
e814383d36a10839104efaa4df277996ab220fa3
|
/opal/mca/smsc/base/smsc_base_frame.c
|
ea41b63f05a6d3d1b97bd6f7595c3ddf89fbb43c
|
[
"mpich2",
"BSD-3-Clause-Open-MPI"
] |
permissive
|
open-mpi/ompi
|
a1d7483ae1d83dd8fd8ae3ee95e832e0a0ee04e3
|
1edfdb025c4450f694600083ad871cf06c8d45cd
|
refs/heads/main
| 2023-09-01T01:30:02.040705
| 2023-08-29T17:32:18
| 2023-08-29T17:32:18
| 24,107,001
| 2,008
| 973
|
NOASSERTION
| 2023-09-14T20:59:26
| 2014-09-16T16:08:30
|
C
|
UTF-8
|
C
| false
| false
| 5,339
|
c
|
smsc_base_frame.c
|
/*
* Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana
* University Research and Technology
* Corporation. All rights reserved.
* Copyright (c) 2004-2005 The University of Tennessee and The University
* of Tennessee Research Foundation. All rights
* reserved.
* Copyright (c) 2004-2005 High Performance Computing Center Stuttgart,
* University of Stuttgart. All rights reserved.
* Copyright (c) 2004-2005 The Regents of the University of California.
* All rights reserved.
* Copyright (c) 2021 Google, LLC. All rights reserved.
* Copyright (c) 2022 IBM Corporation. All rights reserved.
* $COPYRIGHT$
*
* Additional copyrights may follow
*
* $HEADER$
*/
#include "opal_config.h"
#include <stdio.h>
#include <string.h>
#include "opal/class/opal_list.h"
#include "opal/mca/base/base.h"
#include "opal/mca/mca.h"
#include "opal/mca/smsc/base/base.h"
#include "opal/mca/smsc/smsc.h"
#include "opal/util/printf.h"
/*
* The following file was created by configure. It contains extern
* statements and the definition of an array of pointers to each
* component's public mca_base_component_t struct.
*/
#include "opal/mca/smsc/base/static-components.h"
static mca_smsc_component_t *selected_component = NULL;
mca_smsc_module_t *mca_smsc = NULL;
/*
* Global variables
*/
MCA_BASE_FRAMEWORK_DECLARE(opal, smsc, NULL, NULL, NULL, NULL, mca_smsc_base_static_components, 0);
static int mca_smsc_compare_components(opal_list_item_t **a, opal_list_item_t **b)
{
mca_smsc_component_t *componenta
= (mca_smsc_component_t *) ((mca_base_component_list_item_t *) *a)->cli_component;
mca_smsc_component_t *componentb
= (mca_smsc_component_t *) ((mca_base_component_list_item_t *) *b)->cli_component;
return (componenta->priority > componentb->priority)
? -1
: ((componenta->priority < componentb->priority) ? 1 : 0);
}
int mca_smsc_base_select(void)
{
mca_base_component_list_item_t *cli, *next;
OPAL_LIST_FOREACH_SAFE (cli, next, &opal_smsc_base_framework.framework_components,
mca_base_component_list_item_t) {
mca_smsc_component_t *component = (mca_smsc_component_t *) cli->cli_component;
opal_output_verbose(MCA_BASE_VERBOSE_COMPONENT, opal_smsc_base_framework.framework_output,
"mca_smsc_base_select: checking component %s",
component->smsc_version.mca_component_name);
int ret = component->query();
if (OPAL_SUCCESS != ret) {
opal_output_verbose(MCA_BASE_VERBOSE_COMPONENT,
opal_smsc_base_framework.framework_output,
"mca_smsc_base_select: could not select component %s. query "
"returned error code %d",
component->smsc_version.mca_component_name, ret);
opal_list_remove_item(&opal_smsc_base_framework.framework_components, &cli->super);
OBJ_RELEASE(cli);
mca_base_component_close(&component->smsc_version,
opal_smsc_base_framework.framework_output);
continue;
}
opal_output_verbose(MCA_BASE_VERBOSE_COMPONENT, opal_smsc_base_framework.framework_output,
"mca_smsc_base_select: component %s priority=%d",
component->smsc_version.mca_component_name, component->priority);
}
opal_list_sort(&opal_smsc_base_framework.framework_components, mca_smsc_compare_components);
if (opal_list_get_size(&opal_smsc_base_framework.framework_components) > 0) {
cli = (mca_base_component_list_item_t *) opal_list_get_first(
&opal_smsc_base_framework.framework_components);
selected_component = (mca_smsc_component_t *) cli->cli_component;
mca_smsc = selected_component->enable();
opal_output_verbose(
MCA_BASE_VERBOSE_COMPONENT, opal_smsc_base_framework.framework_output,
"mca_smsc_base_select: selected shared-memory single-copy component: %s",
selected_component->smsc_version.mca_component_name);
} else {
opal_output_verbose(
MCA_BASE_VERBOSE_COMPONENT, opal_smsc_base_framework.framework_output,
"mca_smsc_base_select: no shared-memory single-copy component available for selection");
}
return OPAL_SUCCESS;
}
void mca_smsc_base_register_default_params(mca_smsc_component_t *component, int default_priority)
{
char *tmp;
(void) opal_asprintf(&tmp, "Priority of the %s component (default: %d)",
component->smsc_version.mca_component_name, default_priority);
component->priority = default_priority;
(void) mca_base_component_var_register(&component->smsc_version, "priority", /*help_msg=*/tmp,
MCA_BASE_VAR_TYPE_INT, /*enumerator=*/NULL, /*bind=*/0,
MCA_BASE_VAR_FLAG_SETTABLE, OPAL_INFO_LVL_3,
MCA_BASE_VAR_SCOPE_ALL_EQ, &component->priority);
free(tmp);
}
|
582fc5ed53a98c514cd5a4f684c00898fb4e67d4
|
03666e5f961946fc1a0ac67781ac1425562ef0d7
|
/src/mdserver/main/QuitRPCExecutor.C
|
6cc132f70e8059f38605ca1ca2f47013c18bb366
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
visit-dav/visit
|
e9f81b4d4b9b9930a0db9d5282cd1bcabf465e2e
|
601ae46e0bef2e18425b482a755d03490ade0493
|
refs/heads/develop
| 2023-09-06T08:19:38.397058
| 2023-09-05T21:29:32
| 2023-09-05T21:29:32
| 165,565,988
| 335
| 120
|
BSD-3-Clause
| 2023-09-14T00:53:37
| 2019-01-13T23:27:26
|
C
|
UTF-8
|
C
| false
| false
| 1,927
|
c
|
QuitRPCExecutor.C
|
// Copyright (c) Lawrence Livermore National Security, LLC and other VisIt
// Project developers. See the top-level LICENSE file for dates and other
// details. No copyright assignment is required to contribute to VisIt.
#ifdef DEBUG
#include <visitstream.h>
#endif
#include <QuitRPCExecutor.h>
#include <QuitRPC.h>
// ****************************************************************************
// Method: QuitRPCExecutor::QuitRPCExecutor
//
// Purpose:
// Constructor for the QuitRPCExecutor class.
//
// Arguments:
// s : A pointer to the QuitRPC object that this executor observes.
//
// Programmer: Jeremy Meredith
// Creation: August 29, 2000
//
// Modifications:
//
// ****************************************************************************
QuitRPCExecutor::QuitRPCExecutor(Subject *s) : Observer(s)
{
}
// ****************************************************************************
// Method: QuitRPCExecutor::~QuitRPCExecutor
//
// Purpose:
// Destructor for the QuitRPCExecutor class.
//
// Programmer: Brad Whitlock
// Creation: Fri Nov 17 16:04:03 PST 2000
//
// Modifications:
//
// ****************************************************************************
QuitRPCExecutor::~QuitRPCExecutor()
{
}
// ****************************************************************************
// Method: QuitRPCExecutor::Update
//
// Purpose:
// Does the work for the QuitRPC.
//
// Arguments:
// s : A pointer to the QuitRPC that caused this method to be called.
//
// Programmer: Brad Whitlock
// Creation: Fri Nov 17 16:05:35 PST 2000
//
// Modifications:
//
// ****************************************************************************
void
QuitRPCExecutor::Update(Subject *s)
{
QuitRPC *quit = (QuitRPC *)s;
#ifdef DEBUG
cout << "QuitRPCExecutor::Update\n"; cout.flush();
#endif
if(!quit->GetQuit())
quit->SendError();
else
quit->SendReply();
}
|
edd548c3ad1820067c9fdfb57fe6229dc845fb45
|
79d343002bb63a44f8ab0dbac0c9f4ec54078c3a
|
/lib/libc/include/any-linux-any/linux/udmabuf.h
|
4178559689ff9c4757f76ee3f71b7ff634c3ca8c
|
[
"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
| 642
|
h
|
udmabuf.h
|
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
#ifndef _LINUX_UDMABUF_H
#define _LINUX_UDMABUF_H
#include <linux/types.h>
#include <linux/ioctl.h>
#define UDMABUF_FLAGS_CLOEXEC 0x01
struct udmabuf_create {
__u32 memfd;
__u32 flags;
__u64 offset;
__u64 size;
};
struct udmabuf_create_item {
__u32 memfd;
__u32 __pad;
__u64 offset;
__u64 size;
};
struct udmabuf_create_list {
__u32 flags;
__u32 count;
struct udmabuf_create_item list[];
};
#define UDMABUF_CREATE _IOW('u', 0x42, struct udmabuf_create)
#define UDMABUF_CREATE_LIST _IOW('u', 0x43, struct udmabuf_create_list)
#endif /* _LINUX_UDMABUF_H */
|
8ac23560586141d66a7d71991550115f6d070c25
|
e1cddfd754d952134e72dfd03522c5ea4fb6008e
|
/src/vnet/session/session_api.c
|
55fc72ee4c2b4ef6bdfde32df5bced9b2bf964ee
|
[
"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
| 50,722
|
c
|
session_api.c
|
/*
* Copyright (c) 2015-2019 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <vnet/vnet.h>
#include <vlibmemory/api.h>
#include <vnet/session/application.h>
#include <vnet/session/application_interface.h>
#include <vnet/session/application_local.h>
#include <vnet/session/session_rules_table.h>
#include <vnet/session/session_table.h>
#include <vnet/session/session.h>
#include <vnet/ip/ip_types_api.h>
#include <vnet/format_fns.h>
#include <vnet/session/session.api_enum.h>
#include <vnet/session/session.api_types.h>
#define REPLY_MSG_ID_BASE session_main.msg_id_base
#include <vlibapi/api_helper_macros.h>
static transport_proto_t
api_session_transport_proto_decode (const vl_api_transport_proto_t * api_tp)
{
switch (*api_tp)
{
case TRANSPORT_PROTO_API_TCP:
return TRANSPORT_PROTO_TCP;
case TRANSPORT_PROTO_API_UDP:
return TRANSPORT_PROTO_UDP;
case TRANSPORT_PROTO_API_TLS:
return TRANSPORT_PROTO_TLS;
case TRANSPORT_PROTO_API_QUIC:
return TRANSPORT_PROTO_QUIC;
default:
return TRANSPORT_PROTO_NONE;
}
}
static vl_api_transport_proto_t
api_session_transport_proto_encode (const transport_proto_t tp)
{
switch (tp)
{
case TRANSPORT_PROTO_TCP:
return TRANSPORT_PROTO_API_TCP;
case TRANSPORT_PROTO_UDP:
return TRANSPORT_PROTO_API_UDP;
case TRANSPORT_PROTO_TLS:
return TRANSPORT_PROTO_API_TLS;
case TRANSPORT_PROTO_QUIC:
return TRANSPORT_PROTO_API_QUIC;
default:
return TRANSPORT_PROTO_API_NONE;
}
}
static int
session_send_fds (vl_api_registration_t * reg, int fds[], int n_fds)
{
clib_error_t *error;
if (vl_api_registration_file_index (reg) == VL_API_INVALID_FI)
return SESSION_E_BAPI_NO_FD;
error = vl_api_send_fd_msg (reg, fds, n_fds);
if (error)
{
clib_error_report (error);
return SESSION_E_BAPI_SEND_FD;
}
return 0;
}
static int
mq_send_session_accepted_cb (session_t * s)
{
app_worker_t *app_wrk = app_worker_get (s->app_wrk_index);
session_accepted_msg_t m = { 0 };
fifo_segment_t *eq_seg;
session_t *listener;
application_t *app;
app = application_get (app_wrk->app_index);
m.context = app->app_index;
m.server_rx_fifo = fifo_segment_fifo_offset (s->rx_fifo);
m.server_tx_fifo = fifo_segment_fifo_offset (s->tx_fifo);
m.segment_handle = session_segment_handle (s);
m.flags = s->flags;
eq_seg = application_get_rx_mqs_segment (app);
if (session_has_transport (s))
{
listener = listen_session_get_from_handle (s->listener_handle);
m.listener_handle = app_listen_session_handle (listener);
if (application_is_proxy (app))
{
listener =
app_worker_first_listener (app_wrk, session_get_fib_proto (s),
session_get_transport_proto (s));
if (listener)
m.listener_handle = listen_session_get_handle (listener);
}
m.vpp_event_queue_address =
fifo_segment_msg_q_offset (eq_seg, s->thread_index);
m.mq_index = s->thread_index;
m.handle = session_handle (s);
session_get_endpoint (s, &m.rmt, 0 /* is_lcl */);
session_get_endpoint (s, &m.lcl, 1 /* is_lcl */);
}
else
{
ct_connection_t *ct;
ct = (ct_connection_t *) session_get_transport (s);
listener = listen_session_get_from_handle (s->listener_handle);
m.listener_handle = app_listen_session_handle (listener);
m.rmt.is_ip4 = session_type_is_ip4 (listener->session_type);
m.rmt.port = ct->c_rmt_port;
m.lcl.port = ct->c_lcl_port;
m.handle = session_handle (s);
m.vpp_event_queue_address =
fifo_segment_msg_q_offset (eq_seg, s->thread_index);
m.mq_index = s->thread_index;
}
if (application_original_dst_is_enabled (app))
{
session_get_original_dst (&m.lcl, &m.rmt,
session_get_transport_proto (s),
&m.original_dst_ip4, &m.original_dst_port);
}
app_wrk_send_ctrl_evt (app_wrk, SESSION_CTRL_EVT_ACCEPTED, &m, sizeof (m));
return 0;
}
static inline void
mq_send_session_close_evt (app_worker_t * app_wrk, session_handle_t sh,
session_evt_type_t evt_type)
{
session_disconnected_msg_t m = { 0 };
m.handle = sh;
m.context = app_wrk->api_client_index;
app_wrk_send_ctrl_evt (app_wrk, evt_type, &m, sizeof (m));
}
static inline void
mq_notify_close_subscribers (u32 app_index, session_handle_t sh,
svm_fifo_t * f, session_evt_type_t evt_type)
{
app_worker_t *app_wrk;
application_t *app;
int i;
app = application_get (app_index);
if (!app)
return;
for (i = 0; i < f->shr->n_subscribers; i++)
{
if (!(app_wrk = application_get_worker (app, f->shr->subscribers[i])))
continue;
mq_send_session_close_evt (app_wrk, sh, SESSION_CTRL_EVT_DISCONNECTED);
}
}
static void
mq_send_session_disconnected_cb (session_t * s)
{
app_worker_t *app_wrk = app_worker_get (s->app_wrk_index);
session_handle_t sh = session_handle (s);
mq_send_session_close_evt (app_wrk, session_handle (s),
SESSION_CTRL_EVT_DISCONNECTED);
if (svm_fifo_n_subscribers (s->rx_fifo))
mq_notify_close_subscribers (app_wrk->app_index, sh, s->rx_fifo,
SESSION_CTRL_EVT_DISCONNECTED);
}
static void
mq_send_session_reset_cb (session_t * s)
{
app_worker_t *app_wrk = app_worker_get (s->app_wrk_index);
session_handle_t sh = session_handle (s);
mq_send_session_close_evt (app_wrk, sh, SESSION_CTRL_EVT_RESET);
if (svm_fifo_n_subscribers (s->rx_fifo))
mq_notify_close_subscribers (app_wrk->app_index, sh, s->rx_fifo,
SESSION_CTRL_EVT_RESET);
}
int
mq_send_session_connected_cb (u32 app_wrk_index, u32 api_context,
session_t * s, session_error_t err)
{
session_connected_msg_t m = { 0 };
transport_connection_t *tc;
fifo_segment_t *eq_seg;
app_worker_t *app_wrk;
application_t *app;
app_wrk = app_worker_get (app_wrk_index);
m.context = api_context;
m.retval = err;
if (err)
goto snd_msg;
app = application_get (app_wrk->app_index);
eq_seg = application_get_rx_mqs_segment (app);
if (session_has_transport (s))
{
tc = session_get_transport (s);
if (!tc)
{
clib_warning ("failed to retrieve transport!");
m.retval = SESSION_E_REFUSED;
goto snd_msg;
}
m.handle = session_handle (s);
m.vpp_event_queue_address =
fifo_segment_msg_q_offset (eq_seg, s->thread_index);
session_get_endpoint (s, &m.lcl, 1 /* is_lcl */);
m.server_rx_fifo = fifo_segment_fifo_offset (s->rx_fifo);
m.server_tx_fifo = fifo_segment_fifo_offset (s->tx_fifo);
m.segment_handle = session_segment_handle (s);
m.mq_index = s->thread_index;
}
else
{
ct_connection_t *cct;
session_t *ss;
cct = (ct_connection_t *) session_get_transport (s);
m.handle = session_handle (s);
m.lcl.port = cct->c_lcl_port;
m.lcl.is_ip4 = cct->c_is_ip4;
m.vpp_event_queue_address =
fifo_segment_msg_q_offset (eq_seg, s->thread_index);
m.server_rx_fifo = fifo_segment_fifo_offset (s->rx_fifo);
m.server_tx_fifo = fifo_segment_fifo_offset (s->tx_fifo);
m.segment_handle = session_segment_handle (s);
ss = ct_session_get_peer (s);
m.ct_rx_fifo = fifo_segment_fifo_offset (ss->tx_fifo);
m.ct_tx_fifo = fifo_segment_fifo_offset (ss->rx_fifo);
m.ct_segment_handle = session_segment_handle (ss);
m.mq_index = s->thread_index;
}
/* Setup client session index in advance, in case data arrives
* before the app processes message and updates it */
s->rx_fifo->shr->client_session_index = api_context;
s->tx_fifo->shr->client_session_index = api_context;
snd_msg:
app_wrk_send_ctrl_evt (app_wrk, SESSION_CTRL_EVT_CONNECTED, &m, sizeof (m));
return 0;
}
int
mq_send_session_bound_cb (u32 app_wrk_index, u32 api_context,
session_handle_t handle, int rv)
{
session_bound_msg_t m = { 0 };
transport_endpoint_t tep;
fifo_segment_t *eq_seg;
app_worker_t *app_wrk;
application_t *app;
app_listener_t *al;
session_t *ls = 0;
app_wrk = app_worker_get (app_wrk_index);
m.context = api_context;
m.retval = rv;
if (rv)
goto snd_msg;
m.handle = handle;
al = app_listener_get_w_handle (handle);
if (al->session_index != SESSION_INVALID_INDEX)
ls = app_listener_get_session (al);
else
ls = app_listener_get_local_session (al);
session_get_endpoint (ls, &tep, 1 /* is_lcl */);
m.lcl_port = tep.port;
m.lcl_is_ip4 = tep.is_ip4;
clib_memcpy_fast (m.lcl_ip, &tep.ip, sizeof (tep.ip));
app = application_get (app_wrk->app_index);
eq_seg = application_get_rx_mqs_segment (app);
m.vpp_evt_q = fifo_segment_msg_q_offset (eq_seg, ls->thread_index);
m.mq_index = ls->thread_index;
if (session_transport_service_type (ls) == TRANSPORT_SERVICE_CL &&
ls->rx_fifo)
{
m.mq_index = transport_cl_thread ();
m.vpp_evt_q = fifo_segment_msg_q_offset (eq_seg, m.mq_index);
m.rx_fifo = fifo_segment_fifo_offset (ls->rx_fifo);
m.tx_fifo = fifo_segment_fifo_offset (ls->tx_fifo);
m.segment_handle = session_segment_handle (ls);
}
snd_msg:
app_wrk_send_ctrl_evt (app_wrk, SESSION_CTRL_EVT_BOUND, &m, sizeof (m));
return 0;
}
void
mq_send_unlisten_reply (app_worker_t * app_wrk, session_handle_t sh,
u32 context, int rv)
{
session_unlisten_reply_msg_t m = { 0 };
m.context = context;
m.handle = sh;
m.retval = rv;
app_wrk_send_ctrl_evt (app_wrk, SESSION_CTRL_EVT_UNLISTEN_REPLY, &m,
sizeof (m));
}
static void
mq_send_session_migrate_cb (session_t * s, session_handle_t new_sh)
{
session_migrated_msg_t m = { 0 };
fifo_segment_t *eq_seg;
app_worker_t *app_wrk;
application_t *app;
u32 thread_index;
thread_index = session_thread_from_handle (new_sh);
app_wrk = app_worker_get (s->app_wrk_index);
app = application_get (app_wrk->app_index);
eq_seg = application_get_rx_mqs_segment (app);
m.handle = session_handle (s);
m.new_handle = new_sh;
m.vpp_thread_index = thread_index;
m.vpp_evt_q = fifo_segment_msg_q_offset (eq_seg, thread_index);
m.segment_handle = SESSION_INVALID_HANDLE;
app_wrk_send_ctrl_evt (app_wrk, SESSION_CTRL_EVT_MIGRATED, &m, sizeof (m));
}
static int
mq_send_add_segment_cb (u32 app_wrk_index, u64 segment_handle)
{
session_app_add_segment_msg_t m = { 0 };
vl_api_registration_t *reg;
app_worker_t *app_wrk;
fifo_segment_t *fs;
ssvm_private_t *sp;
u8 fd_flags = 0;
app_wrk = app_worker_get (app_wrk_index);
reg = vl_mem_api_client_index_to_registration (app_wrk->api_client_index);
if (!reg)
{
clib_warning ("no api registration for client: %u",
app_wrk->api_client_index);
return -1;
}
fs = segment_manager_get_segment_w_handle (segment_handle);
sp = &fs->ssvm;
if (ssvm_type (sp) == SSVM_SEGMENT_MEMFD)
{
if (vl_api_registration_file_index (reg) == VL_API_INVALID_FI)
{
clib_warning ("can't send memfd fd");
return -1;
}
fd_flags |= SESSION_FD_F_MEMFD_SEGMENT;
}
m.segment_size = sp->ssvm_size;
m.fd_flags = fd_flags;
m.segment_handle = segment_handle;
strncpy ((char *) m.segment_name, (char *) sp->name,
sizeof (m.segment_name) - 1);
app_wrk_send_ctrl_evt_fd (app_wrk, SESSION_CTRL_EVT_APP_ADD_SEGMENT, &m,
sizeof (m), sp->fd);
return 0;
}
static int
mq_send_del_segment_cb (u32 app_wrk_index, u64 segment_handle)
{
session_app_del_segment_msg_t m = { 0 };
vl_api_registration_t *reg;
app_worker_t *app_wrk;
app_wrk = app_worker_get (app_wrk_index);
reg = vl_mem_api_client_index_to_registration (app_wrk->api_client_index);
if (!reg)
{
clib_warning ("no registration: %u", app_wrk->api_client_index);
return -1;
}
m.segment_handle = segment_handle;
app_wrk_send_ctrl_evt (app_wrk, SESSION_CTRL_EVT_APP_DEL_SEGMENT, &m,
sizeof (m));
return 0;
}
static void
mq_send_session_cleanup_cb (session_t * s, session_cleanup_ntf_t ntf)
{
session_cleanup_msg_t m = { 0 };
app_worker_t *app_wrk;
/* Propagate transport cleanup notifications only if app didn't close */
if (ntf == SESSION_CLEANUP_TRANSPORT
&& s->session_state != SESSION_STATE_TRANSPORT_DELETED)
return;
app_wrk = app_worker_get_if_valid (s->app_wrk_index);
if (!app_wrk)
return;
m.handle = session_handle (s);
m.type = ntf;
app_wrk_send_ctrl_evt (app_wrk, SESSION_CTRL_EVT_CLEANUP, &m, sizeof (m));
}
static int
mq_send_io_rx_event (session_t *s)
{
session_event_t *mq_evt;
svm_msg_q_msg_t mq_msg;
app_worker_t *app_wrk;
svm_msg_q_t *mq;
if (svm_fifo_has_event (s->rx_fifo))
return 0;
app_wrk = app_worker_get (s->app_wrk_index);
mq = app_wrk->event_queue;
mq_msg = svm_msg_q_alloc_msg_w_ring (mq, SESSION_MQ_IO_EVT_RING);
mq_evt = svm_msg_q_msg_data (mq, &mq_msg);
mq_evt->event_type = SESSION_IO_EVT_RX;
mq_evt->session_index = s->rx_fifo->shr->client_session_index;
(void) svm_fifo_set_event (s->rx_fifo);
svm_msg_q_add_raw (mq, &mq_msg);
return 0;
}
static int
mq_send_io_tx_event (session_t *s)
{
app_worker_t *app_wrk = app_worker_get (s->app_wrk_index);
svm_msg_q_t *mq = app_wrk->event_queue;
session_event_t *mq_evt;
svm_msg_q_msg_t mq_msg;
mq_msg = svm_msg_q_alloc_msg_w_ring (mq, SESSION_MQ_IO_EVT_RING);
mq_evt = svm_msg_q_msg_data (mq, &mq_msg);
mq_evt->event_type = SESSION_IO_EVT_TX;
mq_evt->session_index = s->tx_fifo->shr->client_session_index;
svm_msg_q_add_raw (mq, &mq_msg);
return 0;
}
static session_cb_vft_t session_mq_cb_vft = {
.session_accept_callback = mq_send_session_accepted_cb,
.session_disconnect_callback = mq_send_session_disconnected_cb,
.session_connected_callback = mq_send_session_connected_cb,
.session_reset_callback = mq_send_session_reset_cb,
.session_migrate_callback = mq_send_session_migrate_cb,
.session_cleanup_callback = mq_send_session_cleanup_cb,
.add_segment_callback = mq_send_add_segment_cb,
.del_segment_callback = mq_send_del_segment_cb,
.builtin_app_rx_callback = mq_send_io_rx_event,
.builtin_app_tx_callback = mq_send_io_tx_event,
};
static void
vl_api_session_enable_disable_t_handler (vl_api_session_enable_disable_t * mp)
{
vl_api_session_enable_disable_reply_t *rmp;
vlib_main_t *vm = vlib_get_main ();
int rv = 0;
vnet_session_enable_disable (vm, mp->is_enable);
REPLY_MACRO (VL_API_SESSION_ENABLE_DISABLE_REPLY);
}
static void
vl_api_session_sapi_enable_disable_t_handler (
vl_api_session_sapi_enable_disable_t *mp)
{
vl_api_session_sapi_enable_disable_reply_t *rmp;
int rv = 0;
rv = appns_sapi_enable_disable (mp->is_enable);
REPLY_MACRO (VL_API_SESSION_SAPI_ENABLE_DISABLE_REPLY);
}
static void
vl_api_app_attach_t_handler (vl_api_app_attach_t * mp)
{
int rv = 0, *fds = 0, n_fds = 0, n_workers, i;
fifo_segment_t *segp, *rx_mqs_seg = 0;
vnet_app_attach_args_t _a, *a = &_a;
vl_api_app_attach_reply_t *rmp;
u8 fd_flags = 0, ctrl_thread;
vl_api_registration_t *reg;
svm_msg_q_t *rx_mq;
application_t *app;
reg = vl_api_client_index_to_registration (mp->client_index);
if (!reg)
return;
n_workers = vlib_num_workers ();
if (!session_main_is_enabled () || appns_sapi_enabled ())
{
rv = VNET_API_ERROR_FEATURE_DISABLED;
goto done;
}
/* Only support binary api with socket transport */
if (vl_api_registration_file_index (reg) == VL_API_INVALID_FI)
{
rv = VNET_API_ERROR_APP_UNSUPPORTED_CFG;
goto done;
}
STATIC_ASSERT (sizeof (u64) * APP_OPTIONS_N_OPTIONS <=
sizeof (mp->options),
"Out of options, fix api message definition");
clib_memset (a, 0, sizeof (*a));
a->api_client_index = mp->client_index;
a->options = mp->options;
a->session_cb_vft = &session_mq_cb_vft;
a->namespace_id = vl_api_from_api_to_new_vec (mp, &mp->namespace_id);
if ((rv = vnet_application_attach (a)))
{
clib_warning ("attach returned: %U", format_session_error, rv);
rv = VNET_API_ERROR_UNSPECIFIED;
vec_free (a->namespace_id);
goto done;
}
vec_free (a->namespace_id);
vec_validate (fds, 3 /* segs + tx evtfd */ + n_workers);
/* Send rx mqs segment */
app = application_get (a->app_index);
rx_mqs_seg = application_get_rx_mqs_segment (app);
fd_flags |= SESSION_FD_F_VPP_MQ_SEGMENT;
fds[n_fds] = rx_mqs_seg->ssvm.fd;
n_fds += 1;
/* Send fifo segment fd if needed */
if (ssvm_type (a->segment) == SSVM_SEGMENT_MEMFD)
{
fd_flags |= SESSION_FD_F_MEMFD_SEGMENT;
fds[n_fds] = a->segment->fd;
n_fds += 1;
}
if (a->options[APP_OPTIONS_FLAGS] & APP_OPTIONS_FLAGS_EVT_MQ_USE_EVENTFD)
{
fd_flags |= SESSION_FD_F_MQ_EVENTFD;
fds[n_fds] = svm_msg_q_get_eventfd (a->app_evt_q);
n_fds += 1;
}
if (application_use_private_rx_mqs ())
{
fd_flags |= SESSION_FD_F_VPP_MQ_EVENTFD;
for (i = 0; i < n_workers + 1; i++)
{
rx_mq = application_rx_mq_get (app, i);
fds[n_fds] = svm_msg_q_get_eventfd (rx_mq);
n_fds += 1;
}
}
done:
/* *INDENT-OFF* */
REPLY_MACRO3 (
VL_API_APP_ATTACH_REPLY,
((!rv) ? vec_len (((fifo_segment_t *) a->segment)->ssvm.name) : 0), ({
if (!rv)
{
ctrl_thread = n_workers ? 1 : 0;
segp = (fifo_segment_t *) a->segment;
rmp->app_index = clib_host_to_net_u32 (a->app_index);
rmp->app_mq = fifo_segment_msg_q_offset (segp, 0);
rmp->vpp_ctrl_mq =
fifo_segment_msg_q_offset (rx_mqs_seg, ctrl_thread);
rmp->vpp_ctrl_mq_thread = ctrl_thread;
rmp->n_fds = n_fds;
rmp->fd_flags = fd_flags;
if (vec_len (segp->ssvm.name))
{
vl_api_vec_to_api_string (segp->ssvm.name, &rmp->segment_name);
}
rmp->segment_size = segp->ssvm.ssvm_size;
rmp->segment_handle = clib_host_to_net_u64 (a->segment_handle);
}
}));
/* *INDENT-ON* */
if (n_fds)
session_send_fds (reg, fds, n_fds);
vec_free (fds);
}
static void
vl_api_app_worker_add_del_t_handler (vl_api_app_worker_add_del_t * mp)
{
int rv = 0, fds[SESSION_N_FD_TYPE], n_fds = 0;
vl_api_app_worker_add_del_reply_t *rmp;
vl_api_registration_t *reg;
application_t *app;
u8 fd_flags = 0;
if (!session_main_is_enabled () || appns_sapi_enabled ())
{
rv = VNET_API_ERROR_FEATURE_DISABLED;
goto done;
}
reg = vl_api_client_index_to_registration (mp->client_index);
if (!reg)
return;
app = application_get_if_valid (clib_net_to_host_u32 (mp->app_index));
if (!app)
{
rv = VNET_API_ERROR_INVALID_VALUE;
goto done;
}
vnet_app_worker_add_del_args_t args = {
.app_index = app->app_index,
.wrk_map_index = clib_net_to_host_u32 (mp->wrk_index),
.api_client_index = mp->client_index,
.is_add = mp->is_add
};
rv = vnet_app_worker_add_del (&args);
if (rv)
{
clib_warning ("app worker add/del returned: %U", format_session_error,
rv);
rv = VNET_API_ERROR_UNSPECIFIED;
goto done;
}
if (!mp->is_add)
goto done;
/* Send fifo segment fd if needed */
if (ssvm_type (args.segment) == SSVM_SEGMENT_MEMFD)
{
fd_flags |= SESSION_FD_F_MEMFD_SEGMENT;
fds[n_fds] = args.segment->fd;
n_fds += 1;
}
if (application_segment_manager_properties (app)->use_mq_eventfd)
{
fd_flags |= SESSION_FD_F_MQ_EVENTFD;
fds[n_fds] = svm_msg_q_get_eventfd (args.evt_q);
n_fds += 1;
}
/* *INDENT-OFF* */
done:
REPLY_MACRO3 (
VL_API_APP_WORKER_ADD_DEL_REPLY,
((!rv && mp->is_add) ? vec_len (args.segment->name) : 0), ({
rmp->is_add = mp->is_add;
rmp->wrk_index = clib_host_to_net_u32 (args.wrk_map_index);
rmp->segment_handle = clib_host_to_net_u64 (args.segment_handle);
if (!rv && mp->is_add)
{
rmp->app_event_queue_address =
fifo_segment_msg_q_offset ((fifo_segment_t *) args.segment, 0);
rmp->n_fds = n_fds;
rmp->fd_flags = fd_flags;
if (vec_len (args.segment->name))
{
vl_api_vec_to_api_string (args.segment->name,
&rmp->segment_name);
}
}
}));
/* *INDENT-ON* */
if (n_fds)
session_send_fds (reg, fds, n_fds);
}
static void
vl_api_application_detach_t_handler (vl_api_application_detach_t * mp)
{
vl_api_application_detach_reply_t *rmp;
int rv = VNET_API_ERROR_INVALID_VALUE_2;
vnet_app_detach_args_t _a, *a = &_a;
application_t *app;
if (!session_main_is_enabled () || appns_sapi_enabled ())
{
rv = VNET_API_ERROR_FEATURE_DISABLED;
goto done;
}
app = application_lookup (mp->client_index);
if (app)
{
a->app_index = app->app_index;
a->api_client_index = mp->client_index;
rv = vnet_application_detach (a);
if (rv)
{
clib_warning ("vnet_application_detach: %U", format_session_error,
rv);
rv = VNET_API_ERROR_UNSPECIFIED;
}
}
done:
REPLY_MACRO (VL_API_APPLICATION_DETACH_REPLY);
}
static void
vl_api_app_namespace_add_del_t_handler (vl_api_app_namespace_add_del_t * mp)
{
vl_api_app_namespace_add_del_reply_t *rmp;
u32 appns_index = 0;
u8 *ns_id = 0;
int rv = 0;
if (session_main_is_enabled () == 0)
{
rv = VNET_API_ERROR_FEATURE_DISABLED;
goto done;
}
ns_id = vl_api_from_api_to_new_vec (mp, &mp->namespace_id);
vnet_app_namespace_add_del_args_t args = {
.ns_id = ns_id,
.sock_name = 0,
.secret = clib_net_to_host_u64 (mp->secret),
.sw_if_index = clib_net_to_host_u32 (mp->sw_if_index),
.ip4_fib_id = clib_net_to_host_u32 (mp->ip4_fib_id),
.ip6_fib_id = clib_net_to_host_u32 (mp->ip6_fib_id),
.is_add = 1
};
rv = vnet_app_namespace_add_del (&args);
if (!rv)
{
appns_index = app_namespace_index_from_id (ns_id);
if (appns_index == APP_NAMESPACE_INVALID_INDEX)
{
clib_warning ("app ns lookup failed");
rv = VNET_API_ERROR_UNSPECIFIED;
}
}
vec_free (ns_id);
/* *INDENT-OFF* */
done:
REPLY_MACRO2 (VL_API_APP_NAMESPACE_ADD_DEL_REPLY, ({
if (!rv)
rmp->appns_index = clib_host_to_net_u32 (appns_index);
}));
/* *INDENT-ON* */
}
static void
vl_api_app_namespace_add_del_v2_t_handler (
vl_api_app_namespace_add_del_v2_t *mp)
{
vl_api_app_namespace_add_del_v2_reply_t *rmp;
u8 *ns_id = 0;
u32 appns_index = 0;
int rv = 0;
if (session_main_is_enabled () == 0)
{
rv = VNET_API_ERROR_FEATURE_DISABLED;
goto done;
}
mp->namespace_id[sizeof (mp->namespace_id) - 1] = 0;
ns_id = format (0, "%s", &mp->namespace_id);
vnet_app_namespace_add_del_args_t args = {
.ns_id = ns_id,
.sock_name = 0,
.secret = clib_net_to_host_u64 (mp->secret),
.sw_if_index = clib_net_to_host_u32 (mp->sw_if_index),
.ip4_fib_id = clib_net_to_host_u32 (mp->ip4_fib_id),
.ip6_fib_id = clib_net_to_host_u32 (mp->ip6_fib_id),
.is_add = 1
};
rv = vnet_app_namespace_add_del (&args);
if (!rv)
{
appns_index = app_namespace_index_from_id (ns_id);
if (appns_index == APP_NAMESPACE_INVALID_INDEX)
{
clib_warning ("app ns lookup failed id:%s", ns_id);
rv = VNET_API_ERROR_UNSPECIFIED;
}
}
vec_free (ns_id);
done:
REPLY_MACRO2 (VL_API_APP_NAMESPACE_ADD_DEL_V2_REPLY, ({
if (!rv)
rmp->appns_index = clib_host_to_net_u32 (appns_index);
}));
}
static void
vl_api_app_namespace_add_del_v4_t_handler (
vl_api_app_namespace_add_del_v4_t *mp)
{
vl_api_app_namespace_add_del_v4_reply_t *rmp;
u8 *ns_id = 0, *sock_name = 0;
u32 appns_index = 0;
int rv = 0;
if (session_main_is_enabled () == 0)
{
rv = VNET_API_ERROR_FEATURE_DISABLED;
goto done;
}
mp->namespace_id[sizeof (mp->namespace_id) - 1] = 0;
ns_id = format (0, "%s", &mp->namespace_id);
sock_name = vl_api_from_api_to_new_vec (mp, &mp->sock_name);
vnet_app_namespace_add_del_args_t args = {
.ns_id = ns_id,
.sock_name = sock_name,
.secret = clib_net_to_host_u64 (mp->secret),
.sw_if_index = clib_net_to_host_u32 (mp->sw_if_index),
.ip4_fib_id = clib_net_to_host_u32 (mp->ip4_fib_id),
.ip6_fib_id = clib_net_to_host_u32 (mp->ip6_fib_id),
.is_add = mp->is_add,
};
rv = vnet_app_namespace_add_del (&args);
if (!rv && mp->is_add)
{
appns_index = app_namespace_index_from_id (ns_id);
if (appns_index == APP_NAMESPACE_INVALID_INDEX)
{
clib_warning ("app ns lookup failed id:%s", ns_id);
rv = VNET_API_ERROR_UNSPECIFIED;
}
}
vec_free (ns_id);
vec_free (sock_name);
done:
REPLY_MACRO2 (VL_API_APP_NAMESPACE_ADD_DEL_V4_REPLY, ({
if (!rv)
rmp->appns_index = clib_host_to_net_u32 (appns_index);
}));
}
static void
vl_api_app_namespace_add_del_v3_t_handler (
vl_api_app_namespace_add_del_v3_t *mp)
{
vl_api_app_namespace_add_del_v3_reply_t *rmp;
u8 *ns_id = 0, *sock_name = 0, *api_sock_name = 0;
u32 appns_index = 0;
int rv = 0;
if (session_main_is_enabled () == 0)
{
rv = VNET_API_ERROR_FEATURE_DISABLED;
goto done;
}
mp->namespace_id[sizeof (mp->namespace_id) - 1] = 0;
ns_id = format (0, "%s", &mp->namespace_id);
api_sock_name = vl_api_from_api_to_new_vec (mp, &mp->sock_name);
mp->netns[sizeof (mp->netns) - 1] = 0;
if (strlen ((char *) mp->netns) != 0)
{
sock_name =
format (0, "abstract:%v,netns_name=%s", api_sock_name, &mp->netns);
}
else
{
sock_name = api_sock_name;
api_sock_name = 0; // for vec_free
}
vnet_app_namespace_add_del_args_t args = {
.ns_id = ns_id,
.sock_name = sock_name,
.secret = clib_net_to_host_u64 (mp->secret),
.sw_if_index = clib_net_to_host_u32 (mp->sw_if_index),
.ip4_fib_id = clib_net_to_host_u32 (mp->ip4_fib_id),
.ip6_fib_id = clib_net_to_host_u32 (mp->ip6_fib_id),
.is_add = mp->is_add,
};
rv = vnet_app_namespace_add_del (&args);
if (!rv && mp->is_add)
{
appns_index = app_namespace_index_from_id (ns_id);
if (appns_index == APP_NAMESPACE_INVALID_INDEX)
{
clib_warning ("app ns lookup failed id:%s", ns_id);
rv = VNET_API_ERROR_UNSPECIFIED;
}
}
vec_free (ns_id);
vec_free (sock_name);
vec_free (api_sock_name);
done:
REPLY_MACRO2 (VL_API_APP_NAMESPACE_ADD_DEL_V3_REPLY, ({
if (!rv)
rmp->appns_index = clib_host_to_net_u32 (appns_index);
}));
}
static void
vl_api_session_rule_add_del_t_handler (vl_api_session_rule_add_del_t * mp)
{
vl_api_session_rule_add_del_reply_t *rmp;
session_rule_add_del_args_t args;
session_rule_table_add_del_args_t *table_args = &args.table_args;
int rv = 0;
clib_memset (&args, 0, sizeof (args));
ip_prefix_decode (&mp->lcl, &table_args->lcl);
ip_prefix_decode (&mp->rmt, &table_args->rmt);
table_args->lcl_port = mp->lcl_port;
table_args->rmt_port = mp->rmt_port;
table_args->action_index = clib_net_to_host_u32 (mp->action_index);
table_args->is_add = mp->is_add;
mp->tag[sizeof (mp->tag) - 1] = 0;
table_args->tag = format (0, "%s", mp->tag);
args.appns_index = clib_net_to_host_u32 (mp->appns_index);
args.scope = mp->scope;
args.transport_proto =
api_session_transport_proto_decode (&mp->transport_proto) ==
TRANSPORT_PROTO_UDP ? 1 : 0;
rv = vnet_session_rule_add_del (&args);
if (rv)
{
clib_warning ("rule add del returned: %U", format_session_error, rv);
rv = VNET_API_ERROR_UNSPECIFIED;
}
vec_free (table_args->tag);
REPLY_MACRO (VL_API_SESSION_RULE_ADD_DEL_REPLY);
}
static void
send_session_rule_details4 (mma_rule_16_t * rule, u8 is_local,
u8 transport_proto, u32 appns_index, u8 * tag,
vl_api_registration_t * reg, u32 context)
{
vl_api_session_rules_details_t *rmp = 0;
session_mask_or_match_4_t *match =
(session_mask_or_match_4_t *) & rule->match;
session_mask_or_match_4_t *mask =
(session_mask_or_match_4_t *) & rule->mask;
fib_prefix_t lcl, rmt;
rmp = vl_msg_api_alloc (sizeof (*rmp));
clib_memset (rmp, 0, sizeof (*rmp));
rmp->_vl_msg_id = ntohs (REPLY_MSG_ID_BASE + VL_API_SESSION_RULES_DETAILS);
rmp->context = context;
clib_memset (&lcl, 0, sizeof (lcl));
clib_memset (&rmt, 0, sizeof (rmt));
ip_set (&lcl.fp_addr, &match->lcl_ip, 1);
ip_set (&rmt.fp_addr, &match->rmt_ip, 1);
lcl.fp_len = ip4_mask_to_preflen (&mask->lcl_ip);
rmt.fp_len = ip4_mask_to_preflen (&mask->rmt_ip);
ip_prefix_encode (&lcl, &rmp->lcl);
ip_prefix_encode (&rmt, &rmp->rmt);
rmp->lcl_port = match->lcl_port;
rmp->rmt_port = match->rmt_port;
rmp->action_index = clib_host_to_net_u32 (rule->action_index);
rmp->scope =
is_local ? SESSION_RULE_SCOPE_API_LOCAL : SESSION_RULE_SCOPE_API_GLOBAL;
rmp->transport_proto = api_session_transport_proto_encode (transport_proto);
rmp->appns_index = clib_host_to_net_u32 (appns_index);
if (tag)
{
clib_memcpy_fast (rmp->tag, tag, vec_len (tag));
rmp->tag[vec_len (tag)] = 0;
}
vl_api_send_msg (reg, (u8 *) rmp);
}
static void
send_session_rule_details6 (mma_rule_40_t * rule, u8 is_local,
u8 transport_proto, u32 appns_index, u8 * tag,
vl_api_registration_t * reg, u32 context)
{
vl_api_session_rules_details_t *rmp = 0;
session_mask_or_match_6_t *match =
(session_mask_or_match_6_t *) & rule->match;
session_mask_or_match_6_t *mask =
(session_mask_or_match_6_t *) & rule->mask;
fib_prefix_t lcl, rmt;
rmp = vl_msg_api_alloc (sizeof (*rmp));
clib_memset (rmp, 0, sizeof (*rmp));
rmp->_vl_msg_id = ntohs (REPLY_MSG_ID_BASE + VL_API_SESSION_RULES_DETAILS);
rmp->context = context;
clib_memset (&lcl, 0, sizeof (lcl));
clib_memset (&rmt, 0, sizeof (rmt));
ip_set (&lcl.fp_addr, &match->lcl_ip, 0);
ip_set (&rmt.fp_addr, &match->rmt_ip, 0);
lcl.fp_len = ip6_mask_to_preflen (&mask->lcl_ip);
rmt.fp_len = ip6_mask_to_preflen (&mask->rmt_ip);
ip_prefix_encode (&lcl, &rmp->lcl);
ip_prefix_encode (&rmt, &rmp->rmt);
rmp->lcl_port = match->lcl_port;
rmp->rmt_port = match->rmt_port;
rmp->action_index = clib_host_to_net_u32 (rule->action_index);
rmp->scope =
is_local ? SESSION_RULE_SCOPE_API_LOCAL : SESSION_RULE_SCOPE_API_GLOBAL;
rmp->transport_proto = api_session_transport_proto_encode (transport_proto);
rmp->appns_index = clib_host_to_net_u32 (appns_index);
if (tag)
{
clib_memcpy_fast (rmp->tag, tag, vec_len (tag));
rmp->tag[vec_len (tag)] = 0;
}
vl_api_send_msg (reg, (u8 *) rmp);
}
static void
send_session_rules_table_details (session_rules_table_t * srt, u8 fib_proto,
u8 tp, u8 is_local, u32 appns_index,
vl_api_registration_t * reg, u32 context)
{
mma_rule_16_t *rule16;
mma_rule_40_t *rule40;
mma_rules_table_16_t *srt16;
mma_rules_table_40_t *srt40;
u32 ri;
if (is_local || fib_proto == FIB_PROTOCOL_IP4)
{
u8 *tag = 0;
/* *INDENT-OFF* */
srt16 = &srt->session_rules_tables_16;
pool_foreach (rule16, srt16->rules) {
ri = mma_rules_table_rule_index_16 (srt16, rule16);
tag = session_rules_table_rule_tag (srt, ri, 1);
send_session_rule_details4 (rule16, is_local, tp, appns_index, tag,
reg, context);
}
/* *INDENT-ON* */
}
if (is_local || fib_proto == FIB_PROTOCOL_IP6)
{
u8 *tag = 0;
/* *INDENT-OFF* */
srt40 = &srt->session_rules_tables_40;
pool_foreach (rule40, srt40->rules) {
ri = mma_rules_table_rule_index_40 (srt40, rule40);
tag = session_rules_table_rule_tag (srt, ri, 1);
send_session_rule_details6 (rule40, is_local, tp, appns_index, tag,
reg, context);
}
/* *INDENT-ON* */
}
}
static void
vl_api_session_rules_dump_t_handler (vl_api_session_rules_dump_t * mp)
{
vl_api_registration_t *reg;
session_table_t *st;
u8 tp;
reg = vl_api_client_index_to_registration (mp->client_index);
if (!reg)
return;
/* *INDENT-OFF* */
session_table_foreach (st, ({
for (tp = 0; tp < TRANSPORT_N_PROTOS; tp++)
{
send_session_rules_table_details (&st->session_rules[tp],
st->active_fib_proto, tp,
st->is_local, st->appns_index, reg,
mp->context);
}
}));
/* *INDENT-ON* */
}
static void
vl_api_app_add_cert_key_pair_t_handler (vl_api_app_add_cert_key_pair_t * mp)
{
vl_api_app_add_cert_key_pair_reply_t *rmp;
vnet_app_add_cert_key_pair_args_t _a, *a = &_a;
u32 certkey_len, key_len, cert_len;
int rv = 0;
if (session_main_is_enabled () == 0)
{
rv = VNET_API_ERROR_FEATURE_DISABLED;
goto done;
}
cert_len = clib_net_to_host_u16 (mp->cert_len);
if (cert_len > 10000)
{
rv = VNET_API_ERROR_INVALID_VALUE;
goto done;
}
certkey_len = clib_net_to_host_u16 (mp->certkey_len);
if (certkey_len < cert_len)
{
rv = VNET_API_ERROR_INVALID_VALUE;
goto done;
}
key_len = certkey_len - cert_len;
if (key_len > 10000)
{
rv = VNET_API_ERROR_INVALID_VALUE;
goto done;
}
clib_memset (a, 0, sizeof (*a));
a->cert = mp->certkey;
a->key = mp->certkey + cert_len;
a->cert_len = cert_len;
a->key_len = key_len;
rv = vnet_app_add_cert_key_pair (a);
done:
/* *INDENT-OFF* */
REPLY_MACRO2 (VL_API_APP_ADD_CERT_KEY_PAIR_REPLY, ({
if (!rv)
rmp->index = clib_host_to_net_u32 (a->index);
}));
/* *INDENT-ON* */
}
static void
vl_api_app_del_cert_key_pair_t_handler (vl_api_app_del_cert_key_pair_t * mp)
{
vl_api_app_del_cert_key_pair_reply_t *rmp;
u32 ckpair_index;
int rv = 0;
if (session_main_is_enabled () == 0)
{
rv = VNET_API_ERROR_FEATURE_DISABLED;
goto done;
}
ckpair_index = clib_net_to_host_u32 (mp->index);
rv = vnet_app_del_cert_key_pair (ckpair_index);
if (rv)
{
clib_warning ("vnet_app_del_cert_key_pair: %U", format_session_error,
rv);
rv = VNET_API_ERROR_UNSPECIFIED;
}
done:
REPLY_MACRO (VL_API_APP_DEL_CERT_KEY_PAIR_REPLY);
}
static clib_error_t *
application_reaper_cb (u32 client_index)
{
application_t *app = application_lookup (client_index);
vnet_app_detach_args_t _a, *a = &_a;
if (app)
{
a->app_index = app->app_index;
a->api_client_index = client_index;
vnet_application_detach (a);
}
return 0;
}
VL_MSG_API_REAPER_FUNCTION (application_reaper_cb);
/*
* Socket api functions
*/
static int
mq_send_add_segment_sapi_cb (u32 app_wrk_index, u64 segment_handle)
{
session_app_add_segment_msg_t m = { 0 };
app_worker_t *app_wrk;
fifo_segment_t *fs;
ssvm_private_t *sp;
u8 fd_flags = 0;
app_wrk = app_worker_get (app_wrk_index);
fs = segment_manager_get_segment_w_handle (segment_handle);
sp = &fs->ssvm;
ASSERT (ssvm_type (sp) == SSVM_SEGMENT_MEMFD);
fd_flags |= SESSION_FD_F_MEMFD_SEGMENT;
m.segment_size = sp->ssvm_size;
m.fd_flags = fd_flags;
m.segment_handle = segment_handle;
strncpy ((char *) m.segment_name, (char *) sp->name,
sizeof (m.segment_name) - 1);
app_wrk_send_ctrl_evt_fd (app_wrk, SESSION_CTRL_EVT_APP_ADD_SEGMENT, &m,
sizeof (m), sp->fd);
return 0;
}
static int
mq_send_del_segment_sapi_cb (u32 app_wrk_index, u64 segment_handle)
{
session_app_del_segment_msg_t m = { 0 };
app_worker_t *app_wrk;
app_wrk = app_worker_get (app_wrk_index);
m.segment_handle = segment_handle;
app_wrk_send_ctrl_evt (app_wrk, SESSION_CTRL_EVT_APP_DEL_SEGMENT, &m,
sizeof (m));
return 0;
}
static session_cb_vft_t session_mq_sapi_cb_vft = {
.session_accept_callback = mq_send_session_accepted_cb,
.session_disconnect_callback = mq_send_session_disconnected_cb,
.session_connected_callback = mq_send_session_connected_cb,
.session_reset_callback = mq_send_session_reset_cb,
.session_migrate_callback = mq_send_session_migrate_cb,
.session_cleanup_callback = mq_send_session_cleanup_cb,
.add_segment_callback = mq_send_add_segment_sapi_cb,
.del_segment_callback = mq_send_del_segment_sapi_cb,
.builtin_app_rx_callback = mq_send_io_rx_event,
.builtin_app_tx_callback = mq_send_io_tx_event,
};
static void
session_api_attach_handler (app_namespace_t * app_ns, clib_socket_t * cs,
app_sapi_attach_msg_t * mp)
{
int rv = 0, *fds = 0, n_fds = 0, i, n_workers;
vnet_app_attach_args_t _a, *a = &_a;
app_sapi_attach_reply_msg_t *rmp;
u8 fd_flags = 0, ctrl_thread;
app_ns_api_handle_t *handle;
fifo_segment_t *rx_mqs_seg;
app_sapi_msg_t msg = { 0 };
app_worker_t *app_wrk;
application_t *app;
svm_msg_q_t *rx_mq;
/* Make sure name is null terminated */
mp->name[63] = 0;
clib_memset (a, 0, sizeof (*a));
a->api_client_index = appns_sapi_socket_handle (app_ns, cs);
a->name = format (0, "%s", (char *) mp->name);
a->options = mp->options;
a->session_cb_vft = &session_mq_sapi_cb_vft;
a->use_sock_api = 1;
a->options[APP_OPTIONS_NAMESPACE] = app_namespace_index (app_ns);
if ((rv = vnet_application_attach (a)))
{
clib_warning ("attach returned: %d", rv);
goto done;
}
n_workers = vlib_num_workers ();
vec_validate (fds, 3 /* segs + tx evtfd */ + n_workers);
/* Send event queues segment */
app = application_get (a->app_index);
rx_mqs_seg = application_get_rx_mqs_segment (app);
fd_flags |= SESSION_FD_F_VPP_MQ_SEGMENT;
fds[n_fds] = rx_mqs_seg->ssvm.fd;
n_fds += 1;
/* Send fifo segment fd if needed */
if (ssvm_type (a->segment) == SSVM_SEGMENT_MEMFD)
{
fd_flags |= SESSION_FD_F_MEMFD_SEGMENT;
fds[n_fds] = a->segment->fd;
n_fds += 1;
}
if (a->options[APP_OPTIONS_FLAGS] & APP_OPTIONS_FLAGS_EVT_MQ_USE_EVENTFD)
{
fd_flags |= SESSION_FD_F_MQ_EVENTFD;
fds[n_fds] = svm_msg_q_get_eventfd (a->app_evt_q);
n_fds += 1;
}
if (application_use_private_rx_mqs ())
{
fd_flags |= SESSION_FD_F_VPP_MQ_EVENTFD;
for (i = 0; i < n_workers + 1; i++)
{
rx_mq = application_rx_mq_get (app, i);
fds[n_fds] = svm_msg_q_get_eventfd (rx_mq);
n_fds += 1;
}
}
done:
msg.type = APP_SAPI_MSG_TYPE_ATTACH_REPLY;
rmp = &msg.attach_reply;
rmp->retval = rv;
if (!rv)
{
ctrl_thread = n_workers ? 1 : 0;
rmp->app_index = a->app_index;
rmp->app_mq =
fifo_segment_msg_q_offset ((fifo_segment_t *) a->segment, 0);
rmp->vpp_ctrl_mq = fifo_segment_msg_q_offset (rx_mqs_seg, ctrl_thread);
rmp->vpp_ctrl_mq_thread = ctrl_thread;
rmp->n_fds = n_fds;
rmp->fd_flags = fd_flags;
/* No segment name and size since we only support memfds
* in this configuration */
rmp->segment_handle = a->segment_handle;
rmp->api_client_handle = a->api_client_index;
/* Update app index for socket */
handle = (app_ns_api_handle_t *) & cs->private_data;
app_wrk = application_get_worker (app, 0);
handle->aah_app_wrk_index = app_wrk->wrk_index;
}
clib_socket_sendmsg (cs, &msg, sizeof (msg), fds, n_fds);
vec_free (a->name);
vec_free (fds);
}
void
sapi_socket_close_w_handle (u32 api_handle)
{
app_namespace_t *app_ns = app_namespace_get (api_handle >> 16);
u16 sock_index = api_handle & 0xffff;
app_ns_api_handle_t *handle;
clib_socket_t *cs;
clib_file_t *cf;
cs = appns_sapi_get_socket (app_ns, sock_index);
if (!cs)
return;
handle = (app_ns_api_handle_t *) & cs->private_data;
cf = clib_file_get (&file_main, handle->aah_file_index);
clib_file_del (&file_main, cf);
clib_socket_close (cs);
appns_sapi_free_socket (app_ns, cs);
}
static void
sapi_add_del_worker_handler (app_namespace_t * app_ns,
clib_socket_t * cs,
app_sapi_worker_add_del_msg_t * mp)
{
int rv = 0, fds[SESSION_N_FD_TYPE], n_fds = 0;
app_sapi_worker_add_del_reply_msg_t *rmp;
app_ns_api_handle_t *handle;
app_sapi_msg_t msg = { 0 };
app_worker_t *app_wrk;
u32 sapi_handle = -1;
application_t *app;
u8 fd_flags = 0;
app = application_get_if_valid (mp->app_index);
if (!app)
{
rv = SESSION_E_INVALID;
goto done;
}
sapi_handle = appns_sapi_socket_handle (app_ns, cs);
vnet_app_worker_add_del_args_t args = {
.app_index = app->app_index,
.wrk_map_index = mp->wrk_index,
.api_client_index = sapi_handle,
.is_add = mp->is_add
};
rv = vnet_app_worker_add_del (&args);
if (rv)
{
clib_warning ("app worker add/del returned: %U", format_session_error,
rv);
goto done;
}
if (!mp->is_add)
goto done;
/* Send fifo segment fd if needed */
if (ssvm_type (args.segment) == SSVM_SEGMENT_MEMFD)
{
fd_flags |= SESSION_FD_F_MEMFD_SEGMENT;
fds[n_fds] = args.segment->fd;
n_fds += 1;
}
if (application_segment_manager_properties (app)->use_mq_eventfd)
{
fd_flags |= SESSION_FD_F_MQ_EVENTFD;
fds[n_fds] = svm_msg_q_get_eventfd (args.evt_q);
n_fds += 1;
}
done:
msg.type = APP_SAPI_MSG_TYPE_ADD_DEL_WORKER_REPLY;
rmp = &msg.worker_add_del_reply;
rmp->retval = rv;
rmp->is_add = mp->is_add;
rmp->api_client_handle = sapi_handle;
rmp->wrk_index = args.wrk_map_index;
rmp->segment_handle = args.segment_handle;
if (!rv && mp->is_add)
{
/* No segment name and size. This supports only memfds */
rmp->app_event_queue_address =
fifo_segment_msg_q_offset ((fifo_segment_t *) args.segment, 0);
rmp->n_fds = n_fds;
rmp->fd_flags = fd_flags;
/* Update app index for socket */
handle = (app_ns_api_handle_t *) & cs->private_data;
app_wrk = application_get_worker (app, args.wrk_map_index);
handle->aah_app_wrk_index = app_wrk->wrk_index;
}
clib_socket_sendmsg (cs, &msg, sizeof (msg), fds, n_fds);
}
/* This is a workaround for the case when session layer starts reading
* the socket before the client actualy sends the data
*/
static clib_error_t *
sapi_socket_receive_wait (clib_socket_t *cs, u8 *msg, u32 msg_len)
{
clib_error_t *err;
int n_tries = 5;
while (1)
{
err = clib_socket_recvmsg (cs, msg, msg_len, 0, 0);
if (!err)
break;
if (!n_tries)
return err;
n_tries--;
usleep (1);
}
return err;
}
static void
sapi_add_del_cert_key_handler (app_namespace_t *app_ns, clib_socket_t *cs,
app_sapi_cert_key_add_del_msg_t *mp)
{
vnet_app_add_cert_key_pair_args_t _a, *a = &_a;
app_sapi_cert_key_add_del_reply_msg_t *rmp;
app_sapi_msg_t msg = { 0 };
int rv = 0;
if (mp->is_add)
{
const u32 max_certkey_len = 2e4, max_cert_len = 1e4, max_key_len = 1e4;
clib_error_t *err;
u8 *certkey = 0;
u32 key_len;
if (mp->certkey_len > max_certkey_len)
{
rv = SESSION_E_INVALID;
goto send_reply;
}
vec_validate (certkey, mp->certkey_len - 1);
err = sapi_socket_receive_wait (cs, certkey, mp->certkey_len);
if (err)
{
clib_error_report (err);
rv = SESSION_E_INVALID;
goto send_reply;
}
if (mp->cert_len > max_cert_len)
{
rv = SESSION_E_INVALID;
goto send_reply;
}
if (mp->certkey_len < mp->cert_len)
{
rv = SESSION_E_INVALID;
goto send_reply;
}
key_len = mp->certkey_len - mp->cert_len;
if (key_len > max_key_len)
{
rv = SESSION_E_INVALID;
goto send_reply;
}
clib_memset (a, 0, sizeof (*a));
a->cert = certkey;
a->key = certkey + mp->cert_len;
a->cert_len = mp->cert_len;
a->key_len = key_len;
rv = vnet_app_add_cert_key_pair (a);
vec_free (certkey);
}
else
{
rv = vnet_app_del_cert_key_pair (mp->index);
}
send_reply:
msg.type = APP_SAPI_MSG_TYPE_ADD_DEL_CERT_KEY_REPLY;
rmp = &msg.cert_key_add_del_reply;
rmp->retval = rv;
rmp->context = mp->context;
if (!rv && mp->is_add)
rmp->index = a->index;
clib_socket_sendmsg (cs, &msg, sizeof (msg), 0, 0);
}
static void
sapi_socket_detach (app_namespace_t * app_ns, clib_socket_t * cs)
{
app_ns_api_handle_t *handle;
app_worker_t *app_wrk;
u32 api_client_handle;
api_client_handle = appns_sapi_socket_handle (app_ns, cs);
/* Cleanup everything because app worker closed socket or crashed */
handle = (app_ns_api_handle_t *) & cs->private_data;
app_wrk = app_worker_get_if_valid (handle->aah_app_wrk_index);
if (!app_wrk)
return;
vnet_app_worker_add_del_args_t args = {
.app_index = app_wrk->app_index,
.wrk_map_index = app_wrk->wrk_map_index,
.api_client_index = api_client_handle,
.is_add = 0
};
/* Send rpc to main thread for worker barrier */
vlib_rpc_call_main_thread (vnet_app_worker_add_del, (u8 *) & args,
sizeof (args));
}
static clib_error_t *
sapi_sock_read_ready (clib_file_t * cf)
{
app_ns_api_handle_t *handle = (app_ns_api_handle_t *) & cf->private_data;
vlib_main_t *vm = vlib_get_main ();
app_sapi_msg_t msg = { 0 };
app_namespace_t *app_ns;
clib_error_t *err = 0;
clib_socket_t *cs;
app_ns = app_namespace_get (handle->aah_app_ns_index);
cs = appns_sapi_get_socket (app_ns, handle->aah_sock_index);
if (!cs)
goto error;
err = clib_socket_recvmsg (cs, &msg, sizeof (msg), 0, 0);
if (err)
{
clib_error_free (err);
sapi_socket_detach (app_ns, cs);
goto error;
}
handle = (app_ns_api_handle_t *) & cs->private_data;
vlib_worker_thread_barrier_sync (vm);
switch (msg.type)
{
case APP_SAPI_MSG_TYPE_ATTACH:
session_api_attach_handler (app_ns, cs, &msg.attach);
break;
case APP_SAPI_MSG_TYPE_ADD_DEL_WORKER:
sapi_add_del_worker_handler (app_ns, cs, &msg.worker_add_del);
break;
case APP_SAPI_MSG_TYPE_ADD_DEL_CERT_KEY:
sapi_add_del_cert_key_handler (app_ns, cs, &msg.cert_key_add_del);
break;
default:
clib_warning ("app wrk %u unknown message type: %u",
handle->aah_app_wrk_index, msg.type);
break;
}
vlib_worker_thread_barrier_release (vm);
error:
return 0;
}
static clib_error_t *
sapi_sock_write_ready (clib_file_t * cf)
{
app_ns_api_handle_t *handle = (app_ns_api_handle_t *) & cf->private_data;
clib_warning ("called for app ns %u", handle->aah_app_ns_index);
return 0;
}
static clib_error_t *
sapi_sock_error (clib_file_t * cf)
{
app_ns_api_handle_t *handle = (app_ns_api_handle_t *) & cf->private_data;
app_namespace_t *app_ns;
clib_socket_t *cs;
app_ns = app_namespace_get (handle->aah_app_ns_index);
cs = appns_sapi_get_socket (app_ns, handle->aah_sock_index);
if (!cs)
return 0;
sapi_socket_detach (app_ns, cs);
return 0;
}
static clib_error_t *
sapi_sock_accept_ready (clib_file_t * scf)
{
app_ns_api_handle_t handle = *(app_ns_api_handle_t *) & scf->private_data;
app_namespace_t *app_ns;
clib_file_t cf = { 0 };
clib_error_t *err = 0;
clib_socket_t *ccs, *scs;
/* Listener files point to namespace */
app_ns = app_namespace_get (handle.aah_app_ns_index);
/*
* Initialize client socket
*/
ccs = appns_sapi_alloc_socket (app_ns);
/* Grab server socket after client is initialized */
scs = appns_sapi_get_socket (app_ns, handle.aah_sock_index);
if (!scs)
goto error;
err = clib_socket_accept (scs, ccs);
if (err)
{
clib_error_report (err);
goto error;
}
cf.read_function = sapi_sock_read_ready;
cf.write_function = sapi_sock_write_ready;
cf.error_function = sapi_sock_error;
cf.file_descriptor = ccs->fd;
/* File points to app namespace and socket */
handle.aah_sock_index = appns_sapi_socket_index (app_ns, ccs);
cf.private_data = handle.as_u64;
cf.description = format (0, "app sock conn fd: %d", ccs->fd);
/* Poll until we get an attach message. Socket points to file and
* application that owns the socket */
handle.aah_app_wrk_index = APP_INVALID_INDEX;
handle.aah_file_index = clib_file_add (&file_main, &cf);
ccs->private_data = handle.as_u64;
return err;
error:
appns_sapi_free_socket (app_ns, ccs);
return err;
}
void
appns_sapi_del_ns_socket (app_namespace_t *app_ns)
{
app_ns_api_handle_t *handle;
clib_socket_t *cs;
pool_foreach (cs, app_ns->app_sockets)
{
handle = (app_ns_api_handle_t *) &cs->private_data;
clib_file_del_by_index (&file_main, handle->aah_file_index);
clib_socket_close (cs);
clib_socket_free (cs);
}
pool_free (app_ns->app_sockets);
}
int
appns_sapi_add_ns_socket (app_namespace_t * app_ns)
{
char *subdir = "/app_ns_sockets/";
app_ns_api_handle_t *handle;
clib_file_t cf = { 0 };
struct stat file_stat;
clib_error_t *err;
clib_socket_t *cs;
char dir[4096];
snprintf (dir, sizeof (dir), "%s%s", vlib_unix_get_runtime_dir (), subdir);
if (!app_ns->sock_name)
app_ns->sock_name = format (0, "%s%v%c", dir, app_ns->ns_id, 0);
/*
* Create and initialize socket to listen on
*/
cs = appns_sapi_alloc_socket (app_ns);
cs->config = (char *) vec_dup (app_ns->sock_name);
cs->flags = CLIB_SOCKET_F_IS_SERVER |
CLIB_SOCKET_F_ALLOW_GROUP_WRITE |
CLIB_SOCKET_F_SEQPACKET | CLIB_SOCKET_F_PASSCRED;
if (clib_socket_prefix_get_type (cs->config) == CLIB_SOCKET_TYPE_UNIX)
{
err = vlib_unix_recursive_mkdir ((char *) dir);
if (err)
{
clib_error_report (err);
return SESSION_E_SYSCALL;
}
}
if ((err = clib_socket_init (cs)))
{
clib_error_report (err);
return -1;
}
if (clib_socket_prefix_get_type (cs->config) == CLIB_SOCKET_TYPE_UNIX &&
stat ((char *) app_ns->sock_name, &file_stat) == -1)
return -1;
/*
* Start polling it
*/
cf.read_function = sapi_sock_accept_ready;
cf.file_descriptor = cs->fd;
/* File points to namespace */
handle = (app_ns_api_handle_t *) & cf.private_data;
handle->aah_app_ns_index = app_namespace_index (app_ns);
handle->aah_sock_index = appns_sapi_socket_index (app_ns, cs);
cf.description = format (0, "app sock listener: %s", app_ns->sock_name);
/* Socket points to clib file index */
handle = (app_ns_api_handle_t *) & cs->private_data;
handle->aah_file_index = clib_file_add (&file_main, &cf);
handle->aah_app_wrk_index = APP_INVALID_INDEX;
return 0;
}
#include <vnet/session/session.api.c>
static clib_error_t *
session_api_hookup (vlib_main_t *vm)
{
/*
* Set up the (msg_name, crc, message-id) table
*/
REPLY_MSG_ID_BASE = setup_message_id_table ();
return 0;
}
VLIB_API_INIT_FUNCTION (session_api_hookup);
/*
* fd.io coding-style-patch-verification: ON
*
* Local Variables:
* eval: (c-set-style "gnu")
* End:
*/
|
c6e152e4327f889c8decb65c4fee8fd6aa761cb4
|
a6b5276e3ef02668a9d6eee80acfd7d3cc7ffbb7
|
/src/ffx-fsr2-api/ffx_fsr2_private.h
|
6b5fbc51177c7cc806c3d29fa81670347927310f
|
[
"MIT"
] |
permissive
|
GPUOpen-Effects/FidelityFX-FSR2
|
1e5ff0709647c1365afb871c89ba176b30a0baaa
|
1680d1edd5c034f88ebbbb793d8b88f8842cf804
|
refs/heads/master
| 2023-06-22T14:38:32.950255
| 2023-05-31T13:59:47
| 2023-05-31T13:59:47
| 506,164,578
| 1,592
| 159
|
NOASSERTION
| 2023-08-26T18:40:53
| 2022-06-22T08:37:24
|
C
|
UTF-8
|
C
| false
| false
| 3,880
|
h
|
ffx_fsr2_private.h
|
// This file is part of the FidelityFX SDK.
//
// Copyright (c) 2022-2023 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, 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
// Constants for FSR2 DX12 dispatches. Must be kept in sync with cbFSR2 in ffx_fsr2_callbacks_hlsl.h
typedef struct Fsr2Constants {
int32_t renderSize[2];
int32_t maxRenderSize[2];
int32_t displaySize[2];
int32_t inputColorResourceDimensions[2];
int32_t lumaMipDimensions[2];
int32_t lumaMipLevelToUse;
int32_t frameIndex;
float deviceToViewDepth[4];
float jitterOffset[2];
float motionVectorScale[2];
float downscaleFactor[2];
float motionVectorJitterCancellation[2];
float preExposure;
float previousFramePreExposure;
float tanHalfFOV;
float jitterPhaseCount;
float deltaTime;
float dynamicResChangeFactor;
float viewSpaceToMetersFactor;
} Fsr2Constants;
struct FfxFsr2ContextDescription;
struct FfxDeviceCapabilities;
struct FfxPipelineState;
struct FfxResource;
// FfxFsr2Context_Private
// The private implementation of the FSR2 context.
typedef struct FfxFsr2Context_Private {
FfxFsr2ContextDescription contextDescription;
Fsr2Constants constants;
FfxDevice device;
FfxDeviceCapabilities deviceCapabilities;
FfxPipelineState pipelineDepthClip;
FfxPipelineState pipelineReconstructPreviousDepth;
FfxPipelineState pipelineLock;
FfxPipelineState pipelineAccumulate;
FfxPipelineState pipelineAccumulateSharpen;
FfxPipelineState pipelineRCAS;
FfxPipelineState pipelineComputeLuminancePyramid;
FfxPipelineState pipelineGenerateReactive;
FfxPipelineState pipelineTcrAutogenerate;
// 2 arrays of resources, as e.g. FFX_FSR2_RESOURCE_IDENTIFIER_LOCK_STATUS will use different resources when bound as SRV vs when bound as UAV
FfxResourceInternal srvResources[FFX_FSR2_RESOURCE_IDENTIFIER_COUNT];
FfxResourceInternal uavResources[FFX_FSR2_RESOURCE_IDENTIFIER_COUNT];
bool firstExecution;
bool refreshPipelineStates;
uint32_t resourceFrameIndex;
float previousJitterOffset[2];
int32_t jitterPhaseCountRemaining;
} FfxFsr2Context_Private;
|
0751f27a0d22ef4585c19e9abd8235c82f387623
|
736e760612f2b431c4b2524fe1a4a8e4083c72a1
|
/libsip/src/uac/sip-uac-bye.c
|
edfcc3f6d95967aaabc11c9bd3885871ed9ea641
|
[
"MIT"
] |
permissive
|
ireader/media-server
|
7f86da8ff0c8694876a2043d50a1260f315dad8a
|
3d8647f50fe832856f42b03d1e5b0fe2eafe5796
|
refs/heads/master
| 2023-09-03T17:53:13.722595
| 2023-09-02T03:38:19
| 2023-09-02T03:38:19
| 15,598,496
| 2,785
| 1,015
|
MIT
| 2023-08-30T03:45:24
| 2014-01-03T01:43:35
|
C
|
UTF-8
|
C
| false
| false
| 1,010
|
c
|
sip-uac-bye.c
|
#include "sip-uac.h"
#include "sip-dialog.h"
#include "sip-message.h"
#include "sip-uac-transaction.h"
int sip_uac_onbye(struct sip_uac_transaction_t* t, int code)
{
struct sip_dialog_t* dialog;
//if ( (200 <= reply->u.s.code && reply->u.s.code < 300) || 481 == reply->u.s.code )
{
dialog = sip_dialog_fetch(t->agent, &t->req->callid, &t->req->from.tag, &t->req->to.tag);
if (dialog)
{
sip_dialog_remove(t->agent, dialog);
sip_dialog_release(dialog);
}
}
return 0;
}
struct sip_uac_transaction_t* sip_uac_bye(struct sip_agent_t* sip, struct sip_dialog_t* dialog, sip_uac_onreply onbye, void* param)
{
struct sip_message_t* req;
struct sip_uac_transaction_t* t;
++dialog->local.id;
req = sip_message_create(SIP_MESSAGE_REQUEST);
if (0 != sip_message_init2(req, SIP_METHOD_BYE, dialog))
{
--dialog->local.id;
sip_message_destroy(req);
return NULL;
}
t = sip_uac_transaction_create(sip, req);
t->onhandle = sip_uac_onbye;
t->onreply = onbye;
t->param = param;
return t;
}
|
ba03c961720a3bcca65888074371e605d001c0fe
|
9ddb8156ad2955f303055ae6d69509ddbdaecc41
|
/libs/OpenSSL/include/openssl/hmac.h
|
2b7b20727830b42ae50af2cfb95ca3f5183dd0b2
|
[
"MIT"
] |
permissive
|
Serial-Studio/Serial-Studio
|
3097a03a785a1e5d293357dd14bbb248609152b4
|
0a16c90acdde2e99a5e78dc158eae38cf0926c19
|
refs/heads/master
| 2023-08-27T08:42:15.383058
| 2023-02-06T03:32:38
| 2023-02-06T03:32:38
| 305,089,628
| 3,794
| 568
|
NOASSERTION
| 2022-09-27T17:41:22
| 2020-10-18T11:49:02
|
C++
|
UTF-8
|
C
| false
| false
| 1,976
|
h
|
hmac.h
|
/*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef OPENSSL_HMAC_H
#define OPENSSL_HMAC_H
#pragma once
#include <openssl/macros.h>
#ifndef OPENSSL_NO_DEPRECATED_3_0
# define HEADER_HMAC_H
#endif
#include <openssl/opensslconf.h>
#include <openssl/evp.h>
#ifndef OPENSSL_NO_DEPRECATED_3_0
# define HMAC_MAX_MD_CBLOCK 200 /* Deprecated */
#endif
#ifdef __cplusplus
extern "C" {
#endif
#ifndef OPENSSL_NO_DEPRECATED_3_0
OSSL_DEPRECATEDIN_3_0 size_t HMAC_size(const HMAC_CTX *e);
OSSL_DEPRECATEDIN_3_0 HMAC_CTX *HMAC_CTX_new(void);
OSSL_DEPRECATEDIN_3_0 int HMAC_CTX_reset(HMAC_CTX *ctx);
OSSL_DEPRECATEDIN_3_0 void HMAC_CTX_free(HMAC_CTX *ctx);
#endif
#ifndef OPENSSL_NO_DEPRECATED_1_1_0
OSSL_DEPRECATEDIN_1_1_0 __owur int HMAC_Init(HMAC_CTX *ctx, const void *key, int len,
const EVP_MD *md);
#endif
#ifndef OPENSSL_NO_DEPRECATED_3_0
OSSL_DEPRECATEDIN_3_0 int HMAC_Init_ex(HMAC_CTX *ctx, const void *key, int len, const EVP_MD *md,
ENGINE *impl);
OSSL_DEPRECATEDIN_3_0 int HMAC_Update(HMAC_CTX *ctx, const unsigned char *data, size_t len);
OSSL_DEPRECATEDIN_3_0 int HMAC_Final(HMAC_CTX *ctx, unsigned char *md, unsigned int *len);
OSSL_DEPRECATEDIN_3_0 __owur int HMAC_CTX_copy(HMAC_CTX *dctx, HMAC_CTX *sctx);
OSSL_DEPRECATEDIN_3_0 void HMAC_CTX_set_flags(HMAC_CTX *ctx, unsigned long flags);
OSSL_DEPRECATEDIN_3_0 const EVP_MD *HMAC_CTX_get_md(const HMAC_CTX *ctx);
#endif
unsigned char *HMAC(const EVP_MD *evp_md, const void *key, int key_len, const unsigned char *data,
size_t data_len, unsigned char *md, unsigned int *md_len);
#ifdef __cplusplus
}
#endif
#endif
|
1fb44e14bb33814742fa3fa9d322b63cd9851afd
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/include/linux/platform_data/clk-u300.h
|
8429e73911a1f76c03fa1aeb0d63ff0136976fe2
|
[
"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
| 47
|
h
|
clk-u300.h
|
void __init u300_clk_init(void __iomem *base);
|
71d7fb74ce5df0a3a81c4d3ad36f05fc1f600bb1
|
19102a3c11268052348cf669e23bbfe2780bb067
|
/MinecraftC/GUI/LevelNameScreen.c
|
58ddabefc0fe99d1176b79186d3110eed9864e78
|
[
"MIT"
] |
permissive
|
johnpayne-dev/MinecraftC
|
4f6578fd12c0ff8b70e8b9d2c11c4934a822203c
|
43928d42e1f32bd76a994f0bb22c0153a7271b3f
|
refs/heads/main
| 2023-08-04T00:51:16.467779
| 2022-07-31T18:45:33
| 2022-07-31T18:45:33
| 338,597,768
| 303
| 31
|
MIT
| 2022-07-31T18:45:34
| 2021-02-13T14:55:07
|
C
|
UTF-8
|
C
| false
| false
| 3,422
|
c
|
LevelNameScreen.c
|
#include <string.h>
#include "LevelNameScreen.h"
#include "Screen.h"
#include "../Minecraft.h"
#include "../Utilities/Log.h"
void LevelNameScreenCreate(LevelNameScreen * screen, GUIScreen * parent, char * name, int id) {
GUIScreenCreate(screen);
screen->type = GUIScreenTypeLevelName;
screen->levelName.title = "Enter level name:";
screen->levelName.counter = 0;
screen->levelName.parent = parent;
screen->levelName.name = StringCreate(name);
screen->levelName.id = id;
if (strcmp(name, "---") == 0) { StringSet(&screen->levelName.name, ""); }
}
void LevelNameScreenOnOpen(LevelNameScreen * screen) {
screen->buttons = ListPush(screen->buttons, &(Button){ 0 });
ButtonCreate(&screen->buttons[ListLength(screen->buttons) - 1], 0, screen->width / 2 - 100, screen->height / 4 + 120, "Save");
screen->buttons = ListPush(screen->buttons, &(Button){ 0 });
ButtonCreate(&screen->buttons[ListLength(screen->buttons) - 1], 1, screen->width / 2 - 100, screen->height / 4 + 144, "Cancel");
screen->buttons[0].active = StringLength(screen->levelName.name) > 0;
}
void LevelNameScreenOnClose(LevelNameScreen * screen) {
}
void LevelNameScreenTick(LevelNameScreen * screen) {
screen->levelName.counter++;
}
void LevelNameScreenRender(LevelNameScreen * screen, int mx, int my) {
ScreenDrawFadingBox(0, 0, screen->width, screen->height, 0x05050060, 0x303060A0);
ScreenDrawCenteredString(screen->font, screen->levelName.title, screen->width / 2, 40, 0xffffffff);
int x = screen->width / 2 - 100;
int y = screen->height / 2 - 10;
ScreenDrawBox(x - 1, y - 1, x + 201, y + 21, 0xA0A0A0FF);
ScreenDrawBox(x, y, x + 200, y + 20, 0x000000ff);
String string = StringCreate(screen->levelName.name);
StringConcat(&string, screen->levelName.counter / 6 % 2 == 0 ? "_" : "");
ScreenDrawString(screen->font, string, x + 4, y + 6, 0xE0E0E0FF);
StringFree(string);
}
void LevelNameScreenOnKeyPressed(LevelNameScreen * screen, char eventChar, int eventKey) {
if (eventKey == SDL_SCANCODE_BACKSPACE && StringLength(screen->levelName.name) > 0) {
screen->levelName.name = StringSub(screen->levelName.name, 0, StringLength(screen->levelName.name) - 2);
}
String allowedChars = StringCreate("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ,.:-_\'*!\"#%/()=+?[]{}<>");
if (StringIndexOf(allowedChars, eventChar) >= 0 && StringLength(screen->levelName.name) < 64) {
StringConcat(&screen->levelName.name, (char[]){ eventChar, '\0' });
}
StringFree(allowedChars);
screen->buttons[0].active = StringLength(screen->levelName.name) > 0;
}
void LevelNameScreenOnButtonClicked(LevelNameScreen * screen, Button * button) {
if (button->active) {
if (button->id == 0 && StringLength(screen->levelName.name) > 0) {
String filePath = StringCreate(screen->minecraft->workingDirectory);
StringConcat(&filePath, "Level0.dat");
filePath[StringLength(filePath) - 5] += screen->levelName.id;
bool success = LevelSave(&screen->minecraft->level, filePath, screen->levelName.name);
StringFree(filePath);
if (!success) {
LogWarning("failed to save level: %s\n", SDL_GetError());
}
MinecraftSetCurrentScreen(screen->minecraft, NULL);
MinecraftGrabMouse(screen->minecraft);
}
if (button->id == 1) {
MinecraftSetCurrentScreen(screen->minecraft, screen->levelName.parent);
}
}
}
void LevelNameScreenDestroy(LevelNameScreen * screen) {
StringFree(screen->levelName.name);
}
|
dabf7aaaa5eda55d9f4b38493a3504fcd0bde0fe
|
f369e1f7dd4312baf5c524ebeade904a89d48047
|
/src/win/stdio.c
|
302fcf0c1460504de4353f345ef3f025726f920f
|
[
"MIT"
] |
permissive
|
r-lib/processx
|
0f0639c77fb897249eeb2598c1712a631f0de2a2
|
25812a1b98d6a8f993f6799079616fffeae7aa56
|
refs/heads/main
| 2023-07-26T11:10:03.374683
| 2023-07-01T16:17:27
| 2023-07-01T16:17:27
| 66,083,698
| 184
| 48
|
NOASSERTION
| 2023-07-19T00:17:14
| 2016-08-19T13:18:57
|
R
|
UTF-8
|
C
| false
| false
| 13,545
|
c
|
stdio.c
|
#include <R.h>
#include "../processx.h"
#include "processx-stdio.h"
#include <stdio.h>
#include <io.h>
HANDLE processx__default_iocp = NULL;
static int processx__create_nul_handle(HANDLE *handle_ptr, DWORD access) {
HANDLE handle;
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
handle = CreateFileW(
/* lpFilename = */ L"NUL",
/* dwDesiredAccess= */ access,
/* dwShareMode = */ FILE_SHARE_READ | FILE_SHARE_WRITE,
/* lpSecurityAttributes = */ &sa,
/* dwCreationDisposition = */ OPEN_EXISTING,
/* dwFlagsAndAttributes = */ 0,
/* hTemplateFile = */ NULL);
if (handle == INVALID_HANDLE_VALUE) { return GetLastError(); }
*handle_ptr = handle;
return 0;
}
static int processx__create_input_handle(HANDLE *handle_ptr, const char *file,
DWORD access) {
HANDLE handle;
SECURITY_ATTRIBUTES sa;
int err;
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
WCHAR *filew;
err = processx__utf8_to_utf16_alloc(file, &filew);
if (err) return(err);
handle = CreateFileW(
/* lpFilename = */ filew,
/* dwDesiredAccess= */ access,
/* dwShareMode = */ FILE_SHARE_READ | FILE_SHARE_WRITE,
/* lpSecurityAttributes = */ &sa,
/* dwCreationDisposition = */ OPEN_EXISTING,
/* dwFlagsAndAttributes = */ 0,
/* hTemplateFile = */ NULL);
if (handle == INVALID_HANDLE_VALUE) { return GetLastError(); }
*handle_ptr = handle;
return 0;
}
static int processx__create_output_handle(HANDLE *handle_ptr, const char *file,
DWORD access) {
HANDLE handle;
SECURITY_ATTRIBUTES sa;
int err;
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
WCHAR *filew;
err = processx__utf8_to_utf16_alloc(file, &filew);
if (err) return(err);
handle = CreateFileW(
/* lpFilename = */ filew,
/* dwDesiredAccess= */ access,
/* dwShareMode = */ FILE_SHARE_READ | FILE_SHARE_WRITE,
/* lpSecurityAttributes = */ &sa,
/* dwCreationDisposition = */ CREATE_ALWAYS,
/* dwFlagsAndAttributes = */ 0,
/* hTemplateFile = */ NULL);
if (handle == INVALID_HANDLE_VALUE) { return GetLastError(); }
/* We will append, so set pointer to end of file */
SetFilePointer(handle, 0, NULL, FILE_END);
*handle_ptr = handle;
return 0;
}
static void processx__unique_pipe_name(char* ptr, char* name, size_t size) {
int r;
GetRNGstate();
r = (int)(unif_rand() * 65000);
snprintf(name, size, "\\\\?\\pipe\\px\\%p-%lu", ptr + r, GetCurrentProcessId());
PutRNGstate();
}
int processx__create_pipe(void *id, HANDLE* parent_pipe_ptr,
HANDLE* child_pipe_ptr, const char *cname) {
char pipe_name[40];
HANDLE hOutputRead = INVALID_HANDLE_VALUE;
HANDLE hOutputWrite = INVALID_HANDLE_VALUE;
SECURITY_ATTRIBUTES sa;
DWORD err;
char *errmessage = "error for process '%s'";
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
for (;;) {
processx__unique_pipe_name(id, pipe_name, sizeof(pipe_name));
hOutputRead = CreateNamedPipeA(
pipe_name,
PIPE_ACCESS_OUTBOUND | PIPE_ACCESS_INBOUND |
FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
1,
65536,
65536,
0,
NULL);
if (hOutputRead != INVALID_HANDLE_VALUE) {
break;
}
err = GetLastError();
if (err != ERROR_PIPE_BUSY && err != ERROR_ACCESS_DENIED) {
errmessage = "creating read pipe for '%s'";
goto error;
}
}
hOutputWrite = CreateFileA(
pipe_name,
GENERIC_WRITE,
0,
&sa,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hOutputWrite == INVALID_HANDLE_VALUE) {
err = GetLastError();
errmessage = "creating write pipe for '%s'";
goto error;
}
*parent_pipe_ptr = hOutputRead;
*child_pipe_ptr = hOutputWrite;
return 0;
error:
if (hOutputRead != INVALID_HANDLE_VALUE) CloseHandle(hOutputRead);
if (hOutputWrite != INVALID_HANDLE_VALUE) CloseHandle(hOutputWrite);
R_THROW_SYSTEM_ERROR_CODE(err, errmessage, cname);
return 0; /* never reached */
}
int processx__create_input_pipe(void *id, HANDLE* parent_pipe_ptr,
HANDLE* child_pipe_ptr, const char *cname) {
char pipe_name[40];
HANDLE hOutputRead = INVALID_HANDLE_VALUE;
HANDLE hOutputWrite = INVALID_HANDLE_VALUE;
SECURITY_ATTRIBUTES sa;
DWORD err;
char *errmessage = "error for '%s'";
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
for (;;) {
processx__unique_pipe_name(id, pipe_name, sizeof(pipe_name));
hOutputRead = CreateNamedPipeA(
pipe_name,
PIPE_ACCESS_OUTBOUND | PIPE_ACCESS_INBOUND |
FILE_FLAG_FIRST_PIPE_INSTANCE,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
1,
65536,
65536,
0,
NULL);
if (hOutputRead != INVALID_HANDLE_VALUE) {
break;
}
err = GetLastError();
if (err != ERROR_PIPE_BUSY && err != ERROR_ACCESS_DENIED) {
errmessage = "creating read pipe for '%s'";
goto error;
}
}
hOutputWrite = CreateFileA(
pipe_name,
GENERIC_READ,
0,
&sa,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hOutputWrite == INVALID_HANDLE_VALUE) {
err = GetLastError();
errmessage = "creating write pipe for '%s'";
goto error;
}
*parent_pipe_ptr = hOutputRead;
*child_pipe_ptr = hOutputWrite;
return 0;
error:
if (hOutputRead != INVALID_HANDLE_VALUE) CloseHandle(hOutputRead);
if (hOutputWrite != INVALID_HANDLE_VALUE) CloseHandle(hOutputWrite);
R_THROW_SYSTEM_ERROR_CODE(err, errmessage, cname);
return 0; /* never reached */
}
processx_connection_t * processx__create_connection(
HANDLE pipe_handle, const char *membername, SEXP private,
const char *encoding, BOOL async) {
processx_connection_t *con;
SEXP res;
con = processx_c_connection_create(
pipe_handle,
async ? PROCESSX_FILE_TYPE_ASYNCPIPE : PROCESSX_FILE_TYPE_PIPE,
encoding, NULL, &res);
defineVar(install(membername), res, private);
return con;
}
static int processx__duplicate_handle(HANDLE handle, HANDLE* dup) {
HANDLE current_process;
/* _get_osfhandle will sometimes return -2 in case of an error. This seems */
/* to happen when fd <= 2 and the process' corresponding stdio handle is */
/* set to NULL. Unfortunately DuplicateHandle will happily duplicate */
/* (HANDLE) -2, so this situation goes unnoticed until someone tries to */
/* use the duplicate. Therefore we filter out known-invalid handles here. */
if (handle == INVALID_HANDLE_VALUE ||
handle == NULL ||
handle == (HANDLE) -2) {
*dup = INVALID_HANDLE_VALUE;
return ERROR_INVALID_HANDLE;
}
current_process = GetCurrentProcess();
if (!DuplicateHandle(current_process,
handle,
current_process,
dup,
0,
TRUE,
DUPLICATE_SAME_ACCESS)) {
*dup = INVALID_HANDLE_VALUE;
return GetLastError();
}
return 0;
}
int processx__stdio_create(processx_handle_t *handle,
SEXP connections, BYTE** buffer_ptr, SEXP private,
const char *encoding, const char *cname, int* inherit_std) {
BYTE* buffer;
int i;
int err;
int count = LENGTH(connections);
if (count > 255) {
R_THROW_ERROR("Too many processx connections to inherit, '%s'", cname);
}
/* Allocate the child stdio buffer */
buffer = malloc(CHILD_STDIO_SIZE(count));
if (!buffer) { R_THROW_ERROR("Out of memory for process"); }
/* Prepopulate the buffer with INVALID_HANDLE_VALUE handles, so we can
clean up on failure*/
CHILD_STDIO_COUNT(buffer) = count;
for (i = 0; i < count; i++) {
CHILD_STDIO_CRT_FLAGS(buffer, i) = 0;
CHILD_STDIO_HANDLE(buffer, i) = INVALID_HANDLE_VALUE;
}
handle->pipes[0] = handle->pipes[1] = handle->pipes[2] = 0;
for (i = 0; i < count; i++) {
DWORD access = (i == 0) ?
FILE_GENERIC_READ | FILE_WRITE_ATTRIBUTES :
FILE_GENERIC_WRITE | FILE_READ_ATTRIBUTES;
SEXP output = VECTOR_ELT(connections, i);
const char *stroutput =
Rf_isString(output) ? CHAR(STRING_ELT(output, 0)) : NULL;
/* NULL means ignore */
if (isNull(output)) {
/* ignored output */
err = processx__create_nul_handle(&CHILD_STDIO_HANDLE(buffer, i), access);
if (err) { goto error; }
CHILD_STDIO_CRT_FLAGS(buffer, i) = FOPEN | FDEV;
} else if (i == 2 && stroutput && ! strcmp("2>&1", stroutput)) {
/* This is stderr, sent to stdout */
/* We need to turn off buffering, otherwise the output on
the two handles won't be correctly interleaved.
We set FDEV on the pipes/files. This tricks windows
into turning off the CRT buffering */
CHILD_STDIO_COPY(buffer, 2, 1);
CHILD_STDIO_CRT_FLAGS(buffer, 1) = FOPEN | FDEV;
CHILD_STDIO_CRT_FLAGS(buffer, 2) = FOPEN | FDEV;
} else if (stroutput && ! strcmp("|", stroutput)) {
/* piped output */
processx_connection_t *con = 0;
HANDLE parent_handle;
const char *r_pipe_name = i == 0 ? "stdin_pipe" :
(i == 1 ? "stdout_pipe" : "stderr_pipe");
if (i == 0) {
err = processx__create_input_pipe(handle, &parent_handle,
&CHILD_STDIO_HANDLE(buffer, i), cname);
} else {
err = processx__create_pipe(handle, &parent_handle,
&CHILD_STDIO_HANDLE(buffer, i), cname);
}
if (err) goto error;
CHILD_STDIO_CRT_FLAGS(buffer, i) = FOPEN | FPIPE;
con = processx__create_connection(parent_handle, r_pipe_name,
private, encoding, i != 0);
handle->pipes[i] = con;
} else if (stroutput && strcmp("", stroutput)) {
/* output to file */
if (i == 0) {
err = processx__create_input_handle(&CHILD_STDIO_HANDLE(buffer, i),
stroutput, access);
} else {
err = processx__create_output_handle(&CHILD_STDIO_HANDLE(buffer, i),
stroutput, access);
}
if (err) { goto error; }
CHILD_STDIO_CRT_FLAGS(buffer, i) = FOPEN | FDEV;
} else {
/* inherit connection */
HANDLE child_handle;
HANDLE ihnd;
/* std connection or extra connection */
if (stroutput) {
*inherit_std = 1;
DWORD nh = i == 0 ? STD_INPUT_HANDLE :
(i == 1 ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE );
ihnd = GetStdHandle(nh);
if (ihnd == INVALID_HANDLE_VALUE ||
ihnd == NULL ||
ihnd == (HANDLE) -2) {
FILE *sh = i == 0 ? stdin : (i == 1 ? stdout : stderr);
int fd = _fileno(sh);
REprintf("Opening fd %i\n", fd);
ihnd = (HANDLE) _get_osfhandle(fd);
}
} else {
processx_connection_t *ccon = R_ExternalPtrAddr(output);
if (!ccon) R_THROW_ERROR("Invalid (closed) connection");
ihnd = (HANDLE*) processx_c_connection_fileno(ccon);
}
err = processx__duplicate_handle(ihnd, &child_handle);
if (err) goto error;
switch (GetFileType(child_handle)) {
case FILE_TYPE_DISK:
CHILD_STDIO_CRT_FLAGS(buffer, i) = FOPEN;
break;
case FILE_TYPE_PIPE:
CHILD_STDIO_CRT_FLAGS(buffer, i) = FOPEN | FDEV;
break;
case FILE_TYPE_CHAR:
case FILE_TYPE_REMOTE:
case FILE_TYPE_UNKNOWN:
CHILD_STDIO_CRT_FLAGS(buffer, i) = FOPEN | FDEV;
break;
default:
err = -1;
goto error;
}
CHILD_STDIO_HANDLE(buffer, i) = child_handle;
}
}
*buffer_ptr = buffer;
return 0;
error:
processx__stdio_destroy(buffer);
for (i = 0; i < 3; i++) {
if (handle->pipes[i]) {
processx_c_connection_destroy(handle->pipes[i]);
}
}
return err;
}
void processx__stdio_destroy(BYTE* buffer) {
int i, count;
count = CHILD_STDIO_COUNT(buffer);
for (i = 0; i < count; i++) {
HANDLE handle = CHILD_STDIO_HANDLE(buffer, i);
if (handle != INVALID_HANDLE_VALUE) {
CloseHandle(handle);
}
}
free(buffer);
}
void processx__stdio_noinherit(BYTE* buffer) {
int i, count;
count = CHILD_STDIO_COUNT(buffer);
for (i = 0; i < count; i++) {
HANDLE handle = CHILD_STDIO_HANDLE(buffer, i);
if (handle != INVALID_HANDLE_VALUE) {
SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0);
}
}
}
int processx__stdio_verify(BYTE* buffer, WORD size) {
unsigned int count;
/* Check the buffer pointer. */
if (buffer == NULL)
return 0;
/* Verify that the buffer is at least big enough to hold the count. */
if (size < CHILD_STDIO_SIZE(0))
return 0;
/* Verify if the count is within range. */
count = CHILD_STDIO_COUNT(buffer);
if (count > 256)
return 0;
/* Verify that the buffer size is big enough to hold info for N FDs. */
if (size < CHILD_STDIO_SIZE(count))
return 0;
return 1;
}
WORD processx__stdio_size(BYTE* buffer) {
return (WORD) CHILD_STDIO_SIZE(CHILD_STDIO_COUNT((buffer)));
}
HANDLE processx__stdio_handle(BYTE* buffer, int fd) {
return CHILD_STDIO_HANDLE(buffer, fd);
}
|
3b872b758fbcf0b6dc999c08b21376e6974cb940
|
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
|
/sys/arch/acorn32/podulebus/rapidereg.h
|
f8c06c24bdac1e89306ef059c27ec391b0e392c6
|
[] |
no_license
|
NetBSD/src
|
1a9cbc22ed778be638b37869ed4fb5c8dd616166
|
23ee83f7c0aea0777bd89d8ebd7f0cde9880d13c
|
refs/heads/trunk
| 2023-08-31T13:24:58.105962
| 2023-08-27T15:50:47
| 2023-08-27T15:50:47
| 88,439,547
| 656
| 348
| null | 2023-07-20T20:07:24
| 2017-04-16T20:03:43
| null |
UTF-8
|
C
| false
| false
| 3,391
|
h
|
rapidereg.h
|
/* $NetBSD: rapidereg.h,v 1.1 2001/10/05 22:27:58 reinoud Exp $ */
/*
* Copyright (c) 1997 Mark Brinicombe
* Copyright (c) 1997 Causality Limited
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Mark Brinicombe
* for the NetBSD Project.
* 4. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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.
*/
/*
* Thanks to Chris Honey at Raymond Datalink for providing information on
* addressing the RapIDE podule.
* RapIDE32 is Copyright (C) 1995,1996 Raymond Datalink. RapIDE32 is
* manufactured under license by Yellowstone Educational Solutions.
*/
/*
* Registers and address offsets for the Yellowstone RapIDE card.
*
* These are for issue 2 cards only.
*/
/*
* This file needs to be extended to provide register information on
* both versions of the card.
*/
/* IDE drive registers */
#define PRIMARY_DRIVE_REGISTERS_OFFSET 0x400080
#define PRIMARY_AUX_REGISTER_OFFSET 0x400298
#define PRIMARY_DATA_REGISTER_OFFSET 0x600080
#define SECONDARY_DRIVE_REGISTERS_OFFSET 0x400000
#define SECONDARY_AUX_REGISTER_OFFSET 0x400218
#define SECONDARY_DATA_REGISTER_OFFSET 0x600000
#define DRIVE_REGISTERS_SPACE 0x20
#define DRIVE_REGISTER_BYTE_SPACING 4
/* Other registers */
#define CONTROL_REGISTERS_OFFSET 0x200000
#define CONTROL_REGISTER_SPACE 16
#define IRQ_MASK_REGISTER_OFFSET 0
#define IRQ_STATUS_REGISTER_OFFSET 0
#define IRQ_REQUEST_REGISTER_OFFSET 1
#define IRQ_REQUEST_REGISTER_BYTE_OFFSET (IRQ_REQUEST_REGISTER_OFFSET << 2)
#define IRQ_CLEAR_REGISTER_OFFSET 1
#define PRIMARY_IRQ_MASK 0x01
#define SECONDARY_IRQ_MASK 0x02
#define IRQ_MASK (PRIMARY_IRQ_MASK | SECONDARY_IRQ_MASK)
#define VERSION_REGISTER_OFFSET 3
#define VERSION_REGISTER_MASK 0x03
#define VERSION_1_ID 0x00
#define VERSION_2_ID 0x01
#define PIO_MODE_CONTROL_REGISTER_OFFSET 3
#define PIO_MODE_0 0
#define PIO_MODE_1 1
#define PIO_MODE_2 2
#define PIO_MODE_3 3
#define PIO_MODE_4 4
|
940e32ae36fe3cf1209f591f919930cc5caa1318
|
aa3befea459382dc5c01c925653d54f435b3fb0f
|
/arch/arm/src/lpc31xx/lpc31_pllconfig.c
|
5cfebad25f2c5eca7496e87f90cee12cd73d51c7
|
[
"MIT-open-group",
"BSD-3-Clause",
"HPND-sell-variant",
"BSD-4-Clause-UC",
"LicenseRef-scancode-warranty-disclaimer",
"MIT-0",
"LicenseRef-scancode-bsd-atmel",
"LicenseRef-scancode-gary-s-brown",
"LicenseRef-scancode-proprietary-license",
"SunPro",
"MIT",
"LicenseRef-scancode-public-domain-disclaimer",
"LicenseRef-scancode-other-permissive",
"HPND",
"ISC",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"GPL-1.0-or-later",
"CC-BY-2.0",
"CC-BY-4.0"
] |
permissive
|
apache/nuttx
|
14519a7bff4a87935d94fb8fb2b19edb501c7cec
|
606b6d9310fb25c7d92c6f95bf61737e3c79fa0f
|
refs/heads/master
| 2023-08-25T06:55:45.822534
| 2023-08-23T16:03:31
| 2023-08-24T21:25:47
| 228,103,273
| 407
| 241
|
Apache-2.0
| 2023-09-14T18:26:05
| 2019-12-14T23:27:55
|
C
|
UTF-8
|
C
| false
| false
| 7,756
|
c
|
lpc31_pllconfig.c
|
/****************************************************************************
* arch/arm/src/lpc31xx/lpc31_pllconfig.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.
*
****************************************************************************/
/* References:
* - NXP UM10314 LPC3130/31 User manual Rev. 1.01 - 9 September 2009
* - NXP lpc313x.cdl.drivers.zip example driver code
*/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <stdint.h>
#include <arch/board/board.h>
#include "lpc31_cgudrvr.h"
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/****************************************************************************
* Private Types
****************************************************************************/
/****************************************************************************
* Private Data
****************************************************************************/
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Name: lpc31_switchdomains
*
* Description:
* Temporarily switch the reference clock of all domains whose selected
* input is the PLL-to-be configured .
*
****************************************************************************/
static inline uint16_t
lpc31_switchdomains(const struct lpc31_pllconfig_s * const cfg)
{
uint32_t hppll = (cfg->hppll ? CGU_SSR_HPPLL1 : CGU_SSR_HPPLL0);
uint32_t address;
uint32_t regval;
uint16_t dmnset = 0;
int i;
/* Check each domain */
for (i = 0; i < CGU_NDOMAINS; i++)
{
/* Get the switch status registers (SSR) for this frequency input
* domain
*/
address = LPC31_CGU_SSR(i);
regval = getreg32(address);
/* Check if the current frequency selection is the
* PLL-to-be-configured
*/
if ((regval & CGU_SSR_FS_MASK) == hppll)
{
/* Yes.. switch reference clock in to FFAST */
lpc31_selectfreqin((enum lpc31_domainid_e)i, CGU_FS_FFAST);
/* Add the domain to the set to be restored after the PLL is
* configured
*/
dmnset |= (1 << i);
}
}
return dmnset;
}
/****************************************************************************
* Name: lpc31_restoredomains
*
* Description:
* Restore the PLL reference clock to the domains that were temporarily
* switched to FFAST by lpc31_switchdomains.
*
****************************************************************************/
static inline void
lpc31_restoredomains(const struct lpc31_pllconfig_s * const cfg,
uint16_t dmnset)
{
uint32_t finsel = (cfg->hppll ? CGU_FS_HPPLL1 : CGU_FS_HPPLL0);
int i;
/* Check each domain */
for (i = 0; i < CGU_NDOMAINS; i++)
{
/* Was this one switched? */
if ((dmnset & (1 << i)) != 0)
{
/* Switch input reference clock to newly configured HPLL */
lpc31_selectfreqin((enum lpc31_domainid_e)i, finsel);
}
}
}
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: lpc31_pllconfig
*
* Description:
* Configure the PLL according to the provided selections.
*
****************************************************************************/
void lpc31_pllconfig(const struct lpc31_pllconfig_s * const cfg)
{
uint32_t pllbase;
uint16_t dmnset = 0;
/* Switch domains connected to HPLL to FFAST */
dmnset = lpc31_switchdomains(cfg);
/* Get the PLL register base address */
pllbase = LPC313x_CGU_HPPLL(cfg->hppll);
/* Disable clock, disable skew enable, power down pll, (dis/en)able post
* divider, (dis/en)able pre-divider, disable free running mode, disable
* bandsel, enable up limmiter, disable bypass
*/
putreg32(CGU_HPMODE_PD, pllbase + LPC31_CGU_HPMODE_OFFSET);
/* Select PLL input frequency source */
putreg32(cfg->finsel, pllbase + LPC31_CGU_HPFINSEL_OFFSET);
/* Set M divider */
putreg32(cfg->mdec & CGU_HPMDEC_MASK, pllbase + LPC31_CGU_HPMDEC_OFFSET);
/* Set N divider */
putreg32(cfg->ndec & CGU_HPNDEC_MASK, pllbase + LPC31_CGU_HPNDEC_OFFSET);
/* Set P divider */
putreg32(cfg->pdec & CGU_HPPDEC_MASK, pllbase + LPC31_CGU_HPPDEC_OFFSET);
/* Set bandwidth */
putreg32(cfg->selr, pllbase + LPC31_CGU_HPSELR_OFFSET);
putreg32(cfg->seli, pllbase + LPC31_CGU_HPSELI_OFFSET);
putreg32(cfg->selp, pllbase + LPC31_CGU_HPSELP_OFFSET);
/* Power up pll */
putreg32((cfg->mode & ~CGU_HPMODE_PD) | CGU_HPMODE_CLKEN,
pllbase + LPC31_CGU_HPMODE_OFFSET);
/* Save the estimated freq in driver data for future clk calcs */
g_boardfreqin[CGU_FREQIN_HPPLL0 + cfg->hppll] = cfg->freq;
/* Wait for PLL to lock */
while ((getreg32(pllbase + LPC31_CGU_HPSTATUS_OFFSET) &
CGU_HPSTATUS_LOCK) == 0);
/* Switch the domains that were temporarily switched to FFAST back to
* the HPPLL
*/
lpc31_restoredomains(cfg, dmnset);
}
/****************************************************************************
* Name: lpc31_hp0pllconfig
*
* Description:
* Configure the HP0 PLL according to the board.h selections.
*
****************************************************************************/
void lpc31_hp0pllconfig(void)
{
struct lpc31_pllconfig_s cfg =
{
.hppll = CGU_HP0PLL,
.finsel = BOARD_HPLL0_FINSEL,
.ndec = BOARD_HPLL0_NDEC,
.mdec = BOARD_HPLL0_MDEC,
.pdec = BOARD_HPLL0_PDEC,
.selr = BOARD_HPLL0_SELR,
.seli = BOARD_HPLL0_SELI,
.selp = BOARD_HPLL0_SELP,
.mode = BOARD_HPLL0_MODE,
.freq = BOARD_HPLL0_FREQ
};
lpc31_pllconfig(&cfg);
}
/****************************************************************************
* Name: lpc31_hp1pllconfig
*
* Description:
* Configure the HP1 PLL according to the board.h selections.
*
****************************************************************************/
void lpc31_hp1pllconfig(void)
{
struct lpc31_pllconfig_s cfg =
{
.hppll = CGU_HP1PLL,
.finsel = BOARD_HPLL1_FINSEL,
.ndec = BOARD_HPLL1_NDEC,
.mdec = BOARD_HPLL1_MDEC,
.pdec = BOARD_HPLL1_PDEC,
.selr = BOARD_HPLL1_SELR,
.seli = BOARD_HPLL1_SELI,
.selp = BOARD_HPLL1_SELP,
.mode = BOARD_HPLL1_MODE,
.freq = BOARD_HPLL1_FREQ
};
lpc31_pllconfig(&cfg);
}
|
f07900932af87ab81afa731297dfb17b0d0a4a28
|
035660e8cc10571ebbd0d4393fef063bb7eb98f6
|
/src/overlays/actors/ovl_En_Tite/z_en_tite.c
|
b9d547fb02c966b4cb59ee7ebbacb702e05eff26
|
[] |
no_license
|
zeldaret/mm
|
f163a5e7c4314105777369fa7671ce9c2a99922a
|
4ae00e909e74044f05155683b49d2561f91de7ba
|
refs/heads/master
| 2023-08-06T07:22:04.912966
| 2023-08-04T20:36:03
| 2023-08-04T20:36:03
| 247,875,852
| 915
| 328
| null | 2023-09-14T11:48:59
| 2020-03-17T04:03:07
|
C
|
UTF-8
|
C
| false
| false
| 42,782
|
c
|
z_en_tite.c
|
/*
* File: z_en_tite.c
* Overlay: ovl_En_Tite
* Description: Tektites
*/
#include "z_en_tite.h"
#include "overlays/actors/ovl_En_Clear_Tag/z_en_clear_tag.h"
#include "objects/object_tite/object_tite.h"
#define FLAGS (ACTOR_FLAG_1 | ACTOR_FLAG_4 | ACTOR_FLAG_200)
#define THIS ((EnTite*)thisx)
void EnTite_Init(Actor* thisx, PlayState* play);
void EnTite_Destroy(Actor* thisx, PlayState* play);
void EnTite_Update(Actor* thisx, PlayState* play);
void EnTite_Draw(Actor* thisx, PlayState* play);
void func_80893ED4(EnTite* this);
void func_80893F30(EnTite* this, PlayState* play);
void func_80893FD0(EnTite* this);
void func_80894024(EnTite* this, PlayState* play);
void func_8089408C(EnTite* this, PlayState* play);
void func_808942B4(EnTite* this, PlayState* play);
void func_80894414(EnTite* this);
void func_80894454(EnTite* this, PlayState* play);
void func_8089452C(EnTite* this, PlayState* play);
void func_808945B4(EnTite* this, PlayState* play);
void func_808945EC(EnTite* this);
void func_80894638(EnTite* this, PlayState* play);
void func_8089484C(EnTite* this);
void func_80894910(EnTite* this, PlayState* play);
void func_80894B2C(EnTite* this);
void func_80894BC8(EnTite* this, PlayState* play);
void func_80894E0C(EnTite* this, PlayState* play);
void func_80895020(EnTite* this, PlayState* play);
void func_808951B8(EnTite* this, PlayState* play);
void func_80895424(EnTite* this, PlayState* play);
void func_808955E4(EnTite* this);
void func_80895640(EnTite* this, PlayState* play);
void func_808956B8(EnTite* this);
void func_80895738(EnTite* this, PlayState* play);
void func_80895A10(EnTite* this);
void func_80895AC0(EnTite* this, PlayState* play);
void func_80895CB0(EnTite* this);
void func_80895D08(EnTite* this, PlayState* play);
void func_80895E28(EnTite* this, PlayState* play);
ActorInit En_Tite_InitVars = {
ACTOR_EN_TITE,
ACTORCAT_ENEMY,
FLAGS,
OBJECT_TITE,
sizeof(EnTite),
(ActorFunc)EnTite_Init,
(ActorFunc)EnTite_Destroy,
(ActorFunc)EnTite_Update,
(ActorFunc)EnTite_Draw,
};
static ColliderSphereInit sSphereInit = {
{
COLTYPE_HIT6,
AT_ON | AT_TYPE_ENEMY,
AC_ON | AC_TYPE_PLAYER,
OC1_ON | OC1_TYPE_ALL,
OC2_TYPE_1,
COLSHAPE_SPHERE,
},
{
ELEMTYPE_UNK0,
{ 0xF7CFFFFF, 0x00, 0x08 },
{ 0xF7CFFFFF, 0x00, 0x00 },
TOUCH_ON | TOUCH_SFX_HARD,
BUMP_ON | BUMP_HOOKABLE,
OCELEM_ON,
},
{ 0, { { 0, 1500, 0 }, 20 }, 100 },
};
static DamageTable sDamageTable = {
/* Deku Nut */ DMG_ENTRY(0, 0x1),
/* Deku Stick */ DMG_ENTRY(1, 0x0),
/* Horse trample */ DMG_ENTRY(1, 0x0),
/* Explosives */ DMG_ENTRY(1, 0x0),
/* Zora boomerang */ DMG_ENTRY(1, 0x0),
/* Normal arrow */ DMG_ENTRY(1, 0x0),
/* UNK_DMG_0x06 */ DMG_ENTRY(0, 0x0),
/* Hookshot */ DMG_ENTRY(0, 0xF),
/* Goron punch */ DMG_ENTRY(1, 0x0),
/* Sword */ DMG_ENTRY(1, 0x0),
/* Goron pound */ DMG_ENTRY(0, 0x0),
/* Fire arrow */ DMG_ENTRY(2, 0x2),
/* Ice arrow */ DMG_ENTRY(1, 0x3),
/* Light arrow */ DMG_ENTRY(2, 0x4),
/* Goron spikes */ DMG_ENTRY(1, 0x0),
/* Deku spin */ DMG_ENTRY(0, 0x1),
/* Deku bubble */ DMG_ENTRY(1, 0x0),
/* Deku launch */ DMG_ENTRY(2, 0x0),
/* UNK_DMG_0x12 */ DMG_ENTRY(0, 0x1),
/* Zora barrier */ DMG_ENTRY(0, 0x5),
/* Normal shield */ DMG_ENTRY(0, 0x0),
/* Light ray */ DMG_ENTRY(0, 0x0),
/* Thrown object */ DMG_ENTRY(1, 0x0),
/* Zora punch */ DMG_ENTRY(1, 0x0),
/* Spin attack */ DMG_ENTRY(1, 0x0),
/* Sword beam */ DMG_ENTRY(0, 0x0),
/* Normal Roll */ DMG_ENTRY(0, 0x0),
/* UNK_DMG_0x1B */ DMG_ENTRY(0, 0x0),
/* UNK_DMG_0x1C */ DMG_ENTRY(0, 0x0),
/* Unblockable */ DMG_ENTRY(0, 0x0),
/* UNK_DMG_0x1E */ DMG_ENTRY(0, 0x0),
/* Powder Keg */ DMG_ENTRY(1, 0x0),
};
static CollisionCheckInfoInit sColChkInfoInit = { 2, 40, 40, MASS_HEAVY };
static TexturePtr D_80896B24[2][3] = {
{ object_tite_Tex_001300, object_tite_Tex_001700, object_tite_Tex_001900 },
{ object_tite_Tex_001B00, object_tite_Tex_001F00, object_tite_Tex_002100 },
};
static Color_RGBA8 D_80896B3C = { 250, 250, 250, 255 };
static Color_RGBA8 D_80896B40 = { 180, 180, 180, 255 };
static Vec3f D_80896B44 = { 0.0f, 0.45f, 0.0f };
static InitChainEntry sInitChain[] = {
ICHAIN_S8(hintId, TATL_HINT_ID_BLUE_TEKTITE, ICHAIN_CONTINUE),
ICHAIN_F32(targetArrowOffset, 2000, ICHAIN_CONTINUE),
ICHAIN_F32(terminalVelocity, -40, ICHAIN_CONTINUE),
ICHAIN_F32_DIV1000(gravity, -1000, ICHAIN_STOP),
};
static s32 D_80896B60 = 0;
static Vec3f D_80896B64 = { 0.0f, 0.3f, 0.0f };
void EnTite_Init(Actor* thisx, PlayState* play) {
EnTite* this = THIS;
s32 i;
s32 j;
Actor_ProcessInitChain(&this->actor, sInitChain);
SkelAnime_Init(play, &this->skelAnime, &object_tite_Skel_003A20, &object_tite_Anim_0012E4, this->jointTable,
this->morphTable, 25);
ActorShape_Init(&this->actor.shape, 0.0f, ActorShadow_DrawCircle, 60.0f);
Actor_SetFocus(&this->actor, 20.0f);
CollisionCheck_SetInfo(&this->actor.colChkInfo, &sDamageTable, &sColChkInfoInit);
Collider_InitAndSetSphere(play, &this->collider, &this->actor, &sSphereInit);
this->collider.dim.worldSphere.radius = sSphereInit.dim.modelSphere.radius;
this->updBgCheckInfoFlags =
UPDBGCHECKINFO_FLAG_1 | UPDBGCHECKINFO_FLAG_4 | UPDBGCHECKINFO_FLAG_8 | UPDBGCHECKINFO_FLAG_10;
if (!D_80896B60) {
for (i = 0; i < ARRAY_COUNT(D_80896B24); i++) {
for (j = 0; j < ARRAY_COUNT(D_80896B24[0]); j++) {
D_80896B24[i][j] = Lib_SegmentedToVirtual(D_80896B24[i][j]);
}
}
D_80896B60 = true;
}
if (this->actor.params == ENTITE_MINUS_3) {
this->actor.params = ENTITE_MINUS_2;
this->unk_2BE = 240;
this->actor.flags &= ~ACTOR_FLAG_1;
this->actor.shape.yOffset = -3000.0f;
this->actor.shape.shadowDraw = NULL;
func_80895A10(this);
} else {
if (this->actor.params == ENTITE_MINUS_4) {
this->actor.params = ENTITE_MINUS_2;
this->unk_2BE = 240;
} else if (this->actor.params == ENTITE_MINUS_2) {
this->unk_2BE = 128;
} else {
this->unk_2BE = 64;
}
func_80893ED4(this);
}
if (this->actor.params == ENTITE_MINUS_2) {
this->updBgCheckInfoFlags |= UPDBGCHECKINFO_FLAG_40;
this->actor.colChkInfo.health = 3;
}
}
void EnTite_Destroy(Actor* thisx, PlayState* play) {
EnTite* this = THIS;
Collider_DestroySphere(play, &this->collider);
}
void func_80893A18(EnTite* this) {
this->collider.base.colType = COLTYPE_HIT6;
this->collider.base.acFlags &= ~AC_HARD;
}
s32 func_80893A34(EnTite* this, PlayState* play) {
if ((this->actor.params == ENTITE_MINUS_2) && (this->actor.bgCheckFlags & BGCHECKFLAG_GROUND) &&
(SurfaceType_GetFloorType(&play->colCtx, this->actor.floorPoly, this->actor.floorBgId) == FLOOR_TYPE_5)) {
return true;
}
return false;
}
void func_80893A9C(EnTite* this, PlayState* play) {
if (func_80893A34(this, play)) {
func_808956B8(this);
} else {
func_80893FD0(this);
}
}
s32 func_80893ADC(EnTite* this) {
if ((this->actor.params == ENTITE_MINUS_2) && (this->actor.bgCheckFlags & BGCHECKFLAG_WATER)) {
return true;
}
return false;
}
s32 func_80893B10(EnTite* this) {
Math_StepToF(&this->actor.velocity.y, 0.0f, 2.0f);
return Math_StepToF(&this->actor.world.pos.y, (this->actor.world.pos.y + this->actor.depthInWater) - 1.0f, 2.0f);
}
void func_80893B70(EnTite* this) {
if (this->actor.params == ENTITE_MINUS_2) {
if (this->actor.bgCheckFlags & BGCHECKFLAG_WATER) {
this->actor.gravity = 0.0f;
func_80893B10(this);
} else {
this->actor.gravity = -1.0f;
}
}
}
void func_80893BCC(EnTite* this, PlayState* play) {
Vec3f sp7C;
s32 i;
s32 j;
if (this->actor.bgCheckFlags & BGCHECKFLAG_GROUND_TOUCH) {
SurfaceMaterial surfaceMaterial =
SurfaceType_GetMaterial(&play->colCtx, this->actor.floorPoly, this->actor.floorBgId);
if ((surfaceMaterial == SURFACE_MATERIAL_DIRT) || (surfaceMaterial == SURFACE_MATERIAL_SAND)) {
for (i = 5; i < ARRAY_COUNT(this->limbPos); i++) {
func_800BBFB0(play, &this->limbPos[i], 1.0f, 2, 80, 15, 1);
}
} else if (surfaceMaterial == SURFACE_MATERIAL_SNOW) {
Vec3f* ptr;
for (i = 5; i < ARRAY_COUNT(this->limbPos); i++) {
for (j = 0; j < 2; j++) {
ptr = &this->limbPos[i];
sp7C.x = ptr->x + Rand_CenteredFloat(1.0f);
sp7C.y = ptr->y + Rand_CenteredFloat(1.0f);
sp7C.z = ptr->z + Rand_CenteredFloat(1.0f);
func_800B0DE0(play, &sp7C, &gZeroVec3f, &D_80896B64, &D_80896B3C, &D_80896B40,
(s32)Rand_ZeroFloat(16.0f) + 80, 15);
}
}
}
Actor_PlaySfx(&this->actor, NA_SE_EN_EYEGOLE_ATTACK);
}
}
void func_80893DD4(EnTite* this) {
this->drawDmgEffType = ACTOR_DRAW_DMGEFF_FROZEN_NO_SFX;
this->collider.base.colType = COLTYPE_HIT3;
this->unk_2BC = 80;
this->drawDmgEffScale = 0.5f;
this->drawDmgEffFrozenSteamScale = 0.75f;
this->drawDmgEffAlpha = 1.0f;
Actor_SetColorFilter(&this->actor, COLORFILTER_COLORFLAG_RED, 255, COLORFILTER_BUFFLAG_OPA, 80);
this->actor.flags &= ~ACTOR_FLAG_200;
}
void func_80893E54(EnTite* this, PlayState* play) {
if (this->drawDmgEffType == ACTOR_DRAW_DMGEFF_FROZEN_NO_SFX) {
this->drawDmgEffType = ACTOR_DRAW_DMGEFF_FIRE;
this->collider.base.colType = COLTYPE_HIT6;
this->drawDmgEffAlpha = 0.0f;
Actor_SpawnIceEffects(play, &this->actor, this->limbPos, 9, 2, 0.2f, 0.2f);
this->actor.flags |= ACTOR_FLAG_200;
}
}
void func_80893ED4(EnTite* this) {
Animation_MorphToLoop(&this->skelAnime, &object_tite_Anim_0012E4, 4.0f);
this->unk_2BC = Rand_S16Offset(15, 30);
this->actor.speed = 0.0f;
this->actionFunc = func_80893F30;
}
void func_80893F30(EnTite* this, PlayState* play) {
SkelAnime_Update(&this->skelAnime);
func_80893B70(this);
if (this->unk_2BC > 0) {
this->unk_2BC--;
} else if ((Player_GetMask(play) != PLAYER_MASK_STONE) && (this->actor.xzDistToPlayer < 300.0f) &&
(this->actor.playerHeightRel < 80.0f)) {
func_808945EC(this);
}
}
void func_80893FD0(EnTite* this) {
Animation_PlayOnce(&this->skelAnime, &object_tite_Anim_00083C);
this->actor.velocity.y = 0.0f;
this->actor.speed = 0.0f;
this->actor.world.rot.y = this->actor.shape.rot.y;
this->actionFunc = func_80894024;
}
void func_80894024(EnTite* this, PlayState* play) {
if (SkelAnime_Update(&this->skelAnime)) {
func_8089408C(this, play);
} else {
func_80893B70(this);
Math_ScaledStepToS(&this->actor.shape.rot.y, this->actor.yawTowardsPlayer, 1000);
this->actor.world.rot.y = this->actor.shape.rot.y;
}
}
void func_8089408C(EnTite* this, PlayState* play) {
Animation_PlayOnce(&this->skelAnime, &object_tite_Anim_0004F8);
if (!func_80893ADC(this)) {
Actor_PlaySfx(&this->actor, NA_SE_EN_TEKU_JUMP);
} else {
this->actor.world.pos.y += this->actor.depthInWater;
Actor_PlaySfx(&this->actor, NA_SE_EN_TEKU_JUMP_WATER);
}
if (this->actor.shape.yOffset < 0.0f) {
s32 i;
Vec3f sp70;
Vec3f sp64;
sp64.y = 3.0f;
this->actor.shape.yOffset = 0.0f;
for (i = 0; i < 4; i++) {
sp64.x = 2.0f * Math_SinS(this->actor.shape.rot.y);
sp64.z = 2.0f * Math_CosS(this->actor.shape.rot.y);
sp70.x = this->actor.world.pos.x + (12.5f * sp64.x);
sp70.y = this->actor.world.pos.y + 15.0f;
sp70.z = this->actor.world.pos.z + (12.5f * sp64.z);
func_800B0DE0(play, &sp70, &sp64, &D_80896B44, &D_80896B3C, &D_80896B40, 500, 50);
this->actor.shape.rot.y += 0x4000;
}
this->actor.shape.rot.y = this->actor.yawTowardsPlayer;
this->actor.world.rot.y = this->actor.shape.rot.y;
this->actor.shape.shadowDraw = ActorShadow_DrawCircle;
this->actor.flags |= ACTOR_FLAG_1;
this->actor.velocity.y = 10.0f;
} else {
this->actor.velocity.y = 8.0f;
}
this->actor.bgCheckFlags &=
~(BGCHECKFLAG_GROUND | BGCHECKFLAG_GROUND_TOUCH | BGCHECKFLAG_WATER | BGCHECKFLAG_WATER_TOUCH);
this->actor.gravity = -1.0f;
this->actor.speed = 4.0f;
this->actionFunc = func_808942B4;
}
void func_808942B4(EnTite* this, PlayState* play) {
SkelAnime_Update(&this->skelAnime);
if (((this->actor.bgCheckFlags & BGCHECKFLAG_GROUND) ||
(func_80893ADC(this) && (this->actor.depthInWater > 0.0f))) &&
(this->actor.velocity.y <= 0.0f)) {
this->actor.speed = 0.0f;
this->collider.base.atFlags &= ~AT_HIT;
if (!func_80893ADC(this)) {
func_80893BCC(this, play);
func_80894414(this);
} else {
this->actor.gravity = 0.0f;
if (this->actor.velocity.y < -8.0f) {
func_8089452C(this, play);
} else {
this->actor.velocity.y = 0.0f;
Actor_PlaySfx(&this->actor, NA_SE_EN_TEKU_LAND_WATER2);
func_80894414(this);
}
}
} else if (!(this->collider.base.atFlags & AT_HIT)) {
this->actor.flags |= ACTOR_FLAG_1000000;
CollisionCheck_SetAT(play, &play->colChkCtx, &this->collider.base);
} else {
this->collider.base.atFlags &= ~AT_HIT;
func_80894B2C(this);
}
}
void func_80894414(EnTite* this) {
Animation_PlayOnce(&this->skelAnime, &object_tite_Anim_00069C);
this->actionFunc = func_80894454;
}
void func_80894454(EnTite* this, PlayState* play) {
if (SkelAnime_Update(&this->skelAnime)) {
if ((Player_GetMask(play) == PLAYER_MASK_STONE) || (this->actor.xzDistToPlayer > 450.0f) ||
(this->actor.playerHeightRel > 80.0f)) {
func_80893ED4(this);
} else if (!Actor_IsFacingPlayer(&this->actor, 0x2328)) {
func_808945EC(this);
} else {
func_80893A9C(this, play);
}
} else {
Math_ScaledStepToS(&this->actor.world.rot.y, this->actor.yawTowardsPlayer, 1500);
func_80893B70(this);
}
}
void func_8089452C(EnTite* this, PlayState* play) {
Vec3f sp2C;
Math_Vec3f_Copy(&sp2C, &this->actor.world.pos);
sp2C.y += this->actor.depthInWater;
this->actor.velocity.y *= 0.75f;
EffectSsGRipple_Spawn(play, &sp2C, 0, 500, 0);
Actor_PlaySfx(&this->actor, NA_SE_EN_TEKU_LAND_WATER);
this->actionFunc = func_808945B4;
}
void func_808945B4(EnTite* this, PlayState* play) {
if (func_80893B10(this)) {
func_80894414(this);
}
}
void func_808945EC(EnTite* this) {
Animation_PlayLoop(&this->skelAnime, &object_tite_Anim_000A14);
this->actor.speed = 0.0f;
this->actor.velocity.y = 0.0f;
this->actionFunc = func_80894638;
}
void func_80894638(EnTite* this, PlayState* play) {
s16 temp_v0;
s16 temp_v1;
func_80893B70(this);
temp_v0 = this->actor.yawTowardsPlayer - this->actor.shape.rot.y;
if (temp_v0 > 0) {
temp_v1 = (s32)(temp_v0 * (1.0f / 42.0f)) + 10;
} else {
temp_v1 = (s32)(temp_v0 * (1.0f / 42.0f)) - 10;
}
this->actor.shape.rot.y = this->actor.shape.rot.y + (temp_v1 * 2);
this->actor.world.rot.y = this->actor.shape.rot.y;
this->skelAnime.playSpeed = temp_v1 * 0.01f;
SkelAnime_Update(&this->skelAnime);
if (Animation_OnFrame(&this->skelAnime, 7.0f)) {
if (func_80893ADC(this)) {
Actor_PlaySfx(&this->actor, NA_SE_EN_TEKU_WALK_WATER);
} else {
Actor_PlaySfx(&this->actor, NA_SE_EN_TEKU_WALK);
}
}
if ((Player_GetMask(play) == PLAYER_MASK_STONE) || (this->actor.xzDistToPlayer > 450.0f) ||
(this->actor.playerHeightRel > 80.0f)) {
func_80893ED4(this);
} else if (((this->actor.bgCheckFlags & BGCHECKFLAG_GROUND) ||
(func_80893ADC(this) && (this->actor.depthInWater < 10.0f))) &&
Actor_IsFacingPlayer(&this->actor, 0xE38)) {
if ((this->actor.xzDistToPlayer <= 180.0f) && (this->actor.playerHeightRel <= 80.0f)) {
func_80893A9C(this, play);
} else {
func_8089484C(this);
}
}
}
void func_8089484C(EnTite* this) {
Animation_MorphToPlayOnce(&this->skelAnime, &object_tite_Anim_000C70, -3.0f);
if (this->actionFunc != func_80894910) {
this->unk_2B8 = Rand_S16Offset(1, 3);
}
this->actor.velocity.y = 9.5f;
this->actor.gravity = -1.0f;
this->actor.speed = 4.0f;
if (func_80893ADC(this)) {
this->actor.world.pos.y += this->actor.depthInWater;
Actor_PlaySfx(&this->actor, NA_SE_EN_TEKU_JUMP_WATER);
} else {
Actor_PlaySfx(&this->actor, NA_SE_EN_TEKU_JUMP);
}
this->actionFunc = func_80894910;
}
void func_80894910(EnTite* this, PlayState* play) {
Vec3f sp34;
Math_SmoothStepToF(&this->actor.speed, 0.0f, 0.1f, 1.0f, 0.0f);
SkelAnime_Update(&this->skelAnime);
if (this->actor.bgCheckFlags & BGCHECKFLAG_WATER_TOUCH) {
Actor_PlaySfx(&this->actor, NA_SE_EN_TEKU_LAND_WATER);
if (func_80893ADC(this)) {
Math_Vec3f_Copy(&sp34, &this->actor.world.pos);
sp34.y += this->actor.depthInWater;
this->actor.velocity.y *= 0.75f;
EffectSsGRipple_Spawn(play, &sp34, 0, 500, 0);
}
} else {
func_80893BCC(this, play);
}
if (((this->actor.bgCheckFlags & BGCHECKFLAG_GROUND) ||
(func_80893ADC(this) && (this->actor.depthInWater > 0.0f))) &&
(this->actor.velocity.y <= 0.0f)) {
this->actor.speed = 0.0f;
Math_ScaledStepToS(&this->actor.shape.rot.y, this->actor.yawTowardsPlayer, 4000);
this->actor.world.rot.y = this->actor.shape.rot.y;
if (func_80893ADC(this)) {
this->actor.gravity = 0.0f;
if (!func_80893B10(this)) {
return;
}
}
if ((Player_GetMask(play) == PLAYER_MASK_STONE) || (this->actor.xzDistToPlayer > 450.0f) ||
(this->actor.playerHeightRel > 80.0f)) {
func_80893ED4(this);
} else if ((this->actor.xzDistToPlayer <= 180.0f) && (this->actor.playerHeightRel <= 80.0f)) {
func_808945EC(this);
} else {
func_8089484C(this);
}
} else {
Math_ScaledStepToS(&this->actor.shape.rot.y, this->actor.yawTowardsPlayer, 1000);
}
}
void func_80894B2C(EnTite* this) {
Animation_MorphToLoop(&this->skelAnime, &object_tite_Anim_0012E4, 4.0f);
this->actor.speed = -6.0f;
this->actor.gravity = -1.0f;
if (this->collider.base.ac != NULL) {
func_800BE568(&this->actor, &this->collider);
} else {
this->actor.world.rot.y = BINANG_ROT180(this->actor.yawTowardsPlayer);
}
this->actor.world.rot.y += 0x8000;
this->actionFunc = func_80894BC8;
}
void func_80894BC8(EnTite* this, PlayState* play) {
Math_SmoothStepToF(&this->actor.speed, 0.0f, 1.0f, 0.5f, 0.0f);
SkelAnime_Update(&this->skelAnime);
if (func_80893ADC(this) && (this->actor.velocity.y <= 0.0f)) {
this->actor.gravity = 0.0f;
this->actor.velocity.y = 0.0f;
this->actor.world.pos.y += this->actor.depthInWater - 1.0f;
}
if (this->actor.bgCheckFlags & BGCHECKFLAG_WATER_TOUCH) {
Actor_PlaySfx(&this->actor, NA_SE_EN_TEKU_LAND_WATER2);
} else {
func_80893BCC(this, play);
}
if ((this->actor.speed == 0.0f) && ((this->actor.bgCheckFlags & BGCHECKFLAG_GROUND) || func_80893ADC(this))) {
this->actor.world.rot.y = this->actor.shape.rot.y;
this->collider.base.acFlags |= AC_ON;
if ((Player_GetMask(play) == PLAYER_MASK_STONE) ||
(((this->actor.xzDistToPlayer > 450.0f) || (this->actor.playerHeightRel > 80.0f)) &&
(ABS_ALT(this->actor.shape.rot.x) < 4000) && (ABS_ALT(this->actor.shape.rot.z) < 4000))) {
func_80893ED4(this);
} else if ((this->actor.xzDistToPlayer < 180.0f) && (this->actor.playerHeightRel <= 80.0f) &&
Actor_IsFacingPlayer(&this->actor, 0x1770)) {
func_80893A9C(this, play);
} else {
func_8089484C(this);
}
}
}
void func_80894DD0(EnTite* this) {
this->actor.speed = 0.0f;
if (this->actor.velocity.y > 0.0f) {
this->actor.velocity.y = 0.0f;
}
this->actor.world.rot.y = this->actor.shape.rot.y;
this->actionFunc = func_80894E0C;
}
void func_80894E0C(EnTite* this, PlayState* play) {
if (this->unk_2BC != 0) {
this->unk_2BC--;
}
if ((func_80893ADC(this) != 0) && (this->actor.velocity.y <= 0.0f)) {
this->actor.gravity = 0.0f;
this->actor.velocity.y = 0.0f;
this->actor.world.pos.y += this->actor.depthInWater;
}
if (this->actor.bgCheckFlags & BGCHECKFLAG_WATER_TOUCH) {
Actor_PlaySfx(&this->actor, NA_SE_EN_TEKU_LAND_WATER2);
} else {
func_80893BCC(this, play);
}
if (this->unk_2BC == 0) {
func_80893E54(this, play);
if (this->actor.colChkInfo.health == 0) {
func_80895020(this, play);
} else if (this->unk_2B9 != 0) {
func_808955E4(this);
} else if ((Player_GetMask(play) == PLAYER_MASK_STONE) ||
(((this->actor.xzDistToPlayer > 450.0f) || (this->actor.playerHeightRel > 80.0f)) &&
(ABS_ALT(this->actor.shape.rot.x) < 4000) && (ABS_ALT(this->actor.shape.rot.z) < 4000))) {
func_80893ED4(this);
} else if ((this->actor.xzDistToPlayer < 180.0f) && (this->actor.playerHeightRel <= 80.0f) &&
Actor_IsFacingPlayer(&this->actor, 0x1770)) {
func_80893A9C(this, play);
} else {
func_8089484C(this);
}
}
}
void func_80895020(EnTite* this, PlayState* play) {
Vec3f sp74;
s32 i;
f32 temp_f0;
Vec3f* ptr;
this->actor.speed = 0.0f;
this->collider.base.acFlags &= ~AC_ON;
this->actor.colorFilterTimer = 0;
SoundSource_PlaySfxAtFixedWorldPos(play, &this->actor.world.pos, 40, NA_SE_EN_TEKU_DEAD);
this->actor.flags &= ~ACTOR_FLAG_1;
this->actor.flags |= ACTOR_FLAG_10;
this->unk_2BA = 1;
Item_DropCollectibleRandom(play, &this->actor, &this->actor.world.pos, this->unk_2BE);
this->unk_2BC = 25;
this->actor.gravity = -0.58f;
this->actor.velocity.y = 0.0f;
this->actor.speed = 0.0f;
ptr = &this->unk_33C[0];
for (i = 0; i < ARRAY_COUNT(this->limbPos); i++, ptr++) {
Math_Vec3f_Diff(&this->limbPos[i], &this->actor.world.pos, &sp74);
temp_f0 = Math3D_Vec3fMagnitude(&sp74);
if (temp_f0 > 1.0f) {
temp_f0 = 1.2f / temp_f0;
}
ptr->x = sp74.x * temp_f0;
ptr->z = sp74.z * temp_f0;
ptr->y = Rand_ZeroFloat(3.5f) + 5.5f;
}
this->actionFunc = func_808951B8;
}
void func_808951B8(EnTite* this, PlayState* play) {
s32 i;
this->unk_2BC--;
Math_SmoothStepToS(&this->actor.world.rot.z, 0x4000, 4, 0x1000, 0x400);
if (this->unk_2BC == 0) {
for (i = 0; i < ARRAY_COUNT(this->limbPos); i++) {
func_800B3030(play, &this->limbPos[i], &gZeroVec3f, &gZeroVec3f, 40, 7, 1);
SoundSource_PlaySfxAtFixedWorldPos(play, &this->limbPos[i], 11, NA_SE_EN_EXTINCT);
}
Actor_Kill(&this->actor);
return;
}
for (i = 0; i < ARRAY_COUNT(this->unk_33C); i++) {
Math_Vec3f_Sum(&this->limbPos[i], &this->unk_33C[i], &this->limbPos[i]);
this->unk_33C[i].y += this->actor.gravity;
}
}
void func_808952EC(EnTite* this) {
Animation_PlayLoopSetSpeed(&this->skelAnime, &object_tite_Anim_000A14, 1.5f);
Actor_PlaySfx(&this->actor, NA_SE_EN_LAST1_GROW_HEAD);
this->collider.base.acFlags &= ~AC_ON;
func_80893A18(this);
this->unk_2B9 = 1;
this->unk_2BC = 400;
this->actor.speed = 0.0f;
this->actor.gravity = -1.0f;
this->unk_2B8 = Rand_ZeroOne() * 50.0f;
this->actor.bgCheckFlags &= ~BGCHECKFLAG_GROUND;
this->actor.velocity.y = 11.0f;
this->actionFunc = func_80895424;
}
void func_80895424(EnTite* this, PlayState* play) {
Math_ScaledStepToS(&this->actor.shape.rot.z, -0x8000, 4000);
if (this->unk_2B8 != 0) {
this->unk_2B8--;
} else {
this->unk_2B8 = Rand_ZeroOne() * 30.0f;
this->skelAnime.curFrame = Rand_ZeroOne() * 5.0f;
}
SkelAnime_Update(&this->skelAnime);
if (this->actor.bgCheckFlags & BGCHECKFLAG_GROUND) {
this->collider.base.acFlags |= AC_ON;
if (this->actor.bgCheckFlags & BGCHECKFLAG_GROUND_TOUCH) {
Actor_SpawnFloorDustRing(play, &this->actor, &this->actor.world.pos, 20.0f, 11, 4.0f, 0, 0, 0);
Actor_PlaySfx(&this->actor, NA_SE_EN_EYEGOLE_ATTACK);
}
if (this->unk_2BC == 0) {
func_808955E4(this);
} else {
this->unk_2BC--;
}
} else if (this->actor.shape.yOffset < 2800.0f) {
this->actor.shape.yOffset += 400.0f;
}
}
void func_808955E4(EnTite* this) {
this->unk_2B9 = 0;
this->actor.velocity.y = 13.0f;
Actor_PlaySfx(&this->actor, NA_SE_EN_LAST1_GROW_HEAD);
this->actor.bgCheckFlags &= ~BGCHECKFLAG_GROUND;
this->collider.base.acFlags &= ~AC_ON;
this->actionFunc = func_80895640;
}
void func_80895640(EnTite* this, PlayState* play) {
Math_ScaledStepToS(&this->actor.shape.rot.z, 0, 4000);
SkelAnime_Update(&this->skelAnime);
if (this->actor.bgCheckFlags & BGCHECKFLAG_GROUND) {
this->collider.base.acFlags |= AC_ON;
this->actor.shape.yOffset = 0.0f;
func_80893BCC(this, play);
func_80893ED4(this);
}
}
void func_808956B8(EnTite* this) {
this->unk_2BC = 400;
this->actor.world.rot.y = this->actor.yawTowardsPlayer;
this->collider.base.colType = COLTYPE_HARD;
this->collider.base.acFlags |= AC_HARD;
this->actor.gravity = -1.0f;
this->actionFunc = func_80895738;
}
void func_808956FC(EnTite* this) {
this->unk_2BC = -1;
this->actor.bgCheckFlags &= ~BGCHECKFLAG_GROUND;
this->actor.velocity.y = 7.5f;
func_80893A18(this);
}
void func_80895738(EnTite* this, PlayState* play) {
func_80893BCC(this, play);
if (this->collider.base.atFlags & AT_HIT) {
this->collider.base.atFlags &= ~AT_HIT;
this->actor.world.rot.y = BINANG_ROT180(this->actor.yawTowardsPlayer);
if (this->collider.base.atFlags & AT_BOUNCED) {
func_808956FC(this);
}
} else if (this->actor.bgCheckFlags & BGCHECKFLAG_WALL) {
this->actor.world.rot.y = BINANG_SUB((this->actor.wallYaw * 2) - this->actor.world.rot.y, 0x8000);
}
if (this->unk_2BC == -1) {
Math_StepToF(&this->actor.speed, 0.0f, 0.3f);
if (this->actor.bgCheckFlags & BGCHECKFLAG_GROUND) {
this->actor.world.rot.y = this->actor.shape.rot.y;
func_80893ED4(this);
this->unk_2BC = 100;
}
} else if (this->unk_2BC > 0) {
this->unk_2BC--;
Math_StepToF(&this->actor.speed, 10.0f, 0.3f);
this->actor.flags |= ACTOR_FLAG_1000000;
CollisionCheck_SetAT(play, &play->colChkCtx, &this->collider.base);
if (!func_80893A34(this, play)) {
this->unk_2BC = 0;
}
} else if ((this->unk_2BC == 0) && Math_StepToF(&this->actor.speed, 0.0f, 0.3f)) {
this->actor.world.rot.y = this->actor.shape.rot.y;
func_80893A18(this);
if ((Player_GetMask(play) == PLAYER_MASK_STONE) || (this->actor.xzDistToPlayer > 450.0f) ||
(this->actor.playerHeightRel > 80.0f)) {
func_80893ED4(this);
} else if (!Actor_IsFacingPlayer(&this->actor, 0x2328)) {
func_808945EC(this);
} else {
func_80893A9C(this, play);
}
}
this->actor.shape.rot.y += (s16)(this->actor.speed * 768.0f);
}
void func_8089595C(EnTite* this, PlayState* play) {
Vec3f sp2C;
sp2C.x = Rand_CenteredFloat(20.0f) + this->actor.world.pos.x;
sp2C.y = this->actor.world.pos.y + 15.0f;
sp2C.z = Rand_CenteredFloat(20.0f) + this->actor.world.pos.z;
func_800B0DE0(play, &sp2C, &gZeroVec3f, &D_80896B44, &D_80896B3C, &D_80896B40, 500, 50);
}
void func_80895A10(EnTite* this) {
s32 pad;
s16 rand;
Animation_Change(&this->skelAnime, &object_tite_Anim_000A14, 2.0f, 0.0f, 0.0f, ANIMMODE_LOOP, 4.0f);
this->actor.speed = 0.0f;
rand = Rand_S16Offset(20, 20);
this->unk_2BC = ((Rand_ZeroOne() < 0.5f) ? -1 : 1) * rand;
this->actionFunc = func_80895AC0;
}
void func_80895AC0(EnTite* this, PlayState* play) {
s16 temp_v1;
s32 temp_v0;
SkelAnime_Update(&this->skelAnime);
if (Animation_OnFrame(&this->skelAnime, 7.0f)) {
if (Rand_ZeroOne() < 0.25f) {
func_8089595C(this, play);
}
Actor_PlaySfx(&this->actor, NA_SE_EN_TEKU_WALK);
}
if ((this->unk_2BC == 1) || (this->unk_2BC == -1)) {
if (this->actor.bgCheckFlags & BGCHECKFLAG_WALL) {
temp_v1 = this->actor.shape.rot.y - this->actor.wallYaw;
temp_v0 = ABS_ALT(temp_v1);
if (temp_v0 > 0x3000) {
this->unk_2BC = (temp_v0 >> 9) * this->unk_2BC;
}
} else if (Actor_WorldDistXZToPoint(&this->actor, &this->actor.home.pos) < 200.0f) {
temp_v1 = this->actor.shape.rot.y - Actor_WorldYawTowardPoint(&this->actor, &this->actor.home.pos);
temp_v0 = ABS_ALT(temp_v1);
if (temp_v0 > 0x2000) {
this->unk_2BC = (temp_v0 >> 9) * this->unk_2BC;
}
}
}
if ((this->actor.xzDistToPlayer < 240.0f) && (Player_GetMask(play) != PLAYER_MASK_STONE)) {
func_8089408C(this, play);
} else if (this->unk_2BC > 0) {
this->unk_2BC--;
this->actor.shape.rot.y += 0x100;
} else if (this->unk_2BC < 0) {
this->unk_2BC++;
this->actor.shape.rot.y -= 0x100;
} else {
func_80895CB0(this);
}
}
void func_80895CB0(EnTite* this) {
this->skelAnime.playSpeed = 1.0f;
this->actor.speed = 1.0f;
this->actor.world.rot.y = this->actor.shape.rot.y;
this->unk_2BC = Rand_S16Offset(20, 20);
this->actionFunc = func_80895D08;
}
void func_80895D08(EnTite* this, PlayState* play) {
SkelAnime_Update(&this->skelAnime);
if (Animation_OnFrame(&this->skelAnime, 7.0f)) {
if (Rand_ZeroOne() < 0.5f) {
func_8089595C(this, play);
}
Actor_PlaySfx(&this->actor, NA_SE_EN_TEKU_WALK);
}
if ((this->actor.xzDistToPlayer < 240.0f) && (Player_GetMask(play) != PLAYER_MASK_STONE)) {
func_8089408C(this, play);
} else {
this->unk_2BC--;
if (this->unk_2BC == 0) {
func_80895A10(this);
}
}
}
void func_80895DE8(EnTite* this) {
this->collider.base.acFlags &= ~AC_ON;
this->actor.shape.shadowDraw = ActorShadow_DrawCircle;
this->skelAnime.playSpeed = 1.0f;
this->actor.speed = 0.0f;
this->actionFunc = func_80895E28;
}
void func_80895E28(EnTite* this, PlayState* play) {
Vec3f sp44;
Vec3f sp38;
s16 sp36;
SkelAnime_Update(&this->skelAnime);
this->actor.shape.rot.y += 0x1E00;
sp44.x = (Math_SinS(this->actor.shape.rot.y) * 25.0f) + this->actor.world.pos.x;
sp44.y = this->actor.world.pos.y + 15.0f;
sp44.z = (Math_CosS(this->actor.shape.rot.y) * 25.0f) + this->actor.world.pos.z;
sp36 = BINANG_SUB(this->actor.shape.rot.y, 0x4000);
sp38.x = 2.0f * Math_SinS(sp36);
sp38.y = 3.0f;
sp38.z = 2.0f * Math_CosS(sp36);
func_800B0DE0(play, &sp44, &sp38, &D_80896B44, &D_80896B3C, &D_80896B40, 500, 50);
sp44.x = (2.0f * this->actor.world.pos.x) - sp44.x;
sp44.z = (2.0f * this->actor.world.pos.z) - sp44.z;
sp38.x *= -1.0f;
sp38.z *= -1.0f;
func_800B0DE0(play, &sp44, &sp38, &D_80896B44, &D_80896B3C, &D_80896B40, 500, 50);
if (Math_StepToF(&this->actor.shape.yOffset, 0.0f, 200.0f)) {
this->actor.flags |= ACTOR_FLAG_1;
this->actor.world.rot.y = this->actor.shape.rot.y;
this->collider.base.acFlags |= AC_ON;
func_808945EC(this);
}
}
void func_80895FF8(EnTite* this, PlayState* play) {
if (this->collider.base.acFlags & AC_HIT) {
this->collider.base.acFlags &= ~AC_HIT;
this->collider.base.atFlags &= ~AT_HIT;
if (this->collider.base.colType == COLTYPE_HARD) {
func_808956FC(this);
func_800BE568(&this->actor, &this->collider);
return;
}
Actor_SetDropFlag(&this->actor, &this->collider.info);
if ((this->drawDmgEffType != ACTOR_DRAW_DMGEFF_FROZEN_NO_SFX) ||
!(this->collider.info.acHitInfo->toucher.dmgFlags & 0xDB0B3)) {
func_80893E54(this, play);
if (this->actor.shape.yOffset < 0.0f) {
func_80895DE8(this);
return;
}
if (!Actor_ApplyDamage(&this->actor)) {
Enemy_StartFinishingBlow(play, &this->actor);
}
if (this->actor.colChkInfo.damageEffect != 0xF) {
if (this->actor.colChkInfo.damageEffect == 5) {
this->unk_2BC = 40;
Actor_SetColorFilter(&this->actor, COLORFILTER_COLORFLAG_BLUE, 200, COLORFILTER_BUFFLAG_OPA, 40);
Actor_PlaySfx(&this->actor, NA_SE_EN_COMMON_FREEZE);
this->drawDmgEffType = ACTOR_DRAW_DMGEFF_ELECTRIC_SPARKS_LARGE;
this->drawDmgEffScale = 0.5f;
this->drawDmgEffAlpha = 2.0f;
func_80894DD0(this);
return;
}
if (this->actor.colChkInfo.damageEffect == 1) {
this->unk_2BC = 40;
Actor_SetColorFilter(&this->actor, COLORFILTER_COLORFLAG_BLUE, 200, COLORFILTER_BUFFLAG_OPA, 40);
Actor_PlaySfx(&this->actor, NA_SE_EN_COMMON_FREEZE);
func_80894DD0(this);
return;
}
if (this->actor.colChkInfo.damageEffect == 3) {
func_80893DD4(this);
if (this->actor.colChkInfo.health == 0) {
this->unk_2BC = 3;
this->collider.base.acFlags &= ~AC_ON;
}
func_80894DD0(this);
return;
}
if (this->actor.colChkInfo.damageEffect == 2) {
this->drawDmgEffType = ACTOR_DRAW_DMGEFF_FIRE;
this->drawDmgEffAlpha = 4.0f;
this->drawDmgEffScale = 0.5f;
} else if (this->actor.colChkInfo.damageEffect == 4) {
this->drawDmgEffType = ACTOR_DRAW_DMGEFF_LIGHT_ORBS;
this->drawDmgEffAlpha = 4.0f;
this->drawDmgEffScale = 0.5f;
Actor_Spawn(&play->actorCtx, play, ACTOR_EN_CLEAR_TAG, this->collider.info.bumper.hitPos.x,
this->collider.info.bumper.hitPos.y, this->collider.info.bumper.hitPos.z, 0, 0, 0,
CLEAR_TAG_PARAMS(CLEAR_TAG_LARGE_LIGHT_RAYS));
}
Actor_SetColorFilter(&this->actor, COLORFILTER_COLORFLAG_RED, 255, COLORFILTER_BUFFLAG_OPA, 8);
if (this->actor.colChkInfo.health == 0) {
func_80895020(this, play);
} else {
Actor_PlaySfx(&this->actor, NA_SE_EN_TEKU_DAMAGE);
if (this->unk_2B9 == 0) {
func_80894B2C(this);
this->collider.base.acFlags &= ~AC_ON;
} else {
func_808955E4(this);
}
}
}
}
} else if ((this->actor.bgCheckFlags & BGCHECKFLAG_GROUND) && (this->collider.base.acFlags & AC_ON) &&
(this->actor.colChkInfo.health != 0) && (play->actorCtx.unk2 != 0) &&
(this->actor.xyzDistToPlayerSq < SQ(200.0f))) {
this->actor.flags |= ACTOR_FLAG_1;
if (this->actor.shape.yOffset < 0.0f) {
this->actor.shape.yOffset = 0.0f;
this->actor.shape.shadowDraw = ActorShadow_DrawCircle;
}
if (this->unk_2B9 != 0) {
func_808955E4(this);
} else {
func_808952EC(this);
}
}
}
void func_808963B4(EnTite* this, PlayState* play) {
s32 i;
Vec3f sp48;
if (this->actor.bgCheckFlags & BGCHECKFLAG_WATER_TOUCH) {
for (i = 5; i < ARRAY_COUNT(this->limbPos); i++) {
Math_Vec3f_Copy(&sp48, &this->limbPos[i]);
sp48.y = this->actor.world.pos.y + this->actor.depthInWater;
EffectSsGRipple_Spawn(play, &sp48, 0, 220, 0);
}
} else if (this->actor.bgCheckFlags & BGCHECKFLAG_WATER) {
s32 temp = play->gameplayFrames & 7;
if (!(temp & 1) && (this->actor.depthInWater < 10.0f)) {
Math_Vec3f_Copy(&sp48, &this->limbPos[5 + (temp >> 1)]);
sp48.y = this->actor.world.pos.y + this->actor.depthInWater;
EffectSsGRipple_Spawn(play, &sp48, 0, 220, 0);
}
}
}
void EnTite_Update(Actor* thisx, PlayState* play) {
EnTite* this = THIS;
func_80895FF8(this, play);
this->actionFunc(this, play);
if (this->actionFunc != func_808951B8) {
Actor_MoveWithGravity(&this->actor);
Actor_UpdateBgCheckInfo(play, &this->actor, 25.0f, 40.0f, 20.0f, this->updBgCheckInfoFlags);
func_808963B4(this, play);
if (this->actor.bgCheckFlags & BGCHECKFLAG_GROUND) {
func_800BE3D0(&this->actor, this->actor.shape.rot.y, &this->actor.shape.rot);
if (this->unk_2B9 != 0) {
this->actor.shape.rot.z = BINANG_ROT180(this->actor.shape.rot.z);
}
} else {
Math_ScaledStepToS(&this->actor.shape.rot.x, 0, 1000);
if (this->unk_2B9 == 0) {
Math_ScaledStepToS(&this->actor.shape.rot.z, 0, 1000);
if (this->actor.shape.yOffset > 0.0f) {
this->actor.shape.yOffset -= 400.0f;
}
}
}
Actor_SetFocus(&this->actor, this->actor.scale.y * 2000.0f);
this->collider.dim.worldSphere.center.x = this->actor.world.pos.x;
this->collider.dim.worldSphere.center.y = (s32)this->actor.world.pos.y + 15;
this->collider.dim.worldSphere.center.z = this->actor.world.pos.z;
if (this->collider.base.acFlags & AC_ON) {
CollisionCheck_SetAC(play, &play->colChkCtx, &this->collider.base);
}
CollisionCheck_SetOC(play, &play->colChkCtx, &this->collider.base);
if (this->drawDmgEffAlpha > 0.0f) {
if (this->drawDmgEffType != ACTOR_DRAW_DMGEFF_FROZEN_NO_SFX) {
Math_StepToF(&this->drawDmgEffAlpha, 0.0f, 0.05f);
this->drawDmgEffScale = (this->drawDmgEffAlpha + 1.0f) * 0.25f;
this->drawDmgEffScale = CLAMP_MAX(this->drawDmgEffScale, 0.5f);
} else if (!Math_StepToF(&this->drawDmgEffFrozenSteamScale, 0.5f, 0.0125f)) {
Actor_PlaySfx_Flagged(&this->actor, NA_SE_EV_ICE_FREEZE - SFX_FLAG);
}
}
}
}
s32 EnTite_OverrideLimbDraw(PlayState* play, s32 limbIndex, Gfx** dList, Vec3f* pos, Vec3s* rot, Actor* thisx) {
EnTite* this = THIS;
if (this->unk_2BA == -1) {
this->unk_3A8 = *dList;
*dList = NULL;
}
return false;
}
void EnTite_PostLimbDraw(PlayState* play, s32 limbIndex, Gfx** dList, Vec3s* rot, Actor* thisx) {
static s8 D_80896B70[] = {
-1, -1, -1, -1, 0, -1, -1, -1, 1, -1, -1, -1, -1, 2, -1, -1, -1, -1, 3, -1, -1, -1, -1, 4, -1,
};
static s8 D_80896B8C[] = {
-1, -1, -1, -1, 0, -1, -1, -1, 1, 5, -1, -1, -1, 2, 6, -1, -1, -1, 3, 7, -1, -1, -1, 4, 8,
};
EnTite* this = THIS;
MtxF* matrix;
s8 idx;
if (this->unk_2BA == 0) {
idx = D_80896B70[limbIndex];
if (idx != -1) {
Matrix_MultZero(&this->limbPos[idx]);
if (idx >= 1) {
Matrix_MultVecX(2500.0f, &this->limbPos[idx + 4]);
}
}
} else if (this->unk_2BA > 0) {
if (D_80896B8C[limbIndex] != -1) {
Matrix_MultZero(&this->limbPos[D_80896B8C[limbIndex]]);
}
if (limbIndex == 24) {
this->unk_2BA = -1;
}
} else if (D_80896B8C[limbIndex] != -1) {
OPEN_DISPS(play->state.gfxCtx);
matrix = Matrix_GetCurrent();
matrix->xw = this->limbPos[D_80896B8C[limbIndex]].x;
matrix->yw = this->limbPos[D_80896B8C[limbIndex]].y;
matrix->zw = this->limbPos[D_80896B8C[limbIndex]].z;
Matrix_RotateZS(this->actor.world.rot.z, MTXMODE_APPLY);
gSPMatrix(POLY_OPA_DISP++, Matrix_NewMtx(play->state.gfxCtx), G_MTX_NOPUSH | G_MTX_LOAD | G_MTX_MODELVIEW);
gSPDisplayList(POLY_OPA_DISP++, this->unk_3A8);
CLOSE_DISPS(play->state.gfxCtx);
}
}
void EnTite_Draw(Actor* thisx, PlayState* play) {
EnTite* this = THIS;
Gfx* gfx;
OPEN_DISPS(play->state.gfxCtx);
gfx = POLY_OPA_DISP;
gSPDisplayList(&gfx[0], gSetupDLs[SETUPDL_25]);
if (this->actor.params == ENTITE_MINUS_2) {
gSPSegment(&gfx[1], 0x08, D_80896B24[0][0]);
gSPSegment(&gfx[2], 0x09, D_80896B24[0][1]);
gSPSegment(&gfx[3], 0x0A, D_80896B24[0][2]);
} else {
gSPSegment(&gfx[1], 0x08, D_80896B24[1][0]);
gSPSegment(&gfx[2], 0x09, D_80896B24[1][1]);
gSPSegment(&gfx[3], 0x0A, D_80896B24[1][2]);
}
POLY_OPA_DISP = &gfx[4];
SkelAnime_DrawOpa(play, this->skelAnime.skeleton, this->skelAnime.jointTable, EnTite_OverrideLimbDraw,
EnTite_PostLimbDraw, &this->actor);
Actor_DrawDamageEffects(play, &this->actor, this->limbPos, ARRAY_COUNT(this->limbPos), this->drawDmgEffScale,
this->drawDmgEffFrozenSteamScale, this->drawDmgEffAlpha, this->drawDmgEffType);
CLOSE_DISPS(play->state.gfxCtx);
}
|
362db7b35e7c7b91f71a640de4dccc0692e139da
|
65089dbc386e1184983c15fe3a2282763ae65960
|
/gear-lib/libposix/MsvcLibX/include/iconv.h
|
9b7a42e163fe8558330e983bcd5b93fc5796d5e0
|
[
"LicenseRef-scancode-proprietary-license",
"MIT"
] |
permissive
|
gozfree/gear-lib
|
9f4db1bce799ded1cf1f3411cb51bdfbcbe7c7bc
|
bffbfd25af4ff7b04ebfafdab391b55270b0273e
|
refs/heads/master
| 2023-08-14T16:01:29.449910
| 2023-07-24T16:08:47
| 2023-07-24T16:09:41
| 40,359,871
| 1,771
| 488
|
MIT
| 2023-05-27T11:08:46
| 2015-08-07T12:41:05
|
C
|
UTF-8
|
C
| false
| false
| 5,614
|
h
|
iconv.h
|
/*****************************************************************************\
* *
* Filename iconv.h *
* *
* Description: WIN32 port of standard C library's iconv() *
* *
* Notes: Define here a number of routines, that will eventually *
* be used by iconv(). *
* *
* History: *
* 2014-02-27 JFL Created this file. *
* 2017-03-03 JFL Added routine ConvertBuf(). *
* 2017-03-12 JFL Restructured the UTF16 writing mechanism. *
* 2017-09-27 JFL Added standard C library routines iconv(), etc. *
* 2018-04-27 JFL Added MultiByteToNewWideString(). *
* 2021-05-17 JFL Added two new arguments to ConvertBuf() etc. *
* 2021-05-28 JFL Added a third argument to ConvertBuf() etc; Renamed them *
* with an Ex suffix; And added macros with the old name *
* without the extra three arguments. *
* *
* ?Copyright 2016 Hewlett Packard Enterprise Development LP *
* Licensed under the Apache 2.0 license - www.apache.org/licenses/LICENSE-2.0 *
\*****************************************************************************/
#ifndef _ICONV_H
#define _ICONV_H 1
#include "msvclibx.h"
#include <stdlib.h>
#if defined(_MSDOS)
/* Count the number of characters (not bytes!) in a string */
/* For now, assume the # of characters is the same as the # of bytes */
/* TO DO: Add support for DOS code pages! */
#define CountCharacters(string, cp) (int)strlen(string)
#endif /* defined(_MSDOS) */
#if defined(_WIN32)
#include <windows.h>
/* Standard C library routines */
typedef long iconv_t;
iconv_t iconv_open(const char *toEnc, const char *fromEnc);
size_t iconv(iconv_t cpFromTo, char **inBuf, size_t *inBytesLeft, char **outBuf, size_t *outBytesLeft);
#define iconv_close(cpFromTo) 0
/* MsvcLibX public routines */
#ifndef WC_NO_BEST_FIT_CHARS /* Not defined if targeting Windows 95, but we want it anyway */
#define WC_NO_BEST_FIT_CHARS 0x00000400 /* Do not use best fit chars */
#endif
#ifndef WC_ERR_INVALID_CHARS
#define WC_ERR_INVALID_CHARS 0x00000080 /* Fail the conversion if any invalid character is present */
#endif
int ConvertBufEx(const char *pFromBuf, size_t nFromBufSize, UINT cpFrom, char *pToBuf, size_t nToBufSize, UINT cpTo, DWORD dwFlags, LPCSTR lpDefaultChar, LPBOOL lpUsedDef);
#define ConvertBuf(pFromBuf, nFromBufSize, cpFrom, pToBuf, nToBufSize, cpTo) ConvertBufEx(pFromBuf, nFromBufSize, cpFrom, pToBuf, nToBufSize, cpTo, 0, NULL, NULL)
int ConvertStringEx(char *buf, size_t nBufSize, UINT cpFrom, UINT cpTo, DWORD dwFlags, LPCSTR lpDefaultChar, LPBOOL lpUsedDef);
#define ConvertString(buf, nBufSize, cpFrom, cpTo) ConvertStringEx(buf, nBufSize, cpFrom, cpTo, 0, NULL, NULL)
int CountCharacters(const char *string, UINT cp);
char *DupAndConvertEx(const char *string, UINT cpFrom, UINT cpTo, DWORD dwFlags, LPCSTR lpDefaultChar, LPBOOL lpUsedDef);
#define DupAndConvert(string, cpFrom, cpTo) DupAndConvertEx(string, cpFrom, cpTo, 0, NULL, NULL)
WCHAR *MultiByteToNewWideStringEx(UINT cp, DWORD dwFlags, const char *string);
#define MultiByteToNewWideString(cp, string) MultiByteToNewWideStringEx(cp, 0, string)
UINT GetBufferEncoding(const char *pszBuffer, size_t nBufSize, DWORD dwFlags); /* If dwFlags is 0, test everything, else test only the specified encodings + Windows' own */
#define BE_TEST_BINARY 0x0001 /* Test if the buffer contains binary data, and if so return CP_UNDEFINED */
#define BE_TEST_ASCII 0x0002 /* Test if the buffer contains ASCII text, and if so return CP_ASCII */
#define BE_TEST_SYSTEM 0x0004 /* Test if the buffer contains Windows text, and if so return CP_ACP */
#define BE_TEST_UTF8 0x0008 /* Test if the buffer contains UTF-8 text, and if so return CP_UTF8 */
#define BE_TEST_UTF16 0x0010 /* Test if the buffer contains UTF-16 text, and if so return CP_UTF16 */
#define BE_TEST_UTF32 0x0020 /* Test if the buffer contains UTF-32 text, and if so return CP_UTF32 */
/* MsvcLibX internal routines */
int initWideFiles(void); /* Initialize the UTF-8 output handlers */
int isWideFile(int iFile); /* Test if the file is open for writing in wide mode */
int isTranslatedFile(int iFile, UINT cp, UINT *pcpOut); /* Test if the file encoding is to be translated from cp, and if so into which other cp. */
#define isConsole(iFile) isatty(iFile)
extern UINT consoleCodePage; /* The current console code page (may change) */
extern UINT systemCodePage; /* The system code page (unchangeable) */
extern UINT codePage; /* The user-specified code page */
#define CP_UNDEFINED ((UINT)-1) /* Can't be 0, which is CP_ACP, a valid code page */
#define CP_UTF16 1200 /* The pseudo-code page 1200 is UTF-16 */
#define CP_UTF16LE 1200 /* The pseudo-code page 1200 is UTF-16 little endian*/
#define CP_UTF16BE 1201 /* The pseudo-code page 1201 is UTF-16 big endian */
#define CP_UTF32 12000 /* The pseudo-code page 12000 is UTF-32 */
#define CP_UTF32LE 12000 /* The pseudo-code page 12000 is UTF-32 little endian*/
#define CP_UTF32BE 12001 /* The pseudo-code page 12001 is UTF-32 big endian */
#define CP_ASCII 20127 /* The pure 7-bits US-ASCII code page */
#define CP_EBCDIC 37 /* IBM US EBCDIC code page */
#endif /* defined(_WIN32) */
#endif /* !defined(_ICONV_H) */
|
3d26d7e93e8de07d0fe471849fec4f6697ba1688
|
bb38c44037a99d0a12a12d92059678f2faebbc80
|
/src/include/access/xlog_internal.h
|
776dba2a8e0573818bc7cd2ff0ef24dce7a3369f
|
[
"LicenseRef-scancode-mulanpsl-2.0-en",
"LicenseRef-scancode-unknown-license-reference",
"PostgreSQL",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"LicenseRef-scancode-unicode",
"LicenseRef-scancode-warranty-disclaimer",
"curl",
"GPL-1.0-or-later",
"LGPL-2.1-or-later",
"LGPL-2.1-only",
"CC-BY-4.0",
"LicenseRef-scancode-protobuf",
"OpenSSL",
"LicenseRef-scancode-generic-export-compliance",
"X11-distribute-modifications-variant",
"LicenseRef-scancode-other-permissive",
"MIT",
"NCSA",
"Python-2.0",
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-ssleay-windows",
"CC-BY-3.0",
"LicenseRef-scancode-other-copyleft",
"GPL-2.0-only",
"BSL-1.0",
"Apache-2.0",
"LGPL-2.0-only",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"Zlib"
] |
permissive
|
opengauss-mirror/openGauss-server
|
a9c5a62908643492347830826c56da49f0942796
|
310e84631c68c8bf37b004148b66f94064f701e4
|
refs/heads/master
| 2023-07-26T19:29:12.495484
| 2023-07-17T12:23:32
| 2023-07-17T12:23:32
| 276,117,477
| 591
| 208
|
MulanPSL-2.0
| 2023-04-28T12:30:18
| 2020-06-30T14:08:59
|
C++
|
UTF-8
|
C
| false
| false
| 12,553
|
h
|
xlog_internal.h
|
/*
* xlog_internal.h
*
* openGauss transaction log internal declarations
*
* NOTE: this file is intended to contain declarations useful for
* manipulating the XLOG files directly, but it is not supposed to be
* needed by rmgr routines (redo support for individual record types).
* So the XLogRecord typedef and associated stuff appear in xlogrecord.h.
*
* Portions Copyright (c) 2020 Huawei Technologies Co.,Ltd.
* Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* src/include/access/xlog_internal.h
*/
#ifndef XLOG_INTERNAL_H
#define XLOG_INTERNAL_H
#include "access/xlogdefs.h"
#include "access/xlogreader.h"
#include "access/xlog_basic.h"
#include "access/ustore/knl_undorequest.h"
#include "datatype/timestamp.h"
#include "fmgr.h"
#include "pgtime.h"
#include "storage/buf/block.h"
#include "storage/smgr/relfilenode.h"
#include "storage/buf/buf.h"
/*
* if ValidateXlogRecord Failed in XLOG_FROM_STREAM source, the unexpected
* walreceiver shutdown will be caused. To avoid this, add retry for readrecord in xlog redo
*/
#define XLOG_STREAM_READREC_MAXTRY 10
#define XLOG_STREAM_READREC_INTERVAL 100 * 1000L
#ifndef FRONTEND
/* Compute the xlog filename with timelineId and segment number.*/
#define XLogFileName(fname, len, tli, logSegNo) \
do { \
int nRet; \
nRet = snprintf_s(fname, \
len, \
len - 1, \
"%08X%08X%08X", \
tli, \
(uint32)((logSegNo) / XLogSegmentsPerXLogId), \
(uint32)((logSegNo) % XLogSegmentsPerXLogId)); \
securec_check_ss(nRet, "\0", "\0"); \
} while (0)
/* compute xlog file path with timelineId and segment number. */
#define XLogFilePath(path, len, tli, logSegNo) \
do { \
int nRet; \
nRet = snprintf_s(path, \
len, \
len - 1, \
"%s/%08X%08X%08X", \
SS_XLOGDIR, \
tli, \
(uint32)((logSegNo) / XLogSegmentsPerXLogId), \
(uint32)((logSegNo) % XLogSegmentsPerXLogId)); \
securec_check_ss(nRet, "\0", "\0"); \
} while (0)
#else
#define XLOG_FNAME_LEN 24
#define IsXLogFileName(fname) \
(strlen(fname) == XLOG_FNAME_LEN && \
strspn(fname, "0123456789ABCDEF") == XLOG_FNAME_LEN)
#define IsPartialXLogFileName(fname) \
(strlen(fname) == XLOG_FNAME_LEN + strlen(".partial") && \
strspn(fname, "0123456789ABCDEF") == XLOG_FNAME_LEN && \
strcmp((fname) + XLOG_FNAME_LEN, ".partial") == 0)
#define IsTLHistoryFileName(fname) \
(strlen(fname) == 8 + strlen(".history") && \
strspn(fname, "0123456789ABCDEF") == 8 && \
strcmp((fname) + 8, ".history") == 0)
#define IsBackupHistoryFileName(fname) \
(strlen(fname) > XLOG_FNAME_LEN && \
strspn(fname, "0123456789ABCDEF") == XLOG_FNAME_LEN && \
strcmp((fname) + strlen(fname) - strlen(".backup"), ".backup") == 0)
#define XLogFileName(fname, len, tli, logSegNo) \
do { \
int nRet; \
nRet = snprintf_s(fname, \
len, \
len - 1, \
"%08X%08X%08X", \
tli, \
(uint32)((logSegNo) / XLogSegmentsPerXLogId), \
(uint32)((logSegNo) % XLogSegmentsPerXLogId)); \
securec_check_ss_c(nRet, "\0", "\0"); \
} while (0)
#define XLogFilePath(path, len, tli, logSegNo) \
do { \
int nRet; \
nRet = snprintf_s(path, \
len, \
len - 1, \
"%s/%08X%08X%08X", \
SS_XLOGDIR, \
tli, \
(uint32)((logSegNo) / XLogSegmentsPerXLogId), \
(uint32)((logSegNo) % XLogSegmentsPerXLogId)); \
securec_check_ss_c(nRet, "\0", "\0"); \
} while (0)
#endif
/* compute the xlog segment number with xlog filename and timelineId. */
#define XLogFromFileName(fname, tli, logSegNo) \
do { \
uint32 log; \
uint32 seg; \
int ret; \
ret = sscanf_s(fname, "%08X%08X%08X", tli, &log, &seg); \
securec_check_for_sscanf_s(ret, 3, "\0", "\0"); \
*logSegNo = (uint64)log * XLogSegmentsPerXLogId + seg; \
} while (0)
/* compute history filename with timelineID. */
#define TLHistoryFileName(fname, len, tli) \
do { \
int nRet = 0; \
nRet = snprintf_s(fname, len, len - 1, "%08X.history", tli); \
securec_check_ss(nRet, "\0", "\0"); \
} while (0)
/* compute history filepath with timelineID. */
#define TLHistoryFilePath(path, len, tli) \
do { \
int nRet = 0; \
nRet = snprintf_s(path, len, len - 1, XLOGDIR "/%08X.history", tli); \
securec_check_ss(nRet, "\0", "\0"); \
} while (0)
/* compute status filePath with xlog name and suffix. */
#define StatusFilePath(path, len, xlog, suffix) \
do { \
int nRet = 0; \
nRet = snprintf_s(path, len, len - 1, "%s/%s%s", ARCHIVEDIR, xlog, suffix); \
securec_check_ss(nRet, "\0", "\0"); \
} while (0)
/*compute backup history filename with timelineID, segment number and offset. */
#define BackupHistoryFileName(fname, len, tli, logSegNo, offset) \
do { \
int nRet = 0; \
nRet = snprintf_s(fname, \
len, \
len - 1, \
"%08X%08X%08X.%08X.backup", \
tli, \
(uint32)((logSegNo) / XLogSegmentsPerXLogId), \
(uint32)((logSegNo) % XLogSegmentsPerXLogId), \
offset); \
securec_check_ss(nRet, "\0", "\0"); \
} while (0)
/**/
#define BackupHistoryFilePath(path, len, tli, logSegNo, offset) \
do { \
int nRet = 0; \
nRet = snprintf_s(path, \
len, \
len - 1, \
"%s/%08X%08X%08X.%08X.backup", \
SS_XLOGDIR, \
tli, \
(uint32)((logSegNo) / XLogSegmentsPerXLogId), \
(uint32)((logSegNo) % XLogSegmentsPerXLogId), \
offset); \
securec_check_ss(nRet, "\0", "\0"); \
} while (0)
/*
* Information logged when we detect a change in one of the parameters
* important for Hot Standby.
*/
typedef struct xl_parameter_change {
int MaxConnections;
int max_prepared_xacts;
int max_locks_per_xact;
int wal_level;
} xl_parameter_change;
/* logs restore point */
typedef struct xl_restore_point {
TimestampTz rp_time;
char rp_name[MAXFNAMELEN];
} xl_restore_point;
/*
* The functions in xloginsert.c construct a chain of XLogRecData structs
* to represent the final WAL record.
*/
typedef struct XLogRecData {
struct XLogRecData* next; /* next struct in chain, or NULL */
char* data; /* start of rmgr data to include */
uint32 len; /* length of rmgr data to include */
Buffer buffer; /* buffer associated with data, if any */
} XLogRecData;
/*
* Method table for resource managers.
*
* This struct must be kept in sync with the PG_RMGR definition in
* rmgr.cpp.
*
* RmgrTable[] is indexed by RmgrId values (see rmgrlist.h).
*/
typedef struct RmgrData {
const char* rm_name;
void (*rm_redo)(XLogReaderState* record);
void (*rm_desc)(StringInfo buf, XLogReaderState* record);
void (*rm_startup)(void);
void (*rm_cleanup)(void);
bool (*rm_safe_restartpoint)(void);
int (*rm_undo)(URecVector *urecvector, int startIdx, int endIdx,
TransactionId xid, Oid reloid, Oid partitionoid,
BlockNumber blkno, bool isFullChain,
int preRetCode, Oid *preReloid, Oid *prePartitionoid);
void (*rm_undo_desc) (StringInfo buf, UndoRecord *record);
const char* (*rm_type_name)(uint8 subtype);
} RmgrData;
/*
* New XLogCtlInsert Structure.
*/
struct Combined128 {
uint64 currentBytePos;
uint32 byteSize;
int32 LRC;
};
union Union128 {
uint128_u value;
struct Combined128 struct128;
};
extern const RmgrData RmgrTable[];
/*
* Exported to support xlog switching from checkpointer
*/
extern pg_time_t GetLastSegSwitchTime(void);
extern XLogRecPtr RequestXLogSwitch(void);
/*
* Exported to support xlog archive status setting from WALReceiver
*/
extern void XLogArchiveForceDone(const char* xlog);
/*
* These aren't in xlog.h because I'd rather not include fmgr.h there.
*/
extern Datum pg_start_backup(PG_FUNCTION_ARGS);
extern Datum pg_stop_backup(PG_FUNCTION_ARGS);
extern Datum gs_roach_stop_backup(PG_FUNCTION_ARGS);
extern Datum pg_switch_xlog(PG_FUNCTION_ARGS);
extern Datum gs_roach_switch_xlog(PG_FUNCTION_ARGS);
extern Datum pg_create_restore_point(PG_FUNCTION_ARGS);
extern Datum pg_current_xlog_location(PG_FUNCTION_ARGS);
extern Datum pg_current_xlog_insert_location(PG_FUNCTION_ARGS);
extern Datum gs_current_xlog_insert_end_location(PG_FUNCTION_ARGS);
extern Datum pg_last_xlog_receive_location(PG_FUNCTION_ARGS);
extern Datum pg_last_xlog_replay_location(PG_FUNCTION_ARGS);
extern Datum pg_last_xact_replay_timestamp(PG_FUNCTION_ARGS);
extern Datum pg_xlogfile_name_offset(PG_FUNCTION_ARGS);
extern Datum pg_xlogfile_name(PG_FUNCTION_ARGS);
extern Datum pg_is_in_recovery(PG_FUNCTION_ARGS);
extern Datum pg_xlog_replay_pause(PG_FUNCTION_ARGS);
extern Datum pg_xlog_replay_resume(PG_FUNCTION_ARGS);
extern Datum pg_is_xlog_replay_paused(PG_FUNCTION_ARGS);
extern Datum pg_xlog_location_diff(PG_FUNCTION_ARGS);
extern int XLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr,
char *readBuf, TimeLineID *readTLI, char* xlog_path = NULL);
bool XLogReadFromWriteBuffer(XLogRecPtr targetStartPtr, int reqLen, char* readBuf, uint32 *rereadlen);
extern void handleRecoverySusPend(XLogRecPtr lsn);
#endif /* XLOG_INTERNAL_H */
|
f808a40f12c579043848e974af3318d6c4c2088e
|
97c44f18459163c0baa546ab2578339b716c3238
|
/crypto/BRCryptoPaymentP.h
|
8c83e3e41dfba9b2b89ca078f39dc64dd171fbcc
|
[
"MIT"
] |
permissive
|
breadwallet/breadwallet-core
|
fe8a0ac99f3e47216860b2918c8ad14d3503b140
|
73566cb79f753954eccbf07d5ab25ca54741198e
|
refs/heads/develop
| 2023-08-21T22:27:45.735652
| 2020-02-06T18:43:51
| 2020-02-06T18:43:51
| 37,500,549
| 284
| 283
|
MIT
| 2023-03-21T09:07:32
| 2015-06-16T01:22:12
|
C
|
UTF-8
|
C
| false
| false
| 601
|
h
|
BRCryptoPaymentP.h
|
//
// BRCryptoPaymentP.h
// BRCore
//
// Created by Ed Gamble on 12/19/19.
// Copyright © 2019 Breadwinner AG. All rights reserved.
//
// See the LICENSE file at the project root for license information.
// See the CONTRIBUTORS file at the project root for a list of contributors.
#ifndef BRCryptoPaymentP_h
#define BRCryptoPaymentP_h
#include "BRCryptoPayment.h"
#ifdef __cplusplus
extern "C" {
#endif
private_extern BRArrayOf(BRTxOutput)
cryptoPaymentProtocolRequestGetOutputsAsBTC (BRCryptoPaymentProtocolRequest request);
#ifdef __cplusplus
}
#endif
#endif /* BRCryptoPaymentP_h */
|
b7609e80dac5d12833e35d5b18534157e907aace
|
fdbb74a95924e2677466614f6ab6e2bb13b2a95a
|
/libc/calls/tcgetpgrp.c
|
bd6ce3b6c8c493846cf6a6fac9d27e1c4d673e5a
|
[
"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
| 2,803
|
c
|
tcgetpgrp.c
|
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
│vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│
╞══════════════════════════════════════════════════════════════════════════════╡
│ Copyright 2020 Justine Alexandra Roberts Tunney │
│ │
│ Permission to use, copy, modify, and/or distribute this software for │
│ any purpose with or without fee is hereby granted, provided that the │
│ above copyright notice and this permission notice appear in all copies. │
│ │
│ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │
│ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │
│ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │
│ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │
│ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │
│ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/calls/calls.h"
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/calls/termios.h"
#include "libc/dce.h"
#include "libc/intrin/strace.internal.h"
#include "libc/sysv/consts/termios.h"
#include "libc/sysv/errfuns.h"
#define TIOCGPGRP_linux 0x0000540f
#define TIOCGPGRP_bsd 0x40047477
/**
* Returns which process group controls terminal.
*
* @return process group id on success, or -1 w/ errno
* @raise ENOTTY if `fd` is isn't controlling teletypewriter
* @raise EBADF if `fd` isn't an open file descriptor
* @raise ENOSYS on Windows and Bare Metal
* @asyncsignalsafe
*/
int tcgetpgrp(int fd) {
int rc, pgrp;
if (IsLinux()) {
rc = sys_ioctl(fd, TIOCGPGRP_linux, &pgrp);
} else if (IsBsd()) {
rc = sys_ioctl(fd, TIOCGPGRP_bsd, &pgrp);
} else if (IsWindows()) {
pgrp = rc = getpid();
} else {
rc = enosys();
}
STRACE("tcgetpgrp(%d) → %d% m", fd, rc == -1 ? rc : pgrp);
return rc == -1 ? rc : pgrp;
}
|
7bdcca2248654ebbf38b8b275726a83c8d2b1d68
|
79d343002bb63a44f8ab0dbac0c9f4ec54078c3a
|
/lib/libc/wasi/libc-top-half/musl/src/ctype/isblank.c
|
716da23a566155ebc90646751a3be838523c0c10
|
[
"BSD-3-Clause",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-musl-exception",
"MIT",
"LLVM-exception",
"Apache-2.0",
"NCSA"
] |
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
| 173
|
c
|
isblank.c
|
#include <ctype.h>
int isblank(int c)
{
return (c == ' ' || c == '\t');
}
int __isblank_l(int c, locale_t l)
{
return isblank(c);
}
weak_alias(__isblank_l, isblank_l);
|
3529c02a27daf3946ae1663998dd6d28db1acc70
|
03b2c80dbc41e904b167d504666e27d798da5447
|
/src/lambda.h
|
181f1a9d500bed370d7593ec567038e7f5906077
|
[
"Unlicense"
] |
permissive
|
nptcl/npt
|
7c1570b497cdce0b8971cb445fbc04cb500232d3
|
aa714a2370ac9fa5348c2fc96159b40b9de3de07
|
refs/heads/master
| 2023-03-20T09:13:54.669118
| 2022-07-02T11:17:44
| 2022-07-02T11:17:44
| 171,985,905
| 160
| 12
|
Unlicense
| 2023-03-11T01:36:37
| 2019-02-22T03:11:34
|
C
|
UTF-8
|
C
| false
| false
| 4,671
|
h
|
lambda.h
|
#ifndef __LAMBDA_HEADER__
#define __LAMBDA_HEADER__
#include "local.h"
#include "typedef.h"
#define lambda_macro_ _n(lambda_macro_)
#define lambda_deftype_ _n(lambda_deftype_)
#define lambda_generic_function_ _n(lambda_generic_function_)
#define lambda_specialized_ _n(lambda_specialized_)
#define lambda_ordinary_ _n(lambda_ordinary_)
#define atleast_argument_count _n(atleast_argument_count)
#define lambda_defsetf_ _n(lambda_defsetf_)
#define getenvironment_macro_lambda _n(getenvironment_macro_lambda)
#define define_modify_macro_heap_ _n(define_modify_macro_heap_)
#define argumentp _n(argumentp)
#define getargument _n(getargument)
#define setargument _n(setargument)
#define argumentstruct _n(argumentstruct)
#define argument_alloc _n(argument_alloc)
#define argument_local _n(argument_local)
#define argument_heap _n(argument_heap)
#define argument_ordinary_heap_ _n(argument_ordinary_heap_)
#define argument_generic_heap_ _n(argument_generic_heap_)
#define argument_method_heap_ _n(argument_method_heap_)
#define argument_combination_heap_ _n(argument_combination_heap_)
#define argument_boa_heap_ _n(argument_boa_heap_)
#define argument_ordinary_lambda_heap_ _n(argument_ordinary_lambda_heap_)
#define argument_generic_lambda_heap_ _n(argument_generic_lambda_heap_)
#define argument_method_lambda_heap_ _n(argument_method_lambda_heap_)
#define argument_method_keywords_heap_ _n(argument_method_keywords_heap_)
#define argument_method_to_generic _n(argument_method_to_generic)
#define argument_boa_lambda_heap_ _n(argument_boa_lambda_heap_)
#define argument_boa_variables_heap_ _n(argument_boa_variables_heap_)
#define find_keyword_allow_other_keys _n(find_keyword_allow_other_keys)
enum ArgumentType {
ArgumentType_macro,
ArgumentType_ordinary,
ArgumentType_deftype,
ArgumentType_generic,
ArgumentType_method,
ArgumentType_combination,
ArgumentType_defsetf,
ArgumentType_boa,
ArgumentType_size,
};
enum ArgumentIndex {
ArgumentIndex_var,
ArgumentIndex_opt,
ArgumentIndex_rest,
ArgumentIndex_body,
ArgumentIndex_restbody,
ArgumentIndex_key,
ArgumentIndex_aux,
ArgumentIndex_whole,
ArgumentIndex_environment,
ArgumentIndex_dotted,
ArgumentIndex_size
};
struct argument_struct {
unsigned keyp : 1;
unsigned allow : 1;
unsigned whole : 1;
unsigned rest : 1;
unsigned body : 1;
unsigned restbody : 1;
unsigned environment : 1;
unsigned dotted : 1;
enum ArgumentType type;
size_t var, opt, key, aux;
};
#define PtrArgument_Low PtrBodySS
#define GetArgument_Low GetArraySS
#define SetArgument_Low SetArraySS
#define ArgumentStruct_Low(x) ((struct argument_struct *)PtrArgument_Low(x))
#ifdef LISP_DEBUG
#define GetArgument getargument
#define SetArgument setargument
#define ArgumentStruct argumentstruct
#else
#define GetArgument GetArgument_Low
#define SetArgument SetArgument_Low
#define ArgumentStruct ArgumentStruct_Low
#endif
/* parse */
int lambda_macro_(LocalRoot local, addr *ret, addr cons, addr instance);
int lambda_deftype_(LocalRoot local, addr *ret, addr cons, addr instance);
int lambda_generic_function_(LocalRoot local, addr *ret, addr cons);
int lambda_specialized_(LocalRoot local, addr *ret, addr cons);
int lambda_ordinary_(LocalRoot local, addr *ret, addr cons);
void atleast_argument_count(addr cons, size_t *ret);
int lambda_defsetf_(LocalRoot local, addr *ret, addr cons);
void getenvironment_macro_lambda(addr pos, addr *ret);
int define_modify_macro_heap_(LocalRoot local, addr *ret, addr *rest, addr list);
/* argument */
int argumentp(addr pos);
void getargument(addr pos, size_t index, addr *ret);
void setargument(addr pos, size_t index, addr value);
struct argument_struct *argumentstruct(addr pos);
void argument_alloc(LocalRoot local, addr *ret);
void argument_local(LocalRoot local, addr *ret);
void argument_heap(addr *ret);
int argument_ordinary_heap_(LocalRoot local, addr *ret, addr list);
int argument_generic_heap_(LocalRoot local, addr *ret, addr list);
int argument_method_heap_(LocalRoot local, addr *ret, addr list);
int argument_combination_heap_(LocalRoot local, addr *ret, addr list);
int argument_boa_heap_(LocalRoot local, addr *ret, addr list, addr g);
/* expand */
int argument_ordinary_lambda_heap_(addr *ret, addr pos);
int argument_generic_lambda_heap_(addr *ret, addr pos);
int argument_method_lambda_heap_(addr *ret, addr pos);
int argument_method_keywords_heap_(addr pos, addr *ret, int *allow);
void argument_method_to_generic(addr pos, addr *ret);
int argument_boa_lambda_heap_(addr *ret, addr pos);
int argument_boa_variables_heap_(addr *ret, addr pos);
/* :allow-other-keys */
int find_keyword_allow_other_keys(addr list);
#endif
|
74061c0b3ab84fb4170a8a115b7707972793494f
|
59864cbd213b5da6f50d6255b0a021564b3d5bd4
|
/disabled-challenges/adventure_game/src/Battle.c
|
aef93df783bd6d4271d5d41ed13e86457951cab2
|
[
"MIT"
] |
permissive
|
trailofbits/cb-multios
|
8af96a4fbc3b34644367faa135347f88e0e0d0a3
|
810d7b24b1f62f56ef49b148fe155b0d0629cad2
|
refs/heads/master
| 2023-09-05T03:56:20.229403
| 2022-12-27T15:47:54
| 2022-12-27T15:47:54
| 41,688,943
| 522
| 133
|
MIT
| 2023-06-29T02:47:13
| 2015-08-31T17:04:31
|
C
|
UTF-8
|
C
| false
| false
| 5,774
|
c
|
Battle.c
|
/*
* Copyright (c) 2014 Kaprica Security, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* 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 "Battle.h"
#include "Program.h"
#include "Monster.h"
#include <ctype.h>
DefineClass(Battle, Object)
static Monster *get_next_alive(Array *team)
{
size_t i;
for (i = 0; i < team->m_count; i++)
{
Monster *m = $(team, get, i);
if (m->m_health > 0)
return m;
}
return NULL;
}
static const attack_data_t *attack_menu(Monster *m)
{
size_t i;
for (i = 0; i < m->m_kind->num_attacks; i++)
{
const attack_data_t *atk = &m->m_kind->attacks[i];
$($io, format, "%d. %s (%d)\n", i + 1, atk->name, atk->power);
}
do {
char c;
$($io, format, "What attack to perform?\n");
if ($($io, receive, &c, 1) == 0)
raise(EXC_IO);
i = c - '1';
} while (i > m->m_kind->num_attacks);
return &m->m_kind->attacks[i];
}
static void apply_damage(Monster *attacker, Monster *defender, unsigned int power)
{
int dmg = attacker->m_attack - defender->m_defense + power * attack_multiplier(attacker->m_kind, defender->m_kind) / 100;
// add some randomness
dmg = dmg * (int)$($g->m_random, randint, 110) / 100;
if (dmg > 0)
{
if (dmg > defender->m_health)
defender->m_health = 0;
else
defender->m_health -= dmg;
}
}
static unsigned int calc_xp(unsigned int enemy_level)
{
return 100 * enemy_level;
}
DefineFunction(Battle, int, run, Player *p)
{
Monster *player_monster = NULL, *enemy_monster = NULL;
while (1)
{
if (enemy_monster == NULL)
enemy_monster = get_next_alive(this->m_enemy_team);
if (player_monster == NULL)
player_monster = get_next_alive(p->m_team);
if (enemy_monster == NULL || player_monster == NULL)
break;
$($io, format, "%s (Lvl %d) versus %s (Lvl %d)\n", player_monster->m_name,
player_monster->m_level, enemy_monster->m_name, enemy_monster->m_level);
while (enemy_monster && player_monster)
{
const attack_data_t *player_attack = NULL;
char c;
$($io, format, "\nPlayer: %s\n Health %d / %d\n",
player_monster->m_name, player_monster->m_health, player_monster->m_max_health);
$($io, format, "\nEnemy: %s\n Health %d / %d\n",
enemy_monster->m_name, enemy_monster->m_health, enemy_monster->m_max_health);
try_again:
$($io, format, "Menu: (A)ttack, (D)efend, (C)apture, (R)etreat\n");
if ($($io, receive, &c, 1) == 0)
raise(EXC_IO);
switch (tolower(c))
{
case 'r':
if (this->m_can_retreat && $($g->m_random, randint, 100) < 30)
{
$($io, format, "Successful retreat!\n");
return 0;
}
$($io, format, "Unable to retreat...\n");
break;
case 'a':
player_attack = attack_menu(player_monster);
apply_damage(player_monster, enemy_monster, player_attack->power);
break;
case 'd':
$($io, format, "%s takes a defensive stance.\n", player_monster->m_name);
break;
case 'c':
if (this->m_can_capture &&
enemy_monster->m_health * 10 < enemy_monster->m_max_health &&
$($g->m_random, randint, 100) < 70)
{
$($io, format, "Successfully captured %s!\n", enemy_monster->m_name);
$(p, capture, enemy_monster);
$(this->m_enemy_team, remove, 0);
enemy_monster = NULL;
}
else
{
$($io, format, "Unable to capture %s.\n", enemy_monster->m_name);
}
break;
default:
goto try_again;
}
if (enemy_monster == NULL)
break;
if (enemy_monster->m_health == 0)
{
$(player_monster, gain_xp, calc_xp(enemy_monster->m_level));
enemy_monster = NULL;
break;
}
const attack_data_t *enemy_attack = &enemy_monster->m_kind->attacks[$($g->m_random, randint, enemy_monster->m_kind->num_attacks)];
apply_damage(enemy_monster, player_monster, enemy_attack->power * (c == 'd' ? 70 : 100) / 100);
if (player_monster->m_health == 0)
player_monster = NULL;
}
}
return enemy_monster == NULL;
}
|
dfffd083f696de2cf5bda121f61ceada52d3be86
|
c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64
|
/Engine/Source/Developer/GraphColor/Public/GraphColor.h
|
29269b474893b8f9a46a55ae2b48706f64b377a3
|
[
"MIT",
"LicenseRef-scancode-proprietary-license"
] |
permissive
|
windystrife/UnrealEngine_NVIDIAGameWorks
|
c3c7863083653caf1bc67d3ef104fb4b9f302e2a
|
b50e6338a7c5b26374d66306ebc7807541ff815e
|
refs/heads/4.18-GameWorks
| 2023-03-11T02:50:08.471040
| 2022-01-13T20:50:29
| 2022-01-13T20:50:29
| 124,100,479
| 262
| 179
|
MIT
| 2022-12-16T05:36:38
| 2018-03-06T15:44:09
|
C++
|
UTF-8
|
C
| false
| false
| 201
|
h
|
GraphColor.h
|
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
GRAPHCOLOR_API void GraphColorMesh( TArray< uint8 >& VertColors, const TArray< uint32 >& Indexes );
|
7293be380dce840fe6586492f5d7d6be55e5d679
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/arch/arm/mach-shmobile/include/mach/intc.h
|
a5603c76cfe0bcc99a502ad3c5ab4e5ab2b951d8
|
[
"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
| 10,605
|
h
|
intc.h
|
#ifndef __ASM_MACH_INTC_H
#define __ASM_MACH_INTC_H
#include <linux/sh_intc.h>
#define INTC_IRQ_PINS_ENUM_16L(p) \
p ## _IRQ0, p ## _IRQ1, p ## _IRQ2, p ## _IRQ3, \
p ## _IRQ4, p ## _IRQ5, p ## _IRQ6, p ## _IRQ7, \
p ## _IRQ8, p ## _IRQ9, p ## _IRQ10, p ## _IRQ11, \
p ## _IRQ12, p ## _IRQ13, p ## _IRQ14, p ## _IRQ15
#define INTC_IRQ_PINS_ENUM_16H(p) \
p ## _IRQ16, p ## _IRQ17, p ## _IRQ18, p ## _IRQ19, \
p ## _IRQ20, p ## _IRQ21, p ## _IRQ22, p ## _IRQ23, \
p ## _IRQ24, p ## _IRQ25, p ## _IRQ26, p ## _IRQ27, \
p ## _IRQ28, p ## _IRQ29, p ## _IRQ30, p ## _IRQ31
#define INTC_IRQ_PINS_VECT_16L(p, vect) \
vect(p ## _IRQ0, 0x0200), vect(p ## _IRQ1, 0x0220), \
vect(p ## _IRQ2, 0x0240), vect(p ## _IRQ3, 0x0260), \
vect(p ## _IRQ4, 0x0280), vect(p ## _IRQ5, 0x02a0), \
vect(p ## _IRQ6, 0x02c0), vect(p ## _IRQ7, 0x02e0), \
vect(p ## _IRQ8, 0x0300), vect(p ## _IRQ9, 0x0320), \
vect(p ## _IRQ10, 0x0340), vect(p ## _IRQ11, 0x0360), \
vect(p ## _IRQ12, 0x0380), vect(p ## _IRQ13, 0x03a0), \
vect(p ## _IRQ14, 0x03c0), vect(p ## _IRQ15, 0x03e0)
#define INTC_IRQ_PINS_VECT_16H(p, vect) \
vect(p ## _IRQ16, 0x3200), vect(p ## _IRQ17, 0x3220), \
vect(p ## _IRQ18, 0x3240), vect(p ## _IRQ19, 0x3260), \
vect(p ## _IRQ20, 0x3280), vect(p ## _IRQ21, 0x32a0), \
vect(p ## _IRQ22, 0x32c0), vect(p ## _IRQ23, 0x32e0), \
vect(p ## _IRQ24, 0x3300), vect(p ## _IRQ25, 0x3320), \
vect(p ## _IRQ26, 0x3340), vect(p ## _IRQ27, 0x3360), \
vect(p ## _IRQ28, 0x3380), vect(p ## _IRQ29, 0x33a0), \
vect(p ## _IRQ30, 0x33c0), vect(p ## _IRQ31, 0x33e0)
#define INTC_IRQ_PINS_MASK_16L(p, base) \
{ base + 0x40, base + 0x60, 8, /* INTMSK00A / INTMSKCLR00A */ \
{ p ## _IRQ0, p ## _IRQ1, p ## _IRQ2, p ## _IRQ3, \
p ## _IRQ4, p ## _IRQ5, p ## _IRQ6, p ## _IRQ7 } }, \
{ base + 0x44, base + 0x64, 8, /* INTMSK10A / INTMSKCLR10A */ \
{ p ## _IRQ8, p ## _IRQ9, p ## _IRQ10, p ## _IRQ11, \
p ## _IRQ12, p ## _IRQ13, p ## _IRQ14, p ## _IRQ15 } }
#define INTC_IRQ_PINS_MASK_16H(p, base) \
{ base + 0x48, base + 0x68, 8, /* INTMSK20A / INTMSKCLR20A */ \
{ p ## _IRQ16, p ## _IRQ17, p ## _IRQ18, p ## _IRQ19, \
p ## _IRQ20, p ## _IRQ21, p ## _IRQ22, p ## _IRQ23 } }, \
{ base + 0x4c, base + 0x6c, 8, /* INTMSK30A / INTMSKCLR30A */ \
{ p ## _IRQ24, p ## _IRQ25, p ## _IRQ26, p ## _IRQ27, \
p ## _IRQ28, p ## _IRQ29, p ## _IRQ30, p ## _IRQ31 } }
#define INTC_IRQ_PINS_PRIO_16L(p, base) \
{ base + 0x10, 0, 32, 4, /* INTPRI00A */ \
{ p ## _IRQ0, p ## _IRQ1, p ## _IRQ2, p ## _IRQ3, \
p ## _IRQ4, p ## _IRQ5, p ## _IRQ6, p ## _IRQ7 } }, \
{ base + 0x14, 0, 32, 4, /* INTPRI10A */ \
{ p ## _IRQ8, p ## _IRQ9, p ## _IRQ10, p ## _IRQ11, \
p ## _IRQ12, p ## _IRQ13, p ## _IRQ14, p ## _IRQ15 } }
#define INTC_IRQ_PINS_PRIO_16H(p, base) \
{ base + 0x18, 0, 32, 4, /* INTPRI20A */ \
{ p ## _IRQ16, p ## _IRQ17, p ## _IRQ18, p ## _IRQ19, \
p ## _IRQ20, p ## _IRQ21, p ## _IRQ22, p ## _IRQ23 } }, \
{ base + 0x1c, 0, 32, 4, /* INTPRI30A */ \
{ p ## _IRQ24, p ## _IRQ25, p ## _IRQ26, p ## _IRQ27, \
p ## _IRQ28, p ## _IRQ29, p ## _IRQ30, p ## _IRQ31 } }
#define INTC_IRQ_PINS_SENSE_16L(p, base) \
{ base + 0x00, 32, 4, /* ICR1A */ \
{ p ## _IRQ0, p ## _IRQ1, p ## _IRQ2, p ## _IRQ3, \
p ## _IRQ4, p ## _IRQ5, p ## _IRQ6, p ## _IRQ7 } }, \
{ base + 0x04, 32, 4, /* ICR2A */ \
{ p ## _IRQ8, p ## _IRQ9, p ## _IRQ10, p ## _IRQ11, \
p ## _IRQ12, p ## _IRQ13, p ## _IRQ14, p ## _IRQ15 } }
#define INTC_IRQ_PINS_SENSE_16H(p, base) \
{ base + 0x08, 32, 4, /* ICR3A */ \
{ p ## _IRQ16, p ## _IRQ17, p ## _IRQ18, p ## _IRQ19, \
p ## _IRQ20, p ## _IRQ21, p ## _IRQ22, p ## _IRQ23 } }, \
{ base + 0x0c, 32, 4, /* ICR4A */ \
{ p ## _IRQ24, p ## _IRQ25, p ## _IRQ26, p ## _IRQ27, \
p ## _IRQ28, p ## _IRQ29, p ## _IRQ30, p ## _IRQ31 } }
#define INTC_IRQ_PINS_ACK_16L(p, base) \
{ base + 0x20, 0, 8, /* INTREQ00A */ \
{ p ## _IRQ0, p ## _IRQ1, p ## _IRQ2, p ## _IRQ3, \
p ## _IRQ4, p ## _IRQ5, p ## _IRQ6, p ## _IRQ7 } }, \
{ base + 0x24, 0, 8, /* INTREQ10A */ \
{ p ## _IRQ8, p ## _IRQ9, p ## _IRQ10, p ## _IRQ11, \
p ## _IRQ12, p ## _IRQ13, p ## _IRQ14, p ## _IRQ15 } }
#define INTC_IRQ_PINS_ACK_16H(p, base) \
{ base + 0x28, 0, 8, /* INTREQ20A */ \
{ p ## _IRQ16, p ## _IRQ17, p ## _IRQ18, p ## _IRQ19, \
p ## _IRQ20, p ## _IRQ21, p ## _IRQ22, p ## _IRQ23 } }, \
{ base + 0x2c, 0, 8, /* INTREQ30A */ \
{ p ## _IRQ24, p ## _IRQ25, p ## _IRQ26, p ## _IRQ27, \
p ## _IRQ28, p ## _IRQ29, p ## _IRQ30, p ## _IRQ31 } }
#define INTC_IRQ_PINS_16(p, base, vect, str) \
\
static struct resource p ## _resources[] __initdata = { \
[0] = { \
.start = base, \
.end = base + 0x64, \
.flags = IORESOURCE_MEM, \
}, \
}; \
\
enum { \
p ## _UNUSED = 0, \
INTC_IRQ_PINS_ENUM_16L(p), \
}; \
\
static struct intc_vect p ## _vectors[] __initdata = { \
INTC_IRQ_PINS_VECT_16L(p, vect), \
}; \
\
static struct intc_mask_reg p ## _mask_registers[] __initdata = { \
INTC_IRQ_PINS_MASK_16L(p, base), \
}; \
\
static struct intc_prio_reg p ## _prio_registers[] __initdata = { \
INTC_IRQ_PINS_PRIO_16L(p, base), \
}; \
\
static struct intc_sense_reg p ## _sense_registers[] __initdata = { \
INTC_IRQ_PINS_SENSE_16L(p, base), \
}; \
\
static struct intc_mask_reg p ## _ack_registers[] __initdata = { \
INTC_IRQ_PINS_ACK_16L(p, base), \
}; \
\
static struct intc_desc p ## _desc __initdata = { \
.name = str, \
.resource = p ## _resources, \
.num_resources = ARRAY_SIZE(p ## _resources), \
.hw = INTC_HW_DESC(p ## _vectors, NULL, \
p ## _mask_registers, p ## _prio_registers, \
p ## _sense_registers, p ## _ack_registers) \
}
#define INTC_IRQ_PINS_16H(p, base, vect, str) \
\
static struct resource p ## _resources[] __initdata = { \
[0] = { \
.start = base, \
.end = base + 0x64, \
.flags = IORESOURCE_MEM, \
}, \
}; \
\
enum { \
p ## _UNUSED = 0, \
INTC_IRQ_PINS_ENUM_16H(p), \
}; \
\
static struct intc_vect p ## _vectors[] __initdata = { \
INTC_IRQ_PINS_VECT_16H(p, vect), \
}; \
\
static struct intc_mask_reg p ## _mask_registers[] __initdata = { \
INTC_IRQ_PINS_MASK_16H(p, base), \
}; \
\
static struct intc_prio_reg p ## _prio_registers[] __initdata = { \
INTC_IRQ_PINS_PRIO_16H(p, base), \
}; \
\
static struct intc_sense_reg p ## _sense_registers[] __initdata = { \
INTC_IRQ_PINS_SENSE_16H(p, base), \
}; \
\
static struct intc_mask_reg p ## _ack_registers[] __initdata = { \
INTC_IRQ_PINS_ACK_16H(p, base), \
}; \
\
static struct intc_desc p ## _desc __initdata = { \
.name = str, \
.resource = p ## _resources, \
.num_resources = ARRAY_SIZE(p ## _resources), \
.hw = INTC_HW_DESC(p ## _vectors, NULL, \
p ## _mask_registers, p ## _prio_registers, \
p ## _sense_registers, p ## _ack_registers) \
}
#define INTC_IRQ_PINS_32(p, base, vect, str) \
\
static struct resource p ## _resources[] __initdata = { \
[0] = { \
.start = base, \
.end = base + 0x6c, \
.flags = IORESOURCE_MEM, \
}, \
}; \
\
enum { \
p ## _UNUSED = 0, \
INTC_IRQ_PINS_ENUM_16L(p), \
INTC_IRQ_PINS_ENUM_16H(p), \
}; \
\
static struct intc_vect p ## _vectors[] __initdata = { \
INTC_IRQ_PINS_VECT_16L(p, vect), \
INTC_IRQ_PINS_VECT_16H(p, vect), \
}; \
\
static struct intc_mask_reg p ## _mask_registers[] __initdata = { \
INTC_IRQ_PINS_MASK_16L(p, base), \
INTC_IRQ_PINS_MASK_16H(p, base), \
}; \
\
static struct intc_prio_reg p ## _prio_registers[] __initdata = { \
INTC_IRQ_PINS_PRIO_16L(p, base), \
INTC_IRQ_PINS_PRIO_16H(p, base), \
}; \
\
static struct intc_sense_reg p ## _sense_registers[] __initdata = { \
INTC_IRQ_PINS_SENSE_16L(p, base), \
INTC_IRQ_PINS_SENSE_16H(p, base), \
}; \
\
static struct intc_mask_reg p ## _ack_registers[] __initdata = { \
INTC_IRQ_PINS_ACK_16L(p, base), \
INTC_IRQ_PINS_ACK_16H(p, base), \
}; \
\
static struct intc_desc p ## _desc __initdata = { \
.name = str, \
.resource = p ## _resources, \
.num_resources = ARRAY_SIZE(p ## _resources), \
.hw = INTC_HW_DESC(p ## _vectors, NULL, \
p ## _mask_registers, p ## _prio_registers, \
p ## _sense_registers, p ## _ack_registers) \
}
#define INTC_PINT_E_EMPTY
#define INTC_PINT_E_NONE 0, 0, 0, 0, 0, 0, 0, 0,
#define INTC_PINT_E(p) \
PINT ## p ## 0, PINT ## p ## 1, PINT ## p ## 2, PINT ## p ## 3, \
PINT ## p ## 4, PINT ## p ## 5, PINT ## p ## 6, PINT ## p ## 7,
#define INTC_PINT_V_NONE
#define INTC_PINT_V(p, vect) \
vect(PINT ## p ## 0, 0), vect(PINT ## p ## 1, 1), \
vect(PINT ## p ## 2, 2), vect(PINT ## p ## 3, 3), \
vect(PINT ## p ## 4, 4), vect(PINT ## p ## 5, 5), \
vect(PINT ## p ## 6, 6), vect(PINT ## p ## 7, 7),
#define INTC_PINT(p, mask_reg, sense_base, str, \
enums_1, enums_2, enums_3, enums_4, \
vect_1, vect_2, vect_3, vect_4, \
mask_a, mask_b, mask_c, mask_d, \
sense_a, sense_b, sense_c, sense_d) \
\
enum { \
PINT ## p ## _UNUSED = 0, \
enums_1 enums_2 enums_3 enums_4 \
}; \
\
static struct intc_vect p ## _vectors[] __initdata = { \
vect_1 vect_2 vect_3 vect_4 \
}; \
\
static struct intc_mask_reg p ## _mask_registers[] __initdata = { \
{ mask_reg, 0, 32, /* PINTER */ \
{ mask_a mask_b mask_c mask_d } } \
}; \
\
static struct intc_sense_reg p ## _sense_registers[] __initdata = { \
{ sense_base + 0x00, 16, 2, /* PINTCR */ \
{ sense_a } }, \
{ sense_base + 0x04, 16, 2, /* PINTCR */ \
{ sense_b } }, \
{ sense_base + 0x08, 16, 2, /* PINTCR */ \
{ sense_c } }, \
{ sense_base + 0x0c, 16, 2, /* PINTCR */ \
{ sense_d } }, \
}; \
\
static struct intc_desc p ## _desc __initdata = { \
.name = str, \
.hw = INTC_HW_DESC(p ## _vectors, NULL, \
p ## _mask_registers, NULL, \
p ## _sense_registers, NULL), \
}
#endif /* __ASM_MACH_INTC_H */
|
e601f2799db91d63b7e9dcb02062d8f359e82381
|
7664f318ed04bd0680f3d82321c18896e3ef6ad5
|
/src/overlays/actors/ovl_Oceff_Storm/z_oceff_storm.h
|
e4b831a20841e3ef9e9431c048faae9cc05368cd
|
[] |
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
| 488
|
h
|
z_oceff_storm.h
|
#ifndef Z_OCEFF_STORM_H
#define Z_OCEFF_STORM_H
#include "ultra64.h"
#include "global.h"
struct OceffStorm;
typedef void (*OceffStormActionFunc)(struct OceffStorm*, PlayState*);
typedef struct OceffStorm {
/* 0x0000 */ Actor actor;
/* 0x014C */ u16 counter;
/* 0x014E */ u8 primColorAlpha;
/* 0x014F */ u8 vtxAlpha;
/* 0x0150 */ s16 posYOff;
/* 0x0152 */ s16 posYOffAdd;
/* 0x0154 */ OceffStormActionFunc actionFunc;
} OceffStorm; // size = 0x0158
#endif
|
36edb76b0f662fe59f12ddfbb04191148ea51763
|
35806cf316f378a8ca98c0e244d149e052b1248d
|
/src/cmd/go/testdata/src/badc/x.c
|
f6cbf6924db1414a3001acd3c6005eff2bb99b8b
|
[
"LicenseRef-scancode-google-patent-license-golang",
"BSD-3-Clause"
] |
permissive
|
gomini/go-mips32
|
337000fe20d8c35e24245d3a9d205defddedad65
|
56b0efd6bad0c9554b5670fa6c3641282dd4d570
|
refs/heads/dev.github
| 2023-03-10T01:34:51.544213
| 2023-02-20T22:40:56
| 2023-02-20T22:40:56
| 43,116,287
| 155
| 52
|
BSD-3-Clause
| 2023-02-20T22:40:57
| 2015-09-25T07:30:35
|
Go
|
UTF-8
|
C
| false
| false
| 11
|
c
|
x.c
|
// C code!
|
1a853f253fe8228afcd848976e28fda0b9bcd3f4
|
badb70a0b235c98ac034cfe5b4bfafda36647831
|
/Include/Acidanthera/Library/OcAppleImageConversionLib.h
|
7360dcfa89377a681fd4a2dbb07028971149e9f5
|
[
"BSD-3-Clause"
] |
permissive
|
acidanthera/OpenCorePkg
|
f34a7d67b22c74fb5ab559e48519e5f5855b6751
|
1d5b1736fe5a5ef7662b5c076c6d11aac96fd5d6
|
refs/heads/master
| 2023-08-30T21:03:02.993659
| 2023-08-28T23:30:43
| 2023-08-28T23:30:43
| 179,354,282
| 13,212
| 2,999
|
BSD-3-Clause
| 2023-09-10T18:29:53
| 2019-04-03T19:14:29
|
C
|
UTF-8
|
C
| false
| false
| 1,156
|
h
|
OcAppleImageConversionLib.h
|
/** @file
Copyright (C) 2018 savvas. All rights reserved.<BR>
Portions copyright (C) 2016 slice. All rights reserved.<BR>
Portions copyright (C) 2018 vit9696. 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.
**/
#ifndef OC_APPLE_IMAGE_CONVERSION_LIB_H
#define OC_APPLE_IMAGE_CONVERSION_LIB_H
#include <Protocol/UgaDraw.h>
#include <Protocol/AppleImageConversion.h>
/**
Install and initialise the Apple Image Conversion protocol.
@param[in] Reinstall Replace any installed protocol.
@returns Installed or located protocol.
@retval NULL There was an error locating or installing the protocol.
**/
APPLE_IMAGE_CONVERSION_PROTOCOL *
OcAppleImageConversionInstallProtocol (
IN BOOLEAN Reinstall
);
#endif // OC_APPLE_IMAGE_CONVERSION_LIB_H
|
1ad80abaae6fea8e563efdf1c0e93771ad61097c
|
1c92d2c1fb2ed9a4bf6a9c9f1875bb5fff546086
|
/common/one_hot.c
|
fb5b3bfcf51e6eeabe41af3cca342d1bc96896a6
|
[] |
permissive
|
n64dev/cen64
|
83a5b77221408745a16c323b902c20ecdb00f146
|
1c1118462bd9d9b8ceb4c556a647718072477aab
|
refs/heads/master
| 2023-09-05T18:35:09.152950
| 2023-05-29T04:24:38
| 2023-05-29T04:24:38
| 9,182,531
| 435
| 65
|
BSD-3-Clause
| 2023-09-02T21:07:35
| 2013-04-02T23:17:08
|
C
|
UTF-8
|
C
| false
| false
| 1,504
|
c
|
one_hot.c
|
//
// vr4300/one_hot.c: 8-bit one-hot LUT.
//
// CEN64: Cycle-Accurate Nintendo 64 Emulator.
// Copyright (C) 2015, Tyler J. Stachecki.
//
// This file is subject to the terms and conditions defined in
// 'LICENSE', which is part of this source code package.
//
#include "common.h"
cen64_align(const int8_t cen64_one_hot_lut[256], CACHE_LINE_SIZE) = {
-1,
// 1
0,
// 2
1, -1,
// 4
2, -1, -1, -1,
// 8
3, -1, -1, -1, -1, -1, -1, -1,
// 16
4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
// 32
5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
// 64
6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
// 128
7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
|
063afac67bc5ce3cdf407713c545933d4e60b20c
|
3bbf88dc48d70e4c362e15589967c271f5ce844f
|
/core/src/xmake/winos/registry_values.c
|
ecddabdf58b71162bd559b16c51cd65d59aba7ba
|
[
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"Unlicense",
"MIT"
] |
permissive
|
xmake-io/xmake
|
ed420a84d9dddd36946893e60799bd912ffd917d
|
025c5e8415b456bf5f24e37322731615bd5ddea1
|
refs/heads/master
| 2023-08-31T13:40:45.719615
| 2023-08-31T14:33:50
| 2023-08-31T14:33:50
| 34,431,834
| 6,914
| 618
|
Apache-2.0
| 2023-09-14T09:23:40
| 2015-04-23T03:37:31
|
Lua
|
UTF-8
|
C
| false
| false
| 5,813
|
c
|
registry_values.c
|
/*!A cross-platform build utility based on Lua
*
* 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.
*
* Copyright (C) 2015-present, TBOOX Open Source Group.
*
* @author ruki
* @file registry_values.c
*
*/
/* //////////////////////////////////////////////////////////////////////////////////////
* trace
*/
#define TB_TRACE_MODULE_NAME "registry_values"
#define TB_TRACE_MODULE_DEBUG (0)
/* //////////////////////////////////////////////////////////////////////////////////////
* includes
*/
#include "prefix.h"
/* //////////////////////////////////////////////////////////////////////////////////////
* implementation
*/
/* get registry values
*
* local count, errors = winos.registry_values("HKEY_LOCAL_MACHINE",
* "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug",
* function (value_name)
* return true -- continue or break
* end)
*/
tb_int_t xm_winos_registry_values(lua_State* lua)
{
// check
tb_assert_and_check_return_val(lua, 0);
// get the arguments
tb_char_t const* rootkey = luaL_checkstring(lua, 1);
tb_char_t const* rootdir = luaL_checkstring(lua, 2);
tb_bool_t is_function = lua_isfunction(lua, 3);
tb_check_return_val(rootkey && rootdir && is_function, 0);
// enum values
tb_bool_t ok = tb_false;
tb_int_t count = 0;
HKEY key = tb_null;
HKEY keynew = tb_null;
do
{
// get registry rootkey
if (!tb_strcmp(rootkey, "HKEY_CLASSES_ROOT")) key = HKEY_CLASSES_ROOT;
else if (!tb_strcmp(rootkey, "HKCR")) key = HKEY_CLASSES_ROOT;
else if (!tb_strcmp(rootkey, "HKEY_CURRENT_CONFIG")) key = HKEY_CURRENT_CONFIG;
else if (!tb_strcmp(rootkey, "HKCC")) key = HKEY_CURRENT_CONFIG;
else if (!tb_strcmp(rootkey, "HKEY_CURRENT_USER")) key = HKEY_CURRENT_USER;
else if (!tb_strcmp(rootkey, "HKCU")) key = HKEY_CURRENT_USER;
else if (!tb_strcmp(rootkey, "HKEY_LOCAL_MACHINE")) key = HKEY_LOCAL_MACHINE;
else if (!tb_strcmp(rootkey, "HKLM")) key = HKEY_LOCAL_MACHINE;
else if (!tb_strcmp(rootkey, "HKEY_USERS")) key = HKEY_USERS;
else
{
lua_pushnil(lua);
lua_pushfstring(lua, "invalid registry rootkey: %s", rootkey);
break;
}
// open registry key
if (RegOpenKeyExA(key, rootdir, 0, KEY_QUERY_VALUE, &keynew) != ERROR_SUCCESS && keynew)
{
lua_pushnil(lua);
lua_pushfstring(lua, "open registry key failed: %s\\%s", rootkey, rootdir);
break;
}
// query values
DWORD value_name_num = 0;
DWORD value_name_maxn = 0;
if (RegQueryInfoKeyW(keynew, tb_null, tb_null, tb_null, tb_null, tb_null, tb_null, &value_name_num, &value_name_maxn, tb_null, tb_null, tb_null) != ERROR_SUCCESS)
{
lua_pushnil(lua);
lua_pushfstring(lua, "query registry info failed: %s\\%s", rootkey, rootdir);
break;
}
value_name_maxn++; // add `\0`
// ensure enough value name buffer
tb_wchar_t value_name[1024];
if (value_name_maxn > tb_arrayn(value_name))
{
lua_pushnil(lua);
lua_pushfstring(lua, "no enough value name buffer: %s\\%s", rootkey, rootdir);
break;
}
// get all values
DWORD i = 0;
tb_char_t value_name_a[1024];
for (i = 0; i < value_name_num; i++)
{
// get value name
value_name[0] = L'\0';
DWORD value_name_size = tb_arrayn(value_name);
if (RegEnumValueW(keynew, i, value_name, &value_name_size, tb_null, tb_null, tb_null, tb_null) != ERROR_SUCCESS)
{
lua_pushnil(lua);
lua_pushfstring(lua, "get registry value name(%d) failed: %s\\%s", i, rootkey, rootdir);
break;
}
// get value name (mbs)
tb_size_t value_name_a_size = tb_wtoa(value_name_a, value_name, sizeof(value_name_a));
if (value_name_a_size == -1)
{
lua_pushnil(lua);
lua_pushfstring(lua, "convert registry value name(%d) failed: %s\\%s", i, rootkey, rootdir);
break;
}
// do callback(value_name)
lua_pushvalue(lua, 3);
lua_pushlstring(lua, value_name_a, value_name_a_size);
lua_call(lua, 1, 1);
count++;
// is continue?
tb_bool_t is_continue = lua_toboolean(lua, -1);
lua_pop(lua, 1);
if (!is_continue)
{
ok = tb_true;
break;
}
}
// ok
if (i == value_name_num)
ok = tb_true;
} while (0);
// exit registry key
if (keynew)
RegCloseKey(keynew);
keynew = tb_null;
// ok?
if (ok)
{
lua_pushinteger(lua, count);
return 1;
}
else return 2;
}
|
80126d84d261c588e03c3992a199b9dca920140f
|
89adda6b74cf044491fc3aea784f75abf8855bc7
|
/srcs/net/net.h
|
49ca51c470e5883fba02f6dc433341da18165fa5
|
[
"MIT"
] |
permissive
|
gamozolabs/falkervisor_grilled_cheese
|
00288953a577132d62858593ce31bc518edc4aff
|
9d7ef8e17c44c0f8ed8a5c6ee47d875fb6de4449
|
refs/heads/master
| 2022-07-09T19:19:45.496207
| 2022-06-24T00:08:44
| 2022-06-24T00:08:44
| 148,107,646
| 162
| 30
| null | 2020-08-12T23:16:23
| 2018-09-10T06:15:11
|
C
|
UTF-8
|
C
| false
| false
| 6,359
|
h
|
net.h
|
#pragma once
#define NET_BASE_PORT 1400
#define NET_TERM_PRINTSTR 0xc1bc2ea7cd2f4ac6
#define NET_NOTIFY_REBOOT 0x636300e3c6e4f392
#define NET_REBOOT_REQUEST 0x9d7367f260ec073a
#define NET_REPORT_COVERAGE_STATUS 0xc0330f3bd9f585d9
#define NET_FILE_DOWNLOAD 0x18c59e5b342482c1
#define NET_FILE_DOWNLOAD_RESP 0x767bc53bc2d2ced0
#define NET_FILE_DOWNLOAD_CHUNK 0xeb717e7f8d411b03
#define NET_SNAP_UPLOAD 0x1A8FA024
#define NET_SNAP_UPLOAD_DATA 0x1E004AFA
#define NET_SNAP_UPLOAD_CONF 0x4E0E3AFD
#define NET_FILE_CHUNK_SIZE 8192
#define NET_COVERAGE_INFO 0xe645244373577400
#pragma pack(push, 1)
struct _file_download {
uint64_t magic;
uint64_t req_id;
uint64_t offset;
uint64_t size;
uint64_t info_only;
char fn[256];
};
struct _file_download_response {
uint64_t magic;
uint64_t req_id;
uint64_t hash;
uint64_t file_len; /* -1 if file not found */
};
struct _file_download_chunk {
uint64_t magic;
uint64_t req_id;
uint64_t seq_id;
uint8_t buf[8192];
};
struct _snap_upload {
uint64_t magic;
uint64_t req_id;
uint64_t file_len;
uint64_t padding;
uint8_t fn[256];
__m128i hash;
};
struct _snap_upload_data {
uint64_t magic;
uint64_t req_id;
uint8_t data[NET_FILE_CHUNK_SIZE];
};
struct _snap_upload_conf {
uint64_t magic;
uint64_t req_id;
};
struct _coverage_info {
uint64_t magic;
uint64_t fuzzes;
uint64_t cc_count;
uint64_t uniq_crashes;
};
#pragma pack(pop)
struct _net_queue {
/* Identifier of the queue. This number is used directly for NICs with
* multiple queues, so it should be 0-based.
*
* All queues other than queue 0 must have a filter in order for packets
* to be routed to it.
*
* Maximum number of queues:
*
* +-------------------------+-----------+-----------+
* | Device | RX Queues | TX Queues |
* +-------------------------+-----------+-----------+
* | Intel X540 | 128 | 128 |
* +-------------------------+-----------+-----------+
*/
int queue_id;
/* UDP port which will be used as the filter to route to this queue. This
* field is unused for queue 0, as no filters are allowed on queue 0.
* Filters only apply to RX queues, any TX queue can be used to send any
* packet.
*
* Queues are filtered with the following:
*
* Packet must be UDP
* Packet destination IP must match queue->device->ip.
* Packet destination port must match queue->filter_port.
*/
int filter_port;
/* Per-device specific context related to the queue */
void *device_context;
/* Pointer to routine to send packets on this queue */
rstate_t
(*send)(
struct _net_queue *queue,
const void *packet,
uint32_t length);
/* Pointer to routine to recv packets on this queue */
rstate_t
(*recv)(
struct _net_queue *queue,
void **packet,
uint32_t *packet_len);
/* Pointer to routine to advance recv pointer */
rstate_t
(*recv_release)(struct _net_queue *queue);
/* Current task who owns the lock on this structure. If NULL, available
* for use.
*/
struct _task *task_using;
/* Network device to which this queue belongs */
struct _net_device *device;
/* Next queue in the linked list of queues for the given device */
struct _net_queue *next;
};
struct _net_device {
/* MAC address and IP of this device, stored in network endianness. If
* DHCP assignment failed, the IP will be 0.
*/
uint8_t mac[6];
uint32_t ip;
/* MAC address and IP of the DHCP server, stored in network endianness. If
* DHCP failed both fields will be filled with 0xff.
*/
uint8_t dhcp_mac[6];
uint32_t dhcp_ip;
uint32_t dhcp_lease_time;
/* PCI BAR0 address */
uintptr_t bar0;
/* Number of queues for this device */
uint32_t num_queues;
/* Linked list of queues associated with this device */
struct _net_queue queues;
struct _net_queue *queues_end;
/* Queue to use in timer interrupts */
struct _net_queue *interrupt_queue;
/* Next network device in the linked list */
struct _net_device *next;
};
struct _remote_map_state {
uint64_t chunk_size;
void *chunk_tmp;
char fn[256];
};
#pragma pack(push, 1)
struct _udp_packet {
/* MAC header */
uint8_t dest_mac[6];
uint8_t src_mac[6];
uint16_t type;
/* IP header */
uint8_t ver;
uint8_t svc;
uint16_t len; /* 28 + payload_len */
uint16_t ident;
uint8_t flags;
uint8_t frag;
uint8_t ttl;
uint8_t proto; /* 0x11 - UDP */
uint16_t ip_chk;
uint32_t src_ip;
uint32_t dest_ip;
/* UDP header */
uint16_t src_port;
uint16_t dest_port;
uint16_t ulen; /* 8 + payload_len */
uint16_t udp_chk;
uint8_t payload[8972];
};
#pragma pack(pop)
#pragma pack(push, 1)
struct _arp_packet {
/* MAC header */
uint8_t dest_mac[6];
uint8_t src_mac[6];
uint16_t type;
uint16_t hw_type;
uint16_t proto_type;
uint8_t hw_size;
uint8_t proto_size;
uint16_t op;
uint8_t sender_mac[6];
uint32_t sender_ip;
uint8_t target_mac[6];
uint32_t target_ip;
};
#pragma pack(pop)
rstate_t
net_init(void);
rstate_t
net_init_local_queue(void);
void
net_display_devices(void);
rstate_t
net_process_interval(void);
rstate_t
net_consume_unwanted(struct _net_device *device,
uint8_t *packet, uint32_t packet_len);
rstate_t
net_send_udp(
struct _net_queue *queue,
const void *payload,
uint32_t len,
uint32_t dest_ip,
uint32_t dest_port);
rstate_t
net_parse_udp(
const void *packet,
uint32_t packet_len,
void **udp_payload,
uint32_t *udp_payload_len);
rstate_t
net_recv_udp(
struct _net_queue *queue,
void **packet,
uint32_t *packet_len,
struct _udp_packet **raw);
rstate_t
net_recv_release(struct _net_queue *queue);
rstate_t
net_notify_server(void);
rstate_t
net_download_file(
struct _net_queue *queue,
const char *filename,
uint64_t offset,
void **outbuf,
uint64_t *outlen);
rstate_t
net_map_remote(
struct _net_queue *queue,
const char *filename,
uint64_t chunk_size,
void **outbuf,
uint64_t *outlen);
rstate_t
net_start(struct _net_queue *queue);
void
net_stop(struct _net_queue *queue);
rstate_t
net_upload(
struct _net_queue *queue,
const char *fn,
void *buf,
size_t len);
|
bfae1b81eb0b2590b4833b27226305ff8fe5bdea
|
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
|
/usr.bin/xlint/lint1/mem1.c
|
18495f0e11819d82ad8011709eaf0ee7b572dcc5
|
[] |
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
| 9,700
|
c
|
mem1.c
|
/* $NetBSD: mem1.c,v 1.74 2023/08/12 20:48:24 rillig Exp $ */
/*
* Copyright (c) 1994, 1995 Jochen Pohl
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Jochen Pohl for
* The NetBSD Project.
* 4. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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.
*/
#if HAVE_NBTOOL_CONFIG_H
#include "nbtool_config.h"
#endif
#include <sys/cdefs.h>
#if defined(__RCSID)
__RCSID("$NetBSD: mem1.c,v 1.74 2023/08/12 20:48:24 rillig Exp $");
#endif
#include <sys/param.h>
#include <stdlib.h>
#include <string.h>
#include "lint1.h"
/*
* Filenames allocated by record_filename are shared and have unlimited
* lifetime.
*/
struct filename {
const char *fn_name;
size_t fn_len;
int fn_id;
struct filename *fn_next;
};
static struct filename *filenames; /* null-terminated array */
static int next_filename_id;
/* Find the given filename, or return NULL. */
static const struct filename *
search_filename(const char *s, size_t len)
{
const struct filename *fn;
for (fn = filenames; fn != NULL; fn = fn->fn_next) {
if (fn->fn_len == len && memcmp(fn->fn_name, s, len) == 0)
break;
}
return fn;
}
struct filename_replacement {
const char *orig;
size_t orig_len;
const char *repl;
const struct filename_replacement *next;
};
static struct filename_replacement *filename_replacements;
void
add_directory_replacement(char *arg)
{
struct filename_replacement *r = xmalloc(sizeof(*r));
char *sep = strchr(arg, '=');
if (sep == NULL)
err(1, "Bad replacement directory spec `%s'", arg);
*sep = '\0';
r->orig = arg;
r->orig_len = (size_t)(sep - arg);
r->repl = sep + 1;
r->next = filename_replacements;
filename_replacements = r;
}
const char *
transform_filename(const char *name, size_t len)
{
static char buf[MAXPATHLEN];
const struct filename_replacement *r;
for (r = filename_replacements; r != NULL; r = r->next)
if (r->orig_len < len &&
memcmp(name, r->orig, r->orig_len) == 0)
break;
if (r == NULL)
return name;
(void)snprintf(buf, sizeof(buf), "%s%s", r->repl, name + r->orig_len);
return buf;
}
/*
* Return a copy of the filename s with unlimited lifetime.
* If the filename is new, write it to the output file.
*/
const char *
record_filename(const char *s, size_t slen)
{
const struct filename *existing_fn = search_filename(s, slen);
if (existing_fn != NULL)
return existing_fn->fn_name;
char *name = xmalloc(slen + 1);
(void)memcpy(name, s, slen);
name[slen] = '\0';
struct filename *fn = xmalloc(sizeof(*fn));
fn->fn_name = name;
fn->fn_len = slen;
fn->fn_id = next_filename_id++;
fn->fn_next = filenames;
filenames = fn;
outint(fn->fn_id);
outchar('s');
outstrg(transform_filename(fn->fn_name, fn->fn_len));
outchar('\n');
return fn->fn_name;
}
/* Get the ID of a filename. */
int
get_filename_id(const char *s)
{
const struct filename *fn;
if (s == NULL || (fn = search_filename(s, strlen(s))) == NULL)
return -1;
return fn->fn_id;
}
typedef struct memory_pools {
struct memory_pool *pools;
size_t cap;
} memory_pools;
/* Array of memory pools, indexed by mem_block_level. */
static memory_pools mpools;
/* The pool for the current expression is independent of any block level. */
static memory_pool expr_pool;
static void
mpool_add(memory_pool *pool, struct memory_pool_item item)
{
if (pool->len >= pool->cap) {
pool->cap = 2 * pool->len + 16;
pool->items = xrealloc(pool->items,
sizeof(*pool->items) * pool->cap);
}
pool->items[pool->len++] = item;
}
#ifdef DEBUG_MEM
static void
debug_memory_pool_item(const struct memory_pool_item *item)
{
void *p = item->p;
size_t size = item->size;
const char *descr = item->descr;
if (strcmp(descr, "string") == 0) {
const char *str = p;
debug_step("%s: freeing string '%s'", __func__, str);
} else if (strcmp(descr, "sym") == 0) {
const sym_t *sym = p;
debug_step("%s: freeing symbol '%s'", __func__, sym->s_name);
} else if (strcmp(descr, "type") == 0) {
const type_t *tp = p;
debug_step("%s: freeing type '%s'", __func__, type_name(tp));
} else if (strcmp(descr, "tnode") == 0) {
const tnode_t *tn = p;
debug_step("%s: freeing node '%s' with type '%s'",
__func__, op_name(tn->tn_op), type_name(tn->tn_type));
} else
debug_step("%s: freeing '%s' with %zu bytes",
__func__, descr, size);
}
#endif
static void
mpool_free(memory_pool *pool)
{
#ifdef DEBUG_MEM
for (size_t i = pool->len; i-- > 0; )
debug_memory_pool_item(pool->items + i);
#endif
for (size_t i = pool->len; i-- > 0;) {
#ifdef DEBUG_MEM
static void *(*volatile set)(void *, int, size_t) = memset;
set(pool->items[i].p, 'Z', pool->items[i].size);
#endif
free(pool->items[i].p);
}
pool->len = 0;
}
static void *
#ifdef DEBUG_MEM
mpool_zero_alloc(memory_pool *pool, size_t size, const char *descr)
#else
mpool_zero_alloc(memory_pool *pool, size_t size)
#endif
{
void *mem = xmalloc(size);
memset(mem, 0, size);
#if DEBUG_MEM
mpool_add(pool, (struct memory_pool_item){ mem, size, descr });
#else
mpool_add(pool, (struct memory_pool_item){ mem });
#endif
return mem;
}
static memory_pool *
mpool_at(size_t level)
{
if (level >= mpools.cap) {
size_t prev_cap = mpools.cap;
mpools.cap = level + 16;
mpools.pools = xrealloc(mpools.pools,
sizeof(*mpools.pools) * mpools.cap);
for (size_t i = prev_cap; i < mpools.cap; i++)
mpools.pools[i] = (memory_pool){ NULL, 0, 0 };
}
return mpools.pools + level;
}
/* Allocate memory associated with the level, initialized with zero. */
#ifdef DEBUG_MEM
void *
level_zero_alloc(size_t level, size_t size, const char *descr)
{
debug_step("%s: %s at level %zu", __func__, descr, level);
return mpool_zero_alloc(mpool_at(level), size, descr);
}
#else
void *
(level_zero_alloc)(size_t level, size_t size)
{
return mpool_zero_alloc(mpool_at(level), size);
}
#endif
/* Allocate memory that is freed at the end of the current block. */
#ifdef DEBUG_MEM
void *
block_zero_alloc(size_t size, const char *descr)
{
return level_zero_alloc(mem_block_level, size, descr);
}
#else
void *
(block_zero_alloc)(size_t size)
{
return (level_zero_alloc)(mem_block_level, size);
}
#endif
void
level_free_all(size_t level)
{
debug_step("+ %s %zu", __func__, level);
debug_indent_inc();
mpool_free(mpool_at(level));
debug_leave();
}
/* Allocate memory that is freed at the end of the current expression. */
#if DEBUG_MEM
void *
expr_zero_alloc(size_t s, const char *descr)
{
return mpool_zero_alloc(&expr_pool, s, descr);
}
#else
void *
(expr_zero_alloc)(size_t size)
{
return mpool_zero_alloc(&expr_pool, size);
}
#endif
static bool
str_ends_with(const char *haystack, const char *needle)
{
size_t hlen = strlen(haystack);
size_t nlen = strlen(needle);
return nlen <= hlen &&
memcmp(haystack + hlen - nlen, needle, nlen) == 0;
}
/*
* Return a freshly allocated tree node that is freed at the end of the
* current expression.
*
* The node records whether it comes from a system file, which makes strict
* bool mode less restrictive.
*/
tnode_t *
expr_alloc_tnode(void)
{
tnode_t *tn = expr_zero_alloc(sizeof(*tn), "tnode");
/*
* files named *.c that are different from the main translation unit
* typically contain generated code that cannot be influenced, such
* as a flex lexer or a yacc parser.
*/
tn->tn_sys = in_system_header ||
(curr_pos.p_file != csrc_pos.p_file &&
str_ends_with(curr_pos.p_file, ".c"));
return tn;
}
/* Free all memory which is allocated by the current expression. */
void
expr_free_all(void)
{
debug_step("%s", __func__);
mpool_free(&expr_pool);
}
/*
* Save the memory which is used by the current expression. This memory
* is not freed by the next expr_free_all() call. The returned value can be
* used to restore the memory.
*/
memory_pool
expr_save_memory(void)
{
memory_pool saved_pool = expr_pool;
expr_pool = (memory_pool){ NULL, 0, 0 };
return saved_pool;
}
/*
* Free all memory used for the current expression and restore the memory used
* by a previous expression and saved by expr_save_memory(). The next call to
* expr_free_all() frees the restored memory.
*/
void
expr_restore_memory(memory_pool saved_pool)
{
expr_free_all();
free(expr_pool.items);
expr_pool = saved_pool;
}
|
fee78f8c8705747337940d71a3270c295aba33c3
|
fcad0847f36caed70c6823a7fa93f64309d75597
|
/cudnn/cudnn_basic.c
|
a452813a371f92e7c8aff0a19a2366c90dc64717
|
[
"BSD-3-Clause"
] |
permissive
|
mvitez/thnets
|
923e7c76ee9b275e17d83da80eaad3dd273333eb
|
ac3ad6d98e7cce17ecd3e44de1311eb27935e00e
|
refs/heads/master
| 2020-12-15T01:29:11.491275
| 2019-04-30T09:48:32
| 2019-04-30T09:49:23
| 48,061,703
| 202
| 34
| null | 2017-01-20T13:57:46
| 2015-12-15T18:36:33
|
C
|
UTF-8
|
C
| false
| false
| 14,338
|
c
|
cudnn_basic.c
|
#include <stdlib.h>
#include <string.h>
#include "../thnets.h"
#include "cublas_v2.h"
static cudnnHandle_t handle;
static cublasHandle_t blashandle;
int floattype = CUDNN_DATA_FLOAT;
void checkerr(int status)
{
if(status)
THError("cudnn call failed");
}
cudnnHandle_t THcudnn_getHandle()
{
if(!handle)
cudnnCreate(&handle);
return handle;
}
cublasHandle_t THcublas_getHandle()
{
if(!blashandle)
cublasCreate(&blashandle);
return blashandle;
}
int THcudnn_TensorDescriptor(cudnnTensorDescriptor_t *d, THFloatTensor *t)
{
int i, rc, base;
int size[4], stride[4];
rc = cudnnCreateTensorDescriptor(d);
if(rc)
return rc;
if(t->nDimension == 3)
{
size[0] = 1;
stride[0] = THFloatTensor_nElement(t);
base = 1;
} else base = 0;
for(i = 0; i < t->nDimension; i++)
{
size[i+base] = t->size[i];
stride[i+base] = t->stride[i];
}
return cudnnSetTensorNdDescriptor(*d, floattype, 4, size, stride);
}
THFloatStorage *THCudaStorage_new(long size)
{
THFloatStorage *s = malloc(sizeof(*s));
int datasize = floattype == CUDNN_DATA_HALF ? 2 : 4;
errcheck(cudaMalloc((void **)&s->data, size * datasize));
s->nref = 1;
s->mustfree = 2;
return s;
}
THFloatTensor *THCudaTensor_newFromFloatTensor(THFloatTensor *t)
{
THFloatTensor *n = malloc(sizeof(*n));
memcpy(n, t, sizeof(*n));
if(t->storage)
{
n->storage = malloc(sizeof(*n->storage));
n->storage->nref = 1;
n->storage->mustfree = 2;
n->storageOffset = 0;
int datasize = floattype == CUDNN_DATA_HALF ? 2 : 4;
errcheck(cudaMalloc((void **)&n->storage->data, THFloatTensor_nElement(t) * datasize));
errcheck(cudaMemcpy(n->storage->data, THFloatTensor_data(t), THFloatTensor_nElement(t) * datasize, cudaMemcpyHostToDevice));
}
return n;
}
THFloatTensor *THFloatTensor_newFromCudaTensor(THFloatTensor *t)
{
THFloatTensor *n = malloc(sizeof(*n));
memcpy(n, t, sizeof(*n));
if(t->storage)
{
n->storage = malloc(sizeof(*n->storage));
n->storageOffset = 0;
n->storage->nref = 1;
n->storage->mustfree = 1;
n->storage->data = malloc(THFloatTensor_nElement(t) * sizeof(*n->storage->data));
errcheck(cudaMemcpy(n->storage->data, THFloatTensor_data(t), THFloatTensor_nElement(t) * sizeof(*n->storage->data), cudaMemcpyDeviceToHost));
}
return n;
}
void THCudaTensor_resize4d(THFloatTensor *t, long size0, long size1, long size2, long size3)
{
long nelemorig = THFloatTensor_nElement(t);
t->nDimension = 4;
t->size[0] = size0;
t->size[1] = size1;
t->size[2] = size2;
t->size[3] = size3;
t->stride[3] = 1;
t->stride[2] = size3;
t->stride[1] = size2 * size3;
t->stride[0] = size1 * size2 * size3;
if(!t->storage)
{
t->storage = malloc(sizeof(*t->storage));
t->storage->nref = 1;
t->storage->mustfree = 2;
int datasize = floattype == CUDNN_DATA_HALF ? 2 : 4;
errcheck(cudaMalloc((void **)&t->storage->data, THFloatTensor_nElement(t) * datasize));
} else if(nelemorig != THFloatTensor_nElement(t))
THError("Resizing of CUDA tensors not supported");
}
void THCudaTensor_resize3d(THFloatTensor *t, long size0, long size1, long size2)
{
long nelemorig = THFloatTensor_nElement(t);
t->nDimension = 3;
t->size[0] = size0;
t->size[1] = size1;
t->size[2] = size2;
t->stride[2] = 1;
t->stride[1] = size2;
t->stride[0] = size1 * size2;
if(!t->storage)
{
t->storage = malloc(sizeof(*t->storage));
t->storage->nref = 1;
t->storage->mustfree = 2;
int datasize = floattype == CUDNN_DATA_HALF ? 2 : 4;
errcheck(cudaMalloc((void **)&t->storage->data, THFloatTensor_nElement(t) * datasize));
} else if(nelemorig != THFloatTensor_nElement(t))
THError("Resizing of CUDA tensors not supported");
}
void THCudaTensor_resize2d(THFloatTensor *t, long size0, long size1)
{
long nelemorig = THFloatTensor_nElement(t);
t->nDimension = 2;
t->size[0] = size0;
t->size[1] = size1;
t->stride[1] = 1;
t->stride[0] = size1;
if(!t->storage)
{
t->storage = malloc(sizeof(*t->storage));
t->storage->nref = 1;
t->storage->mustfree = 2;
int datasize = floattype == CUDNN_DATA_HALF ? 2 : 4;
errcheck(cudaMalloc((void **)&t->storage->data, THFloatTensor_nElement(t) * datasize));
} else if(nelemorig != THFloatTensor_nElement(t))
THError("Resizing of CUDA tensors not supported");
}
void THCudaTensor_resize1d(THFloatTensor *t, long size0)
{
long nelemorig = THFloatTensor_nElement(t);
t->nDimension = 1;
t->size[0] = size0;
t->stride[0] = 1;
if(!t->storage)
{
t->storage = malloc(sizeof(*t->storage));
t->storage->nref = 1;
t->storage->mustfree = 2;
int datasize = floattype == CUDNN_DATA_HALF ? 2 : 4;
errcheck(cudaMalloc((void **)&t->storage->data, THFloatTensor_nElement(t) * datasize));
} else if(nelemorig != THFloatTensor_nElement(t))
THError("Resizing of CUDA tensors not supported");
}
void THCudaTensor_resizeAs(THFloatTensor *tdst, THFloatTensor *tsrc)
{
if(tsrc == tdst)
return;
long nelemsrc = THFloatTensor_nElement(tsrc);
tdst->nDimension = tsrc->nDimension;
memcpy(tdst->size, tsrc->size, sizeof(tsrc->size));
memcpy(tdst->stride, tsrc->stride, sizeof(tsrc->stride));
if(!tdst->storage)
tdst->storage = THCudaStorage_new(nelemsrc);
else if(nelemsrc != THFloatTensor_nElement(tdst))
THError("Resizing of CUDA tensors not supported");
}
struct network *THcudnn_ToCUDNN(struct network *net)
{
int i;
struct network *nn = malloc(sizeof(*nn));
nn->nelem = net->nelem;
nn->modules = malloc(sizeof(net->modules[0]) * net->nelem);
nn->engine = ENGINE_CUDA;
memcpy(nn->modules, net->modules, sizeof(net->modules[0]) * net->nelem);
for(i = 0; i < net->nelem; i++)
{
nn->modules[i].output = THCudaTensor_newFromFloatTensor(net->modules[i].output);
nn->modules[i].net = nn;
switch(net->modules[i].type)
{
case MT_SpatialConvolutionMM:
case MT_SpatialConvolution:
case MT_SpatialConvolutionVirtMM:
nn->modules[i].updateOutput = cudnn_SpatialConvolution_updateOutput;
#ifdef HAVEFP16
if(floattype == CUDNN_DATA_HALF)
{
nn->modules[i].SpatialConvolution.weight = THHalfCudaTensor_newFromFloatTensor(net->modules[i].SpatialConvolution.weight);
nn->modules[i].SpatialConvolution.bias = THHalfCudaTensor_newFromFloatTensor(net->modules[i].SpatialConvolution.bias);
} else
#endif
{
nn->modules[i].SpatialConvolution.weight = THCudaTensor_newFromFloatTensor(net->modules[i].SpatialConvolution.weight);
nn->modules[i].SpatialConvolution.bias = THCudaTensor_newFromFloatTensor(net->modules[i].SpatialConvolution.bias);
}
nn->modules[i].SpatialConvolution.finput = 0;
break;
case MT_SpatialMaxPooling:
nn->modules[i].SpatialMaxPooling.indices = THCudaTensor_newFromFloatTensor(net->modules[i].SpatialMaxPooling.indices);
nn->modules[i].updateOutput = cunn_SpatialMaxPooling_updateOutput;
break;
case MT_SpatialMaxUnpooling:
nn->modules[i].updateOutput = cunn_SpatialMaxUnpooling_updateOutput;
break;
case MT_Threshold:
if(nn->modules[i].Threshold.threshold || nn->modules[i].Threshold.val)
THError("Threshold not supported in CUDNN, only ReLU is supported");
nn->modules[i].updateOutput = cudnn_Threshold_updateOutput;
break;
case MT_SoftMax:
nn->modules[i].updateOutput = cudnn_SoftMax_updateOutput;
break;
case MT_Dropout:
if(!nn->modules[i].Dropout.v2)
THError("Non v2 dropout not supported in CUDNN");
nn->modules[i].Dropout.inplace = 1;
break;
case MT_SpatialZeroPadding:
THError("SpatialZeroPadding not supported in CUDNN");
break;
case MT_Linear:
nn->modules[i].type = MT_SpatialConvolutionMM;
nn->modules[i].updateOutput = cudnn_SpatialConvolution_updateOutput;
struct SpatialConvolution *c = &nn->modules[i].SpatialConvolution;
c->finput = 0;
c->padW = c->padH = 0;
c->dW = c->dH = 1;
c->kW = c->kH = 1;
c->nOutputPlane = c->weight->size[0];
c->nInputPlane = c->weight->size[1];
#ifdef HAVEFP16
if(floattype == CUDNN_DATA_HALF)
{
nn->modules[i].SpatialConvolution.weight = THHalfCudaTensor_newFromFloatTensor(net->modules[i].SpatialConvolution.weight);
nn->modules[i].SpatialConvolution.bias = THHalfCudaTensor_newFromFloatTensor(net->modules[i].SpatialConvolution.bias);
} else
#endif
{
nn->modules[i].SpatialConvolution.weight = THCudaTensor_newFromFloatTensor(net->modules[i].SpatialConvolution.weight);
nn->modules[i].SpatialConvolution.bias = THCudaTensor_newFromFloatTensor(net->modules[i].SpatialConvolution.bias);
}
break;
case MT_SpatialBatchNormalization:
nn->modules[i].updateOutput = cudnn_SpatialBatchNormalization_updateOutput;
nn->modules[i].SpatialBatchNormalization.weight = THCudaTensor_newFromFloatTensor(net->modules[i].SpatialBatchNormalization.weight);
nn->modules[i].SpatialBatchNormalization.bias = THCudaTensor_newFromFloatTensor(net->modules[i].SpatialBatchNormalization.bias);
nn->modules[i].SpatialBatchNormalization.running_mean = THCudaTensor_newFromFloatTensor(net->modules[i].SpatialBatchNormalization.running_mean);
nn->modules[i].SpatialBatchNormalization.running_var = THCudaTensor_newFromFloatTensor(net->modules[i].SpatialBatchNormalization.running_var);
break;
case MT_SpatialFullConvolution:
nn->modules[i].updateOutput = cunn_SpatialFullConvolution_updateOutput;
#ifdef HAVEFP16
if(floattype == CUDNN_DATA_HALF)
{
nn->modules[i].SpatialFullConvolution.weight = THHalfCudaTensor_newFromFloatTensor(net->modules[i].SpatialFullConvolution.weight);
nn->modules[i].SpatialFullConvolution.bias = THHalfCudaTensor_newFromFloatTensor(net->modules[i].SpatialFullConvolution.bias);
nn->modules[i].SpatialFullConvolution.columns = THHalfCudaTensor_newFromFloatTensor(net->modules[i].SpatialFullConvolution.columns);
nn->modules[i].SpatialFullConvolution.ones = THHalfCudaTensor_newFromFloatTensor(net->modules[i].SpatialFullConvolution.ones);
} else
#endif
{
nn->modules[i].SpatialFullConvolution.weight = THCudaTensor_newFromFloatTensor(net->modules[i].SpatialFullConvolution.weight);
nn->modules[i].SpatialFullConvolution.bias = THCudaTensor_newFromFloatTensor(net->modules[i].SpatialFullConvolution.bias);
nn->modules[i].SpatialFullConvolution.columns = THCudaTensor_newFromFloatTensor(net->modules[i].SpatialFullConvolution.columns);
nn->modules[i].SpatialFullConvolution.ones = THCudaTensor_newFromFloatTensor(net->modules[i].SpatialFullConvolution.ones);
}
break;
case MT_SpatialAveragePooling:
THError("MT_SpatialAveragePooling not supported in CUDNN");
break;
case MT_Sequential:
THError("MT_Sequential not supported in CUDNN");
break;
case MT_Concat:
THError("MT_Concat not supported in CUDNN");
break;
}
}
return nn;
}
void adjustLd(char transa, char transb, long m, long n, long k, long *lda, long *ldb, long *ldc)
{
int transa_ = ((transa == 't') || (transa == 'T'));
int transb_ = ((transb == 't') || (transb == 'T'));
if(n == 1)
*ldc = m;
if(transa_)
{
if(m == 1)
*lda = k;
}
else
{
if(k == 1)
*lda = m;
}
if(transb_)
{
if(k == 1)
*ldb = n;
}
else
{
if(n == 1)
*ldb = k;
}
}
void THCudaBlas_gemm(char transa, char transb, long m, long n, long k, float alpha, float *a, long lda, float *b, long ldb, float beta, float *c, long ldc)
{
adjustLd(transa, transb, m, n, k, &lda, &ldb, &ldc);
if( (m <= INT_MAX) && (n <= INT_MAX) && (k <= INT_MAX) && (lda <= INT_MAX) && (ldb <= INT_MAX) && (ldc <= INT_MAX) )
{
int i_m = (int)m;
int i_n = (int)n;
int i_k = (int)k;
int i_lda = (int)lda;
int i_ldb = (int)ldb;
int i_ldc = (int)ldc;
#ifdef HAVEFP16
if(floattype == CUDNN_DATA_HALF)
{
__half h_alpha;
__half h_beta;
tofp16((__fp16 *)&h_alpha, &alpha, 1);
tofp16((__fp16 *)&h_beta, &beta, 1);
errcheck(cublasHgemm(THcublas_getHandle(), transa == 't' ? CUBLAS_OP_T : CUBLAS_OP_N,
transb == 't' ? CUBLAS_OP_T : CUBLAS_OP_N,
i_m, i_n, i_k, &h_alpha, (__half *)a, i_lda, (__half *)b, i_ldb, &h_beta, (__half *)c, i_ldc));
} else
#endif
errcheck(cublasSgemm(THcublas_getHandle(), transa == 't' ? CUBLAS_OP_T : CUBLAS_OP_N,
transb == 't' ? CUBLAS_OP_T : CUBLAS_OP_N,
i_m, i_n, i_k, &alpha, a, i_lda, b, i_ldb, &beta, c, i_ldc));
return;
}
THError("Cublas_gemm only supports m, n, k, lda, ldb, ldc with the bound [val] <= %d", INT_MAX);
}
void THCudaTensor_Ones(THFloatTensor *t)
{
int n1 = 0, n2 = 0, stride = 0;
if(t->nDimension == 2)
{
n1 = t->size[0];
n2 = t->size[1];
stride = t->stride[0];
} else if(t->nDimension == 1)
{
n1 = 1;
n2 = t->size[0];
} else THError("Unsupported nDimension for THCudaTensor_Ones");
#ifdef HAVEFP16
if(floattype == CUDNN_DATA_HALF)
cuda_fillwithoneH(n1, n2, THFloatTensor_data(t), stride);
else
#endif
cuda_fillwithone(n1, n2, THFloatTensor_data(t), stride);
}
#ifdef HAVEFP16
THFloatTensor *THHalfCudaTensor_newFromFloatTensor(THFloatTensor *t)
{
THFloatTensor *n = malloc(sizeof(*n));
memcpy(n, t, sizeof(*n));
if(t->storage)
{
n->storage = malloc(sizeof(*n->storage));
n->storage->nref = 1;
n->storage->mustfree = 2;
void *tmp = malloc(THFloatTensor_nElement(t) * 2);
tofp16(tmp, THFloatTensor_data(t), THFloatTensor_nElement(t));
errcheck(cudaMalloc((void **)&n->storage->data, THFloatTensor_nElement(t) * 2));
errcheck(cudaMemcpy(n->storage->data, tmp, THFloatTensor_nElement(t) * 2, cudaMemcpyHostToDevice));
free(tmp);
}
return n;
}
THFloatTensor *THFloatTensor_newFromHalfCudaTensor(THFloatTensor *t)
{
THFloatTensor *n = malloc(sizeof(*n));
memcpy(n, t, sizeof(*n));
if(t->storage)
{
n->storage = malloc(sizeof(*n->storage));
n->storage->nref = 1;
n->storage->mustfree = 1;
void *tmp = malloc(THFloatTensor_nElement(t) * 2);
errcheck(cudaMemcpy(tmp, t->storage->data, THFloatTensor_nElement(t) * 2, cudaMemcpyDeviceToHost));
n->storage->data = malloc(THFloatTensor_nElement(t) * sizeof(*n->storage->data));
fromfp16(n->storage->data, tmp, THFloatTensor_nElement(t));
free(tmp);
}
return n;
}
#endif
|
9733fa1e22edacfeab1589dfe31d414f71d79fd7
|
9ceacf33fd96913cac7ef15492c126d96cae6911
|
/sys/net/pf_osfp.c
|
247d8760001ff89f13b1753b10a5e49f710f4297
|
[
"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
| 16,858
|
c
|
pf_osfp.c
|
/* $OpenBSD: pf_osfp.c,v 1.46 2023/05/07 12:45:21 kn Exp $ */
/*
* Copyright (c) 2003 Mike Frantzen <frantzen@w4g.org>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include <sys/param.h>
#include <sys/socket.h>
#ifdef _KERNEL
#include <sys/systm.h>
#include <sys/pool.h>
#endif /* _KERNEL */
#include <sys/queue.h>
#include <sys/mbuf.h>
#include <sys/syslog.h>
#include <net/if.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>
#ifdef INET6
#include <netinet/ip6.h>
#include <netinet/icmp6.h>
#endif /* INET6 */
#include <net/pfvar.h>
#include <net/pfvar_priv.h>
#ifdef _KERNEL
typedef struct pool pool_t;
#else /* !_KERNEL */
/* Userland equivalents so we can lend code to tcpdump et al. */
#include <arpa/inet.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#define pool_t int
#define pool_get(pool, flags) malloc(*(pool))
#define pool_put(pool, item) free(item)
#define pool_init(pool, size, a, ao, f, m, p) (*(pool)) = (size)
#define PF_LOCK()
#define PF_UNLOCK()
#define PF_ASSERT_LOCKED()
#ifdef PFDEBUG
#include <sys/stdarg.h> /* for DPFPRINTF() */
#endif /* PFDEBUG */
#endif /* _KERNEL */
/*
* Protection/ownership:
* I immutable after pf_osfp_initialize()
* p pf_lock
*/
SLIST_HEAD(pf_osfp_list, pf_os_fingerprint) pf_osfp_list =
SLIST_HEAD_INITIALIZER(pf_osfp_list); /* [p] */
pool_t pf_osfp_entry_pl; /* [I] */
pool_t pf_osfp_pl; /* [I] */
struct pf_os_fingerprint *pf_osfp_find(struct pf_os_fingerprint *,
u_int8_t);
struct pf_os_fingerprint *pf_osfp_find_exact(struct pf_os_fingerprint *);
void pf_osfp_insert(struct pf_os_fingerprint *);
#ifdef _KERNEL
/*
* Passively fingerprint the OS of the host (IPv4 TCP SYN packets only)
* Returns the list of possible OSes.
*/
struct pf_osfp_enlist *
pf_osfp_fingerprint(struct pf_pdesc *pd)
{
struct tcphdr *th = &pd->hdr.tcp;
struct ip *ip = NULL;
struct ip6_hdr *ip6 = NULL;
char hdr[60];
if (pd->proto != IPPROTO_TCP)
return (NULL);
switch (pd->af) {
case AF_INET:
ip = mtod(pd->m, struct ip *);
break;
case AF_INET6:
ip6 = mtod(pd->m, struct ip6_hdr *);
break;
}
if (!pf_pull_hdr(pd->m, pd->off, hdr, th->th_off << 2, NULL, NULL,
pd->af))
return (NULL);
return (pf_osfp_fingerprint_hdr(ip, ip6, (struct tcphdr *)hdr));
}
#endif /* _KERNEL */
struct pf_osfp_enlist *
pf_osfp_fingerprint_hdr(const struct ip *ip, const struct ip6_hdr *ip6,
const struct tcphdr *tcp)
{
struct pf_os_fingerprint fp, *fpresult;
int cnt, optlen = 0;
const u_int8_t *optp;
#ifdef _KERNEL
char srcname[128];
#else /* !_KERNEL */
char srcname[NI_MAXHOST];
#endif /* _KERNEL */
if ((tcp->th_flags & (TH_SYN|TH_ACK)) != TH_SYN)
return (NULL);
if (ip) {
if ((ip->ip_off & htons(IP_OFFMASK)) != 0)
return (NULL);
}
memset(&fp, 0, sizeof(fp));
if (ip) {
#ifndef _KERNEL
struct sockaddr_in sin;
#endif /* _KERNEL */
fp.fp_psize = ntohs(ip->ip_len);
fp.fp_ttl = ip->ip_ttl;
if (ip->ip_off & htons(IP_DF))
fp.fp_flags |= PF_OSFP_DF;
#ifdef _KERNEL
inet_ntop(AF_INET, &ip->ip_src, srcname, sizeof(srcname));
#else /* !_KERNEL */
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_len = sizeof(struct sockaddr_in);
sin.sin_addr = ip->ip_src;
(void)getnameinfo((struct sockaddr *)&sin,
sizeof(struct sockaddr_in), srcname, sizeof(srcname),
NULL, 0, NI_NUMERICHOST);
#endif /* _KERNEL */
}
#ifdef INET6
else if (ip6) {
#ifndef _KERNEL
struct sockaddr_in6 sin6;
#endif /* !_KERNEL */
/* jumbo payload? */
fp.fp_psize = sizeof(struct ip6_hdr) + ntohs(ip6->ip6_plen);
fp.fp_ttl = ip6->ip6_hlim;
fp.fp_flags |= PF_OSFP_DF;
fp.fp_flags |= PF_OSFP_INET6;
#ifdef _KERNEL
inet_ntop(AF_INET6, &ip6->ip6_src, srcname, sizeof(srcname));
#else /* !_KERNEL */
memset(&sin6, 0, sizeof(sin6));
sin6.sin6_family = AF_INET6;
sin6.sin6_len = sizeof(struct sockaddr_in6);
sin6.sin6_addr = ip6->ip6_src;
(void)getnameinfo((struct sockaddr *)&sin6,
sizeof(struct sockaddr_in6), srcname, sizeof(srcname),
NULL, 0, NI_NUMERICHOST);
#endif /* !_KERNEL */
}
#endif /* INET6 */
else
return (NULL);
fp.fp_wsize = ntohs(tcp->th_win);
cnt = (tcp->th_off << 2) - sizeof(*tcp);
optp = (const u_int8_t *)((const char *)tcp + sizeof(*tcp));
for (; cnt > 0; cnt -= optlen, optp += optlen) {
if (*optp == TCPOPT_EOL)
break;
fp.fp_optcnt++;
if (*optp == TCPOPT_NOP) {
fp.fp_tcpopts = (fp.fp_tcpopts << PF_OSFP_TCPOPT_BITS) |
PF_OSFP_TCPOPT_NOP;
optlen = 1;
} else {
if (cnt < 2)
return (NULL);
optlen = optp[1];
if (optlen > cnt || optlen < 2)
return (NULL);
switch (*optp) {
case TCPOPT_MAXSEG:
if (optlen >= TCPOLEN_MAXSEG)
memcpy(&fp.fp_mss, &optp[2],
sizeof(fp.fp_mss));
fp.fp_tcpopts = (fp.fp_tcpopts <<
PF_OSFP_TCPOPT_BITS) | PF_OSFP_TCPOPT_MSS;
fp.fp_mss = ntohs(fp.fp_mss);
break;
case TCPOPT_WINDOW:
if (optlen >= TCPOLEN_WINDOW)
memcpy(&fp.fp_wscale, &optp[2],
sizeof(fp.fp_wscale));
fp.fp_tcpopts = (fp.fp_tcpopts <<
PF_OSFP_TCPOPT_BITS) |
PF_OSFP_TCPOPT_WSCALE;
break;
case TCPOPT_SACK_PERMITTED:
fp.fp_tcpopts = (fp.fp_tcpopts <<
PF_OSFP_TCPOPT_BITS) | PF_OSFP_TCPOPT_SACK;
break;
case TCPOPT_TIMESTAMP:
if (optlen >= TCPOLEN_TIMESTAMP) {
u_int32_t ts;
memcpy(&ts, &optp[2], sizeof(ts));
if (ts == 0)
fp.fp_flags |= PF_OSFP_TS0;
}
fp.fp_tcpopts = (fp.fp_tcpopts <<
PF_OSFP_TCPOPT_BITS) | PF_OSFP_TCPOPT_TS;
break;
default:
return (NULL);
}
}
optlen = MAX(optlen, 1); /* paranoia */
}
DPFPRINTF(LOG_INFO,
"fingerprinted %s:%d %d:%d:%d:%d:%llx (%d) "
"(TS=%s,M=%s%d,W=%s%d)",
srcname, ntohs(tcp->th_sport),
fp.fp_wsize, fp.fp_ttl, (fp.fp_flags & PF_OSFP_DF) != 0,
fp.fp_psize, (long long int)fp.fp_tcpopts, fp.fp_optcnt,
(fp.fp_flags & PF_OSFP_TS0) ? "0" : "",
(fp.fp_flags & PF_OSFP_MSS_MOD) ? "%" :
(fp.fp_flags & PF_OSFP_MSS_DC) ? "*" : "",
fp.fp_mss,
(fp.fp_flags & PF_OSFP_WSCALE_MOD) ? "%" :
(fp.fp_flags & PF_OSFP_WSCALE_DC) ? "*" : "",
fp.fp_wscale);
if ((fpresult = pf_osfp_find(&fp, PF_OSFP_MAXTTL_OFFSET)))
return (&fpresult->fp_oses);
return (NULL);
}
/* Match a fingerprint ID against a list of OSes */
int
pf_osfp_match(struct pf_osfp_enlist *list, pf_osfp_t os)
{
struct pf_osfp_entry *entry;
int os_class, os_version, os_subtype;
int en_class, en_version, en_subtype;
if (os == PF_OSFP_ANY)
return (1);
if (list == NULL) {
DPFPRINTF(LOG_INFO, "osfp no match against %x", os);
return (os == PF_OSFP_UNKNOWN);
}
PF_OSFP_UNPACK(os, os_class, os_version, os_subtype);
SLIST_FOREACH(entry, list, fp_entry) {
PF_OSFP_UNPACK(entry->fp_os, en_class, en_version, en_subtype);
if ((os_class == PF_OSFP_ANY || en_class == os_class) &&
(os_version == PF_OSFP_ANY || en_version == os_version) &&
(os_subtype == PF_OSFP_ANY || en_subtype == os_subtype)) {
DPFPRINTF(LOG_INFO,
"osfp matched %s %s %s %x==%x",
entry->fp_class_nm, entry->fp_version_nm,
entry->fp_subtype_nm, os, entry->fp_os);
return (1);
}
}
DPFPRINTF(LOG_INFO, "fingerprint 0x%x didn't match", os);
return (0);
}
/* Initialize the OS fingerprint system */
void
pf_osfp_initialize(void)
{
pool_init(&pf_osfp_entry_pl, sizeof(struct pf_osfp_entry), 0,
IPL_NONE, PR_WAITOK, "pfosfpen", NULL);
pool_init(&pf_osfp_pl, sizeof(struct pf_os_fingerprint), 0,
IPL_NONE, PR_WAITOK, "pfosfp", NULL);
}
/* Flush the fingerprint list */
void
pf_osfp_flush(void)
{
struct pf_os_fingerprint *fp;
struct pf_osfp_entry *entry;
PF_LOCK();
while ((fp = SLIST_FIRST(&pf_osfp_list))) {
SLIST_REMOVE_HEAD(&pf_osfp_list, fp_next);
while ((entry = SLIST_FIRST(&fp->fp_oses))) {
SLIST_REMOVE_HEAD(&fp->fp_oses, fp_entry);
pool_put(&pf_osfp_entry_pl, entry);
}
pool_put(&pf_osfp_pl, fp);
}
PF_UNLOCK();
}
/* Add a fingerprint */
int
pf_osfp_add(struct pf_osfp_ioctl *fpioc)
{
struct pf_os_fingerprint *fp, *fp_prealloc, fpadd;
struct pf_osfp_entry *entry;
memset(&fpadd, 0, sizeof(fpadd));
fpadd.fp_tcpopts = fpioc->fp_tcpopts;
fpadd.fp_wsize = fpioc->fp_wsize;
fpadd.fp_psize = fpioc->fp_psize;
fpadd.fp_mss = fpioc->fp_mss;
fpadd.fp_flags = fpioc->fp_flags;
fpadd.fp_optcnt = fpioc->fp_optcnt;
fpadd.fp_wscale = fpioc->fp_wscale;
fpadd.fp_ttl = fpioc->fp_ttl;
DPFPRINTF(LOG_DEBUG,
"adding osfp %s %s %s = %s%d:%d:%d:%s%d:0x%llx %d "
"(TS=%s,M=%s%d,W=%s%d) %x",
fpioc->fp_os.fp_class_nm, fpioc->fp_os.fp_version_nm,
fpioc->fp_os.fp_subtype_nm,
(fpadd.fp_flags & PF_OSFP_WSIZE_MOD) ? "%" :
(fpadd.fp_flags & PF_OSFP_WSIZE_MSS) ? "S" :
(fpadd.fp_flags & PF_OSFP_WSIZE_MTU) ? "T" :
(fpadd.fp_flags & PF_OSFP_WSIZE_DC) ? "*" : "",
fpadd.fp_wsize,
fpadd.fp_ttl,
(fpadd.fp_flags & PF_OSFP_DF) ? 1 : 0,
(fpadd.fp_flags & PF_OSFP_PSIZE_MOD) ? "%" :
(fpadd.fp_flags & PF_OSFP_PSIZE_DC) ? "*" : "",
fpadd.fp_psize,
(long long int)fpadd.fp_tcpopts, fpadd.fp_optcnt,
(fpadd.fp_flags & PF_OSFP_TS0) ? "0" : "",
(fpadd.fp_flags & PF_OSFP_MSS_MOD) ? "%" :
(fpadd.fp_flags & PF_OSFP_MSS_DC) ? "*" : "",
fpadd.fp_mss,
(fpadd.fp_flags & PF_OSFP_WSCALE_MOD) ? "%" :
(fpadd.fp_flags & PF_OSFP_WSCALE_DC) ? "*" : "",
fpadd.fp_wscale,
fpioc->fp_os.fp_os);
entry = pool_get(&pf_osfp_entry_pl, PR_WAITOK|PR_LIMITFAIL);
if (entry == NULL)
return (ENOMEM);
fp_prealloc = pool_get(&pf_osfp_pl, PR_WAITOK|PR_ZERO|PR_LIMITFAIL);
if (fp_prealloc == NULL) {
pool_put(&pf_osfp_entry_pl, entry);
return (ENOMEM);
}
PF_LOCK();
if ((fp = pf_osfp_find_exact(&fpadd))) {
struct pf_osfp_entry *tentry;
SLIST_FOREACH(tentry, &fp->fp_oses, fp_entry) {
if (PF_OSFP_ENTRY_EQ(tentry, &fpioc->fp_os)) {
PF_UNLOCK();
pool_put(&pf_osfp_entry_pl, entry);
pool_put(&pf_osfp_pl, fp_prealloc);
return (EEXIST);
}
}
} else {
fp = fp_prealloc;
fp_prealloc = NULL;
fp->fp_tcpopts = fpioc->fp_tcpopts;
fp->fp_wsize = fpioc->fp_wsize;
fp->fp_psize = fpioc->fp_psize;
fp->fp_mss = fpioc->fp_mss;
fp->fp_flags = fpioc->fp_flags;
fp->fp_optcnt = fpioc->fp_optcnt;
fp->fp_wscale = fpioc->fp_wscale;
fp->fp_ttl = fpioc->fp_ttl;
SLIST_INIT(&fp->fp_oses);
pf_osfp_insert(fp);
}
memcpy(entry, &fpioc->fp_os, sizeof(*entry));
/* Make sure the strings are NUL terminated */
entry->fp_class_nm[sizeof(entry->fp_class_nm)-1] = '\0';
entry->fp_version_nm[sizeof(entry->fp_version_nm)-1] = '\0';
entry->fp_subtype_nm[sizeof(entry->fp_subtype_nm)-1] = '\0';
SLIST_INSERT_HEAD(&fp->fp_oses, entry, fp_entry);
PF_UNLOCK();
#ifdef PFDEBUG
if ((fp = pf_osfp_validate()))
DPFPRINTF(LOG_NOTICE,
"Invalid fingerprint list");
#endif /* PFDEBUG */
if (fp_prealloc != NULL)
pool_put(&pf_osfp_pl, fp_prealloc);
return (0);
}
/* Find a fingerprint in the list */
struct pf_os_fingerprint *
pf_osfp_find(struct pf_os_fingerprint *find, u_int8_t ttldiff)
{
struct pf_os_fingerprint *f;
PF_ASSERT_LOCKED();
#define MATCH_INT(_MOD, _DC, _field) \
if ((f->fp_flags & _DC) == 0) { \
if ((f->fp_flags & _MOD) == 0) { \
if (f->_field != find->_field) \
continue; \
} else { \
if (f->_field == 0 || find->_field % f->_field) \
continue; \
} \
}
SLIST_FOREACH(f, &pf_osfp_list, fp_next) {
if (f->fp_tcpopts != find->fp_tcpopts ||
f->fp_optcnt != find->fp_optcnt ||
f->fp_ttl < find->fp_ttl ||
f->fp_ttl - find->fp_ttl > ttldiff ||
(f->fp_flags & (PF_OSFP_DF|PF_OSFP_TS0)) !=
(find->fp_flags & (PF_OSFP_DF|PF_OSFP_TS0)))
continue;
MATCH_INT(PF_OSFP_PSIZE_MOD, PF_OSFP_PSIZE_DC, fp_psize)
MATCH_INT(PF_OSFP_MSS_MOD, PF_OSFP_MSS_DC, fp_mss)
MATCH_INT(PF_OSFP_WSCALE_MOD, PF_OSFP_WSCALE_DC, fp_wscale)
if ((f->fp_flags & PF_OSFP_WSIZE_DC) == 0) {
if (f->fp_flags & PF_OSFP_WSIZE_MSS) {
if (find->fp_mss == 0)
continue;
/* Some "smart" NAT devices and DSL routers will tweak the MSS size and
* will set it to whatever is suitable for the link type.
*/
#define SMART_MSS 1460
if ((find->fp_wsize % find->fp_mss ||
find->fp_wsize / find->fp_mss !=
f->fp_wsize) &&
(find->fp_wsize % SMART_MSS ||
find->fp_wsize / SMART_MSS !=
f->fp_wsize))
continue;
} else if (f->fp_flags & PF_OSFP_WSIZE_MTU) {
if (find->fp_mss == 0)
continue;
#define MTUOFF (sizeof(struct ip) + sizeof(struct tcphdr))
#define SMART_MTU (SMART_MSS + MTUOFF)
if ((find->fp_wsize % (find->fp_mss + MTUOFF) ||
find->fp_wsize / (find->fp_mss + MTUOFF) !=
f->fp_wsize) &&
(find->fp_wsize % SMART_MTU ||
find->fp_wsize / SMART_MTU !=
f->fp_wsize))
continue;
} else if (f->fp_flags & PF_OSFP_WSIZE_MOD) {
if (f->fp_wsize == 0 || find->fp_wsize %
f->fp_wsize)
continue;
} else {
if (f->fp_wsize != find->fp_wsize)
continue;
}
}
return (f);
}
return (NULL);
}
/* Find an exact fingerprint in the list */
struct pf_os_fingerprint *
pf_osfp_find_exact(struct pf_os_fingerprint *find)
{
struct pf_os_fingerprint *f;
PF_ASSERT_LOCKED();
SLIST_FOREACH(f, &pf_osfp_list, fp_next) {
if (f->fp_tcpopts == find->fp_tcpopts &&
f->fp_wsize == find->fp_wsize &&
f->fp_psize == find->fp_psize &&
f->fp_mss == find->fp_mss &&
f->fp_flags == find->fp_flags &&
f->fp_optcnt == find->fp_optcnt &&
f->fp_wscale == find->fp_wscale &&
f->fp_ttl == find->fp_ttl)
return (f);
}
return (NULL);
}
/* Insert a fingerprint into the list */
void
pf_osfp_insert(struct pf_os_fingerprint *ins)
{
struct pf_os_fingerprint *f, *prev = NULL;
PF_ASSERT_LOCKED();
/* XXX need to go semi tree based. can key on tcp options */
SLIST_FOREACH(f, &pf_osfp_list, fp_next)
prev = f;
if (prev)
SLIST_INSERT_AFTER(prev, ins, fp_next);
else
SLIST_INSERT_HEAD(&pf_osfp_list, ins, fp_next);
}
/* Fill a fingerprint by its number (from an ioctl) */
int
pf_osfp_get(struct pf_osfp_ioctl *fpioc)
{
struct pf_os_fingerprint *fp;
struct pf_osfp_entry *entry;
int num = fpioc->fp_getnum;
int i = 0;
memset(fpioc, 0, sizeof(*fpioc));
PF_LOCK();
SLIST_FOREACH(fp, &pf_osfp_list, fp_next) {
SLIST_FOREACH(entry, &fp->fp_oses, fp_entry) {
if (i++ == num) {
fpioc->fp_mss = fp->fp_mss;
fpioc->fp_wsize = fp->fp_wsize;
fpioc->fp_flags = fp->fp_flags;
fpioc->fp_psize = fp->fp_psize;
fpioc->fp_ttl = fp->fp_ttl;
fpioc->fp_wscale = fp->fp_wscale;
fpioc->fp_getnum = num;
memcpy(&fpioc->fp_os, entry,
sizeof(fpioc->fp_os));
PF_UNLOCK();
return (0);
}
}
}
PF_UNLOCK();
return (EBUSY);
}
/* Validate that each signature is reachable */
struct pf_os_fingerprint *
pf_osfp_validate(void)
{
struct pf_os_fingerprint *f, *f2, find;
PF_ASSERT_LOCKED();
SLIST_FOREACH(f, &pf_osfp_list, fp_next) {
memcpy(&find, f, sizeof(find));
/* We do a few MSS/th_win percolations to make things unique */
if (find.fp_mss == 0)
find.fp_mss = 128;
if (f->fp_flags & PF_OSFP_WSIZE_MSS)
find.fp_wsize *= find.fp_mss;
else if (f->fp_flags & PF_OSFP_WSIZE_MTU)
find.fp_wsize *= (find.fp_mss + 40);
else if (f->fp_flags & PF_OSFP_WSIZE_MOD)
find.fp_wsize *= 2;
if (f != (f2 = pf_osfp_find(&find, 0))) {
if (f2)
DPFPRINTF(LOG_NOTICE,
"Found \"%s %s %s\" instead of "
"\"%s %s %s\"\n",
SLIST_FIRST(&f2->fp_oses)->fp_class_nm,
SLIST_FIRST(&f2->fp_oses)->fp_version_nm,
SLIST_FIRST(&f2->fp_oses)->fp_subtype_nm,
SLIST_FIRST(&f->fp_oses)->fp_class_nm,
SLIST_FIRST(&f->fp_oses)->fp_version_nm,
SLIST_FIRST(&f->fp_oses)->fp_subtype_nm);
else
DPFPRINTF(LOG_NOTICE,
"Couldn't find \"%s %s %s\"\n",
SLIST_FIRST(&f->fp_oses)->fp_class_nm,
SLIST_FIRST(&f->fp_oses)->fp_version_nm,
SLIST_FIRST(&f->fp_oses)->fp_subtype_nm);
return (f);
}
}
return (NULL);
}
|
5de8fa299394f0959c93afb9dba070e4ebf9b3ac
|
99bdb3251fecee538e0630f15f6574054dfc1468
|
/bsp/airm2m/air105/libraries/HAL_Driver/Inc/air105.h
|
e0dd1af1c0c749542cc62ea04e50ab7471d43bb8
|
[
"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
| 99,948
|
h
|
air105.h
|
/*
* Copyright (c) 2022 OpenLuat & AirM2M
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef __AIR105_H__
#define __AIR105_H__
#ifdef __cplusplus
extern "C" {
#endif
/* ToDo: replace '<Device>' with your device name; add your doxyGen comment */
/** @addtogroup <Device>_Definitions <Device> Definitions
This file defines all structures and symbols for <Device>:
- registers and bitfields
- peripheral base address
- peripheral ID
- Peripheral definitions
@{
*/
/******************************************************************************/
/* Processor and Core Peripherals */
/******************************************************************************/
/** @addtogroup <Device>_CMSIS Device CMSIS Definitions
Configuration of the Cortex-M# Processor and Core Peripherals
@{
*/
/*
* ==========================================================================
* ---------- Interrupt Number Definition -----------------------------------
* ==========================================================================
*/
typedef enum IRQn
{
/****** Cortex-M# Processor Exceptions Numbers ***************************************************/
/* ToDo: use this Cortex interrupt numbers if your device is a CORTEX-M3 / Cortex-M4 device */
NonMaskableInt_IRQn = -14, /*!< 2 Non Maskable Interrupt */
MemoryManagement_IRQn = -12, /*!< 4 Memory Management Interrupt */
BusFault_IRQn = -11, /*!< 5 Bus Fault Interrupt */
UsageFault_IRQn = -10, /*!< 6 Usage Fault Interrupt */
SVCall_IRQn = -5, /*!< 11 SV Call Interrupt */
DebugMonitor_IRQn = -4, /*!< 12 Debug Monitor Interrupt */
PendSV_IRQn = -2, /*!< 14 Pend SV Interrupt */
SysTick_IRQn = -1, /*!< 15 System Tick Interrupt */
/****** Device Specific Interrupt Numbers ********************************************************/
/* ToDo: add here your device specific external interrupt numbers
according the interrupt handlers defined in startup_Device.s
eg.: Interrupt for Timer#1 TIM1_IRQHandler -> TIM1_IRQn */
DMA_IRQn = 0,
USB_IRQn = 1,
USBDMA_IRQn = 2,
LCD_IRQn = 3,
SCI0_IRQn = 4,
UART0_IRQn = 5,
UART1_IRQn = 6,
SPI0_IRQn = 7,
CRYPT0_IRQn = 8,
TIM0_0_IRQn = 9,
TIM0_1_IRQn = 10,
TIM0_2_IRQn = 11,
TIM0_3_IRQn = 12,
EXTI0_IRQn = 13,
EXTI1_IRQn = 14,
EXTI2_IRQn = 15,
RTC_IRQn = 16,
SENSOR_IRQn = 17,
TRNG_IRQn = 18,
ADC0_IRQn = 19,
SSC_IRQn = 20,
TIM0_4_IRQn = 21,
TIM0_5_IRQn = 22,
KBD_IRQn = 23,
MSR_IRQn = 24,
EXTI3_IRQn = 25,
SPI1_IRQn = 26,
SPI2_IRQn = 27,
SCI2_IRQn = 29,
UART2_IRQn = 32,
UART3_IRQn = 33,
QSPI_IRQn = 35,
I2C0_IRQn = 36,
EXTI4_IRQn = 37,
EXTI5_IRQn = 38,
TIM0_6_IRQn = 39,
TIM0_7_IRQn = 40,
DCMI_IRQn = 42,
QR_IRQn = 46,
GPU_IRQn = 47,
AWD_IRQn = 49,
DAC_IRQn = 50,
SPI5_IRQn = 51
} IRQn_Type;
/*
* ==========================================================================
* ----------- Processor and Core Peripheral Section ------------------------
* ==========================================================================
*/
/* Configuration of the Cortex-M# Processor and Core Peripherals */
/* ToDo: set the defines according your Device */
/* ToDo: define the correct core revision
__CM0_REV if your device is a CORTEX-M0 device
__CM3_REV if your device is a CORTEX-M3 device
__CM4_REV if your device is a CORTEX-M4 device */
//#define __CM3_REV 0x0201 /*!< Core Revision r2p1 */
//#define __CM3_REV 0x0200 /*!< Core Revision r2p0 */
#define __CM4_REV 0x0001 /*!< Core Revision r2p0 */
#define __NVIC_PRIO_BITS 3 /*!< Number of Bits used for Priority Levels */
#define __Vendor_SysTickConfig 0 /*!< Set to 1 if different SysTick Config is used */
#define __MPU_PRESENT 1 /*!< MPU present or not */
/* ToDo: define __FPU_PRESENT if your devise is a CORTEX-M4 */
#define __FPU_PRESENT 1 /*!< FPU present or not */
/*@}*/ /* end of group <Device>_CMSIS */
/* ToDo: include the correct core_cm#.h file
core_cm0.h if your device is a CORTEX-M0 device
core_cm3.h if your device is a CORTEX-M3 device
core_cm4.h if your device is a CORTEX-M4 device */
#include "core_cm4.h" /* Cortex-M# processor and core peripherals */
/* ToDo: include your system_<Device>.h file
replace '<Device>' with your device name */
#include "system_air105.h" /* <Device> System include file */
/******************************************************************************/
/* Device Specific Peripheral registers structures */
/******************************************************************************/
/** @addtogroup <Device>_Peripherals <Device> Peripherals
<Device> Device Specific Peripheral registers structures
@{
*/
#if defined ( __CC_ARM )
#pragma anon_unions
#endif
#include <stdint.h>
/** @addtogroup Exported_types
* @{
*/
typedef enum {RESET = 0, SET = !RESET} FlagStatus, ITStatus;
typedef enum {DISABLE = 0, ENABLE = !DISABLE} FunctionalState;
#define IS_FUNCTIONAL_STATE(STATE) (((STATE) == DISABLE) || ((STATE) == ENABLE))
typedef enum {FALSE = 0, TRUE = !FALSE} Boolean;
typedef enum {ERROR = 0, SUCCESS = !ERROR} ErrorStatus;
/* ToDo: add here your device specific peripheral access structure typedefs
following is an example for a timer */
#define BIT0 (0x00000001U)
#define BIT1 (0x00000002U)
#define BIT2 (0x00000004U)
#define BIT3 (0x00000008U)
#define BIT4 (0x00000010U)
#define BIT5 (0x00000020U)
#define BIT6 (0x00000040U)
#define BIT7 (0x00000080U)
#define BIT8 (0x00000100U)
#define BIT9 (0x00000200U)
#define BIT10 (0x00000400U)
#define BIT11 (0x00000800U)
#define BIT12 (0x00001000U)
#define BIT13 (0x00002000U)
#define BIT14 (0x00004000U)
#define BIT15 (0x00008000U)
#define BIT16 (0x00010000U)
#define BIT17 (0x00020000U)
#define BIT18 (0x00040000U)
#define BIT19 (0x00080000U)
#define BIT20 (0x00100000U)
#define BIT21 (0x00200000U)
#define BIT22 (0x00400000U)
#define BIT23 (0x00800000U)
#define BIT24 (0x01000000U)
#define BIT25 (0x02000000U)
#define BIT26 (0x04000000U)
#define BIT27 (0x08000000U)
#define BIT28 (0x10000000U)
#define BIT29 (0x20000000U)
#define BIT30 (0x40000000U)
#define BIT31 (0x80000000U)
#define BIT(n) (1UL << (n))
typedef struct
{
__IO uint32_t FREQ_SEL;
__IO uint32_t CG_CTRL1;
__IO uint32_t CG_CTRL2;
__O uint32_t SOFT_RST1;
__O uint32_t SOFT_RST2;
__IO uint32_t LOCK_R;
__IO uint32_t PHER_CTRL;
__I uint32_t SYS_RSVD[(0x2C-0x1C) >> 2];
__I uint32_t HCLK_1MS_VAL;
__I uint32_t PCLK_1MS_VAL;
__IO uint32_t ANA_CTRL;
__IO uint32_t DMA_CHAN;
__IO uint32_t SCI0_GLF;
__IO uint32_t SW_RSV1;
__IO uint32_t SW_RSV2;
__IO uint32_t CARD_RSVD;
__IO uint32_t LDO25_CR;
__IO uint32_t DMA_CHAN1;
__I uint32_t SYS_RSVD2[(0x100-0x54) >> 2];
__IO uint32_t MSR_CR1;
__IO uint32_t MSR_CR2;
__IO uint32_t USBPHY_CR1;
__IO uint32_t USBPHY_CR2;
__IO uint32_t USBPHY_CR3;
__IO uint32_t ISO7816_CR;
__IO uint32_t LDO_CR;
__IO uint32_t CHG_CSR;
__I uint32_t SYS_RSVD3[(0x204-0x120) >> 2];
__IO uint32_t RSVD_POR;
__I uint32_t SYS_RSVD4[(0x3EC-0x208) >> 2];
__IO uint32_t PM2_WK_FLAG;
__IO uint32_t CALIB_CSR;
__IO uint32_t DBG_CR;
__IO uint32_t CHIP_ID;
} SYSCTRL_TypeDef;
typedef struct
{
union
{
__I uint32_t RBR;
__O uint32_t THR;
__IO uint32_t DLL;
} OFFSET_0;
union
{
__IO uint32_t DLH;
__IO uint32_t IER;
} OFFSET_4;
union
{
__I uint32_t IIR;
__O uint32_t FCR;
} OFFSET_8;
__IO uint32_t LCR;
__IO uint32_t MCR;
__I uint32_t LSR;
__I uint32_t MSR;
__IO uint32_t SCR;
__IO uint32_t LPDLL;
__IO uint32_t LPDLH;
__I uint32_t RES0[2];
union
{
__I uint32_t SRBR[16];
__O uint32_t STHR[16];
} OFFSET_48;
__IO uint32_t FAR;
__I uint32_t TFR;
__O uint32_t RFW;
__I uint32_t USR;
__I uint32_t TFL;
__I uint32_t RFL;
__O uint32_t SRR;
__IO uint32_t SRTS;
__IO uint32_t SBCR;
__IO uint32_t SDMAM;
__IO uint32_t SFE;
__IO uint32_t SRT;
__IO uint32_t STET;
__IO uint32_t HTX;
__O uint32_t DMASA;
__I uint32_t RES1[18];
__I uint32_t CPR;
__I uint32_t UCV;
__I uint32_t CTR;
} UART_TypeDef;
typedef struct
{
__IO uint16_t CTRLR0;
uint16_t RESERVED0;
__IO uint16_t CTRLR1;
uint16_t RESERVED1;
__IO uint32_t SSIENR;
__IO uint32_t MWCR;
__IO uint32_t SER;
__IO uint32_t BAUDR;
__IO uint32_t TXFTLR;
__IO uint32_t RXFTLR;
__I uint32_t TXFLR;
__I uint32_t RXFLR;
__I uint32_t SR;
__IO uint32_t IMR;
__I uint32_t ISR;
__I uint32_t RISR;
__I uint32_t TXOICR;
__I uint32_t RXOICR;
__I uint32_t RXUICR;
__I uint32_t MSTICR;
__IO uint32_t ICR;
__IO uint32_t DMACR;
__IO uint32_t DMATDLR;
__IO uint32_t DMARDLR;
__I uint32_t IDR;
__I uint32_t SSI_COMP_VERSION;
__IO uint32_t DR;
__IO uint32_t DR_Array[35];
__IO uint32_t RX_SAMPLE_DLY;
} SPI_TypeDef;
typedef struct
{
__IO uint32_t FCU_CMD;
__O uint32_t ADDRES;
__IO uint32_t BYTE_NUM;
__O uint32_t WR_FIFO;
__I uint32_t RD_FIFO;
__IO uint32_t DEVICE_PARA;
__IO uint32_t REG_WDATA;
__O uint32_t REG_RDATA;
__IO uint32_t INT_MASK;
__IO uint32_t INT_UMASK;
__IO uint32_t INT_MASK_STATUS;
__IO uint32_t INT_STATUS;
__IO uint32_t INT_RAWSTATUS;
__IO uint32_t INT_CLEAR;
__IO uint32_t CACHE_INTF_CMD;
__IO uint32_t DMA_CNTL;
__IO uint32_t FIFO_CNTL;
} QSPI_TypeDef;
typedef struct
{
__IO uint32_t CACHE_I0;
__IO uint32_t CACHE_I1;
__IO uint32_t CACHE_I2;
__IO uint32_t CACHE_I3;
__IO uint32_t CACHE_K0;
__IO uint32_t CACHE_K1;
__IO uint32_t CACHE_K2;
__IO uint32_t CACHE_K3;
__IO uint32_t CACHE_CS;
__IO uint32_t CACHE_REF;
__I uint32_t CACHE_RSVD0[(0x40-0x28) >> 2];
__IO uint32_t CACHE_CONFIG;
__I uint32_t CACHE_RSVD1[(0x74-0x44) >> 2];
__IO uint32_t CACHE_SADDR;
__IO uint32_t CACHE_EADDR;
} CACHE_TypeDef;
typedef struct
{
__IO uint32_t CR0; /*!< HSPIM Control register0 */
__IO uint32_t FLCR; /*!< HSPIM Flow Control register */
__IO uint32_t FLSR; /*!< HSPIM Flow Status register */
__IO uint32_t FCR; /*!< HSPIM FIFO Control register */
__I uint32_t RDR; /*!< HSPIM Read Data register */
__O uint32_t WDR; /*!< HSPIM Write Data register */
__I uint32_t SR; /*!< HSPIM Status register */
__IO uint32_t CR1; /*!< HSPIM Control register1 */
__IO uint32_t FSR; /*!< HSPIM FIFO Status register */
__IO uint32_t DCR; /*!< HSPIM DMA Control register */
__I uint32_t TISR; /*!< HSPIM TX Interrput Status register */
__I uint32_t RISR; /*!< HSPIM RX Interrput Status register */
}HSPIM_TypeDef;
typedef struct
{
__IO uint32_t SMU_CTRL;
__IO uint32_t FPM_CTRL;
__O uint32_t INTR_STAT;
__IO uint32_t INTR_CTRL;
__IO uint32_t RESERVED1[12];
__IO uint32_t SMU_OP1;
__IO uint32_t SMU_OP2;
__O uint32_t SMU_RES;
__IO uint32_t RESERVED2[13];
__IO float MATRIX1_00;
__IO float MATRIX1_01;
__IO float MATRIX1_02;
__IO float MATRIX1_10;
__IO float MATRIX1_11;
__IO float MATRIX1_12;
__IO float MATRIX1_20;
__IO float MATRIX1_21;
__IO float MATRIX1_22;
__IO uint32_t RESERVED3[7];
__IO float MATRIX2_00;
__IO float MATRIX2_01;
__IO float MATRIX2_02;
__IO uint32_t RESERVED4[13];
__IO uint32_t TABLE1_LEN;
__IO uint32_t TABLE2_LEN;
__IO uint32_t ACC;
__IO uint32_t POSITION;
__IO uint32_t VAL3;
__IO uint32_t RESERVED5[443];
__IO uint32_t TABLE1_RAM;
__IO uint32_t RESERVED6[255];
__IO uint32_t TABLE2_RAM;
__IO uint32_t RESERVED7[63];
}QRCODE_TypeDef;
typedef struct
{
__IO uint32_t WDT_CR;
__IO uint32_t RESERVED0;
__I uint32_t WDT_CCVR;
__O uint32_t WDT_CRR;
__I uint32_t WDT_STAT;
__I uint32_t WDT_EOI;
__I uint32_t RESERVED1;
__IO uint32_t WDT_RLD;
__I uint32_t RESERVED[53];
__I uint32_t WDT_COMP_PARAMS_1;
__I uint32_t WDT_COMP_VERSION;
__I uint32_t WDT_COMP_TYPE;
} WDT_TypeDef;
typedef struct
{
__IO uint32_t CRC_CSR;
__O uint32_t CRC_INI;
union
{
__I uint32_t DOUT;
__O uint8_t DIN;
} CRC_DATA;
} CRC_TypeDef;
typedef struct
{
__IO uint32_t LoadCount;
__I uint32_t CurrentValue;
__IO uint32_t ControlReg;
__IO uint32_t EOI;
__I uint32_t IntStatus;
} TIM_TypeDef;
#define TIM_NUM 8
typedef struct
{
TIM_TypeDef TIM[TIM_NUM];
__I uint32_t TIM_IntStatus;
__I uint32_t TIM_EOI;
__I uint32_t TIM_RawIntStatus;
__I uint32_t TIM_Comp;
__IO uint32_t TIM_ReloadCount[TIM_NUM];
} TIM_Module_TypeDef;
typedef struct
{
__IO uint32_t ADC_CR1;
__I uint32_t ADC_SR;
__IO uint32_t ADC_FIFO;
__I uint32_t ADC_DATA;
__I uint32_t ADC_FIFO_FL;
__IO uint32_t ADC_FIFO_THR;
__IO uint32_t ADC_CR2;
} ADC_TypeDef;
typedef struct
{
__IO uint32_t DAC_CR1;
__IO uint32_t DAC_DATA;
__IO uint32_t DAC_TIMER;
__I uint32_t DAC_FIFO_FL;
__IO uint32_t DAC_FIFO_THR;
} DAC_TypeDef;
typedef struct
{
__IO uint32_t AWD_CR1;
__IO uint32_t AWD_CR2;
__I uint32_t AWD_SR;
} AWD_TypeDef;
typedef struct
{
__IO uint32_t IODR;
__IO uint32_t BSRR;
__IO uint32_t OEN;
__IO uint32_t PUE;
} GPIO_TypeDef;
typedef struct
{
__IO uint32_t INTP_TYPE;
__IO uint32_t INTP_STA;
} GPIO_INTP_TypeDef;
#define GPIO_GROUP_NUM 6
typedef struct
{
GPIO_TypeDef GPIO[GPIO_GROUP_NUM];
__I uint32_t RSVD0[(0x114 - 0x060)>>2];
__I uint32_t INTP[GPIO_GROUP_NUM];
__I uint32_t RSVD1[(0x180 - 0x12C)>>2];
__IO uint32_t ALT[GPIO_GROUP_NUM];
__I uint32_t RSVD2[(0x200 - 0x198)>>2];
__IO uint32_t SYS_CR1;
__I uint32_t RSVD3[(0x220 - 0x204)>>2];
__IO uint32_t WAKE_TYPE_EN;
__IO uint32_t WAKE_P0_EN;
__IO uint32_t WAKE_P1_EN;
__IO uint32_t WAKE_P2_EN;
__IO uint32_t WAKE_P3_EN;
__I uint32_t RSVD5[(0x800 - 0x234)>>2];
GPIO_INTP_TypeDef INTP_TYPE_STA[GPIO_GROUP_NUM];
} GPIO_MODULE_TypeDef;
typedef struct
{
__IO uint32_t FLAG[(0x0174 - 0x00164) >> 2];
} FLAG_TypeDef;
#define BPK_KEY_NUM 16
typedef struct
{
__IO uint32_t KEY[BPK_KEY_NUM];
__I uint32_t BPK_RSVD0[(0x80-0x40)>>2];
__IO uint32_t BPK_RDY;
__IO uint32_t BPK_CLR;
__IO uint32_t BPK_LRA;
__IO uint32_t BPK_LWA;
__I uint32_t BPK_RSVD1;
__IO uint32_t BPK_LR;
__IO uint32_t BPK_SCR;
__IO uint32_t BPK_POWER;
__IO uint32_t RTC_CS;
__IO uint32_t RTC_REF;
__IO uint32_t RTC_ARM;
__I uint32_t RTC_TIM;
__O uint32_t RTC_INTCLR;
__IO uint32_t OSC32K_CR;
__IO uint32_t RTC_ATTA_TIM;
__IO uint32_t BPK_RR;
__IO uint32_t SEN_EXT_TYPE;
__IO uint32_t SEN_EXT_CFG;
__IO uint32_t SEN_SOFT_EN;
__IO uint32_t SEN_STATE;
__IO uint32_t SEN_BRIDGE;
__IO uint32_t SEN_SOFT_ATTACK;
__IO uint32_t SEN_SOFT_LOCK;
__IO uint32_t SEN_ATTACK_CNT;
__IO uint32_t SEN_ATTACK_TYP;
__IO uint32_t SEN_VG_DETECT;
__IO uint32_t SEN_RNG_INI;
__IO uint32_t RESERVED3[(0x0104 - 0x00EC) >> 2];
__IO uint32_t SEN_EN[19];
__IO uint32_t SEN_EXTS_START;
__IO uint32_t SEN_LOCK;
__IO uint32_t SEN_ANA0;
__IO uint32_t SEN_ANA1;
__IO uint32_t SEN_ATTCLR;
FLAG_TypeDef SEN_FLAG;
__IO uint32_t SEN_DEBUG;
__I uint32_t BPU_RSVD4[(0x200- 0x178) >> 2];
__IO uint32_t BPK_RAM[(0x600-0x200) >> 2];
} BPU_TypeDef;
typedef struct
{
__IO uint32_t KEY[BPK_KEY_NUM];
__I uint32_t BPK_RSVD0[(0x80-0x40) >> 2];
__IO uint32_t BPK_RDY;
__IO uint32_t BPK_CLR;
__IO uint32_t BPK_LRA;
__IO uint32_t BPK_LWA;
__I uint32_t BPK_RSVD1;
__IO uint32_t BPK_LR;
__IO uint32_t BPK_SCR;
__IO uint32_t BPK_POWER;
} BPK_TypeDef;
typedef struct
{
__IO uint32_t RTC_CS;
__IO uint32_t RTC_REF;
__IO uint32_t RTC_ARM;
__I uint32_t RTC_TIM;
__O uint32_t RTC_INTCLR;
__IO uint32_t OSC32K_CR;
__IO uint32_t RTC_ATTA_TIM;
} RTC_TypeDef;
#define EXT_SENSOR_NUM 8
#define INNER_SENSOR_NUM 7
typedef struct
{
__IO uint32_t BPK_RR;
__IO uint32_t SEN_EXT_TYPE;
__IO uint32_t SEN_EXT_CFG;
__IO uint32_t SEN_SOFT_EN;
__IO uint32_t SEN_STATE;
__IO uint32_t SEN_BRIDGE;
__IO uint32_t SEN_SOFT_ATTACK;
__IO uint32_t SEN_SOFT_LOCK;
__IO uint32_t SEN_ATTACK_CNT;
__IO uint32_t SEN_ATTACK_TYP;
__IO uint32_t SEN_VG_DETECT;
__IO uint32_t SEN_RNG_INI;
__IO uint32_t RESERVED3[(0x0104-0x00EC) >> 2];
__IO uint32_t SEN_EN[19];
__IO uint32_t SEN_EXTS_START;
__IO uint32_t SEN_LOCK;
__IO uint32_t SEN_ANA0;
__IO uint32_t SEN_ANA1;
__IO uint32_t SEN_ATTCLR;
FLAG_TypeDef SEN_FLAG;
__IO uint32_t SEN_DEBUG;
__I uint32_t RESERVED4[(0x200- 0x178) >> 2];
__IO uint32_t BPK_RAM[(0x600-0x200) >> 2];
} SEN_TypeDef;
typedef struct
{
__IO uint32_t RNG_CSR;
__IO uint32_t RNG_DATA[1];
__I uint32_t RES;
__IO uint32_t RNG_ANA;
__IO uint32_t RNG_PN;
__IO uint32_t RNG_INDEX;
} TRNG_TypeDef;
typedef struct
{
__IO uint32_t IC_CON;
__IO uint32_t IC_TAR;
__IO uint32_t IC_SAR;
__IO uint32_t IC_HS_MADDR;
__IO uint32_t IC_DATA_CMD;
__IO uint32_t IC_SS_SCL_HCNT;
__IO uint32_t IC_SS_SCL_LCNT;
__IO uint32_t IC_FS_SCL_HCNT;
__IO uint32_t IC_FS_SCL_LCNT;
__IO uint32_t IC_HS_SCL_HCNT;
__IO uint32_t IC_HS_SCL_LCNT;
__I uint32_t IC_INTR_STAT;
__IO uint32_t IC_INTR_MASK;
__I uint32_t IC_RAW_INTR_STAT;
__IO uint32_t IC_RX_TL;
__IO uint32_t IC_TX_TL;
__I uint32_t IC_CLR_INTR;
__I uint32_t IC_CLR_RX_UNDER;
__I uint32_t IC_CLR_RX_OVER;
__I uint32_t IC_CLR_TX_OVER;
__I uint32_t IC_CLR_RD_REQ;
__I uint32_t IC_CLR_TX_ABRT;
__I uint32_t IC_CLR_RX_DONE;
__I uint32_t IC_CLR_ACTIVITY;
__I uint32_t IC_CLR_STOP_DET;
__I uint32_t IC_CLR_START_DET;
__I uint32_t IC_CLR_GEN_CALL;
__IO uint32_t IC_ENABLE;
__I uint32_t IC_STATUS;
__I uint32_t IC_TXFLR;
__I uint32_t IC_RXFLR;
__IO uint32_t IC_SDA_HOLD;
__I uint32_t IC_TX_ABRT_SOURCE;
__IO uint32_t IC_SLV_DATA_NACK_ONLY;
__IO uint32_t IC_DMA_CR;
__IO uint32_t IC_DMA_TDLR;
__IO uint32_t IC_DMA_RDLR;
__IO uint32_t IC_SDA_SETUP;
__IO uint32_t IC_ACK_GENERAL_CALL;
__I uint32_t IC_ENABLE_STATUS;
__IO uint32_t IC_FS_SPKLEN;
__IO uint32_t IC_HS_SPKLEN;
} I2C_TypeDef;
typedef struct
{
__IO uint32_t KCU_CTRL0;
__IO uint32_t KCU_CTRL1;
__I uint32_t KCU_STATUS;
__I uint32_t KCU_EVENT;
__IO uint32_t KCU_RNG;
} KCU_TypeDef;
typedef struct
{
__IO uint32_t SAR_L;
__IO uint32_t SAR_H;
__IO uint32_t DAR_L;
__IO uint32_t DAR_H;
__IO uint32_t LLP_L;
__IO uint32_t LLP_H;
__IO uint32_t CTL_L;
__IO uint32_t CTL_H;
__IO uint32_t SSTAT_L;
__IO uint32_t SSTAT_H;
__IO uint32_t DSTAT_L;
__IO uint32_t DSTAT_H;
__IO uint32_t SSTATAR_L;
__IO uint32_t SSTATAR_H;
__IO uint32_t DSTATAR_L;
__IO uint32_t DSTATAR_H;
__IO uint32_t CFG_L;
__IO uint32_t CFG_H;
__IO uint32_t SGR_L;
__IO uint32_t SGR_H;
__IO uint32_t DSR_L;
__IO uint32_t DSR_H;
} DMA_TypeDef;
typedef struct
{
DMA_TypeDef DMA_Channel[8];
__I uint32_t RawTfr_L;
__I uint32_t RawTfr_H;
__I uint32_t RawBlock_L;
__I uint32_t RawBlock_H;
__I uint32_t RawSrcTran_L;
__I uint32_t RawSrcTran_H;
__I uint32_t RawDstTran_L;
__I uint32_t RawDstTran_H;
__I uint32_t RawErr_L;
__I uint32_t RawErr_H;
__I uint32_t StatusTfr_L;
__I uint32_t StatusTfr_H;
__I uint32_t StatusBlock_L;
__I uint32_t StatusBlock_H;
__I uint32_t StatusSrcTran_L;
__I uint32_t StatusSrcTran_H;
__I uint32_t StatusDstTran_L;
__I uint32_t StatusDstTran_H;
__I uint32_t StatusErr_L;
__I uint32_t StatusErr_H;
__IO uint32_t MaskTfr_L;
__IO uint32_t MaskTfr_H;
__IO uint32_t MaskBlock_L;
__IO uint32_t MaskBlock_H;
__IO uint32_t MaskSrcTran_L;
__IO uint32_t MaskSrcTran_H;
__IO uint32_t MaskDstTran_L;
__IO uint32_t MaskDstTran_H;
__IO uint32_t MaskErr_L;
__IO uint32_t MaskErr_H;
__O uint32_t ClearTfr_L;
__O uint32_t ClearTfr_H;
__O uint32_t ClearBlock_L;
__O uint32_t ClearBlock_H;
__O uint32_t ClearSrcTran_L;
__O uint32_t ClearSrcTran_H;
__O uint32_t ClearDstTran_L;
__O uint32_t ClearDstTran_H;
__O uint32_t ClearErr_L;
__O uint32_t ClearErr_H;
__I uint32_t StatusInt_L;
__I uint32_t StatusInt_H;
__IO uint32_t ReqSrcReg_L;
__IO uint32_t ReqSrcReg_H;
__IO uint32_t ReqDstReg_L;
__IO uint32_t ReqDstReg_H;
__IO uint32_t SglReqSrcReg_L;
__IO uint32_t SglReqSrcReg_H;
__IO uint32_t SglReqDstReg_L;
__IO uint32_t SglReqDstReg_H;
__IO uint32_t LstSrcReg_L;
__IO uint32_t LstSrcReg_H;
__IO uint32_t LstDstReg_L;
__IO uint32_t LstDstReg_H;
__IO uint32_t DmaCfgReg_L;
__IO uint32_t DmaCfgReg_H;
__IO uint32_t ChEnReg_L;
__IO uint32_t ChEnReg_H;
__I uint32_t DmaIdReg_L;
__I uint32_t DmaIdReg_H;
__IO uint32_t DmaTestReg_L;
__IO uint32_t DmaTestReg_H;
__IO uint32_t RESERVED2[4];
__I uint32_t DMA_COMP_PARAMS_6_L;
__I uint32_t DMA_COMP_PARAMS_6_H;
__I uint32_t DMA_COMP_PARAMS_5_L;
__I uint32_t DMA_COMP_PARAMS_5_H;
__I uint32_t DMA_COMP_PARAMS_4_L;
__I uint32_t DMA_COMP_PARAMS_4_H;
__I uint32_t DMA_COMP_PARAMS_3_L;
__I uint32_t DMA_COMP_PARAMS_3_H;
__I uint32_t DMA_COMP_PARAMS_2_L;
__I uint32_t DMA_COMP_PARAMS_2_H;
__I uint32_t DMA_COMP_PARAMS_1_L;
__I uint32_t DMA_COMP_PARAMS_1_H;
__I uint32_t DMA_Component_ID_Register_L;
__I uint32_t DMA_Component_ID_Register_H;
} DMA_MODULE_TypeDef;
typedef struct
{
__IO uint32_t lcdi_ctrl;
__IO uint32_t lcdi_cycle;
__IO uint32_t lcdi_status;
__IO uint32_t lcdi_data;
__IO uint32_t lcdi_fifolevel;
__IO uint32_t lcdi_fifothr;
} LCD_TypeDef;
typedef struct
{
__IO uint32_t SCI_DATA;
__IO uint32_t SCI_CR0;
__IO uint32_t SCI_CR1;
__IO uint32_t SCI_CR2;
__IO uint32_t SCI_IER;
__IO uint32_t SCI_RETRY;
__IO uint32_t SCI_TIDE;
__IO uint32_t SCI_TXCOUNT;
__IO uint32_t SCI_RXCOUNT;
__I uint32_t SCI_FR;
__IO uint32_t SCI_RXTIME;
__IO uint32_t SCI_ISTAT;
__IO uint32_t SCI_STABLE;
__IO uint32_t SCI_ATIME;
__IO uint32_t SCI_DTIME;
__IO uint32_t SCI_ATRSTIME;
__IO uint32_t SCI_ATRDTIME;
__IO uint32_t SCI_BLKTIME;
__IO uint32_t SCI_CHTIME;
__IO uint32_t SCI_CLKICC;
__IO uint32_t SCI_BAUD;
__IO uint32_t SCI_VALUE;
__IO uint32_t SCI_CHGUARD;
__IO uint32_t SCI_BLKGUARD;
__IO uint32_t SCI_SYNCCR;
__IO uint32_t SCI_SYNCDATA;
__IO uint32_t SCI_RAWSTAT;
__IO uint32_t SCI_IIR;
__I uint32_t SCI_RES1[4];
__I uint32_t SCI_RES2[32];
} SCI_TypeDef;
/**
* @brief DCMI&IMG COP
*/
typedef struct
{
__IO uint32_t CR; /*!< DCMI control register 1, Address offset: 0x00 */
__IO uint32_t SR; /*!< DCMI status register, Address offset: 0x04 */
__IO uint32_t RISR; /*!< DCMI raw interrupt status register, Address offset: 0x08 */
__IO uint32_t IER; /*!< DCMI interrupt enable register, Address offset: 0x0C */
__IO uint32_t MISR; /*!< DCMI masked interrupt status register, Address offset: 0x10 */
__IO uint32_t ICR; /*!< DCMI interrupt clear register, Address offset: 0x14 */
__IO uint32_t RESERVED1[2];
__IO uint32_t CWSTRTR; /*!< DCMI crop window start, Address offset: 0x20 */
__IO uint32_t CWSIZER; /*!< DCMI crop window size, Address offset: 0x24 */
__IO uint32_t DR; /*!< DCMI data register, Address offset: 0x28 */
} DCMI_TypeDef;
typedef struct
{
__IO uint32_t RESERVED[(0x2000-0x0000)/4];
__IO uint32_t CFG;
__IO uint32_t CS;
__IO uint32_t PROT;
__IO uint32_t ADDR;
__IO uint32_t PDATA;
__IO uint32_t RO;
__IO uint32_t ROL;
__IO uint32_t RSVD;
__IO uint32_t TIM;
__IO uint32_t TIM_EN;
} OTP_TypeDef;
typedef struct
{
__IO uint32_t RESERVED0[(0x0008-0x0000) >> 2];
__IO uint32_t SSC_CR3;
__O uint32_t RESERVED1[(0x0104-0x000C) >> 2];
__IO uint32_t SSC_SR;
__IO uint32_t SSC_SR_CLR;
__IO uint32_t SSC_ACK;
__O uint32_t RESERVED2[(0x0184-0x0110) >> 2];
__IO uint32_t DATARAM_SCR;
__O uint32_t RESERVED3[(0x01FC-0x0188) >> 2];
__IO uint32_t BPU_RWC;
__O uint32_t RESERVED4[(0x03EC-0x0200) >> 2];
__IO uint32_t MAIN_SEN_LOCK;
__IO uint32_t MAIN_SEN_EN;
} SSC_TypeDef;
typedef struct
{
__IO uint32_t TST_JTAG;
__IO uint32_t TST_ROM;
__IO uint32_t TST_FLASH;
} MH_SMCU_TST_TypeDef;
#if defined ( __CC_ARM )
#pragma no_anon_unions
#endif
/*@}*/ /* end of group <Device>_Peripherals */
/******************************************************************************/
/* Peripheral memory map */
/******************************************************************************/
/* ToDo: add here your device peripherals base addresses
following is an example for timer */
/** @addtogroup <Device>_MemoryMap <Device> Memory Mapping
@{
*/
/* Peripheral and SRAM base address */
#define AIR105_FLASH_BASE (0x01000000UL) /*!< (FLASH ) Base Address */
#define AIR105_SRAM_BASE (0x20000000UL) /*!< (SRAM ) Base Address */
#define AIR105_PERIPH_BASE (0x40000000UL) /*!< (Peripheral) Base Address */
#define AIR105_SRAM_SIZE (0xA0000)
#define AIR105_OTP_BASE (0x40008000UL)
#define AIR105_OTP_SIZE (1UL << 13)
/* Peripheral memory map */
#define AIR105_AHB_BASE (AIR105_PERIPH_BASE)
#define AIR105_APB0_BASE (AIR105_PERIPH_BASE + 0x10000)
#define AIR105_APB1_BASE (AIR105_PERIPH_BASE + 0x20000)
#define AIR105_APB2_BASE (AIR105_PERIPH_BASE + 0x30000)
#define AIR105_APB3_BASE (AIR105_PERIPH_BASE + 0x40000)
#define SSC_BASE (AIR105_AHB_BASE + 0x0000)
#define TST_BASE (AIR105_AHB_BASE + 0x03F4)
#define DMA_BASE (AIR105_AHB_BASE + 0x0800)
#define USB_BASE (AIR105_AHB_BASE + 0x0C00)
#define LCD_BASE (AIR105_AHB_BASE + 0x1000)
#define OTP_BASE (AIR105_AHB_BASE + 0x8000)
#define DCMI_BASE (AIR105_AHB_BASE + 0x60000)
#define CACHE_BASE (AIR105_AHB_BASE + 0x80000)
#define QRCODE_BASE (AIR105_AHB_BASE + 0x90000)
#define GPU_BASE (AIR105_AHB_BASE + 0xA1000)
#define QSPI_BASE (AIR105_AHB_BASE + 0xA2000)
#define HSPI_BASE (AIR105_AHB_BASE + 0xA3000)
#define SCI0_BASE (AIR105_APB0_BASE)
#define CRC_BASE (AIR105_APB0_BASE + 0x2000)
#define TIMM0_BASE (AIR105_APB0_BASE + 0x3000)
#define ADC_BASE (AIR105_APB0_BASE + 0x4000)
#define DAC_BASE (AIR105_APB0_BASE + 0x4100)
#define AWD_BASE (AIR105_APB0_BASE + 0x4200)
#define SCI2_BASE (AIR105_APB0_BASE + 0x5000)
#define UART0_BASE (AIR105_APB0_BASE + 0x6000)
#define UART1_BASE (AIR105_APB0_BASE + 0x7000)
#define SPIM1_BASE (AIR105_APB0_BASE + 0x8000)
#define SPIM2_BASE (AIR105_APB0_BASE + 0x9000)
#define SPIM0_BASE (AIR105_APB0_BASE + 0xA000)
#define SPIS0_BASE (AIR105_APB0_BASE + 0xB000)
#define WDG_BASE (AIR105_APB0_BASE + 0xC000)
#define GPIO_BASE (AIR105_APB0_BASE + 0xD000)
#define TRNG_BASE (AIR105_APB0_BASE + 0xE000)
#define SYSCTRL_BASE (AIR105_APB0_BASE + 0xF000)
#define MSR_BASE (AIR105_APB1_BASE)
#define BPU_BASE (AIR105_APB2_BASE)
#define UART2_BASE (AIR105_APB3_BASE + 0x4000)
#define UART3_BASE (AIR105_APB3_BASE + 0x5000)
#define KEYBOARD_BASE (AIR105_APB3_BASE + 0x8000)
#define I2C0_BASE (AIR105_APB3_BASE + 0x9000)
#define HSPIM_BASE (AIR105_AHB_BASE + 0xA3020)
/*@}*/ /* end of group <Device>_MemoryMap */
/******************************************************************************/
/* Peripheral declaration */
/******************************************************************************/
/* ToDo: add here your device peripherals pointer definitions
following is an example for timer */
/** @addtogroup <Device>_PeripheralDecl <Device> Peripheral Declaration
@{
*/
#define SYSCTRL ((SYSCTRL_TypeDef *) SYSCTRL_BASE)
#define UART0 ((UART_TypeDef *) UART0_BASE)
#define UART1 ((UART_TypeDef *) UART1_BASE)
#define UART2 ((UART_TypeDef *) UART2_BASE)
#define UART3 ((UART_TypeDef *) UART3_BASE)
#define SPIM0 ((SPI_TypeDef *) SPIM0_BASE)
#define SPIM1 ((SPI_TypeDef *) SPIM1_BASE)
#define SPIM2 ((SPI_TypeDef *) SPIM2_BASE)
#define SPIS0 ((SPI_TypeDef *) SPIS0_BASE)
#define QSPI ((QSPI_TypeDef *) QSPI_BASE)
#define HSPIM ((HSPIM_TypeDef *) HSPIM_BASE)
#define CACHE ((CACHE_TypeDef *)CACHE_BASE)
#define QRCODE ((QRCODE_TypeDef *)QRCODE_BASE)
#define GPU ((GPU_TypeDef *)GPU_BASE)
#define SCI0 ((SCI_TypeDef *) SCI0_BASE)
#define SCI2 ((SCI_TypeDef *) SCI2_BASE)
#define TIMM0 ((TIM_Module_TypeDef *)TIMM0_BASE)
#define ADC0 ((ADC_TypeDef *)ADC_BASE)
#define DAC ((DAC_TypeDef *)DAC_BASE)
#define AWD ((AWD_TypeDef *)AWD_BASE)
#define TRNG ((TRNG_TypeDef *)TRNG_BASE)
#define LCD ((LCD_TypeDef *)LCD_BASE)
#define KCU ((KCU_TypeDef *)KEYBOARD_BASE)
#define CRC ((CRC_TypeDef *)CRC_BASE)
#define OTP ((OTP_TypeDef *)OTP_BASE)
#define I2C0 ((I2C_TypeDef *)I2C0_BASE)
#define DMA ((DMA_MODULE_TypeDef *)DMA_BASE)
#define DMA_Channel_0 ((DMA_TypeDef *)DMA_BASE)
#define DMA_Channel_1 ((DMA_TypeDef *)(DMA_BASE + 0x58))
#define DMA_Channel_2 ((DMA_TypeDef *)(DMA_BASE + 0x58*2))
#define DMA_Channel_3 ((DMA_TypeDef *)(DMA_BASE + 0x58*3))
#define DMA_Channel_4 ((DMA_TypeDef *)(DMA_BASE + 0x58*4))
#define DMA_Channel_5 ((DMA_TypeDef *)(DMA_BASE + 0x58*5))
#define DMA_Channel_6 ((DMA_TypeDef *)(DMA_BASE + 0x58*6))
#define DMA_Channel_7 ((DMA_TypeDef *)(DMA_BASE + 0x58*7))
#define GPIO ((GPIO_MODULE_TypeDef *)GPIO_BASE)
#define GPIOA ((GPIO_TypeDef *)GPIO_BASE)
#define GPIOB ((GPIO_TypeDef *)(GPIO_BASE + 0x0010))
#define GPIOC ((GPIO_TypeDef *)(GPIO_BASE + 0x0020))
#define GPIOD ((GPIO_TypeDef *)(GPIO_BASE + 0x0030))
#define GPIOE ((GPIO_TypeDef *)(GPIO_BASE + 0x0040))
#define GPIOF ((GPIO_TypeDef *)(GPIO_BASE + 0x0050))
#define GPIO_GROUP ((GPIO_TypeDef *)GPIO_BASE)
#define GPIO_ALT_GROUP ((__IO uint32_t *)(GPIO_BASE + 0x180))
#define GPIO_WKEN_TYPE_EN ((__IO uint32_t *)(GPIO_BASE + 0x220))
#define GPIO_WKEN_P0_EN ((__IO uint32_t *)(GPIO_BASE + 0x224))
#define GPIO_WKEN_P1_EN ((__IO uint32_t *)(GPIO_BASE + 0x228))
#define GPIO_WKEN_P2_EN ((__IO uint32_t *)(GPIO_BASE + 0x22C))
#define WDT ((WDT_TypeDef *)WDG_BASE)
#define SSC ((SSC_TypeDef *)SSC_BASE)
#define TST ((MH_SMCU_TST_TypeDef *)TST_BASE)
#define DCMI ((DCMI_TypeDef *)DCMI_BASE)
#define BPU ((BPU_TypeDef *)BPU_BASE)
#define BPK ((BPK_TypeDef *)BPU_BASE)
#define RTC ((RTC_TypeDef *)(BPU_BASE + 0xA0))
#define SENSOR ((SEN_TypeDef *)(BPU_BASE + 0xBC))
#define SEN_FLAG ((FLAG_TypeDef*)(BPU_BASE + 0x164))
/** @addtogroup Exported_constants
* @{
*/
/** @addtogroup Peripheral_Registers_Bits_Definition
* @{
*/
/******************************************************************************/
/* Peripheral Registers_Bits_Definition */
/******************************************************************************/
/******************************************************************************/
/* */
/* System Control Unit */
/* */
/******************************************************************************/
/******************* Bit definition for FREQ_SEL register *******************/
#define SYSCTRL_FREQ_SEL_XTAL_Pos (16)
#define SYSCTRL_FREQ_SEL_XTAL_Mask (0x1F << SYSCTRL_FREQ_SEL_XTAL_Pos)
#define SYSCTRL_FREQ_SEL_XTAL_108Mhz (0x08 << SYSCTRL_FREQ_SEL_XTAL_Pos)
#define SYSCTRL_FREQ_SEL_XTAL_120Mhz (0x09 << SYSCTRL_FREQ_SEL_XTAL_Pos)
#define SYSCTRL_FREQ_SEL_XTAL_132Mhz (0x0a << SYSCTRL_FREQ_SEL_XTAL_Pos)
#define SYSCTRL_FREQ_SEL_XTAL_144Mhz (0x0b << SYSCTRL_FREQ_SEL_XTAL_Pos)
#define SYSCTRL_FREQ_SEL_XTAL_156Mhz (0x0c << SYSCTRL_FREQ_SEL_XTAL_Pos)
#define SYSCTRL_FREQ_SEL_XTAL_168Mhz (0x0d << SYSCTRL_FREQ_SEL_XTAL_Pos)
#define SYSCTRL_FREQ_SEL_XTAL_180Mhz (0x0e << SYSCTRL_FREQ_SEL_XTAL_Pos)
#define SYSCTRL_FREQ_SEL_XTAL_192Mhz (0x0f << SYSCTRL_FREQ_SEL_XTAL_Pos)
#define SYSCTRL_FREQ_SEL_XTAL_204Mhz (0x10 << SYSCTRL_FREQ_SEL_XTAL_Pos)
#define SYSCTRL_FREQ_SEL_CLOCK_SOURCE_Pos (12)
#define SYSCTRL_FREQ_SEL_CLOCK_SOURCE_Mask (0x01 << SYSCTRL_FREQ_SEL_CLOCK_SOURCE_Pos)
#define SYSCTRL_FREQ_SEL_CLOCK_SOURCE_EXT (0x00 << SYSCTRL_FREQ_SEL_CLOCK_SOURCE_Pos)
#define SYSCTRL_FREQ_SEL_CLOCK_SOURCE_INC (0x01 << SYSCTRL_FREQ_SEL_CLOCK_SOURCE_Pos)
#define SYSCTRL_FREQ_SEL_PLL_DIV_Pos (8)
#define SYSCTRL_FREQ_SEL_PLL_DIV_Mask (0x03 << SYSCTRL_FREQ_SEL_PLL_DIV_Pos)
#define SYSCTRL_FREQ_SEL_PLL_DIV_1_0 (0x00 << SYSCTRL_FREQ_SEL_PLL_DIV_Pos)
#define SYSCTRL_FREQ_SEL_PLL_DIV_1_2 (0x01 << SYSCTRL_FREQ_SEL_PLL_DIV_Pos)
#define SYSCTRL_FREQ_SEL_PLL_DIV_1_4 (0x02 << SYSCTRL_FREQ_SEL_PLL_DIV_Pos)
#define SYSCTRL_FREQ_SEL_HCLK_DIV_Pos (4)
#define SYSCTRL_FREQ_SEL_HCLK_DIV_Mask (0x01 << SYSCTRL_FREQ_SEL_HCLK_DIV_Pos)
#define SYSCTRL_FREQ_SEL_HCLK_DIV_1_0 (0x00 << SYSCTRL_FREQ_SEL_HCLK_DIV_Pos)
#define SYSCTRL_FREQ_SEL_HCLK_DIV_1_2 (0x01 << SYSCTRL_FREQ_SEL_HCLK_DIV_Pos)
#define SYSCTRL_FREQ_SEL_PCLK_DIV_Pos (0)
#define SYSCTRL_FREQ_SEL_PCLK_DIV_Mask (0x01 << SYSCTRL_FREQ_SEL_PCLK_DIV_Pos)
#define SYSCTRL_FREQ_SEL_PCLK_DIV_1_2 (0x00 << SYSCTRL_FREQ_SEL_PCLK_DIV_Pos)
#define SYSCTRL_FREQ_SEL_PCLK_DIV_1_4 (0x01 << SYSCTRL_FREQ_SEL_PCLK_DIV_Pos)
/******************* Bit definition for CG_CTRL2 register *******************/
#define SYSCTRL_AHBPeriph_DMA ((uint32_t)0x20000000)
#define SYSCTRL_AHBPeriph_USB ((uint32_t)0x10000000)
#define SYSCTRL_AHBPeriph_QR ((uint32_t)0x00000020)
#define SYSCTRL_AHBPeriph_OTP ((uint32_t)0x00000008)
#define SYSCTRL_AHBPeriph_GPU ((uint32_t)0x00000004)
#define SYSCTRL_AHBPeriph_LCD ((uint32_t)0x00000002)
#define SYSCTRL_AHBPeriph_CRYPT ((uint32_t)0x00000001)
#define SYSCTRL_AHBPeriph_ALL ((uint32_t)0x3000002F)
#define IS_SYSCTRL_AHB_PERIPH(PERIPH) ((((PERIPH) & ~SYSCTRL_AHBPeriph_ALL) == 0x00) && ((PERIPH) != 0x00))
/******************* Bit definition for CG_CTRL1 register *******************/
#define SYSCTRL_APBPeriph_TRNG ((uint32_t)0x80000000)
#define SYSCTRL_APBPeriph_ADC ((uint32_t)0x40000000)
#define SYSCTRL_APBPeriph_CRC ((uint32_t)0x20000000)
#define SYSCTRL_APBPeriph_KBD ((uint32_t)0x08000000)
#define SYSCTRL_APBPeriph_BPU ((uint32_t)0x04000000)
#define SYSCTRL_APBPeriph_DCMIS ((uint32_t)0x00800000)
#define SYSCTRL_APBPeriph_TIMM0 ((uint32_t)0x00200000)
#define SYSCTRL_APBPeriph_GPIO ((uint32_t)0x00100000)
#define SYSCTRL_APBPeriph_I2C0 ((uint32_t)0x00040000)
#define SYSCTRL_APBPeriph_SCI2 ((uint32_t)0x00010000)
#define SYSCTRL_APBPeriph_SCI0 ((uint32_t)0x00004000)
#define SYSCTRL_APBPeriph_HSPI ((uint32_t)0x00002000)
#define SYSCTRL_APBPeriph_SPI2 ((uint32_t)0x00000400)
#define SYSCTRL_APBPeriph_SPI1 ((uint32_t)0x00000200)
#define SYSCTRL_APBPeriph_SPI0 ((uint32_t)0x00000100)
#define SYSCTRL_APBPeriph_UART3 ((uint32_t)0x00000008)
#define SYSCTRL_APBPeriph_UART2 ((uint32_t)0x00000004)
#define SYSCTRL_APBPeriph_UART1 ((uint32_t)0x00000002)
#define SYSCTRL_APBPeriph_UART0 ((uint32_t)0x00000001)
#define SYSCTRL_APBPeriph_ALL ((uint32_t)0xECB5670F)
#define IS_SYSCTRL_APB_PERIPH(PERIPH) ((((PERIPH) & ~SYSCTRL_APBPeriph_ALL) == 0x00) && ((PERIPH) != 0x00))
/******************* Bit definition for SOFT_RST2 register *******************/
#define SYSCTRL_GLB_RESET ((uint32_t)0x80000000)
#define SYSCTRL_CM3_RESET ((uint32_t)0x40000000)
#define SYSCTRL_DMA_RESET ((uint32_t)0x20000000)
#define SYSCTRL_USB_RESET ((uint32_t)0x10000000)
#define SYSCTRL_QR_RESET ((uint32_t)0x00000020)
#define SYSCTRL_OTP_RESET ((uint32_t)0x00000008)
#define SYSCTRL_GPU_RESET ((uint32_t)0x00000004)
#define SYSCTRL_LCD_RESET ((uint32_t)0x00000002)
#define SYSCTRL_CRYPT_RESET ((uint32_t)0x00000001)
#define SYSCTRL_AHBPeriph_RESET_ALL ((uint32_t)0xF000002F)
#define IS_SYSCTRL_AHB_PERIPH_RESET(PERIPH) ((((PERIPH) & ~SYSCTRL_AHBPeriph_RESET_ALL) == 0x00) && ((PERIPH) != 0x00))
/******************* Bit definition for PHER_CTRL register *******************/
#define SYSCTRL_PHER_CTRL_SPI0_SLV_EN ((uint32_t)0x01000000) /* 0:MASTER 1:SLAVE */
#define SYSCTRL_PHER_CTRL_SCI2_VCCEN_INV ((uint32_t)0x00400000)
#define SYSCTRL_PHER_CTRL_SCI0_VCCEN_INV ((uint32_t)0x00100000)
#define SYSCTRL_PHER_CTRL_SCI2_CDET_INV ((uint32_t)0x00040000)
#define SYSCTRL_PHER_CTRL_SCI0_CDET_INV ((uint32_t)0x00010000)
/******************* Bit definition for DMA_CHAN REGISTER ********************/
#define SYSCTRL_PHER_CTRL_DMA_CH0_IF_Pos (0)
#define SYSCTRL_PHER_CTRL_DMA_CH0_IF_Mask (0x3FU<<SYSCTRL_PHER_CTRL_DMA_CH0_IF_Pos)
#define SYSCTRL_PHER_CTRL_DMA_CH1_IF_Pos (8)
#define SYSCTRL_PHER_CTRL_DMA_CH1_IF_Mask (0x3FU<<SYSCTRL_PHER_CTRL_DMA_CH1_IF_Pos)
#define SYSCTRL_PHER_CTRL_DMA_CH2_IF_Pos (16)
#define SYSCTRL_PHER_CTRL_DMA_CH2_IF_Mask (0x3FU<<SYSCTRL_PHER_CTRL_DMA_CH2_IF_Pos)
#define SYSCTRL_PHER_CTRL_DMA_CH3_IF_Pos (24)
#define SYSCTRL_PHER_CTRL_DMA_CH3_IF_Mask (0x3FU<<SYSCTRL_PHER_CTRL_DMA_CH3_IF_Pos)
#define SYSCTRL_PHER_CTRL_DMA_CH4_IF_Pos (0)
#define SYSCTRL_PHER_CTRL_DMA_CH4_IF_Mask (0x3FU<<SYSCTRL_PHER_CTRL_DMA_CH4_IF_Pos)
#define SYSCTRL_PHER_CTRL_DMA_CH5_IF_Pos (8)
#define SYSCTRL_PHER_CTRL_DMA_CH5_IF_Mask (0x3FU<<SYSCTRL_PHER_CTRL_DMA_CH5_IF_Pos)
#define SYSCTRL_PHER_CTRL_DMA_CH6_IF_Pos (16)
#define SYSCTRL_PHER_CTRL_DMA_CH6_IF_Mask (0x3FU<<SYSCTRL_PHER_CTRL_DMA_CH6_IF_Pos)
#define SYSCTRL_PHER_CTRL_DMA_CH7_IF_Pos (24)
#define SYSCTRL_PHER_CTRL_DMA_CH7_IF_Mask (0x3FU<<SYSCTRL_PHER_CTRL_DMA_CH7_IF_Pos)
#define SYSCTRL_PHER_CTRL_DMA_CHx_IF_DCMI_TX (0x00)
#define SYSCTRL_PHER_CTRL_DMA_CHx_IF_LCD (0x01)
#define SYSCTRL_PHER_CTRL_DMA_CHx_IF_UART0_TX (0x02)
#define SYSCTRL_PHER_CTRL_DMA_CHx_IF_UART0_RX (0x03)
#define SYSCTRL_PHER_CTRL_DMA_CHx_IF_UART1_TX (0x04)
#define SYSCTRL_PHER_CTRL_DMA_CHx_IF_UART1_RX (0x05)
#define SYSCTRL_PHER_CTRL_DMA_CHx_IF_DAC (0x06)
#define SYSCTRL_PHER_CTRL_DMA_CHx_IF_SPI0_TX (0x0A)
#define SYSCTRL_PHER_CTRL_DMA_CHx_IF_SPI0_RX (0x0B)
#define SYSCTRL_PHER_CTRL_DMA_CHx_IF_SPI1_TX (0x0C)
#define SYSCTRL_PHER_CTRL_DMA_CHx_IF_SPI1_RX (0x0D)
#define SYSCTRL_PHER_CTRL_DMA_CHx_IF_SPI2_TX (0x0E)
#define SYSCTRL_PHER_CTRL_DMA_CHx_IF_SPI2_RX (0x0F)
#define SYSCTRL_PHER_CTRL_DMA_CHx_IF_UART2_TX (0x14)
#define SYSCTRL_PHER_CTRL_DMA_CHx_IF_UART2_RX (0x15)
#define SYSCTRL_PHER_CTRL_DMA_CHx_IF_UART3_TX (0x16)
#define SYSCTRL_PHER_CTRL_DMA_CHx_IF_UART3_RX (0x17)
#define SYSCTRL_PHER_CTRL_DMA_CHx_IF_I2C_TX (0x18)
#define SYSCTRL_PHER_CTRL_DMA_CHx_IF_I2C_RX (0x19)
#define SYSCTRL_PHER_CTRL_DMA_CHx_IF_QSPI_TX (0x1A)
#define SYSCTRL_PHER_CTRL_DMA_CHx_IF_HSPI_RX (0x20)
#define SYSCTRL_PHER_CTRL_DMA_CHx_IF_HSPI_TX (0x21)
/******************************************************************************/
/* */
/* Universal Asynchronous Receiver Transmitter */
/* */
/******************************************************************************/
/******************* Bit definition for UART_RBR register *******************/
#define UART_RBR_RBR ((uint32_t)0x01FF) /*!< Data value */
/******************* Bit definition for UART_THR register *******************/
#define UART_THR_THR ((uint32_t)0x01FF) /*!< Data value */
/******************* Bit definition for UART_DLH register *******************/
#define UART_DLH_DLH ((uint32_t)0x0FF)
/******************* Bit definition for UART_DLL register *******************/
#define UART_DLL_DLL ((uint32_t)0x0FF)
/******************* Bit definition for UART_IER register *******************/
#define UART_IER_ERBFI ((uint32_t)0x0001)
#define UART_IER_ETBEI ((uint32_t)0x0002)
#define UART_IER_ELSI ((uint32_t)0x0004)
#define UART_IER_EDSSI ((uint32_t)0x0008)
#define UART_IER_PTIME ((uint32_t)0x0080)
/******************* Bit definition for UART_IIR register *******************/
#define UART_IIR_IID ((uint32_t)0x0007)
#define UART_IIR_IID_0 ((uint32_t)0x0001)
#define UART_IIR_IID_1 ((uint32_t)0x0002)
#define UART_IIR_IID_2 ((uint32_t)0x0004)
#define UART_IIR_IID_3 ((uint32_t)0x0008)
#define UART_IIR_FIFOSE ((uint32_t)0x0060)
#define UART_IIR_FIFOSE_0 ((uint32_t)0x0020)
#define UART_IIR_FIFOSE_1 ((uint32_t)0x0040)
/******************* Bit definition for UART_FCR register *******************/
#define UART_FCR_FIFOE ((uint32_t)0x0001)
#define UART_FCR_RFIFOR ((uint32_t)0x0002)
#define UART_FCR_XFIFOR ((uint32_t)0x0004)
#define UART_FCR_DMAM ((uint32_t)0x0008)
#define UART_FCR_TET ((uint32_t)0x0030)
#define UART_FCR_TET_0 ((uint32_t)0x0010)
#define UART_FCR_TET_1 ((uint32_t)0x0020)
#define UART_FCR_RCVER ((uint32_t)0x00C0)
#define UART_FCR_RCVER_0 ((uint32_t)0x0040)
#define UART_FCR_RCVER_1 ((uint32_t)0x0080)
/******************* Bit definition for UART_LCR register *******************/
#define UART_LCR_DLS ((uint32_t)0x0003)
#define UART_LCR_DLS_0 ((uint32_t)0x0001)
#define UART_LCR_DLS_1 ((uint32_t)0x0002)
#define UART_LCR_STOP ((uint32_t)0x0004)
#define UART_LCR_PEN ((uint32_t)0x0008)
#define UART_LCR_EPS ((uint32_t)0x0010)
#define UART_LCR_SP ((uint32_t)0x0020)
#define UART_LCR_BC ((uint32_t)0x0040)
#define UART_LCR_DLAB ((uint32_t)0x0080)
/******************* Bit definition for UART_MCR register *******************/
#define UART_MCR_DTR ((uint32_t)0x0001)
#define UART_MCR_RTS ((uint32_t)0x0002)
#define UART_MCR_OUT1 ((uint32_t)0x0004)
#define UART_MCR_OUT2 ((uint32_t)0x0008)
#define UART_MCR_LB ((uint32_t)0x0010)
#define UART_MCR_AFCE ((uint32_t)0x0020)
#define UART_MCR_SIRE ((uint32_t)0x0040)
/******************* Bit definition for UART_LSR register *******************/
#define UART_LSR_DR ((uint32_t)0x0001)
#define UART_LSR_OE ((uint32_t)0x0002)
#define UART_LSR_PE ((uint32_t)0x0004)
#define UART_LSR_FE ((uint32_t)0x0008)
#define UART_LSR_BI ((uint32_t)0x0010)
#define UART_LSR_THRE ((uint32_t)0x0020)
#define UART_LSR_TEMT ((uint32_t)0x0040)
#define UART_LSR_PFE ((uint32_t)0x0080)
/******************* Bit definition for UART_MSR register *******************/
#define UART_MSR_DCTS ((uint32_t)0x0001)
#define UART_MSR_DDSR ((uint32_t)0x0002)
#define UART_MSR_TERI ((uint32_t)0x0004)
#define UART_MSR_DDCD ((uint32_t)0x0008)
#define UART_MSR_CTS ((uint32_t)0x0010)
#define UART_MSR_DSR ((uint32_t)0x0020)
#define UART_MSR_RI ((uint32_t)0x0040)
#define UART_MSR_DCD ((uint32_t)0x0080)
/******************* Bit definition for UART_SRBR register *******************/
#define UART_SRBR_SRBR ((uint32_t)0x01FF) /*!< Data value */
/******************* Bit definition for UART_STHR register *******************/
#define UART_STHR_STHR ((uint32_t)0x01FF) /*!< Data value */
/******************* Bit definition for UART_FAR register *******************/
#define UART_FAR_FAR ((uint32_t)0x0001)
/******************* Bit definition for UART_TFR register *******************/
#define UART_TFR_TFR ((uint32_t)0x00FF)
/******************* Bit definition for UART_RFW register *******************/
#define UART_RFW_RFWD ((uint32_t)0x00FF)
#define UART_RFW_RFPE ((uint32_t)0x0100)
#define UART_RFW_RFFE ((uint32_t)0x0200)
/******************* Bit definition for UART_USR register *******************/
#define UART_USR_BUSY ((uint32_t)0x0001)
#define UART_USR_TFNF ((uint32_t)0x0002)
#define UART_USR_TFE ((uint32_t)0x0004)
#define UART_USR_RFNE ((uint32_t)0x0008)
#define UART_USR_RFF ((uint32_t)0x0010)
/******************* Bit definition for UART_TFL register *******************/
#define UART_TFL_TFL ((uint32_t)0x000F)
/******************* Bit definition for UART_RFL register *******************/
#define UART_RFL_RFL ((uint32_t)0x000F)
/******************* Bit definition for UART_SRR register *******************/
#define UART_SRR_UR ((uint32_t)0x0001)
#define UART_SRR_RFR ((uint32_t)0x0002)
#define UART_SRR_XFR ((uint32_t)0x0004)
/******************* Bit definition for UART_SRR register *******************/
#define UART_SRR_UR ((uint32_t)0x0001)
/******************* Bit definition for UART_SRTS register *******************/
#define UART_SRTS_SRTS ((uint32_t)0x0001)
/******************* Bit definition for UART_SBCR register *******************/
#define UART_SBCR_SBCR ((uint32_t)0x0001)
/******************* Bit definition for UART_SDMAM register *******************/
#define UART_SDMAM_SDMAM ((uint32_t)0x0001)
/******************* Bit definition for UART_SFE register *******************/
#define UART_SFE_SFE ((uint32_t)0x0001)
/******************* Bit definition for UART_SRT register *******************/
#define UART_SRT_SRT ((uint32_t)0x0003)
#define UART_SRT_SRT_0 ((uint32_t)0x0001)
#define UART_SRT_SRT_1 ((uint32_t)0x0002)
/******************* Bit definition for UART_STET register *******************/
#define UART_STET_STET ((uint32_t)0x0003)
#define UART_STET_STET_0 ((uint32_t)0x0001)
#define UART_STET_STET_1 ((uint32_t)0x0002)
/******************* Bit definition for UART_HTX register *******************/
#define UART_HTX_HTX ((uint32_t)0x0001)
/******************* Bit definition for UART_DMASA register *******************/
#define UART_DMASA_DMASA ((uint32_t)0x0001)
/******************************************************************************/
/* */
/* General Purpose and Alternate Function I/O */
/* */
/******************************************************************************/
/*!<****************** Bit definition for GPIO_IODR register *******************/
#define DEEP_SLEEP_WKUP_EN_SENSOR (BIT14)
#define DEEP_SLEEP_WKUP_EN_MSR (BIT13)
#define DEEP_SLEEP_WKUP_EN_RTC (BIT12)
#define DEEP_SLEEP_WKUP_EN_KBD (BIT11)
#define DEEP_SLEEP_WKUP_EN_GPIO (BIT0)
/******************************************************************************/
/* */
/* Serial Peripheral Interface */
/* */
/******************************************************************************/
/***************** Bit definition for SPI_CTRLR0 register *******************/
#define SPI_CTRLR0_DFS ((uint32_t)0x000F)
#define SPI_CTRLR0_DFS_0 ((uint32_t)0x0001)
#define SPI_CTRLR0_DFS_1 ((uint32_t)0x0002)
#define SPI_CTRLR0_DFS_2 ((uint32_t)0x0004)
#define SPI_CTRLR0_DFS_3 ((uint32_t)0x0008)
#define SPI_CTRLR0_FRF ((uint32_t)0x0030)
#define SPI_CTRLR0_FRF_0 ((uint32_t)0x0010)
#define SPI_CTRLR0_FRF_1 ((uint32_t)0x0020)
#define SPI_CTRLR0_SCPH ((uint32_t)0x0040)
#define SPI_CTRLR0_SCPOL ((uint32_t)0x0080)
#define SPI_CTRLR0_TMOD ((uint32_t)0x0300)
#define SPI_CTRLR0_TMOD_0 ((uint32_t)0x0100)
#define SPI_CTRLR0_TMOD_1 ((uint32_t)0x0200)
#define SPI_CTRLR0_SLV_OE ((uint32_t)0x0400)
#define SPI_CTRLR0_SRL ((uint32_t)0x0800)
#define SPI_CTRLR0_CFS ((uint32_t)0xF000)
/***************** Bit definition for SPI_CTRLR1 register *******************/
#define SPI_CTRLR0_NDF ((uint32_t)0xFFFF)
/***************** Bit definition for SPI_SSIENR register *******************/
#define SPI_SSIENR_SSIENR ((uint32_t)0x0001)
/***************** Bit definition for SPI_MWCR register *********************/
#define SPI_MWCR_MWMOD ((uint32_t)0x0001)
#define SPI_MWCR_MDD ((uint32_t)0x0002)
#define SPI_MWCR_MHS ((uint32_t)0x0004)
/***************** Bit definition for SPI_SER register **********************/
#define SPI_SER_SER ((uint32_t)0x000F)
#define SPI_SER_0 ((uint32_t)0x0001)
#define SPI_SER_1 ((uint32_t)0x0002)
#define SPI_SER_2 ((uint32_t)0x0004)
#define SPI_SER_3 ((uint32_t)0x0008)
/***************** Bit definition for SPI_BAUDR register ********************/
#define SPI_BAUDR_BAUDR ((uint32_t)0xFFFF)
/***************** Bit definition for SPI_TXFTLR register *******************/
#define SPI_TXFTLR_TFT ((uint32_t)0x000F)
/***************** Bit definition for SPI_RXFTLR register *******************/
#define SPI_RXFTLR_RFT ((uint32_t)0x000F)
/***************** Bit definition for SPI_TXFLR register ********************/
#define SPI_TXFLR_TXTFL ((uint32_t)0x001F)
/***************** Bit definition for SPI_RXFLR register ********************/
#define SPI_RXFLR_RXTFL ((uint32_t)0x001F)
/***************** Bit definition for SPI_SR register ***********************/
#define SPI_SR_BUSY ((uint32_t)0x0001)
#define SPI_SR_TFNF ((uint32_t)0x0002)
#define SPI_SR_TFE ((uint32_t)0x0004)
#define SPI_SR_RFNE ((uint32_t)0x0008)
#define SPI_SR_RFF ((uint32_t)0x0010)
#define SPI_SR_TXE ((uint32_t)0x0020)
#define SPI_SR_DCOL ((uint32_t)0x0040)
/***************** Bit definition for SPI_IMR register **********************/
#define SPI_IMR_TXEIM ((uint32_t)0x0001)
#define SPI_IMR_TXOIM ((uint32_t)0x0002)
#define SPI_IMR_RXUIM ((uint32_t)0x0004)
#define SPI_IMR_RXOIM ((uint32_t)0x0008)
#define SPI_IMR_RXFIM ((uint32_t)0x0010)
#define SPI_IMR_MSTIM ((uint32_t)0x0020)
/***************** Bit definition for SPI_ISR register **********************/
#define SPI_ISR_TXEIS ((uint32_t)0x0001)
#define SPI_ISR_TXOIS ((uint32_t)0x0002)
#define SPI_ISR_RXUIS ((uint32_t)0x0004)
#define SPI_ISR_RXOIS ((uint32_t)0x0008)
#define SPI_ISR_RXFIS ((uint32_t)0x0010)
#define SPI_ISR_MSTIS ((uint32_t)0x0020)
/***************** Bit definition for SPI_RISR register *********************/
#define SPI_RISR_TXEIR ((uint32_t)0x0001)
#define SPI_RISR_TXOIR ((uint32_t)0x0002)
#define SPI_RISR_RXUIR ((uint32_t)0x0004)
#define SPI_RISR_RXOIR ((uint32_t)0x0008)
#define SPI_RISR_RXFIR ((uint32_t)0x0010)
#define SPI_RISR_MSTIR ((uint32_t)0x0020)
/***************** Bit definition for SPI_TXOICR register *******************/
#define SPI_TXOICR_TXOICR ((uint32_t)0x0001)
/***************** Bit definition for SPI_RXOICR register *******************/
#define SPI_RXOICR_RXOICR ((uint32_t)0x0001)
/***************** Bit definition for SPI_RXUICR register *******************/
#define SPI_RXUICR_RXUICR ((uint32_t)0x0001)
/***************** Bit definition for SPI_MSTICR register *******************/
#define SPI_MSTICR_MSTICR ((uint32_t)0x0001)
/***************** Bit definition for SPI_DMACR register ********************/
#define SPI_DMACR_RDMAE ((uint32_t)0x0001)
#define SPI_DMACR_TDMAE ((uint32_t)0x0002)
/***************** Bit definition for SPI_DMATDLR register ******************/
#define SPI_DMATDLR_DMATDLR ((uint32_t)0x000F)
/***************** Bit definition for SPI_DMARDLR register ******************/
#define SPI_DMATDLR_DMARDLR ((uint32_t)0x000F)
/***************** Bit definition for SPI_DMARDLR register ******************/
#define SPI_DMATDLR_DMARDLR ((uint32_t)0x000F)
/***************** Bit definition for SPI_DR register ***********************/
#define SPI_DR_DR ((uint32_t)0xFFFF)
/************** Bit definition for SPI_RX_SAMPLE_DLY register ***************/
#define SPI_RX_SAMPLE_DLY ((uint32_t)0xFFFF)
/******************************************************************************/
/* */
/* Inter-integrated Circuit Interface */
/* */
/******************************************************************************/
/******************* Bit definition for IC_CON register *********************/
#define I2C_IC_CON_MASTER_MODE ((uint32_t)0x0001)
#define I2C_IC_CON_SPEED ((uint32_t)0x0006)
#define I2C_IC_CON_SPEED_0 ((uint32_t)0x0002)
#define I2C_IC_CON_SPEED_1 ((uint32_t)0x0004)
#define I2C_IC_CON_10BITADDR_SLAVE ((uint32_t)0x0008)
#define I2C_IC_CON_10BITADDR_MASTER ((uint32_t)0x0010)
#define I2C_IC_CON_RESTART_EN ((uint32_t)0x0020)
#define I2C_IC_CON_SLAVE_DISABLE ((uint32_t)0x0040)
/******************* Bit definition for IC_TAR register *********************/
#define I2C_IC_TAR_TAR ((uint32_t)0x03FF)
#define I2C_IC_TAR_GC_OR_START ((uint32_t)0x0400)
#define I2C_IC_TAR_SPECIAL ((uint32_t)0x0800)
#define I2C_IC_TAR_10BITADDR_MASTER ((uint32_t)0x1000)
/******************* Bit definition for IC_SAR register *********************/
#define I2C_IC_SAR_SAR ((uint32_t)0x03FF)
/******************* Bit definition for IC_HS_MADDR register ****************/
#define I2C_IC_HS_MADDR_MAR ((uint32_t)0x0007)
#define I2C_IC_HS_MADDR_MAR_0 ((uint32_t)0x0001)
#define I2C_IC_HS_MADDR_MAR_1 ((uint32_t)0x0002)
#define I2C_IC_HS_MADDR_MAR_2 ((uint32_t)0x0004)
/******************* Bit definition for IC_DATA_CMD register ****************/
#define I2C_IC_DATA_CMD_DAT ((uint32_t)0x00FF)
#define I2C_IC_DATA_CMD_CMD ((uint32_t)0x0100)
#define I2C_IC_DATA_CMD_STOP ((uint32_t)0x0200)
#define I2C_IC_DATA_CMD_RESTART ((uint32_t)0x0400)
/******************* Bit definition for IC_SS_SCL_HCNT register *************/
#define I2C_IC_SS_SCL_HCNT_HCNT ((uint32_t)0xFFFF)
/******************* Bit definition for IC_SS_SCL_LCNT register *************/
#define I2C_IC_SS_SCL_LCNT_LCNT ((uint32_t)0xFFFF)
/******************* Bit definition for IC_FS_SCL_HCNT register *************/
#define I2C_IC_FS_SCL_HCNT_HCNT ((uint32_t)0xFFFF)
/******************* Bit definition for IC_FS_SCL_LCNT register *************/
#define I2C_IC_FS_SCL_LCNT_LCNT ((uint32_t)0xFFFF)
/******************* Bit definition for IC_HS_SCL_HCNT register *************/
#define I2C_IC_HS_SCL_HCNT_HCNT ((uint32_t)0xFFFF)
/******************* Bit definition for IC_HS_SCL_LCNT register *************/
#define I2C_IC_HS_SCL_LCNT_LCNT ((uint32_t)0xFFFF)
/******************* Bit definition for IC_INTR_STAT register ***************/
#define I2C_IC_INTR_STAT_R_RX_UNDER ((uint32_t)0x0001)
#define I2C_IC_INTR_STAT_R_RX_OVER ((uint32_t)0x0002)
#define I2C_IC_INTR_STAT_R_RX_FULL ((uint32_t)0x0004)
#define I2C_IC_INTR_STAT_R_TX_OVER ((uint32_t)0x0008)
#define I2C_IC_INTR_STAT_R_TX_EMPTY ((uint32_t)0x0010)
#define I2C_IC_INTR_STAT_R_RD_REQ ((uint32_t)0x0020)
#define I2C_IC_INTR_STAT_R_TX_ABRT ((uint32_t)0x0040)
#define I2C_IC_INTR_STAT_R_RX_DONE ((uint32_t)0x0080)
#define I2C_IC_INTR_STAT_R_ACTIVITY ((uint32_t)0x0100)
#define I2C_IC_INTR_STAT_R_STOP_DET ((uint32_t)0x0200)
#define I2C_IC_INTR_STAT_R_START_DET ((uint32_t)0x0400)
#define I2C_IC_INTR_STAT_R_GEN_CALL ((uint32_t)0x0800)
/******************* Bit definition for IC_INTR_MASK register ***************/
#define I2C_IC_INTR_MASK_M_RX_UNDER ((uint32_t)0x0001)
#define I2C_IC_INTR_MASK_M_RX_OVER ((uint32_t)0x0002)
#define I2C_IC_INTR_MASK_M_RX_FULL ((uint32_t)0x0004)
#define I2C_IC_INTR_MASK_M_TX_OVER ((uint32_t)0x0008)
#define I2C_IC_INTR_MASK_M_TX_EMPTY ((uint32_t)0x0010)
#define I2C_IC_INTR_MASK_M_RD_REQ ((uint32_t)0x0020)
#define I2C_IC_INTR_MASK_M_TX_ABRT ((uint32_t)0x0040)
#define I2C_IC_INTR_MASK_M_RX_DONE ((uint32_t)0x0080)
#define I2C_IC_INTR_MASK_M_ACTIVITY ((uint32_t)0x0100)
#define I2C_IC_INTR_MASK_M_STOP_DET ((uint32_t)0x0200)
#define I2C_IC_INTR_MASK_M_START_DET ((uint32_t)0x0400)
#define I2C_IC_INTR_MASK_M_GEN_CALL ((uint32_t)0x0800)
/******************* Bit definition for IC_RAW_INTR_STAT register ***********/
#define I2C_IC_RAW_INTR_STAT_RX_UNDER ((uint32_t)0x0001)
#define I2C_IC_RAW_INTR_STAT_RX_OVER ((uint32_t)0x0002)
#define I2C_IC_RAW_INTR_STAT_RX_FULL ((uint32_t)0x0004)
#define I2C_IC_RAW_INTR_STAT_TX_OVER ((uint32_t)0x0008)
#define I2C_IC_RAW_INTR_STAT_TX_EMPTY ((uint32_t)0x0010)
#define I2C_IC_RAW_INTR_STAT_RD_REQ ((uint32_t)0x0020)
#define I2C_IC_RAW_INTR_STAT_TX_ABRT ((uint32_t)0x0040)
#define I2C_IC_RAW_INTR_STAT_RX_DONE ((uint32_t)0x0080)
#define I2C_IC_RAW_INTR_STAT_ACTIVITY ((uint32_t)0x0100)
#define I2C_IC_RAW_INTR_STAT_STOP_DET ((uint32_t)0x0200)
#define I2C_IC_RAW_INTR_STAT_START_DET ((uint32_t)0x0400)
#define I2C_IC_RAW_INTR_STAT_GEN_CALL ((uint32_t)0x0800)
/******************* Bit definition for IC_RX_TL register *******************/
#define I2C_IC_RX_TL_TL ((uint32_t)0x00FF)
/******************* Bit definition for IC_TX_TL register *******************/
#define I2C_IC_TX_TL_TL ((uint32_t)0x00FF)
/******************* Bit definition for IC_CLR_INTR register ****************/
#define I2C_IC_CLR_INTR ((uint32_t)0x0001)
/******************* Bit definition for IC_CLR_RX_UNDER register ************/
#define I2C_IC_CLR_RX_UNDER ((uint32_t)0x0001)
/******************* Bit definition for IC_CLR_RX_OVER register *************/
#define I2C_IC_CLR_RX_OVER ((uint32_t)0x0001)
/******************* Bit definition for IC_CLR_TX_OVER register *************/
#define I2C_IC_CLR_TX_OVER ((uint32_t)0x0001)
/******************* Bit definition for IC_CLR_RD_REQ register **************/
#define I2C_IC_CLR_RD_REQ ((uint32_t)0x0001)
/******************* Bit definition for IC_CLR_TX_ABRT register *************/
#define I2C_IC_CLR_TX_ABRT ((uint32_t)0x0001)
/******************* Bit definition for IC_CLR_RX_DONE register *************/
#define I2C_IC_CLR_RX_DONE ((uint32_t)0x0001)
/******************* Bit definition for IC_CLR_ACTIVITY register ************/
#define I2C_IC_CLR_ACTIVITY ((uint32_t)0x0001)
/******************* Bit definition for IC_CLR_STOP_DET register ************/
#define I2C_IC_CLR_STOP_DET ((uint32_t)0x0001)
/******************* Bit definition for IC_CLR_START_DET register ***********/
#define I2C_IC_CLR_START_DET ((uint32_t)0x0001)
/******************* Bit definition for IC_CLR_GEN_CALL register ************/
#define I2C_IC_CLR_GEN_CALL ((uint32_t)0x0001)
/******************* Bit definition for IC_ENABLE register *****************/
#define I2C_IC_ENABLE_ENABLE ((uint32_t)0x0001)
#define I2C_IC_ENABLE_ABORT ((uint32_t)0x0002)
/******************* Bit definition for IC_STATUS register *****************/
#define I2C_IC_STATUS_ACTIVITY ((uint32_t)0x0001)
#define I2C_IC_STATUS_TFNF ((uint32_t)0x0002)
#define I2C_IC_STATUS_TFE ((uint32_t)0x0004)
#define I2C_IC_STATUS_RFNE ((uint32_t)0x0008)
#define I2C_IC_STATUS_RFF ((uint32_t)0x0010)
#define I2C_IC_STATUS_MST_ACTIVITY ((uint32_t)0x0020)
#define I2C_IC_STATUS_SLV_ACTIVITY ((uint32_t)0x0040)
/******************* Bit definition for IC_TXFLR register ******************/
#define I2C_IC_TXFLR_TXFLR (8)
/******************* Bit definition for IC_RXFLR register ******************/
#define I2C_IC_RXFLR_RXFLR (8)
/******************* Bit definition for IC_SDA_HOLD register ***************/
#define I2C_IC_SDA_HOLD ((uint32_t)0xFFFF)
/******************* Bit definition for IC_TX_ABRT_SOURCE register *********/
#define I2C_IC_TX_ABRT_SOURCE_7B_ADDR_NOACK ((uint32_t)0x00000001)
#define I2C_IC_TX_ABRT_SOURCE_10ADDR1_NOACK ((uint32_t)0x00000002)
#define I2C_IC_TX_ABRT_SOURCE_10ADDR2_NOACK ((uint32_t)0x00000004)
#define I2C_IC_TX_ABRT_SOURCE_TXDATA_NOACK ((uint32_t)0x00000008)
#define I2C_IC_TX_ABRT_SOURCE_GCALL_NOACK ((uint32_t)0x00000010)
#define I2C_IC_TX_ABRT_SOURCE_GCALL_READ ((uint32_t)0x00000020)
#define I2C_IC_TX_ABRT_SOURCE_HS_ACKDET ((uint32_t)0x00000040)
#define I2C_IC_TX_ABRT_SOURCE_SBYTE_ACKDET ((uint32_t)0x00000080)
#define I2C_IC_TX_ABRT_SOURCE_HS_NORSTRT ((uint32_t)0x00000100)
#define I2C_IC_TX_ABRT_SOURCE_SBYTE_NORSTRT ((uint32_t)0x00000200)
#define I2C_IC_TX_ABRT_SOURCE_10B_RD_NORSTRT ((uint32_t)0x00000400)
#define I2C_IC_TX_ABRT_SOURCE_MASTER_DIS ((uint32_t)0x00000800)
#define I2C_IC_TX_ABRT_SOURCE_LOST ((uint32_t)0x00001000)
#define I2C_IC_TX_ABRT_SOURCE_SLVFLUSH_TXFIFO ((uint32_t)0x00002000)
#define I2C_IC_TX_ABRT_SOURCE_SLV_ARBLOST ((uint32_t)0x00004000)
#define I2C_IC_TX_ABRT_SOURCE_SLVRD_INTX ((uint32_t)0x00008000)
#define I2C_IC_TX_ABRT_SOURCE_USER_ABRT ((uint32_t)0x00010000)
#define I2C_IC_TX_ABRT_SOURCE_TX_FLUSH_CNT ((uint32_t)0xFF000000)
/******************* Bit definition for IC_SLV_DATA_NACK_ONLY register *****/
#define I2C_IC_SLV_DATA_NACK_ONLY ((uint32_t)0x0001)
/******************* Bit definition for IC_DMA_TDLR register ***************/
#define I2C_IC_DMA_TDLR_TDLR ((uint32_t)0x000F)
/******************* Bit definition for IC_DMA_RDLR register ***************/
#define I2C_IC_DMA_TDLR_TDLR ((uint32_t)0x000F)
/******************* Bit definition for IC_SDA_SETUP register **************/
#define I2C_IC_SDA_SETUP ((uint32_t)0x00FF)
/******************* Bit definition for IC_ACK_GENERAL_CALL register *******/
#define I2C_IC_ACK_GENERAL_CALL ((uint32_t)0x0001)
/******************* Bit definition for IC_ENABLE_STATUS register **********/
#define I2C_IC_ENABLE_STATUS_IC_EN ((uint32_t)0x0001)
#define I2C_IC_ENABLE_STATUS_SLV_RX_ABORTED ((uint32_t)0x0001)
#define I2C_IC_ENABLE_STATUS_SLV_FIFO_FILLED_AND_FLUSHED ((uint32_t)0x0001)
/******************* Bit definition for IC_FS_SPKLEN register **************/
#define I2C_IC_FS_SPKLEN_SPKLEN ((uint32_t)0x00FF)
/******************* Bit definition for IC_HS_SPKLEN register **************/
#define I2C_IC_HS_SPKLEN_SPKLEN ((uint32_t)0x00FF)
/******************* Bit definition for IC_COMP_PARAM_1 register ***********/
#define I2C_IC_COMP_PARAM_1_APB_DATA_WIDTH ((uint32_t)0x0003)
#define I2C_IC_COMP_PARAM_1_APB_DATA_WIDTH_0 ((uint32_t)0x0001)
#define I2C_IC_COMP_PARAM_1_APB_DATA_WIDTH_1 ((uint32_t)0x0002)
#define I2C_IC_COMP_PARAM_1_MAX_SPEED_MODE ((uint32_t)0x000C)
#define I2C_IC_COMP_PARAM_1_MAX_SPEED_MODE_0 ((uint32_t)0x0004)
#define I2C_IC_COMP_PARAM_1_MAX_SPEED_MODE_1 ((uint32_t)0x0008)
#define I2C_IC_COMP_PARAM_1_HC_COUNT_VALUES ((uint32_t)0x0010)
#define I2C_IC_COMP_PARAM_1_INTR_IO ((uint32_t)0x0020)
#define I2C_IC_COMP_PARAM_1_HAS_DMA ((uint32_t)0x0040)
#define I2C_IC_COMP_PARAM_1_ADD_ENCODED_PARAMS ((uint32_t)0x0080)
#define I2C_IC_COMP_PARAM_1_RX_BUFFER_DEPTH ((uint32_t)0x0000FF00)
#define I2C_IC_COMP_PARAM_1_TX_BUFFER_DEPTH ((uint32_t)0x00FF0000)
/******************* Bit definition for IC_COMP_VERSION register ***********/
#define I2C_IC_COMP_VERSION ((uint32_t)0xFFFFFFFF)
/******************* Bit definition for IC_COMP_TYPE register **************/
#define I2C_IC_COMP_TYPE ((uint32_t)0xFFFFFFFF)
/******************************************************************************/
/* */
/* Backup Register Unit Block */
/* */
/******************************************************************************/
/******************* Bit definition for BPK_RDY register ********************/
#define BPK_RDY_POR ((uint32_t)0x0002)
#define BPK_RDY_READY ((uint32_t)0x0001)
/******************* Bit definition for BPK_RR register *********************/
#define BPK_RR_RESET ((uint32_t)0x0001)
/******************* Bit definition for BPK_LR register *********************/
#define BPK_LR_LOCK_SELF ((uint32_t)0x0001)
#define BPK_LR_LOCK_RESET ((uint32_t)0x0002)
#define BPK_LR_LOCK_KEYWRITE ((uint32_t)0x0004)
#define BPK_LR_LOCK_KEYREAD ((uint32_t)0x0008)
#define BPK_LR_LOCK_KEYCLEAR ((uint32_t)0x0010)
#define BPK_LR_LOCK_SCRAMBER ((uint32_t)0x0020)
#define BPK_LR_LOCK_ALL ((uint32_t)0x003F)
/******************************************************************************/
/* */
/* RTC Unit Block */
/* */
/******************************************************************************/
/******************* Bit definition for RTC_CS register *********************/
#define RTC_CS_ALARM_IT ((uint32_t)0x01)
#define RTC_CS_LOCK_TIM ((uint32_t)0x02)
#define RTC_CS_ALARM_EN ((uint32_t)0x04)
#define RTC_CS_READY ((uint32_t)0x08)
#define RTC_CS_CLR ((uint32_t)0x10)
/******************************************************************************/
/* */
/* Keyboard Control Unit Block */
/* */
/******************************************************************************/
/***************** Bit definition for KCU_CTRL0 register ********************/
#define KCU_PORT_0 ((uint32_t)0x0001)
#define KCU_PORT_1 ((uint32_t)0x0002)
#define KCU_PORT_2 ((uint32_t)0x0004)
#define KCU_PORT_3 ((uint32_t)0x0008)
#define KCU_PORT_4 ((uint32_t)0x0010)
#define KCU_PORT_5 ((uint32_t)0x0020)
#define KCU_PORT_6 ((uint32_t)0x0040)
#define KCU_PORT_7 ((uint32_t)0x0080)
#define KCU_PORT_8 ((uint32_t)0x0100)
#define KCU_PORT_ALL_Mask ((uint32_t)0x001F)
#define KCU_DEBOUNCETIMELEVEL_0 ((uint32_t)0x0000)
#define KCU_DEBOUNCETIMELEVEL_1 ((uint32_t)0x0001)
#define KCU_DEBOUNCETIMELEVEL_2 ((uint32_t)0x0002)
#define KCU_DEBOUNCETIMELEVEL_3 ((uint32_t)0x0003)
#define KCU_DEBOUNCETIMELEVEL_4 ((uint32_t)0x0004)
#define KCU_DEBOUNCETIMELEVEL_5 ((uint32_t)0x0005)
#define KCU_DEBOUNCETIMELEVEL_6 ((uint32_t)0x0006)
#define KCU_DEBOUNCETIMELEVEL_7 ((uint32_t)0x0007)
#define KCU_DEBOUNCETIMELEVEL_POS (9)
/***************** Bit definition for KCU_CTRL1 register ********************/
#define KCU_CTRL1_KBD_EN ((uint32_t)0x0001)
#define KCU_CTRL1_PUSH_IT ((uint32_t)0x0002)
#define KCU_CTRL1_RELEASE_IT ((uint32_t)0x0004)
#define KCU_CTRL1_OVERRUN_IT ((uint32_t)0x0008)
#define KCU_CTRL1_KCU_RUNING ((uint32_t)0x80000000)
/***************** Bit definition for KCU_STATUS register *******************/
#define KCU_STATUS_IT ((uint32_t)0x0001)
#define KCU_STATUS_OVERRUN_IT ((uint32_t)0x0002)
#define KCU_STATUS_PUSH_IT ((uint32_t)0x0004)
#define KCU_STATUS_RELEASE_IT ((uint32_t)0x0008)
#define KCU_STATUS_EVENT_0_PUSH ((uint32_t)0x0010)
#define KCU_STATUS_EVENT_0_NEW ((uint32_t)0x0020)
#define KCU_STATUS_EVENT_1_PUSH ((uint32_t)0x0040)
#define KCU_STATUS_EVENT_1_NEW ((uint32_t)0x0080)
#define KCU_STATUS_EVENT_2_PUSH ((uint32_t)0x0100)
#define KCU_STATUS_EVENT_2_NEW ((uint32_t)0x0200)
#define KCU_STATUS_EVENT_3_PUSH ((uint32_t)0x0400)
#define KCU_STATUS_EVENT_3_NEW ((uint32_t)0x0800)
/***************** Bit definition for KCU_EVENT register ********************/
#define KCU_EVENT_EVENT_0_INPUT_NUM ((uint32_t)0x0000000F)
#define KCU_EVENT_EVENT_0_OUTPUT_NUM ((uint32_t)0x000000F0)
#define KCU_EVENT_EVENT_1_INPUT_NUM ((uint32_t)0x00000F00)
#define KCU_EVENT_EVENT_1_OUTPUT_NUM ((uint32_t)0x0000F000)
#define KCU_EVENT_EVENT_2_INPUT_NUM ((uint32_t)0x000F0000)
#define KCU_EVENT_EVENT_2_OUTPUT_NUM ((uint32_t)0x00F00000)
#define KCU_EVENT_EVENT_3_INPUT_NUM ((uint32_t)0x0F000000)
#define KCU_EVENT_EVENT_3_OUTPUT_NUM ((uint32_t)0xF0000000)
/******************************************************************************/
/* */
/* Timer Control Unit Block */
/* */
/******************************************************************************/
/********** Bit definition for TIMER_CONTROL_REG register *******************/
#define TIMER_CONTROL_REG_TIMER_ENABLE (0x0001U)
#define TIMER_CONTROL_REG_TIMER_MODE (0x0002U)
#define TIMER_CONTROL_REG_TIMER_INTERRUPT (0x0004U)
#define TIMER_CONTROL_REG_TIMER_PWM (0x0008U)
#define TIMER_CONTROL_REG_PWM_SINGLE_PULSE (0x0010U)
#define TIMER_CONTROL_REG_PWM_RELOAD_SINGLE_PULSE (0x0020U)
/***************** Bit definition for IntStatus register ********************/
#define TIMER_INT_STATUS_INTERRUPT (0x0001U)
/******************************************************************************/
/* */
/* WDT Control Unit Block */
/* */
/******************************************************************************/
/***************** Bit definition for WDT_CR register ***********************/
#define WDT_CR_WDT_EN ((uint32_t)0x0001)
#define WDT_CR_RMOD ((uint32_t)0x0002)
/***************** Bit definition for WDT_CCVR register *********************/
#define WDT_CCVR_CCVR ((uint32_t)0xFFFFFFFF)
/***************** Bit definition for WDT_CRR register **********************/
#define WDT_CRR_CRR ((uint32_t)0x00FF)
/***************** Bit definition for WDT_STAT register *********************/
#define WDT_STAT_INT ((uint32_t)0x0001)
/***************** Bit definition for WDT_EOI register **********************/
#define WDT_EOI_EOI ((uint32_t)0x0001)
/***************** Bit definition for WDT_RLD register **********************/
#define WDT_RLD_RLD ((uint32_t)0xFFFFFFFF)
/******************************************************************************/
/* */
/* RNG Control Unit Block */
/* */
/******************************************************************************/
/************ bit definition for TRNG RNG_INDEX REGISTER ************/
#define RNG_FIFO_INDEX_Mask BIT(31)
/************ bit definition for TRNG RNG_CSR REGISTER ************/
#define TRNG_RNG_CSR_INTP_EN_Mask ((uint32_t)0x0010)
#define TRNG_RNG_CSR_ATTACK_TRNG0_Mask ((uint32_t)0x0004)
#define TRNG_RNG_CSR_S128_TRNG0_Mask ((uint32_t)0x0001)
/************ bit definition for TRNG RNG_AMA REGISTER ************/
#define TRNG_RNG_AMA_ANA_OUT_TRNG0_Mask ((uint32_t)0x10000000)
#define TRNG_RNG_AMA_PD_TRNG0_Mask ((uint32_t)0x00001000)
#define TRNG_RNG_AMA_PD_TRNG1_Mask ((uint32_t)0x00002000)
#define TRNG_RNG_AMA_PD_TRNG2_Mask ((uint32_t)0x00004000)
#define TRNG_RNG_AMA_PD_TRNG3_Mask ((uint32_t)0x00008000)
#define TRNG_RNG_AMA_PD_ALL_Mask ((uint32_t)0x0000F000)
/******************************************************************************/
/* */
/* DCMI */
/* */
/******************************************************************************/
/************** Bit definition for DCMI SYSCTRL DBG_CR register *************/
#define DCMI_DBG_CR_INPUTSEL ((uint32_t)0x00002000)
/******************** Bits definition for DCMI_CR register ******************/
#define DCMI_CR_CAPTURE ((uint32_t)0x00000001)
#define DCMI_CR_CM ((uint32_t)0x00000002)
#define DCMI_CR_CROP ((uint32_t)0x00000004)
#define DCMI_CR_JPEG ((uint32_t)0x00000008)
#define DCMI_CR_ESS ((uint32_t)0x00000010)
#define DCMI_CR_PCKPOL ((uint32_t)0x00000020)
#define DCMI_CR_HSPOL ((uint32_t)0x00000040)
#define DCMI_CR_VSPOL ((uint32_t)0x00000080)
#define DCMI_CR_FCRC_0 ((uint32_t)0x00000100)
#define DCMI_CR_FCRC_1 ((uint32_t)0x00000200)
#define DCMI_CR_EDM_0 ((uint32_t)0x00000400)
#define DCMI_CR_EDM_1 ((uint32_t)0x00000800)
#define DCMI_CR_CRE ((uint32_t)0x00001000)
#define DCMI_CR_ENABLE ((uint32_t)0x00004000)
#define DCMI_CR_BSM_0 ((uint32_t)0x00010000)
#define DCMI_CR_BSM_1 ((uint32_t)0x00020000)
#define DCMI_CR_OEBS ((uint32_t)0x00040000)
#define DCMI_CR_LSM ((uint32_t)0x00080000)
#define DCMI_CR_OELS ((uint32_t)0x00100000)
#define DCMI_CR_DMAS ((uint32_t)0xE0000000)
/******************** Bits definition for DCMI_SR register ******************/
#define DCMI_SR_HSYNC ((uint32_t)0x00000001)
#define DCMI_SR_VSYNC ((uint32_t)0x00000002)
#define DCMI_SR_FNE ((uint32_t)0x00000004)
/******************** Bits definition for DCMI_RISR register ****************/
#define DCMI_RISR_FRAME_RIS ((uint32_t)0x00000001)
#define DCMI_RISR_OVF_RIS ((uint32_t)0x00000002)
#define DCMI_RISR_ERR_RIS ((uint32_t)0x00000004)
#define DCMI_RISR_VSYNC_RIS ((uint32_t)0x00000008)
#define DCMI_RISR_LINE_RIS ((uint32_t)0x00000010)
/******************** Bits definition for DCMI_IER register *****************/
#define DCMI_IER_FRAME_IE ((uint32_t)0x00000001)
#define DCMI_IER_OVF_IE ((uint32_t)0x00000002)
#define DCMI_IER_ERR_IE ((uint32_t)0x00000004)
#define DCMI_IER_VSYNC_IE ((uint32_t)0x00000008)
#define DCMI_IER_LINE_IE ((uint32_t)0x00000010)
/******************** Bits definition for DCMI_MISR register ****************/
#define DCMI_MISR_FRAME_MIS ((uint32_t)0x00000001)
#define DCMI_MISR_OVF_MIS ((uint32_t)0x00000002)
#define DCMI_MISR_ERR_MIS ((uint32_t)0x00000004)
#define DCMI_MISR_VSYNC_MIS ((uint32_t)0x00000008)
#define DCMI_MISR_LINE_MIS ((uint32_t)0x00000010)
/******************** Bits definition for DCMI_ICR register *****************/
#define DCMI_ICR_FRAME_ISC ((uint32_t)0x00000001)
#define DCMI_ICR_OVF_ISC ((uint32_t)0x00000002)
#define DCMI_ICR_ERR_ISC ((uint32_t)0x00000004)
#define DCMI_ICR_VSYNC_ISC ((uint32_t)0x00000008)
#define DCMI_ICR_LINE_ISC ((uint32_t)0x00000010)
/****************** Bit definition for QUADSPI_FCU_CMD register ******************/
#define QUADSPI_FCU_CMD_CODE ((uint32_t)0xFF000000U)
#define QUADSPI_FCU_CMD_BUS_MODE ((uint32_t)0x00000300U)
#define QUADSPI_FCU_CMD_CMD_FORMAT ((uint32_t)0x000000F0U)
#define QUADSPI_FCU_CMD_DONE ((uint32_t)0x00000008U)
#define QUADSPI_FCU_CMD_BUSY ((uint32_t)0x00000004U)
#define QUADSPI_FCU_CMD_ACCESS_ACK ((uint32_t)0x00000002U)
#define QUADSPI_FCU_CMD_ACCESS_REQ ((uint32_t)0x00000001U)
#define QUADSPI_ADDRESS_ADR ((uint32_t)0xFFFFFF00U)
#define QUADSPI_ADDRESS_M8 ((uint32_t)0x000000FFU)
#define QUADSPI_BYTE_NUM_WR_BYTE ((uint32_t)0x00001FFFU)
#define QUADSPI_BYTE_NUM_RD_BYTE ((uint32_t)0x1FFF0000U)
#define QUADSPI_WR_FIFO_WR_DATA ((uint32_t)0xFFFFFFFFU)
#define QUADSPI_RD_FIFO_RD_DATA ((uint32_t)0xFFFFFFFFU)
#define QUADSPI_DEVICE_PARA_SAMPLE_DLY ((uint32_t)0x00008000U)
#define QUADSPI_DEVICE_PARA_SAMPLE_PHA ((uint32_t)0x00004000U)
#define QUADSPI_DEVICE_PARA_PROTOCOL ((uint32_t)0x00000300U)
#define QUADSPI_DEVICE_PARA_DUMMY_CYCLE ((uint32_t)0x000000F0U)
#define QUADSPI_DEVICE_PARA_FLASH_READY ((uint32_t)0x00000008U)
#define QUADSPI_DEVICE_PARA_FREQ_SEL ((uint32_t)0x00000003U)
#define QUADSPI_REG_WDATA ((uint32_t)0xFFFFFFFFU)
#define QUADSPI_REG_RDATA ((uint32_t)0xFFFFFFFFU)
#define QUADSPI_INT_MASK_TFDM ((uint32_t)0x00000040U)
#define QUADSPI_INT_MASK_RFDM ((uint32_t)0x00000020U)
#define QUADSPI_INT_MASK_TFOM ((uint32_t)0x00000010U)
#define QUADSPI_INT_MASK_TFUM ((uint32_t)0x00000008U)
#define QUADSPI_INT_MASK_RFOM ((uint32_t)0x00000004U)
#define QUADSPI_INT_MASK_RFUM ((uint32_t)0x00000002U)
#define QUADSPI_INT_MASK_DONE_IM ((uint32_t)0x00000001U)
#define QUADSPI_INT_UMSAK_TFDU ((uint32_t)0x00000040U)
#define QUADSPI_INT_UMSAK_RFDU ((uint32_t)0x00000020U)
#define QUADSPI_INT_UMSAK_TFOU ((uint32_t)0x00000010U)
#define QUADSPI_INT_UMSAK_TFUU ((uint32_t)0x00000008U)
#define QUADSPI_INT_UMSAK_RFOU ((uint32_t)0x00000004U)
#define QUADSPI_INT_UMSAK_RFUU ((uint32_t)0x00000002U)
#define QUADSPI_INT_UMSAK_DONE_IU ((uint32_t)0x00000001U)
#define QUADSPI_INT_MASK_STATUS_TFDM ((uint32_t)0x00000040U)
#define QUADSPI_INT_MASK_STATUS_RFDM ((uint32_t)0x00000020U)
#define QUADSPI_INT_MASK_STATUS_TFOM ((uint32_t)0x00000010U)
#define QUADSPI_INT_MASK_STATUS_TFUM ((uint32_t)0x00000008U)
#define QUADSPI_INT_MASK_STATUS_RFOM ((uint32_t)0x00000004U)
#define QUADSPI_INT_MASK_STATUS_RFUM ((uint32_t)0x00000002U)
#define QUADSPI_INT_MASK_STATUS_DONE_IM ((uint32_t)0x00000001U)
#define QUADSPI_INT_STATUS_TFDS ((uint32_t)0x00000040U)
#define QUADSPI_INT_STATUS_RFDS ((uint32_t)0x00000020U)
#define QUADSPI_INT_STATUS_TFOS ((uint32_t)0x00000010U)
#define QUADSPI_INT_STATUS_TFUS ((uint32_t)0x00000008U)
#define QUADSPI_INT_STATUS_RFOS ((uint32_t)0x00000004U)
#define QUADSPI_INT_STATUS_RFUS ((uint32_t)0x00000002U)
#define QUADSPI_INT_STATUS_DONE_IS ((uint32_t)0x00000001U)
#define QUADSPI_INT_RAWSTATUS_TFDR ((uint32_t)0x00000040U)
#define QUADSPI_INT_RAWSTATUS_RFDR ((uint32_t)0x00000020U)
#define QUADSPI_INT_RAWSTATUS_TFOR ((uint32_t)0x00000010U)
#define QUADSPI_INT_RAWSTATUS_TFUR ((uint32_t)0x00000008U)
#define QUADSPI_INT_RAWSTATUS_RFOR ((uint32_t)0x00000004U)
#define QUADSPI_INT_RAWSTATUS_RFUR ((uint32_t)0x00000002U)
#define QUADSPI_INT_RAWSTATUS_DONE_IR ((uint32_t)0x00000001U)
#define QUADSPI_INT_CLEAR_CTFD ((uint32_t)0x00000040U)
#define QUADSPI_INT_CLEAR_CRFD ((uint32_t)0x00000020U)
#define QUADSPI_INT_CLEAR_CTFO ((uint32_t)0x00000010U)
#define QUADSPI_INT_CLEAR_CTFU ((uint32_t)0x00000008U)
#define QUADSPI_INT_CLEAR_CRFO ((uint32_t)0x00000004U)
#define QUADSPI_INT_CLEAR_CRFU ((uint32_t)0x00000002U)
#define QUADSPI_INT_CLEAR_DONE ((uint32_t)0x00000001U)
#define QUADSPI_CACHE_INTF_CMD_RELDS ((uint32_t)0xFF000000U)
#define QUADSPI_CACHE_INTF_CMD_DS ((uint32_t)0x00FF0000U)
#define QUADSPI_CACHE_INTF_CMD_RD_BUS_MODE ((uint32_t)0x00003000U)
#define QUADSPI_CACHE_INTF_CMD_RD_FORMAT ((uint32_t)0x00000F00U)
#define QUADSPI_CACHE_INTF_CMD_RDCMD ((uint32_t)0x000000FFU)
#define QUADSPI_DMA_CNTL_TX_EN ((uint32_t)0x00000001U)
#define QUADSPI_FIFO_CNTL_TFFH ((uint32_t)0x80000000U)
#define QUADSPI_FIFO_CNTL_TFE ((uint32_t)0x00200000U)
#define QUADSPI_FIFO_CNTL_TFFL ((uint32_t)0x00100000U)
#define QUADSPI_FIFO_CNTL_TFL ((uint32_t)0x000F0000U)
#define QUADSPI_FIFO_CNTL_RFFH ((uint32_t)0x00008000U)
#define QUADSPI_FIFO_CNTL_RFE ((uint32_t)0x00000020U)
#define QUADSPI_FIFO_CNTL_RFFL ((uint32_t)0x00000010U)
#define QUADSPI_FIFO_CNTL_RFL ((uint32_t)0x0000000FU)
#define AIR105_READ_REG8(reg) (*(__IO uint8_t *) reg)
#define AIR105_READ_REG16(reg) (*(__IO uint16_t *) reg)
#define AIR105_READ_REG32(reg) (*(__IO uint32_t *) reg)
#define AIR105_WRITE_REG8(reg, value) (*(__IO uint8_t *) reg = value)
#define AIR105_WRITE_REG16(reg, value) (*(__IO uint16_t *) reg = value)
#define AIR105_WRITE_REG32(reg, value) (*(__IO uint32_t *) reg = value)
#define AIR105_MODIFY_REG8(reg, clear_mask, set_mask) \
AIR105_WRITE_REG8(reg, (((AIR105_READ_REG8(reg)) & ~clear_mask) | set_mask))
#define AIR105_MODIFY_REG16(reg, clear_mask, set_mask) \
AIR105_WRITE_REG16(reg, (((AIR105_READ_REG16(reg)) & ~clear_mask) | set_mask))
#define AIR105_MODIFY_REG32(reg, clear_mask, set_mask) \
AIR105_WRITE_REG32(reg, (((AIR105_READ_REG32(reg)) & ~clear_mask) | set_mask))
#include "air105_conf.h"
#ifdef __cplusplus
}
#endif
#endif /* AIR105_H */
|
6d6a5c38551523a37e24de82d1aea427dca5bf7c
|
e4aec45494ca19bd33ca42779052028b6a639277
|
/src/firo_params.h
|
e8b8d26e725766afb76984553766dcf2be210b31
|
[
"MIT"
] |
permissive
|
firoorg/firo
|
b7e171b441bdbd12fc6e453abdbae15673c901aa
|
705857955ece204c935d5645955fb06a9db3d1a7
|
refs/heads/master
| 2023-08-31T06:19:03.976824
| 2023-08-30T13:14:36
| 2023-08-30T13:14:36
| 67,837,600
| 245
| 101
|
MIT
| 2023-09-11T08:09:27
| 2016-09-09T22:50:27
|
C++
|
UTF-8
|
C
| false
| false
| 8,258
|
h
|
firo_params.h
|
#ifndef FIRO_PARAMS_H
#define FIRO_PARAMS_H
#define ZEROCOIN_MODULUS "25195908475657893494027183240048398571429282126204032027777137836043662020707595556264018525880784406918290641249515082189298559149176184502808489120072844992687392807287776735971418347270261896375014971824691165077613379859095700097330459748808428401797429100642458691817195118746121515172654632282216869987549182422433637259085141865462043576798423387184774447920739934236584823824281198163815010674810451660377306056201619676256133844143603833904414952634432190114657544454178424020924616515723350778707749817125772467962926386356373289912154831438167899885040445364023527381951378636564391212010397122822120720357"
#define ZEROCOIN_MODULUS_V2 "C7970CEEDCC3B0754490201A7AA613CD73911081C790F5F1A8726F463550BB5B7FF0DB8E1EA1189EC72F93D1650011BD721AEEACC2ACDE32A04107F0648C2813A31F5B0B7765FF8B44B4B6FFC93384B646EB09C7CF5E8592D40EA33C80039F35B4F14A04B51F7BFD781BE4D1673164BA8EB991C2C4D730BBBE35F592BDEF524AF7E8DAEFD26C66FC02C479AF89D64D373F442709439DE66CEB955F3EA37D5159F6135809F85334B5CB1813ADDC80CD05609F10AC6A95AD65872C909525BDAD32BC729592642920F24C61DC5B3C3B7923E56B16A4D9D373D8721F24A3FC0F1B3131F55615172866BCCC30F95054C824E733A5EB6817F7BC16399D48C6361CC7E5"
/** Dust Soft Limit, allowed with additional fee per output */
//static const int64_t DUST_SOFT_LIMIT = 100000; // 0.001 FIRO
/** Dust Hard Limit, ignored as wallet inputs (mininput default) */
static const int64_t DUST_HARD_LIMIT = 1000; // 0.00001 FIRO mininput
// There were bugs before this block, don't do some checks on early blocks
#define ZC_CHECK_BUG_FIXED_AT_BLOCK 61168
// Before this block we allowed not paying to the znodes.
#define ZC_ZNODE_PAYMENT_BUG_FIXED_AT_BLOCK 107246
// Do strict check on duplicate minted public coin value after this block
#define ZC_CHECK_DUPLICATE_MINT_AT_BLOCK 70000
// The mint id number to change to zerocoin v2
#define ZC_V2_SWITCH_ID_1 200
#define ZC_V2_SWITCH_ID_10 30
#define ZC_V2_SWITCH_ID_25 15
#define ZC_V2_SWITCH_ID_50 15
#define ZC_V2_SWITCH_ID_100 100
// Same for testnet
#define ZC_V2_TESTNET_SWITCH_ID_1 18
#define ZC_V2_TESTNET_SWITCH_ID_10 7
#define ZC_V2_TESTNET_SWITCH_ID_25 5
#define ZC_V2_TESTNET_SWITCH_ID_50 4
#define ZC_V2_TESTNET_SWITCH_ID_100 10
#define ZC_V1_5_STARTING_BLOCK 78500
#define ZC_V1_5_TESTNET_STARTING_BLOCK 37954
#define ZC_V1_5_GRACEFUL_MEMPOOL_PERIOD 500
#define ZC_V1_5_GRACEFUL_PERIOD 1500
// Block after which sigma mints are activated.
#define ZC_SIGMA_STARTING_BLOCK 184200 //Approx July 30th, 2019, 8:00 AM UTC
#define ZC_SIGMA_TESTNET_STARTING_BLOCK 50000
// Block after which anonymity sets are being padded.
#define ZC_SIGMA_PADDING_BLOCK 220720 //Approx December 5th 12PM UTC
#define ZC_SIGMA_TESTNET_PADDING_BLOCK 110000
//Block after whinch we are disabling sigma to enable after starting padding
#define ZC_SIGMA_DISABLE_UNPADDED_BLOCK 219904 //December 2nd 12PM UTC
#define ZC_SIGMA_TESTNET_DISABLE_UNPADDED_BLOCK 109160
// The block number after which old sigma clients are banned.
#define ZC_OLD_SIGMA_BAN_BLOCK 181850 //Approx July 22nd, 2019, 4:00 AM UTC
// Block after which lelantus mints are activated.
#define ZC_LELANTUS_STARTING_BLOCK 336888
#define ZC_LELANTUS_FIXES_START_BLOCK 365544 //Approx April 22, 20211, 2:00 PM UTC
#define ZC_LELANTUS_TESTNET_STARTING_BLOCK 15700
#define ZC_LELANTUS_TESTNET_FIXES_START_BLOCK 27600
// Number of blocks after ZC_SIGMA_STARTING_BLOCK during which we still accept zerocoin V2 mints into mempool.
#define ZC_V2_MINT_GRACEFUL_MEMPOOL_PERIOD 4500
#define ZC_V2_MINT_TESTNET_GRACEFUL_MEMPOOL_PERIOD 500
// Number of blocks after ZC_SIGMA_STARTING_BLOCK during which we still accept zerocoin V2 mints to newly mined blocks.
#define ZC_V2_MINT_GRACEFUL_PERIOD 5000
#define ZC_V2_MINT_TESTNET_GRACEFUL_PERIOD 1000
// Number of blocks after ZC_SIGMA_STARTING_BLOCK during which we still accept zerocoin V2 spends into mempool.
#define ZC_V2_SPEND_GRACEFUL_MEMPOOL_PERIOD 9000
#define ZC_V2_SPEND_TESTNET_GRACEFUL_MEMPOOL_PERIOD 1500
// Number of blocks after ZC_SIGMA_STARTING_BLOCK during which we still accept zerocoin V2 spends to newly mined blocks.
#define ZC_V2_SPEND_GRACEFUL_PERIOD 10000
#define ZC_V2_SPEND_TESTNET_GRACEFUL_PERIOD 2000
#define ZC_MODULUS_V2_START_BLOCK 89300
#define ZC_MODULUS_V1_MEMPOOL_STOP_BLOCK 89500
#define ZC_MODULUS_V1_STOP_BLOCK 89800
#define ZC_MODULUS_V2_TESTNET_START_BLOCK 87000
#define ZC_MODULUS_V1_TESTNET_MEMPOOL_STOP_BLOCK 87500
#define ZC_MODULUS_V1_TESTNET_STOP_BLOCK 88000
#define ZC_MODULUS_V2_BASE_ID 1000
#define ZC_MULTIPLE_SPEND_INPUT_STARTING_BLOCK 119000
// Number of coins per id in spend v1/v1.5
#define ZC_SPEND_V1_COINSPERID 10
// Number of coins per id in spend v2.0
#define ZC_SPEND_V2_COINSPERID 10000
// limit of coins number per id in spend v3.0
#define ZC_SPEND_V3_COINSPERID_LIMIT 16000
// limit of coins number per id in Lelantus
#define ZC_LELANTUS_MAX_MINT_NUM 65000
#define ZC_LELANTUS_SET_START_SIZE 16000
// Version of index that introduced storing accumulators and coin serials
#define ZC_ADVANCED_INDEX_VERSION 130500
// Version of wallet.db entry that introduced storing extra information for mints
#define ZC_ADVANCED_WALLETDB_MINT_VERSION 130504
// Version of the block index entry that introduces Lelantus protocol
#define LELANTUS_PROTOCOL_ENABLEMENT_VERSION 140100
// Version of the block index enty that introduces evo sporks
#define EVOSPORK_MIN_VERSION 140200
// number of mint confirmations needed to spend coin
#define ZC_MINT_CONFIRMATIONS 1
// Genesis block timestamp
#define ZC_GENESIS_BLOCK_TIME 1414776286
#define SWITCH_TO_MTP_BLOCK_HEADER 1544443200 // 2018 December 10th 12:00 UTC
#define SWITCH_TO_MTP_5MIN_BLOCK 118600
// Number of zerocoin spends allowed per block and per transaction
#define ZC_SPEND_LIMIT 5
// Value of sigma spends allowed per block
#define ZC_SIGMA_VALUE_SPEND_LIMIT_PER_BLOCK (600 * COIN)
// Amount of sigma spends allowed per block
#define ZC_SIGMA_INPUT_LIMIT_PER_BLOCK 50
// Value of sigma spends allowed per transaction
#define ZC_SIGMA_VALUE_SPEND_LIMIT_PER_TRANSACTION (500 * COIN)
// Amount of sigma spends allowed per transaction
#define ZC_SIGMA_INPUT_LIMIT_PER_TRANSACTION 35
// Value of lelantus spends allowed per block
#define ZC_LELANTUS_VALUE_SPEND_LIMIT_PER_BLOCK (5100 * COIN)
// Amount of lelantus spends allowed per block
#define ZC_LELANTUS_INPUT_LIMIT_PER_BLOCK 100
// Value of lelantus spends allowed per transaction
#define ZC_LELANTUS_VALUE_SPEND_LIMIT_PER_TRANSACTION (5001 * COIN)
// Amount of lelantus spends allowed per transaction
#define ZC_LELANTUS_INPUT_LIMIT_PER_TRANSACTION 50
// Maximum amount of lelantus mint
#define ZC_LELANTUS_MAX_MINT (5001 * COIN)
// Number of zerocoin mints allowed per transaction
#define ZC_MINT_LIMIT 100
/** Maximum number of outbound peers designated as Dandelion destinations */
#define DANDELION_MAX_DESTINATIONS 2
/** Expected time between Dandelion routing shuffles (in seconds). */
#define DANDELION_SHUFFLE_INTERVAL 600
/** The minimum amount of time a Dandelion transaction is embargoed (seconds) */
#define DANDELION_EMBARGO_MINIMUM 10
#define DANDELION_TESTNET_EMBARGO_MINIMUM 1
/** The average additional embargo time beyond the minimum amount (seconds) */
#define DANDELION_EMBARGO_AVG_ADD 20
#define DANDELION_TESTNET_EMBARGO_AVG_ADD 1
/** Probability (percentage) that a Dandelion transaction enters fluff phase */
#define DANDELION_FLUFF 10
// Versions of zerocoin mint/spend transactions
#define ZEROCOIN_TX_VERSION_3 30
#define ZEROCOIN_TX_VERSION_3_1 31
#define LELANTUS_TX_VERSION_4 40
#define SIGMA_TO_LELANTUS_JOINSPLIT 41
#define LELANTUS_TX_VERSION_4_5 45
#define SIGMA_TO_LELANTUS_JOINSPLIT_FIXED 46
#define LELANTUS_TX_TPAYLOAD 47
#define SIGMA_TO_LELANTUS_TX_TPAYLOAD 48
#define ZEROCOIN_PUBLICKEY_TO_SERIALNUMBER "PUBLICKEY_TO_SERIALNUMBER"
#endif
|
354419dbad71c7e35a2c0754d93c5ef59f3e4b1e
|
3b1223e5259c580cbf107d1f45960d9f08aff27f
|
/OS2/PM/API/PMVIOP/VioShield/viosub.h
|
76addb144959e5b37b25aae57bcc6fc747761834
|
[] |
no_license
|
osfree-project/osfree
|
6be0fe3e2fb5ef577650b7a3a9eee1f38fb2eb8b
|
04ba405e346948ef0ae1a1b483aeb76f044c50a0
|
refs/heads/master
| 2023-09-02T21:38:29.849765
| 2023-08-30T05:21:33
| 2023-08-30T05:21:33
| 122,781,887
| 105
| 11
| null | 2023-01-24T08:36:57
| 2018-02-24T21:36:31
|
C
|
UTF-8
|
C
| false
| false
| 1,522
|
h
|
viosub.h
|
#ifndef _VIOSUB_H_
#define _VIOSUB_H_
#define VI_VIOGETPHYSBUF 0
#define VI_VIOGETBUF 1
#define VI_VIOSHOWBUF 2
#define VI_VIOGETCURPOS 3
#define VI_VIOGETCURTYPE 4
#define VI_VIOGETMODE 5
#define VI_VIOSETCURPOS 6
#define VI_VIOSETCURTYPE 7
#define VI_VIOSETMODE 8
#define VI_VIOREADCHARSTR 9
#define VI_VIOREADCELLSTR 10
#define VI_VIOWRTNCHAR 11
#define VI_VIOWRTNATTR 12
#define VI_VIOWRTNCELL 13
#define VI_VIOWRTCHARSTR 14
#define VI_VIOWRTCHARSTRATT 15
#define VI_VIOWRTCELLSTR 16
#define VI_VIOWRTTTY 17
#define VI_VIOSCROLLUP 18
#define VI_VIOSCROLLDN 19
#define VI_VIOSCROLLLF 20
#define VI_VIOSCROLLRT 21
#define VI_VIOSETANSI 22
#define VI_VIOGETANSI 23
#define VI_VIOPRTSC 24
#define VI_VIOSCRLOCK 25
#define VI_VIOSCRUNLOCK 26
#define VI_VIOSAVREDRAWWAIT 27
#define VI_VIOSAVREDRAWUNDO 28
#define VI_VIOPOPUP 29
#define VI_VIOENDPOPUP 30
#define VI_VIOPRTSCTOGGLE 31
#define VI_VIOMODEWAIT 32
#define VI_VIOMODEUNDO 33
#define VI_VIOGETFONT 34
#define VI_VIOGETCONFIG 35
#define VI_VIOSETCP 36
#define VI_VIOGETCP 37
#define VI_VIOSETFONT 38
#define VI_VIOGETSTATE 39
#define VI_VIOSETSTATE 40
#endif
|
a3ae954f12edde19474ba060c552b2fc05bf89c3
|
38bd665e7a80f9aa8f3acac7317c7924ed3e745a
|
/ffplay_cpp/cmdutils.c
|
49fe9f8069ba771493f5b57ce1e232dc46a47593
|
[
"BSD-3-Clause"
] |
permissive
|
MayaPosch/NymphCast
|
855cb5e05a1b979a600a8b7baf62619f4cc431dd
|
7ac8d5a86e1a1b4987092a3398d1fa1987f18eb6
|
refs/heads/master
| 2023-08-30T06:06:25.443885
| 2023-08-07T17:58:57
| 2023-08-07T17:58:57
| 169,604,606
| 2,405
| 89
|
BSD-3-Clause
| 2023-04-14T08:54:58
| 2019-02-07T16:38:44
|
C++
|
UTF-8
|
C
| false
| false
| 76,372
|
c
|
cmdutils.c
|
/*
* Various utilities for command line tools
* Copyright (c) 2000-2003 Fabrice Bellard
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <string.h>
#include <stdint.h>
#include <stdlib.h>
#include <errno.h>
#include <math.h>
/* Include only the enabled headers since some compilers (namely, Sun
Studio) will not omit unused inline functions and create undefined
references to libraries that are not being built. */
#include "config.h"
//#include "compat/va_copy.h"
#include "libavformat/avformat.h"
#include "libavfilter/avfilter.h"
#include "libavdevice/avdevice.h"
//#include "libavresample/avresample.h"
#include "libswscale/swscale.h"
#include "libswresample/swresample.h"
#include "libpostproc/postprocess.h"
#include "libavutil/attributes.h"
#include "libavutil/avassert.h"
#include "libavutil/avstring.h"
#include "libavutil/bprint.h"
#include "libavutil/display.h"
#include "libavutil/mathematics.h"
#include "libavutil/imgutils.h"
//#include "libavutil/libm.h"
#include "libavutil/parseutils.h"
#include "libavutil/pixdesc.h"
#include "libavutil/eval.h"
#include "libavutil/dict.h"
#include "libavutil/opt.h"
#include "libavutil/cpu.h"
#include "libavutil/ffversion.h"
#include "libavutil/version.h"
#include "cmdutils.h"
#if CONFIG_NETWORK
#include "libavformat/network.h"
#endif
#if HAVE_SYS_RESOURCE_H
#include <sys/time.h>
#include <sys/resource.h>
#endif
#ifdef _WIN32
#include <windows.h>
#endif
#define LIBAVRESAMPLE_VERSION_MAJOR 0
#define LIBAVRESAMPLE_VERSION_MINOR 0
#define LIBAVRESAMPLE_VERSION_MICRO 0
static int init_report(const char *env);
AVDictionary *sws_dict;
AVDictionary *swr_opts;
AVDictionary *format_opts, *codec_opts, *resample_opts;
static FILE *report_file;
static int report_file_level = AV_LOG_DEBUG;
int hide_banner = 0;
enum show_muxdemuxers {
SHOW_DEFAULT,
SHOW_DEMUXERS,
SHOW_MUXERS,
};
void init_opts(void)
{
av_dict_set(&sws_dict, "flags", "bicubic", 0);
}
void uninit_opts(void)
{
av_dict_free(&swr_opts);
av_dict_free(&sws_dict);
av_dict_free(&format_opts);
av_dict_free(&codec_opts);
av_dict_free(&resample_opts);
}
void log_callback_help(void *ptr, int level, const char *fmt, va_list vl)
{
vfprintf(stdout, fmt, vl);
}
static void log_callback_report(void *ptr, int level, const char *fmt, va_list vl)
{
va_list vl2;
char line[1024];
static int print_prefix = 1;
va_copy(vl2, vl);
av_log_default_callback(ptr, level, fmt, vl);
av_log_format_line(ptr, level, fmt, vl2, line, sizeof(line), &print_prefix);
va_end(vl2);
if (report_file_level >= level) {
fputs(line, report_file);
fflush(report_file);
}
}
void init_dynload(void)
{
#ifdef _WIN32
/* Calling SetDllDirectory with the empty string (but not NULL) removes the
* current working directory from the DLL search path as a security pre-caution. */
SetDllDirectory("");
#endif
}
static void (*program_exit)(int ret);
void register_exit(void (*cb)(int ret))
{
program_exit = cb;
}
void exit_program(int ret)
{
if (program_exit)
program_exit(ret);
exit(ret);
}
double parse_number_or_die(const char *context, const char *numstr, int type,
double min, double max)
{
char *tail;
const char *error;
double d = av_strtod(numstr, &tail);
if (*tail)
error = "Expected number for %s but found: %s\n";
else if (d < min || d > max)
error = "The value for %s was %s which is not within %f - %f\n";
else if (type == OPT_INT64 && (int64_t)d != d)
error = "Expected int64 for %s but found %s\n";
else if (type == OPT_INT && (int)d != d)
error = "Expected int for %s but found %s\n";
else
return d;
av_log(NULL, AV_LOG_FATAL, error, context, numstr, min, max);
exit_program(1);
return 0;
}
int64_t parse_time_or_die(const char *context, const char *timestr,
int is_duration)
{
int64_t us;
if (av_parse_time(&us, timestr, is_duration) < 0) {
av_log(NULL, AV_LOG_FATAL, "Invalid %s specification for %s: %s\n",
is_duration ? "duration" : "date", context, timestr);
exit_program(1);
}
return us;
}
void show_help_options(const OptionDef *options, const char *msg, int req_flags,
int rej_flags, int alt_flags)
{
const OptionDef *po;
int first;
first = 1;
for (po = options; po->name; po++) {
char buf[64];
if (((po->flags & req_flags) != req_flags) ||
(alt_flags && !(po->flags & alt_flags)) ||
(po->flags & rej_flags))
continue;
if (first) {
printf("%s\n", msg);
first = 0;
}
av_strlcpy(buf, po->name, sizeof(buf));
if (po->argname) {
av_strlcat(buf, " ", sizeof(buf));
av_strlcat(buf, po->argname, sizeof(buf));
}
printf("-%-17s %s\n", buf, po->help);
}
printf("\n");
}
void show_help_children(const AVClass *class, int flags)
{
const AVClass *child = NULL;
if (class->option) {
av_opt_show2(&class, NULL, flags, 0);
printf("\n");
}
while (child = av_opt_child_class_next(class, child))
show_help_children(child, flags);
}
static const OptionDef *find_option(const OptionDef *po, const char *name)
{
const char *p = strchr(name, ':');
int len = p ? p - name : strlen(name);
while (po->name) {
if (!strncmp(name, po->name, len) && strlen(po->name) == len)
break;
po++;
}
return po;
}
/* _WIN32 means using the windows libc - cygwin doesn't define that
* by default. HAVE_COMMANDLINETOARGVW is true on cygwin, while
* it doesn't provide the actual command line via GetCommandLineW(). */
#if HAVE_COMMANDLINETOARGVW && defined(_WIN32)
#include <shellapi.h>
/* Will be leaked on exit */
static char** win32_argv_utf8 = NULL;
static int win32_argc = 0;
/**
* Prepare command line arguments for executable.
* For Windows - perform wide-char to UTF-8 conversion.
* Input arguments should be main() function arguments.
* @param argc_ptr Arguments number (including executable)
* @param argv_ptr Arguments list.
*/
static void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
{
char *argstr_flat;
wchar_t **argv_w;
int i, buffsize = 0, offset = 0;
if (win32_argv_utf8) {
*argc_ptr = win32_argc;
*argv_ptr = win32_argv_utf8;
return;
}
win32_argc = 0;
argv_w = CommandLineToArgvW(GetCommandLineW(), &win32_argc);
if (win32_argc <= 0 || !argv_w)
return;
/* determine the UTF-8 buffer size (including NULL-termination symbols) */
for (i = 0; i < win32_argc; i++)
buffsize += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
NULL, 0, NULL, NULL);
win32_argv_utf8 = av_mallocz(sizeof(char *) * (win32_argc + 1) + buffsize);
argstr_flat = (char *)win32_argv_utf8 + sizeof(char *) * (win32_argc + 1);
if (!win32_argv_utf8) {
LocalFree(argv_w);
return;
}
for (i = 0; i < win32_argc; i++) {
win32_argv_utf8[i] = &argstr_flat[offset];
offset += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
&argstr_flat[offset],
buffsize - offset, NULL, NULL);
}
win32_argv_utf8[i] = NULL;
LocalFree(argv_w);
*argc_ptr = win32_argc;
*argv_ptr = win32_argv_utf8;
}
#else
static inline void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
{
/* nothing to do */
}
#endif /* HAVE_COMMANDLINETOARGVW */
static int write_option(void *optctx, const OptionDef *po, const char *opt,
const char *arg)
{
/* new-style options contain an offset into optctx, old-style address of
* a global var*/
void *dst = po->flags & (OPT_OFFSET | OPT_SPEC) ?
(uint8_t *)optctx + po->u.off : po->u.dst_ptr;
int *dstcount;
if (po->flags & OPT_SPEC) {
SpecifierOpt **so = dst;
char *p = strchr(opt, ':');
char *str;
dstcount = (int *)(so + 1);
*so = grow_array(*so, sizeof(**so), dstcount, *dstcount + 1);
str = av_strdup(p ? p + 1 : "");
if (!str)
return AVERROR(ENOMEM);
(*so)[*dstcount - 1].specifier = str;
dst = &(*so)[*dstcount - 1].u;
}
if (po->flags & OPT_STRING) {
char *str;
str = av_strdup(arg);
av_freep(dst);
if (!str)
return AVERROR(ENOMEM);
*(char **)dst = str;
} else if (po->flags & OPT_BOOL || po->flags & OPT_INT) {
*(int *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);
} else if (po->flags & OPT_INT64) {
*(int64_t *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT64_MIN, INT64_MAX);
} else if (po->flags & OPT_TIME) {
*(int64_t *)dst = parse_time_or_die(opt, arg, 1);
} else if (po->flags & OPT_FLOAT) {
*(float *)dst = parse_number_or_die(opt, arg, OPT_FLOAT, -INFINITY, INFINITY);
} else if (po->flags & OPT_DOUBLE) {
*(double *)dst = parse_number_or_die(opt, arg, OPT_DOUBLE, -INFINITY, INFINITY);
} else if (po->u.func_arg) {
int ret = po->u.func_arg(optctx, opt, arg);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR,
"Failed to set value '%s' for option '%s': %s\n",
arg, opt, av_err2str(ret));
return ret;
}
}
if (po->flags & OPT_EXIT)
exit_program(0);
return 0;
}
int parse_option(void *optctx, const char *opt, const char *arg,
const OptionDef *options)
{
const OptionDef *po;
int ret;
po = find_option(options, opt);
if (!po->name && opt[0] == 'n' && opt[1] == 'o') {
/* handle 'no' bool option */
po = find_option(options, opt + 2);
if ((po->name && (po->flags & OPT_BOOL)))
arg = "0";
} else if (po->flags & OPT_BOOL)
arg = "1";
if (!po->name)
po = find_option(options, "default");
if (!po->name) {
av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
return AVERROR(EINVAL);
}
if (po->flags & HAS_ARG && !arg) {
av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'\n", opt);
return AVERROR(EINVAL);
}
ret = write_option(optctx, po, opt, arg);
if (ret < 0)
return ret;
return !!(po->flags & HAS_ARG);
}
void parse_options(void *optctx, int argc, char **argv, const OptionDef *options,
void (*parse_arg_function)(void *, const char*))
{
const char *opt;
int optindex, handleoptions = 1, ret;
/* perform system-dependent conversions for arguments list */
prepare_app_arguments(&argc, &argv);
/* parse options */
optindex = 1;
while (optindex < argc) {
opt = argv[optindex++];
if (handleoptions && opt[0] == '-' && opt[1] != '\0') {
if (opt[1] == '-' && opt[2] == '\0') {
handleoptions = 0;
continue;
}
opt++;
if ((ret = parse_option(optctx, opt, argv[optindex], options)) < 0)
exit_program(1);
optindex += ret;
} else {
if (parse_arg_function)
parse_arg_function(optctx, opt);
}
}
}
int parse_optgroup(void *optctx, OptionGroup *g)
{
int i, ret;
av_log(NULL, AV_LOG_DEBUG, "Parsing a group of options: %s %s.\n",
g->group_def->name, g->arg);
for (i = 0; i < g->nb_opts; i++) {
Option *o = &g->opts[i];
if (g->group_def->flags &&
!(g->group_def->flags & o->opt->flags)) {
av_log(NULL, AV_LOG_ERROR, "Option %s (%s) cannot be applied to "
"%s %s -- you are trying to apply an input option to an "
"output file or vice versa. Move this option before the "
"file it belongs to.\n", o->key, o->opt->help,
g->group_def->name, g->arg);
return AVERROR(EINVAL);
}
av_log(NULL, AV_LOG_DEBUG, "Applying option %s (%s) with argument %s.\n",
o->key, o->opt->help, o->val);
ret = write_option(optctx, o->opt, o->key, o->val);
if (ret < 0)
return ret;
}
av_log(NULL, AV_LOG_DEBUG, "Successfully parsed a group of options.\n");
return 0;
}
int locate_option(int argc, char **argv, const OptionDef *options,
const char *optname)
{
const OptionDef *po;
int i;
for (i = 1; i < argc; i++) {
const char *cur_opt = argv[i];
if (*cur_opt++ != '-')
continue;
po = find_option(options, cur_opt);
if (!po->name && cur_opt[0] == 'n' && cur_opt[1] == 'o')
po = find_option(options, cur_opt + 2);
if ((!po->name && !strcmp(cur_opt, optname)) ||
(po->name && !strcmp(optname, po->name)))
return i;
if (!po->name || po->flags & HAS_ARG)
i++;
}
return 0;
}
static void dump_argument(const char *a)
{
const unsigned char *p;
for (p = a; *p; p++)
if (!((*p >= '+' && *p <= ':') || (*p >= '@' && *p <= 'Z') ||
*p == '_' || (*p >= 'a' && *p <= 'z')))
break;
if (!*p) {
fputs(a, report_file);
return;
}
fputc('"', report_file);
for (p = a; *p; p++) {
if (*p == '\\' || *p == '"' || *p == '$' || *p == '`')
fprintf(report_file, "\\%c", *p);
else if (*p < ' ' || *p > '~')
fprintf(report_file, "\\x%02x", *p);
else
fputc(*p, report_file);
}
fputc('"', report_file);
}
static void check_options(const OptionDef *po)
{
while (po->name) {
if (po->flags & OPT_PERFILE)
av_assert0(po->flags & (OPT_INPUT | OPT_OUTPUT));
po++;
}
}
void parse_loglevel(int argc, char **argv, const OptionDef *options)
{
int idx = locate_option(argc, argv, options, "loglevel");
const char *env;
check_options(options);
if (!idx)
idx = locate_option(argc, argv, options, "v");
if (idx && argv[idx + 1])
opt_loglevel(NULL, "loglevel", argv[idx + 1]);
idx = locate_option(argc, argv, options, "report");
if ((env = getenv("FFREPORT")) || idx) {
init_report(env);
if (report_file) {
int i;
fprintf(report_file, "Command line:\n");
for (i = 0; i < argc; i++) {
dump_argument(argv[i]);
fputc(i < argc - 1 ? ' ' : '\n', report_file);
}
fflush(report_file);
}
}
idx = locate_option(argc, argv, options, "hide_banner");
if (idx)
hide_banner = 1;
}
static const AVOption *opt_find(void *obj, const char *name, const char *unit,
int opt_flags, int search_flags)
{
const AVOption *o = av_opt_find(obj, name, unit, opt_flags, search_flags);
if(o && !o->flags)
return NULL;
return o;
}
#define FLAGS (o->type == AV_OPT_TYPE_FLAGS && (arg[0]=='-' || arg[0]=='+')) ? AV_DICT_APPEND : 0
int opt_default(void *optctx, const char *opt, const char *arg)
{
const AVOption *o;
int consumed = 0;
char opt_stripped[128];
const char *p;
const AVClass *cc = avcodec_get_class(), *fc = avformat_get_class();
#if CONFIG_AVRESAMPLE
const AVClass *rc = avresample_get_class();
#endif
#if CONFIG_SWSCALE
const AVClass *sc = sws_get_class();
#endif
#if CONFIG_SWRESAMPLE
const AVClass *swr_class = swr_get_class();
#endif
if (!strcmp(opt, "debug") || !strcmp(opt, "fdebug"))
av_log_set_level(AV_LOG_DEBUG);
if (!(p = strchr(opt, ':')))
p = opt + strlen(opt);
av_strlcpy(opt_stripped, opt, FFMIN(sizeof(opt_stripped), p - opt + 1));
if ((o = opt_find(&cc, opt_stripped, NULL, 0,
AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) ||
((opt[0] == 'v' || opt[0] == 'a' || opt[0] == 's') &&
(o = opt_find(&cc, opt + 1, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ)))) {
av_dict_set(&codec_opts, opt, arg, FLAGS);
consumed = 1;
}
if ((o = opt_find(&fc, opt, NULL, 0,
AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
av_dict_set(&format_opts, opt, arg, FLAGS);
if (consumed)
av_log(NULL, AV_LOG_VERBOSE, "Routing option %s to both codec and muxer layer\n", opt);
consumed = 1;
}
#if CONFIG_SWSCALE
if (!consumed && (o = opt_find(&sc, opt, NULL, 0,
AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
struct SwsContext *sws = sws_alloc_context();
int ret = av_opt_set(sws, opt, arg, 0);
sws_freeContext(sws);
if (!strcmp(opt, "srcw") || !strcmp(opt, "srch") ||
!strcmp(opt, "dstw") || !strcmp(opt, "dsth") ||
!strcmp(opt, "src_format") || !strcmp(opt, "dst_format")) {
av_log(NULL, AV_LOG_ERROR, "Directly using swscale dimensions/format options is not supported, please use the -s or -pix_fmt options\n");
return AVERROR(EINVAL);
}
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);
return ret;
}
av_dict_set(&sws_dict, opt, arg, FLAGS);
consumed = 1;
}
#else
if (!consumed && !strcmp(opt, "sws_flags")) {
av_log(NULL, AV_LOG_WARNING, "Ignoring %s %s, due to disabled swscale\n", opt, arg);
consumed = 1;
}
#endif
#if CONFIG_SWRESAMPLE
if (!consumed && (o=opt_find(&swr_class, opt, NULL, 0,
AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
struct SwrContext *swr = swr_alloc();
int ret = av_opt_set(swr, opt, arg, 0);
swr_free(&swr);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);
return ret;
}
av_dict_set(&swr_opts, opt, arg, FLAGS);
consumed = 1;
}
#endif
#if CONFIG_AVRESAMPLE
if ((o=opt_find(&rc, opt, NULL, 0,
AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
av_dict_set(&resample_opts, opt, arg, FLAGS);
consumed = 1;
}
#endif
if (consumed)
return 0;
return AVERROR_OPTION_NOT_FOUND;
}
/*
* Check whether given option is a group separator.
*
* @return index of the group definition that matched or -1 if none
*/
static int match_group_separator(const OptionGroupDef *groups, int nb_groups,
const char *opt)
{
int i;
for (i = 0; i < nb_groups; i++) {
const OptionGroupDef *p = &groups[i];
if (p->sep && !strcmp(p->sep, opt))
return i;
}
return -1;
}
/*
* Finish parsing an option group.
*
* @param group_idx which group definition should this group belong to
* @param arg argument of the group delimiting option
*/
static void finish_group(OptionParseContext *octx, int group_idx,
const char *arg)
{
OptionGroupList *l = &octx->groups[group_idx];
OptionGroup *g;
//l->groups = grow_array(l->groups, sizeof(*l->groups), &l->nb_groups, l->nb_groups + 1);
GROW_ARRAY(l->groups, l->nb_groups);
g = &l->groups[l->nb_groups - 1];
*g = octx->cur_group;
g->arg = arg;
g->group_def = l->group_def;
g->sws_dict = sws_dict;
g->swr_opts = swr_opts;
g->codec_opts = codec_opts;
g->format_opts = format_opts;
g->resample_opts = resample_opts;
codec_opts = NULL;
format_opts = NULL;
resample_opts = NULL;
sws_dict = NULL;
swr_opts = NULL;
init_opts();
memset(&octx->cur_group, 0, sizeof(octx->cur_group));
}
/*
* Add an option instance to currently parsed group.
*/
static void add_opt(OptionParseContext *octx, const OptionDef *opt,
const char *key, const char *val)
{
int global = !(opt->flags & (OPT_PERFILE | OPT_SPEC | OPT_OFFSET));
OptionGroup *g = global ? &octx->global_opts : &octx->cur_group;
//g->opts = grow_array(g->opts, sizeof(*g->opts), &g->nb_opts, g->nb_opts + 1);
GROW_ARRAY(g->opts, g->nb_opts);
g->opts[g->nb_opts - 1].opt = opt;
g->opts[g->nb_opts - 1].key = key;
g->opts[g->nb_opts - 1].val = val;
}
static void init_parse_context(OptionParseContext *octx,
const OptionGroupDef *groups, int nb_groups)
{
static const OptionGroupDef global_group = { "global" };
int i;
memset(octx, 0, sizeof(*octx));
octx->nb_groups = nb_groups;
octx->groups = av_mallocz_array(octx->nb_groups, sizeof(*octx->groups));
if (!octx->groups)
exit_program(1);
for (i = 0; i < octx->nb_groups; i++)
octx->groups[i].group_def = &groups[i];
octx->global_opts.group_def = &global_group;
octx->global_opts.arg = "";
init_opts();
}
void uninit_parse_context(OptionParseContext *octx)
{
int i, j;
for (i = 0; i < octx->nb_groups; i++) {
OptionGroupList *l = &octx->groups[i];
for (j = 0; j < l->nb_groups; j++) {
av_freep(&l->groups[j].opts);
av_dict_free(&l->groups[j].codec_opts);
av_dict_free(&l->groups[j].format_opts);
av_dict_free(&l->groups[j].resample_opts);
av_dict_free(&l->groups[j].sws_dict);
av_dict_free(&l->groups[j].swr_opts);
}
av_freep(&l->groups);
}
av_freep(&octx->groups);
av_freep(&octx->cur_group.opts);
av_freep(&octx->global_opts.opts);
uninit_opts();
}
int split_commandline(OptionParseContext *octx, int argc, char *argv[],
const OptionDef *options,
const OptionGroupDef *groups, int nb_groups)
{
int optindex = 1;
int dashdash = -2;
/* perform system-dependent conversions for arguments list */
prepare_app_arguments(&argc, &argv);
init_parse_context(octx, groups, nb_groups);
av_log(NULL, AV_LOG_DEBUG, "Splitting the commandline.\n");
while (optindex < argc) {
const char *opt = argv[optindex++], *arg;
const OptionDef *po;
int ret;
av_log(NULL, AV_LOG_DEBUG, "Reading option '%s' ...", opt);
if (opt[0] == '-' && opt[1] == '-' && !opt[2]) {
dashdash = optindex;
continue;
}
/* unnamed group separators, e.g. output filename */
if (opt[0] != '-' || !opt[1] || dashdash+1 == optindex) {
finish_group(octx, 0, opt);
av_log(NULL, AV_LOG_DEBUG, " matched as %s.\n", groups[0].name);
continue;
}
opt++;
#define GET_ARG(arg) \
do { \
arg = argv[optindex++]; \
if (!arg) { \
av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'.\n", opt);\
return AVERROR(EINVAL); \
} \
} while (0)
/* named group separators, e.g. -i */
if ((ret = match_group_separator(groups, nb_groups, opt)) >= 0) {
GET_ARG(arg);
finish_group(octx, ret, arg);
av_log(NULL, AV_LOG_DEBUG, " matched as %s with argument '%s'.\n",
groups[ret].name, arg);
continue;
}
/* normal options */
po = find_option(options, opt);
if (po->name) {
if (po->flags & OPT_EXIT) {
/* optional argument, e.g. -h */
arg = argv[optindex++];
} else if (po->flags & HAS_ARG) {
GET_ARG(arg);
} else {
arg = "1";
}
add_opt(octx, po, opt, arg);
av_log(NULL, AV_LOG_DEBUG, " matched as option '%s' (%s) with "
"argument '%s'.\n", po->name, po->help, arg);
continue;
}
/* AVOptions */
if (argv[optindex]) {
ret = opt_default(NULL, opt, argv[optindex]);
if (ret >= 0) {
av_log(NULL, AV_LOG_DEBUG, " matched as AVOption '%s' with "
"argument '%s'.\n", opt, argv[optindex]);
optindex++;
continue;
} else if (ret != AVERROR_OPTION_NOT_FOUND) {
av_log(NULL, AV_LOG_ERROR, "Error parsing option '%s' "
"with argument '%s'.\n", opt, argv[optindex]);
return ret;
}
}
/* boolean -nofoo options */
if (opt[0] == 'n' && opt[1] == 'o' &&
(po = find_option(options, opt + 2)) &&
po->name && po->flags & OPT_BOOL) {
add_opt(octx, po, opt, "0");
av_log(NULL, AV_LOG_DEBUG, " matched as option '%s' (%s) with "
"argument 0.\n", po->name, po->help);
continue;
}
av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'.\n", opt);
return AVERROR_OPTION_NOT_FOUND;
}
if (octx->cur_group.nb_opts || codec_opts || format_opts || resample_opts)
av_log(NULL, AV_LOG_WARNING, "Trailing option(s) found in the "
"command: may be ignored.\n");
av_log(NULL, AV_LOG_DEBUG, "Finished splitting the commandline.\n");
return 0;
}
int opt_cpuflags(void *optctx, const char *opt, const char *arg)
{
int ret;
unsigned flags = av_get_cpu_flags();
if ((ret = av_parse_cpu_caps(&flags, arg)) < 0)
return ret;
av_force_cpu_flags(flags);
return 0;
}
int opt_loglevel(void *optctx, const char *opt, const char *arg)
{
const struct { const char *name; int level; } log_levels[] = {
{ "quiet" , AV_LOG_QUIET },
{ "panic" , AV_LOG_PANIC },
{ "fatal" , AV_LOG_FATAL },
{ "error" , AV_LOG_ERROR },
{ "warning", AV_LOG_WARNING },
{ "info" , AV_LOG_INFO },
{ "verbose", AV_LOG_VERBOSE },
{ "debug" , AV_LOG_DEBUG },
{ "trace" , AV_LOG_TRACE },
};
const char *token;
char *tail;
int flags = av_log_get_flags();
int level = av_log_get_level();
int cmd, i = 0;
av_assert0(arg);
while (*arg) {
token = arg;
if (*token == '+' || *token == '-') {
cmd = *token++;
} else {
cmd = 0;
}
if (!i && !cmd) {
flags = 0; /* missing relative prefix, build absolute value */
}
if (!strncmp(token, "repeat", 6)) {
if (cmd == '-') {
flags |= AV_LOG_SKIP_REPEATED;
} else {
flags &= ~AV_LOG_SKIP_REPEATED;
}
arg = token + 6;
} else if (!strncmp(token, "level", 5)) {
if (cmd == '-') {
flags &= ~AV_LOG_PRINT_LEVEL;
} else {
flags |= AV_LOG_PRINT_LEVEL;
}
arg = token + 5;
} else {
break;
}
i++;
}
if (!*arg) {
goto end;
} else if (*arg == '+') {
arg++;
} else if (!i) {
flags = av_log_get_flags(); /* level value without prefix, reset flags */
}
for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++) {
if (!strcmp(log_levels[i].name, arg)) {
level = log_levels[i].level;
goto end;
}
}
level = strtol(arg, &tail, 10);
if (*tail) {
av_log(NULL, AV_LOG_FATAL, "Invalid loglevel \"%s\". "
"Possible levels are numbers or:\n", arg);
for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++)
av_log(NULL, AV_LOG_FATAL, "\"%s\"\n", log_levels[i].name);
exit_program(1);
}
end:
av_log_set_flags(flags);
av_log_set_level(level);
return 0;
}
static void expand_filename_template(AVBPrint *bp, const char *template,
struct tm *tm)
{
int c;
while ((c = *(template++))) {
if (c == '%') {
if (!(c = *(template++)))
break;
switch (c) {
case 'p':
av_bprintf(bp, "%s", program_name);
break;
case 't':
av_bprintf(bp, "%04d%02d%02d-%02d%02d%02d",
tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
tm->tm_hour, tm->tm_min, tm->tm_sec);
break;
case '%':
av_bprint_chars(bp, c, 1);
break;
}
} else {
av_bprint_chars(bp, c, 1);
}
}
}
static int init_report(const char *env)
{
char *filename_template = NULL;
char *key, *val;
int ret, count = 0;
int prog_loglevel, envlevel = 0;
time_t now;
struct tm *tm;
AVBPrint filename;
if (report_file) /* already opened */
return 0;
time(&now);
tm = localtime(&now);
while (env && *env) {
if ((ret = av_opt_get_key_value(&env, "=", ":", 0, &key, &val)) < 0) {
if (count)
av_log(NULL, AV_LOG_ERROR,
"Failed to parse FFREPORT environment variable: %s\n",
av_err2str(ret));
break;
}
if (*env)
env++;
count++;
if (!strcmp(key, "file")) {
av_free(filename_template);
filename_template = val;
val = NULL;
} else if (!strcmp(key, "level")) {
char *tail;
report_file_level = strtol(val, &tail, 10);
if (*tail) {
av_log(NULL, AV_LOG_FATAL, "Invalid report file level\n");
exit_program(1);
}
envlevel = 1;
} else {
av_log(NULL, AV_LOG_ERROR, "Unknown key '%s' in FFREPORT\n", key);
}
av_free(val);
av_free(key);
}
av_bprint_init(&filename, 0, AV_BPRINT_SIZE_AUTOMATIC);
expand_filename_template(&filename,
av_x_if_null(filename_template, "%p-%t.log"), tm);
av_free(filename_template);
if (!av_bprint_is_complete(&filename)) {
av_log(NULL, AV_LOG_ERROR, "Out of memory building report file name\n");
return AVERROR(ENOMEM);
}
prog_loglevel = av_log_get_level();
if (!envlevel)
report_file_level = FFMAX(report_file_level, prog_loglevel);
report_file = fopen(filename.str, "w");
if (!report_file) {
int ret = AVERROR(errno);
av_log(NULL, AV_LOG_ERROR, "Failed to open report \"%s\": %s\n",
filename.str, strerror(errno));
return ret;
}
av_log_set_callback(log_callback_report);
av_log(NULL, AV_LOG_INFO,
"%s started on %04d-%02d-%02d at %02d:%02d:%02d\n"
"Report written to \"%s\"\n"
"Log level: %d\n",
program_name,
tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
tm->tm_hour, tm->tm_min, tm->tm_sec,
filename.str, report_file_level);
av_bprint_finalize(&filename, NULL);
return 0;
}
int opt_report(void *optctx, const char *opt, const char *arg)
{
return init_report(NULL);
}
int opt_max_alloc(void *optctx, const char *opt, const char *arg)
{
char *tail;
size_t max;
max = strtol(arg, &tail, 10);
if (*tail) {
av_log(NULL, AV_LOG_FATAL, "Invalid max_alloc \"%s\".\n", arg);
exit_program(1);
}
av_max_alloc(max);
return 0;
}
int opt_timelimit(void *optctx, const char *opt, const char *arg)
{
#if HAVE_SETRLIMIT
int lim = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
struct rlimit rl = { lim, lim + 1 };
if (setrlimit(RLIMIT_CPU, &rl))
perror("setrlimit");
#else
av_log(NULL, AV_LOG_WARNING, "-%s not implemented on this OS\n", opt);
#endif
return 0;
}
void print_error(const char *filename, int err)
{
char errbuf[128];
const char *errbuf_ptr = errbuf;
if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
errbuf_ptr = strerror(AVUNERROR(err));
av_log(NULL, AV_LOG_ERROR, "%s: %s\n", filename, errbuf_ptr);
}
static int warned_cfg = 0;
#define INDENT 1
#define SHOW_VERSION 2
#define SHOW_CONFIG 4
#define SHOW_COPYRIGHT 8
#define PRINT_LIB_INFO(libname, LIBNAME, flags, level) \
if (CONFIG_##LIBNAME) { \
const char *indent = flags & INDENT? " " : ""; \
if (flags & SHOW_VERSION) { \
unsigned int version = libname##_version(); \
av_log(NULL, level, \
"%slib%-11s %2d.%3d.%3d / %2d.%3d.%3d\n", \
indent, #libname, \
LIB##LIBNAME##_VERSION_MAJOR, \
LIB##LIBNAME##_VERSION_MINOR, \
LIB##LIBNAME##_VERSION_MICRO, \
AV_VERSION_MAJOR(version), AV_VERSION_MINOR(version),\
AV_VERSION_MICRO(version)); \
} \
if (flags & SHOW_CONFIG) { \
const char *cfg = libname##_configuration(); \
if (strcmp(FFMPEG_CONFIGURATION, cfg)) { \
if (!warned_cfg) { \
av_log(NULL, level, \
"%sWARNING: library configuration mismatch\n", \
indent); \
warned_cfg = 1; \
} \
av_log(NULL, level, "%s%-11s configuration: %s\n", \
indent, #libname, cfg); \
} \
} \
} \
static void print_all_libs_info(int flags, int level)
{
PRINT_LIB_INFO(avutil, AVUTIL, flags, level);
PRINT_LIB_INFO(avcodec, AVCODEC, flags, level);
PRINT_LIB_INFO(avformat, AVFORMAT, flags, level);
PRINT_LIB_INFO(avdevice, AVDEVICE, flags, level);
PRINT_LIB_INFO(avfilter, AVFILTER, flags, level);
PRINT_LIB_INFO(avresample, AVRESAMPLE, flags, level);
PRINT_LIB_INFO(swscale, SWSCALE, flags, level);
PRINT_LIB_INFO(swresample, SWRESAMPLE, flags, level);
PRINT_LIB_INFO(postproc, POSTPROC, flags, level);
}
static void print_program_info(int flags, int level)
{
const char *indent = flags & INDENT? " " : "";
av_log(NULL, level, "%s version " FFMPEG_VERSION, program_name);
if (flags & SHOW_COPYRIGHT)
av_log(NULL, level, " Copyright (c) %d-%d the FFmpeg developers",
program_birth_year, CONFIG_THIS_YEAR);
av_log(NULL, level, "\n");
av_log(NULL, level, "%sbuilt with %s\n", indent, CC_IDENT);
av_log(NULL, level, "%sconfiguration: " FFMPEG_CONFIGURATION "\n", indent);
}
static void print_buildconf(int flags, int level)
{
const char *indent = flags & INDENT ? " " : "";
char str[] = { FFMPEG_CONFIGURATION };
char *conflist, *remove_tilde, *splitconf;
// Change all the ' --' strings to '~--' so that
// they can be identified as tokens.
while ((conflist = strstr(str, " --")) != NULL) {
strncpy(conflist, "~--", 3);
}
// Compensate for the weirdness this would cause
// when passing 'pkg-config --static'.
while ((remove_tilde = strstr(str, "pkg-config~")) != NULL) {
strncpy(remove_tilde, "pkg-config ", 11);
}
splitconf = strtok(str, "~");
av_log(NULL, level, "\n%sconfiguration:\n", indent);
while (splitconf != NULL) {
av_log(NULL, level, "%s%s%s\n", indent, indent, splitconf);
splitconf = strtok(NULL, "~");
}
}
void show_banner(int argc, char **argv, const OptionDef *options)
{
int idx = locate_option(argc, argv, options, "version");
if (hide_banner || idx)
return;
print_program_info (INDENT|SHOW_COPYRIGHT, AV_LOG_INFO);
print_all_libs_info(INDENT|SHOW_CONFIG, AV_LOG_INFO);
print_all_libs_info(INDENT|SHOW_VERSION, AV_LOG_INFO);
}
int show_version(void *optctx, const char *opt, const char *arg)
{
av_log_set_callback(log_callback_help);
print_program_info (SHOW_COPYRIGHT, AV_LOG_INFO);
print_all_libs_info(SHOW_VERSION, AV_LOG_INFO);
return 0;
}
int show_buildconf(void *optctx, const char *opt, const char *arg)
{
av_log_set_callback(log_callback_help);
print_buildconf (INDENT|0, AV_LOG_INFO);
return 0;
}
int show_license(void *optctx, const char *opt, const char *arg)
{
#if CONFIG_NONFREE
printf(
"This version of %s has nonfree parts compiled in.\n"
"Therefore it is not legally redistributable.\n",
program_name );
#elif CONFIG_GPLV3
printf(
"%s is free software; you can redistribute it and/or modify\n"
"it under the terms of the GNU General Public License as published by\n"
"the Free Software Foundation; either version 3 of the License, or\n"
"(at your option) any later version.\n"
"\n"
"%s is distributed in the hope that it will be useful,\n"
"but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
"GNU General Public License for more details.\n"
"\n"
"You should have received a copy of the GNU General Public License\n"
"along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
program_name, program_name, program_name );
#elif CONFIG_GPL
printf(
"%s is free software; you can redistribute it and/or modify\n"
"it under the terms of the GNU General Public License as published by\n"
"the Free Software Foundation; either version 2 of the License, or\n"
"(at your option) any later version.\n"
"\n"
"%s is distributed in the hope that it will be useful,\n"
"but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
"GNU General Public License for more details.\n"
"\n"
"You should have received a copy of the GNU General Public License\n"
"along with %s; if not, write to the Free Software\n"
"Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
program_name, program_name, program_name );
#elif CONFIG_LGPLV3
printf(
"%s is free software; you can redistribute it and/or modify\n"
"it under the terms of the GNU Lesser General Public License as published by\n"
"the Free Software Foundation; either version 3 of the License, or\n"
"(at your option) any later version.\n"
"\n"
"%s is distributed in the hope that it will be useful,\n"
"but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
"GNU Lesser General Public License for more details.\n"
"\n"
"You should have received a copy of the GNU Lesser General Public License\n"
"along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
program_name, program_name, program_name );
#else
printf(
"%s is free software; you can redistribute it and/or\n"
"modify it under the terms of the GNU Lesser General Public\n"
"License as published by the Free Software Foundation; either\n"
"version 2.1 of the License, or (at your option) any later version.\n"
"\n"
"%s is distributed in the hope that it will be useful,\n"
"but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
"Lesser General Public License for more details.\n"
"\n"
"You should have received a copy of the GNU Lesser General Public\n"
"License along with %s; if not, write to the Free Software\n"
"Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
program_name, program_name, program_name );
#endif
return 0;
}
static int is_device(const AVClass *avclass)
{
if (!avclass)
return 0;
return AV_IS_INPUT_DEVICE(avclass->category) || AV_IS_OUTPUT_DEVICE(avclass->category);
}
static int show_formats_devices(void *optctx, const char *opt, const char *arg, int device_only, int muxdemuxers)
{
void *ifmt_opaque = NULL;
const AVInputFormat *ifmt = NULL;
void *ofmt_opaque = NULL;
const AVOutputFormat *ofmt = NULL;
const char *last_name;
int is_dev;
printf("%s\n"
" D. = Demuxing supported\n"
" .E = Muxing supported\n"
" --\n", device_only ? "Devices:" : "File formats:");
last_name = "000";
for (;;) {
int decode = 0;
int encode = 0;
const char *name = NULL;
const char *long_name = NULL;
if (muxdemuxers !=SHOW_DEMUXERS) {
ofmt_opaque = NULL;
while ((ofmt = av_muxer_iterate(&ofmt_opaque))) {
is_dev = is_device(ofmt->priv_class);
if (!is_dev && device_only)
continue;
if ((!name || strcmp(ofmt->name, name) < 0) &&
strcmp(ofmt->name, last_name) > 0) {
name = ofmt->name;
long_name = ofmt->long_name;
encode = 1;
}
}
}
if (muxdemuxers != SHOW_MUXERS) {
ifmt_opaque = NULL;
while ((ifmt = av_demuxer_iterate(&ifmt_opaque))) {
is_dev = is_device(ifmt->priv_class);
if (!is_dev && device_only)
continue;
if ((!name || strcmp(ifmt->name, name) < 0) &&
strcmp(ifmt->name, last_name) > 0) {
name = ifmt->name;
long_name = ifmt->long_name;
encode = 0;
}
if (name && strcmp(ifmt->name, name) == 0)
decode = 1;
}
}
if (!name)
break;
last_name = name;
printf(" %s%s %-15s %s\n",
decode ? "D" : " ",
encode ? "E" : " ",
name,
long_name ? long_name:" ");
}
return 0;
}
int show_formats(void *optctx, const char *opt, const char *arg)
{
return show_formats_devices(optctx, opt, arg, 0, SHOW_DEFAULT);
}
int show_muxers(void *optctx, const char *opt, const char *arg)
{
return show_formats_devices(optctx, opt, arg, 0, SHOW_MUXERS);
}
int show_demuxers(void *optctx, const char *opt, const char *arg)
{
return show_formats_devices(optctx, opt, arg, 0, SHOW_DEMUXERS);
}
int show_devices(void *optctx, const char *opt, const char *arg)
{
return show_formats_devices(optctx, opt, arg, 1, SHOW_DEFAULT);
}
#define PRINT_CODEC_SUPPORTED(codec, field, type, list_name, term, get_name) \
if (codec->field) { \
const type *p = codec->field; \
\
printf(" Supported " list_name ":"); \
while (*p != term) { \
get_name(*p); \
printf(" %s", name); \
p++; \
} \
printf("\n"); \
} \
static void print_codec(const AVCodec *c)
{
int encoder = av_codec_is_encoder(c);
printf("%s %s [%s]:\n", encoder ? "Encoder" : "Decoder", c->name,
c->long_name ? c->long_name : "");
printf(" General capabilities: ");
if (c->capabilities & AV_CODEC_CAP_DRAW_HORIZ_BAND)
printf("horizband ");
if (c->capabilities & AV_CODEC_CAP_DR1)
printf("dr1 ");
if (c->capabilities & AV_CODEC_CAP_TRUNCATED)
printf("trunc ");
if (c->capabilities & AV_CODEC_CAP_DELAY)
printf("delay ");
if (c->capabilities & AV_CODEC_CAP_SMALL_LAST_FRAME)
printf("small ");
if (c->capabilities & AV_CODEC_CAP_SUBFRAMES)
printf("subframes ");
if (c->capabilities & AV_CODEC_CAP_EXPERIMENTAL)
printf("exp ");
if (c->capabilities & AV_CODEC_CAP_CHANNEL_CONF)
printf("chconf ");
if (c->capabilities & AV_CODEC_CAP_PARAM_CHANGE)
printf("paramchange ");
if (c->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE)
printf("variable ");
if (c->capabilities & (AV_CODEC_CAP_FRAME_THREADS |
AV_CODEC_CAP_SLICE_THREADS |
AV_CODEC_CAP_AUTO_THREADS))
printf("threads ");
if (c->capabilities & AV_CODEC_CAP_AVOID_PROBING)
printf("avoidprobe ");
if (c->capabilities & AV_CODEC_CAP_INTRA_ONLY)
printf("intraonly ");
if (c->capabilities & AV_CODEC_CAP_LOSSLESS)
printf("lossless ");
if (c->capabilities & AV_CODEC_CAP_HARDWARE)
printf("hardware ");
if (c->capabilities & AV_CODEC_CAP_HYBRID)
printf("hybrid ");
if (!c->capabilities)
printf("none");
printf("\n");
if (c->type == AVMEDIA_TYPE_VIDEO ||
c->type == AVMEDIA_TYPE_AUDIO) {
printf(" Threading capabilities: ");
switch (c->capabilities & (AV_CODEC_CAP_FRAME_THREADS |
AV_CODEC_CAP_SLICE_THREADS |
AV_CODEC_CAP_AUTO_THREADS)) {
case AV_CODEC_CAP_FRAME_THREADS |
AV_CODEC_CAP_SLICE_THREADS: printf("frame and slice"); break;
case AV_CODEC_CAP_FRAME_THREADS: printf("frame"); break;
case AV_CODEC_CAP_SLICE_THREADS: printf("slice"); break;
case AV_CODEC_CAP_AUTO_THREADS : printf("auto"); break;
default: printf("none"); break;
}
printf("\n");
}
if (avcodec_get_hw_config(c, 0)) {
printf(" Supported hardware devices: ");
for (int i = 0;; i++) {
const AVCodecHWConfig *config = avcodec_get_hw_config(c, i);
if (!config)
break;
printf("%s ", av_hwdevice_get_type_name(config->device_type));
}
printf("\n");
}
if (c->supported_framerates) {
const AVRational *fps = c->supported_framerates;
printf(" Supported framerates:");
while (fps->num) {
printf(" %d/%d", fps->num, fps->den);
fps++;
}
printf("\n");
}
PRINT_CODEC_SUPPORTED(c, pix_fmts, enum AVPixelFormat, "pixel formats",
AV_PIX_FMT_NONE, GET_PIX_FMT_NAME);
PRINT_CODEC_SUPPORTED(c, supported_samplerates, int, "sample rates", 0,
GET_SAMPLE_RATE_NAME);
PRINT_CODEC_SUPPORTED(c, sample_fmts, enum AVSampleFormat, "sample formats",
AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME);
PRINT_CODEC_SUPPORTED(c, channel_layouts, uint64_t, "channel layouts",
0, GET_CH_LAYOUT_DESC);
if (c->priv_class) {
show_help_children(c->priv_class,
AV_OPT_FLAG_ENCODING_PARAM |
AV_OPT_FLAG_DECODING_PARAM);
}
}
static char get_media_type_char(enum AVMediaType type)
{
switch (type) {
case AVMEDIA_TYPE_VIDEO: return 'V';
case AVMEDIA_TYPE_AUDIO: return 'A';
case AVMEDIA_TYPE_DATA: return 'D';
case AVMEDIA_TYPE_SUBTITLE: return 'S';
case AVMEDIA_TYPE_ATTACHMENT:return 'T';
default: return '?';
}
}
static const AVCodec *next_codec_for_id(enum AVCodecID id, const AVCodec *prev,
int encoder)
{
while ((prev = av_codec_next(prev))) {
if (prev->id == id &&
(encoder ? av_codec_is_encoder(prev) : av_codec_is_decoder(prev)))
return prev;
}
return NULL;
}
static int compare_codec_desc(const void *a, const void *b)
{
const AVCodecDescriptor * const *da = a;
const AVCodecDescriptor * const *db = b;
return (*da)->type != (*db)->type ? FFDIFFSIGN((*da)->type, (*db)->type) :
strcmp((*da)->name, (*db)->name);
}
static unsigned get_codecs_sorted(const AVCodecDescriptor ***rcodecs)
{
const AVCodecDescriptor *desc = NULL;
const AVCodecDescriptor **codecs;
unsigned nb_codecs = 0, i = 0;
while ((desc = avcodec_descriptor_next(desc)))
nb_codecs++;
if (!(codecs = av_calloc(nb_codecs, sizeof(*codecs)))) {
av_log(NULL, AV_LOG_ERROR, "Out of memory\n");
exit_program(1);
}
desc = NULL;
while ((desc = avcodec_descriptor_next(desc)))
codecs[i++] = desc;
av_assert0(i == nb_codecs);
qsort(codecs, nb_codecs, sizeof(*codecs), compare_codec_desc);
*rcodecs = codecs;
return nb_codecs;
}
static void print_codecs_for_id(enum AVCodecID id, int encoder)
{
const AVCodec *codec = NULL;
printf(" (%s: ", encoder ? "encoders" : "decoders");
while ((codec = next_codec_for_id(id, codec, encoder)))
printf("%s ", codec->name);
printf(")");
}
int show_codecs(void *optctx, const char *opt, const char *arg)
{
const AVCodecDescriptor **codecs;
unsigned i, nb_codecs = get_codecs_sorted(&codecs);
printf("Codecs:\n"
" D..... = Decoding supported\n"
" .E.... = Encoding supported\n"
" ..V... = Video codec\n"
" ..A... = Audio codec\n"
" ..S... = Subtitle codec\n"
" ...I.. = Intra frame-only codec\n"
" ....L. = Lossy compression\n"
" .....S = Lossless compression\n"
" -------\n");
for (i = 0; i < nb_codecs; i++) {
const AVCodecDescriptor *desc = codecs[i];
const AVCodec *codec = NULL;
if (strstr(desc->name, "_deprecated"))
continue;
printf(" ");
printf(avcodec_find_decoder(desc->id) ? "D" : ".");
printf(avcodec_find_encoder(desc->id) ? "E" : ".");
printf("%c", get_media_type_char(desc->type));
printf((desc->props & AV_CODEC_PROP_INTRA_ONLY) ? "I" : ".");
printf((desc->props & AV_CODEC_PROP_LOSSY) ? "L" : ".");
printf((desc->props & AV_CODEC_PROP_LOSSLESS) ? "S" : ".");
printf(" %-20s %s", desc->name, desc->long_name ? desc->long_name : "");
/* print decoders/encoders when there's more than one or their
* names are different from codec name */
while ((codec = next_codec_for_id(desc->id, codec, 0))) {
if (strcmp(codec->name, desc->name)) {
print_codecs_for_id(desc->id, 0);
break;
}
}
codec = NULL;
while ((codec = next_codec_for_id(desc->id, codec, 1))) {
if (strcmp(codec->name, desc->name)) {
print_codecs_for_id(desc->id, 1);
break;
}
}
printf("\n");
}
av_free(codecs);
return 0;
}
static void print_codecs(int encoder)
{
const AVCodecDescriptor **codecs;
unsigned i, nb_codecs = get_codecs_sorted(&codecs);
printf("%s:\n"
" V..... = Video\n"
" A..... = Audio\n"
" S..... = Subtitle\n"
" .F.... = Frame-level multithreading\n"
" ..S... = Slice-level multithreading\n"
" ...X.. = Codec is experimental\n"
" ....B. = Supports draw_horiz_band\n"
" .....D = Supports direct rendering method 1\n"
" ------\n",
encoder ? "Encoders" : "Decoders");
for (i = 0; i < nb_codecs; i++) {
const AVCodecDescriptor *desc = codecs[i];
const AVCodec *codec = NULL;
while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
printf(" %c", get_media_type_char(desc->type));
printf((codec->capabilities & AV_CODEC_CAP_FRAME_THREADS) ? "F" : ".");
printf((codec->capabilities & AV_CODEC_CAP_SLICE_THREADS) ? "S" : ".");
printf((codec->capabilities & AV_CODEC_CAP_EXPERIMENTAL) ? "X" : ".");
printf((codec->capabilities & AV_CODEC_CAP_DRAW_HORIZ_BAND)?"B" : ".");
printf((codec->capabilities & AV_CODEC_CAP_DR1) ? "D" : ".");
printf(" %-20s %s", codec->name, codec->long_name ? codec->long_name : "");
if (strcmp(codec->name, desc->name))
printf(" (codec %s)", desc->name);
printf("\n");
}
}
av_free(codecs);
}
int show_decoders(void *optctx, const char *opt, const char *arg)
{
print_codecs(0);
return 0;
}
int show_encoders(void *optctx, const char *opt, const char *arg)
{
print_codecs(1);
return 0;
}
int show_bsfs(void *optctx, const char *opt, const char *arg)
{
const AVBitStreamFilter *bsf = NULL;
void *opaque = NULL;
printf("Bitstream filters:\n");
while ((bsf = av_bsf_iterate(&opaque)))
printf("%s\n", bsf->name);
printf("\n");
return 0;
}
int show_protocols(void *optctx, const char *opt, const char *arg)
{
void *opaque = NULL;
const char *name;
printf("Supported file protocols:\n"
"Input:\n");
while ((name = avio_enum_protocols(&opaque, 0)))
printf(" %s\n", name);
printf("Output:\n");
while ((name = avio_enum_protocols(&opaque, 1)))
printf(" %s\n", name);
return 0;
}
int show_filters(void *optctx, const char *opt, const char *arg)
{
#if CONFIG_AVFILTER
const AVFilter *filter = NULL;
char descr[64], *descr_cur;
void *opaque = NULL;
int i, j;
const AVFilterPad *pad;
printf("Filters:\n"
" T.. = Timeline support\n"
" .S. = Slice threading\n"
" ..C = Command support\n"
" A = Audio input/output\n"
" V = Video input/output\n"
" N = Dynamic number and/or type of input/output\n"
" | = Source or sink filter\n");
while ((filter = av_filter_iterate(&opaque))) {
descr_cur = descr;
for (i = 0; i < 2; i++) {
if (i) {
*(descr_cur++) = '-';
*(descr_cur++) = '>';
}
pad = i ? filter->outputs : filter->inputs;
for (j = 0; pad && avfilter_pad_get_name(pad, j); j++) {
if (descr_cur >= descr + sizeof(descr) - 4)
break;
*(descr_cur++) = get_media_type_char(avfilter_pad_get_type(pad, j));
}
if (!j)
*(descr_cur++) = ((!i && (filter->flags & AVFILTER_FLAG_DYNAMIC_INPUTS)) ||
( i && (filter->flags & AVFILTER_FLAG_DYNAMIC_OUTPUTS))) ? 'N' : '|';
}
*descr_cur = 0;
printf(" %c%c%c %-17s %-10s %s\n",
filter->flags & AVFILTER_FLAG_SUPPORT_TIMELINE ? 'T' : '.',
filter->flags & AVFILTER_FLAG_SLICE_THREADS ? 'S' : '.',
filter->process_command ? 'C' : '.',
filter->name, descr, filter->description);
}
#else
printf("No filters available: libavfilter disabled\n");
#endif
return 0;
}
int show_colors(void *optctx, const char *opt, const char *arg)
{
const char *name;
const uint8_t *rgb;
int i;
printf("%-32s #RRGGBB\n", "name");
for (i = 0; name = av_get_known_color_name(i, &rgb); i++)
printf("%-32s #%02x%02x%02x\n", name, rgb[0], rgb[1], rgb[2]);
return 0;
}
int show_pix_fmts(void *optctx, const char *opt, const char *arg)
{
const AVPixFmtDescriptor *pix_desc = NULL;
printf("Pixel formats:\n"
"I.... = Supported Input format for conversion\n"
".O... = Supported Output format for conversion\n"
"..H.. = Hardware accelerated format\n"
"...P. = Paletted format\n"
"....B = Bitstream format\n"
"FLAGS NAME NB_COMPONENTS BITS_PER_PIXEL\n"
"-----\n");
#if !CONFIG_SWSCALE
# define sws_isSupportedInput(x) 0
# define sws_isSupportedOutput(x) 0
#endif
while ((pix_desc = av_pix_fmt_desc_next(pix_desc))) {
enum AVPixelFormat av_unused pix_fmt = av_pix_fmt_desc_get_id(pix_desc);
printf("%c%c%c%c%c %-16s %d %2d\n",
sws_isSupportedInput (pix_fmt) ? 'I' : '.',
sws_isSupportedOutput(pix_fmt) ? 'O' : '.',
pix_desc->flags & AV_PIX_FMT_FLAG_HWACCEL ? 'H' : '.',
pix_desc->flags & AV_PIX_FMT_FLAG_PAL ? 'P' : '.',
pix_desc->flags & AV_PIX_FMT_FLAG_BITSTREAM ? 'B' : '.',
pix_desc->name,
pix_desc->nb_components,
av_get_bits_per_pixel(pix_desc));
}
return 0;
}
int show_layouts(void *optctx, const char *opt, const char *arg)
{
int i = 0;
uint64_t layout, j;
const char *name, *descr;
printf("Individual channels:\n"
"NAME DESCRIPTION\n");
for (i = 0; i < 63; i++) {
name = av_get_channel_name((uint64_t)1 << i);
if (!name)
continue;
descr = av_get_channel_description((uint64_t)1 << i);
printf("%-14s %s\n", name, descr);
}
printf("\nStandard channel layouts:\n"
"NAME DECOMPOSITION\n");
for (i = 0; !av_get_standard_channel_layout(i, &layout, &name); i++) {
if (name) {
printf("%-14s ", name);
for (j = 1; j; j <<= 1)
if ((layout & j))
printf("%s%s", (layout & (j - 1)) ? "+" : "", av_get_channel_name(j));
printf("\n");
}
}
return 0;
}
int show_sample_fmts(void *optctx, const char *opt, const char *arg)
{
int i;
char fmt_str[128];
for (i = -1; i < AV_SAMPLE_FMT_NB; i++)
printf("%s\n", av_get_sample_fmt_string(fmt_str, sizeof(fmt_str), i));
return 0;
}
static void show_help_codec(const char *name, int encoder)
{
const AVCodecDescriptor *desc;
const AVCodec *codec;
if (!name) {
av_log(NULL, AV_LOG_ERROR, "No codec name specified.\n");
return;
}
codec = encoder ? avcodec_find_encoder_by_name(name) :
avcodec_find_decoder_by_name(name);
if (codec)
print_codec(codec);
else if ((desc = avcodec_descriptor_get_by_name(name))) {
int printed = 0;
while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
printed = 1;
print_codec(codec);
}
if (!printed) {
av_log(NULL, AV_LOG_ERROR, "Codec '%s' is known to FFmpeg, "
"but no %s for it are available. FFmpeg might need to be "
"recompiled with additional external libraries.\n",
name, encoder ? "encoders" : "decoders");
}
} else {
av_log(NULL, AV_LOG_ERROR, "Codec '%s' is not recognized by FFmpeg.\n",
name);
}
}
static void show_help_demuxer(const char *name)
{
const AVInputFormat *fmt = av_find_input_format(name);
if (!fmt) {
av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
return;
}
printf("Demuxer %s [%s]:\n", fmt->name, fmt->long_name);
if (fmt->extensions)
printf(" Common extensions: %s.\n", fmt->extensions);
if (fmt->priv_class)
show_help_children(fmt->priv_class, AV_OPT_FLAG_DECODING_PARAM);
}
static void show_help_muxer(const char *name)
{
const AVCodecDescriptor *desc;
const AVOutputFormat *fmt = av_guess_format(name, NULL, NULL);
if (!fmt) {
av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
return;
}
printf("Muxer %s [%s]:\n", fmt->name, fmt->long_name);
if (fmt->extensions)
printf(" Common extensions: %s.\n", fmt->extensions);
if (fmt->mime_type)
printf(" Mime type: %s.\n", fmt->mime_type);
if (fmt->video_codec != AV_CODEC_ID_NONE &&
(desc = avcodec_descriptor_get(fmt->video_codec))) {
printf(" Default video codec: %s.\n", desc->name);
}
if (fmt->audio_codec != AV_CODEC_ID_NONE &&
(desc = avcodec_descriptor_get(fmt->audio_codec))) {
printf(" Default audio codec: %s.\n", desc->name);
}
if (fmt->subtitle_codec != AV_CODEC_ID_NONE &&
(desc = avcodec_descriptor_get(fmt->subtitle_codec))) {
printf(" Default subtitle codec: %s.\n", desc->name);
}
if (fmt->priv_class)
show_help_children(fmt->priv_class, AV_OPT_FLAG_ENCODING_PARAM);
}
#if CONFIG_AVFILTER
static void show_help_filter(const char *name)
{
#if CONFIG_AVFILTER
const AVFilter *f = avfilter_get_by_name(name);
int i, count;
if (!name) {
av_log(NULL, AV_LOG_ERROR, "No filter name specified.\n");
return;
} else if (!f) {
av_log(NULL, AV_LOG_ERROR, "Unknown filter '%s'.\n", name);
return;
}
printf("Filter %s\n", f->name);
if (f->description)
printf(" %s\n", f->description);
if (f->flags & AVFILTER_FLAG_SLICE_THREADS)
printf(" slice threading supported\n");
printf(" Inputs:\n");
count = avfilter_pad_count(f->inputs);
for (i = 0; i < count; i++) {
printf(" #%d: %s (%s)\n", i, avfilter_pad_get_name(f->inputs, i),
media_type_string(avfilter_pad_get_type(f->inputs, i)));
}
if (f->flags & AVFILTER_FLAG_DYNAMIC_INPUTS)
printf(" dynamic (depending on the options)\n");
else if (!count)
printf(" none (source filter)\n");
printf(" Outputs:\n");
count = avfilter_pad_count(f->outputs);
for (i = 0; i < count; i++) {
printf(" #%d: %s (%s)\n", i, avfilter_pad_get_name(f->outputs, i),
media_type_string(avfilter_pad_get_type(f->outputs, i)));
}
if (f->flags & AVFILTER_FLAG_DYNAMIC_OUTPUTS)
printf(" dynamic (depending on the options)\n");
else if (!count)
printf(" none (sink filter)\n");
if (f->priv_class)
show_help_children(f->priv_class, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_FILTERING_PARAM |
AV_OPT_FLAG_AUDIO_PARAM);
if (f->flags & AVFILTER_FLAG_SUPPORT_TIMELINE)
printf("This filter has support for timeline through the 'enable' option.\n");
#else
av_log(NULL, AV_LOG_ERROR, "Build without libavfilter; "
"can not to satisfy request\n");
#endif
}
#endif
static void show_help_bsf(const char *name)
{
const AVBitStreamFilter *bsf = av_bsf_get_by_name(name);
if (!name) {
av_log(NULL, AV_LOG_ERROR, "No bitstream filter name specified.\n");
return;
} else if (!bsf) {
av_log(NULL, AV_LOG_ERROR, "Unknown bit stream filter '%s'.\n", name);
return;
}
printf("Bit stream filter %s\n", bsf->name);
PRINT_CODEC_SUPPORTED(bsf, codec_ids, enum AVCodecID, "codecs",
AV_CODEC_ID_NONE, GET_CODEC_NAME);
if (bsf->priv_class)
show_help_children(bsf->priv_class, AV_OPT_FLAG_BSF_PARAM);
}
int show_help(void *optctx, const char *opt, const char *arg)
{
char *topic, *par;
av_log_set_callback(log_callback_help);
topic = av_strdup(arg ? arg : "");
if (!topic)
return AVERROR(ENOMEM);
par = strchr(topic, '=');
if (par)
*par++ = 0;
if (!*topic) {
show_help_default(topic, par);
} else if (!strcmp(topic, "decoder")) {
show_help_codec(par, 0);
} else if (!strcmp(topic, "encoder")) {
show_help_codec(par, 1);
} else if (!strcmp(topic, "demuxer")) {
show_help_demuxer(par);
} else if (!strcmp(topic, "muxer")) {
show_help_muxer(par);
#if CONFIG_AVFILTER
} else if (!strcmp(topic, "filter")) {
show_help_filter(par);
#endif
} else if (!strcmp(topic, "bsf")) {
show_help_bsf(par);
} else {
show_help_default(topic, par);
}
av_freep(&topic);
return 0;
}
int read_yesno(void)
{
int c = getchar();
int yesno = (av_toupper(c) == 'Y');
while (c != '\n' && c != EOF)
c = getchar();
return yesno;
}
FILE *get_preset_file(char *filename, size_t filename_size,
const char *preset_name, int is_path,
const char *codec_name)
{
FILE *f = NULL;
int i;
const char *base[3] = { getenv("FFMPEG_DATADIR"),
getenv("HOME"),
FFMPEG_DATADIR, };
if (is_path) {
av_strlcpy(filename, preset_name, filename_size);
f = fopen(filename, "r");
} else {
#ifdef _WIN32
char datadir[MAX_PATH], *ls;
base[2] = NULL;
if (GetModuleFileNameA(GetModuleHandleA(NULL), datadir, sizeof(datadir) - 1))
{
for (ls = datadir; ls < datadir + strlen(datadir); ls++)
if (*ls == '\\') *ls = '/';
if (ls = strrchr(datadir, '/'))
{
*ls = 0;
strncat(datadir, "/ffpresets", sizeof(datadir) - 1 - strlen(datadir));
base[2] = datadir;
}
}
#endif
for (i = 0; i < 3 && !f; i++) {
if (!base[i])
continue;
snprintf(filename, filename_size, "%s%s/%s.ffpreset", base[i],
i != 1 ? "" : "/.ffmpeg", preset_name);
f = fopen(filename, "r");
if (!f && codec_name) {
snprintf(filename, filename_size,
"%s%s/%s-%s.ffpreset",
base[i], i != 1 ? "" : "/.ffmpeg", codec_name,
preset_name);
f = fopen(filename, "r");
}
}
}
return f;
}
int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
{
int ret = avformat_match_stream_specifier(s, st, spec);
if (ret < 0)
av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
return ret;
}
AVDictionary *filter_codec_opts(AVDictionary *opts, enum AVCodecID codec_id,
AVFormatContext *s, AVStream *st, AVCodec *codec)
{
AVDictionary *ret = NULL;
AVDictionaryEntry *t = NULL;
int flags = s->oformat ? AV_OPT_FLAG_ENCODING_PARAM
: AV_OPT_FLAG_DECODING_PARAM;
char prefix = 0;
const AVClass *cc = avcodec_get_class();
if (!codec)
codec = s->oformat ? avcodec_find_encoder(codec_id)
: avcodec_find_decoder(codec_id);
switch (st->codecpar->codec_type) {
case AVMEDIA_TYPE_VIDEO:
prefix = 'v';
flags |= AV_OPT_FLAG_VIDEO_PARAM;
break;
case AVMEDIA_TYPE_AUDIO:
prefix = 'a';
flags |= AV_OPT_FLAG_AUDIO_PARAM;
break;
case AVMEDIA_TYPE_SUBTITLE:
prefix = 's';
flags |= AV_OPT_FLAG_SUBTITLE_PARAM;
break;
}
while (t = av_dict_get(opts, "", t, AV_DICT_IGNORE_SUFFIX)) {
char *p = strchr(t->key, ':');
/* check stream specification in opt name */
if (p)
switch (check_stream_specifier(s, st, p + 1)) {
case 1: *p = 0; break;
case 0: continue;
default: exit_program(1);
}
if (av_opt_find(&cc, t->key, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ) ||
!codec ||
(codec->priv_class &&
av_opt_find(&codec->priv_class, t->key, NULL, flags,
AV_OPT_SEARCH_FAKE_OBJ)))
av_dict_set(&ret, t->key, t->value, 0);
else if (t->key[0] == prefix &&
av_opt_find(&cc, t->key + 1, NULL, flags,
AV_OPT_SEARCH_FAKE_OBJ))
av_dict_set(&ret, t->key + 1, t->value, 0);
if (p)
*p = ':';
}
return ret;
}
AVDictionary **setup_find_stream_info_opts(AVFormatContext *s,
AVDictionary *codec_opts)
{
int i;
AVDictionary **opts;
if (!s->nb_streams)
return NULL;
opts = av_mallocz_array(s->nb_streams, sizeof(*opts));
if (!opts) {
av_log(NULL, AV_LOG_ERROR,
"Could not alloc memory for stream options.\n");
return NULL;
}
for (i = 0; i < s->nb_streams; i++)
opts[i] = filter_codec_opts(codec_opts, s->streams[i]->codecpar->codec_id,
s, s->streams[i], NULL);
return opts;
}
void *grow_array(void *array, int elem_size, int *size, int new_size)
{
if (new_size >= INT_MAX / elem_size) {
av_log(NULL, AV_LOG_ERROR, "Array too big.\n");
exit_program(1);
}
if (*size < new_size) {
uint8_t *tmp = av_realloc_array(array, new_size, elem_size);
if (!tmp) {
av_log(NULL, AV_LOG_ERROR, "Could not alloc buffer.\n");
exit_program(1);
}
memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
*size = new_size;
return tmp;
}
return array;
}
double get_rotation(AVStream *st)
{
uint8_t* displaymatrix = av_stream_get_side_data(st,
AV_PKT_DATA_DISPLAYMATRIX, NULL);
double theta = 0;
if (displaymatrix)
theta = -av_display_rotation_get((int32_t*) displaymatrix);
theta -= 360*floor(theta/360 + 0.9/360);
if (fabs(theta - 90*round(theta/90)) > 2)
av_log(NULL, AV_LOG_WARNING, "Odd rotation angle.\n"
"If you want to help, upload a sample "
"of this file to ftp://upload.ffmpeg.org/incoming/ "
"and contact the ffmpeg-devel mailing list. (ffmpeg-devel@ffmpeg.org)");
return theta;
}
#if CONFIG_AVDEVICE
static int print_device_sources(AVInputFormat *fmt, AVDictionary *opts)
{
int ret, i;
AVDeviceInfoList *device_list = NULL;
if (!fmt || !fmt->priv_class || !AV_IS_INPUT_DEVICE(fmt->priv_class->category))
return AVERROR(EINVAL);
printf("Auto-detected sources for %s:\n", fmt->name);
if (!fmt->get_device_list) {
ret = AVERROR(ENOSYS);
printf("Cannot list sources. Not implemented.\n");
goto fail;
}
if ((ret = avdevice_list_input_sources(fmt, NULL, opts, &device_list)) < 0) {
printf("Cannot list sources.\n");
goto fail;
}
for (i = 0; i < device_list->nb_devices; i++) {
printf("%s %s [%s]\n", device_list->default_device == i ? "*" : " ",
device_list->devices[i]->device_name, device_list->devices[i]->device_description);
}
fail:
avdevice_free_list_devices(&device_list);
return ret;
}
static int print_device_sinks(AVOutputFormat *fmt, AVDictionary *opts)
{
int ret, i;
AVDeviceInfoList *device_list = NULL;
if (!fmt || !fmt->priv_class || !AV_IS_OUTPUT_DEVICE(fmt->priv_class->category))
return AVERROR(EINVAL);
printf("Auto-detected sinks for %s:\n", fmt->name);
if (!fmt->get_device_list) {
ret = AVERROR(ENOSYS);
printf("Cannot list sinks. Not implemented.\n");
goto fail;
}
if ((ret = avdevice_list_output_sinks(fmt, NULL, opts, &device_list)) < 0) {
printf("Cannot list sinks.\n");
goto fail;
}
for (i = 0; i < device_list->nb_devices; i++) {
printf("%s %s [%s]\n", device_list->default_device == i ? "*" : " ",
device_list->devices[i]->device_name, device_list->devices[i]->device_description);
}
fail:
avdevice_free_list_devices(&device_list);
return ret;
}
static int show_sinks_sources_parse_arg(const char *arg, char **dev, AVDictionary **opts)
{
int ret;
if (arg) {
char *opts_str = NULL;
av_assert0(dev && opts);
*dev = av_strdup(arg);
if (!*dev)
return AVERROR(ENOMEM);
if ((opts_str = strchr(*dev, ','))) {
*(opts_str++) = '\0';
if (opts_str[0] && ((ret = av_dict_parse_string(opts, opts_str, "=", ":", 0)) < 0)) {
av_freep(dev);
return ret;
}
}
} else
printf("\nDevice name is not provided.\n"
"You can pass devicename[,opt1=val1[,opt2=val2...]] as an argument.\n\n");
return 0;
}
int show_sources(void *optctx, const char *opt, const char *arg)
{
AVInputFormat *fmt = NULL;
char *dev = NULL;
AVDictionary *opts = NULL;
int ret = 0;
int error_level = av_log_get_level();
av_log_set_level(AV_LOG_ERROR);
if ((ret = show_sinks_sources_parse_arg(arg, &dev, &opts)) < 0)
goto fail;
do {
fmt = av_input_audio_device_next(fmt);
if (fmt) {
if (!strcmp(fmt->name, "lavfi"))
continue; //it's pointless to probe lavfi
if (dev && !av_match_name(dev, fmt->name))
continue;
print_device_sources(fmt, opts);
}
} while (fmt);
do {
fmt = av_input_video_device_next(fmt);
if (fmt) {
if (dev && !av_match_name(dev, fmt->name))
continue;
print_device_sources(fmt, opts);
}
} while (fmt);
fail:
av_dict_free(&opts);
av_free(dev);
av_log_set_level(error_level);
return ret;
}
int show_sinks(void *optctx, const char *opt, const char *arg)
{
AVOutputFormat *fmt = NULL;
char *dev = NULL;
AVDictionary *opts = NULL;
int ret = 0;
int error_level = av_log_get_level();
av_log_set_level(AV_LOG_ERROR);
if ((ret = show_sinks_sources_parse_arg(arg, &dev, &opts)) < 0)
goto fail;
do {
fmt = av_output_audio_device_next(fmt);
if (fmt) {
if (dev && !av_match_name(dev, fmt->name))
continue;
print_device_sinks(fmt, opts);
}
} while (fmt);
do {
fmt = av_output_video_device_next(fmt);
if (fmt) {
if (dev && !av_match_name(dev, fmt->name))
continue;
print_device_sinks(fmt, opts);
}
} while (fmt);
fail:
av_dict_free(&opts);
av_free(dev);
av_log_set_level(error_level);
return ret;
}
#endif
|
7da2f3b5b27692febc31b393a97915a4c4c78315
|
41eb0837713f297134529591b66f3d4d82bcf98e
|
/src/Raine/source/games/taito_f2.c
|
265c759659e06f390a3e12a908ad5e4157fb0892
|
[] |
no_license
|
AlexxandreFS/Batocera.PLUS
|
27b196b3cbb781b6fc99e62cad855396d1d5f8f2
|
997ee763ae7135fdf0c34a081e789918bd2eb169
|
refs/heads/master
| 2023-08-17T21:52:39.083687
| 2023-08-17T15:03:44
| 2023-08-17T15:03:44
| 215,869,486
| 135
| 57
| null | 2023-08-14T14:46:14
| 2019-10-17T19:23:42
|
C
|
SHIFT_JIS
|
C
| false
| false
| 120,670
|
c
|
taito_f2.c
|
#define DRV_DEF_SOUND taito_ym2610_sound
/* Current taito f2 driver - work in progress */
/* Most of this emulation is done by the external video chips :
tc100scn for the background layers (and fg0)
tc280grd/TC0430GRW for the tile with zoom/rotation
In this file all I handle is the priorities, what mame calls the TC0360PRI.
Congratulations to their team for their findings about this chip, no wonder
Antiriad didn't guess it was a priority chip.
Notice : the taito f2 is clearly not a standardized hardware, there are differences
almost between every game, in the memory map, sometimes even in the video chips used.
It's said on the web that dead connection and metal black use taito f2 hardware, but
they don't use the tC100scn, they use a much more powerfull chip. So I will not emulate
them here.
Growl seems to have a bug, because I could reproduce it in mame : when you select your
player, sometimes the background music does not start. It seems to depend on the time
you spend before pressing the button. When you put 2 coins instead of 1, you have one
more sound effect, and more chances that the music starts ! This bug made me quite
crazy but it seems to be a game bug and not a raine bug.
Also it tries to access what we call a tc220ioc for its inputs when it has none.
Crappy code, really.
There might be some sounds issues anyway, maybe the ym2610 does not start some
samples sometimes but I am not totally sure...
Here is the description of this chip from the info in mame.
For the other 2 chips, look in tc100scn.c, tc005rot.c, and tc200obj.c for the sprites.
TC0360PRI
---------
Priority manager
A higher priority value means higher priority. 0 could mean disable but
I'm not sure. If two inputs have the same priority value, I think the first
one has priority, but I'm not sure of that either.
It seems the chip accepts three inputs from three different sources, and
each one of them can declare to have four different priority levels.
000 unknown. Could it be related to highlight/shadow effects in qcrayon2
and gunfront?
001 in games with a roz layer, this is the roz palette bank (bottom 6 bits
affect roz color, top 2 bits affect priority)
002 unknown
003 unknown
004 ----xxxx \ priority level 0 (unused? usually 0, pulirula sets it to F in some places)
xxxx---- | Input priority level 1 (usually FG0)
005 ----xxxx | #1 priority level 2 (usually BG0)
xxxx---- / priority level 3 (usually BG1)
006 ----xxxx \ priority level 0 (usually sprites with top color bits 00)
xxxx---- | Input priority level 1 (usually sprites with top color bits 01)
007 ----xxxx | #2 priority level 2 (usually sprites with top color bits 10)
xxxx---- / priority level 3 (usually sprites with top color bits 11)
008 ----xxxx \ priority level 0 (e.g. roz layer if top bits of register 001 are 00)
xxxx---- | Input priority level 1 (e.g. roz layer if top bits of register 001 are 01)
009 ----xxxx | #3 priority level 2 (e.g. roz layer if top bits of register 001 are 10)
xxxx---- / priority level 3 (e.g. roz layer if top bits of register 001 are 11)
00a unused
00b unused
00c unused
00d unused
00e unused
00f unused
Metalb uses in the PRI chip
---------------------------
+4 xxxx0000 BG1
0000xxxx BG0
+6 xxxx0000 BG3
0000xxxx BG2
About the clones :
I removed dinorexu and dinorexj, because they are just taito clones, which means only
1 region byte changes between the roms. The coinage changes too, but I really don't care
about the coinage.
Games known to use line scroll : don do kod, dino rex, thunder fox (every stage ?)
SSI can't use line scroll because it only uses sprites.
The others might use it at one place or another, but it's not easy to find !
*/
#include "gameinc.h"
#include "tc005rot.h"
#include "tc100scn.h"
#include "tc200obj.h"
#include "tc220ioc.h"
#include "sasound.h" // sample support routines
#include "taitosnd.h"
#include "timer.h"
#include "blit.h"
#include "adpcm.h"
#include "tc110pcr.h"
#include "2203intf.h"
static UINT8 *TC0360PRI_regs;
/* Well this clone really looks like the original, but the roms are definetely different
(see the hack in load_ssi : clearly different for the 2 roms. So well, let's keep it...
*/
static struct ROM_INFO rom_cameltry[] =
{
LOAD8_16( REGION_ROM1, 0x00000, 0x20000,
"c38-11", 0xbe172da0, "c38-14", 0xffa430de),
/* empty! */
{ "c38-01.bin", 0x80000, 0xc170ff36, REGION_GFX2, 0x00000, LOAD_NORMAL },
{ "c38-02.bin", 0x20000, 0x1a11714b, REGION_GFX3, 0x00000, LOAD_NORMAL },
{ "c38-08.bin", 0x10000, 0x7ff78873, REGION_ROM2, 0, LOAD_NORMAL },
/* no Delta-T samples */
{ "c38-03.bin", 0x020000, 0x59fa59a7, REGION_SMP1, 0x000000, LOAD_NORMAL },
{ NULL, 0, 0, 0, 0, 0 }
};
static struct ROM_INFO rom_camltrua[] =
{
/* empty! */
{ "c38-us.15", 0x10000, 0x0e60faac, REGION_ROM2, 0x00000, LOAD_NORMAL },
/* no Delta-T samples */
{ NULL, 0, 0, 0, 0, 0 }
};
static struct ROM_INFO rom_gunfront[] =
{
LOAD8_16( REGION_ROM1, 0x00000, 0x20000,
"c71-09.42", 0x10a544a2, "c71-08.41", 0xc17dc0a0),
LOAD8_16( REGION_ROM1, 0x40000, 0x20000,
"c71-10.40", 0xf39c0a06, "c71-14.39", 0x312da036),
LOAD8_16( REGION_ROM1, 0x80000, 0x20000,
"c71-16.38", 0x1bbcc2d4, "c71-15.37", 0xdf3e00bb),
{ "c71-02.59", 0x100000, 0x2a600c92, REGION_GFX1, 0x000000, LOAD_NORMAL },
{ "c71-03.19", 0x100000, 0x9133c605, REGION_GFX2, 0x000000, LOAD_NORMAL },
{ "c71-12.49", 0x10000, 0x0038c7f8, REGION_ROM2, 0, LOAD_NORMAL },
/* no Delta-T samples */
/* Pals c71-16.28 c71-07.27 */
{ "c71-01.29", 0x100000, 0x0e73105a, REGION_SMP1, 0x000000, LOAD_NORMAL },
{ NULL, 0, 0, 0, 0, 0 }
};
static struct ROM_INFO rom_growl[] =
{
LOAD8_16( REGION_ROM1, 0x00000, 0x40000,
"c74-10.59", 0xca81a20b, "c74-08.61", 0xaa35dd9e),
LOAD8_16( REGION_ROM1, 0x80000, 0x40000,
"c74-11.58", 0xee3bd6d5, "c74-14.60", 0xb6c24ec7),
{ "c74-01.34", 0x100000, 0x3434ce80, REGION_GFX1, 0x000000, LOAD_NORMAL },
{ "c74-03.12", 0x100000, 0x1a0d8951, REGION_GFX2, 0x000000, LOAD_NORMAL },
{ "c74-02.11", 0x100000, 0x15a21506, REGION_GFX2, 0x100000, LOAD_NORMAL },
{ "c74-12.62", 0x10000, 0xbb6ed668, REGION_ROM2, 0, LOAD_NORMAL },
{ "c74-04.28", 0x100000, 0x2d97edf2, REGION_SMP1, 0x000000, LOAD_NORMAL },
/*Pals c74-06.48 c74-07.47 */
{ "c74-05.29", 0x080000, 0xe29c0828, REGION_SMP2, 0x000000, LOAD_NORMAL },
{ NULL, 0, 0, 0, 0, 0 }
};
static struct ROM_INFO rom_finalb[] =
{
{ "b82_09.10", 0x20000, 0x632f1ecd, REGION_ROM1, 0x00000, LOAD_8_16 },
{ "b82_17.11", 0x20000, 0xe91b2ec9, REGION_ROM1, 0x00001, LOAD_8_16 },
{ "b82-06.19", 0x20000, 0xfc450a25, REGION_GFX1, 0x00000, LOAD_8_16 },
{ "b82-07.18", 0x20000, 0xec3df577, REGION_GFX1, 0x00001, LOAD_8_16 },
{ "b82-04.4", 0x80000, 0x6346f98e, REGION_GFX2, 0x000000, LOAD_8_16 },
/* Note: this is intentional to load at 0x180000, not at 0x100000
because finalb_driver_init will move some bits around before data
will be 'gfxdecoded'. The whole thing is because this data is 2bits-
while above is 4bits-packed format, for a total of 6 bits per pixel. */
{ "b82-03.5", 0x80000, 0xdaa11561, REGION_GFX2, 0x000001, LOAD_8_16 },
{ "b82-05.3", 0x80000, 0xaa90b93a, REGION_GFX2, 0x180000, LOAD_NORMAL },
{ "b82_10.16", 0x10000, 0xa38aaaed, REGION_ROM2, 0, LOAD_NORMAL },
{ "b82-02.1", 0x80000, 0x5dd06bdd, REGION_SMP1, 0x00000, LOAD_NORMAL },
{ "b82-01.2", 0x80000, 0xf0eb6846, REGION_SMP2, 0x00000, LOAD_NORMAL },
{ NULL, 0, 0, 0, 0, 0 }
};
static struct ROM_INFO rom_solfigtr[] =
{
LOAD8_16( REGION_ROM1, 0x00000, 0x40000,
"c91-05.59", 0xc1260e7c, "c91-09.61", 0xd82b5266),
{ "c91-03.34", 0x100000, 0x8965da12, REGION_GFX1, 0x000000, LOAD_NORMAL },
{ "c91-01.12", 0x100000, 0x0f3f4e00, REGION_GFX2, 0x000000, LOAD_NORMAL },
{ "c91-02.11", 0x100000, 0xe14ab98e, REGION_GFX2, 0x100000, LOAD_NORMAL },
{ "c91-07.62", 0x10000, 0xe471a05a, REGION_ROM2, 0, LOAD_NORMAL },
/* no Delta-T samples */
/*Pals c74-06.48 */
{ "c91-04.28", 0x80000, 0x390b1065, REGION_SMP1, 0x00000, LOAD_NORMAL },
{ NULL, 0, 0, 0, 0, 0 }
};
static struct ROM_INFO rom_mjnquest[] =
{
LOAD8_16( REGION_ROM1, 0x000000, 0x020000,
"c77-09", 0x0a005d01, "c77-08", 0x4244f775),
{ "c77-04", 0x080000, 0xc2e7e038, REGION_ROM1, 0x080000, LOAD_SWAP_16 },
{ "c77-01", 0x100000, 0x5ba51205, REGION_GFX1, 0x000000, LOAD_NORMAL },
{ "c77-02", 0x100000, 0x6a6f3040, REGION_GFX1, 0x100000, LOAD_NORMAL },
{ "c77-05", 0x80000, 0xc5a54678, REGION_GFX2, 0x00000, LOAD_NORMAL },
{ "c77-10", 0x10000, 0xf16b2c1e, REGION_ROM2, 0, LOAD_NORMAL },
/* no Delta-T samples */
{ "c77-03", 0x080000, 0x312f17b1, REGION_SMP1, 0x000000, LOAD_NORMAL },
{ NULL, 0, 0, 0, 0, 0 }
};
static struct ROM_INFO rom_f2demo[] =
{
{ "lk_obj0.bin", 0x00080000, 0x1bb8aa37, REGION_GFX2, 0, LOAD_NORMAL },
{ "lk_obj1.bin", 0x00080000, 0x75660aac, REGION_GFX2, 0x80000, LOAD_NORMAL },
{ "lk_scr.bin", 0x00080000, 0xb178fb05, REGION_GFX1, 0, LOAD_NORMAL },
LOAD8_16( REGION_ROM1, 0, 0x00020000,
"lq09.bin", 0x809a968b, "lq11.bin", 0x7ba3a5cb),
LOAD8_16( REGION_ROM1, 0x40000, 0x00020000,
"lq10.bin", 0x7ee8cdcd, "lq12.bin", 0x7ee8cdcd),
{ NULL, 0, 0, 0, 0, 0, },
};
static struct ROM_INFO rom_dinorex[] =
{
LOAD8_16( REGION_ROM1, 0x000000, 0x080000,
"d39_14.9", 0xe6aafdac, "d39_16.8", 0xcedc8537),
{ "d39-04.6", 0x100000, 0x3800506d, REGION_ROM1, 0x100000, LOAD_SWAP_16 },
{ "d39-05.7", 0x100000, 0xe2ec3b5d, REGION_ROM1, 0x200000, LOAD_SWAP_16 },
{ "d39-06.2", 0x100000, 0x52f62835, REGION_GFX1, 0x000000, LOAD_NORMAL },
{ "d39-01.29", 0x200000, 0xd10e9c7d, REGION_GFX2, 0x000000, LOAD_NORMAL },
{ "d39-02.28", 0x200000, 0x6c304403, REGION_GFX2, 0x200000, LOAD_NORMAL },
{ "d39-03.27", 0x200000, 0xfc9cdab4, REGION_GFX2, 0x400000, LOAD_NORMAL },
{ "d39_12.5", 0x10000, 0x8292c7c1, REGION_ROM2, 0, LOAD_NORMAL },
{ "d39-07.10", 0x100000, 0x28262816, REGION_SMP1, 0x000000, LOAD_NORMAL },
{ "d39-08.4", 0x080000, 0x377b8b7b, REGION_SMP2, 0x000000, LOAD_NORMAL },
{ NULL, 0, 0, 0, 0, 0 }
};
static struct ROM_INFO rom_thundfox[] =
{
LOAD8_16( REGION_ROM1, 0x00000, 0x20000,
"c28-13-1.51", 0xacb07013, "c28-16-1.40", 0x1e43d55b),
LOAD8_16( REGION_ROM1, 0x40000, 0x20000,
"c28-08.50", 0x38e038f1, "c28-07.39", 0x24419abb),
{ "c28-02.61", 0x80000, 0x6230a09d, REGION_GFX1, 0x000000, LOAD_NORMAL },
LOAD8_16( REGION_GFX2, 0x00000, 0x80000,
"c28-03.29", 0x51bdc7af, "c28-04.28", 0xba7ed535),
{ "c28-01.63", 0x80000, 0x44552b25, REGION_GFX3, 0x000000, LOAD_NORMAL },
{ "c28-14.3", 0x10000, 0x45ef3616, REGION_ROM2, 0, LOAD_NORMAL },
{ "c28-06.41", 0x80000, 0xdb6983db, REGION_SMP1, 0x00000, LOAD_NORMAL },
/* Pals: c28-09.25 c28-10.26 c28-11.35 b89-01.19 b89-03.37 b89-04.33 */
{ "c28-05.42", 0x80000, 0xd3b238fa, REGION_SMP2, 0x00000, LOAD_NORMAL },
{ NULL, 0, 0, 0, 0, 0 }
};
static struct ROM_INFO rom_driveout[] =
{
LOAD8_16( REGION_ROM1, 0x00000, 0x80000,
"driveout.003", 0xdc431e4e, "driveout.002", 0x6f9063f4),
/* empty */
LOAD8_16( REGION_GFX2, 0x00000, 0x40000,
"driveout.084", 0x530ac420, "driveout.081", 0x0e9a3e9e),
{ "driveout.020", 0x8000, 0x99aaeb2e, REGION_ROM2, 0x0000, LOAD_NORMAL },
{ "driveout.028", 0x80000, 0xcbde0b66, REGION_SMP1, 0, LOAD_NORMAL },
{ "driveout.029", 0x20000, 0x0aba2026, REGION_SMP1, 0x20000, LOAD_NORMAL },
{ "driveout.029", 0x20000, 0x0aba2026, REGION_SMP1, 0x60000, LOAD_NORMAL },
{ "driveout.029", 0x20000, 0x0aba2026, REGION_SMP1, 0xa0000, LOAD_NORMAL },
{ "driveout.029", 0x20000, 0x0aba2026, REGION_SMP1, 0xe0000, LOAD_NORMAL },
{ NULL, 0, 0, 0, 0, 0 }
};
static struct ROM_INFO rom_driftout[] =
{
LOAD8_16( REGION_ROM1, 0x00000, 0x80000,
"do_46.rom", 0xf960363e, "do_45.rom", 0xe3fe66b9),
/* empty */
{ "do_obj.rom", 0x80000, 0x5491f1c4, REGION_GFX2, 0x00000, LOAD_NORMAL },
{ "do_piv.rom", 0x80000, 0xc4f012f7, REGION_GFX3, 0x00000, LOAD_NORMAL },
{ "do_50.rom", 0x10000, 0xffe10124, REGION_ROM2, 0, LOAD_NORMAL },
/* no Delta-T samples */
{ "do_snd.rom", 0x80000, 0xf2deb82b, REGION_SMP1, 0x00000, LOAD_NORMAL },
{ NULL, 0, 0, 0, 0, 0 }
};
static struct ROM_INFO rom_ssi[] =
{
{ "c64-01.1", 0x00100000, 0xa1b4f486, REGION_GFX2, 0x000000, LOAD_NORMAL, },
{ "c64-02.2", 0x00020000, 0x3cb0b907, REGION_SMP1, 0x000000, LOAD_NORMAL, },
LOAD8_16( REGION_ROM1, 0x000000, 0x00040000,
"c64_15-1.bin", 0xce9308a6, "c64_16-1.bin", 0x470a483a),
{ "c64_09.13", 0x00010000, 0x88d7f65c, REGION_ROM2, 0x000000, LOAD_NORMAL, },
{ NULL, 0, 0, 0, 0, 0, },
};
static struct ROM_INFO rom_majest12[] =
{
LOAD8_16( REGION_ROM1, 0x000000, 0x00020000,
"c64_07.10", 0xf29ed5c9, "c64_08.11", 0xddfd33d5),
LOAD8_16( REGION_ROM1, 0x040000, 0x00020000,
"c64_06.4", 0x18dc71ac, "c64_05.5", 0xb61866c0),
{ NULL, 0, 0, 0, 0, 0, },
};
static struct ROM_INFO rom_dondokdj[] =
{
LOAD8_16( REGION_ROM1, 0x00000, 0x20000,
"b95-12.bin", 0xd0fce87a, "b95-11-1.bin", 0xdad40cd3),
LOAD8_16( REGION_ROM1, 0x40000, 0x20000,
"b95-10.bin", 0xa46e1f0b, "b95-wrld.7", 0x6e4e1351),
{ "b95-02.bin", 0x80000, 0x67b4e979, REGION_GFX1, 0x00000, LOAD_NORMAL },
{ "b95-01.bin", 0x80000, 0x51c176ce, REGION_GFX2, 0x00000, LOAD_NORMAL },
{ "b95-03.bin", 0x80000, 0x543aa0d1, REGION_GFX3, 0x00000, LOAD_NORMAL },
{ "b95-08.bin", 0x10000, 0xb5aa49e1, REGION_ROM2, 0, LOAD_NORMAL },
/* no Delta-T samples */
{ "b95-04.bin", 0x80000, 0xac4c1716, REGION_SMP1, 0x00000, LOAD_NORMAL },
{ NULL, 0, 0, 0, 0, 0 }
};
static struct ROM_INFO rom_megab[] =
{
LOAD8_16( REGION_ROM1, 0x00000, 0x20000,
"c11-07.55", 0x11d228b6, "c11-08.39", 0xa79d4dca),
LOAD8_16( REGION_ROM1, 0x40000, 0x20000,
"c11-06.54", 0x7c249894, "c11-11.38", 0x263ecbf9),
{ "c11-05.58", 0x80000, 0x733e6d8e, REGION_GFX1, 0x00000, LOAD_NORMAL },
LOAD8_16( REGION_GFX2, 0x00000, 0x80000,
"c11-03.32", 0x46718c7a, "c11-04.31", 0x663f33cc),
{ "c11-12.3", 0x10000, 0xb11094f1, REGION_ROM2, 0, LOAD_NORMAL },
{ "c11-01.29", 0x80000, 0xfd1ea532, REGION_SMP1, 0x00000, LOAD_NORMAL },
/*Pals b89-01.8 b89-02.28 b89-04.27 c11-13.13 c11-14.23 */
{ "c11-02.30", 0x80000, 0x451cc187, REGION_SMP2, 0x00000, LOAD_NORMAL },
{ NULL, 0, 0, 0, 0, 0 }
};
static struct ROM_INFO rom_liquidk[] =
{
LOAD8_16( REGION_ROM1, 0x00000, 0x20000,
"c49_09.12", 0x6ae09eb9, "c49_11.14", 0x42d2be6e),
LOAD8_16( REGION_ROM1, 0x40000, 0x20000,
"c49_10.13", 0x50bef2e0, "c49_12.15", 0xcb16bad5),
{ "lk_scr.bin", 0x80000, 0xc3364f9b, REGION_GFX1, 0x00000, LOAD_NORMAL },
{ "lk_obj0.bin", 0x80000, 0x67cc3163, REGION_GFX2, 0x00000, LOAD_NORMAL },
{ "lk_obj1.bin", 0x80000, 0xd2400710, REGION_GFX2, 0x80000, LOAD_NORMAL },
{ "c49_08.9", 0x10000, 0x413c310c, REGION_ROM2, 0, LOAD_NORMAL },
/* no Delta-T samples */
{ "lk_snd.bin", 0x80000, 0x474d45a4, REGION_SMP1, 0x00000, LOAD_NORMAL },
{ NULL, 0, 0, 0, 0, 0 }
};
static struct ROM_INFO rom_pulirula[] =
{
LOAD8_16( REGION_ROM1, 0x00000, 0x40000,
"c98-12.rom", 0x816d6cde, "c98-16.rom", 0x59df5c77),
LOAD8_16( REGION_ROM1, 0x80000, 0x20000,
"c98-06.rom", 0x64a71b45, "c98-07.rom", 0x90195bc0),
{ "c98-04.rom", 0x100000, 0x0e1fe3b2, REGION_GFX1, 0x000000, LOAD_NORMAL },
{ "c98-02.rom", 0x100000, 0x4a2ad2b3, REGION_GFX2, 0x000000, LOAD_NORMAL },
{ "c98-03.rom", 0x100000, 0x589a678f, REGION_GFX2, 0x100000, LOAD_NORMAL },
{ "c98-05.rom", 0x080000, 0x9ddd9c39, REGION_GFX3, 0x000000, LOAD_NORMAL },
{ "c98-14.rom", 0x20000, 0xa858e17c, REGION_ROM2, 0, LOAD_NORMAL },
/* no Delta-T samples */
{ "c98-01.rom", 0x100000, 0x197f66f5, REGION_SMP1, 0x000000, LOAD_NORMAL },
{ NULL, 0, 0, 0, 0, 0 }
};
/*
static struct ROM_INFO koshien_roms[] =
{
LOAD8_16( REGION_ROM1, 0x000000, 0x020000,
"c81-11.bin", 0xb44ea8c9, "c81-10.bin", 0x8f98c40a),
{ "c81-04.bin", 0x080000, 0x1592b460, REGION_ROM1, 0x080000, LOAD_SWAP_16 },
{ "c81-03.bin", 0x100000, 0x29bbf492, REGION_GFX1, 0x000000, LOAD_NORMAL },
{ "c81-01.bin", 0x100000, 0x64b15d2a, REGION_GFX2, 0x000000, LOAD_NORMAL },
{ "c81-02.bin", 0x100000, 0x962461e8, REGION_GFX2, 0x100000, LOAD_NORMAL },
{ "c81-12.bin", 0x10000, 0x6e8625b6, REGION_ROM2, 0, LOAD_NORMAL },
{ "c81-05.bin", 0x80000, 0x9c3d71be, REGION_SMP1, 0x00000, LOAD_NORMAL },
{ "c81-06.bin", 0x80000, 0x927833b4, REGION_SMP2, 0x00000, LOAD_NORMAL },
{ NULL, 0, 0, 0, 0, 0 }
};
*/
static struct INPUT_INFO input_f2b1[] =
{
INP0( COIN1, 0xe, 0x04 ),
INP0( COIN2, 0xe, 0x08 ),
INP0( TILT, 0xe, 0x01 ),
INP0( SERVICE, 0xe, 0x02 ),
INP0( P1_START, 0x4, 0x80 ),
INP0( P1_UP, 0x4, 0x01 ),
INP0( P1_DOWN, 0x4, 0x02 ),
INP0( P1_LEFT, 0x4, 0x04 ),
INP0( P1_RIGHT, 0x4, 0x08 ),
INP0( P1_B1, 0x4, 0x10 ),
INP0( P2_START, 0x6, 0x80 ),
INP0( P2_UP, 0x6, 0x01 ),
INP0( P2_DOWN, 0x6, 0x02 ),
INP0( P2_LEFT, 0x6, 0x04 ),
INP0( P2_RIGHT, 0x6, 0x08 ),
INP0( P2_B1, 0x6, 0x10 ),
END_INPUT
};
static struct INPUT_INFO input_f2b2[] =
{
INCL_INP( f2b1 ),
INP0( P1_B2, 0x4, 0x20 ),
INP0( P2_B2, 0x6, 0x20 ),
END_INPUT
};
// 3 buttons
static struct INPUT_INFO input_f2b3[] =
{
INCL_INP( f2b2 ),
INP0( P1_B3, 0x4, 0x40 ),
INP0( P2_B3, 0x6, 0x40 ),
END_INPUT
};
// 4 players
static struct INPUT_INFO input_growl[] =
{
INP0( COIN1, 0x032384, 0x04 ),
INP0( COIN2, 0x032384, 0x08 ),
INP0( TILT, 0x032384, 0x01 ),
INP0( SERVICE, 0x032384, 0x02 ),
INP0( P1_START, 0x032380, 0x80 ),
INP0( P1_UP, 0x032380, 0x01 ),
INP0( P1_DOWN, 0x032380, 0x02 ),
INP0( P1_LEFT, 0x032380, 0x04 ),
INP0( P1_RIGHT, 0x032380, 0x08 ),
INP0( P1_B1, 0x032380, 0x10 ),
INP0( P1_B2, 0x032380, 0x20 ),
INP0( P1_B3, 0x032380, 0x40 ),
INP0( P2_START, 0x032382, 0x80 ),
INP0( P2_UP, 0x032382, 0x01 ),
INP0( P2_DOWN, 0x032382, 0x02 ),
INP0( P2_LEFT, 0x032382, 0x04 ),
INP0( P2_RIGHT, 0x032382, 0x08 ),
INP0( P2_B1, 0x032382, 0x10 ),
INP0( P2_B2, 0x032382, 0x20 ),
INP0( P2_B3, 0x032382, 0x40 ),
INP0( P3_UP, 0x04, 0x01 ),
INP0( P3_DOWN, 0x04, 0x02 ),
INP0( P3_LEFT, 0x04, 0x04 ),
INP0( P3_RIGHT, 0x04, 0x08 ),
INP0( P3_B1, 0x04, 0x10 ),
INP0( P3_B2, 0x04, 0x20 ),
INP0( P3_B3, 0x04, 0x40 ),
INP0( P3_START, 0x04, 0x80 ),
INP0( P4_UP, 0x05, 0x01 ),
INP0( P4_DOWN, 0x05, 0x02 ),
INP0( P4_LEFT, 0x05, 0x04 ),
INP0( P4_RIGHT, 0x05, 0x08 ),
INP0( P4_B1, 0x05, 0x10 ),
INP0( P4_B2, 0x05, 0x20 ),
INP0( P4_B3, 0x05, 0x40 ),
INP0( P4_START, 0x05, 0x80 ),
INP0( COIN3, 0x06, 0x01 ),
INP0( COIN4, 0x06, 0x02 ),
INP0( SERVICE, 6, 0x04 ),
END_INPUT
};
// mahjong quest inputs (generated by conv_inputs.pl from the mame source...)
static struct INPUT_INFO input_mjnquest[] =
{
INP0( P1_A, 0x00, 0x01 ),
INP0( P1_E, 0x00, 0x02 ),
INP0( P1_I, 0x00, 0x04 ),
INP0( P1_M, 0x00, 0x08 ),
INP0( P1_KAN, 0x00, 0x10 ),
INP0( P1_START, 0x00, 0x20 ),
INP0( P1_B, 0x02, 0x01 ),
INP0( P1_F, 0x02, 0x02 ),
INP0( P1_J, 0x02, 0x04 ),
INP0( P1_N, 0x02, 0x08 ),
INP0( P1_REACH, 0x02, 0x10 ),
INP0( P1_C, 0x04, 0x01 ),
INP0( P1_G, 0x04, 0x02 ),
INP0( P1_K, 0x04, 0x04 ),
INP0( P1_CHI, 0x04, 0x08 ),
INP0( P1_RON, 0x04, 0x10 ),
INP0( P1_D, 0x06, 0x01 ),
INP0( P1_H, 0x06, 0x02 ),
INP0( P1_L, 0x06, 0x04 ),
INP0( P1_PON, 0x06, 0x08 ),
INP0( TILT, 0x0a, 0x01 ),
INP0( COIN2, 0x0a, 0x02 ),
INP0( SERVICE, 0x0c, 0x01 ),
INP0( COIN1, 0x0c, 0x02 ),
END_INPUT
};
#define TAITO_COINAGE_WORLD_8 \
{ MSG_COIN1, 0x30, 4 },\
{ MSG_4COIN_1PLAY, 0x00, 0x00 },\
{ MSG_3COIN_1PLAY, 0x10, 0x00 },\
{ MSG_2COIN_1PLAY, 0x20, 0x00 },\
{ MSG_1COIN_1PLAY, 0x30, 0x00 },\
{ MSG_COIN2, 0xc0, 4 },\
{ MSG_1COIN_1PLAY, 0xc0, 0x00 },\
{ MSG_1COIN_3PLAY, 0x80, 0x00 },\
{ MSG_1COIN_4PLAY, 0x40, 0x00 },\
{ MSG_1COIN_6PLAY, 0x00, 0x00 },\
#define TAITO_DIFFICULTY_8 \
{ MSG_DIFFICULTY, 0x03, 4 },\
{ "Easy" , 0x02, 0x00 },\
{ "Medium" , 0x03, 0x00 },\
{ "Hard" , 0x01, 0x00 },\
{ "Hardest" , 0x00, 0x00 },\
static struct DSW_DATA dsw_data_camel_try_0[] =
{
{ _("Game Style"), 0x01, 0x02 },
{ _("Table"), 0x01},
{ _("Upright"), 0x00},
DSW_SCREEN( 0x02, 0x00),
DSW_TEST_MODE( 0x00, 0x04),
DSW_DEMO_SOUND( 0x08, 0x00),
{ MSG_COIN1, 0x30, 0x04 },
{ MSG_1COIN_1PLAY, 0x30},
{ MSG_1COIN_2PLAY, 0x20},
{ MSG_2COIN_1PLAY, 0x10},
{ MSG_2COIN_3PLAY, 0x00},
{ MSG_COIN2, 0xC0, 0x04 },
{ MSG_1COIN_1PLAY, 0xC0},
{ MSG_1COIN_2PLAY, 0x80},
{ MSG_2COIN_1PLAY, 0x40},
{ MSG_2COIN_3PLAY, 0x00},
{ NULL, 0, },
};
static struct DSW_DATA dsw_data_camel_try_1[] =
{
{ MSG_DIFFICULTY, 0x03, 0x04 },
{ MSG_NORMAL, 0x03},
{ MSG_EASY, 0x02},
{ MSG_HARD, 0x01},
{ MSG_HARDEST, 0x00},
{ _("Start Time"), 0x0C, 0x04 },
{ _("50 sec"), 0x0C},
{ _("60 sec"), 0x08},
{ _("40 sec"), 0x04},
{ _("35 sec"), 0x00},
{ _("Continue Time Add"), 0x30, 0x04 },
{ _("30 sec"), 0x30},
{ _("40 sec"), 0x20},
{ _("25 sec"), 0x10},
{ _("20 sec"), 0x00},
DSW_CONTINUE_PLAY( 0x40, 0x00),
{ _("2 Player Mode"), 0x80, 0x02 },
{ _("Single"), 0x80},
{ _("Together"), 0x00},
{ NULL, 0, },
};
static struct DSW_INFO dsw_cameltry[] =
{
{ 0x00, 0xFF, dsw_data_camel_try_0 },
{ 0x02, 0xFF, dsw_data_camel_try_1 },
{ 0, 0, NULL, },
};
static struct DSW_DATA dsw_data_final_blow_0[] =
{
DSW_SCREEN( 0x02, 0x00),
DSW_TEST_MODE( 0x00, 0x04),
DSW_DEMO_SOUND( 0x08, 0x00),
{ MSG_COIN1, 0x30, 0x04 },
{ MSG_1COIN_1PLAY, 0x30},
{ MSG_1COIN_2PLAY, 0x20},
{ MSG_2COIN_1PLAY, 0x10},
{ MSG_2COIN_3PLAY, 0x00},
{ MSG_COIN2, 0xC0, 0x04 },
{ MSG_1COIN_1PLAY, 0xC0},
{ MSG_1COIN_2PLAY, 0x80},
{ MSG_2COIN_1PLAY, 0x40},
{ MSG_2COIN_3PLAY, 0x00},
{ NULL, 0, },
};
static struct DSW_DATA dsw_data_final_blow_1[] =
{
{ MSG_DIFFICULTY, 0x03, 0x04 },
{ MSG_NORMAL, 0x03},
{ MSG_EASY, 0x02},
{ MSG_HARD, 0x01},
{ MSG_HARDEST, 0x00},
{ NULL, 0, },
};
static struct DSW_INFO dsw_finalb[] =
{
{ 0x0, 0xFF, dsw_data_final_blow_0 },
{ 0x2, 0xFF, dsw_data_final_blow_1 },
{ 0, 0, NULL, },
};
static struct DSW_DATA dsw_data_dondokod_0[] =
{
{ MSG_UNKNOWN, 0x01, 2 },
{ MSG_OFF, 0x01},
{ MSG_ON, 0x00},
DSW_SCREEN( 0x02, 0x00),
DSW_SERVICE( 0, 0x04),
TAITO_COINAGE_WORLD_8
DSW_DEMO_SOUND( 0x08, 0x00),
{ NULL, 0}
};
static struct DSW_DATA dsw_data_dondokod_1[] =
{
TAITO_DIFFICULTY_8
{ MSG_EXTRA_LIFE, 0x0c, 4 },
{ _("10k and 100k") , 0x0c},
{ _("10k and 150k") , 0x08},
{ _("10k and 250k") , 0x04},
{ _("10k and 350k") , 0x00},
{ MSG_LIVES, 0x30, 4 },
{ "2" , 0x20},
{ "3" , 0x30},
{ "4" , 0x00},
{ "5" , 0x10},
{ MSG_UNKNOWN, 0x40, 2 },
{ MSG_OFF, 0x40},
{ MSG_ON, 0x00},
{ MSG_UNKNOWN, 0x80, 2 },
{ MSG_OFF, 0x80},
{ MSG_ON, 0x00},
{ NULL, 0}
};
static struct DSW_INFO dsw_dondokdj[] =
{
{ 0x00, 0xFF, dsw_data_dondokod_0 },
{ 0x02, 0xFF, dsw_data_dondokod_1 },
{ 0, 0, NULL, },
};
static struct DSW_DATA dsw_data_gunfront_1[] =
{
{ MSG_DIFFICULTY, 0x03, 0x04 },
{ MSG_NORMAL, 0x03},
{ MSG_EASY, 0x02},
{ MSG_HARD, 0x01},
{ MSG_HARDEST, 0x00},
{ MSG_DSWB_BIT3, 0x04, 0x02 },
{ MSG_OFF, 0x04},
{ MSG_ON, 0x00},
{ MSG_DSWB_BIT4, 0x08, 0x02 },
{ MSG_ON, 0x08},
{ MSG_OFF, 0x00},
{ _("Lives"), 0x30, 0x04 },
{ "3", 0x30},
{ "1", 0x20},
{ "2", 0x10},
{ "5", 0x00},
{ _("Continue Mode"), 0x40, 0x02 },
{ MSG_OFF, 0x40},
{ MSG_ON, 0x00},
{ _("Simultaneous Play"), 0x80, 0x02 },
{ MSG_OFF, 0x80},
{ MSG_ON, 0x00},
{ NULL, 0, },
};
static struct DSW_INFO dsw_gunfront[] =
{
{ 0x0, 0xff, dsw_data_dondokod_0 },
{ 0x2, 0xff, dsw_data_gunfront_1 },
{ 0, 0, NULL }
};
static struct DSW_DATA dsw_data_megab_0[] =
{
DSW_CABINET( 0x00,1 ),
DSW_SCREEN( 0x02, 0x00),
DSW_TEST_MODE( 0x00, 0x04),
DSW_DEMO_SOUND( 0x08, 0x00),
{ MSG_COIN1, 0x30, 0x04 },
{ MSG_1COIN_1PLAY, 0x30},
{ MSG_2COIN_1PLAY, 0x20},
{ MSG_3COIN_1PLAY, 0x10},
{ MSG_4COIN_1PLAY, 0x00},
{ MSG_COIN2, 0xC0, 0x04 },
{ MSG_1COIN_2PLAY, 0xC0},
{ MSG_1COIN_3PLAY, 0x80},
{ MSG_1COIN_4PLAY, 0x40},
{ MSG_1COIN_6PLAY, 0x00},
{ NULL, 0, },
};
static struct DSW_DATA dsw_data_mega_blast_1[] =
{
{ MSG_DIFFICULTY, 0x03, 0x04 },
{ MSG_NORMAL, 0x03},
{ MSG_EASY, 0x02},
{ MSG_HARD, 0x01},
{ MSG_HARDEST, 0x00},
{ _("Bonus / K=10,000"), 0x0c, 0x04 },
{ _("10k, 110K, 210K, 310K"), 0x0c, 0x00 },
{ _("20k, 220K, 420K, 620K"), 0x08, 0x00 },
{ _("15K, 145K, 365K, 515K"), 0x04, 0x00 },
{ _("No Bonus Lives"), 0x00},
{ _("Lives"), 0x30, 0x04 },
{ "3", 0x30},
{ "4", 0x20},
{ "1", 0x10},
{ "2", 0x00},
{ _("Control Panel"), 0x40, 0x02 },
{ _("Double"), 0x40},
{ _("Single"), 0x00},
{ NULL, 0, },
};
static struct DSW_INFO dsw_megab[] =
{
{ 0x00, 0xFF, dsw_data_megab_0 },
{ 0x02, 0xFF, dsw_data_mega_blast_1 },
{ 0, 0, NULL, },
};
static struct DSW_DATA dsw_data_liquidk_1[] =
{
TAITO_DIFFICULTY_8
{ MSG_EXTRA_LIFE, 0x0c, 4 },
{ _("30k and 100k") , 0x0c},
{ _("30k and 150k") , 0x08},
{ _("50k and 250k") , 0x04},
{ _("50k and 350k") , 0x00},
{ MSG_LIVES, 0x30, 4 },
{ "2" , 0x20},
{ "3" , 0x30},
{ "4" , 0x00},
{ "5" , 0x10},
{ _("Allow Continue"), 0x40, 2 },
{ MSG_OFF, 0x00},
{ MSG_ON, 0x40},
{ _("Upright Controls"), 0x80, 2 },
{ _("Single") , 0x80},
{ _("Dual") , 0x00},
{ NULL, 0}
};
static struct DSW_INFO dsw_liquidk[] =
{
{ 0x00, 0xFF, dsw_data_megab_0 },
{ 0x02, 0xFF, dsw_data_liquidk_1 },
{ 0, 0, NULL, },
};
static struct DSW_DATA dsw_data_ssi_1[] =
{
TAITO_DIFFICULTY_8
{ _("Shields"), 0x0c, 4 },
{ _("None"), 0x00},
{ "1", 0x0c},
{ "2", 0x04},
{ "3", 0x08},
{ MSG_LIVES, 0x10, 2 },
{ "2", 0x00},
{ "3", 0x10},
{ _("2 Players Mode"), 0xa0, 4 },
{ _("Simultaneous"), 0xa0},
{ _("AlternateSingle"), 0x80},
{ _("AlternateDual"), 0x00},
{ _("Not Allowed"), 0x20},
{ _("Allow Continue"), 0x40, 2 },
{ MSG_OFF, 0x00},
{ MSG_ON, 0x40},
{ NULL, 0}
};
static struct DSW_INFO dsw_ssi[] =
{
{ 0x00, 0xfe, dsw_data_megab_0 },
{ 0x02, 0xff, dsw_data_ssi_1 },
{ 0, 0, NULL }
};
static struct DSW_DATA dsw_data_drift_out_0[] =
{
DSW_SCREEN( 0x02, 0x00),
DSW_TEST_MODE( 0x00, 0x04),
DSW_DEMO_SOUND( 0x08, 0x00),
{ MSG_COIN1, 0x30, 0x04 },
{ MSG_1COIN_1PLAY, 0x30},
{ MSG_2COIN_1PLAY, 0x20},
{ MSG_1COIN_2PLAY, 0x10},
{ MSG_2COIN_3PLAY, 0x00},
{ MSG_COIN2, 0xC0, 0x04 },
{ MSG_1COIN_1PLAY, 0xC0},
{ MSG_2COIN_1PLAY, 0x80},
{ MSG_1COIN_2PLAY, 0x40},
{ MSG_2COIN_3PLAY, 0x00},
{ NULL, 0, },
};
static struct DSW_DATA dsw_data_drift_out_1[] =
{
{ MSG_DIFFICULTY, 0x03, 0x04 },
{ MSG_NORMAL, 0x03},
{ MSG_EASY, 0x02},
{ MSG_HARD, 0x01},
{ MSG_HARDEST, 0x00},
{ _("Control"), 0x0C, 0x04 },
{ _("Lever"), 0x0C},
{ _("Paddle A"), 0x08},
{ _("Lever"), 0x04},
{ _("Paddle B"), 0x00},
{ NULL, 0, },
};
static struct DSW_INFO dsw_driftout[] =
{
{ 0x00, 0xFF, dsw_data_drift_out_0 },
{ 0x02, 0xFF, dsw_data_drift_out_1 },
{ 0, 0, NULL, },
};
static struct DSW_DATA dsw_data_thunder_fox_0[] =
{
{ MSG_DSWA_BIT1, 0x01, 0x02 },
{ MSG_OFF, 0x01},
{ MSG_ON, 0x00},
DSW_SCREEN( 0x02, 0x00),
DSW_TEST_MODE( 0x00, 0x04),
DSW_DEMO_SOUND( 0x08, 0x00),
{ MSG_COIN1, 0x30, 0x04 },
{ MSG_1COIN_1PLAY, 0x30},
{ MSG_2COIN_1PLAY, 0x20},
{ MSG_3COIN_1PLAY, 0x10},
{ MSG_4COIN_1PLAY, 0x00},
{ MSG_COIN2, 0xC0, 0x04 },
{ MSG_1COIN_2PLAY, 0xC0},
{ MSG_1COIN_3PLAY, 0x80},
{ MSG_1COIN_4PLAY, 0x40},
{ MSG_1COIN_6PLAY, 0x00},
{ NULL, 0, },
};
static struct DSW_DATA dsw_data_thunder_fox_1[] =
{
{ MSG_DIFFICULTY, 0x03, 0x04 },
{ MSG_NORMAL, 0x03},
{ MSG_EASY, 0x02},
{ MSG_HARD, 0x01},
{ MSG_HARDEST, 0x00},
{ _("Time Limit"), 0x04, 0x02 },
{ MSG_ON, 0x04},
{ MSG_OFF, 0x00},
{ _("Lives"), 0x30, 0x04 },
{ "3", 0x30},
{ "2", 0x20},
{ "4", 0x10},
{ "5", 0x00},
DSW_CONTINUE_PLAY( 0x40, 0x00),
{ _("Controls"), 0x80, 0x02 },
{ _("Dual"), 0x80},
{ _("Single"), 0x00},
{ NULL, 0, },
};
static struct DSW_INFO dsw_thundfox[] =
{
{ 0x00, 0xFF, dsw_data_thunder_fox_0 },
{ 0x02, 0xFF, dsw_data_thunder_fox_1 },
{ 0, 0, NULL, },
};
static struct DSW_DATA dsw_data_growl_1[] =
{
{ MSG_DIFFICULTY, 0x03, 0x04 },
{ MSG_NORMAL, 0x03},
{ MSG_EASY, 0x02},
{ MSG_HARD, 0x01},
{ MSG_HARDEST, 0x00},
{ _("Game Type"), 0x30, 0x04 },
{ _("1 Credit/2P"), 0x30},
{ _("4 Credits/4P"), 0x20},
{ _("1 Credit/4P"), 0x10},
{ _("2 Credits/4P"), 0x00},
{ _("Final Stage Cont"), 0x40, 0x02 },
{ MSG_OFF, 0x40},
{ MSG_ON, 0x00},
{ NULL, 0, },
};
static struct DSW_INFO dsw_growl[] =
{
{ 0x32100, 0xff, dsw_data_thunder_fox_0 },
{ 0x32102, 0xff, dsw_data_growl_1 },
{ 0, 0, NULL }
};
static struct DSW_DATA dsw_data_dino_rex_1[] =
{
{ MSG_DIFFICULTY, 0x03, 0x04 },
{ MSG_NORMAL, 0x03},
{ MSG_EASY, 0x02},
{ MSG_HARD, 0x01},
{ MSG_HARDEST, 0x00},
{ _("Damage"), 0x0C, 0x04 },
{ MSG_NORMAL, 0x0C},
{ _("Small"), 0x08},
{ _("Big"), 0x04},
{ _("Biggest"), 0x00},
{ _("Timer"), 0x10, 0x02 },
{ MSG_NORMAL, 0x10},
{ _("Fast"), 0x00},
{ _("Match Type"), 0x20, 0x02 },
{ _("Best of 3"), 0x20},
{ _("Single"), 0x00},
{ _("2 Player Mode"), 0x40, 0x02 },
{ _("Upright"), 0x40},
{ _("Cocktail"), 0x00},
{ _("Upright Controls"), 0x80, 0x02 },
{ _("Dual"), 0x80},
{ _("Single"), 0x00},
{ NULL, 0, },
};
static struct DSW_INFO dsw_dinorex[] =
{
{ 0x0, 0xFF, dsw_data_thunder_fox_0 },
{ 0x2, 0xFF, dsw_data_dino_rex_1 },
{ 0, 0, NULL, },
};
static struct DSW_DATA dsw_data_solfigtr_1[] =
{
TAITO_DIFFICULTY_8
{ MSG_UNKNOWN, 0x04, 2 },
{ MSG_OFF, 0x04},
{ MSG_ON, 0x00},
{ MSG_UNKNOWN, 0x08, 2 },
{ MSG_OFF, 0x08},
{ MSG_ON, 0x00},
{ MSG_UNKNOWN, 0x10, 2 },
{ MSG_OFF, 0x10},
{ MSG_ON, 0x00},
{ MSG_UNKNOWN, 0x20, 2 },
{ MSG_OFF, 0x20},
{ MSG_ON, 0x00},
{ MSG_UNKNOWN, 0x40, 2 },
{ MSG_OFF, 0x40},
{ MSG_ON, 0x00},
{ NULL, 0}
};
static struct DSW_INFO dsw_solfigtr[] =
{
{ 0x0, 0xff, dsw_data_dondokod_0 },
{ 0x2, 0xff, dsw_data_solfigtr_1 },
{ 0, 0, NULL }
};
#define TAITO_COINAGE_JAPAN_NEW_8 \
{ MSG_COIN1, 0x30, 4 },\
{ MSG_3COIN_1PLAY, 0x00, 0x00 },\
{ MSG_2COIN_1PLAY, 0x10, 0x00 },\
{ MSG_1COIN_1PLAY, 0x30, 0x00 },\
{ MSG_1COIN_1PLAY, 0x20, 0x00 },\
{ MSG_COIN2, 0xc0, 4 },\
{ MSG_3COIN_1PLAY, 0x00, 0x00 },\
{ MSG_2COIN_1PLAY, 0x40, 0x00 },\
{ MSG_1COIN_1PLAY, 0xc0, 0x00 },\
{ MSG_1COIN_1PLAY, 0x80, 0x00 },\
static struct DSW_DATA dsw_data_pulirulj_0[] =
{
{ MSG_UNKNOWN, 0x01, 2 },
{ MSG_OFF, 0x01},
{ MSG_ON, 0x00},
DSW_SCREEN( 0x02, 0x00),
DSW_SERVICE( 0, 0x04),
TAITO_COINAGE_JAPAN_NEW_8
DSW_DEMO_SOUND( 0x08, 0x00),
{ NULL, 0}
};
// mjnquest has some kind of protection to filter inputs/dsw. I use input_buffer for that
static struct DSW_INFO dsw_mjnquest[] =
{
{ 0xe, 0xff, dsw_data_pulirulj_0 },
{ 0x10, 0xff, dsw_data_solfigtr_1 },
{ 0, 0, NULL }
};
static struct ROMSW_DATA romsw_data_taito_jap_us[] =
{
{ "Taito Japan", 0x01 },
{ "Taito America", 0x02 },
{ "World", 0x03 },
{ NULL, 0 },
};
static struct ROMSW_DATA romsw_data_majestic_twelve_0[] =
{
{ "Taito Japan (MJ12)", 0x01 },
{ "Taito America (MJ12)", 0x02 },
{ "Taito Japan (SSI)", 0x03 },
{ NULL, 0 },
};
static struct ROMSW_DATA romsw_data_thunder_fox_0[] =
{
{ "Taito Japan", 0x00 },
{ "Taito America", 0x01 },
{ "Taito", 0x02 },
{ NULL, 0 },
};
static struct ROMSW_DATA romsw_data_growl_0[] =
{
{ "Taito Japan (Runark)", 0x01 },
{ "Taito America (Growl)", 0x02 },
{ "Taito Worldwide (Growl)", 0x03 },
{ NULL, 0 },
};
static struct ROMSW_DATA romsw_data_camel_try_alt_0[] =
{
{ "Taito Japan (Japanese)", 0x00 },
{ "Taito America", 0x01 },
{ "Taito Japan", 0x02 },
/* { "Taito America (Romstar)",0x03 },
{ "Taito (Phoenix)", 0x04 }, */
{ NULL, 0 },
};
static struct ROMSW_INFO romsw_cameltry[] =
{
{ 0x03FFFF, 0x01, romsw_data_camel_try_alt_0 },
{ 0, 0, NULL },
};
static struct ROMSW_INFO romsw_growl[] =
{
{ 0x0FFFFF, 0x03, romsw_data_growl_0 },
{ 0, 0, NULL },
};
static struct ROMSW_INFO romsw_thundfox[] =
{
{ 0x03FFFF, 0x02, romsw_data_thunder_fox_0 },
{ 0, 0, NULL },
};
static struct ROMSW_INFO romsw_dondokdj[] =
{
{ 0x077FFF, 0x03, romsw_data_taito_jap_us },
{ 0, 0, NULL },
};
static struct ROMSW_INFO romsw_solfigtr[] =
{
{ 0x03ffff, 0x03, romsw_data_taito_jap_us },
{ 0, 0, NULL },
};
static struct ROMSW_INFO romsw_f2demo[] =
{
{ 0x07FFFF, 0x02, romsw_data_thunder_fox_0 },
{ 0, 0, NULL },
};
static struct ROMSW_INFO romsw_ssi[] =
{
{ 0x07FFFF, 0x03, romsw_data_majestic_twelve_0 },
{ 0, 0, NULL },
};
static struct ROMSW_INFO romsw_liquidk[] =
{
{ 0x07FFFF, 0x03, romsw_data_taito_jap_us },
{ 0, 0, NULL },
};
static GfxLayout tilelayout =
{
16,16, /* 16*16 sprites */
RGN_FRAC(1,1),
4, /* 4 bits per pixel */
{ 0, 1, 2, 3 },
{ 1*4, 0*4, 3*4, 2*4, 5*4, 4*4, 7*4, 6*4, 9*4, 8*4, 11*4, 10*4, 13*4, 12*4, 15*4, 14*4 },
{ 0*64, 1*64, 2*64, 3*64, 4*64, 5*64, 6*64, 7*64, 8*64, 9*64, 10*64, 11*64, 12*64, 13*64, 14*64, 15*64 },
128*8 /* every sprite takes 128 consecutive bytes */
};
static GfxLayout charlayout =
{
8,8, /* 8*8 characters */
RGN_FRAC(1,1),
4, /* 4 bits per pixel */
{ 0, 1, 2, 3 },
{ 2*4, 3*4, 0*4, 1*4, 6*4, 7*4, 4*4, 5*4 },
{ 0*32, 1*32, 2*32, 3*32, 4*32, 5*32, 6*32, 7*32 },
32*8 /* every sprite takes 32 consecutive bytes */
};
static GfxLayout pivotlayout =
{
8,8, /* 8*8 characters */
RGN_FRAC(1,1),
4, /* 4 bits per pixel */
{ 0, 1, 2, 3 },
{ 0*4, 1*4, 2*4, 3*4, 4*4, 5*4, 6*4, 7*4 },
{ 0*32, 1*32, 2*32, 3*32, 4*32, 5*32, 6*32, 7*32 },
32*8 /* every sprite takes 32 consecutive bytes */
};
static GfxLayout finalb_tilelayout =
{
16,16, /* 16*16 sprites */
RGN_FRAC(1,2),
6, /* 6 bits per pixel */
{ RGN_FRAC(1,2)+0, RGN_FRAC(1,2)+1, 0, 1, 2, 3 },
{ 3*4, 2*4, 1*4, 0*4, 7*4, 6*4, 5*4, 4*4,
11*4, 10*4, 9*4, 8*4, 15*4, 14*4, 13*4, 12*4 },
{ 0*64, 1*64, 2*64, 3*64, 4*64, 5*64, 6*64, 7*64,
8*64, 9*64, 10*64, 11*64, 12*64, 13*64, 14*64, 15*64 },
128*8 /* every sprite takes 128 consecutive bytes */
};
static struct GFX_LIST pivot_gfxdecodeinfo[] =
{
{ REGION_GFX1, &charlayout }, // 256 color banks
{ REGION_GFX2, &tilelayout }, // 256 color banks
{ REGION_GFX3, &pivotlayout }, // 256 color banks
{ 0, NULL } /* end of array */
};
static struct GFX_LIST thundfox_decodeinfo[] =
{
{ REGION_GFX1, &charlayout }, // tc100scn #0
{ REGION_GFX2, &tilelayout }, // 256 color banks
{ REGION_GFX3, &charlayout }, // tc100scn #1
{ 0, NULL } /* end of array */
};
// REGION_GFX3 is empty
static struct GFX_LIST finalb_gfxdecodeinfo[] =
{
{ REGION_GFX1, &charlayout }, // 256 color banks
{ REGION_GFX2, &finalb_tilelayout },
{ 0, NULL } /* end of array */
};
static struct GFX_LIST mjnquest_gfxdecodeinfo[] =
{
{ REGION_GFX1, &charlayout }, // 256 color banks
{ REGION_GFX2, &tilelayout },
{ 0, NULL } /* end of array */
};
static UINT8 *RAM_VIDEO,*RAM_VIDEO2,*GFX_BANK;
static UINT8 *RAM_SCROLL,*RAM_SCROLL2;
static UINT8 *RAM_OBJECT;
static UINT8 *RAM_INPUT;
static UINT8 *RAM_ROTATE;
static struct layer {
UINT32 pri,num;
} layer[16];
static int layer_cmp(const void *a, const void *b) {
return ((struct layer *)a)->pri - ((struct layer *)b)->pri;
}
static void load_common() {
UINT32 size = get_region_size(REGION_CPU1);
RAMSize=0x50000;
if(!(RAM=AllocateMem(0x40000+0x14000))) return;
/*-----------------------*/
memset(RAM+0x00000,0x00,0x40000);
// make_solid_mask not called for GFX3.
ByteSwap(ROM,size);
AddMemFetch(0x000000, size-1, ROM+0x000000-0x000000); // 68000 ROM
AddMemFetch(-1, -1, NULL);
AddReadBW(0x000000, size-1, NULL, ROM+0x000000); // 68000 ROM
}
static int init_gfx;
static void setup_gfx() {
// Init tc0200obj emulation
// ------------------------
init_gfx = 0;
tc0200obj.RAM = RAM_OBJECT+0x0000;
tc0200obj.RAM_B = NULL;
tc0200obj.ofs_x = -3;
tc0200obj.ofs_y = 0; // sprite type now
// Init tc0100scn emulation
// ------------------------
tc0100scn[0].layer[0].RAM =RAM_VIDEO+0x0000;
tc0100scn[0].layer[0].SCR =RAM_SCROLL+0;
tc0100scn[0].layer[0].type =0;
tc0100scn[0].layer[0].bmp_x =32;
tc0100scn[0].layer[0].bmp_y =32;
tc0100scn[0].layer[0].bmp_w =320;
tc0100scn[0].layer[0].bmp_h =224;
tc0100scn[0].layer[1].RAM =RAM_VIDEO+0x8000;
tc0100scn[0].layer[1].SCR =RAM_SCROLL+2;
tc0100scn[0].layer[1].type =0;
tc0100scn[0].layer[1].bmp_x =32;
tc0100scn[0].layer[1].bmp_y =32;
tc0100scn[0].layer[1].bmp_w =320;
tc0100scn[0].layer[1].bmp_h =224;
tc0100scn[0].layer[2].RAM =RAM_VIDEO+0x4000;
tc0100scn[0].layer[2].GFX =GFX_FG0;
tc0100scn[0].layer[2].SCR =RAM_SCROLL+4;
tc0100scn[0].layer[2].type =3;
tc0100scn[0].layer[2].bmp_x =32;
tc0100scn[0].layer[2].bmp_y =32;
tc0100scn[0].layer[2].bmp_w =320;
tc0100scn[0].layer[2].bmp_h =224;
tc0100scn[0].RAM = RAM_VIDEO;
tc0100scn[0].GFX_FG0 = GFX_FG0;
tc0100scn[0].layer[0].scr_x =16-3;
tc0100scn[0].layer[0].scr_y =8;
tc0100scn[0].layer[1].scr_x =13; // -80 for f2demo !
tc0100scn[0].layer[1].scr_y =8;
tc0100scn[0].layer[2].scr_x =13;
tc0100scn[0].layer[2].scr_y =8;
if (load_region[REGION_GFX3] && tc0005rot.RAM) {
// to init pixel_bitmap in tc005rot (will be called in finish_setup_gfx again)
tc0005rot.GFX_ROT = load_region[REGION_GFX3]; // init this to tell loadroms that we
// don't want to call make_solid_region on it
init_tc0005rot();
}
}
static void finish_setup_gfx() {
// called when the layouts have been applied
init_gfx = 1;
tc0200obj.GFX = gfx2;
tc0200obj.MASK = gfx2_solid;
tc0100scn[0].layer[0].GFX =GFX;
tc0100scn[0].layer[0].MASK =gfx_solid[0];
tc0100scn[0].layer[1].GFX =GFX;
tc0100scn[0].layer[1].MASK =gfx_solid[0];
tc0200obj.tile_mask = max_sprites[1]-1;
tc0100scn[0].layer[0].tile_mask=max_sprites[0]-1;
tc0100scn[0].layer[1].tile_mask=max_sprites[0]-1;
init_tc0200obj();
if (gfx3 && tc0005rot.RAM) {
tc0005rot.GFX_ROT = gfx3;
if (is_current_game("pulirula") || is_current_game("driftout") ||
is_current_game("driveout"))
init_tc430grw();
else
init_tc0005rot();
{
int max = 0;
int size = get_region_size(REGION_GFX3);
int n;
for (n=0; n<size; n++) {
if (gfx3[n] > max)
max = n;
}
}
}
}
static void load_common_cameltry() {
UINT8 *RAM_COLOUR;
// 68000 Speed Hack
WriteLong68k(&ROM[0x00BA2],0x13FC0000); // move.b #$00,$AA0000
WriteLong68k(&ROM[0x00BA6],0x00AA0000);
WriteWord68k(&ROM[0x00BAA],0x6100-16); // bra.s <loop>
// Set vcu type
WriteWord68k(&ROM[0x3FF8C],0x0000);
load_common();
RAM_OBJECT = RAM+0x10000;
RAM_ROTATE = RAM+0x34000;
RAM_COLOUR = RAM+0x36000;
RAM_VIDEO = RAM+0x20000;
RAM_SCROLL = RAM+0x38200;
TC0360PRI_regs = RAM+0x38300;
GFX_FG0 = RAM+0x40000;
RAMSize = 0x38320;
set_colour_mapper(&col_map_rrrr_gggg_bbbb_xxxx);
InitPaletteMap(RAM_COLOUR, 0x100, 0x10, 0x1000);
// Init tc0220ioc emulation
// ------------------------
tc0220ioc.RAM = input_buffer;
tc0220ioc.ctrl = 0; //TC0220_STOPCPU;
reset_tc0220ioc();
// Init tc0005rot emulation
// ------------------------
tc0005rot.RAM = RAM_ROTATE;
tc0005rot.RAM_SCR = RAM+0x30100;
setup_gfx();
tc0100scn[0].layer[2].scr_x =19;
tc0200obj.ofs_x = 8;
init_tc0100scn(0);
AddRWBW(0x100000, 0x10FFFF, NULL, RAM+0x000000); // 68000 RAM
AddRWBW(0x900000, 0x90fFFF, NULL, RAM_OBJECT); // OBJECT RAM
AddWriteByte(0x806000, 0x806FFF, tc0100scn_0_gfx_fg0_wb, NULL); // FG0 GFX RAM
AddWriteWord(0x806000, 0x806FFF, tc0100scn_0_gfx_fg0_ww, NULL); // FG0 GFX RAM
AddRWBW(0x800000, 0x813FFF, NULL, RAM_VIDEO); // SCREEN RAM
AddWriteWord(0xA00000, 0xA01FFF, tc0005rot_bg0_ww, NULL); // SCREEN RAM (ROTATE)
AddRWBW(0xA00000, 0xA01FFF, NULL, RAM_ROTATE); // SCREEN RAM (ROTATION)
AddReadByte(0x320000, 0x320003, tc0140syt_read_main_68k, NULL); // SOUND COMM
AddReadBW(0x300000, 0x30001F, NULL, input_buffer); // INPUT RAM
AddReadByte(0x000000, 0xFFFFFF, DefBadReadByte, NULL); // <Bad Reads>
AddReadByte(-1, -1, NULL, NULL);
AddReadWord(0x200000, 0x201FFF, NULL, RAM_COLOUR); // COLOR RAM
AddWriteWord(0x200000, 0x201FFF, NULL, RAM_COLOUR); // COLOR RAM
AddReadWord(0x000000, 0xFFFFFF, DefBadReadWord, NULL); // <Bad Reads>
AddReadWord(-1, -1,NULL, NULL);
AddWriteByte(0x320000, 0x320003, tc0140syt_write_main_68k, NULL); // SOUND COMM
AddWriteByte(0x300000, 0x30001F, tc0220ioc_wb, NULL); // INPUT RAM
AddWriteByte(0xAA0000, 0xAA0001, Stop68000, NULL); // Trap Idle 68000
AddWriteByte(0x000000, 0xFFFFFF, DefBadWriteByte, NULL); // <Bad Writes>
AddWriteByte(-1, -1, NULL, NULL);
AddWriteWord(0xA02000, 0xA0200F, NULL, RAM+0x030100); // SCROLL RAM (ROTATION)
AddWriteWord(0x820000, 0x82000F, NULL, RAM_SCROLL); // SCROLL RAM
AddWriteWord(0xD00000, 0xD0001F, NULL, TC0360PRI_regs); // Priorities
AddWriteWord(0x300000, 0x30001F, tc0220ioc_ww, NULL); // INPUT RAM
AddWriteWord(0x000000, 0xFFFFFF, DefBadWriteWord, NULL); // <Bad Writes>
AddWriteWord(-1, -1, NULL, NULL);
AddInitMemory(); // Set Starscream mem pointers...
GameMouse=1;
}
static void load_cameltry() {
load_common_cameltry();
AddTaitoYM2610(0x01E6, 0x0185, 0x10000);
}
static struct YM2203interface ym2203_interface =
{
1, /* 1 chip ??? */
3000000, /* 3 MHz ??? (tempo much too fast @4) */
{ YM2203_VOL(60,20) },
{ 0 }, /* portA read */
{ 0 },
{ NULL }, // camltrua_porta_w }, /* portA write - not implemented */
{ 0 }, /* portB write */
{ z80_irq_handler }
};
static struct SOUND_INFO sound_camltrua[] =
{
{ SOUND_YM2203, &ym2203_interface, },
{ 0, NULL, },
};
static void load_camltrua() {
/* Alt version with YM2203 sound missing ADPCM chip? Also sound tempo
may be fractionally too slow. */
/* This alternate version seems quite experimental, I take its specificities from mame */
UINT8 *z80_ram;
load_common_cameltry();
z80_ram = RAM + RAMSize;
AddZ80AROMBase(Z80ROM, 0x0038, 0x0066);
AddZ80ARead(0x0000, 0x7FFF, NULL, Z80ROM); // No bank control found
AddZ80ARead(0x8000, 0x8fff, NULL, z80_ram);
AddZ80ARead(0x9000, 0x9000, YM2203_status_port_0_r, NULL);
AddZ80ARead(0xa001, 0xa001, tc0140syt_read_sub_z80, NULL);
AddZ80AWrite(0x8000,0x8fff, NULL, z80_ram);
AddZ80AWrite(0x9000,0x9000, YM2203_control_port_0_w, NULL);
AddZ80AWrite(0x9001,0x9001, YM2203_write_port_0_w, NULL);
AddZ80AWrite(0xa000,0xa001, tc0140syt_write_sub_z80, NULL);
AddZ80ARead(0, 0xffff, DefBadReadZ80, NULL);
AddZ80ARead ( -1, -1, NULL, NULL);
AddZ80AWrite (0x0000, 0xFFFF, DefBadWriteZ80, NULL);
AddZ80AWrite( -1, -1, NULL, NULL);
AddZ80AReadPort(0x00, 0xFF, DefBadReadZ80, NULL);
AddZ80AReadPort( -1, -1, NULL, NULL);
// AddZ80AWritePort(0xAA, 0xAA, StopZ80Mode2, NULL);
AddZ80AWritePort(0x00, 0xFF, DefBadWriteZ80, NULL);
AddZ80AWritePort( -1, -1, NULL, NULL);
AddZ80AInit();
}
static void load_gunfront() {
// speed hack
WriteWord68k(&ROM[0x151DE],0x4EF9); // jmp $0000C0
WriteLong68k(&ROM[0x151E0],0x000000C0);
WriteLong68k(&ROM[0x000C0],0x13FC0000); // move.b #$00,$AA0000
WriteLong68k(&ROM[0x000C4],0x00AA0000);
WriteWord68k(&ROM[0x000C8],0x082D); // btst #2,-32762(a5)
WriteLong68k(&ROM[0x000CA],0x00028006);
WriteWord68k(&ROM[0x000CE],0x6700+(0x100-0x10)); // beq.s <loop>
WriteWord68k(&ROM[0x000D0],0x082D); // btst #5,-1223(a5)
WriteLong68k(&ROM[0x000D2],0x0005FB39);
WriteWord68k(&ROM[0x000D6],0x6600+(0x100-0x18)); // bne.s <loop>
WriteWord68k(&ROM[0x000D8],0x4EF9); // jmp $0151EE
WriteLong68k(&ROM[0x000DA],0x000151EE);
// scroll hack
WriteLong68k(&ROM[0x10DFC],0x4EB80100); // jsr $100.w
WriteWord68k(&ROM[0x00100],0x4EB9); // jsr $1101C
WriteLong68k(&ROM[0x00102],0x0001101C);
WriteLong68k(&ROM[0x00106],0x13FC0000); // move.b #$00,$AA0000
WriteLong68k(&ROM[0x0010A],0x00AA0000);
WriteWord68k(&ROM[0x0010E],0x4E75); // rts
load_common();
AddTaitoYM2610(0x01A4, 0x0150, 0x10000);
RAM_VIDEO = RAM+0x10000;
RAM_SCROLL = RAM+0x32000;
RAM_OBJECT = RAM+0x20000;
TC0360PRI_regs = RAM+0x32200;
GFX_FG0 = RAM+0x35000;
RAMSize = 0x33000;
set_colour_mapper(&col_map_rrrr_gggg_bbbb_xxxx);
InitPaletteMap(RAM+0x30000, 0x100, 0x10, 0x1000);
setup_gfx();
// Init tc0220ioc emulation
// ------------------------
tc0220ioc.RAM = input_buffer;
tc0220ioc.ctrl = 0; //TC0220_STOPCPU;
reset_tc0220ioc();
// Init tc0100scn emulation
// ------------------------
tc0100scn[0].layer[0].scr_x =19;
tc0100scn[0].layer[1].scr_x =19; // -80 for f2demo !
tc0100scn[0].layer[2].scr_x =19;
tc0200obj.ofs_x = 8+1;
init_tc0100scn(0);
AddRWBW(0x100000, 0x10FFFF, NULL, RAM+0x000000); // 68000 RAM
AddWriteByte(0x806000, 0x806FFF, tc0100scn_0_gfx_fg0_wb, NULL); // FG0 GFX RAM
AddWriteWord(0x806000, 0x806FFF, tc0100scn_0_gfx_fg0_ww, NULL); // FG0 GFX RAM
AddRWBW(0x800000, 0x80FFFF, NULL, RAM_VIDEO); // SCREEN RAM
AddRWBW(0x900000, 0x90FFFF, NULL, RAM_OBJECT); // OBJECT RAM
AddReadByte(0x300000, 0x30000F, tc0220ioc_rb_bswap, NULL); // INPUT
AddReadByte(0x320000, 0x320003, tc0140syt_read_main_68k, NULL); // SOUND COMM
AddReadWord(0x200000, 0x201FFF, NULL, RAM+0x030000); // COLOR RAM
AddReadWord(0x300000, 0x30000F, tc0220ioc_rw_bswap, NULL); // INPUT
AddWriteByte(0x320000, 0x320003, tc0140syt_write_main_68k, NULL); // SOUND COMM
AddWriteByte(0x300000, 0x30000F, tc0220ioc_wb_bswap, NULL); // INPUT
AddWriteByte(0xAA0000, 0xAA0001, Stop68000, NULL); // Trap Idle 68000
AddWriteWord(0x200000, 0x201FFF, NULL, RAM+0x030000); // COLOR RAM
AddWriteWord(0x820000, 0x82000F, NULL, RAM_SCROLL); // SCROLL RAM
AddWriteWord(0xB00000, 0xB0001F, NULL, TC0360PRI_regs); // ??? RAM
AddWriteWord(0x300000, 0x30000F, tc0220ioc_ww_bswap, NULL); // INPUT
finish_conf_68000(0);
}
static void load_growl() {
UINT8 *RAM_COLOUR;
// Addresses in rom :
// 1124 : sound mode
// called from 7542 from f34 (int 5)
ROM[0x01010]=0x4E; // SKIP OLD CODE (NO ROOM FOR HACK)
ROM[0x01011]=0xF9; // (JMP $72900)
ROM[0x01012]=0x00;
ROM[0x01013]=0x07;
ROM[0x01014]=0x29;
ROM[0x01015]=0x00;
ROM[0x72900]=0x4E; // jsr $BB4
ROM[0x72901]=0xB9; // (random number)
ROM[0x72902]=0x00;
ROM[0x72903]=0x00;
ROM[0x72904]=0x0B;
ROM[0x72905]=0xB4;
ROM[0x72906]=0x13; // move.b #$00,$AA0000
ROM[0x72907]=0xFC; // (Speed Hack)
ROM[0x72908]=0x00;
ROM[0x72909]=0x00;
ROM[0x7290A]=0x00;
ROM[0x7290B]=0xAA;
ROM[0x7290C]=0x00;
ROM[0x7290D]=0x00;
ROM[0x7290E]=0x60; // Loop
ROM[0x7290F]=0x100-16;
// Frame Sync Hack
// ---------------
WriteLong68k(&ROM[0x75B0],0x13FC0000);
WriteLong68k(&ROM[0x75B4],0x00AA0000);
WriteLong68k(&ROM[0x75B8],0x4E714E71);
// Fix Sprite/Int6 Wait
// --------------------
WriteLong68k(&ROM[0x4CEE],0x4E714E71);
load_common();
RAM_VIDEO = RAM+0x10000;
RAM_OBJECT = RAM+0x20000;
RAM_SCROLL = RAM+0x30000;
GFX_BANK = RAM+0x30010;
TC0360PRI_regs = RAM+0x30020;
RAM_INPUT = RAM+0x32100;
GFX_FG0 = RAM+0x32200;
RAM_COLOUR = RAM+0x36100;
RAMSize = 0x38100;
AddTaitoYM2610(0x01A9, 0x0155, 0x10000);
// AddTaitoYM2610(0, 0, 0x10000);
set_colour_mapper(&col_map_rrrr_gggg_bbbb_xxxx);
InitPaletteMap(RAM_COLOUR, 0x100, 0x10, 0x1000);
setup_gfx();
tc0100scn[0].layer[0].scr_x = 0x3+16;
tc0100scn[0].layer[1].scr_x = 0x3+16;
tc0100scn[0].layer[2].scr_x = 0x3+16;
init_tc0100scn(0);
tc0200obj.ofs_x = 0; // - 0x13;
tc0200obj.ofs_y = 0; // - 0x60;
AddRWBW(0x100000, 0x10FFFF, NULL, RAM+0x000000); // 68000 RAM
AddWriteWord(0x806000, 0x806FFF, tc0100scn_0_gfx_fg0_ww, NULL); // FG0 GFX RAM
AddWriteByte(0x806000, 0x806FFF, tc0100scn_0_gfx_fg0_wb, NULL); // FG0 GFX RAM
AddRWBW(0x800000, 0x80FFFF, NULL, RAM_VIDEO); // SCREEN RAM
AddRWBW(0x900000, 0x90FFFF, NULL, RAM_OBJECT); // OBJECT RAM
AddReadBW(0x300000, 0x30000F, NULL, RAM_INPUT); // input (dsw)
AddReadBW(0x320000, 0x32000F, NULL, RAM+0x32380); // INPUT
AddReadBW(0x508000, 0x508001, NULL, &input_buffer[4]); // input player 3
AddReadBW(0x50c000, 0x50c001, NULL, &input_buffer[6]); // input player 3
AddReadByte(0x400000, 0x400003, tc0140syt_read_main_68k, NULL); // SOUND COMM
AddRWBW(0x820000, 0x82000F, NULL, RAM_SCROLL); // SCROLL RAM
AddRWBW(0x200000, 0x201FFF, NULL, RAM_COLOUR); // COLOR RAM
AddRWBW(0x500000, 0x50000F, NULL, GFX_BANK); // OBJECT BANK?
AddReadByte(0x000000, 0xFFFFFF, DefBadReadByte, NULL); // <Bad Reads>
AddReadByte(-1, -1, NULL, NULL);
AddReadWord(0x000000, 0xFFFFFF, DefBadReadWord, NULL); // <Bad Reads>
AddReadWord(-1, -1, NULL, NULL);
// AddWriteByte(0x300000, 0x30000F, tc0220ioc_wb, NULL); // tc0220ioc
AddWriteByte(0x400000, 0x400003, tc0140syt_write_main_68k, NULL); // SOUND COMM
AddWriteByte(0xAA0000, 0xAA0001, Stop68000, NULL); // Trap Idle 68000
AddWriteByte(0x000000, 0xFFFFFF, DefBadWriteByte, NULL); // <Bad Writes>
AddWriteByte(-1, -1, NULL, NULL);
// AddWriteWord(0x340000, 0x34000F, NULL, RAM+0x032380); // watchdog
// AddWriteWord(0x380000, 0x38000F, NULL, RAM+0x032180); // ???
// AddWriteWord(0x600000, 0x60000F, NULL, RAM+0x032280); // ???
AddWriteWord(0xB00000, 0xB0001F, NULL, TC0360PRI_regs); // priorities
AddWriteWord(0x000000, 0xFFFFFF, DefBadWriteWord, NULL); // <Bad Writes>
AddWriteWord(-1, -1, NULL, NULL);
AddInitMemory(); // Set Starscream mem pointers...
}
static void load_dondokdj(void)
{
// 68000 Speed Hack
// ----------------
WriteWord68k(&ROM[0x005EC4],0x4E71);
// Fix ROM Checksum
// ----------------
WriteWord68k(&ROM[0x00D1A],0x4E75);
// Fix Long Sound Wait
// -------------------
WriteWord68k(&ROM[0x001A6],0x4E71);
load_common();
/*-----[Sound Setup]-----*/
AddTaitoYM2610(0x01E6, 0x0185, 0x10000);
RAM_VIDEO = RAM+0x10000;
RAM_SCROLL = RAM+0x32000;
RAM_ROTATE = RAM+0x34000;
RAM_OBJECT = RAM+0x20000;
GFX_FG0 = RAM+0x3C000;
set_colour_mapper(&col_map_rrrr_gggg_bbbb_xxxx);
InitPaletteMap(RAM+0x30000, 0x100, 0x10, 0x1000);
// Init tc0220ioc emulation
// ------------------------
tc0220ioc.RAM = input_buffer;
tc0220ioc.ctrl = TC0220_STOPCPU;
reset_tc0220ioc();
// Init tc0005rot emulation
// ------------------------
tc0005rot.RAM = RAM_ROTATE;
tc0005rot.RAM_SCR = RAM+0x36000;
setup_gfx();
tc0200obj.RAM_B = RAM_OBJECT+0x8000;
// tc0200obj.ofs_x = -3+7; // ???
init_tc0100scn(0);
/*
* StarScream Stuff follows
*/
AddRWBW( 0x100000, 0x10FFFF, NULL, RAM+0x000000); // 68000 RAM
AddWriteByte(0x806000, 0x806FFF, tc0100scn_0_gfx_fg0_wb, NULL); // FG0 GFX RAM
AddWriteWord(0x806000, 0x806FFF, tc0100scn_0_gfx_fg0_ww, NULL); // FG0 GFX RAM
AddRWBW(0x800000, 0x80FFFF, NULL, RAM_VIDEO); // SCREEN RAM
AddRWBW(0x900000, 0x90FFFF, NULL, RAM_OBJECT); // OBJECT RAM
AddReadBW(0x300000, 0x30001F, NULL, input_buffer); // INPUT
AddReadByte(0x320000, 0x320003, tc0140syt_read_main_68k, NULL); // SOUND COMM
AddReadByte(0x000000, 0xFFFFFF, DefBadReadByte, NULL); // <Bad Reads>
AddReadByte(-1, -1, NULL, NULL);
AddReadWord(0x200000, 0x201FFF, NULL, RAM+0x030000); // COLOR RAM
AddReadWord(0x000000, 0xFFFFFF, DefBadReadWord, NULL); // <Bad Reads>
AddReadWord(-1, -1,NULL, NULL);
AddWriteByte(0x300000, 0x30000F, tc0220ioc_wb, NULL); // INPUT
AddWriteByte(0x320000, 0x320003, tc0140syt_write_main_68k, NULL); // SOUND COMM
AddWriteByte(0xAA0000, 0xAA0001, Stop68000, NULL); // Trap Idle 68000
AddWriteBW(0xB00000, 0xB000FF, NULL, RAM+0x032300); // priority register
TC0360PRI_regs = RAM+0x032300;
AddWriteByte(0x000000, 0xFFFFFF, DefBadWriteByte, NULL); // <Bad Writes>
AddWriteByte(-1, -1, NULL, NULL);
AddWriteWord(0x200000, 0x201FFF, NULL, RAM+0x030000); // COLOR RAM
AddWriteWord(0xA00000, 0xA01FFF, tc0005rot_bg0_ww, NULL); // SCREEN RAM (ROTATE)
AddWriteWord(0x300000, 0x30000F, tc0220ioc_ww, NULL); // INPUT
AddWriteWord(0x820000, 0x82000F, NULL, RAM_SCROLL); // SCROLL RAM
AddWriteWord(0xA02000, 0xA0200F, NULL, RAM+0x036000); // SCROLL RAM (ROTATE)
AddWriteWord(0x000000, 0xFFFFFF, DefBadWriteWord, NULL); // <Bad Writes>
AddWriteWord(-1, -1, NULL, NULL);
AddInitMemory(); // Set Starscream mem pointers...
}
void load_finalb() {
int i;
unsigned char data;
unsigned int offset;
UINT8 *gfx = load_region[REGION_GFX2];
offset = 0x100000;
for (i = 0x180000; i<0x200000; i++)
{
int d1,d2,d3,d4;
/* convert from 2bits into 4bits format */
data = gfx[i];
d1 = (data>>0) & 3;
d2 = (data>>2) & 3;
d3 = (data>>4) & 3;
d4 = (data>>6) & 3;
gfx[offset] = (d3<<2) | (d4<<6);
offset++;
gfx[offset] = (d1<<2) | (d2<<6);
offset++;
}
// Fix Int#6
// ---------
//WriteLong68k(&ROM[0x00610],0x4E714E71); // nop
// Speed Hack
// ----------
WriteLong68k(&ROM[0x00744],0x13FC0000); // move.b #$00,$AA0000
WriteLong68k(&ROM[0x00748],0x00AA0000);
WriteWord68k(&ROM[0x0074C],0x6100-16);
//WriteLong68k(&ROM[0x00618],0x13FC0000); // move.b #$00,$AA0000
//WriteLong68k(&ROM[0x0061C],0x00AA0000);
// Fix Colour ram error
// --------------------
WriteWord68k(&ROM[0x022E6],0x4E71);
load_common();
AddTaitoYM2610(0x033A, 0x02A7, 0x10000);
RAM_VIDEO = RAM+0x20000;
RAM_SCROLL = RAM+0x30000;
RAM_OBJECT = RAM+0x10000;
RAM_INPUT = RAM+0x3c000;
GFX_FG0 = RAM+0x31000;
RAMSize = 0x3c010;
tc0110pcr_init(RAM+0x35000, 0);
set_colour_mapper(&col_map_xbbb_bbgg_gggr_rrrr);
InitPaletteMap(RAM+0x35000, 0x100, 0x10, 0x8000);
// Init tc0220ioc emulation
// ------------------------
tc0220ioc.RAM = RAM_INPUT;
tc0220ioc.ctrl = 0; //TC0220_STOPCPU;
reset_tc0220ioc();
setup_gfx();
init_tc0100scn(0);
f2_sprites_colors = 64;
AddRWBW(0x100000, 0x10FFFF, NULL, RAM+0x000000); // 68000 RAM
AddReadBW(0x300000, 0x30000F, NULL, RAM_INPUT); // INPUT
AddReadByte(0x320000, 0x320003, tc0140syt_read_main_68k, NULL); // SOUND COMM
AddWriteByte(0x806000, 0x806FFF, tc0100scn_0_gfx_fg0_wb, NULL); // FG0 GFX RAM
AddWriteWord(0x806000, 0x806FFF, tc0100scn_0_gfx_fg0_ww, NULL); // FG0 GFX RAM
AddRWBW(0x800000, 0x80FFFF, NULL, RAM_VIDEO); // SCREEN RAM
AddRWBW(0x900000, 0x90fFFF, NULL, RAM_OBJECT); // OBJECT RAM
AddReadByte(0x000000, 0xFFFFFF, DefBadReadByte, NULL); // <Bad Reads>
AddReadByte(-1, -1, NULL, NULL);
AddReadWord(0x200000, 0x200007, tc0110pcr_rw, NULL); // COLOR RAM
AddReadWord(0x000000, 0xFFFFFF, DefBadReadWord, NULL); // <Bad Reads>
AddReadWord(-1, -1,NULL, NULL);
AddWriteByte(0x320000, 0x320003, tc0140syt_write_main_68k, NULL); // SOUND COMM
AddWriteByte(0x300000, 0x30000F, tc0220ioc_wb, NULL); // INPUT
AddWriteByte(0xAA0000, 0xAA0001, Stop68000, NULL); // Trap Idle 68000
AddWriteByte(0x000000, 0xFFFFFF, DefBadWriteByte, NULL); // <Bad Writes>
AddWriteByte(-1, -1, NULL, NULL);
AddWriteWord(0x200000, 0x200007, tc0110pcr_ww, NULL); // COLOR RAM
AddWriteWord(0x820000, 0x82000F, NULL, RAM_SCROLL); // SCROLL RAM
// AddWriteWord(0x360000, 0x36000F, NULL, RAM+0x03C300); // ??? RAM
AddWriteWord(0x300000, 0x30000F, tc0220ioc_ww, NULL); // INPUT
AddWriteWord(0x000000, 0xFFFFFF, DefBadWriteWord, NULL); // <Bad Writes>
AddWriteWord(-1, -1, NULL, NULL);
AddInitMemory(); // Set Starscream mem pointers...
}
static UINT16 mjnquest_input;
static UINT16 dsw_mjnquest_r (UINT32 offset) {
switch (offset&0xf)
{
case 0x00:
return (input_buffer[0xa] << 0) + (input_buffer[0xe]<<8); /* DSW A + coin */
case 0x02:
return (input_buffer[0xc] << 0) + (input_buffer[0x10]<<8); /* DSW B + coin */
}
return 0xff;
}
static UINT16 mjnquest_input_r (UINT32 offset) {
switch (mjnquest_input)
{
case 0x01:
return input_buffer[0]; /* IN0 */
case 0x02:
return input_buffer[2]; /* IN1 */
case 0x04:
return input_buffer[4]; /* IN2 */
case 0x08:
return input_buffer[6]; /* IN3 */
case 0x10:
return input_buffer[8]; /* IN4 */
}
return 0xff;
}
static void input_mjnquestelect_w (UINT32 offset, UINT16 data) {
mjnquest_input = (data >> 6);
}
static void load_mjnquest() {
UINT8 *RAM_COLOUR;
int i,size = get_region_size(REGION_GFX2);
UINT8 *gfx = load_region[REGION_GFX2];
/* the bytes in each longword are in reversed order, put them in the
order used by the other games. */
for (i = 0;i < size;i += 2) {
int t;
t = gfx[i];
gfx[i] = (gfx[i+1] >> 4) | (gfx[i+1] << 4);
gfx[i+1] = (t >> 4) | (t << 4);
}
// 68000 Speed Hack
// ----------------
WriteLong68k(&ROM[0x004A4],0x13FC0000); // move.b #$00,$AA0000
WriteLong68k(&ROM[0x004A8],0x00AA0000);
load_common();
AddTaitoYM2610(0x0338, 0x02A5, 0x10000);
RAM_OBJECT = RAM+0x20000;
RAM_VIDEO = RAM+0x30000;
RAM_SCROLL = RAM+0x4A000;
RAM_COLOUR = RAM+0x40000;
RAM_INPUT = RAM+0x4A100;
GFX_BANK = RAM+0x4A200;
GFX_FG0 = RAM+0x50000;
RAMSize = 0x54000;
setup_gfx();
tc0110pcr_init(RAM_COLOUR, 0);
set_colour_mapper(&col_map_xbbb_bbgg_gggr_rrrr);
InitPaletteMap(RAM_COLOUR, 0x100, 0x10, 0x8000);
// Init tc0220ioc emulation
// ------------------------
tc0220ioc.RAM = RAM_INPUT;
tc0220ioc.ctrl = 0; //TC0220_STOPCPU;
reset_tc0220ioc();
tc0100scn[0].layer[0].scr_x =16+1;
tc0100scn[0].layer[1].scr_x =16+1;
tc0100scn[0].layer[2].scr_x =16+1;
init_tc0100scn(0);
tc0200obj.ofs_x = 0+6;
AddRWBW(0x110000, 0x12FFFF, NULL, RAM+0x000000); // 68000 RAM
AddReadWord(0x200000, 0x200007, tc0110pcr_rw, NULL); // COLOR RAM
AddReadBW(0x300000, 0x30000f, dsw_mjnquest_r, NULL);
AddReadBW(0x310000, 0x310001, mjnquest_input_r, NULL);
AddReadByte(0x360000, 0x360003, tc0140syt_read_main_68k, NULL); // SOUND COMM
AddWriteByte(0x406000, 0x406FFF, tc0100scn_0_gfx_fg0_wb, NULL); // FG0 GFX RAM
AddWriteWord(0x406000, 0x406FFF, tc0100scn_0_gfx_fg0_ww, NULL); // FG0 GFX RAM
AddRWBW(0x400000, 0x40FFFF, NULL, RAM_VIDEO); // SCREEN RAM
AddRWBW(0x420000, 0x42000F, NULL, RAM_SCROLL); // SCROLL RAM
AddRWBW(0x500000, 0x50FFFF, NULL, RAM_OBJECT); // OBJECT RAM
AddReadByte(0x000000, 0xFFFFFF, DefBadReadByte, NULL); // <Bad Reads>
AddReadByte(-1, -1, NULL, NULL);
AddReadWord(0x000000, 0xFFFFFF, DefBadReadWord, NULL); // <Bad Reads>
AddReadWord(-1, -1,NULL, NULL);
AddWriteWord(0x200000, 0x200007, tc0110pcr_ww, NULL); // COLOR RAM
AddWriteWord(0x320000, 0x320001, input_mjnquestelect_w, NULL);
AddWriteByte(0x360000, 0x360003, tc0140syt_write_main_68k, NULL); // SOUND COMM
AddWriteWord(0x380000, 0x380001, NULL, GFX_BANK); // BANK SWITCH
AddWriteByte(0xAA0000, 0xAA0001, Stop68000, NULL); // Trap Idle 68000
AddWriteByte(0x000000, 0xFFFFFF, DefBadWriteByte, NULL); // <Bad Writes>
AddWriteByte(-1, -1, NULL, NULL);
AddWriteWord(0x000000, 0xFFFFFF, DefBadWriteWord, NULL); // <Bad Writes>
AddWriteWord(-1, -1, NULL, NULL);
AddInitMemory(); // Set Starscream mem pointers...
}
static void load_dinorex() {
WriteWord68k(&ROM[0x01084],0x4EF9); // JMP $7FF00
WriteLong68k(&ROM[0x01086],0x0007FF00);
WriteWord68k(&ROM[0x7FF00],0x4EB9);
WriteLong68k(&ROM[0x7FF02],0x000032FC);
WriteLong68k(&ROM[0x7FF06],0x13FC0000); // Stop 68000
WriteLong68k(&ROM[0x7FF0A],0x00AA0000);
WriteWord68k(&ROM[0x7FF0E],0x6100-16); // Loop
load_common();
/*-----[Sound Setup]-----*/
AddTaitoYM2610(0x0211, 0x017A, 0x10000);
RAM_OBJECT = RAM+0x10000;
f2_sprite_extension = (UINT16*)(RAM+0x20000);
RAM_SCROLL = RAM+0x33100;
TC0360PRI_regs = RAM+0x34000;
RAM_VIDEO = RAM+0x40000;
GFX_FG0 = RAM+0x50000;
memset(GFX_FG0,0,0x4000);
RAMSize = 0x54000;
// don't know if this color mapper is correct or not... anyway...
set_colour_mapper(&col_map_rrrr_gggg_bbbb_xxxx);
InitPaletteMap(RAM+0x30000, 0x100, 0x10, 0x8000);
setup_gfx();
// Init tc0220ioc emulation
// ------------------------
tc0220ioc.RAM = input_buffer;
tc0220ioc.ctrl = 0; //TC0220_STOPCPU;
reset_tc0220ioc();
tc0200obj.ofs_x = 9;
tc0200obj.ofs_y = 3; // sprite type now
tc0100scn[0].layer[0].scr_x =19;
tc0100scn[0].layer[1].scr_x =19;
tc0100scn[0].layer[2].scr_x =19;
init_tc0100scn(0);
AddRWBW(0x600000, 0x60FFFF, NULL, RAM+0x000000); // 68000 RAM
AddRWBW(0x800000, 0x80FFFF, NULL, RAM_OBJECT);
AddRWBW(0x400000, 0x400FFF, NULL, (UINT8*)f2_sprite_extension);
// Notice : you can't position GFX_FG0 = RAM_VIDEO + 0x6000
// because these 2 functions create a 0x4000 bytes long buffer from the
// 0x1000 bytes of data (4x the size)
AddWriteByte(0x906000, 0x906FFF, tc0100scn_0_gfx_fg0_wb, NULL); // FG0 GFX RAM
AddWriteWord(0x906000, 0x906FFF, tc0100scn_0_gfx_fg0_ww, NULL); // FG0 GFX RAM
AddRWBW(0x900000, 0x90fFFF, NULL, RAM_VIDEO); // SCREEN RAM
AddRWBW(0x500000, 0x501FFF, NULL, RAM+0x030000); // COLOR RAM
AddReadBW(0x300000, 0x30001F, NULL, input_buffer); // INPUT
AddReadByte(0xA00000, 0xA00003, tc0140syt_read_main_68k, NULL); // SOUND COMM
AddRWBW(0x700000, 0x7000FF, NULL, TC0360PRI_regs);
AddReadByte(0x000000, 0xFFFFFF, DefBadReadByte, NULL); // <Bad Reads>
AddReadByte(-1, -1, NULL, NULL);
AddReadWord(0x000000, 0xFFFFFF, DefBadReadWord, NULL); // <Bad Reads>
AddReadWord(-1, -1,NULL, NULL);
AddWriteByte(0xA00000, 0xA00003, tc0140syt_write_main_68k, NULL); // SOUND COMM
AddWriteByte(0x300000, 0x30001F, tc0220ioc_wb, NULL); // INPUT
AddWriteByte(0xAA0000, 0xAA0001, Stop68000, NULL); // Trap Idle 68000
AddWriteByte(0x000000, 0xFFFFFF, DefBadWriteByte, NULL); // <Bad Writes>
AddWriteByte(-1, -1, NULL, NULL);
AddWriteWord(0x920000, 0x92000F, NULL, RAM_SCROLL); // SCROLL RAM
AddWriteWord(0x300000, 0x30001F, tc0220ioc_ww, NULL); // INPUT
AddWriteWord(0x000000, 0xFFFFFF, DefBadWriteWord, NULL); // <Bad Writes>
AddWriteWord(-1, -1, NULL, NULL);
AddInitMemory(); // Set Starscream mem pointers...
}
static void solitary_fighter_ioc_0_wb(UINT32 offset, UINT8 data)
{
switch(offset & 6){
case 0:
tc0220ioc_wb(0, data);
break;
case 2:
tc0220ioc_wb(2, data);
break;
case 4:
tc0220ioc_wb(8, data);
break;
default:
break;
}
}
static void solitary_fighter_ioc_0_ww(UINT32 offset, UINT16 data)
{
solitary_fighter_ioc_0_wb(offset, (UINT8) (data & 0xFF));
}
static UINT8 solitary_fighter_ioc_0_rb(UINT32 offset)
{
switch(offset & 6){
case 0:
return tc0220ioc_rb(0);
break;
case 2:
return tc0220ioc_rb(2);
break;
case 4:
return tc0220ioc_rb(8);
break;
default:
return 0xFF;
break;
}
}
static UINT16 solitary_fighter_ioc_0_rw(UINT32 offset)
{
return solitary_fighter_ioc_0_rb(offset);
}
static void solitary_fighter_ioc_1_wb(UINT32 offset, UINT8 data)
{
switch(offset & 6){
case 0:
tc0220ioc_wb(4, data);
break;
case 2:
tc0220ioc_wb(6, data);
break;
case 4:
tc0220ioc_wb(14, data);
break;
default:
break;
}
}
static void solitary_fighter_ioc_1_ww(UINT32 offset, UINT16 data)
{
solitary_fighter_ioc_1_wb(offset, (UINT8) (data & 0xFF));
}
static UINT8 solitary_fighter_ioc_1_rb(UINT32 offset)
{
switch(offset & 6){
case 0:
return tc0220ioc_rb(4);
break;
case 2:
return tc0220ioc_rb(6);
break;
case 4:
return tc0220ioc_rb(14);
break;
default:
return 0xFF;
break;
}
}
static UINT16 solitary_fighter_ioc_1_rw(UINT32 offset)
{
return solitary_fighter_ioc_1_rb(offset);
}
static void load_solfigtr() {
UINT8 *RAM_COLOUR;
// SBCD flag bug - game relies on undefined flags (not supported in starscream)
// Effect : big slow down when one of the player is loosing
WriteWord68k(&ROM[0x09B9A],0x4E71);
// 68000 Speed Hack
WriteLong68k(&ROM[0x0058E],0x4EF800C0);
WriteLong68k(&ROM[0x000C0],0x46FC2000);
WriteLong68k(&ROM[0x000C4],0x13FC0000); // move.b #$00,$AA0000
WriteLong68k(&ROM[0x000C8],0x00AA0000);
WriteWord68k(&ROM[0x000CC],0x6100-10);
load_common();
AddTaitoYM2610(0x01A9, 0x0155, 0x10000);
RAM_OBJECT = RAM+0x10000;
RAM_COLOUR = RAM+0x20000;
RAM_SCROLL = RAM+0x22000;
GFX_BANK = RAM+0x22200;
GFX_FG0 = RAM+0x23000;
RAM_VIDEO = RAM+0x30000;
setup_gfx();
RAMSize=0x40000;
set_colour_mapper(&col_map_rrrr_gggg_bbbb_xxxx);
InitPaletteMap(RAM_COLOUR, 0x100, 0x10, 0x1000);
tc0220ioc.RAM = input_buffer;
tc0220ioc.ctrl = 0; //TC0220_STOPCPU;
reset_tc0220ioc();
init_tc0100scn(0);
AddRWBW(0x100000, 0x103FFF, NULL, RAM+0x000000); // 68000 RAM
AddRWBW(0x900000, 0x90FFFF, NULL, RAM_OBJECT); // OBJECT RAM
AddWriteWord(0x806000, 0x806FFF, tc0100scn_0_gfx_fg0_ww, NULL); // FG0 GFX RAM
AddWriteByte(0x806000, 0x806FFF, tc0100scn_0_gfx_fg0_wb, NULL); // FG0 GFX RAM
AddRWBW(0x800000, 0x80FFFF, NULL, RAM_VIDEO); // SCREEN RAM
AddRWBW(0x200000, 0x201FFF, NULL, RAM_COLOUR); // COLOR RAM
AddReadByte(0x300000, 0x300007, solitary_fighter_ioc_0_rb, NULL); // INPUT
AddReadByte(0x320000, 0x320007, solitary_fighter_ioc_1_rb, NULL); // INPUT
AddReadByte(0x400000, 0x400003, tc0140syt_read_main_68k, NULL); // SOUND COMM
AddReadByte(0x000000, 0xFFFFFF, DefBadReadByte, NULL); // <Bad Reads>
AddReadByte(-1, -1, NULL, NULL);
AddReadWord(0x300000, 0x300007, solitary_fighter_ioc_0_rw, NULL); // INPUT
AddReadWord(0x320000, 0x320007, solitary_fighter_ioc_1_rw, NULL); // INPUT
AddReadWord(0x000000, 0xFFFFFF, DefBadReadWord, NULL); // <Bad Reads>
AddReadWord(-1, -1,NULL, NULL);
AddWriteBW(0x820000, 0x82000F, NULL, RAM_SCROLL); // SCROLL RAM
AddWriteByte(0x400000, 0x400003, tc0140syt_write_main_68k, NULL); // SOUND COMM
AddWriteByte(0x300000, 0x300007, solitary_fighter_ioc_0_wb, NULL); // INPUT
AddWriteByte(0x320000, 0x320007, solitary_fighter_ioc_1_wb, NULL); // INPUT
AddWriteByte(0xAA0000, 0xAA0001, Stop68000, NULL); // Trap Idle 68000
AddWriteByte(0x000000, 0xFFFFFF, DefBadWriteByte, NULL); // <Bad Writes>
AddWriteByte(-1, -1, NULL, NULL);
AddWriteWord(0x500000, 0x50001F, NULL, GFX_BANK); // BANK
AddWriteWord(0xB00000, 0xB0001F, NULL, GFX_BANK+0x20); // priorities
TC0360PRI_regs = GFX_BANK + 0x20;
AddWriteWord(0x300000, 0x300007, solitary_fighter_ioc_0_ww, NULL); // INPUT
AddWriteWord(0x320000, 0x320007, solitary_fighter_ioc_1_ww, NULL); // INPUT
AddWriteWord(0x000000, 0xFFFFFF, DefBadWriteWord, NULL); // <Bad Writes>
AddWriteWord(-1, -1, NULL, NULL);
AddInitMemory(); // Set Starscream mem pointers...
}
static int init_gfx3;
static void load_thundfox(void)
{
// 68000 Speed Hack
// ----------------
WriteLong68k(&ROM[0x0A0C],0x13FC0000); // move.b #$00,$AA0000
WriteLong68k(&ROM[0x0A10],0x00AA0000);
WriteWord68k(&ROM[0x0A14],0x6100-16); // bra.s <loop>
WriteLong68k(&ROM[0x07B0],0x13FC0000); // move.b #$00,$AA0000
WriteLong68k(&ROM[0x07B4],0x00AA0000);
load_common();
/*-----[Sound Setup]-----*/
AddTaitoYM2610(0x023A, 0x01BA, 0x10000);
RAM_VIDEO = RAM+0x04000;
RAM_SCROLL = RAM+0x2E000;
RAM_VIDEO2 = RAM+0x14000;
RAM_SCROLL2= RAM+0x2E100;
TC0360PRI_regs = RAM+0x2e200;
RAM_OBJECT = RAM+0x24000;
GFX_FG0 = RAM+0x30000;
GFX_FG1 = RAM+0x34000;
RAMSize=0x38000;
set_colour_mapper(&col_map_rrrr_gggg_bbbb_xxxx);
InitPaletteMap(RAM+0x2C000, 0x100, 0x10, 0x1000);
setup_gfx();
// Init tc0220ioc emulation
// ------------------------
tc0220ioc.RAM = input_buffer;
tc0220ioc.ctrl = 0; //TC0220_STOPCPU;
reset_tc0220ioc();
set_colour_mapper(&col_map_rrrr_gggg_bbbb_xxxx);
InitPaletteMap(RAM+0x2C000, 0x100, 0x10, 0x1000);
init_tc0100scn(0);
memcpy(&tc0100scn[1],&tc0100scn[0],sizeof(struct TC0100SCN));
init_gfx3 = 0;
tc0100scn[1].layer[0].RAM =RAM_VIDEO2 +0x0000;
tc0100scn[1].layer[0].SCR =RAM_SCROLL2 +0;
tc0100scn[1].layer[0].scr_x =15; // to be checked
tc0100scn[1].layer[0].scr_y =15;
tc0100scn[1].layer[1].RAM =RAM_VIDEO2 +0x8000;
tc0100scn[1].layer[1].SCR =RAM_SCROLL2 +2;
tc0100scn[1].layer[1].scr_x =15;
tc0100scn[1].layer[1].scr_y =15;
tc0100scn[1].layer[2].RAM =RAM_VIDEO2 +0x4000;
tc0100scn[1].layer[2].GFX =GFX_FG1;
tc0100scn[1].layer[2].SCR =RAM_SCROLL2 +4;
tc0100scn[1].RAM = RAM_VIDEO2;
tc0100scn[1].GFX_FG0 = GFX_FG1;
init_tc0100scn(1);
AddRWBW(0x300000, 0x303FFF, NULL, RAM+0x000000); // 68000 RAM
AddWriteByte(0x406000, 0x406FFF, tc0100scn_0_gfx_fg0_wb, NULL); // FG0 GFX RAM
AddWriteWord(0x406000, 0x406FFF, tc0100scn_0_gfx_fg0_ww, NULL); // FG0 GFX RAM
AddRWBW(0x400000, 0x40FFFF, NULL, RAM_VIDEO); // SCREEN0 RAM
AddWriteByte(0x506000, 0x506FFF, tc0100scn_1_gfx_fg0_wb, NULL); // FG1 GFX RAM
AddWriteWord(0x506000, 0x506FFF, tc0100scn_1_gfx_fg0_ww, NULL); // FG1 GFX RAM
AddRWBW(0x500000, 0x50FFFF, NULL, RAM_VIDEO2); // SCREEN1 RAM
AddRWBW(0x600000, 0x607FFF, NULL, RAM_OBJECT); // OBJECT RAM
AddReadBW(0x200000, 0x20000F, NULL, input_buffer); // INPUT
AddReadByte(0x220000, 0x220003, tc0140syt_read_main_68k, NULL); // SOUND COMM
AddRWBW(0x800000,0x80001f,NULL,TC0360PRI_regs);
AddReadWord(0x100000, 0x101FFF, NULL, RAM+0x02C000); // COLOR RAM
AddWriteByte(0x220000, 0x220003, tc0140syt_write_main_68k, NULL); // SOUND COMM
AddWriteByte(0x200000, 0x20000F, tc0220ioc_wb, NULL); // INPUT RAM
AddWriteByte(0xAA0000, 0xAA0001, Stop68000, NULL); // Trap Idle 68000
AddWriteWord(0x100000, 0x101FFF, NULL, RAM+0x02C000); // COLOR RAM
AddWriteWord(0x420000, 0x42000F, NULL, RAM_SCROLL); // SCROLL0 RAM
AddWriteWord(0x520000, 0x52000F, NULL, RAM_SCROLL2); // SCROLL1 RAM
AddWriteWord(0x200000, 0x20000F, tc0220ioc_ww, NULL); // INPUT RAM
finish_conf_68000(0);
}
static struct DSW_DATA dsw_data_pulirula_0[] =
{
{ MSG_DSWA_BIT1, 0x01, 0x02 },
{ MSG_OFF, 0x01},
{ MSG_ON, 0x00},
DSW_SCREEN( 0x02, 0x00),
DSW_TEST_MODE( 0x00, 0x04),
DSW_DEMO_SOUND( 0x08, 0x00),
{ MSG_COIN1, 0x30, 0x04 },
{ MSG_1COIN_1PLAY, 0x30},
{ MSG_2COIN_1PLAY, 0x20},
{ MSG_3COIN_1PLAY, 0x10},
{ MSG_4COIN_1PLAY, 0x00},
{ MSG_COIN2, 0xC0, 0x04 },
{ MSG_1COIN_2PLAY, 0xC0},
{ MSG_1COIN_3PLAY, 0x80},
{ MSG_2COIN_1PLAY, 0x40},
{ MSG_2COIN_3PLAY, 0x00},
{ NULL, 0, },
};
static struct DSW_DATA dsw_data_pulirula_1[] =
{
{ MSG_DIFFICULTY, 0x03, 0x04 },
{ MSG_NORMAL, 0x03},
{ MSG_EASY, 0x02},
{ MSG_HARD, 0x01},
{ MSG_HARDEST, 0x00},
{ _("Magic"), 0x0C, 0x03 },
{ "3", 0x0C},
{ "4", 0x08},
{ "5", 0x04},
{ MSG_LIVES, 0x30, 0x04 },
{ "3", 0x30},
{ "2", 0x20},
{ "4", 0x10},
{ "5", 0x00},
{ MSG_DSWB_BIT7, 0x40, 0x02 },
{ MSG_OFF, 0x40},
{ MSG_ON, 0x00},
{ _("Upright Controls"), 0x80, 0x02 },
{ _("Dual"), 0x80},
{ _("Single"), 0x00},
{ NULL, 0, },
};
static struct DSW_INFO dsw_pulirula[] =
{
{ 0x0, 0xFF, dsw_data_pulirula_0 },
{ 0x2, 0xFF, dsw_data_pulirula_1 },
{ 0, 0, NULL, },
};
static void pri_swap_bytes(UINT32 offset, UINT16 data) {
offset &= 0x1f;
if (TC0360PRI_regs[offset] != data) {
TC0360PRI_regs[(offset)] = data;
}
}
static void pri_swap_word(UINT32 offset, UINT16 data) {
offset &= 0x1f;
if (ReadWord68k(&TC0360PRI_regs[offset]) != data) {
WriteWord68k(&TC0360PRI_regs[(offset )], data);
}
}
static void load_pulirula(void)
{
UINT8 *RAM_COLOUR;
// 68000 Speed Hack
// ----------------
WriteWord68k(&ROM[0x084C],0x4EF9); // jmp $300
WriteLong68k(&ROM[0x084E],0x00000300);
WriteLong68k(&ROM[0x00300],0x526DABF2); // jsr <random gen>
WriteLong68k(&ROM[0x00304],0x13FC0000); // move.b #$00,$AA0000
WriteLong68k(&ROM[0x00308],0x00AA0000);
WriteWord68k(&ROM[0x0030C],0x6100-14); // bra.s <loop>
load_common();
/*-----[Sound Setup]-----*/
AddTaitoYM2610(0x01A4, 0x0150, 0x20000);
RAM_OBJECT = RAM+0x10000;
RAM_VIDEO = RAM+0x20000;
RAM_COLOUR = RAM+0x30000;
RAM_SCROLL = RAM+0x32000;
TC0360PRI_regs = RAM_SCROLL+0x10;
RAM_ROTATE = RAM+0x34000;
f2_sprite_extension = (UINT16*)(RAM+0x37000);
GFX_FG0 = RAM+0x40000;
RAMSize = 0x40000;
// set_colour_mapper(&col_map_rrrr_gggg_bbbb_xxxx);
set_colour_mapper(&col_map_xrrr_rrgg_gggb_bbbb);
InitPaletteMap(RAM_COLOUR, 0x100, 0x10, 0x8000);
tc0005rot.RAM = RAM_ROTATE;
tc0005rot.RAM_SCR = RAM_ROTATE+0x2000;
setup_gfx();
// Init tc0220ioc emulation
// ------------------------
tc0220ioc.RAM = input_buffer;
tc0220ioc.ctrl = 0; //TC0220_STOPCPU;
reset_tc0220ioc();
init_gfx3 = 0;
tc0100scn[0].layer[0].scr_x =16+1;
tc0100scn[0].layer[1].scr_x =16+1;
tc0100scn[0].layer[2].scr_x =16+1;
f2_sprites_colors = 64;
init_tc0100scn(0);
tc0200obj.RAM_B = RAM_OBJECT+0x8000;
tc0200obj.ofs_x = 6;
tc0200obj.ofs_y = 2; // sprite type : pulirula
AddRWBW(0x300000, 0x30FFFF, NULL, RAM+0x000000); // 68000 RAM
AddWriteByte(0x806000, 0x806FFF, tc0100scn_0_gfx_fg0_wb, NULL); // FG0 GFX RAM
AddWriteWord(0x806000, 0x806FFF, tc0100scn_0_gfx_fg0_ww, NULL); // FG0 GFX RAM
AddRWBW(0x800000, 0x80FFFF, NULL, RAM_VIDEO); // SCREEN0 RAM
AddRWBW(0x900000, 0x90FFFF, NULL, RAM_OBJECT); // OBJECT RAM
AddWriteWord(0x600000, 0x603FFF, NULL, (UINT8*)f2_sprite_extension); // OBJECT EXTRA RAM
AddWriteWord(0x400000, 0x401fff, tc0005rot_bg0_ww, NULL); // SCREEN RAM (ROTATE)
AddRWBW(0x400000, 0x40200F, NULL, RAM_ROTATE); // SCREEN RAM (ROTATION) + scroll registers
AddReadBW(0xB00000, 0xB0000F, NULL, input_buffer); // INPUT
AddRWBW(0x700000, 0x701FFF, NULL, RAM_COLOUR);
AddReadByte(0x200000, 0x200003, tc0140syt_read_main_68k, NULL); // SOUND COMM
AddWriteByte(0xa00000,0xa0001f,pri_swap_bytes, NULL);
// AddWriteByte(0xa00000,0xa0001f,NULL, TC0360PRI_regs);
AddWriteWord(0xa00000,0xa0001f,pri_swap_word, NULL);
// AddWriteWord(0xa00000,0xa0001f,NULL, TC0360PRI_regs);
AddWriteByte(0x200000, 0x200003, tc0140syt_write_main_68k, NULL); // SOUND COMM
AddWriteByte(0xB00000, 0xB0000F, tc0220ioc_wb, NULL); // INPUT
AddWriteByte(0xAA0000, 0xAA0001, Stop68000, NULL); // Trap Idle 68000
AddWriteWord(0x820000, 0x82000F, NULL, RAM_SCROLL); // SCROLL0 RAM
AddWriteWord(0xB00000, 0xB0000F, tc0220ioc_ww, NULL); // INPUT
finish_conf_68000(0);
}
/* specific sound roms for driveout... */
static struct OKIM6295interface okim6295_interface =
{
1,
{ 8000 }, /* Hz ?? */
{ REGION_SOUND1 }, /* memory region */
{ 255 } /* volume ?? */
};
static SOUND_INFO sound_driveout[] =
{
{ SOUND_M6295, &okim6295_interface, },
{ 0, NULL, },
};
static int driveout_sound_latch = 0;
static UINT8 sound_driveout_command_r(UINT32 offset)
{
//cpu_set_irq_line(1,0,CLEAR_LINE);
/* logerror("sound IRQ OFF (sound command=%02x)\n",driveout_sound_latch); */
return driveout_sound_latch;
}
static int oki_bank = 0;
static void reset_sound_driveout_region(void)
{
OKIM6295_set_bank_base(0, ALL_VOICES, oki_bank*0x40000);
}
static void oki_bank_w(UINT32 offset, UINT8 data)
{
if ((data&4) && (oki_bank!=(data&3)) )
{
oki_bank = (data&3);
}
reset_sound_driveout_region();
}
static void sound_driveout_command_wb(UINT32 offset, UINT16 data)
{
static int nibble = 0;
offset &=3;
if (offset==0)
{
nibble = data & 1;
}
else
{
if (nibble==0)
{
driveout_sound_latch = (data & 0x0f) | (driveout_sound_latch & 0xf0);
}
else
{
driveout_sound_latch = ((data<<4) & 0xf0) | (driveout_sound_latch & 0x0f);
cpu_interrupt(CPU_Z80_0, 0x38);
}
}
}
static void load_common_driftout() {
load_common();
/*-----[Sound Setup]-----*/
RAM_OBJECT = RAM+0x33000;
RAM_VIDEO = RAM+0x16000-0x4000;
RAM_SCROLL = RAM+0x20020;
RAM_ROTATE = RAM+0x10000;
GFX_FG0 = RAM+0x21000;
RAM_INPUT = input_buffer;
set_colour_mapper(&col_map_xrrr_rrgg_gggb_bbbb);
InitPaletteMap(RAM+0x14000, 0x100, 0x10, 0x8000);
// Init tc0005rot emulation
// ------------------------
tc0005rot.RAM = RAM_ROTATE;
tc0005rot.RAM_SCR = RAM_ROTATE+0x2000;
setup_gfx();
// tc0200obj.ofs_x = 8;
tc0220ioc.RAM = input_buffer;
tc0220ioc.ctrl = 0; //TC0220_STOPCPU;
reset_tc0220ioc();
tc0200obj.ofs_x = -3+6; // ???
tc0100scn[0].layer[0].scr_x =19;
tc0100scn[0].layer[1].scr_x =19; // -80 for f2demo !
tc0100scn[0].layer[2].scr_x =19;
init_tc0100scn(0);
/*
* StarScream Stuff follows
*/
AddRWBW(0x300000, 0x30FFFF, NULL, RAM+0x000000); // 68000 RAM
AddReadByte(0xB00000, 0xB0001F, NULL, input_buffer); // INPUT RAM
AddRWBW(0x900000, 0x90fFFF, NULL, RAM_OBJECT); // OBJECT RAM
AddRWBW(0x700000, 0x701FFF, NULL, RAM+0x014000); // COLOR RAM
AddReadWord(0x400000, 0x40200F, NULL, RAM_ROTATE); // SCREEN/SCROLL (ROT)
AddReadWord(0xB00000, 0xB0001F, NULL, RAM_INPUT); // INPUT RAM
AddWriteByte(0xB00000, 0xB0001F, tc0220ioc_wb, NULL); // INPUT RAM
AddWriteByte(0xAA0000, 0xAA0001, Stop68000, NULL); // Trap Idle 68000
AddWriteWord(0x400000, 0x401FFF, tc0005rot_bg0_ww, NULL); // SCREEN RAM (ROTATE)
AddWriteWord(0x402000, 0x40200F, NULL, RAM+0x012000); // SCROLL RAM (ROTATE)
AddWriteWord(0x804000, 0x805FFF, NULL, RAM+0x016000); // SCREEN RAM
AddWriteWord(0x806000, 0x806FFF, tc0100scn_0_gfx_fg0_ww, NULL); // FG0 GFX RAM
AddWriteWord(0x820000, 0x82000F, NULL, RAM+0x020020); // SCROLL RAM
AddWriteBW(0xA00000, 0xA0001F, NULL, RAM+0x020030); // Priorities
TC0360PRI_regs = RAM+0x020030;
AddWriteWord(0xB00000, 0xB0001F, tc0220ioc_ww, NULL); // INPUT RAM
}
static void load_driftout() {
// 68000 Speed Hack
// ----------------
WriteWord68k(&ROM[0x0724],0x13FC); // move.b #$00,$AA0000
WriteWord68k(&ROM[0x0726],0x0000); // move.b #$00,$AA0000
WriteWord68k(&ROM[0x0728],0x00AA); //
WriteWord68k(&ROM[0x072a],0x0000); // move.b #$00,$AA0000
WriteWord68k(&ROM[0x072C],0x6100-14); // bra.s <loop>
load_common_driftout();
AddTaitoYM2610(0x023A, 0x01BA, 0x10000);
AddReadByte(0x200000, 0x200003, tc0140syt_read_main_68k, NULL); // SOUND COMM
AddWriteByte(0x200000, 0x200003, tc0140syt_write_main_68k, NULL); // SOUND COMM
AddReadByte(0x000000, 0xFFFFFF, DefBadReadByte, NULL); // <Bad Reads>
AddReadByte(-1, -1, NULL, NULL);
AddReadWord(0x000000, 0xFFFFFF, DefBadReadWord, NULL); // <Bad Reads>
AddReadWord(-1, -1,NULL, NULL);
AddWriteByte(0x000000, 0xFFFFFF, DefBadWriteByte, NULL); // <Bad Writes>
AddWriteByte(-1, -1, NULL, NULL);
AddWriteWord(0x000000, 0xFFFFFF, DefBadWriteWord, NULL); // <Bad Writes>
AddWriteWord(-1, -1, NULL, NULL);
AddInitMemory(); // Set Starscream mem pointers...
}
static void load_driveout() {
UINT8 *z80_ram;
WriteWord68k(&ROM[0x0700],0x13FC); // move.b #$00,$AA0000
WriteWord68k(&ROM[0x0702],0x0000); // move.b #$00,$AA0000
WriteWord68k(&ROM[0x0704],0x00AA); //
WriteWord68k(&ROM[0x0706],0x0000); // move.b #$00,$AA0000
WriteWord68k(&ROM[0x0708],0x6100-14); // bra.s <loop>
load_common_driftout();
z80_ram = RAM + 0x32120;
AddZ80AROMBase(Z80ROM, 0x0038, 0x0066);
AddZ80AReadByte(0x0000, 0x7FFF, NULL, Z80ROM); // BANK ROM
AddZ80AReadByte(0x8000, 0x87FF, NULL, z80_ram); // Z80 RAM
AddZ80AReadByte(0x9800, 0x9801, OKIM6295_status_0_r, NULL);
AddZ80AReadByte(0xa000, 0xa000, sound_driveout_command_r, NULL);
AddZ80AReadByte(0x0000, 0xFFFF, DefBadReadZ80, NULL);
AddZ80AReadByte( -1, -1, NULL, NULL);
AddZ80AWriteByte(0x8000, 0x87ff, NULL, z80_ram); // Z80 RAM
AddZ80AWrite(0x9000,0x9000,oki_bank_w, NULL);
AddZ80AWrite(0x9800,0x9800,OKIM6295_data_0_w,NULL);
AddZ80AWriteByte(0x0000, 0xFFFF, DefBadWriteZ80, NULL);
AddZ80AWriteByte( -1, -1, NULL, NULL);
AddZ80AReadPort(0x00, 0xFF, DefBadReadZ80, NULL);
AddZ80AReadPort( -1, -1, NULL, NULL);
// AddZ80AWritePort(0xAA, 0xAA, StopZ80Mode2, NULL);
AddZ80AWritePort(0x00, 0xFF, DefBadWriteZ80, NULL);
AddZ80AWritePort( -1, -1, NULL, NULL);
AddZ80AInit();
// AddReadByte(0x200000, 0x200003, tc0140syt_read_main_68k, NULL); // SOUND COMM
AddWriteByte(0x200000, 0x200003, sound_driveout_command_wb, NULL); // SOUND COMM
AddReadByte(0x000000, 0xFFFFFF, DefBadReadByte, NULL); // <Bad Reads>
AddReadByte(-1, -1, NULL, NULL);
// AddReadWord(0x000000, 0xFFFFFF, DefBadReadWord, NULL); // <Bad Reads>
AddReadWord(-1, -1,NULL, NULL);
AddWriteByte(0x000000, 0xFFFFFF, DefBadWriteByte, NULL); // <Bad Writes>
AddWriteByte(-1, -1, NULL, NULL);
// AddWriteWord(0x000000, 0xFFFFFF, DefBadWriteWord, NULL); // <Bad Writes>
AddWriteWord(-1, -1, NULL, NULL);
AddInitMemory(); // Set Starscream mem pointers...
}
static void load_ssi() {
WriteWord68k(&ROM[0x01FB4],0x4EF9);
WriteLong68k(&ROM[0x01FB6],0x000000C0);
WriteWord68k(&ROM[0x000C0],0x4EB9); // jsr <???>
if(is_current_game("ssi"))
WriteLong68k(&ROM[0x000C2],0x0000932A);
else
WriteLong68k(&ROM[0x000C2],0x0000929A);
WriteWord68k(&ROM[0x000C6],0x4EB9); // jsr <random gen>
WriteLong68k(&ROM[0x000C8],0x00001BE6);
WriteLong68k(&ROM[0x000CC],0x13FC0000); // move.b #$00,$AA0000
WriteLong68k(&ROM[0x000D0],0x00AA0000);
WriteWord68k(&ROM[0x000D4],0x6100-0x16); // bra.s <loop>
if(is_current_game("ssi"))
{
WriteLong68k(&ROM[0x09CFC],0x00000100);
WriteWord68k(&ROM[0x00100],0x4EB9);
WriteLong68k(&ROM[0x00102],0x0000B3E6);
WriteLong68k(&ROM[0x00106],0x13FC0000); // move.b #$00,$AA0000
WriteLong68k(&ROM[0x0010A],0x00AA0000);
WriteWord68k(&ROM[0x0010E],0x4E75);
}
else
{
WriteLong68k(&ROM[0x09C6C],0x00000100);
WriteWord68k(&ROM[0x00100],0x4EB9);
WriteLong68k(&ROM[0x00102],0x0000B41C);
WriteLong68k(&ROM[0x00106],0x13FC0000); // move.b #$00,$AA0000
WriteLong68k(&ROM[0x0010A],0x00AA0000);
WriteWord68k(&ROM[0x0010E],0x4E75);
}
load_common();
/*-----[Sound Setup]-----*/
AddTaitoYM2610(0x0217, 0x018F, 0x10000);
RAM_OBJECT = RAM+0x10000;
GFX_FG0 = RAM+0x3C000;
set_colour_mapper(&col_map_rrrr_gggg_bbbb_xxxx);
InitPaletteMap(RAM+0x20000, 0x100, 0x10, 0x1000);
setup_gfx();
tc0220ioc.RAM = input_buffer;
tc0220ioc.ctrl = 0; //TC0220_STOPCPU;
reset_tc0220ioc();
tc0200obj.ofs_x = 10;
/*
* StarScream Stuff follows
*/
AddRWBW (0x200000, 0x20FFFF, NULL, RAM+0x000000); // 68000 RAM
AddReadBW(0x100000, 0x10000F, NULL, input_buffer); // INPUT
AddReadByte(0x400000, 0x400003, tc0140syt_read_main_68k, NULL); // SOUND COMM
AddRWBW (0x800000, 0x80FFFF, NULL, RAM_OBJECT); // SPRITE
AddReadWord(0x300000, 0x301FFF, NULL, RAM+0x020000); // COLOR RAM
AddWriteByte(0x400000, 0x400003, tc0140syt_write_main_68k, NULL); // SOUND COMM
AddWriteByte(0x500000, 0x5000FF, NULL, RAM+0x022200); // ???
AddWriteByte(0x100000, 0x10000F, tc0220ioc_wb, NULL); // INPUT
AddWriteByte(0xAA0000, 0xAA0001, Stop68000, NULL); // Trap Idle 68000
AddWriteWord(0x300000, 0x301FFF, NULL, RAM+0x020000); // COLOR RAM
AddWriteWord(0x500000, 0x5000FF, NULL, RAM+0x022200); // ???
AddWriteWord(0x100000, 0x10000F, tc0220ioc_ww, NULL); // INPUT
finish_conf_68000(0);
}
static void load_megab(void)
{
ROM[0x00628]=0x4E;
ROM[0x00629]=0x71;
ROM[0x0062A]=0x4E;
ROM[0x0062B]=0x71;
ROM[0x0770]=0x13; // move.b #$00,$AA0000
ROM[0x0771]=0xFC; // Speed Hack
ROM[0x0772]=0x00;
ROM[0x0773]=0x00;
ROM[0x0774]=0x00;
ROM[0x0775]=0xAA;
ROM[0x0776]=0x00;
ROM[0x0777]=0x00;
ROM[0x0778]=0x60;
ROM[0x0779]=0x100-(6+10);
load_common();
AddTaitoYM2610(0x023A, 0x01BA, 0x10000);
/*-----------------------*/
RAM_VIDEO = RAM+0x18000;
RAM_SCROLL = RAM+0x3C100;
RAM_OBJECT = RAM+0x10000;
RAM_INPUT = RAM+0x3C000;
GFX_FG0 = RAM+0x3c200;
set_colour_mapper(&col_map_rrrr_gggg_bbbb_xxxx);
InitPaletteMap(RAM+0x3A000, 0x100, 0x10, 0x1000);
setup_gfx();
// Init tc0220ioc emulation
// ------------------------
tc0100scn[0].layer[0].scr_x =19;
tc0100scn[0].layer[1].scr_x =19; // -80 for f2demo !
tc0100scn[0].layer[2].scr_x =19;
tc0200obj.ofs_x = -3+6; // ???
tc0220ioc.RAM = RAM_INPUT;
tc0220ioc.ctrl = 0; //TC0220_STOPCPU;
reset_tc0220ioc();
// Init tc0100scn emulation
// ------------------------
init_tc0100scn(0);
tc0100scn_0_copy_gfx_fg0(ROM+0x10FC2, 0x1000);
/*
* StarScream Stuff follows
*/
AddRWBW(0x200000, 0x20FFFF, NULL, RAM+0x000000); // 68000 RAM
AddRWBW(0x600000, 0x61FFFF, NULL, RAM_VIDEO); // SCREEN RAM
AddReadBW(0x120000, 0x12000F, NULL, RAM_INPUT); // INPUT
AddReadByte(0x100000, 0x100003, tc0140syt_read_main_68k, NULL); // SOUND COMM
AddRWBW(0x180000, 0x180FFF, NULL, RAM+0x038000); // C-CHIP (HACKED?)
AddReadByte(0x000000, 0xFFFFFF, DefBadReadByte, NULL); // <Bad Reads>
AddReadByte(-1, -1, NULL, NULL);
AddReadWord(0x800000, 0x807FFF, NULL, RAM_OBJECT); // SPRITE RAM
AddReadWord(0x300000, 0x301FFF, NULL, RAM+0x03A000); // COLOR RAM
AddReadWord(0x000000, 0xFFFFFF, DefBadReadWord, NULL); // <Bad Reads>
AddReadWord(-1, -1,NULL, NULL);
AddWriteByte(0x800000, 0x807FFF, NULL, RAM_OBJECT); // SPRITE RAM
AddWriteByte(0x400000, 0x4000FF, NULL, RAM+0x039000); // ???
AddWriteByte(0x100000, 0x100003, tc0140syt_write_main_68k, NULL); // SOUND COMM
AddWriteByte(0x120000, 0x12000F, tc0220ioc_wb, NULL); // INPUT
AddWriteByte(0xAA0000, 0xAA0001, Stop68000, NULL); // Trap Idle 68000
AddWriteByte(0x000000, 0xFFFFFF, DefBadWriteByte, NULL); // <Bad Writes>
AddWriteByte(-1, -1, NULL, NULL);
AddWriteWord(0x200000, 0x20FFFF, NULL, RAM+0x000000); // 68000 RAM
AddWriteWord(0x800000, 0x807FFF, NULL, RAM_OBJECT); // SPRITE RAM
AddWriteWord(0x300000, 0x301FFF, NULL, RAM+0x03A000); // COLOR RAM
AddWriteWord(0x620000, 0x6200FF, NULL, RAM+0x03C100); // SCROLL RAM
AddWriteWord(0x400000, 0x4000FF, NULL, RAM+0x039000); // ???
AddWriteWord(0x120000, 0x12000F, tc0220ioc_ww, NULL); // INPUT
AddWriteWord(0x000000, 0xFFFFFF, DefBadWriteWord, NULL); // <Bad Writes>
AddWriteWord(-1, -1, NULL, NULL);
AddInitMemory(); // Set Starscream mem pointers...
TC0360PRI_regs = RAM+0x039000;
}
static void load_liquidk(void)
{
// 68000 Speed Hack
// ----------------
WriteLong68k(&ROM[0x89F6],0x4E714E71);
WriteLong68k(&ROM[0x89FA],0x4E714E71);
// Fix ROM Checksum
// ----------------
WriteWord68k(&ROM[0x1DAE],0x4E75);
// Fix Long Sound Wait
// -------------------
WriteWord68k(&ROM[0x017A],0x4E71);
load_common();
if (load_region[REGION_CPU2]) {
setup_z80_frame(CPU_Z80_0,CPU_FRAME_MHz(4.2,60));
AddTaitoYM2610(0x01DD, 0x0189, 0x10000);
}
/*-----------------------*/
RAM_VIDEO = RAM+0x10000;
RAM_SCROLL = RAM+0x32000;
RAM_OBJECT = RAM+0x20000;
GFX_FG0 = RAM+0x34000;
setup_gfx();
set_colour_mapper(&col_map_rrrr_gggg_bbbb_xxxx);
InitPaletteMap(RAM+0x30000, 0x100, 0x10, 0x1000);
// Init tc0220ioc emulation
// ------------------------
tc0220ioc.RAM = input_buffer;
tc0220ioc.ctrl = TC0220_STOPCPU;
reset_tc0220ioc();
// Init tc0100scn emulation
// ------------------------
// tc0100scn[0].layer[0].scr_x =20;
// tc0100scn[0].layer[1].scr_x =20; // -80 for f2demo !
// tc0100scn[0].layer[2].scr_x =20;
// tc0100scn[0].layer[2].scr_y =24;
init_tc0100scn(0);
// Init tc0200obj emulation
// ------------------------
tc0200obj.RAM_B = RAM_OBJECT+0x8000;
tc0200obj.ofs_x = -3+7; // ???
/*
* StarScream Stuff follows
*/
AddRWBW(0x100000, 0x10FFFF, NULL, RAM+0x000000); // 68000 RAM
AddReadByte(0x800000, 0x80FFFF, NULL, RAM_VIDEO); // SCREEN RAM
AddReadByte(0x900000, 0x90FFFF, NULL, RAM_OBJECT); // OBJECT RAM
AddReadBW(0x300000, 0x30001F, NULL, input_buffer); // INPUT
AddReadByte(0x320000, 0x320003, tc0140syt_read_main_68k, NULL); // SOUND COMM
AddReadByte(0x400000, 0x40000F, NULL, RAM+0x032200); // ???
AddReadWord(0x800000, 0x80FFFF, NULL, RAM_VIDEO); // SCREEN RAM
AddReadWord(0x900000, 0x90FFFF, NULL, RAM_OBJECT); // OBJECT RAM
AddReadWord(0x200000, 0x201FFF, NULL, RAM+0x030000); // COLOR RAM
AddWriteByte(0x806000, 0x806FFF, tc0100scn_0_gfx_fg0_wb, NULL); // FG0 GFX RAM
AddWriteByte(0x800000, 0x80FFFF, NULL, RAM_VIDEO); // SCREEN RAM
AddWriteByte(0x900000, 0x90FFFF, NULL, RAM_OBJECT); // OBJECT RAM
AddWriteByte(0x300000, 0x30001F, tc0220ioc_wb, NULL); // INPUT
AddWriteByte(0x400000, 0x40000F, NULL, RAM+0x032200); // ???
AddWriteByte(0x320000, 0x320003, tc0140syt_write_main_68k, NULL); // SOUND COMM
AddWriteByte(0xAA0000, 0xAA0001, Stop68000, NULL); // Trap Idle 68000
AddWriteBW(0xB00000, 0xB000FF, NULL, RAM+0x032300); // ???
AddWriteWord(0x806000, 0x806FFF, tc0100scn_0_gfx_fg0_ww, NULL); // FG0 GFX RAM
AddWriteWord(0x800000, 0x80FFFF, NULL, RAM_VIDEO); // SCREEN RAM
AddWriteWord(0x900000, 0x90FFFF, NULL, RAM_OBJECT); // OBJECT RAM
AddWriteWord(0x200000, 0x201FFF, NULL, RAM+0x030000); // COLOR RAM
AddWriteWord(0x300000, 0x30001F, tc0220ioc_ww, NULL); // INPUT
AddWriteWord(0x820000, 0x82000F, NULL, RAM_SCROLL); // SCROLL RAM
AddWriteWord(0x380000, 0x38000F, NULL, RAM+0x032180); // ???
AddWriteWord(0x600000, 0x60000F, NULL, RAM+0x032280); // ???
finish_conf_68000(0);
TC0360PRI_regs = RAM+0x032300;
}
static int last_scr,last_scr2;
static void execute_dondokdj(void)
{
tc0005rot_set_bitmap();
last_scr=ReadLong(&RAM_OBJECT[0x24]); // Keep Sprites and Scrolling in sync (sprites are 1 frame behind)
//print_ingame(60,gettext("%04x"),ReadWord(&RAM_OBJECT[0x0A]));
cpu_execute_cycles(CPU_68K_0, CPU_FRAME_MHz(12,60)); // M68000 12MHz (60fps)
cpu_interrupt(CPU_68K_0, 5);
cpu_execute_cycles(CPU_68K_0, CPU_FRAME_MHz(12,60)); // M68000 12MHz (60fps)
cpu_interrupt(CPU_68K_0, 6);
Taito2610_Frame(); // Z80 and YM2610
tc0005rot_unset_bitmap();
}
static void execute_driftout(void)
{
tc0005rot_set_bitmap();
cpu_execute_cycles(CPU_68K_0, CPU_FRAME_MHz(12,60)); // M68000 12MHz (60fps)
cpu_interrupt(CPU_68K_0, 6);
cpu_execute_cycles(CPU_68K_0,500);
cpu_interrupt(CPU_68K_0, 5);
Taito2610_Frame(); // Z80 and YM2610
tc0005rot_unset_bitmap();
}
static void execute_driveout(void)
{
// rotation frame, no sprites delay
tc0005rot_set_bitmap();
cpu_execute_cycles(CPU_68K_0, CPU_FRAME_MHz(12,60)); // M68000 12MHz (60fps)
cpu_interrupt(CPU_68K_0, 5);
cpu_execute_cycles(CPU_68K_0, 500); // M68000 12MHz (60fps)
cpu_interrupt(CPU_68K_0, 6);
cpu_execute_cycles(CPU_Z80_0, (4000000/60)); // Sound Z80
tc0005rot_unset_bitmap();
}
static void execute_liquidk(void)
{
last_scr=ReadLong(&RAM_OBJECT[0x24]); // Keep Sprites and Scrolling in sync (sprites are 1 frame behind)
cpu_execute_cycles(CPU_68K_0, CPU_FRAME_MHz(12,60)); // M68000 12MHz (60fps)
cpu_interrupt(CPU_68K_0, 5);
cpu_execute_cycles(CPU_68K_0,1);
cpu_interrupt(CPU_68K_0, 6);
cpu_execute_cycles(CPU_68K_0, CPU_FRAME_MHz(12,60)); // M68000 12MHz (60fps)
Taito2610_Frame(); // Z80 and YM2610
}
static void execute_f2demo(void)
{
// the demo appears too much on the right, but it's based on mame source...
// It's funny there is such a difference, because we are very similar for the games.
UINT16 *scroll = (UINT16*)RAM_SCROLL+1;
last_scr=ReadLong(&RAM_OBJECT[0x24]); // Keep Sprites and Scrolling in sync (sprites are 1 frame behind)
cpu_execute_cycles(CPU_68K_0, CPU_FRAME_MHz(12,60)); // M68000 12MHz (60fps)
cpu_interrupt(CPU_68K_0, 5);
cpu_execute_cycles(CPU_68K_0, CPU_FRAME_MHz(12,60)); // M68000 12MHz (60fps)
cpu_interrupt(CPU_68K_0, 6);
if ((RAM[0x32104] & 8) == 0)
scroll[1]--;
else if ((RAM[0x32104] & 4) == 0)
scroll[1]++;
else if ((RAM[0x32104] & 1) == 0) // up
scroll[4]++;
else if ((RAM[0x32104] & 2) == 0) // up
scroll[4]--;
}
static void execute_megab(void)
{
RAM[0x38802]=0x01; // c chip for megab
cpu_execute_cycles(CPU_68K_0, CPU_FRAME_MHz(12,60)); // M68000 12MHz (60fps)
cpu_interrupt(CPU_68K_0, 5);
cpu_execute_cycles(CPU_68K_0, 500); // M68000 12MHz (60fps)
cpu_interrupt(CPU_68K_0, 6);
Taito2610_Frame(); // Z80 and YM2610
}
static void execute_ssi(void)
{
cpu_execute_cycles(CPU_68K_0, CPU_FRAME_MHz(12,60)); // M68000 12MHz (60fps)
cpu_interrupt(CPU_68K_0, 5);
cpu_execute_cycles(CPU_68K_0, CPU_FRAME_MHz(6,60)); // Overflow for sprite sync
Taito2610_Frame(); // Z80 and YM2610
}
static void execute_mjnquest(void)
{
// no delay, no c chip, no rotating tile !
cpu_execute_cycles(CPU_68K_0, CPU_FRAME_MHz(12,60)); // M68000 12MHz (60fps)
cpu_interrupt(CPU_68K_0, 5);
cpu_execute_cycles(CPU_68K_0, 500); // M68000 12MHz (60fps)
cpu_interrupt(CPU_68K_0, 6);
Taito2610_Frame(); // Z80 and YM2610
}
static void execute_solfigtr(void)
{
// no delay, no c chip, no rotating tile, but sprite banks...
cpu_execute_cycles(CPU_68K_0, CPU_FRAME_MHz(12,60)); // M68000 12MHz (60fps)
cpu_interrupt(CPU_68K_0, 5);
cpu_execute_cycles(CPU_68K_0, 500); // M68000 12MHz (60fps)
cpu_interrupt(CPU_68K_0, 6);
Taito2610_Frame(); // Z80 and YM2610
make_object_bank(GFX_BANK);
}
static void execute_growl(void)
{
// no delay, no c chip, no rotating tile, but sprite banks...
cpu_execute_cycles(CPU_68K_0, CPU_FRAME_MHz(12,60)); // M68000 12MHz (60fps)
cpu_interrupt(CPU_68K_0, 5);
cpu_execute_cycles(CPU_68K_0, CPU_FRAME_MHz(12,60)); // M68000 12MHz (60fps)
cpu_interrupt(CPU_68K_0, 6);
Taito2610_Frame(); // Z80 and YM2610
make_object_bank(GFX_BANK);
}
static void execute_gunfront(void)
{
// 68k overclocked because of speed hacks, 2 execute_cycles / frame for sprite sync
cpu_execute_cycles(CPU_68K_0, CPU_FRAME_MHz(20,60) - s68000_cycles_run);
cpu_interrupt(CPU_68K_0, 5);
cpu_execute_cycles(CPU_68K_0,1);
cpu_interrupt(CPU_68K_0, 6);
#if USE_MUSASHI < 2
s68000_cycles_run = 0;
#endif
cpu_execute_cycles(CPU_68K_0, CPU_FRAME_MHz(20,60));
Taito2610_Frame(); // Z80 and YM2610
}
static void execute_cameltry(void)
{
static int p1_paddle_x,p1_paddle_y;
static int p2x,p2y;
int px,py;
p1_paddle_x=p1_paddle_x/2;
p1_paddle_y=p1_paddle_y/2;
p2x=p2x/2;
p2y=p2y/2;
/*------[Mouse Hack]-------*/
GetMouseMickeys(&px,&py);
p1_paddle_x+=px/4;
p1_paddle_y+=py/4;
if(*MouseB&1){input_buffer[0x04]&=0x10^255;}
if((!(input_buffer[0x4]&4))&&(p1_paddle_x> -0x40)) p1_paddle_x-=0x08;
if((!(input_buffer[0x4]&8))&&(p1_paddle_x< 0x3F)) p1_paddle_x+=0x08;
if((!(input_buffer[0x6]&4))&&(p2x> -0x40)) p2x-=0x08;
if((!(input_buffer[0x6]&8))&&(p2x< 0x3F)) p2x+=0x08;
WriteWord(&input_buffer[0x18],p1_paddle_x);
WriteWord(&input_buffer[0x1C],p2x);
tc0005rot_set_bitmap();
cpu_execute_cycles(CPU_68K_0, CPU_FRAME_MHz(12,60)); // M68000 12MHz (60fps)
cpu_interrupt(CPU_68K_0, 5);
cpu_execute_cycles(CPU_68K_0,1);
cpu_interrupt(CPU_68K_0, 6);
execute_z80_audio_frame();
tc0005rot_unset_bitmap();
}
#define TC0360PRI_regs_lsb(x) TC0360PRI_regs[(x)*2]
#define TC0360PRI_regs_msb(x) TC0360PRI_regs[(x)*2+1]
static void draw_f2_pri_rot_delay(void)
{
int ta, num,pri_mask=0;
UINT8 rozpri;
ClearPaletteMap();
if (!init_gfx)
finish_setup_gfx();
for (ta=0; ta<8; ta++)
layer[ta].num = ta;
layer[0].pri = TC0360PRI_regs_lsb(5) & 0x0f; // tc100scn BG0 (or flipped)
layer[1].pri = TC0360PRI_regs_lsb(5) >> 4; // tc100scn BG1 (or flipped)
layer[2].pri = TC0360PRI_regs_lsb(4) >> 4; // tc100scn FG0
rozpri = (TC0360PRI_regs_lsb(1) & 0xc0) >> 6;
rozpri = (TC0360PRI_regs_lsb(8 + rozpri/2) >> 4*(rozpri & 1)) & 0x0f;
layer[3].pri = rozpri;
layer[4].pri = TC0360PRI_regs_lsb(6) & 0x0f; // sprites colors 00
layer[5].pri = TC0360PRI_regs_lsb(6) >> 4; // sprites colors 01
layer[6].pri = TC0360PRI_regs_lsb(7) & 0x0f; // sprites colors 10
layer[7].pri = TC0360PRI_regs_lsb(7) >> 4; // sprites colors 11
qsort(&layer,8,sizeof(struct layer),layer_cmp);
// Init tc0100scn emulation
// ------------------------
tc0100scn[0].ctrl = ReadWord(RAM_SCROLL+12);
/* Notice : below there is a hack to try to do without a priority bitmap
* but it doesn't work well for pulirula.
* But adding a priority bitmap would require to use it for all the games
* using tc005rot, tc200obj or tc100scn, which is a really big mess.
* So for now I prefer to leave it as it is... ! */
if(RefreshBuffers){
tc0005rot_refresh_buffer();
}
last_scr2=ReadLong(&RAM_OBJECT[0x24]); // [Store]
WriteLong(&RAM_OBJECT[0x24],last_scr); // Delay Scrolling 1 frame
for (ta=0; ta<8; ta++) {
num = layer[ta].num;
if (ta == 0 && num > 3)
clear_game_screen(0);
switch(num) {
case 0:
case 1:
case 2:
if (pri_mask) {
render_tc0200obj_mapped(pri_mask);
pri_mask = 0;
}
render_tc0100scn_layer_mapped(0,num,ta>0);
break;
case 3:
tc0005rot_draw_rot((ReadWord(&TC0360PRI_regs[2])&0x3F)<<2,ta>0);
break;
default:
pri_mask |= (1<<(num & 3));
}
}
if (pri_mask) {
render_tc0200obj_mapped(pri_mask);
}
WriteLong(&RAM_OBJECT[0x24],last_scr2); // [Restore]
}
// Compared to dondokod it does not have the 1 frame delay for the sprites
// and it does not have bg0/bg1.
static void draw_cameltry(void)
{
int ta, num,pri_mask=0;
UINT8 rozpri;
ClearPaletteMap();
if (!init_gfx)
finish_setup_gfx();
for (ta=0; ta<6; ta++)
layer[ta].num = ta;
rozpri = (TC0360PRI_regs_lsb(1) & 0xc0) >> 6;
rozpri = (TC0360PRI_regs_lsb(8 + rozpri/2) >> 4*(rozpri & 1)) & 0x0f;
layer[0].pri = TC0360PRI_regs_lsb(6) & 0x0f; // sprites colors 00
layer[1].pri = TC0360PRI_regs_lsb(6) >> 4; // sprites colors 01
layer[2].pri = TC0360PRI_regs_lsb(7) & 0x0f; // sprites colors 10
layer[3].pri = TC0360PRI_regs_lsb(7) >> 4; // sprites colors 11
layer[4].pri = rozpri;
layer[5].pri = TC0360PRI_regs_lsb(4) >> 4; // tc100scn FG0
qsort(&layer,6,sizeof(struct layer),layer_cmp);
// Init tc0100scn emulation
// ------------------------
tc0100scn[0].ctrl = ReadWord(RAM_SCROLL+12);
if(RefreshBuffers){
tc0005rot_refresh_buffer();
}
if (layer[0].num != 4) {
UINT8 *map;
MAP_PALETTE_MAPPED_NEW(
0,
16,
map
);
clear_game_screen(ReadLong(&map[0]));
}
for (ta=0; ta<6; ta++) {
num = layer[ta].num;
switch(num) {
case 5:
if (pri_mask) {
render_tc0200obj_mapped(pri_mask);
pri_mask = 0;
}
render_tc0100scn_layer_mapped(0,2,ta>0);
break;
case 4:
if (pri_mask) {
render_tc0200obj_mapped(pri_mask);
pri_mask = 0;
}
tc0005rot_draw_rot((ReadWord(&TC0360PRI_regs[2])&0x3F)<<2,ta>0);
break;
default:
pri_mask |= (1<<(num & 3));
}
}
if (pri_mask) {
render_tc0200obj_mapped(pri_mask);
}
}
static void draw_f2_pri_rot(void)
{
int ta, num,pri_mask=0;
UINT8 rozpri,*map;
ClearPaletteMap();
if (!init_gfx)
finish_setup_gfx();
for (ta=0; ta<6; ta++)
layer[ta].num = ta;
layer[5].pri = TC0360PRI_regs_msb(4) >> 4; // tc100scn FG0
rozpri = (TC0360PRI_regs_msb(1) & 0xc0) >> 6;
rozpri = (TC0360PRI_regs_msb(8 + rozpri/2) >> 4*(rozpri & 1)) & 0x0f;
layer[4].pri = rozpri;
layer[0].pri = TC0360PRI_regs_msb(6) & 0x0f; // sprites colors 00
layer[1].pri = TC0360PRI_regs_msb(6) >> 4; // sprites colors 01
layer[2].pri = TC0360PRI_regs_msb(7) & 0x0f; // sprites colors 10
layer[3].pri = TC0360PRI_regs_msb(7) >> 4; // sprites colors 11
qsort(&layer,6,sizeof(struct layer),layer_cmp);
// Init tc0100scn emulation
// ------------------------
tc0100scn[0].ctrl = ReadWord(RAM_SCROLL+12);
if(RefreshBuffers){
tc0005rot_refresh_buffer();
}
// in fact the priorities in drift out never place the rotating layer as the first
// layer (at least nowhere in the attract mode nor in the 1st race). So no need to
// bother : just clear the screen then draw a transparant rotating layer.
if (layer[0].num < 4) {
MAP_PALETTE_MAPPED_NEW(
0,
16,
map
);
clear_game_screen(ReadLong(&map[0]));
}
for (ta=0; ta<6; ta++) {
num = layer[ta].num;
switch(num) {
case 0:
case 1:
case 2:
case 3:
pri_mask |= (1<<(num));
break;
case 4:
if (pri_mask) {
render_tc0200obj_mapped(pri_mask);
pri_mask = 0;
}
tc0005rot_draw_rot_r270((ReadWord(&TC0360PRI_regs[2])&0x3F)<<2,ta>0);
break;
case 5:
if (pri_mask) {
render_tc0200obj_mapped(pri_mask);
pri_mask = 0;
}
render_tc0100scn_layer_mapped(0,2,ta>0);
break;
}
}
if (pri_mask) {
render_tc0200obj_mapped(pri_mask);
}
}
// same thing without the rotated layer (TC280GRD)
static void draw_f2_pri(void)
{
int ta, num,pri_mask=0;
UINT8 *map;
ClearPaletteMap();
if (!init_gfx)
finish_setup_gfx();
for (ta=0; ta<8; ta++)
layer[ta].num = ta;
layer[0].pri = TC0360PRI_regs_lsb(5) & 0x0f; // tc100scn BG0 (or flipped)
layer[1].pri = TC0360PRI_regs_lsb(5) >> 4; // tc100scn BG1 (or flipped)
layer[2].pri = TC0360PRI_regs_lsb(4) >> 4; // tc100scn FG0
// sprites must start at 4, so layer 3 is empty
layer[4].pri = TC0360PRI_regs_lsb(6) & 0x0f; // sprites colors 00
layer[5].pri = TC0360PRI_regs_lsb(6) >> 4; // sprites colors 01
layer[6].pri = TC0360PRI_regs_lsb(7) & 0x0f; // sprites colors 10
layer[7].pri = TC0360PRI_regs_lsb(7) >> 4; // sprites colors 11
qsort(&layer,8,sizeof(struct layer),layer_cmp);
// Init tc0100scn emulation
// ------------------------
tc0100scn[0].ctrl = ReadWord(RAM_SCROLL+12);
if (layer[0].num >= 4) {
MAP_PALETTE_MAPPED_NEW(
0,
16,
map
);
clear_game_screen(ReadLong(&map[0]));
}
for (ta=0; ta<8; ta++) {
num = layer[ta].num;
switch(num) {
case 0:
case 1:
case 2:
if (pri_mask) {
render_tc0200obj_mapped(pri_mask);
pri_mask = 0;
}
render_tc0100scn_layer_mapped(0,num,ta>0);
break;
case 3:
// tc0005rot_draw_rot((ReadWord(&RAM[0x32302])&0x3F)<<2);
break;
default:
pri_mask |= (1<<(num & 3));
}
}
if (pri_mask) {
render_tc0200obj_mapped(pri_mask);
}
}
// And a mix between the 2
static void draw_f2_pri_delay(void)
{
int ta, num,pri_mask=0;
UINT8 *map;
ClearPaletteMap();
if (!init_gfx)
finish_setup_gfx();
for (ta=0; ta<8; ta++)
layer[ta].num = ta;
layer[0].pri = TC0360PRI_regs_lsb(5) & 0x0f; // tc100scn BG0 (or flipped)
layer[1].pri = TC0360PRI_regs_lsb(5) >> 4; // tc100scn BG1 (or flipped)
layer[2].pri = TC0360PRI_regs_lsb(4) >> 4; // tc100scn FG0
// no layer 3
layer[4].pri = TC0360PRI_regs_lsb(6) & 0x0f; // sprites colors 00
layer[5].pri = TC0360PRI_regs_lsb(6) >> 4; // sprites colors 01
layer[6].pri = TC0360PRI_regs_lsb(7) & 0x0f; // sprites colors 10
layer[7].pri = TC0360PRI_regs_lsb(7) >> 4; // sprites colors 11
qsort(&layer,8,sizeof(struct layer),layer_cmp);
// Init tc0100scn emulation
// ------------------------
tc0100scn[0].ctrl = ReadWord(RAM_SCROLL+12);
last_scr2=ReadLong(&RAM_OBJECT[0x24]); // [Store]
WriteLong(&RAM_OBJECT[0x24],last_scr); // Delay Scrolling 1 frame
if (layer[0].num > 1) {
MAP_PALETTE_MAPPED_NEW(
0,
16,
map
);
clear_game_screen(ReadLong(&map[0]));
}
for (ta=0; ta<8; ta++) {
num = layer[ta].num;
// printf("%d:%d ",num,layer[ta].pri);
switch(num) {
case 0:
case 1:
case 2:
if (pri_mask) {
render_tc0200obj_mapped(pri_mask);
pri_mask = 0;
}
render_tc0100scn_layer_mapped(0,num,ta>0);
break;
case 3:
break;
default:
pri_mask |= (1<<(num & 3));
break;
}
}
if (pri_mask) {
render_tc0200obj_mapped(pri_mask);
}
WriteLong(&RAM_OBJECT[0x24],last_scr2); // [Restore]
}
static void draw_thundfox(void)
{
UINT8 *map;
/* Clearly the priorities chip is not used for this game :
- if you believe theory, a bg layer should go on top of sprites, which creates
a big black thunder bolt during attract mode
- Also fg priority often becomes bad, and text disappears behind sprites
The priorities found by hand by Antiriad seem to work much better ! :-) */
ClearPaletteMap();
if (!init_gfx3) {
tc0100scn[1].layer[0].GFX =gfx3;
tc0100scn[1].layer[0].MASK =gfx3_solid;
tc0100scn[1].layer[1].GFX =gfx3;
tc0100scn[1].layer[1].MASK =gfx3_solid;
tc0100scn[1].layer[0].tile_mask=
tc0100scn[1].layer[1].tile_mask=
max_sprites[2]-1;
init_gfx3 = 1;
finish_setup_gfx();
}
// it would be draw_no_pri if bg0 was really solid, but in attract mode
// you get a black area if you draw bg0 as solid.
// And you have the init of the 2 tc100scn also.
MAP_PALETTE_MAPPED_NEW(
0,
16,
map
);
clear_game_screen(ReadLong(&map[0]));
// Init tc0100scn emulation
// ------------------------
tc0100scn[0].ctrl = ReadWord(RAM_SCROLL + 12);
tc0100scn[1].ctrl = ReadWord(RAM_SCROLL2 + 12);
// BG0 A
// -----
render_tc0100scn_layer_mapped(1,0,1);
// BG0 B
// -----
render_tc0100scn_layer_mapped(0,0,1);
// BG1 A
// -----
render_tc0100scn_layer_mapped(1,1,1);
// BG1 B
// -----
render_tc0100scn_layer_mapped(0,1,1);
// OBJECT
// ------
render_tc0200obj_mapped(255);
// FG0 A
// -----
render_tc0100scn_layer_mapped(1,2,1);
// FG0 B
// -----
render_tc0100scn_layer_mapped(0,2,1);
}
static void draw_ssi(void)
{
UINT8 *map;
ClearPaletteMap();
if (!init_gfx)
finish_setup_gfx();
MAP_PALETTE_MAPPED_NEW(
0,
16,
map
);
clear_game_screen(ReadLong(&map[0]));
// only sprites, and apparently there are no priorities to handle
// (because the sprites are probably grouped since there are big sprites)
render_tc0200obj_mapped(255);
}
static void draw_no_pri() {
ClearPaletteMap();
if (!init_gfx)
finish_setup_gfx();
// Init tc0100scn emulation
// ------------------------
tc0100scn[0].ctrl = ReadWord(RAM_SCROLL+12);
// BG0
// ---
render_tc0100scn_layer_mapped(0,0,0);
// BG1
// ---
render_tc0100scn_layer_mapped(0,1,1);
// OBJECT
// ------
render_tc0200obj_mapped(255);
// FG0
// ---
render_tc0100scn_layer_mapped(0,2,1);
}
// and mahjong quest : no priorities at all ?!!
static void draw_mjnquest(void)
{
if(ReadWord(&GFX_BANK[0])==0){
tc0100scn[0].layer[0].GFX = GFX;
tc0100scn[0].layer[0].MASK = gfx_solid[0];
tc0100scn[0].layer[1].GFX = GFX;
tc0100scn[0].layer[1].MASK = gfx_solid[0];
}
else{
tc0100scn[0].layer[0].GFX = GFX + (0x8000 * 0x40);
tc0100scn[0].layer[0].MASK = gfx_solid[0] + (0x8000);
tc0100scn[0].layer[1].GFX = GFX + (0x8000 * 0x40);
tc0100scn[0].layer[1].MASK = gfx_solid[0] + (0x8000);
}
draw_no_pri();
}
// The inputs do not have the same adreses as dondokod. Maybe we should use input_buffer
// instead of a direct mapping...
static struct INPUT_INFO input_megab[] =
{
INP0( COIN1, 0x03C00E, 0x04 ),
INP0( COIN2, 0x03C00E, 0x08 ),
INP0( TILT, 0x03C00E, 0x01 ),
INP0( SERVICE, 0x03C00E, 0x02 ),
INP0( P1_START, 0x03C00E, 0x10 ),
INP0( P1_UP, 0x03C004, 0x01 ),
INP0( P1_DOWN, 0x03C004, 0x02 ),
INP0( P1_LEFT, 0x03C004, 0x04 ),
INP0( P1_RIGHT, 0x03C004, 0x08 ),
INP0( P1_B1, 0x03C004, 0x10 ),
INP0( P1_B2, 0x03C004, 0x20 ),
INP0( P2_START, 0x03C00E, 0x20 ),
INP0( P2_UP, 0x03C006, 0x01 ),
INP0( P2_DOWN, 0x03C006, 0x02 ),
INP0( P2_LEFT, 0x03C006, 0x04 ),
INP0( P2_RIGHT, 0x03C006, 0x08 ),
INP0( P2_B1, 0x03C006, 0x10 ),
INP0( P2_B2, 0x03C006, 0x20 ),
END_INPUT
};
static struct VIDEO_INFO video_cameltry =
{
draw_cameltry,
320,
224,
32,
VIDEO_ROTATE_NORMAL | VIDEO_ROTATABLE,
pivot_gfxdecodeinfo
};
static struct VIDEO_INFO video_dondokdj =
{
draw_f2_pri_rot_delay,
320,
224,
32,
VIDEO_ROTATE_180 | VIDEO_ROTATABLE,
pivot_gfxdecodeinfo
};
static struct VIDEO_INFO video_driftout =
{
draw_f2_pri_rot,
320,
224,
32,
VIDEO_ROTATE_270 |VIDEO_ROTATABLE,
pivot_gfxdecodeinfo
};
static struct VIDEO_INFO video_finalb =
{
draw_no_pri,
320,
224,
32,
VIDEO_ROTATE_NORMAL | VIDEO_ROTATABLE,
finalb_gfxdecodeinfo
};
static struct VIDEO_INFO video_gunfront =
{
draw_f2_pri,
320,
224,
32,
VIDEO_ROTATE_270 | VIDEO_ROTATABLE,
pivot_gfxdecodeinfo
};
static struct VIDEO_INFO video_liquidk =
{
draw_f2_pri_delay,
320,
224,
32,
VIDEO_ROTATE_180 | VIDEO_ROTATABLE,
pivot_gfxdecodeinfo
};
static struct VIDEO_INFO video_mjnquest =
{
draw_mjnquest,
320,
224,
32,
VIDEO_ROTATE_NORMAL | VIDEO_ROTATABLE,
mjnquest_gfxdecodeinfo
};
static struct VIDEO_INFO video_pulirula =
{
draw_f2_pri_rot_delay,
320,
224,
32,
VIDEO_ROTATE_NORMAL | VIDEO_ROTATABLE,
pivot_gfxdecodeinfo
};
static struct VIDEO_INFO video_solfigtr =
{
draw_f2_pri,
320,
224,
32,
VIDEO_ROTATE_NORMAL | VIDEO_ROTATABLE,
pivot_gfxdecodeinfo
};
static struct VIDEO_INFO video_ssi =
{
// this one is particular : only sprites !
draw_ssi,
320,
224,
32,
VIDEO_ROTATE_270 |
VIDEO_ROTATABLE,
pivot_gfxdecodeinfo
};
static struct VIDEO_INFO video_thundfox =
{
draw_thundfox,
320,
224,
32,
VIDEO_ROTATE_NORMAL | VIDEO_ROTATABLE,
thundfox_decodeinfo
};
#define input_cameltry input_f2b1
GMEI( cameltry, "Camel Try", TAITO, 1989, GAME_PUZZLE,
.romsw = romsw_cameltry,
.long_name_jpn = "キャメルトライ",
.board = "C38",
);
CLNEI(camltrua,cameltry, "Camel Try (Alternate)", TAITO, 1989, GAME_PUZZLE,
.load_game = load_camltrua,
.long_name_jpn = "キャメルトライ",
.board = "C38",
.sound = sound_camltrua,
);
static struct DIR_INFO dir_dinorex[] =
{
{ "dino_rex", },
{ "dinorex", },
{ NULL, },
};
GAME( dinorex, "Dino Rex", TAITO, 1992, GAME_BEAT,
.input = input_f2b2,
.dsw = dsw_dinorex,
.romsw = romsw_dondokdj,
.video = &video_solfigtr,
.exec = execute_mjnquest,
.long_name_jpn = "ダイノレックス",
.board = "D39",
);
static struct DIR_INFO dir_dondokdj[] =
{
{ "don_doko_don", },
{ "dondokod", },
{ "dondokdj", },
{ NULL, },
};
GAME( dondokdj, "Don Doko Don", TAITO, 1989, GAME_PLATFORM,
.input = input_f2b2,
.dsw = dsw_dondokdj,
.romsw = romsw_dondokdj,
.video = &video_dondokdj,
.exec = execute_dondokdj,
.long_name_jpn = "ドンドコドン",
.board = "B95",
);
static struct DIR_INFO dir_driftout[] =
{
{ "drift_out", },
{ "driftout", },
{ NULL, },
};
GAME( driftout, "Drift Out", VISCO, 1991, GAME_RACE,
.input = input_f2b2,
.dsw = dsw_driftout,
.video = &video_driftout,
.exec = execute_driftout,
.long_name_jpn = "ドリフトアウト",
);
static struct DIR_INFO dir_driveout[] =
{
{ "drive_out", },
{ "driveout", },
{ ROMOF("driftout"), },
{ CLONEOF("driftout"), },
{ NULL, },
};
GAME(driveout, "Drive Out", BOOTLEG, 1991, GAME_RACE,
.input = input_f2b2,
.dsw = dsw_driftout,
.video = &video_driftout,
.exec = execute_driveout,
.sound = sound_driveout,
);
static struct DIR_INFO dir_f2demo[] =
{
{ "f2demo", },
{ NULL, },
};
#define input_liquidk input_f2b2
CLNE( f2demo, liquidk, "Demo Taito F2", BOOTLEG, 2000, GAME_MISC,
.input = input_f2b2,
.romsw = romsw_f2demo,
.exec = execute_f2demo,
.board = "C49",
);
static struct DIR_INFO dir_finalb[] =
{
{ "final_blow", },
{ "finalb", },
{ "finalbl", },
{ NULL, },
};
#define input_finalb input_f2b3
GAME( finalb, "Final Blow", TAITO, 1988, GAME_BEAT,
.dsw = dsw_finalb,
.romsw = romsw_thundfox,
.video = &video_finalb,
.exec = execute_mjnquest,
.long_name_jpn = "ファイナルブロー",
.board = "B82",
);
static struct DIR_INFO dir_growl[] =
{
{ "growl" },
{ NULL }
};
GAME( growl, "Growl", TAITO, 1990, GAME_BEAT,
.input = input_growl,
.dsw = dsw_growl,
.romsw = romsw_growl,
.video = &video_solfigtr,
.exec = execute_growl,
.long_name_jpn = "ルナーク",
.board = "C74",
);
static struct DIR_INFO dir_gunfront[] =
{
{ "gun_frontier", },
{ "gunfront", },
{ NULL, },
};
GAME( gunfront, "Gun Frontier", TAITO, 1990, GAME_SHOOT,
.input = input_f2b2,
.dsw = dsw_gunfront,
.romsw = romsw_liquidk,
.video = &video_gunfront,
.exec = execute_gunfront,
.long_name_jpn = "ガンフロンティア",
.board = "C71",
);
static struct DIR_INFO dir_liquidk[] =
{
{ "liquid_kids", },
{ "liquidk", },
{ NULL, },
};
GAME( liquidk, "Liquid Kids", TAITO, 1990, GAME_PLATFORM,
.input = input_f2b2,
.dsw = dsw_liquidk,
.romsw = romsw_liquidk,
.video = &video_liquidk,
.exec = execute_liquidk,
.long_name_jpn = "ミズバクオ蝟`険",
.board = "C49",
);
static struct DIR_INFO dir_mjnquest[] =
{
{ "mahjong_quest", },
{ "mjnquest", },
{ NULL, },
};
GAME( mjnquest, "Mahjong Quest", TAITO, 1990, GAME_PUZZLE,
.input = input_mjnquest,
.dsw = dsw_mjnquest,
.video = &video_mjnquest,
.exec = execute_mjnquest,
.board = "C77",
);
static struct DIR_INFO dir_majest12[] =
{
{ "majestic_twelve", },
{ "mj12", },
{ "majest12", },
{ ROMOF("ssi"), },
{ CLONEOF("ssi"), },
{ NULL, },
};
#define input_ssi input_f2b2
CLNE(majest12, ssi, "Majestic Twelve", TAITO, 1990, GAME_SHOOT,
.long_name_jpn = "マジェスティックトウェルブ",
.board = "C64",
);
static struct DIR_INFO dir_megab[] =
{
{ "mega_blast", },
{ "megab", },
{ "megabl", },
{ NULL, },
};
GAME( megab, "Mega Blast", TAITO, 1989, GAME_SHOOT,
.input = input_megab,
.dsw = dsw_megab,
.romsw = romsw_f2demo,
.video = &video_solfigtr,
.exec = execute_megab,
.long_name_jpn = "メガブラスト",
.board = "C11",
);
static struct DIR_INFO dir_pulirula[] =
{
{ "pulirula", },
{ NULL, },
};
GAME( pulirula, "Pulirula", TAITO, 1991, GAME_BEAT,
.input = input_f2b3,
.dsw = dsw_pulirula,
.romsw = romsw_liquidk,
.video = &video_pulirula,
.exec = execute_driftout,
.long_name_jpn = "プリルラ",
.board = "C98",
);
static struct DIR_INFO dir_solfigtr[] =
{
{ "solitary_fighter", },
{ "solfigtr", },
{ NULL, },
};
#define input_solfigtr input_f2b3
GME( solfigtr, "Solitary Fighter", TAITO, 1990, GAME_BEAT,
.romsw = romsw_solfigtr,
.long_name_jpn = "ダイノレックス",
.board = "C91",
);
static struct DIR_INFO dir_ssi[] =
{
{ "super_space_invaders_91", },
{ "ssi", },
{ "space_invaders_91", },
{ NULL, },
};
GME( ssi, "Super Space Invaders 91", TAITO, 1990, GAME_SHOOT,
.romsw = romsw_ssi,
.long_name_jpn = "スーパースペースインベーダー’91",
.board = "C64",
);
static struct DIR_INFO dir_thundfox[] =
{
{ "thunder_fox", },
{ "thundfox", },
{ "thndfoxj", },
{ NULL, },
};
GAME( thundfox, "Thunder Fox", TAITO, 1990, GAME_SHOOT,
.input = input_f2b3,
.dsw = dsw_thundfox,
.romsw = romsw_thundfox,
.video = &video_thundfox,
.exec = execute_liquidk,
.long_name_jpn = "サンダーフォックス",
.board = "C28",
);
|
a66eca9e8ea5b83866c568493274f849858bb9e7
|
99bdb3251fecee538e0630f15f6574054dfc1468
|
/bsp/hpmicro/libraries/hpm_sdk/soc/ip/hpm_plic_regs.h
|
c7dd01a027524bf3705d77fdf301d2f2bbadf344
|
[
"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
| 13,963
|
h
|
hpm_plic_regs.h
|
/*
* Copyright (c) 2021-2023 HPMicro
*
* SPDX-License-Identifier: BSD-3-Clause
*
*/
#ifndef HPM_PLIC_H
#define HPM_PLIC_H
typedef struct {
__RW uint32_t FEATURE; /* 0x0: Feature enable register */
__RW uint32_t PRIORITY[127]; /* 0x4 - 0x1FC: Source priority */
__R uint8_t RESERVED0[3584]; /* 0x200 - 0xFFF: Reserved */
__RW uint32_t PENDING[4]; /* 0x1000 - 0x100C: Pending status */
__R uint8_t RESERVED1[112]; /* 0x1010 - 0x107F: Reserved */
__R uint32_t TRIGGER[4]; /* 0x1080 - 0x108C: Trigger type */
__R uint8_t RESERVED2[112]; /* 0x1090 - 0x10FF: Reserved */
__R uint32_t NUMBER; /* 0x1100: Number of supported interrupt sources and targets */
__R uint32_t INFO; /* 0x1104: Version and the maximum priority */
__R uint8_t RESERVED3[3832]; /* 0x1108 - 0x1FFF: Reserved */
struct {
__RW uint32_t INTEN[4]; /* 0x2000 - 0x200C: machine interrupt enable */
__R uint8_t RESERVED0[112]; /* 0x2010 - 0x207F: Reserved */
} TARGETINT[2];
__R uint8_t RESERVED4[2088704]; /* 0x2100 - 0x1FFFFF: Reserved */
struct {
__RW uint32_t THRESHOLD; /* 0x200000: Target0 priority threshold */
__RW uint32_t CLAIM; /* 0x200004: Target claim and complete */
__R uint8_t RESERVED0[1016]; /* 0x200008 - 0x2003FF: Reserved */
__RW uint32_t PPS; /* 0x200400: Preempted priority stack */
__R uint8_t RESERVED1[3068]; /* 0x200404 - 0x200FFF: Reserved */
} TARGETCONFIG[2];
} PLIC_Type;
/* Bitfield definition for register: FEATURE */
/*
* VECTORED (RW)
*
* Vector mode enable
* 0: Disabled
* 1: Enabled
*/
#define PLIC_FEATURE_VECTORED_MASK (0x2U)
#define PLIC_FEATURE_VECTORED_SHIFT (1U)
#define PLIC_FEATURE_VECTORED_SET(x) (((uint32_t)(x) << PLIC_FEATURE_VECTORED_SHIFT) & PLIC_FEATURE_VECTORED_MASK)
#define PLIC_FEATURE_VECTORED_GET(x) (((uint32_t)(x) & PLIC_FEATURE_VECTORED_MASK) >> PLIC_FEATURE_VECTORED_SHIFT)
/*
* PREEMPT (RW)
*
* Preemptive priority interrupt enable
* 0: Disabled
* 1: Enabled
*/
#define PLIC_FEATURE_PREEMPT_MASK (0x1U)
#define PLIC_FEATURE_PREEMPT_SHIFT (0U)
#define PLIC_FEATURE_PREEMPT_SET(x) (((uint32_t)(x) << PLIC_FEATURE_PREEMPT_SHIFT) & PLIC_FEATURE_PREEMPT_MASK)
#define PLIC_FEATURE_PREEMPT_GET(x) (((uint32_t)(x) & PLIC_FEATURE_PREEMPT_MASK) >> PLIC_FEATURE_PREEMPT_SHIFT)
/* Bitfield definition for register array: PRIORITY */
/*
* PRIORITY (RW)
*
* Interrupt source priority. The valid range of this field is 0-7.
* 0: Never interrupt
* 1-7: Interrupt source priority. The larger the value, the higher the priority.
*/
#define PLIC_PRIORITY_PRIORITY_MASK (0xFFFFFFFFUL)
#define PLIC_PRIORITY_PRIORITY_SHIFT (0U)
#define PLIC_PRIORITY_PRIORITY_SET(x) (((uint32_t)(x) << PLIC_PRIORITY_PRIORITY_SHIFT) & PLIC_PRIORITY_PRIORITY_MASK)
#define PLIC_PRIORITY_PRIORITY_GET(x) (((uint32_t)(x) & PLIC_PRIORITY_PRIORITY_MASK) >> PLIC_PRIORITY_PRIORITY_SHIFT)
/* Bitfield definition for register array: PENDING */
/*
* INTERRUPT (RW)
*
* The interrupt pending status of inpterrupt sources. Every interrupt source occupies 1 bit.
*/
#define PLIC_PENDING_INTERRUPT_MASK (0xFFFFFFFFUL)
#define PLIC_PENDING_INTERRUPT_SHIFT (0U)
#define PLIC_PENDING_INTERRUPT_SET(x) (((uint32_t)(x) << PLIC_PENDING_INTERRUPT_SHIFT) & PLIC_PENDING_INTERRUPT_MASK)
#define PLIC_PENDING_INTERRUPT_GET(x) (((uint32_t)(x) & PLIC_PENDING_INTERRUPT_MASK) >> PLIC_PENDING_INTERRUPT_SHIFT)
/* Bitfield definition for register array: TRIGGER */
/*
* INTERRUPT (RO)
*
* The interrupt trigger type of interrupt sources. Every interrupt source occupies 1 bit.
* 0: Level-triggered interrupt
* 1: Edge-triggered interrupt
*/
#define PLIC_TRIGGER_INTERRUPT_MASK (0xFFFFFFFFUL)
#define PLIC_TRIGGER_INTERRUPT_SHIFT (0U)
#define PLIC_TRIGGER_INTERRUPT_GET(x) (((uint32_t)(x) & PLIC_TRIGGER_INTERRUPT_MASK) >> PLIC_TRIGGER_INTERRUPT_SHIFT)
/* Bitfield definition for register: NUMBER */
/*
* NUM_TARGET (RO)
*
* The number of supported targets
*/
#define PLIC_NUMBER_NUM_TARGET_MASK (0xFFFF0000UL)
#define PLIC_NUMBER_NUM_TARGET_SHIFT (16U)
#define PLIC_NUMBER_NUM_TARGET_GET(x) (((uint32_t)(x) & PLIC_NUMBER_NUM_TARGET_MASK) >> PLIC_NUMBER_NUM_TARGET_SHIFT)
/*
* NUM_INTERRUPT (RO)
*
* The number of supported interrupt sources
*/
#define PLIC_NUMBER_NUM_INTERRUPT_MASK (0xFFFFU)
#define PLIC_NUMBER_NUM_INTERRUPT_SHIFT (0U)
#define PLIC_NUMBER_NUM_INTERRUPT_GET(x) (((uint32_t)(x) & PLIC_NUMBER_NUM_INTERRUPT_MASK) >> PLIC_NUMBER_NUM_INTERRUPT_SHIFT)
/* Bitfield definition for register: INFO */
/*
* MAX_PRIORITY (RO)
*
* The maximum priority supported
*/
#define PLIC_INFO_MAX_PRIORITY_MASK (0xFFFF0000UL)
#define PLIC_INFO_MAX_PRIORITY_SHIFT (16U)
#define PLIC_INFO_MAX_PRIORITY_GET(x) (((uint32_t)(x) & PLIC_INFO_MAX_PRIORITY_MASK) >> PLIC_INFO_MAX_PRIORITY_SHIFT)
/*
* VERSION (RO)
*
* The version of the PLIC design
*/
#define PLIC_INFO_VERSION_MASK (0xFFFFU)
#define PLIC_INFO_VERSION_SHIFT (0U)
#define PLIC_INFO_VERSION_GET(x) (((uint32_t)(x) & PLIC_INFO_VERSION_MASK) >> PLIC_INFO_VERSION_SHIFT)
/* Bitfield definition for register of struct array TARGETINT: INTEN0 */
/*
* INTERRUPT (RW)
*
* The interrupt enable bit for interrupt. Every interrupt source occupies 1 bit.
*/
#define PLIC_TARGETINT_INTEN_INTERRUPT_MASK (0xFFFFFFFFUL)
#define PLIC_TARGETINT_INTEN_INTERRUPT_SHIFT (0U)
#define PLIC_TARGETINT_INTEN_INTERRUPT_SET(x) (((uint32_t)(x) << PLIC_TARGETINT_INTEN_INTERRUPT_SHIFT) & PLIC_TARGETINT_INTEN_INTERRUPT_MASK)
#define PLIC_TARGETINT_INTEN_INTERRUPT_GET(x) (((uint32_t)(x) & PLIC_TARGETINT_INTEN_INTERRUPT_MASK) >> PLIC_TARGETINT_INTEN_INTERRUPT_SHIFT)
/* Bitfield definition for register of struct array TARGETCONFIG: THRESHOLD */
/*
* THRESHOLD (RW)
*
* Interrupt priority threshold.
*/
#define PLIC_TARGETCONFIG_THRESHOLD_THRESHOLD_MASK (0xFFFFFFFFUL)
#define PLIC_TARGETCONFIG_THRESHOLD_THRESHOLD_SHIFT (0U)
#define PLIC_TARGETCONFIG_THRESHOLD_THRESHOLD_SET(x) (((uint32_t)(x) << PLIC_TARGETCONFIG_THRESHOLD_THRESHOLD_SHIFT) & PLIC_TARGETCONFIG_THRESHOLD_THRESHOLD_MASK)
#define PLIC_TARGETCONFIG_THRESHOLD_THRESHOLD_GET(x) (((uint32_t)(x) & PLIC_TARGETCONFIG_THRESHOLD_THRESHOLD_MASK) >> PLIC_TARGETCONFIG_THRESHOLD_THRESHOLD_SHIFT)
/* Bitfield definition for register of struct array TARGETCONFIG: CLAIM */
/*
* INTERRUPT_ID (RW)
*
* On reads, indicating the interrupt source that has being claimed. On writes, indicating the interrupt source that has been handled (completed).
*/
#define PLIC_TARGETCONFIG_CLAIM_INTERRUPT_ID_MASK (0x3FFU)
#define PLIC_TARGETCONFIG_CLAIM_INTERRUPT_ID_SHIFT (0U)
#define PLIC_TARGETCONFIG_CLAIM_INTERRUPT_ID_SET(x) (((uint32_t)(x) << PLIC_TARGETCONFIG_CLAIM_INTERRUPT_ID_SHIFT) & PLIC_TARGETCONFIG_CLAIM_INTERRUPT_ID_MASK)
#define PLIC_TARGETCONFIG_CLAIM_INTERRUPT_ID_GET(x) (((uint32_t)(x) & PLIC_TARGETCONFIG_CLAIM_INTERRUPT_ID_MASK) >> PLIC_TARGETCONFIG_CLAIM_INTERRUPT_ID_SHIFT)
/* Bitfield definition for register of struct array TARGETCONFIG: PPS */
/*
* PRIORITY_PREEMPTED (RW)
*
* Each bit indicates if the corresponding priority level has been preempted by a higher-priority interrupt.
*/
#define PLIC_TARGETCONFIG_PPS_PRIORITY_PREEMPTED_MASK (0xFFFFFFFFUL)
#define PLIC_TARGETCONFIG_PPS_PRIORITY_PREEMPTED_SHIFT (0U)
#define PLIC_TARGETCONFIG_PPS_PRIORITY_PREEMPTED_SET(x) (((uint32_t)(x) << PLIC_TARGETCONFIG_PPS_PRIORITY_PREEMPTED_SHIFT) & PLIC_TARGETCONFIG_PPS_PRIORITY_PREEMPTED_MASK)
#define PLIC_TARGETCONFIG_PPS_PRIORITY_PREEMPTED_GET(x) (((uint32_t)(x) & PLIC_TARGETCONFIG_PPS_PRIORITY_PREEMPTED_MASK) >> PLIC_TARGETCONFIG_PPS_PRIORITY_PREEMPTED_SHIFT)
/* PRIORITY register group index macro definition */
#define PLIC_PRIORITY_PRIORITY1 (0UL)
#define PLIC_PRIORITY_PRIORITY2 (1UL)
#define PLIC_PRIORITY_PRIORITY3 (2UL)
#define PLIC_PRIORITY_PRIORITY4 (3UL)
#define PLIC_PRIORITY_PRIORITY5 (4UL)
#define PLIC_PRIORITY_PRIORITY6 (5UL)
#define PLIC_PRIORITY_PRIORITY7 (6UL)
#define PLIC_PRIORITY_PRIORITY8 (7UL)
#define PLIC_PRIORITY_PRIORITY9 (8UL)
#define PLIC_PRIORITY_PRIORITY10 (9UL)
#define PLIC_PRIORITY_PRIORITY11 (10UL)
#define PLIC_PRIORITY_PRIORITY12 (11UL)
#define PLIC_PRIORITY_PRIORITY13 (12UL)
#define PLIC_PRIORITY_PRIORITY14 (13UL)
#define PLIC_PRIORITY_PRIORITY15 (14UL)
#define PLIC_PRIORITY_PRIORITY16 (15UL)
#define PLIC_PRIORITY_PRIORITY17 (16UL)
#define PLIC_PRIORITY_PRIORITY18 (17UL)
#define PLIC_PRIORITY_PRIORITY19 (18UL)
#define PLIC_PRIORITY_PRIORITY20 (19UL)
#define PLIC_PRIORITY_PRIORITY21 (20UL)
#define PLIC_PRIORITY_PRIORITY22 (21UL)
#define PLIC_PRIORITY_PRIORITY23 (22UL)
#define PLIC_PRIORITY_PRIORITY24 (23UL)
#define PLIC_PRIORITY_PRIORITY25 (24UL)
#define PLIC_PRIORITY_PRIORITY26 (25UL)
#define PLIC_PRIORITY_PRIORITY27 (26UL)
#define PLIC_PRIORITY_PRIORITY28 (27UL)
#define PLIC_PRIORITY_PRIORITY29 (28UL)
#define PLIC_PRIORITY_PRIORITY30 (29UL)
#define PLIC_PRIORITY_PRIORITY31 (30UL)
#define PLIC_PRIORITY_PRIORITY32 (31UL)
#define PLIC_PRIORITY_PRIORITY33 (32UL)
#define PLIC_PRIORITY_PRIORITY34 (33UL)
#define PLIC_PRIORITY_PRIORITY35 (34UL)
#define PLIC_PRIORITY_PRIORITY36 (35UL)
#define PLIC_PRIORITY_PRIORITY37 (36UL)
#define PLIC_PRIORITY_PRIORITY38 (37UL)
#define PLIC_PRIORITY_PRIORITY39 (38UL)
#define PLIC_PRIORITY_PRIORITY40 (39UL)
#define PLIC_PRIORITY_PRIORITY41 (40UL)
#define PLIC_PRIORITY_PRIORITY42 (41UL)
#define PLIC_PRIORITY_PRIORITY43 (42UL)
#define PLIC_PRIORITY_PRIORITY44 (43UL)
#define PLIC_PRIORITY_PRIORITY45 (44UL)
#define PLIC_PRIORITY_PRIORITY46 (45UL)
#define PLIC_PRIORITY_PRIORITY47 (46UL)
#define PLIC_PRIORITY_PRIORITY48 (47UL)
#define PLIC_PRIORITY_PRIORITY49 (48UL)
#define PLIC_PRIORITY_PRIORITY50 (49UL)
#define PLIC_PRIORITY_PRIORITY51 (50UL)
#define PLIC_PRIORITY_PRIORITY52 (51UL)
#define PLIC_PRIORITY_PRIORITY53 (52UL)
#define PLIC_PRIORITY_PRIORITY54 (53UL)
#define PLIC_PRIORITY_PRIORITY55 (54UL)
#define PLIC_PRIORITY_PRIORITY56 (55UL)
#define PLIC_PRIORITY_PRIORITY57 (56UL)
#define PLIC_PRIORITY_PRIORITY58 (57UL)
#define PLIC_PRIORITY_PRIORITY59 (58UL)
#define PLIC_PRIORITY_PRIORITY60 (59UL)
#define PLIC_PRIORITY_PRIORITY61 (60UL)
#define PLIC_PRIORITY_PRIORITY62 (61UL)
#define PLIC_PRIORITY_PRIORITY63 (62UL)
#define PLIC_PRIORITY_PRIORITY64 (63UL)
#define PLIC_PRIORITY_PRIORITY65 (64UL)
#define PLIC_PRIORITY_PRIORITY66 (65UL)
#define PLIC_PRIORITY_PRIORITY67 (66UL)
#define PLIC_PRIORITY_PRIORITY68 (67UL)
#define PLIC_PRIORITY_PRIORITY69 (68UL)
#define PLIC_PRIORITY_PRIORITY70 (69UL)
#define PLIC_PRIORITY_PRIORITY71 (70UL)
#define PLIC_PRIORITY_PRIORITY72 (71UL)
#define PLIC_PRIORITY_PRIORITY73 (72UL)
#define PLIC_PRIORITY_PRIORITY74 (73UL)
#define PLIC_PRIORITY_PRIORITY75 (74UL)
#define PLIC_PRIORITY_PRIORITY76 (75UL)
#define PLIC_PRIORITY_PRIORITY77 (76UL)
#define PLIC_PRIORITY_PRIORITY78 (77UL)
#define PLIC_PRIORITY_PRIORITY79 (78UL)
#define PLIC_PRIORITY_PRIORITY80 (79UL)
#define PLIC_PRIORITY_PRIORITY81 (80UL)
#define PLIC_PRIORITY_PRIORITY82 (81UL)
#define PLIC_PRIORITY_PRIORITY83 (82UL)
#define PLIC_PRIORITY_PRIORITY84 (83UL)
#define PLIC_PRIORITY_PRIORITY85 (84UL)
#define PLIC_PRIORITY_PRIORITY86 (85UL)
#define PLIC_PRIORITY_PRIORITY87 (86UL)
#define PLIC_PRIORITY_PRIORITY88 (87UL)
#define PLIC_PRIORITY_PRIORITY89 (88UL)
#define PLIC_PRIORITY_PRIORITY90 (89UL)
#define PLIC_PRIORITY_PRIORITY91 (90UL)
#define PLIC_PRIORITY_PRIORITY92 (91UL)
#define PLIC_PRIORITY_PRIORITY93 (92UL)
#define PLIC_PRIORITY_PRIORITY94 (93UL)
#define PLIC_PRIORITY_PRIORITY95 (94UL)
#define PLIC_PRIORITY_PRIORITY96 (95UL)
#define PLIC_PRIORITY_PRIORITY97 (96UL)
#define PLIC_PRIORITY_PRIORITY98 (97UL)
#define PLIC_PRIORITY_PRIORITY99 (98UL)
#define PLIC_PRIORITY_PRIORITY100 (99UL)
#define PLIC_PRIORITY_PRIORITY101 (100UL)
#define PLIC_PRIORITY_PRIORITY102 (101UL)
#define PLIC_PRIORITY_PRIORITY103 (102UL)
#define PLIC_PRIORITY_PRIORITY104 (103UL)
#define PLIC_PRIORITY_PRIORITY105 (104UL)
#define PLIC_PRIORITY_PRIORITY106 (105UL)
#define PLIC_PRIORITY_PRIORITY107 (106UL)
#define PLIC_PRIORITY_PRIORITY108 (107UL)
#define PLIC_PRIORITY_PRIORITY109 (108UL)
#define PLIC_PRIORITY_PRIORITY110 (109UL)
#define PLIC_PRIORITY_PRIORITY111 (110UL)
#define PLIC_PRIORITY_PRIORITY112 (111UL)
#define PLIC_PRIORITY_PRIORITY113 (112UL)
#define PLIC_PRIORITY_PRIORITY114 (113UL)
#define PLIC_PRIORITY_PRIORITY115 (114UL)
#define PLIC_PRIORITY_PRIORITY116 (115UL)
#define PLIC_PRIORITY_PRIORITY117 (116UL)
#define PLIC_PRIORITY_PRIORITY118 (117UL)
#define PLIC_PRIORITY_PRIORITY119 (118UL)
#define PLIC_PRIORITY_PRIORITY120 (119UL)
#define PLIC_PRIORITY_PRIORITY121 (120UL)
#define PLIC_PRIORITY_PRIORITY122 (121UL)
#define PLIC_PRIORITY_PRIORITY123 (122UL)
#define PLIC_PRIORITY_PRIORITY124 (123UL)
#define PLIC_PRIORITY_PRIORITY125 (124UL)
#define PLIC_PRIORITY_PRIORITY126 (125UL)
#define PLIC_PRIORITY_PRIORITY127 (126UL)
/* PENDING register group index macro definition */
#define PLIC_PENDING_PENDING0 (0UL)
#define PLIC_PENDING_PENDING1 (1UL)
#define PLIC_PENDING_PENDING2 (2UL)
#define PLIC_PENDING_PENDING3 (3UL)
/* TRIGGER register group index macro definition */
#define PLIC_TRIGGER_TRIGGER0 (0UL)
#define PLIC_TRIGGER_TRIGGER1 (1UL)
#define PLIC_TRIGGER_TRIGGER2 (2UL)
#define PLIC_TRIGGER_TRIGGER3 (3UL)
/* INTEN register group index macro definition */
#define PLIC_TARGETINT_INTEN_INTEN0 (0UL)
#define PLIC_TARGETINT_INTEN_INTEN1 (1UL)
#define PLIC_TARGETINT_INTEN_INTEN2 (2UL)
#define PLIC_TARGETINT_INTEN_INTEN3 (3UL)
/* TARGETINT register group index macro definition */
#define PLIC_TARGETINT_TARGET0 (0UL)
#define PLIC_TARGETINT_TARGET1 (1UL)
/* TARGETCONFIG register group index macro definition */
#define PLIC_TARGETCONFIG_TARGET0 (0UL)
#define PLIC_TARGETCONFIG_TARGET1 (1UL)
#endif /* HPM_PLIC_H */
|
0e3d56bc846d447d52b6d687f7a6ce6989eafafb
|
2181883c8faac55bfc969a97d22d9b24a3e81ab3
|
/isapi/src/StdAfx.h
|
e0d093dbfb0d84339e2f2cf970955894a0560302
|
[
"PSF-2.0"
] |
permissive
|
mhammond/pywin32
|
574bf121cfeac8c7a9d28f94ee0f2069a425e8ab
|
2a7137f21965013020ef9e4f27565db6dea59003
|
refs/heads/main
| 2023-09-02T13:16:52.307262
| 2023-08-17T19:42:26
| 2023-08-17T19:42:26
| 108,187,130
| 4,757
| 907
| null | 2023-08-23T01:45:49
| 2017-10-24T21:44:27
|
C++
|
UTF-8
|
C
| false
| false
| 2,787
|
h
|
StdAfx.h
|
/*
======================================================================
Copyright 2002-2003 by Blackdog Software Pty Ltd.
All Rights Reserved
Permission to use, copy, modify, and distribute this software and
its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that copyright notice and this permission
notice appear in supporting documentation, and that the name of
Blackdog Software not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.
BLACKDOG SOFTWARE DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
NO EVENT SHALL BLACKDOG SOFTWARE BE LIABLE FOR ANY SPECIAL, INDIRECT OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
======================================================================
*/
#if !defined(AFX_STDAFX_H__E2A54271_C650_437E_999F_A5E3E2F41ACC__INCLUDED_)
#define AFX_STDAFX_H__E2A54271_C650_437E_999F_A5E3E2F41ACC__INCLUDED_
#include "tchar.h"
#include <httpext.h>
#include <httpfilt.h>
#include "Utils.h"
#define PY_SSIZE_T_CLEAN
// windows defines "small" as "char" which breaks Python's accu.h
#undef small
#include "Python.h"
// include structmember here to deal with warnings related to WRITE_RESTRICTED
#ifdef WRITE_RESTRICTED
#undef WRITE_RESTRICTED
#endif
#include "structmember.h"
// avoid anyone accidently using the wrong WRITE_RESTRICTED...
#undef WRITE_RESTRICTED
// ***** py3k support *****
// Note that when built for py3k, 'UNICODE' is defined, which conveniently
// means TCHAR is the same size as the native unicode object in all versions.
// Note however that ISAPI is always an ANSI API - so even when UNICODE is
// defined, most strings passed and received from ISAPI itself remain 'char *'
// in all versions.
// Macros to handle PyObject layout changes in Py3k
#define PYISAPI_OBJECT_HEAD PyVarObject_HEAD_INIT(NULL, 0)
////#define PYISAPI_ATTR_CONVERT PyUnicode_AsUnicode // removed in Py3.12+
// A helper that on py3k takes a str or unicode as input and returns a
// string - exactly how the 's#' PyArg_ParseTuple format string does...
// On py2k accepts str objects only.
const char *PyISAPIString_AsBytes(PyObject *ob, DWORD *psize = NULL);
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_STDAFX_H__E2A54271_C650_437E_999F_A5E3E2F41ACC__INCLUDED)
|
095147ff58d1b863effa8e6ccb51bb11d00c4613
|
79d343002bb63a44f8ab0dbac0c9f4ec54078c3a
|
/lib/libc/include/generic-musl/monetary.h
|
10d8e90ae56942f873f2b0c911a48a851553f3c5
|
[
"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
| 394
|
h
|
monetary.h
|
#ifndef _MONETARY_H
#define _MONETARY_H
#ifdef __cplusplus
extern "C" {
#endif
#include <features.h>
#define __NEED_ssize_t
#define __NEED_size_t
#define __NEED_locale_t
#include <bits/alltypes.h>
ssize_t strfmon(char *__restrict, size_t, const char *__restrict, ...);
ssize_t strfmon_l(char *__restrict, size_t, locale_t, const char *__restrict, ...);
#ifdef __cplusplus
}
#endif
#endif
|
133fc867b21f6db848f3623469449f185a94cc5f
|
cff4428975e403e4ef02d75498b78cd1a610a01a
|
/test/unit/say.c
|
376469b76929aedf471c79e63815d1cd89189954
|
[
"BSD-2-Clause"
] |
permissive
|
tarantool/tarantool
|
c1f252b642d223af62485dc21165c7f7c3354e7e
|
f58cc96f2798ddc5f492223897d0b77e4f902128
|
refs/heads/master
| 2023-09-03T15:16:29.144171
| 2023-08-31T11:39:28
| 2023-09-01T12:39:29
| 911,980
| 3,205
| 490
|
NOASSERTION
| 2023-09-14T17:58:17
| 2010-09-15T07:59:26
|
Lua
|
UTF-8
|
C
| false
| false
| 7,919
|
c
|
say.c
|
#include <string.h>
#include <fiber.h>
#include <memory.h>
#include "unit.h"
#include "say.h"
#include "tt_strerror.h"
#include <pthread.h>
#include <errinj.h>
#include <coio_task.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <fcntl.h>
int
parse_logger_type(const char *input)
{
enum say_logger_type type;
int rc = say_parse_logger_type(&input, &type);
if (rc == 0)
switch (type) {
case SAY_LOGGER_BOOT:
note("type: boot"); break;
case SAY_LOGGER_STDERR:
note("type: stderr"); break;
case SAY_LOGGER_FILE:
note("type: file"); break;
case SAY_LOGGER_PIPE:
note("type: pipe"); break;
case SAY_LOGGER_SYSLOG:
note("type: syslog"); break;
}
note("next: %s", input);
return rc;
}
int
parse_syslog_opts(const char *input)
{
struct say_syslog_opts opts;
if (say_parse_syslog_opts(input, &opts) == -1) {
return -1;
}
if (opts.identity)
note("identity: %s", opts.identity);
if (opts.facility)
note("facility: %i", opts.facility);
say_free_syslog_opts(&opts);
return 0;
}
static int
format_func_custom(struct log *log, char *buf, int len, int level,
const char *module, const char *filename, int line,
const char *error, const char *format, va_list ap)
{
int total = 0;
(void) log;
(void) level;
(void)module;
(void) filename;
(void) line;
(void) error;
SNPRINT(total, snprintf, buf, len, "\"msg\" = \"");
SNPRINT(total, vsnprintf, buf, len, format, ap);
SNPRINT(total, snprintf, buf, len, "\"\n");
return total;
}
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond_sync = PTHREAD_COND_INITIALIZER;
bool is_raised = false;
int created_logs = 0;
const char *tmp_dir;
struct create_log {
struct log logger;
int id;
};
static void *
dummy_log(void *arg)
{
struct create_log *create_log = (struct create_log *) arg;
char tmp_filename[30];
sprintf(tmp_filename, "%s/%i.log", tmp_dir, create_log->id);
tt_pthread_mutex_lock(&mutex);
log_create(&create_log->logger, tmp_filename, false);
/* signal that log is created */
created_logs++;
tt_pthread_cond_signal(&cond_sync);
/* wait until rotate signal is raised */
while (!is_raised)
tt_pthread_cond_wait(&cond, &mutex);
created_logs--;
if (created_logs == 0)
pthread_cond_signal(&cond_sync);
tt_pthread_mutex_unlock(&mutex);
return NULL;
}
static void
test_log_rotate()
{
char template[] = "/tmp/tmpdir.XXXXXX";
tmp_dir = mkdtemp(template);
const int NUMBER_LOGGERS = 10;
struct create_log *loggers = (struct create_log *) calloc(NUMBER_LOGGERS,
sizeof(struct create_log));
if (loggers == NULL) {
return;
}
int running = 0;
for (int i = 0; i < NUMBER_LOGGERS; i++) {
pthread_t thread;
loggers[i].id = i;
if (tt_pthread_create(&thread, NULL, dummy_log,
(void *) &loggers[i]) >= 0)
running++;
}
tt_pthread_mutex_lock(&mutex);
/* wait loggers are created */
while (created_logs < running)
tt_pthread_cond_wait(&cond_sync, &mutex);
tt_pthread_mutex_unlock(&mutex);
say_logrotate(NULL, NULL, 0);
for (int i = 0; i < created_logs; i++) {
log_destroy(&loggers[i].logger);
char tmp_filename[30];
sprintf(tmp_filename, "%s/%i.log", tmp_dir, i);
unlink(tmp_filename);
}
memset(loggers, '#', NUMBER_LOGGERS * sizeof(struct create_log));
free(loggers);
rmdir(tmp_dir);
is_raised = true;
tt_pthread_cond_broadcast(&cond);
tt_pthread_mutex_lock(&mutex);
/* wait threads are finished */
while (created_logs > 0)
tt_pthread_cond_wait(&cond_sync, &mutex);
tt_pthread_mutex_unlock(&mutex);
}
static int
main_f(va_list ap)
{
struct errinj *inj = errinj_by_name("ERRINJ_LOG_ROTATE");
inj->bparam = true;
/* test on log_rotate signal handling */
test_log_rotate();
inj->bparam = false;
ev_break(loop(), EVBREAK_ALL);
return 0;
}
int main()
{
memory_init();
fiber_init(fiber_c_invoke);
say_logger_init("/dev/null", S_INFO, 0, "plain");
plan(36);
#define PARSE_LOGGER_TYPE(input, rc) \
ok(parse_logger_type(input) == rc, "%s", input)
PARSE_LOGGER_TYPE("", 0);
PARSE_LOGGER_TYPE("/dev/null", 0);
PARSE_LOGGER_TYPE("|", 0);
PARSE_LOGGER_TYPE("|/usr/bin/cronolog", 0);
PARSE_LOGGER_TYPE("file:", 0);
PARSE_LOGGER_TYPE("file:instance.log", 0);
PARSE_LOGGER_TYPE("pipe:", 0);
PARSE_LOGGER_TYPE("pipe:gzip > instance.log.gz", 0);
PARSE_LOGGER_TYPE("syslog:", 0);
PARSE_LOGGER_TYPE("syslog:identity=", 0);
PARSE_LOGGER_TYPE("unknown:", -1);
PARSE_LOGGER_TYPE("unknown:example.org", -1);
#define PARSE_SYSLOG_OPTS(input, rc) \
ok(parse_syslog_opts(input) == rc, "%s", input)
PARSE_SYSLOG_OPTS("", 0);
PARSE_SYSLOG_OPTS("identity=tarantool", 0);
PARSE_SYSLOG_OPTS("facility=user", 0);
PARSE_SYSLOG_OPTS("identity=xtarantoolx,facility=local1", 0);
PARSE_SYSLOG_OPTS("identity=xtarantoolx,facility=kern", 0);
PARSE_SYSLOG_OPTS("identity=xtarantoolx,facility=uucp", 0);
PARSE_SYSLOG_OPTS("identity=xtarantoolx,facility=foo", -1);
PARSE_SYSLOG_OPTS("facility=authpriv,identity=bar", 0);
PARSE_SYSLOG_OPTS("invalid=", -1);
PARSE_SYSLOG_OPTS("facility=local1,facility=local2", -1);
PARSE_SYSLOG_OPTS("identity=foo,identity=bar", -1);
char template[] = "/tmp/tmpdir.XXXXXX";
const char *tmp_dir = mkdtemp(template);
if (tmp_dir == NULL) {
diag("unit/say: failed to create temp dir: %s",
tt_strerror(errno));
return check_plan();
}
char tmp_filename[30];
sprintf(tmp_filename, "%s/1.log", tmp_dir);
struct log test_log;
log_create(&test_log, tmp_filename, false);
log_set_format(&test_log, say_format_plain);
log_say(&test_log, 0, NULL, 0, NULL, "hello %s\n", "user");
log_set_format(&test_log, say_format_json);
log_say(&test_log, 0, NULL, 0, NULL, "hello %s", "user");
log_set_format(&test_log, format_func_custom);
log_say(&test_log, 0, NULL, 0, NULL, "hello %s", "user");
FILE* fd = fopen(tmp_filename, "r+");
const size_t len = 4096;
char line[len];
if (fgets(line, len, fd) != NULL) {
ok(strstr(line, "hello user") != NULL, "plain");
fgets(line, len, fd);
}
if (fgets(line, len, fd) != NULL) {
ok(strstr(line, "\"message\": \"hello user\"") != NULL, "json");
}
if (fgets(line, len, fd) != NULL) {
ok(strstr(line, "\"msg\" = \"hello user\"") != NULL, "custom");
}
log_destroy(&test_log);
coio_init();
coio_enable();
struct fiber *test = fiber_new("loggers", main_f);
if (test == NULL) {
diag_log();
return check_plan();
}
fiber_wakeup(test);
ev_run(loop(), 0);
/*
* Ignore possible failure of log_create(). It may fail
* connecting to /dev/log or its analogs. We need only
* the format function here, as we change log.fd to file
* descriptor.
*/
log_create(&test_log, "syslog:identity=tarantool,facility=local0", false);
test_log.fd = fileno(fd);
/*
* redirect stderr to /dev/null in order to filter
* it out from result file.
*/
ok(freopen("/dev/null", "w", stderr) != NULL, "freopen");
ok(strncmp(test_log.syslog_ident, "tarantool", 9) == 0, "parsed identity");
ok(test_log.syslog_facility == SYSLOG_LOCAL0, "parsed facility");
long before = ftell(fd);
ok(before >= 0, "ftell");
ok(log_say(&test_log, 0, NULL, 0, NULL, "hello %s", "user") > 0, "log_say");
ok(fseek(fd, before, SEEK_SET) >= 0, "fseek");
if (fgets(line, len, fd) != NULL) {
ok(strstr(line, "<131>") != NULL, "syslog line");
}
log_destroy(&test_log);
/* Test gh-4450. */
log_create(&test_log, tmp_filename, false);
say_logrotate(NULL, NULL, 0);
coio_shutdown();
log_destroy(&test_log);
const char *level_str = say_log_level_str(S_DEBUG);
ok(strcmp("DEBUG", say_log_level_str(S_DEBUG)) == 0,
"level string is %s", level_str);
level_str = say_log_level_str(-1);
ok(say_log_level_str(-1) == NULL,
"level string is %s", level_str);
level_str = say_log_level_str(1000);
ok(say_log_level_str(-1) == NULL,
"level string is %s", level_str);
fiber_free();
memory_free();
unlink(tmp_filename);
rmdir(tmp_dir);
return check_plan();
}
|
9cfbe5a4fea365718988dbcf1206b9a377f6292f
|
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
|
/mail/xmailwatcher/files/patch-xmailwathcer.c
|
2560c0ff65d9b4449e9682b6ccfc191b2fe31348
|
[
"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
| 299
|
c
|
patch-xmailwathcer.c
|
--- xmailwatcher.c.orig Wed May 30 21:18:27 2007
+++ xmailwatcher.c Wed May 30 21:19:23 2007
@@ -149,7 +149,7 @@
void timedRescan();
void listEvent();
void iconEvent();
-void iconCallback();
+static void iconCallback(Widget w, XtPointer client_data, XtPointer call_data);
static int mapped;
|
fde191369d5d6bb156a418b38c7ffa11fde666ef
|
cdc6c85f66ff27e566aaf8c39b868bda3e80e192
|
/libsrc/unistd/execvp.c
|
aea2b97bfe311884dca0aafdc773970bda612d47
|
[] |
no_license
|
tyfkda/xcc
|
e2deafc3b4f1d163956619742f617b1b1eb81a3b
|
9614ac50d6e813e5b3c2ab76bb3eabad10875f64
|
refs/heads/main
| 2023-08-23T23:48:16.443583
| 2023-08-21T02:58:14
| 2023-08-22T00:41:17
| 166,307,267
| 128
| 9
| null | 2023-07-20T01:09:36
| 2019-01-17T22:38:21
|
C
|
UTF-8
|
C
| false
| false
| 164
|
c
|
execvp.c
|
#if !defined(__WASM)
#include "unistd.h"
extern char **environ;
int execvp(const char *path, char *const args[]) {
return execve(path, args, environ);
}
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.