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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c9a891ee137872bed385c22520a98f701a594c13
|
9ceacf33fd96913cac7ef15492c126d96cae6911
|
/sys/dev/fdt/qcsmem.c
|
2c1e77dd4a3b8806e1dcf48940d430298b9e8f5d
|
[] |
no_license
|
openbsd/src
|
ab97ef834fd2d5a7f6729814665e9782b586c130
|
9e79f3a0ebd11a25b4bff61e900cb6de9e7795e9
|
refs/heads/master
| 2023-09-02T18:54:56.624627
| 2023-09-02T15:16:12
| 2023-09-02T15:16:12
| 66,966,208
| 3,394
| 1,235
| null | 2023-08-08T02:42:25
| 2016-08-30T18:18:25
|
C
|
UTF-8
|
C
| false
| false
| 11,905
|
c
|
qcsmem.c
|
/* $OpenBSD: qcsmem.c,v 1.1 2023/05/19 21:13:49 patrick Exp $ */
/*
* Copyright (c) 2023 Patrick Wildt <patrick@blueri.se>
*
* 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/systm.h>
#include <sys/device.h>
#include <sys/malloc.h>
#include <sys/atomic.h>
#include <machine/bus.h>
#include <machine/fdt.h>
#include <dev/ofw/openfirm.h>
#include <dev/ofw/ofw_misc.h>
#include <dev/ofw/fdt.h>
#define QCSMEM_ITEM_FIXED 8
#define QCSMEM_ITEM_COUNT 512
#define QCSMEM_HOST_COUNT 15
struct qcsmem_proc_comm {
uint32_t command;
uint32_t status;
uint32_t params[2];
};
struct qcsmem_global_entry {
uint32_t allocated;
uint32_t offset;
uint32_t size;
uint32_t aux_base;
#define QCSMEM_GLOBAL_ENTRY_AUX_BASE_MASK 0xfffffffc
};
struct qcsmem_header {
struct qcsmem_proc_comm proc_comm[4];
uint32_t version[32];
#define QCSMEM_HEADER_VERSION_MASTER_SBL_IDX 7
#define QCSMEM_HEADER_VERSION_GLOBAL_HEAP 11
#define QCSMEM_HEADER_VERSION_GLOBAL_PART 12
uint32_t initialized;
uint32_t free_offset;
uint32_t available;
uint32_t reserved;
struct qcsmem_global_entry toc[QCSMEM_ITEM_COUNT];
};
struct qcsmem_ptable_entry {
uint32_t offset;
uint32_t size;
uint32_t flags;
uint16_t host[2];
#define QCSMEM_LOCAL_HOST 0
#define QCSMEM_GLOBAL_HOST 0xfffe
uint32_t cacheline;
uint32_t reserved[7];
};
struct qcsmem_ptable {
uint32_t magic;
#define QCSMEM_PTABLE_MAGIC 0x434f5424
uint32_t version;
#define QCSMEM_PTABLE_VERSION 1
uint32_t num_entries;
uint32_t reserved[5];
struct qcsmem_ptable_entry entry[];
};
struct qcsmem_partition_header {
uint32_t magic;
#define QCSMEM_PART_HDR_MAGIC 0x54525024
uint16_t host[2];
uint32_t size;
uint32_t offset_free_uncached;
uint32_t offset_free_cached;
uint32_t reserved[3];
};
struct qcsmem_partition {
struct qcsmem_partition_header *phdr;
size_t cacheline;
size_t size;
};
struct qcsmem_private_entry {
uint16_t canary;
#define QCSMEM_PRIV_ENTRY_CANARY 0xa5a5
uint16_t item;
uint32_t size;
uint16_t padding_data;
uint16_t padding_hdr;
uint32_t reserved;
};
struct qcsmem_info {
uint32_t magic;
#define QCSMEM_INFO_MAGIC 0x49494953
uint32_t size;
uint32_t base_addr;
uint32_t reserved;
uint32_t num_items;
};
struct qcsmem_softc {
struct device sc_dev;
bus_space_tag_t sc_iot;
bus_space_handle_t sc_ioh;
int sc_node;
bus_addr_t sc_aux_base;
bus_size_t sc_aux_size;
int sc_item_count;
struct qcsmem_partition sc_global_partition;
struct qcsmem_partition sc_partitions[QCSMEM_HOST_COUNT];
};
struct qcsmem_softc *qcsmem_sc;
int qcsmem_match(struct device *, void *, void *);
void qcsmem_attach(struct device *, struct device *, void *);
const struct cfattach qcsmem_ca = {
sizeof (struct qcsmem_softc), qcsmem_match, qcsmem_attach
};
struct cfdriver qcsmem_cd = {
NULL, "qcsmem", DV_DULL
};
int
qcsmem_match(struct device *parent, void *match, void *aux)
{
struct fdt_attach_args *faa = aux;
return OF_is_compatible(faa->fa_node, "qcom,smem");
}
void
qcsmem_attach(struct device *parent, struct device *self, void *aux)
{
struct qcsmem_softc *sc = (struct qcsmem_softc *)self;
struct fdt_attach_args *faa = aux;
struct qcsmem_header *header;
struct qcsmem_ptable *ptable;
struct qcsmem_ptable_entry *pte;
struct qcsmem_info *info;
struct qcsmem_partition *part;
struct qcsmem_partition_header *phdr;
uint32_t version;
int i;
if (faa->fa_nreg < 1) {
printf(": no registers\n");
return;
}
sc->sc_node = faa->fa_node;
sc->sc_iot = faa->fa_iot;
if (bus_space_map(sc->sc_iot, faa->fa_reg[0].addr,
faa->fa_reg[0].size, 0, &sc->sc_ioh)) {
printf(": can't map registers\n");
return;
}
sc->sc_aux_base = faa->fa_reg[0].addr;
sc->sc_aux_size = faa->fa_reg[0].addr;
ptable = bus_space_vaddr(sc->sc_iot, sc->sc_ioh) +
faa->fa_reg[0].size - PAGE_SIZE;
if (ptable->magic != QCSMEM_PTABLE_MAGIC ||
ptable->version != QCSMEM_PTABLE_VERSION) {
printf(": unsupported ptable 0x%x/0x%x\n",
ptable->magic, ptable->version);
bus_space_unmap(sc->sc_iot, sc->sc_ioh,
faa->fa_reg[0].size);
return;
}
header = bus_space_vaddr(sc->sc_iot, sc->sc_ioh);
version = header->version[QCSMEM_HEADER_VERSION_MASTER_SBL_IDX] >> 16;
if (version != QCSMEM_HEADER_VERSION_GLOBAL_PART) {
printf(": unsupported header 0x%x\n", version);
return;
}
for (i = 0; i < ptable->num_entries; i++) {
pte = &ptable->entry[i];
if (!pte->offset || !pte->size)
continue;
if (pte->host[0] == QCSMEM_GLOBAL_HOST &&
pte->host[1] == QCSMEM_GLOBAL_HOST)
part = &sc->sc_global_partition;
else if (pte->host[0] == QCSMEM_LOCAL_HOST &&
pte->host[1] < QCSMEM_HOST_COUNT)
part = &sc->sc_partitions[pte->host[1]];
else if (pte->host[1] == QCSMEM_LOCAL_HOST &&
pte->host[0] < QCSMEM_HOST_COUNT)
part = &sc->sc_partitions[pte->host[0]];
else
continue;
if (part->phdr != NULL)
continue;
phdr = bus_space_vaddr(sc->sc_iot, sc->sc_ioh) +
pte->offset;
if (phdr->magic != QCSMEM_PART_HDR_MAGIC) {
printf(": unsupported partition 0x%x\n",
phdr->magic);
return;
}
if (pte->host[0] != phdr->host[0] ||
pte->host[1] != phdr->host[1]) {
printf(": bad hosts 0x%x/0x%x+0x%x/0x%x\n",
pte->host[0], phdr->host[0],
pte->host[1], phdr->host[1]);
return;
}
if (pte->size != phdr->size) {
printf(": bad size 0x%x/0x%x\n",
pte->size, phdr->size);
return;
}
if (phdr->offset_free_uncached > phdr->size) {
printf(": bad size 0x%x > 0x%x\n",
phdr->offset_free_uncached, phdr->size);
return;
}
part->phdr = phdr;
part->size = pte->size;
part->cacheline = pte->cacheline;
}
if (sc->sc_global_partition.phdr == NULL) {
printf(": could not find global partition\n");
return;
}
sc->sc_item_count = QCSMEM_ITEM_COUNT;
info = (struct qcsmem_info *)&ptable->entry[ptable->num_entries];
if (info->magic == QCSMEM_INFO_MAGIC)
sc->sc_item_count = info->num_items;
printf("\n");
qcsmem_sc = sc;
}
int
qcsmem_alloc_private(struct qcsmem_softc *sc, struct qcsmem_partition *part,
int item, int size)
{
struct qcsmem_private_entry *entry, *last;
struct qcsmem_partition_header *phdr = part->phdr;
entry = (void *)&phdr[1];
last = (void *)phdr + phdr->offset_free_uncached;
if ((void *)last > (void *)phdr + part->size)
return EINVAL;
while (entry < last) {
if (entry->canary != QCSMEM_PRIV_ENTRY_CANARY) {
printf("%s: invalid canary\n", sc->sc_dev.dv_xname);
return EINVAL;
}
if (entry->item == item)
return 0;
entry = (void *)&entry[1] + entry->padding_hdr +
entry->size;
}
if ((void *)entry > (void *)phdr + part->size)
return EINVAL;
if ((void *)&entry[1] + roundup(size, 8) >
(void *)phdr + phdr->offset_free_cached)
return EINVAL;
entry->canary = QCSMEM_PRIV_ENTRY_CANARY;
entry->item = item;
entry->size = roundup(size, 8);
entry->padding_data = entry->size - size;
entry->padding_hdr = 0;
membar_producer();
phdr->offset_free_uncached += sizeof(*entry) + entry->size;
return 0;
}
int
qcsmem_alloc_global(struct qcsmem_softc *sc, int item, int size)
{
struct qcsmem_header *header;
struct qcsmem_global_entry *entry;
header = bus_space_vaddr(sc->sc_iot, sc->sc_ioh);
entry = &header->toc[item];
if (entry->allocated)
return 0;
size = roundup(size, 8);
if (size > header->available)
return EINVAL;
entry->offset = header->free_offset;
entry->size = size;
membar_producer();
entry->allocated = 1;
header->free_offset += size;
header->available -= size;
return 0;
}
int
qcsmem_alloc(int host, int item, int size)
{
struct qcsmem_softc *sc = qcsmem_sc;
struct qcsmem_partition *part;
int ret;
if (sc == NULL)
return ENXIO;
if (item < QCSMEM_ITEM_FIXED)
return EPERM;
if (item >= sc->sc_item_count)
return ENXIO;
ret = hwlock_lock_idx_timeout(sc->sc_node, 0, 1000);
if (ret)
return ret;
if (host < QCSMEM_HOST_COUNT &&
sc->sc_partitions[host].phdr != NULL) {
part = &sc->sc_partitions[host];
ret = qcsmem_alloc_private(sc, part, item, size);
} else if (sc->sc_global_partition.phdr != NULL) {
part = &sc->sc_global_partition;
ret = qcsmem_alloc_private(sc, part, item, size);
} else {
ret = qcsmem_alloc_global(sc, item, size);
}
hwlock_unlock_idx(sc->sc_node, 0);
return ret;
}
void *
qcsmem_get_private(struct qcsmem_softc *sc, struct qcsmem_partition *part,
int item, int *size)
{
struct qcsmem_private_entry *entry, *last;
struct qcsmem_partition_header *phdr = part->phdr;
entry = (void *)&phdr[1];
last = (void *)phdr + phdr->offset_free_uncached;
while (entry < last) {
if (entry->canary != QCSMEM_PRIV_ENTRY_CANARY) {
printf("%s: invalid canary\n", sc->sc_dev.dv_xname);
return NULL;
}
if (entry->item == item) {
if (size != NULL) {
if (entry->size > part->size ||
entry->padding_data > entry->size)
return NULL;
*size = entry->size - entry->padding_data;
}
return (void *)&entry[1] + entry->padding_hdr;
}
entry = (void *)&entry[1] + entry->padding_hdr +
entry->size;
}
if ((void *)entry > (void *)phdr + part->size)
return NULL;
entry = (void *)phdr + phdr->size -
roundup(sizeof(*entry), part->cacheline);
last = (void *)phdr + phdr->offset_free_cached;
if ((void *)entry < (void *)phdr ||
(void *)last > (void *)phdr + part->size)
return NULL;
while (entry > last) {
if (entry->canary != QCSMEM_PRIV_ENTRY_CANARY) {
printf("%s: invalid canary\n", sc->sc_dev.dv_xname);
return NULL;
}
if (entry->item == item) {
if (size != NULL) {
if (entry->size > part->size ||
entry->padding_data > entry->size)
return NULL;
*size = entry->size - entry->padding_data;
}
return (void *)entry - entry->size;
}
entry = (void *)entry - entry->size -
roundup(sizeof(*entry), part->cacheline);
}
if ((void *)entry < (void *)phdr)
return NULL;
return NULL;
}
void *
qcsmem_get_global(struct qcsmem_softc *sc, int item, int *size)
{
struct qcsmem_header *header;
struct qcsmem_global_entry *entry;
uint32_t aux_base;
header = bus_space_vaddr(sc->sc_iot, sc->sc_ioh);
entry = &header->toc[item];
if (!entry->allocated)
return NULL;
aux_base = entry->aux_base & QCSMEM_GLOBAL_ENTRY_AUX_BASE_MASK;
if (aux_base != 0 && aux_base != sc->sc_aux_base)
return NULL;
if (entry->size + entry->offset > sc->sc_aux_size)
return NULL;
if (size != NULL)
*size = entry->size;
return bus_space_vaddr(sc->sc_iot, sc->sc_ioh) + entry->offset;
}
void *
qcsmem_get(int host, int item, int *size)
{
struct qcsmem_softc *sc = qcsmem_sc;
struct qcsmem_partition *part;
void *p = NULL;
int ret;
if (sc == NULL)
return NULL;
if (item >= sc->sc_item_count)
return NULL;
ret = hwlock_lock_idx_timeout(sc->sc_node, 0, 1000);
if (ret)
return NULL;
if (host < QCSMEM_HOST_COUNT &&
sc->sc_partitions[host].phdr != NULL) {
part = &sc->sc_partitions[host];
p = qcsmem_get_private(sc, part, item, size);
} else if (sc->sc_global_partition.phdr != NULL) {
part = &sc->sc_global_partition;
p = qcsmem_get_private(sc, part, item, size);
} else {
p = qcsmem_get_global(sc, item, size);
}
hwlock_unlock_idx(sc->sc_node, 0);
return p;
}
|
44c6bbad719bed3605f4081dfdd528442681b14e
|
300f69741119d3c51c3182d639b0f32b53769baa
|
/src/include/souffle/utility/General.h
|
f3d62f25ca486c1a1d503bd1c6e6df3c5e66eac7
|
[
"UPL-1.0"
] |
permissive
|
souffle-lang/souffle
|
a75aade06ca36beaa0e8defdef16959d460e0920
|
63d6684fe907e8c141d4ffa0e73aefcc857dd83f
|
refs/heads/master
| 2023-08-20T16:30:22.212802
| 2023-08-09T07:29:50
| 2023-08-09T07:29:50
| 53,711,734
| 766
| 213
|
UPL-1.0
| 2023-08-09T07:29:51
| 2016-03-12T03:39:22
|
C++
|
UTF-8
|
C
| false
| false
| 981
|
h
|
General.h
|
/*
* Souffle - A Datalog Compiler
* Copyright (c) 2021, The Souffle Developers. All rights reserved
* Licensed under the Universal Permissive License v 1.0 as shown at:
* - https://opensource.org/licenses/UPL
* - <souffle root>/licenses/SOUFFLE-UPL.txt
*/
/************************************************************************
*
* @file General.h
*
* @brief Lightweight / cheap header for misc utilities.
*
* Misc utilities that require non-trivial headers should go in `MiscUtil.h`
*
***********************************************************************/
#if defined(_MSC_VER)
#define SOUFFLE_ALWAYS_INLINE /* TODO: MSVC equiv */
#else
// clang / gcc recognize this attribute
// NB: GCC will only inline when optimisation is on, and will warn about it.
// Adding `inline` (even though the KW nominally has nothing to do with
// inlining) will force it to inline in all cases. Lovely.
#define SOUFFLE_ALWAYS_INLINE [[gnu::always_inline]] inline
#endif
|
86a93d566a349fce1e660c8567bb9d1026788ed1
|
03f06d028eae3a58ee1f2468f80046b5c85e0e66
|
/gloss-sdl/src/main.c
|
88f5bba7943b435fc5746e3d4af982a27270c8bd
|
[] |
no_license
|
benl23x5/gloss
|
23a9bcd6b6daf4c3cde92d42a880eeba9369fe83
|
af1301a32f311aae5dc64035dfbcf15006012788
|
refs/heads/master
| 2023-09-02T21:12:40.389910
| 2022-03-20T08:45:38
| 2022-03-20T08:45:38
| 14,791,503
| 366
| 99
| null | 2023-01-15T14:19:28
| 2013-11-29T02:53:53
|
Haskell
|
UTF-8
|
C
| false
| false
| 3,558
|
c
|
main.c
|
#include <assert.h>
#include <SDL2/SDL.h>
#include <sys/time.h>
#include "main.h"
bool debug_init = false;
bool debug_events = false;
SDL_Window* state_window = 0;
SDL_Renderer* state_renderer = 0;
SDL_Texture* state_texture = 0;
SDL_Surface* state_surface = 0;
TTF_Font* state_font_DejaVuSans = 0;
TTF_Font* state_font_DejaVuSansMono = 0;
int main(int argc, char** argv)
{
size_t winSizeX = 500;
size_t winSizeY = 500;
// ------------------------------------------------
// Initialize SDL and open the main window.
size_t bufSizeX = 0;
size_t bufSizeY = 0;
gloss_init
( winSizeX, winSizeY
, &bufSizeX, &bufSizeY);
// ------------------------------------------------
// The main drawing loop.
// Event counter.
int iEvent = 0;
while (1) {
SDL_Event event;
SDL_WaitEvent(&event);
iEvent++;
switch (event.type)
{ case SDL_QUIT:
goto quit;
case SDL_MOUSEMOTION:
// printf(" motion\n");
continue;
case SDL_WINDOWEVENT:
switch (event.window.event)
{ case SDL_WINDOWEVENT_SHOWN:
if (debug_events)
printf(" %6d window shown\n", iEvent);
break;
default:
if (debug_events)
printf(" %6d window unhandled\n", iEvent);
break;
}
break;
default:
if (debug_events)
printf(" %6d unhandled\n", iEvent);
break;
}
// Lock texture while we're writing to it.
SDL_LockTexture
( state_texture, 0
, &state_surface->pixels
, &state_surface->pitch);
double time
= gloss_render
( bufSizeX, bufSizeY
, state_surface->pixels
, state_surface->pitch);
// Unlock texture now that we've finished writing.
SDL_UnlockTexture (state_texture);
// Write the frame creation time to the buffer.
char str[256];
snprintf(str, 256, "time %2.6f", time);
SDL_Color color = { 0xa0, 0xa0, 0xa0 };
SDL_Surface *surface_text
= TTF_RenderUTF8_Blended
( state_font_DejaVuSansMono
, str, color);
assert(surface_text != 0);
SDL_BlitSurface(surface_text, 0, state_surface, 0);
SDL_FreeSurface(surface_text);
// Copy the texture to the display.
SDL_RenderClear (state_renderer);
SDL_RenderCopy (state_renderer, state_texture, 0, 0);
SDL_RenderPresent (state_renderer);
}
quit:
SDL_DestroyRenderer(state_renderer);
SDL_Quit();
return 0;
}
|
1884703c9909114559accd5df82c1e140865d55f
|
aec185afb47e7b20615e5d9d872f3912137528f1
|
/dssl/session.h
|
6866231af17f5dda71dd19474158733807accafa
|
[] |
no_license
|
voipmonitor/sniffer
|
f5e15e70526c1fabe48d385fe5ec917b9eada62b
|
162d45491d2b110bdbadfc8a8ac6c44aa44493f0
|
refs/heads/master
| 2023-08-19T05:23:19.837497
| 2023-06-22T15:02:07
| 2023-06-22T15:02:07
| 18,056,680
| 204
| 99
| null | 2022-09-17T02:23:50
| 2014-03-24T08:57:35
|
C++
|
UTF-8
|
C
| false
| false
| 3,462
|
h
|
session.h
|
/*
** This file is a part of DSSL library.
**
** Copyright (C) 2005-2009, Atomic Labs, Inc.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
**
*/
#ifndef __DSSL_SESSION_H__
#define __DSSL_SESSION_H__
#include "dssl_defs.h"
#include "stream.h"
#ifdef __cplusplus
extern "C" {
#endif
/* TCP Session object */
struct _TcpSession
{
/* Session type - TCP/SSL/Null */
NM_SessionType type;
/* session TCP stream objects */
TcpStream clientStream;
TcpStream serverStream;
/* next session in chain (used in session hash table)*/
struct _TcpSession* next;
/* session closure flag */
int closing;
/* callback routines for data and error processing */
DataCallbackProc data_callback;
ErrorCallbackProc error_callback;
EventCallbackProc event_callback;
void* user_data;
/* current packet timestamp (taken from the packet's header) */
struct timeval packet_time;
/* last session activity time */
time_t last_update_time;
/* reassembled packet callback */
int (*OnNewPacket)( struct _TcpStream* stream, DSSL_Pkt* pkt );
/* corresponding SSL session struct (SSL session type only) */
struct DSSL_Session_* ssl_session;
/* parent capture environment */
CapEnv* env;
/* missing packets handling */
int missing_packet_timeout; /**/
uint32_t missing_packet_count;
MissingPacketCallbackProc missing_callback;
/* packet callback */
PacketCallbackProc packet_callback;
};
/* formats an ip:port parameters as a string into buff */
void AddressToString( uint32_t ip, uint16_t port, char* buff );
/* formats the session as a "ip:port<->ip:port" string */
const char* SessionToString( TcpSession* sess, char* buff );
/* Init/Free session */
int SessionInit( CapEnv* env, TcpSession* s, DSSL_Pkt* pkt, NM_SessionType s_type );
void SessionFree( TcpSession* s );
NM_PacketDir SessionGetPacketDirection(const TcpSession* sess, const DSSL_Pkt* pkt );
/* packet processing entry point */
void SessionProcessPacket( struct CapEnv_* env, DSSL_Pkt* pkt );
/* updates the last activity time (set it to current time) */
void TouchSession( TcpSession* s );
/*Get/Set session callbacks, user data */
void SessionSetCallback( TcpSession* sess, DataCallbackProc data_callback,
ErrorCallbackProc error_callback, PacketCallbackProc packet_callback, void* user_data );
void SessionSetMissingPacketCallback( TcpSession* sess, MissingPacketCallbackProc missing_callback,
int missing_packet_count, int timeout_sec );
void SessionSetEventCallback( TcpSession* sess, EventCallbackProc event_callback );
void SessionSetUserData( TcpSession* sess, void* data );
void* SessionGetUserData( const TcpSession* sess );
/* */
void SessionFlushPacketQueue( TcpSession* sess );
int IsNewTcpSessionPacket( const DSSL_Pkt* pkt );
#ifdef __cplusplus
}
#endif
#endif
|
cdd9ead954990d9b16e4d3ef323791276e7b70f5
|
7c857119fe1505b1d80d6e62969661c06dc1a2f4
|
/MdeModulePkg/Universal/PlatformDriOverrideDxe/PlatDriOverrideLib.c
|
dd66e64c1a44c8e082a65b76044a94a4e6751a02
|
[
"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
| 69,609
|
c
|
PlatDriOverrideLib.c
|
/** @file
Implementation of the shared functions to do the platform driver vverride mapping.
Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include "InternalPlatDriOverrideDxe.h"
#define PLATFORM_OVERRIDE_ITEM_SIGNATURE SIGNATURE_32('p','d','o','i')
typedef struct _PLATFORM_OVERRIDE_ITEM {
UINTN Signature;
LIST_ENTRY Link;
UINT32 DriverInfoNum;
EFI_DEVICE_PATH_PROTOCOL *ControllerDevicePath;
///
/// List of DRIVER_IMAGE_INFO
///
LIST_ENTRY DriverInfoList;
EFI_HANDLE LastReturnedImageHandle;
} PLATFORM_OVERRIDE_ITEM;
#define DRIVER_IMAGE_INFO_SIGNATURE SIGNATURE_32('p','d','i','i')
typedef struct _DRIVER_IMAGE_INFO {
UINTN Signature;
LIST_ENTRY Link;
EFI_HANDLE ImageHandle;
EFI_DEVICE_PATH_PROTOCOL *DriverImagePath;
BOOLEAN UnLoadable;
BOOLEAN UnStartable;
} DRIVER_IMAGE_INFO;
#define DEVICE_PATH_STACK_ITEM_SIGNATURE SIGNATURE_32('d','p','s','i')
typedef struct _DEVICE_PATH_STACK_ITEM{
UINTN Signature;
LIST_ENTRY Link;
EFI_DEVICE_PATH_PROTOCOL *DevicePath;
} DEVICE_PATH_STACK_ITEM;
LIST_ENTRY mDevicePathStack = INITIALIZE_LIST_HEAD_VARIABLE (mDevicePathStack);
/**
Push a controller device path into a globle device path list.
@param DevicePath The controller device path to push into stack
@retval EFI_SUCCESS Device path successfully pushed into the stack.
**/
EFI_STATUS
EFIAPI
PushDevPathStack (
IN EFI_DEVICE_PATH_PROTOCOL *DevicePath
)
{
DEVICE_PATH_STACK_ITEM *DevicePathStackItem;
DevicePathStackItem = AllocateZeroPool(sizeof (DEVICE_PATH_STACK_ITEM));
ASSERT (DevicePathStackItem != NULL);
DevicePathStackItem->Signature = DEVICE_PATH_STACK_ITEM_SIGNATURE;
DevicePathStackItem->DevicePath = DuplicateDevicePath (DevicePath);
InsertTailList (&mDevicePathStack, &DevicePathStackItem->Link);
return EFI_SUCCESS;
}
/**
Pop a controller device path from a globle device path list
@param DevicePath The controller device path popped from stack
@retval EFI_SUCCESS Controller device path successfully popped.
@retval EFI_NOT_FOUND Stack is empty.
**/
EFI_STATUS
EFIAPI
PopDevPathStack (
OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath
)
{
DEVICE_PATH_STACK_ITEM *DevicePathStackItem;
LIST_ENTRY *ItemListIndex;
ItemListIndex = mDevicePathStack.BackLink;
//
// Check if the stack is empty
//
if (ItemListIndex != &mDevicePathStack){
DevicePathStackItem = CR(ItemListIndex, DEVICE_PATH_STACK_ITEM, Link, DEVICE_PATH_STACK_ITEM_SIGNATURE);
if (DevicePath != NULL) {
*DevicePath = DuplicateDevicePath (DevicePathStackItem->DevicePath);
}
FreePool(DevicePathStackItem->DevicePath);
RemoveEntryList (&DevicePathStackItem->Link);
FreePool(DevicePathStackItem);
return EFI_SUCCESS;
}
return EFI_NOT_FOUND;
}
/**
Check whether a controller device path is in a globle device path list
@param DevicePath The controller device path to check
@retval TRUE DevicePath exists in the stack.
@retval FALSE DevicePath does not exist in the stack.
**/
BOOLEAN
EFIAPI
CheckExistInStack (
IN EFI_DEVICE_PATH_PROTOCOL *DevicePath
)
{
DEVICE_PATH_STACK_ITEM *DevicePathStackItem;
LIST_ENTRY *ItemListIndex;
UINTN DevicePathSize;
ItemListIndex = mDevicePathStack.BackLink;
while (ItemListIndex != &mDevicePathStack){
DevicePathStackItem = CR(ItemListIndex, DEVICE_PATH_STACK_ITEM, Link, DEVICE_PATH_STACK_ITEM_SIGNATURE);
DevicePathSize = GetDevicePathSize (DevicePath);
if (DevicePathSize == GetDevicePathSize (DevicePathStackItem->DevicePath)) {
if (CompareMem (DevicePath, DevicePathStackItem->DevicePath, DevicePathSize) == 0) {
return TRUE;
}
}
ItemListIndex = ItemListIndex->BackLink;
}
return FALSE;
}
/**
Update the FV file device path if it is not valid.
According to a file GUID, check a Fv file device path is valid. If it is invalid,
try to return the valid device path.
FV address maybe changes for memory layout adjust from time to time, use this function
could promise the Fv file device path is right.
@param DevicePath On input, the FV file device path to check
On output, the updated valid FV file device path
@param FileGuid The FV file GUID
@param CallerImageHandle Image handle of the caller
@retval EFI_INVALID_PARAMETER the input DevicePath or FileGuid is invalid
parameter
@retval EFI_UNSUPPORTED the input DevicePath does not contain FV file
GUID at all
@retval EFI_ALREADY_STARTED the input DevicePath has pointed to FV file, it
is valid
@retval EFI_SUCCESS Successfully updated the invalid DevicePath,
and return the updated device path in DevicePath
**/
EFI_STATUS
EFIAPI
UpdateFvFileDevicePath (
IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath,
IN EFI_GUID *FileGuid,
IN EFI_HANDLE CallerImageHandle
)
{
EFI_DEVICE_PATH_PROTOCOL *TempDevicePath;
EFI_DEVICE_PATH_PROTOCOL *LastDeviceNode;
EFI_STATUS Status;
EFI_GUID *GuidPoint;
UINTN Index;
UINTN FvHandleCount;
EFI_HANDLE *FvHandleBuffer;
EFI_FV_FILETYPE Type;
UINTN Size;
EFI_FV_FILE_ATTRIBUTES Attributes;
UINT32 AuthenticationStatus;
BOOLEAN FindFvFile;
EFI_LOADED_IMAGE_PROTOCOL *LoadedImage;
EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv;
MEDIA_FW_VOL_FILEPATH_DEVICE_PATH FvFileNode;
EFI_HANDLE FoundFvHandle;
EFI_DEVICE_PATH_PROTOCOL *NewDevicePath;
BOOLEAN HasFvNode;
if (DevicePath == NULL) {
return EFI_INVALID_PARAMETER;
}
if (*DevicePath == NULL) {
return EFI_INVALID_PARAMETER;
}
//
// Check whether the device path points to the default the input FV file
//
TempDevicePath = *DevicePath;
LastDeviceNode = TempDevicePath;
while (!IsDevicePathEnd (TempDevicePath)) {
LastDeviceNode = TempDevicePath;
TempDevicePath = NextDevicePathNode (TempDevicePath);
}
GuidPoint = EfiGetNameGuidFromFwVolDevicePathNode ((MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *) LastDeviceNode);
if (GuidPoint == NULL) {
//
// If this option does not point to a FV file, just return EFI_UNSUPPORTED.
//
return EFI_UNSUPPORTED;
}
if (FileGuid != NULL) {
if (!CompareGuid (GuidPoint, FileGuid)) {
//
// If the FV file is not the input file GUID, just return EFI_UNSUPPORTED
//
return EFI_UNSUPPORTED;
}
} else {
FileGuid = GuidPoint;
}
//
// Check to see if the device path contains memory map node
//
TempDevicePath = *DevicePath;
HasFvNode = FALSE;
while (!IsDevicePathEnd (TempDevicePath)) {
//
// Use old Device Path
//
if (DevicePathType (TempDevicePath) == HARDWARE_DEVICE_PATH &&
DevicePathSubType (TempDevicePath) == HW_MEMMAP_DP) {
HasFvNode = TRUE;
break;
}
TempDevicePath = NextDevicePathNode (TempDevicePath);
}
if (!HasFvNode) {
return EFI_UNSUPPORTED;
}
//
// Check whether the input Fv file device path is valid
//
TempDevicePath = *DevicePath;
FoundFvHandle = NULL;
Status = gBS->LocateDevicePath (
&gEfiFirmwareVolume2ProtocolGuid,
&TempDevicePath,
&FoundFvHandle
);
if (!EFI_ERROR(Status)) {
Status = gBS->HandleProtocol (
FoundFvHandle,
&gEfiFirmwareVolume2ProtocolGuid,
(VOID **) &Fv
);
if (!EFI_ERROR(Status)) {
//
// Set FV ReadFile Buffer as NULL, only need to check whether input Fv file exist there
//
Status = Fv->ReadFile (
Fv,
FileGuid,
NULL,
&Size,
&Type,
&Attributes,
&AuthenticationStatus
);
if (!EFI_ERROR(Status)) {
return EFI_ALREADY_STARTED;
}
}
}
//
// Look for the input wanted FV file in current FV
// First, try to look for in Caller own FV. Caller and input wanted FV file usually are in the same FV
//
FindFvFile = FALSE;
FoundFvHandle = NULL;
Status = gBS->HandleProtocol (
CallerImageHandle,
&gEfiLoadedImageProtocolGuid,
(VOID **) &LoadedImage
);
if (!EFI_ERROR(Status)) {
Status = gBS->HandleProtocol (
LoadedImage->DeviceHandle,
&gEfiFirmwareVolume2ProtocolGuid,
(VOID **) &Fv
);
if (!EFI_ERROR(Status)) {
Status = Fv->ReadFile (
Fv,
FileGuid,
NULL,
&Size,
&Type,
&Attributes,
&AuthenticationStatus
);
if (!EFI_ERROR(Status)) {
FindFvFile = TRUE;
FoundFvHandle = LoadedImage->DeviceHandle;
}
}
}
//
// Second, if fail to find, try to enumerate all FV
//
if (!FindFvFile) {
gBS->LocateHandleBuffer (
ByProtocol,
&gEfiFirmwareVolume2ProtocolGuid,
NULL,
&FvHandleCount,
&FvHandleBuffer
);
for (Index = 0; Index < FvHandleCount; Index++) {
gBS->HandleProtocol (
FvHandleBuffer[Index],
&gEfiFirmwareVolume2ProtocolGuid,
(VOID **) &Fv
);
Status = Fv->ReadFile (
Fv,
FileGuid,
NULL,
&Size,
&Type,
&Attributes,
&AuthenticationStatus
);
if (EFI_ERROR(Status)) {
//
// Skip if input Fv file not in the FV
//
continue;
}
FindFvFile = TRUE;
FoundFvHandle = FvHandleBuffer[Index];
break;
}
}
if (FindFvFile) {
//
// Build the shell device path
//
NewDevicePath = DevicePathFromHandle (FoundFvHandle);
EfiInitializeFwVolDevicepathNode (&FvFileNode, FileGuid);
NewDevicePath = AppendDevicePathNode (NewDevicePath, (EFI_DEVICE_PATH_PROTOCOL *) &FvFileNode);
*DevicePath = NewDevicePath;
return EFI_SUCCESS;
}
return EFI_NOT_FOUND;
}
/**
Gets the data and size of a variable.
Read the EFI variable (VendorGuid/Name) and return a dynamically allocated
buffer, and the size of the buffer. If failure return NULL.
@param Name String part of EFI variable name
@param VendorGuid GUID part of EFI variable name
@param VariableSize Returns the size of the EFI variable that was
read
@return Dynamically allocated memory that contains a copy of the EFI variable.
Caller is responsible freeing the buffer.
@retval NULL Variable was not read
**/
VOID *
EFIAPI
GetVariableAndSize (
IN CHAR16 *Name,
IN EFI_GUID *VendorGuid,
OUT UINTN *VariableSize
)
{
EFI_STATUS Status;
UINTN BufferSize;
VOID *Buffer;
Buffer = NULL;
//
// Pass in a zero size buffer to find the required buffer size.
//
BufferSize = 0;
Status = gRT->GetVariable (Name, VendorGuid, NULL, &BufferSize, Buffer);
if (Status == EFI_BUFFER_TOO_SMALL) {
//
// Allocate the buffer to return
//
Buffer = AllocateZeroPool(BufferSize);
if (Buffer == NULL) {
return NULL;
}
//
// Read variable into the allocated buffer.
//
Status = gRT->GetVariable (Name, VendorGuid, NULL, &BufferSize, Buffer);
if (EFI_ERROR(Status)) {
BufferSize = 0;
}
}
*VariableSize = BufferSize;
return Buffer;
}
/**
Connect to the handle to a device on the device path.
This function will create all handles associate with every device
path node. If the handle associate with one device path node can not
be created success, then still give one chance to do the dispatch,
which load the missing drivers if possible.
@param DevicePathToConnect The device path which will be connected, it can
be a multi-instance device path
@retval EFI_SUCCESS All handles associate with every device path
node have been created
@retval EFI_OUT_OF_RESOURCES There is no resource to create new handles
@retval EFI_NOT_FOUND Create the handle associate with one device
path node failed
**/
EFI_STATUS
EFIAPI
ConnectDevicePath (
IN EFI_DEVICE_PATH_PROTOCOL *DevicePathToConnect
)
{
EFI_STATUS Status;
EFI_DEVICE_PATH_PROTOCOL *DevicePath;
EFI_DEVICE_PATH_PROTOCOL *CopyOfDevicePath;
EFI_DEVICE_PATH_PROTOCOL *Instance;
EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath;
EFI_DEVICE_PATH_PROTOCOL *Next;
EFI_HANDLE Handle;
EFI_HANDLE PreviousHandle;
UINTN Size;
if (DevicePathToConnect == NULL) {
return EFI_SUCCESS;
}
DevicePath = DuplicateDevicePath (DevicePathToConnect);
CopyOfDevicePath = DevicePath;
if (DevicePath == NULL) {
return EFI_OUT_OF_RESOURCES;
}
do {
//
// The outer loop handles multi instance device paths.
// Only console variables contain multiple instance device paths.
//
// After this call DevicePath points to the next Instance
//
Instance = GetNextDevicePathInstance (&DevicePath, &Size);
ASSERT (Instance != NULL);
Next = Instance;
while (!IsDevicePathEndType (Next)) {
Next = NextDevicePathNode (Next);
}
SetDevicePathEndNode (Next);
//
// Start the real work of connect with RemainingDevicePath
//
PreviousHandle = NULL;
do {
//
// Find the handle that best matches the Device Path. If it is only a
// partial match the remaining part of the device path is returned in
// RemainingDevicePath.
//
RemainingDevicePath = Instance;
Status = gBS->LocateDevicePath (&gEfiDevicePathProtocolGuid, &RemainingDevicePath, &Handle);
if (!EFI_ERROR(Status)) {
if (Handle == PreviousHandle) {
//
// If no forward progress is made try invoking the Dispatcher.
// A new FV may have been added to the system an new drivers
// may now be found.
// Status == EFI_SUCCESS means a driver was dispatched
// Status == EFI_NOT_FOUND means no new drivers were dispatched
//
Status = gDS->Dispatch ();
}
if (!EFI_ERROR(Status)) {
PreviousHandle = Handle;
//
// Connect all drivers that apply to Handle and RemainingDevicePath,
// the Recursive flag is FALSE so only one level will be expanded.
//
// Do not check the connect status here, if the connect controller fail,
// then still give the chance to do dispatch, because partial
// RemainingDevicepath may be in the new FV
//
// 1. If the connect fails, RemainingDevicepath and handle will not
// change, so next time will do the dispatch, then dispatch's status
// will take effect
// 2. If the connect succeeds, the RemainingDevicepath and handle will
// change, then avoid the dispatch, we have chance to continue the
// next connection
//
gBS->ConnectController (Handle, NULL, RemainingDevicePath, FALSE);
}
}
//
// Loop until RemainingDevicePath is an empty device path
//
} while (!EFI_ERROR(Status) && !IsDevicePathEnd (RemainingDevicePath));
} while (DevicePath != NULL);
if (CopyOfDevicePath != NULL) {
FreePool(CopyOfDevicePath);
}
//
// All handle with DevicePath exists in the handle database
//
return Status;
}
/**
Free all the mapping database memory resource and initialize the mapping list entry.
@param MappingDataBase Mapping database list entry pointer
@retval EFI_SUCCESS Mapping database successfully freed
@retval EFI_INVALID_PARAMETER MappingDataBase is NULL
**/
EFI_STATUS
EFIAPI
FreeMappingDatabase (
IN OUT LIST_ENTRY *MappingDataBase
)
{
LIST_ENTRY *OverrideItemListIndex;
LIST_ENTRY *ImageInfoListIndex;
PLATFORM_OVERRIDE_ITEM *OverrideItem;
DRIVER_IMAGE_INFO *DriverImageInfo;
if (MappingDataBase == NULL) {
return EFI_INVALID_PARAMETER;
}
OverrideItemListIndex = GetFirstNode (MappingDataBase);
while (!IsNull (MappingDataBase, OverrideItemListIndex)) {
OverrideItem = CR(OverrideItemListIndex, PLATFORM_OVERRIDE_ITEM, Link, PLATFORM_OVERRIDE_ITEM_SIGNATURE);
//
// Free PLATFORM_OVERRIDE_ITEM.ControllerDevicePath[]
//
if (OverrideItem->ControllerDevicePath != NULL){
FreePool(OverrideItem->ControllerDevicePath);
}
ImageInfoListIndex = GetFirstNode (&OverrideItem->DriverInfoList);
while (!IsNull (&OverrideItem->DriverInfoList, ImageInfoListIndex)) {
//
// Free DRIVER_IMAGE_INFO.DriverImagePath[]
//
DriverImageInfo = CR(ImageInfoListIndex, DRIVER_IMAGE_INFO, Link, DRIVER_IMAGE_INFO_SIGNATURE);
if (DriverImageInfo->DriverImagePath != NULL) {
FreePool(DriverImageInfo->DriverImagePath);
}
//
// Free DRIVER_IMAGE_INFO itself
//
ImageInfoListIndex = GetNextNode (&OverrideItem->DriverInfoList, ImageInfoListIndex);
RemoveEntryList (&DriverImageInfo->Link);
FreePool(DriverImageInfo);
}
//
// Free PLATFORM_OVERRIDE_ITEM itself
//
OverrideItemListIndex = GetNextNode (MappingDataBase, OverrideItemListIndex);
RemoveEntryList (&OverrideItem->Link);
FreePool(OverrideItem);
}
InitializeListHead (MappingDataBase);
return EFI_SUCCESS;
}
/**
Create the mapping database according to variable.
Read the environment variable(s) that contain the override mappings from Controller Device Path to
a set of Driver Device Paths, and create the mapping database in memory with those variable info.
VariableLayout{
//
// NotEnd indicate whether the variable is the last one, and has no subsequent variable need to load.
// Each variable has MaximumVariableSize limitation, so we maybe need multiple variables to store
// large mapping infos.
// The variable(s) name rule is PlatDriOver, PlatDriOver1, PlatDriOver2, ....
//
UINT32 NotEnd; //Zero is the last one.
//
// The entry which contains the mapping that Controller Device Path to a set of Driver Device Paths
// There are often multi mapping entries in a variable.
//
UINT32 SIGNATURE; //SIGNATURE_32('p','d','o','i')
UINT32 DriverNum;
EFI_DEVICE_PATH_PROTOCOL ControllerDevicePath[];
EFI_DEVICE_PATH_PROTOCOL DriverDevicePath[];
EFI_DEVICE_PATH_PROTOCOL DriverDevicePath[];
EFI_DEVICE_PATH_PROTOCOL DriverDevicePath[];
......
UINT32 NotEnd; //Zero is the last one.
UINT32 SIGNATURE;
UINT32 DriverNum;
EFI_DEVICE_PATH_PROTOCOL ControllerDevicePath[];
EFI_DEVICE_PATH_PROTOCOL DriverDevicePath[];
EFI_DEVICE_PATH_PROTOCOL DriverDevicePath[];
EFI_DEVICE_PATH_PROTOCOL DriverDevicePath[];
......
}
@param MappingDataBase Mapping database list entry pointer
@retval EFI_SUCCESS Create the mapping database in memory successfully
@retval EFI_INVALID_PARAMETER MappingDataBase pointer is null
@retval EFI_NOT_FOUND Cannot find the 'PlatDriOver' NV variable
@retval EFI_VOLUME_CORRUPTED The found NV variable is corrupted
**/
EFI_STATUS
EFIAPI
InitOverridesMapping (
OUT LIST_ENTRY *MappingDataBase
)
{
UINTN BufferSize;
VOID *VariableBuffer;
UINT8 *VariableIndex;
UINTN VariableNum;
CHAR16 OverrideVariableName[40];
UINT32 NotEnd;
UINT32 DriverNumber;
PLATFORM_OVERRIDE_ITEM *OverrideItem;
DRIVER_IMAGE_INFO *DriverImageInfo;
BOOLEAN Corrupted;
UINT32 Signature;
EFI_DEVICE_PATH_PROTOCOL *ControllerDevicePath;
EFI_DEVICE_PATH_PROTOCOL *DriverDevicePath;
UINTN Index;
if (MappingDataBase == NULL) {
return EFI_INVALID_PARAMETER;
}
//
// Check the environment variable(s) that contain the override mappings .
//
VariableBuffer = GetVariableAndSize (L"PlatDriOver", &gEfiCallerIdGuid, &BufferSize);
ASSERT ((UINTN) VariableBuffer % sizeof(UINTN) == 0);
if (VariableBuffer == NULL) {
return EFI_NOT_FOUND;
}
//
// Traverse all variables.
//
VariableNum = 1;
Corrupted = FALSE;
NotEnd = 0;
do {
VariableIndex = VariableBuffer;
if (VariableIndex + sizeof (UINT32) > (UINT8 *) VariableBuffer + BufferSize) {
Corrupted = TRUE;
} else {
//
// End flag
//
NotEnd = *(UINT32*) VariableIndex;
}
//
// Traverse the entries containing the mapping that Controller Device Path
// to a set of Driver Device Paths within this variable.
//
VariableIndex = VariableIndex + sizeof (UINT32);
while (VariableIndex < ((UINT8 *)VariableBuffer + BufferSize)) {
//
// Check signature of this entry
//
if (VariableIndex + sizeof (UINT32) > (UINT8 *) VariableBuffer + BufferSize) {
Corrupted = TRUE;
break;
}
Signature = *(UINT32 *) VariableIndex;
if (Signature != PLATFORM_OVERRIDE_ITEM_SIGNATURE) {
Corrupted = TRUE;
break;
}
//
// Create PLATFORM_OVERRIDE_ITEM for this mapping
//
OverrideItem = AllocateZeroPool(sizeof (PLATFORM_OVERRIDE_ITEM));
ASSERT (OverrideItem != NULL);
OverrideItem->Signature = PLATFORM_OVERRIDE_ITEM_SIGNATURE;
InitializeListHead (&OverrideItem->DriverInfoList);
VariableIndex = VariableIndex + sizeof (UINT32);
//
// Get DriverNum
//
if (VariableIndex + sizeof (UINT32) >= (UINT8 *) VariableBuffer + BufferSize) {
Corrupted = TRUE;
break;
}
DriverNumber = *(UINT32*) VariableIndex;
OverrideItem->DriverInfoNum = DriverNumber;
VariableIndex = VariableIndex + sizeof (UINT32);
//
// Get ControllerDevicePath[]
//
ControllerDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) VariableIndex;
OverrideItem->ControllerDevicePath = DuplicateDevicePath (ControllerDevicePath);
VariableIndex = VariableIndex + GetDevicePathSize (ControllerDevicePath);
//
// Align the VariableIndex since the controller device path may not be aligned, refer to the SaveOverridesMapping()
//
VariableIndex += ((sizeof(UINT32) - ((UINTN) (VariableIndex))) & (sizeof(UINT32) - 1));
//
// Check buffer overflow.
//
if ((OverrideItem->ControllerDevicePath == NULL) || (VariableIndex < (UINT8 *) ControllerDevicePath) ||
(VariableIndex > (UINT8 *) VariableBuffer + BufferSize)) {
Corrupted = TRUE;
break;
}
//
// Get all DriverImageDevicePath[]
//
for (Index = 0; Index < DriverNumber; Index++) {
//
// Create DRIVER_IMAGE_INFO for this DriverDevicePath[]
//
DriverImageInfo = AllocateZeroPool(sizeof (DRIVER_IMAGE_INFO));
ASSERT (DriverImageInfo != NULL);
DriverImageInfo->Signature = DRIVER_IMAGE_INFO_SIGNATURE;
DriverDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) VariableIndex;
DriverImageInfo->DriverImagePath = DuplicateDevicePath (DriverDevicePath);
VariableIndex = VariableIndex + GetDevicePathSize (DriverDevicePath);
//
// Align the VariableIndex since the driver image device path may not be aligned, refer to the SaveOverridesMapping()
//
VariableIndex += ((sizeof(UINT32) - ((UINTN) (VariableIndex))) & (sizeof(UINT32) - 1));
InsertTailList (&OverrideItem->DriverInfoList, &DriverImageInfo->Link);
//
// Check buffer overflow
//
if ((DriverImageInfo->DriverImagePath == NULL) || (VariableIndex < (UINT8 *) DriverDevicePath) ||
(VariableIndex < (UINT8 *) VariableBuffer + BufferSize)) {
Corrupted = TRUE;
break;
}
}
InsertTailList (MappingDataBase, &OverrideItem->Link);
if (Corrupted) {
break;
}
}
FreePool(VariableBuffer);
if (Corrupted) {
FreeMappingDatabase (MappingDataBase);
return EFI_VOLUME_CORRUPTED;
}
//
// If there are additional variables (PlatDriOver1, PlatDriOver2, PlatDriOver3.....), get them.
// NotEnd indicates whether current variable is the end variable.
//
if (NotEnd != 0) {
UnicodeSPrint (OverrideVariableName, sizeof (OverrideVariableName), L"PlatDriOver%d", VariableNum++);
VariableBuffer = GetVariableAndSize (OverrideVariableName, &gEfiCallerIdGuid, &BufferSize);
ASSERT ((UINTN) VariableBuffer % sizeof(UINTN) == 0);
if (VariableBuffer == NULL) {
FreeMappingDatabase (MappingDataBase);
return EFI_VOLUME_CORRUPTED;
}
}
} while (NotEnd != 0);
return EFI_SUCCESS;
}
/**
Calculate the needed size in NV variable for recording a specific PLATFORM_OVERRIDE_ITEM info.
@param OverrideItemListIndex Pointer to the list of a specific PLATFORM_OVERRIDE_ITEM
@return The needed size number
**/
UINTN
EFIAPI
GetOneItemNeededSize (
IN LIST_ENTRY *OverrideItemListIndex
)
{
UINTN NeededSize;
PLATFORM_OVERRIDE_ITEM *OverrideItem;
LIST_ENTRY *ImageInfoListIndex;
DRIVER_IMAGE_INFO *DriverImageInfo;
UINTN DevicePathSize;
NeededSize = 0;
OverrideItem = CR(OverrideItemListIndex, PLATFORM_OVERRIDE_ITEM, Link, PLATFORM_OVERRIDE_ITEM_SIGNATURE);
NeededSize += sizeof (UINT32); //UINT32 SIGNATURE;
NeededSize += sizeof (UINT32); //UINT32 DriverNum;
DevicePathSize = GetDevicePathSize (OverrideItem->ControllerDevicePath);
NeededSize += DevicePathSize; // ControllerDevicePath
//
// Align the controller device path
//
NeededSize += ((sizeof(UINT32) - DevicePathSize) & (sizeof(UINT32) - 1));
//
// Traverse the Driver Info List of this Override Item
//
ImageInfoListIndex = GetFirstNode (&OverrideItem->DriverInfoList);
while (!IsNull (&OverrideItem->DriverInfoList, ImageInfoListIndex)) {
DriverImageInfo = CR(ImageInfoListIndex, DRIVER_IMAGE_INFO, Link, DRIVER_IMAGE_INFO_SIGNATURE);
DevicePathSize = GetDevicePathSize (DriverImageInfo->DriverImagePath);
NeededSize += DevicePathSize; //DriverDevicePath
//
// Align the driver image device path
//
NeededSize += ((sizeof(UINT32) - DevicePathSize) & (sizeof(UINT32) - 1));
ImageInfoListIndex = GetNextNode (&OverrideItem->DriverInfoList, ImageInfoListIndex);
}
return NeededSize;
}
/**
Deletes all environment variable(s) that contain the override mappings from Controller Device Path to
a set of Driver Device Paths.
@retval EFI_SUCCESS Delete all variable(s) successfully.
**/
EFI_STATUS
EFIAPI
DeleteOverridesVariables (
VOID
)
{
EFI_STATUS Status;
VOID *VariableBuffer;
UINTN VariableNum;
UINTN BufferSize;
UINTN Index;
CHAR16 OverrideVariableName[40];
//
// Get environment variable(s) number
//
VariableNum = 0;
VariableBuffer = GetVariableAndSize (L"PlatDriOver", &gEfiCallerIdGuid, &BufferSize);
VariableNum++;
if (VariableBuffer == NULL) {
return EFI_NOT_FOUND;
}
//
// Check NotEnd to get all PlatDriOverX variable(s)
//
while ((VariableBuffer != NULL) && ((*(UINT32*)VariableBuffer) != 0)) {
FreePool(VariableBuffer);
UnicodeSPrint (OverrideVariableName, sizeof (OverrideVariableName), L"PlatDriOver%d", VariableNum);
VariableBuffer = GetVariableAndSize (OverrideVariableName, &gEfiCallerIdGuid, &BufferSize);
VariableNum++;
}
//
// Delete PlatDriOver and all additional variables, if exist.
//
Status = gRT->SetVariable (
L"PlatDriOver",
&gEfiCallerIdGuid,
EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_NON_VOLATILE,
0,
NULL
);
ASSERT (!EFI_ERROR(Status));
for (Index = 1; Index < VariableNum; Index++) {
UnicodeSPrint (OverrideVariableName, sizeof (OverrideVariableName), L"PlatDriOver%d", Index);
Status = gRT->SetVariable (
OverrideVariableName,
&gEfiCallerIdGuid,
EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_NON_VOLATILE,
0,
NULL
);
ASSERT (!EFI_ERROR(Status));
}
return EFI_SUCCESS;
}
/**
Save the memory mapping database into NV environment variable(s).
@param MappingDataBase Mapping database list entry pointer
@retval EFI_SUCCESS Save memory mapping database successfully
@retval EFI_INVALID_PARAMETER MappingDataBase pointer is null
**/
EFI_STATUS
EFIAPI
SaveOverridesMapping (
IN LIST_ENTRY *MappingDataBase
)
{
EFI_STATUS Status;
VOID *VariableBuffer;
UINT8 *VariableIndex;
UINTN NumIndex;
CHAR16 OverrideVariableName[40];
UINT32 NotEnd;
PLATFORM_OVERRIDE_ITEM *OverrideItem;
DRIVER_IMAGE_INFO *DriverImageInfo;
LIST_ENTRY *OverrideItemListIndex;
LIST_ENTRY *ItemIndex;
LIST_ENTRY *ImageInfoListIndex;
UINTN VariableNeededSize;
UINT64 MaximumVariableStorageSize;
UINT64 RemainingVariableStorageSize;
UINT64 MaximumVariableSize;
UINTN OneItemNeededSize;
if (MappingDataBase == NULL) {
return EFI_INVALID_PARAMETER;
}
if (IsListEmpty (MappingDataBase)) {
Status = DeleteOverridesVariables ();
return EFI_SUCCESS;
}
//
// Get the the maximum size of an individual EFI variable in current system
//
gRT->QueryVariableInfo (
EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_NON_VOLATILE,
&MaximumVariableStorageSize,
&RemainingVariableStorageSize,
&MaximumVariableSize
);
NumIndex = 0;
OverrideItemListIndex = GetFirstNode (MappingDataBase);
while (!IsNull (MappingDataBase, OverrideItemListIndex)) {
//
// Try to find the most proper variable size which <= MaximumVariableSize,
// but can contain mapping info as much as possible
//
VariableNeededSize = sizeof (UINT32); // NotEnd;
ItemIndex = OverrideItemListIndex;
NotEnd = FALSE;
//
// Traverse all PLATFORM_OVERRIDE_ITEMs and get the total size.
//
while (!IsNull (MappingDataBase, ItemIndex)) {
OneItemNeededSize = GetOneItemNeededSize (ItemIndex);
//
// If the total size exceeds the MaximumVariableSize, then we must use
// multiple variables.
//
if ((VariableNeededSize +
OneItemNeededSize +
StrSize (L"PlatDriOver ")
) >= MaximumVariableSize
) {
NotEnd = TRUE;
break;
}
VariableNeededSize += OneItemNeededSize;
ItemIndex = GetNextNode (MappingDataBase, ItemIndex);
}
if (NotEnd != 0) {
if (VariableNeededSize == sizeof (UINT32)) {
//
// If an individual EFI variable cannot contain a single Item, return error
//
return EFI_OUT_OF_RESOURCES;
}
}
//
// VariableNeededSize is the most proper variable size, allocate variable buffer
// ItemIndex now points to the next PLATFORM_OVERRIDE_ITEM which is not covered by VariableNeededSize
//
VariableBuffer = AllocateZeroPool(VariableNeededSize);
ASSERT (VariableBuffer != NULL);
ASSERT ((UINTN) VariableBuffer % sizeof(UINTN) == 0);
//
// Fill the variable buffer according to MappingDataBase
//
VariableIndex = VariableBuffer;
*(UINT32 *) VariableIndex = NotEnd;
VariableIndex += sizeof (UINT32); // pass NotEnd
//
// ItemIndex points to the next PLATFORM_OVERRIDE_ITEM which is not covered by VariableNeededSize
//
while (OverrideItemListIndex != ItemIndex){
*(UINT32 *) VariableIndex = PLATFORM_OVERRIDE_ITEM_SIGNATURE;
VariableIndex += sizeof (UINT32); // pass SIGNATURE
OverrideItem = CR(OverrideItemListIndex, PLATFORM_OVERRIDE_ITEM, Link, PLATFORM_OVERRIDE_ITEM_SIGNATURE);
*(UINT32 *) VariableIndex = OverrideItem->DriverInfoNum;
VariableIndex += sizeof (UINT32); // pass DriverNum
CopyMem(VariableIndex, OverrideItem->ControllerDevicePath, GetDevicePathSize (OverrideItem->ControllerDevicePath));
VariableIndex += GetDevicePathSize (OverrideItem->ControllerDevicePath); // pass ControllerDevicePath
//
// Align the VariableIndex since the controller device path may not be aligned
//
VariableIndex += ((sizeof(UINT32) - ((UINTN) (VariableIndex))) & (sizeof(UINT32) - 1));
//
// Save the Driver Info List of this PLATFORM_OVERRIDE_ITEM
//
ImageInfoListIndex = GetFirstNode (&OverrideItem->DriverInfoList);
while (!IsNull (&OverrideItem->DriverInfoList, ImageInfoListIndex)) {
DriverImageInfo = CR(ImageInfoListIndex, DRIVER_IMAGE_INFO, Link, DRIVER_IMAGE_INFO_SIGNATURE);
CopyMem(VariableIndex, DriverImageInfo->DriverImagePath, GetDevicePathSize (DriverImageInfo->DriverImagePath));
VariableIndex += GetDevicePathSize (DriverImageInfo->DriverImagePath); // pass DriverImageDevicePath
//
// Align the VariableIndex since the driver image device path may not be aligned
//
VariableIndex += ((sizeof(UINT32) - ((UINTN) (VariableIndex))) & (sizeof(UINT32) - 1));
ImageInfoListIndex = GetNextNode (&OverrideItem->DriverInfoList, ImageInfoListIndex);
}
OverrideItemListIndex = GetNextNode (MappingDataBase, OverrideItemListIndex);
}
ASSERT (((UINTN)VariableIndex - (UINTN)VariableBuffer) == VariableNeededSize);
if (NumIndex == 0) {
UnicodeSPrint (OverrideVariableName, sizeof (OverrideVariableName), L"PlatDriOver");
} else {
UnicodeSPrint (OverrideVariableName, sizeof (OverrideVariableName), L"PlatDriOver%d", NumIndex );
}
Status = gRT->SetVariable (
OverrideVariableName,
&gEfiCallerIdGuid,
EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_NON_VOLATILE,
VariableNeededSize,
VariableBuffer
);
FreePool(VariableBuffer);
if (EFI_ERROR(Status)) {
if (NumIndex > 0) {
//
// Delete all PlatDriOver variables when full mapping can't be set.
//
DeleteOverridesVariables ();
}
return Status;
}
NumIndex ++;
}
return EFI_SUCCESS;
}
/**
Get the first Binding protocol which has the specific image handle.
@param ImageHandle The Image handle
@param BindingHandle The BindingHandle of the found Driver Binding protocol.
If Binding protocol is not found, it is set to NULL.
@return Pointer into the Binding Protocol interface
@retval NULL The parameter is not valid or the binding protocol is not found.
**/
EFI_DRIVER_BINDING_PROTOCOL *
EFIAPI
GetBindingProtocolFromImageHandle (
IN EFI_HANDLE ImageHandle,
OUT EFI_HANDLE *BindingHandle
)
{
EFI_STATUS Status;
UINTN Index;
UINTN DriverBindingHandleCount;
EFI_HANDLE *DriverBindingHandleBuffer;
EFI_DRIVER_BINDING_PROTOCOL *DriverBindingInterface;
if (BindingHandle == NULL || ImageHandle == NULL) {
return NULL;
}
//
// Get all drivers which support driver binding protocol
//
DriverBindingHandleCount = 0;
Status = gBS->LocateHandleBuffer (
ByProtocol,
&gEfiDriverBindingProtocolGuid,
NULL,
&DriverBindingHandleCount,
&DriverBindingHandleBuffer
);
if (EFI_ERROR(Status) || (DriverBindingHandleCount == 0)) {
return NULL;
}
for (Index = 0; Index < DriverBindingHandleCount; Index++) {
DriverBindingInterface = NULL;
Status = gBS->OpenProtocol (
DriverBindingHandleBuffer[Index],
&gEfiDriverBindingProtocolGuid,
(VOID **) &DriverBindingInterface,
NULL,
NULL,
EFI_OPEN_PROTOCOL_GET_PROTOCOL
);
if (EFI_ERROR(Status)) {
continue;
}
if (DriverBindingInterface->ImageHandle == ImageHandle) {
*BindingHandle = DriverBindingHandleBuffer[Index];
FreePool(DriverBindingHandleBuffer);
return DriverBindingInterface;
}
}
//
// If no Driver Binding Protocol instance is found
//
FreePool(DriverBindingHandleBuffer);
*BindingHandle = NULL;
return NULL;
}
/**
Return the current TPL.
@return Current TPL
**/
EFI_TPL
GetCurrentTpl (
VOID
)
{
EFI_TPL Tpl;
Tpl = gBS->RaiseTPL (TPL_HIGH_LEVEL);
gBS->RestoreTPL (Tpl);
return Tpl;
}
/**
Retrieves the image handle of the platform override driver for a controller in
the system from the memory mapping database.
@param ControllerHandle The device handle of the controller to check if
a driver override exists.
@param DriverImageHandle On input, the previously returnd driver image handle.
On output, a pointer to the next driver handle.
Passing in a pointer to NULL, will return the
first driver handle for ControllerHandle.
@param MappingDataBase Mapping database list entry pointer
@param CallerImageHandle The caller driver's image handle, for
UpdateFvFileDevicePath use.
@retval EFI_INVALID_PARAMETER The handle specified by ControllerHandle is not
a valid handle. Or DriverImagePath is not a
device path that was returned on a previous call
to GetDriverPath().
@retval EFI_NOT_FOUND A driver override for ControllerHandle was not
found.
@retval EFI_UNSUPPORTED The operation is not supported.
@retval EFI_SUCCESS The driver override for ControllerHandle was
returned in DriverImagePath.
**/
EFI_STATUS
EFIAPI
GetDriverFromMapping (
IN EFI_HANDLE ControllerHandle,
IN OUT EFI_HANDLE *DriverImageHandle,
IN LIST_ENTRY *MappingDataBase,
IN EFI_HANDLE CallerImageHandle
)
{
EFI_STATUS Status;
EFI_DEVICE_PATH_PROTOCOL *ControllerDevicePath;
BOOLEAN ControllerFound;
BOOLEAN ImageFound;
EFI_HANDLE *ImageHandleBuffer;
UINTN ImageHandleCount;
UINTN Index;
EFI_DRIVER_BINDING_PROTOCOL *DriverBinding;
EFI_HANDLE DriverBindingHandle;
BOOLEAN FoundLastReturned;
PLATFORM_OVERRIDE_ITEM *OverrideItem;
DRIVER_IMAGE_INFO *DriverImageInfo;
LIST_ENTRY *OverrideItemListIndex;
LIST_ENTRY *ImageInfoListIndex;
EFI_DEVICE_PATH_PROTOCOL *TempDriverImagePath;
EFI_HANDLE ImageHandle;
EFI_HANDLE Handle;
EFI_DEVICE_PATH_PROTOCOL *LoadedImageDevicePath;
EFI_BUS_SPECIFIC_DRIVER_OVERRIDE_PROTOCOL *BusSpecificDriverOverride;
UINTN DevicePathSize;
//
// Check that ControllerHandle is a valid handle
//
if (ControllerHandle == NULL) {
return EFI_INVALID_PARAMETER;
}
//
// Get the device path of ControllerHandle
//
Status = gBS->HandleProtocol (
ControllerHandle,
&gEfiDevicePathProtocolGuid,
(VOID **) &ControllerDevicePath
);
if (EFI_ERROR(Status) || ControllerDevicePath == NULL) {
return EFI_INVALID_PARAMETER;
}
//
// Search ControllerDevicePath in MappingDataBase
//
OverrideItem = NULL;
ControllerFound = FALSE;
DevicePathSize = GetDevicePathSize (ControllerDevicePath);
OverrideItemListIndex = GetFirstNode (MappingDataBase);
while (!IsNull (MappingDataBase, OverrideItemListIndex)) {
OverrideItem = CR(OverrideItemListIndex, PLATFORM_OVERRIDE_ITEM, Link, PLATFORM_OVERRIDE_ITEM_SIGNATURE);
if (DevicePathSize == GetDevicePathSize (OverrideItem->ControllerDevicePath)) {
if (CompareMem (
ControllerDevicePath,
OverrideItem->ControllerDevicePath,
DevicePathSize
) == 0
) {
ControllerFound = TRUE;
break;
}
}
OverrideItemListIndex = GetNextNode (MappingDataBase, OverrideItemListIndex);
}
if (!ControllerFound) {
return EFI_NOT_FOUND;
}
//
// Passing in a pointer to NULL, will return the first driver device path for ControllerHandle.
// Check whether the driverImagePath is not a device path that was returned on a previous call to GetDriverPath().
//
if (*DriverImageHandle != NULL) {
if (*DriverImageHandle != OverrideItem->LastReturnedImageHandle) {
return EFI_INVALID_PARAMETER;
}
}
//
// The GetDriverPath() may be called recursively, because it use ConnectDevicePath() internally,
// so should check whether there is a dead loop.
// Here use a controller device path stack to record all processed controller device path during a GetDriverPath() call,
// and check the controller device path whether appear again during the GetDriverPath() call.
//
if (CheckExistInStack (OverrideItem->ControllerDevicePath)) {
//
// There is a dependency dead loop if the ControllerDevicePath appear in stack twice
//
return EFI_UNSUPPORTED;
}
PushDevPathStack (OverrideItem->ControllerDevicePath);
//
// Check every override driver, try to load and start them
//
ImageInfoListIndex = GetFirstNode (&OverrideItem->DriverInfoList);
while (!IsNull (&OverrideItem->DriverInfoList, ImageInfoListIndex)) {
DriverImageInfo = CR(ImageInfoListIndex, DRIVER_IMAGE_INFO, Link, DRIVER_IMAGE_INFO_SIGNATURE);
if (DriverImageInfo->ImageHandle == NULL) {
//
// Skip if the image is unloadable or unstartable
//
if ((!DriverImageInfo->UnLoadable) && ((!DriverImageInfo->UnStartable))) {
TempDriverImagePath = DriverImageInfo->DriverImagePath;
//
// If the image device path contains an FV node, check the FV file device path is valid.
// If it is invalid, try to return the valid device path.
// FV address maybe changes for memory layout adjust from time to time,
// use this function could promise the FV file device path is right.
//
Status = UpdateFvFileDevicePath (&TempDriverImagePath, NULL, CallerImageHandle);
if (!EFI_ERROR(Status)) {
FreePool(DriverImageInfo->DriverImagePath);
DriverImageInfo->DriverImagePath = TempDriverImagePath;
}
//
// Get all Loaded Image protocol to check whether the driver image has been loaded and started
//
ImageFound = FALSE;
ImageHandleCount = 0;
Status = gBS->LocateHandleBuffer (
ByProtocol,
&gEfiLoadedImageProtocolGuid,
NULL,
&ImageHandleCount,
&ImageHandleBuffer
);
if (EFI_ERROR(Status) || (ImageHandleCount == 0)) {
return EFI_NOT_FOUND;
}
for(Index = 0; Index < ImageHandleCount; Index ++) {
//
// Get the EFI Loaded Image Device Path Protocol
//
LoadedImageDevicePath = NULL;
Status = gBS->HandleProtocol (
ImageHandleBuffer[Index],
&gEfiLoadedImageDevicePathProtocolGuid,
(VOID **) &LoadedImageDevicePath
);
if (EFI_ERROR(Status)) {
//
// Maybe not all EFI_LOADED_IMAGE_DEVICE_PATH_PROTOCOL existed.
//
continue;
}
DevicePathSize = GetDevicePathSize (DriverImageInfo->DriverImagePath);
if (DevicePathSize == GetDevicePathSize (LoadedImageDevicePath)) {
if (CompareMem (
DriverImageInfo->DriverImagePath,
LoadedImageDevicePath,
GetDevicePathSize (LoadedImageDevicePath)
) == 0
) {
ImageFound = TRUE;
break;
}
}
}
if (ImageFound) {
//
// Find its related driver binding protocol
// Driver binding handle may be different with its driver's Image Handle.
//
DriverBindingHandle = NULL;
DriverBinding = GetBindingProtocolFromImageHandle (
ImageHandleBuffer[Index],
&DriverBindingHandle
);
ASSERT (DriverBinding != NULL);
DriverImageInfo->ImageHandle = ImageHandleBuffer[Index];
} else if (GetCurrentTpl() <= TPL_CALLBACK){
//
// The driver image has not been loaded and started. Try to load and start it now.
// Try to connect all device in the driver image path.
//
// Note: LoadImage() and StartImage() should be called under CALLBACK TPL in theory, but
// since many device need to be connected in CALLBACK level environment( e.g. Usb devices )
// and the Fat and Patition driver can endure executing in CALLBACK level in fact, so here permit
// to use LoadImage() and StartImage() in CALLBACK TPL.
//
Status = ConnectDevicePath (DriverImageInfo->DriverImagePath);
//
// check whether it points to a PCI Option Rom image,
// and try to use bus override protocol to get its first option rom image driver
//
TempDriverImagePath = DriverImageInfo->DriverImagePath;
gBS->LocateDevicePath (&gEfiDevicePathProtocolGuid, &TempDriverImagePath, &Handle);
//
// Get the Bus Specific Driver Override Protocol instance on the Controller Handle
//
Status = gBS->HandleProtocol(
Handle,
&gEfiBusSpecificDriverOverrideProtocolGuid,
(VOID **) &BusSpecificDriverOverride
);
if (!EFI_ERROR(Status) && (BusSpecificDriverOverride != NULL)) {
ImageHandle = NULL;
Status = BusSpecificDriverOverride->GetDriver (
BusSpecificDriverOverride,
&ImageHandle
);
if (!EFI_ERROR(Status)) {
//
// Find its related driver binding protocol
// Driver binding handle may be different with its driver's Image handle
//
DriverBindingHandle = NULL;
DriverBinding = GetBindingProtocolFromImageHandle (
ImageHandle,
&DriverBindingHandle
);
ASSERT (DriverBinding != NULL);
DriverImageInfo->ImageHandle = ImageHandle;
}
}
//
// Skip if any device cannot be connected now, future passes through GetDriver() may be able to load that driver.
// Only file path media or FwVol Device Path Node remain if all device is connected
//
TempDriverImagePath = DriverImageInfo->DriverImagePath;
gBS->LocateDevicePath (&gEfiDevicePathProtocolGuid, &TempDriverImagePath, &Handle);
if (((DevicePathType (TempDriverImagePath) == MEDIA_DEVICE_PATH) &&
(DevicePathSubType (TempDriverImagePath) == MEDIA_FILEPATH_DP)) ||
(EfiGetNameGuidFromFwVolDevicePathNode ((MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *) TempDriverImagePath) != NULL)
) {
//
// Try to load the driver
//
TempDriverImagePath = DriverImageInfo->DriverImagePath;
Status = gBS->LoadImage (
FALSE,
CallerImageHandle,
TempDriverImagePath,
NULL,
0,
&ImageHandle
);
if (!EFI_ERROR(Status)) {
//
// Try to start the driver
//
Status = gBS->StartImage (ImageHandle, NULL, NULL);
if (EFI_ERROR(Status)){
DriverImageInfo->UnStartable = TRUE;
DriverImageInfo->ImageHandle = NULL;
} else {
//
// Find its related driver binding protocol
// Driver binding handle may be different with its driver's Image handle
//
DriverBindingHandle = NULL;
DriverBinding = GetBindingProtocolFromImageHandle (
ImageHandle,
&DriverBindingHandle
);
ASSERT (DriverBinding != NULL);
DriverImageInfo->ImageHandle = ImageHandle;
}
} else {
DriverImageInfo->UnLoadable = TRUE;
DriverImageInfo->ImageHandle = NULL;
}
}
}
FreePool(ImageHandleBuffer);
}
}
ImageInfoListIndex = GetNextNode (&OverrideItem->DriverInfoList, ImageInfoListIndex);
}
//
// Finish try to load and start the override driver of a controller, popup the controller's device path
//
PopDevPathStack (NULL);
//
// return the DriverImageHandle for ControllerHandle
//
FoundLastReturned = FALSE;
ImageInfoListIndex = GetFirstNode (&OverrideItem->DriverInfoList);
while (!IsNull (&OverrideItem->DriverInfoList, ImageInfoListIndex)) {
DriverImageInfo = CR(ImageInfoListIndex, DRIVER_IMAGE_INFO, Link, DRIVER_IMAGE_INFO_SIGNATURE);
if (DriverImageInfo->ImageHandle != NULL) {
if ((*DriverImageHandle == NULL) || FoundLastReturned) {
//
// If DriverImageHandle is NULL, then we just need to return the first driver.
// If FoundLastReturned, this means we have just encountered the previously returned driver.
// For both cases, we just return the image handle of this driver.
//
OverrideItem->LastReturnedImageHandle = DriverImageInfo->ImageHandle;
*DriverImageHandle = DriverImageInfo->ImageHandle;
return EFI_SUCCESS;
} else if (*DriverImageHandle == DriverImageInfo->ImageHandle){
//
// We have found the previously returned driver.
//
FoundLastReturned = TRUE;
}
}
ImageInfoListIndex = GetNextNode (&OverrideItem->DriverInfoList, ImageInfoListIndex);
}
return EFI_NOT_FOUND;
}
/**
Check mapping database whether already has the mapping info which
records the input Controller to input DriverImage.
@param ControllerDevicePath The controller device path is to be check.
@param DriverImageDevicePath The driver image device path is to be check.
@param MappingDataBase Mapping database list entry pointer
@param DriverInfoNum the controller's total override driver number
@param DriverImageNO The driver order number for the input DriverImage.
If the DriverImageDevicePath is NULL, DriverImageNO is not set.
@retval EFI_INVALID_PARAMETER ControllerDevicePath or MappingDataBase is NULL.
@retval EFI_NOT_FOUND ControllerDevicePath is not found in MappingDataBase or
DriverImageDevicePath is not found in the found DriverImage Info list.
@retval EFI_SUCCESS The controller's total override driver number and
input DriverImage's order number is correctly return.
**/
EFI_STATUS
EFIAPI
CheckMapping (
IN EFI_DEVICE_PATH_PROTOCOL *ControllerDevicePath,
IN EFI_DEVICE_PATH_PROTOCOL *DriverImageDevicePath OPTIONAL,
IN LIST_ENTRY *MappingDataBase,
OUT UINT32 *DriverInfoNum OPTIONAL,
OUT UINT32 *DriverImageNO OPTIONAL
)
{
LIST_ENTRY *OverrideItemListIndex;
PLATFORM_OVERRIDE_ITEM *OverrideItem;
LIST_ENTRY *ImageInfoListIndex;
DRIVER_IMAGE_INFO *DriverImageInfo;
BOOLEAN Found;
UINT32 ImageNO;
UINTN DevicePathSize;
if (ControllerDevicePath == NULL) {
return EFI_INVALID_PARAMETER;
}
if (MappingDataBase == NULL) {
return EFI_INVALID_PARAMETER;
}
//
// Search ControllerDevicePath in MappingDataBase
//
Found = FALSE;
OverrideItem = NULL;
OverrideItemListIndex = GetFirstNode (MappingDataBase);
while (!IsNull (MappingDataBase, OverrideItemListIndex)) {
OverrideItem = CR(OverrideItemListIndex, PLATFORM_OVERRIDE_ITEM, Link, PLATFORM_OVERRIDE_ITEM_SIGNATURE);
DevicePathSize = GetDevicePathSize (ControllerDevicePath);
if (DevicePathSize == GetDevicePathSize (OverrideItem->ControllerDevicePath)) {
if (CompareMem (
ControllerDevicePath,
OverrideItem->ControllerDevicePath,
DevicePathSize
) == 0
) {
Found = TRUE;
break;
}
}
OverrideItemListIndex = GetNextNode (MappingDataBase, OverrideItemListIndex);
}
if (!Found) {
//
// ControllerDevicePath is not in MappingDataBase
//
return EFI_NOT_FOUND;
}
ASSERT (OverrideItem->DriverInfoNum != 0);
if (DriverInfoNum != NULL) {
*DriverInfoNum = OverrideItem->DriverInfoNum;
}
//
// If DriverImageDevicePath is NULL, skip checking DriverImageDevicePath
// in the controller's Driver Image Info List
//
if (DriverImageDevicePath == NULL) {
return EFI_SUCCESS;
}
//
// return the DriverImageHandle for ControllerHandle
//
ImageNO = 0;
Found = FALSE;
ImageInfoListIndex = GetFirstNode (&OverrideItem->DriverInfoList);
while (!IsNull (&OverrideItem->DriverInfoList, ImageInfoListIndex)) {
DriverImageInfo = CR(ImageInfoListIndex, DRIVER_IMAGE_INFO, Link, DRIVER_IMAGE_INFO_SIGNATURE);
ImageNO++;
DevicePathSize = GetDevicePathSize (DriverImageDevicePath);
if (DevicePathSize == GetDevicePathSize (DriverImageInfo->DriverImagePath)) {
if (CompareMem (
DriverImageDevicePath,
DriverImageInfo->DriverImagePath,
GetDevicePathSize (DriverImageInfo->DriverImagePath)
) == 0
) {
Found = TRUE;
break;
}
}
ImageInfoListIndex = GetNextNode (&OverrideItem->DriverInfoList, ImageInfoListIndex);
}
if (!Found) {
//
// DriverImageDevicePath is not found in the controller's Driver Image Info List
//
return EFI_NOT_FOUND;
} else {
if (DriverImageNO != NULL) {
*DriverImageNO = ImageNO;
}
return EFI_SUCCESS;
}
}
/**
Insert a driver image as a controller's override driver into the mapping database.
The driver image's order number is indicated by DriverImageNO.
@param ControllerDevicePath The controller device path need to add a
override driver image item
@param DriverImageDevicePath The driver image device path need to be insert
@param MappingDataBase Mapping database list entry pointer
@param DriverImageNO The inserted order number. If this number is taken,
the larger available number will be used.
@retval EFI_INVALID_PARAMETER ControllerDevicePath is NULL, or DriverImageDevicePath is NULL
or MappingDataBase is NULL
@retval EFI_ALREADY_STARTED The input Controller to input DriverImage has been
recorded into the mapping database.
@retval EFI_SUCCESS The Controller and DriverImage are inserted into
the mapping database successfully.
**/
EFI_STATUS
EFIAPI
InsertDriverImage (
IN EFI_DEVICE_PATH_PROTOCOL *ControllerDevicePath,
IN EFI_DEVICE_PATH_PROTOCOL *DriverImageDevicePath,
IN LIST_ENTRY *MappingDataBase,
IN UINT32 DriverImageNO
)
{
EFI_STATUS Status;
LIST_ENTRY *OverrideItemListIndex;
PLATFORM_OVERRIDE_ITEM *OverrideItem;
LIST_ENTRY *ImageInfoListIndex;
DRIVER_IMAGE_INFO *DriverImageInfo;
BOOLEAN Found;
UINT32 ImageNO;
UINTN DevicePathSize;
if (ControllerDevicePath == NULL) {
return EFI_INVALID_PARAMETER;
}
if (DriverImageDevicePath == NULL) {
return EFI_INVALID_PARAMETER;
}
if (MappingDataBase == NULL) {
return EFI_INVALID_PARAMETER;
}
//
// If the driver is already in the controller's Driver Image Info List,
// just return EFI_ALREADY_STARTED.
//
Status = CheckMapping (
ControllerDevicePath,
DriverImageDevicePath,
MappingDataBase,
NULL,
NULL
);
if (Status == EFI_SUCCESS) {
return EFI_ALREADY_STARTED;
}
//
// Search the input ControllerDevicePath in MappingDataBase
//
Found = FALSE;
OverrideItem = NULL;
OverrideItemListIndex = GetFirstNode (MappingDataBase);
while (!IsNull (MappingDataBase, OverrideItemListIndex)) {
OverrideItem = CR(OverrideItemListIndex, PLATFORM_OVERRIDE_ITEM, Link, PLATFORM_OVERRIDE_ITEM_SIGNATURE);
DevicePathSize = GetDevicePathSize (ControllerDevicePath);
if (DevicePathSize == GetDevicePathSize (OverrideItem->ControllerDevicePath)) {
if (CompareMem (
ControllerDevicePath,
OverrideItem->ControllerDevicePath,
DevicePathSize
) == 0
) {
Found = TRUE;
break;
}
}
OverrideItemListIndex = GetNextNode (MappingDataBase, OverrideItemListIndex);
}
//
// If cannot find, this is a new controller item
// Add the Controller related PLATFORM_OVERRIDE_ITEM structrue in mapping data base
//
if (!Found) {
OverrideItem = AllocateZeroPool(sizeof (PLATFORM_OVERRIDE_ITEM));
ASSERT (OverrideItem != NULL);
OverrideItem->Signature = PLATFORM_OVERRIDE_ITEM_SIGNATURE;
OverrideItem->ControllerDevicePath = DuplicateDevicePath (ControllerDevicePath);
InitializeListHead (&OverrideItem->DriverInfoList);
InsertTailList (MappingDataBase, &OverrideItem->Link);
}
//
// Prepare the driver image related DRIVER_IMAGE_INFO structure.
//
DriverImageInfo = AllocateZeroPool(sizeof (DRIVER_IMAGE_INFO));
ASSERT (DriverImageInfo != NULL);
DriverImageInfo->Signature = DRIVER_IMAGE_INFO_SIGNATURE;
DriverImageInfo->DriverImagePath = DuplicateDevicePath (DriverImageDevicePath);
//
// Find the driver image wanted order location
//
ImageNO = 0;
Found = FALSE;
ImageInfoListIndex = GetFirstNode (&OverrideItem->DriverInfoList);
while (!IsNull (&OverrideItem->DriverInfoList, ImageInfoListIndex)) {
if (ImageNO == (DriverImageNO - 1)) {
//
// find the wanted order location, insert it
//
InsertTailList (ImageInfoListIndex, &DriverImageInfo->Link);
OverrideItem->DriverInfoNum ++;
Found = TRUE;
break;
}
ImageNO++;
ImageInfoListIndex = GetNextNode (&OverrideItem->DriverInfoList, ImageInfoListIndex);
}
if (!Found) {
//
// if not find the wanted order location, add it as last item of the controller mapping item
//
InsertTailList (&OverrideItem->DriverInfoList, &DriverImageInfo->Link);
OverrideItem->DriverInfoNum ++;
}
return EFI_SUCCESS;
}
/**
Delete a controller's override driver from the mapping database.
@param ControllerDevicePath The controller device path will be deleted
when all drivers images on it are removed.
@param DriverImageDevicePath The driver image device path will be delete.
If NULL, all driver image will be delete.
@param MappingDataBase Mapping database list entry pointer
@retval EFI_INVALID_PARAMETER ControllerDevicePath is NULL, or MappingDataBase is NULL
@retval EFI_NOT_FOUND ControllerDevicePath is not found in MappingDataBase or
DriverImageDevicePath is not found in the found DriverImage Info list.
@retval EFI_SUCCESS Delete the specified driver successfully.
**/
EFI_STATUS
EFIAPI
DeleteDriverImage (
IN EFI_DEVICE_PATH_PROTOCOL *ControllerDevicePath,
IN EFI_DEVICE_PATH_PROTOCOL *DriverImageDevicePath,
IN LIST_ENTRY *MappingDataBase
)
{
EFI_STATUS Status;
LIST_ENTRY *OverrideItemListIndex;
PLATFORM_OVERRIDE_ITEM *OverrideItem;
LIST_ENTRY *ImageInfoListIndex;
DRIVER_IMAGE_INFO *DriverImageInfo;
BOOLEAN Found;
UINTN DevicePathSize;
if (ControllerDevicePath == NULL) {
return EFI_INVALID_PARAMETER;
}
if (MappingDataBase == NULL) {
return EFI_INVALID_PARAMETER;
}
//
// If ControllerDevicePath is not found in mapping database, return EFI_NOT_FOUND.
//
Status = CheckMapping (
ControllerDevicePath,
DriverImageDevicePath,
MappingDataBase,
NULL,
NULL
);
if (EFI_ERROR(Status)) {
return EFI_NOT_FOUND;
}
//
// Search ControllerDevicePath in MappingDataBase
//
Found = FALSE;
OverrideItem = NULL;
OverrideItemListIndex = GetFirstNode (MappingDataBase);
while (!IsNull (MappingDataBase, OverrideItemListIndex)) {
OverrideItem = CR(OverrideItemListIndex, PLATFORM_OVERRIDE_ITEM, Link, PLATFORM_OVERRIDE_ITEM_SIGNATURE);
DevicePathSize = GetDevicePathSize (ControllerDevicePath);
if (DevicePathSize == GetDevicePathSize (OverrideItem->ControllerDevicePath)) {
if (CompareMem (
ControllerDevicePath,
OverrideItem->ControllerDevicePath,
DevicePathSize
) == 0
) {
Found = TRUE;
break;
}
}
OverrideItemListIndex = GetNextNode (MappingDataBase, OverrideItemListIndex);
}
ASSERT (Found);
ASSERT (OverrideItem->DriverInfoNum != 0);
Found = FALSE;
ImageInfoListIndex = GetFirstNode (&OverrideItem->DriverInfoList);
while (!IsNull (&OverrideItem->DriverInfoList, ImageInfoListIndex)) {
DriverImageInfo = CR(ImageInfoListIndex, DRIVER_IMAGE_INFO, Link, DRIVER_IMAGE_INFO_SIGNATURE);
ImageInfoListIndex = GetNextNode (&OverrideItem->DriverInfoList, ImageInfoListIndex);
if (DriverImageDevicePath != NULL) {
//
// Search for the specified DriverImageDevicePath and remove it, then break.
//
DevicePathSize = GetDevicePathSize (DriverImageDevicePath);
if (DevicePathSize == GetDevicePathSize (DriverImageInfo->DriverImagePath)) {
if (CompareMem (
DriverImageDevicePath,
DriverImageInfo->DriverImagePath,
GetDevicePathSize (DriverImageInfo->DriverImagePath)
) == 0
) {
Found = TRUE;
FreePool(DriverImageInfo->DriverImagePath);
RemoveEntryList (&DriverImageInfo->Link);
OverrideItem->DriverInfoNum --;
break;
}
}
} else {
//
// Remove all existing driver image info entries, so no break here.
//
Found = TRUE;
FreePool(DriverImageInfo->DriverImagePath);
RemoveEntryList (&DriverImageInfo->Link);
OverrideItem->DriverInfoNum --;
}
}
//
// Confirm all driver image info entries have been removed,
// if DriverImageDevicePath is NULL.
//
if (DriverImageDevicePath == NULL) {
ASSERT (OverrideItem->DriverInfoNum == 0);
}
//
// If Override Item has no driver image info entry, then delete this item.
//
if (OverrideItem->DriverInfoNum == 0) {
FreePool(OverrideItem->ControllerDevicePath);
RemoveEntryList (&OverrideItem->Link);
FreePool(OverrideItem);
}
if (!Found) {
//
// DriverImageDevicePath is not NULL and cannot be found in the controller's
// driver image info list.
//
return EFI_NOT_FOUND;
}
return EFI_SUCCESS;
}
|
8e4292e0011e0e3b21ad8641713afd5365685f82
|
59864cbd213b5da6f50d6255b0a021564b3d5bd4
|
/challenges/CableGrind/pov_159/pov.c
|
b99182f34d7a8b0d9c212b71d5e7abf4e707ca8b
|
[
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-unknown",
"BSD-2-Clause"
] |
permissive
|
trailofbits/cb-multios
|
8af96a4fbc3b34644367faa135347f88e0e0d0a3
|
810d7b24b1f62f56ef49b148fe155b0d0629cad2
|
refs/heads/master
| 2023-09-05T03:56:20.229403
| 2022-12-27T15:47:54
| 2022-12-27T15:47:54
| 41,688,943
| 522
| 133
|
MIT
| 2023-06-29T02:47:13
| 2015-08-31T17:04:31
|
C
|
UTF-8
|
C
| false
| false
| 14,547
|
c
|
pov.c
|
#include "libpov.h"
int main(int cgc_argc, char *cgc_argv[]) {
cgc_negotiate_type1(0x0, 0x0, 0);
do {
//*** writing data
static unsigned char write_00000_00000[] =
"\x04\x04\x00\x00";
static unsigned int write_00000_00000_len = 4;
unsigned char *write_00000 = NULL;
unsigned int write_00000_len = 0;
write_00000 = cgc_append_buf(write_00000, &write_00000_len, write_00000_00000, write_00000_00000_len);
if (write_00000_len > 0) {
cgc_transmit_all(1, write_00000, write_00000_len);
}
cgc_free(write_00000);
} while (0);
do {
//*** writing data
static unsigned char write_00001_00000[] =
"\x01\x00\x00\x00\x01\x00\x00\x00\xf0\x03\x00\x00\xe8\x03\x00\x00"
"\x00\x00\x00\x00\x00\x00\x00\x00\xe8\x03\x00\x00\xf5\x22\xf2\xd8"
"\x2b\x86\x0b\x1a\x7c\xb2\x0e\x50\x72\x01\x00\x00\x1a\x91\xe9\x9e"
"\xce\x58\xcc\x03\x64\x35\x34\xb9\x25\x90\xe4\xf4\xf4\x61\xf9\x92"
"\x69\x7e\x26\x00\x9b\x9a\xff\x3c\x7d\x77\x3d\xba\x21\x58\x41\x1d"
"\x54\x94\xd9\x24\x1b\x2b\xc1\x87\xeb\x73\xb2\x01\x71\x29\x17\xd8"
"\x64\xed\x80\xd7\x22\x38\xcc\xe6\x77\x37\x96\x83\x7b\xde\x9b\xf6"
"\xf1\x8d\x11\x18\xe5\x6d\xac\xaf\xe6\xc3\xa2\x3b\x8c\x96\x36\x4b"
"\x19\xb6\xb0\x10\xdd\x7a\x96\x04\x55\xa5\x84\x46\xd4\xcf\xf1\xe7"
"\x7e\xd8\xfc\xb5\x3b\x0e\xfe\x53\xd8\xf9\x3e\x1f\x1c\x94\x2b\x86"
"\xdf\x85\x30\x74\x65\x55\xa1\xb8\xbd\x67\xf4\x4d\x2a\x90\xde\x52"
"\x65\xfe\xfb\xb4\x81\xd4\xca\x62\xa5\xeb\x38\x80\x03\x60\x59\xd6"
"\xea\x56\xee\xa4\x8e\xd6\xdb\x79\x39\x4d\x97\xc9\x0a\x9d\xa4\x7e"
"\xcb\xbe\x93\x1c\x14\xf9\x1e\x3c\x76\xe5\x9e\xeb\xd8\x18\x17\x76"
"\x3d\x24\xc4\x46\x21\xa4\x03\x49\xfc\x37\xa9\xea\x68\xa2\xea\x3d"
"\x00\xbe\x46\x5d\xbf\x7a\x16\x24\x0f\xba\x46\x30\xbb\x5e\x10\x5d"
"\xbd\x21\x62\x69\xe6\xc0\xc5\x23\xa7\xd2\xd6\x0e\x43\x1c\xac\x99"
"\xe3\xd7\x4c\x03\xa5\x1a\x5a\x2e\xab\xa4\xf1\x7e\xf1\x5e\xdf\xf7"
"\x6f\x07\x89\x64\x13\xb3\xb0\x68\x1e\x5d\x43\x55\xd2\x23\x35\xa6"
"\x8e\xe7\x28\xa1\x2f\xab\xb9\x00\x49\xff\x28\xaf\xcb\xde\x0a\xb1"
"\xd5\xba\x56\x0e\xc3\x1c\xd3\x46\x48\xb9\x15\x73\x2e\x29\xd3\x3d"
"\xdf\x43\xc2\xd4\xc4\x5e\xe8\xa7\xd3\x85\xa4\x40\xd7\xca\x12\x0c"
"\x2c\xac\x79\x5c\xa1\xca\x8c\xc3\x11\x4a\xaa\x19\xb8\x7d\x0b\xb8"
"\x0f\xe6\x8e\xb7\xba\x34\xaa\x5e\xc9\xa4\xcd\xfa\x90\xa7\x70\x20"
"\xac\x33\x99\x78\x7a\xf9\x9a\x3b\x5b\x3e\xce\xae\xe7\xce\x9a\x53"
"\xd2\x70\x12\xc3\xa0\x53\xa2\xf6\x16\x08\x3b\x86\x01\x9c\xdf\x66"
"\xdd\x21\x9c\x89\xd7\xb4\x42\x69\xfa\x07\xfd\xa5\xa7\x13\x13\x3b"
"\x01\x04\xd1\xdf\x3c\xcd\x96\xaa\x86\xe1\x3d\x80\x97\x24\x88\x4c"
"\x46\xd9\x4b\x2b\x49\x34\xb4\xf7\x7e\xc0\x76\x9d\x2b\x95\xc9\xc2"
"\xcb\x3f\x8b\x67\x66\x62\xb0\x2f\xaf\xe3\x26\xa7\x26\xf6\xa8\x26"
"\x16\x94\x6b\xc0\x8b\x79\xd7\x6a\x13\xa6\x49\x15\xd2\x58\xb2\xaf"
"\x42\x05\x33\xde\x18\xbe\x73\x65\xa3\xea\x85\x5b\x09\xfc\x82\x89"
"\x55\x1a\x8d\x52\xc3\x8f\x74\xac\x61\xff\x65\xd1\x11\x3c\xaa\x66"
"\x73\x36\x45\x8f\x7a\xfa\x9c\x27\x5c\xe5\xc6\x60\xf1\xa3\x2f\xc4"
"\x6c\x28\x62\xd1\x47\x4c\x42\x9b\xe4\x5c\x38\xb9\x2b\x23\xab\xb1"
"\x70\x53\x53\x22\x39\x35\x4f\xc2\x1c\x6b\xbc\x7c\x20\x29\x7f\xc7"
"\x49\x80\x51\x03\x7b\x42\x8e\x14\xf2\xab\x0d\x41\x2e\xf1\x6a\xaa"
"\x26\x00\xdc\x0f\xcb\x34\x8a\x59\x01\xcb\x33\x1d\x2c\xd8\x50\xe8"
"\x13\xc9\x05\x2d\x48\xe7\xe2\xbd\x99\x2a\xe0\x85\x82\xf8\x2b\xc8"
"\xde\xe8\x38\xd8\xe1\x07\xc7\x43\x38\xb5\xf7\x30\x64\xd3\xdc\x8e"
"\xa1\x25\x1f\x7d\xf2\x35\x5e\xfb\xac\xc5\xa4\xfa\xf3\x8b\x9a\x7f"
"\x93\xc0\x44\xb3\xd8\x03\xc6\x50\x47\xe2\xc0\x85\x0b\xec\xbc\x9c"
"\x8b\xb7\x69\x2d\x8b\xdf\xae\x92\x88\x8e\xba\xb2\x53\x48\x0a\xca"
"\x5a\x62\x00\xea\x3e\xac\x6b\xb0\xc9\xaa\x51\x2e\xcd\x7b\xf7\x81"
"\xc4\x91\x27\x6a\x3b\x68\xd2\xdc\x8e\x2b\x12\x80\xce\xf8\xaa\xf7"
"\xe4\x9c\x03\xcb\xca\x8f\x6f\xf0\x57\x88\x33\x83\xfc\xa0\x3b\xd3"
"\x90\xf8\xc7\x53\x58\xa4\x61\xff\xf1\x59\x75\xe8\x25\xa6\x93\x55"
"\x6a\xe6\xfa\xb5\x48\xce\x53\x81\xcc\xd2\xfe\x2f\x53\x16\x57\x9f"
"\x87\xa1\x50\x43\x59\x8d\x83\xa9\xee\xa3\x12\x96\x19\x85\x3a\x91"
"\x4d\x8a\x44\xa6\xb2\x3a\xf4\x7c\x80\x68\x67\xb9\x1f\x31\x88\xf8"
"\xd4\x87\x32\x36\x79\x72\x73\xda\x47\x5a\x13\xad\xcd\x9e\xcd\x26"
"\x26\x00\x25\xa5\x5d\xd0\x7a\x5e\x4b\x96\xa3\xe8\x3d\xd5\xc7\xa2"
"\x1b\x54\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20"
"\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20"
"\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20"
"\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20"
"\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20"
"\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20"
"\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20"
"\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20"
"\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20"
"\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20"
"\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20"
"\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20"
"\x20\x20\x20\x20";
static unsigned int write_00001_00000_len = 1028;
unsigned char *write_00001 = NULL;
unsigned int write_00001_len = 0;
write_00001 = cgc_append_buf(write_00001, &write_00001_len, write_00001_00000, write_00001_00000_len);
if (write_00001_len > 0) {
cgc_transmit_all(1, write_00001, write_00001_len);
}
cgc_free(write_00001);
} while (0);
do {
unsigned char *read_00000;
unsigned int read_00000_len;
unsigned int read_00000_ptr = 0;
//**** delimited read
static unsigned char read_00000_delim[] =
"\x0a";
read_00000 = NULL;
read_00000_len = 0;
int read_00000_res = cgc_delimited_read(0, &read_00000, &read_00000_len, read_00000_delim, 1);
if (read_00000_res) {} //silence unused variable warning
//**** read match data
static unsigned char match_00000_00000[] =
"\x53\x74\x61\x72\x74\x69\x6e\x67\x20\x64\x69\x73\x73\x65\x63\x74"
"\x69\x6f\x6e\x2e\x2e\x2e";
read_00000_ptr += cgc_data_match(read_00000 + read_00000_ptr, read_00000_len - read_00000_ptr, match_00000_00000, 22);
cgc_free(read_00000);
if (read_00000_ptr) {} //silence unused variable warning if any
} while (0);
do {
unsigned char *read_00001;
unsigned int read_00001_len;
unsigned int read_00001_ptr = 0;
//**** delimited read
static unsigned char read_00001_delim[] =
"\x3d\x3d\x3d\x3d\x0a";
read_00001 = NULL;
read_00001_len = 0;
int read_00001_res = cgc_delimited_read(0, &read_00001, &read_00001_len, read_00001_delim, 5);
if (read_00001_res) {} //silence unused variable warning
/* read match pcre:
.*New Packet
*/
static char read_00001_00000_regex[] =
"\x2e\x2a\x4e\x65\x77\x20\x50\x61\x63\x6b\x65\x74";
static match_result read_00001_00000_match;
pcre *read_00001_00000_pcre = cgc_init_regex(read_00001_00000_regex);
if (read_00001_00000_pcre != NULL) {
int rc = cgc_regex_match(read_00001_00000_pcre, 0, read_00001 + read_00001_ptr, read_00001_len - read_00001_ptr, &read_00001_00000_match);
if (rc > 0) {
read_00001_ptr += read_00001_00000_match.match_end - read_00001_00000_match.match_start;
}
else {
//this is a pov so what does this even mean?
//why would we quit on failed match, just keep sending stuff.
}
pcre_free(read_00001_00000_pcre);
}
else {
//this is a pov so what does this even mean?
//why would we quit on failed regex compile, just keep sending stuff.
}
cgc_free(read_00001);
if (read_00001_ptr) {} //silence unused variable warning if any
} while (0);
do {
unsigned char *read_00002;
unsigned int read_00002_len;
unsigned int read_00002_ptr = 0;
//**** delimited read
static unsigned char read_00002_delim[] =
"\x3d\x3d\x3d\x0a";
read_00002 = NULL;
read_00002_len = 0;
int read_00002_res = cgc_delimited_read(0, &read_00002, &read_00002_len, read_00002_delim, 4);
if (read_00002_res) {} //silence unused variable warning
/* read match pcre:
.*===lol
*/
static char read_00002_00000_regex[] =
"\x2e\x2a\x3d\x3d\x3d\x6c\x6f\x6c";
static match_result read_00002_00000_match;
pcre *read_00002_00000_pcre = cgc_init_regex(read_00002_00000_regex);
if (read_00002_00000_pcre != NULL) {
int rc = cgc_regex_match(read_00002_00000_pcre, 0, read_00002 + read_00002_ptr, read_00002_len - read_00002_ptr, &read_00002_00000_match);
if (rc > 0) {
read_00002_ptr += read_00002_00000_match.match_end - read_00002_00000_match.match_start;
}
else {
//this is a pov so what does this even mean?
//why would we quit on failed match, just keep sending stuff.
}
pcre_free(read_00002_00000_pcre);
}
else {
//this is a pov so what does this even mean?
//why would we quit on failed regex compile, just keep sending stuff.
}
cgc_free(read_00002);
if (read_00002_ptr) {} //silence unused variable warning if any
} while (0);
do {
unsigned char *read_00003;
unsigned int read_00003_len;
unsigned int read_00003_ptr = 0;
//**** delimited read
static unsigned char read_00003_delim[] =
"\x3d\x3d\x3d\x0a";
read_00003 = NULL;
read_00003_len = 0;
int read_00003_res = cgc_delimited_read(0, &read_00003, &read_00003_len, read_00003_delim, 4);
if (read_00003_res) {} //silence unused variable warning
/* read match pcre:
.*===Ciceronicpownie
*/
static char read_00003_00000_regex[] =
"\x2e\x2a\x3d\x3d\x3d\x43\x69\x63\x65\x72\x6f\x6e\x69\x63\x70\x6f"
"\x77\x6e\x69\x65";
static match_result read_00003_00000_match;
pcre *read_00003_00000_pcre = cgc_init_regex(read_00003_00000_regex);
if (read_00003_00000_pcre != NULL) {
int rc = cgc_regex_match(read_00003_00000_pcre, 0, read_00003 + read_00003_ptr, read_00003_len - read_00003_ptr, &read_00003_00000_match);
if (rc > 0) {
read_00003_ptr += read_00003_00000_match.match_end - read_00003_00000_match.match_start;
}
else {
//this is a pov so what does this even mean?
//why would we quit on failed match, just keep sending stuff.
}
pcre_free(read_00003_00000_pcre);
}
else {
//this is a pov so what does this even mean?
//why would we quit on failed regex compile, just keep sending stuff.
}
cgc_free(read_00003);
if (read_00003_ptr) {} //silence unused variable warning if any
} while (0);
do {
unsigned char *read_00004;
unsigned int read_00004_len;
unsigned int read_00004_ptr = 0;
//**** delimited read
static unsigned char read_00004_delim[] =
"\x3d\x3d\x3d\x0a";
read_00004 = NULL;
read_00004_len = 0;
int read_00004_res = cgc_delimited_read(0, &read_00004, &read_00004_len, read_00004_delim, 4);
if (read_00004_res) {} //silence unused variable warning
/* read match pcre:
.*===purgaNycticorax
*/
static char read_00004_00000_regex[] =
"\x2e\x2a\x3d\x3d\x3d\x70\x75\x72\x67\x61\x4e\x79\x63\x74\x69\x63"
"\x6f\x72\x61\x78";
static match_result read_00004_00000_match;
pcre *read_00004_00000_pcre = cgc_init_regex(read_00004_00000_regex);
if (read_00004_00000_pcre != NULL) {
int rc = cgc_regex_match(read_00004_00000_pcre, 0, read_00004 + read_00004_ptr, read_00004_len - read_00004_ptr, &read_00004_00000_match);
if (rc > 0) {
read_00004_ptr += read_00004_00000_match.match_end - read_00004_00000_match.match_start;
}
else {
//this is a pov so what does this even mean?
//why would we quit on failed match, just keep sending stuff.
}
pcre_free(read_00004_00000_pcre);
}
else {
//this is a pov so what does this even mean?
//why would we quit on failed regex compile, just keep sending stuff.
}
cgc_free(read_00004);
if (read_00004_ptr) {} //silence unused variable warning if any
} while (0);
do {
unsigned char *read_00005;
unsigned int read_00005_len;
unsigned int read_00005_ptr = 0;
//**** delimited read
static unsigned char read_00005_delim[] =
"\x3d\x3d\x3d\x0a";
read_00005 = NULL;
read_00005_len = 0;
int read_00005_res = cgc_delimited_read(0, &read_00005, &read_00005_len, read_00005_delim, 4);
if (read_00005_res) {} //silence unused variable warning
/* read match pcre:
.*Dissection finished
*/
static char read_00005_00000_regex[] =
"\x2e\x2a\x44\x69\x73\x73\x65\x63\x74\x69\x6f\x6e\x20\x66\x69\x6e"
"\x69\x73\x68\x65\x64";
static match_result read_00005_00000_match;
pcre *read_00005_00000_pcre = cgc_init_regex(read_00005_00000_regex);
if (read_00005_00000_pcre != NULL) {
int rc = cgc_regex_match(read_00005_00000_pcre, 0, read_00005 + read_00005_ptr, read_00005_len - read_00005_ptr, &read_00005_00000_match);
if (rc > 0) {
read_00005_ptr += read_00005_00000_match.match_end - read_00005_00000_match.match_start;
}
else {
//this is a pov so what does this even mean?
//why would we quit on failed match, just keep sending stuff.
}
pcre_free(read_00005_00000_pcre);
}
else {
//this is a pov so what does this even mean?
//why would we quit on failed regex compile, just keep sending stuff.
}
cgc_free(read_00005);
if (read_00005_ptr) {} //silence unused variable warning if any
} while (0);
}
|
cf37312504af64e126c53626bff35689126e8425
|
ae41a6e8b1033015a5a622e4e7b5f90453632741
|
/tests/slab_2/main.c
|
d53ea5166315e0ec34ba11e34483c9d4df01368e
|
[
"BSD-2-Clause"
] |
permissive
|
PikoRT/pikoRT
|
8ac985e89fd640e965f59a651366b67ac996ceea
|
3783e0d9c7fe3533a73db3a91b0caf9817cc78de
|
refs/heads/master
| 2022-11-27T16:28:24.808521
| 2022-11-24T19:58:32
| 2022-11-24T19:58:32
| 99,430,730
| 127
| 40
|
NOASSERTION
| 2022-11-24T19:58:33
| 2017-08-05T15:20:13
|
C
|
UTF-8
|
C
| false
| false
| 1,064
|
c
|
main.c
|
/* test for cache creation, allocation, destruction */
#include <kernel/kernel.h>
#include <kernel/mm/page.h>
#include <kernel/mm/slab.h>
#include "unit.h"
struct foo {
int a;
int b;
};
int main(void)
{
unsigned long hash;
struct kmem_cache *cache = KMEM_CACHE(struct foo, "cache-foo");
if (!cache) {
printk("error: Cannot create cache\n");
TEST_EXIT(1);
}
hash = page_alloc_signature();
struct foo *fp[40];
for (int i = 0; i < 40; i++) {
fp[i] = kmem_cache_alloc(cache, CACHE_OPT_NONE);
fp[i]->a = i;
}
if (page_alloc_signature() == hash) {
printk("error: No memory allocated\n");
TEST_EXIT(1);
}
for (int i = 0; i < 40; i++) {
if (fp[i]->a != i) {
printk("error: Address allocated multiple times\n");
TEST_EXIT(1);
}
kmem_cache_free(cache, fp[i]);
}
if (page_alloc_signature() != hash) {
printk("error: Memory not correctly restored\n");
TEST_EXIT(1);
}
TEST_EXIT(0);
}
|
7456de5a9e63b9d29e3b9a9f0cb91d7e04f80f94
|
0744dcc5394cebf57ebcba343747af6871b67017
|
/os/arch/arm/src/imx6/hardware/imx_gpio.h
|
e4ccbc6069ccac771bae53ab1b2bac74cbeeb519
|
[
"GPL-1.0-or-later",
"BSD-3-Clause",
"ISC",
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-other-permissive",
"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
| 9,299
|
h
|
imx_gpio.h
|
/****************************************************************************
*
* Copyright 2023 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.
*
****************************************************************************/
/****************************************************************************
* arch/arm/src/imx6/hardware/imx_gpio.h
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
/* Reference:
* "i.MX 6Dual/6Quad ApplicationsProcessor Reference Manual",
* Document Number IMX6DQRM, Rev. 3, 07/2015, FreeScale.
*/
#ifndef __ARCH_ARM_SRC_IMX6_HARDWARE_IMX_GPIO_H
#define __ARCH_ARM_SRC_IMX6_HARDWARE_IMX_GPIO_H
/****************************************************************************
* Included Files
****************************************************************************/
#include <tinyara/config.h>
#include "hardware/imx_memorymap.h"
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
#define GPIO1 0 /* Port 1 index */
#define GPIO2 1 /* Port 2 index */
#define GPIO3 2 /* Port 3 index */
#define GPIO4 3 /* Port 4 index */
#define GPIO5 4 /* Port 5 index */
#define GPIO6 5 /* Port 6 index */
#define GPIO7 6 /* Port 7 index */
#define IMX_GPIO_NPORTS 7 /* Seven total ports */
#define IMX_GPIO_NPINS 32 /* Up to 32 pins per port */
/* GPIO Register Offsets ****************************************************/
#define IMX_GPIO_DR_OFFSET 0x0000 /* Data Register */
#define IMX_GPIO_GDIR_OFFSET 0x0004 /* Data Direction Register */
#define IMX_GPIO_PSR_OFFSET 0x0008 /* Pad Status Register */
#define IMX_GPIO_ICR1_OFFSET 0x000c /* Interrupt Configuration Register 1 */
#define IMX_GPIO_ICR2_OFFSET 0x0010 /* Interrupt Configuration Register 2 */
#define IMX_GPIO_IMR_OFFSET 0x0014 /* Interrupt Mask Register */
#define IMX_GPIO_ISR_OFFSET 0x0018 /* Interrupt Status Register */
#define IMX_GPIO_EDGE_OFFSET 0x001c /* Interrupt Status Register */
/* GPIO Register Addresses **************************************************/
#define IMX_GPIO_DR(n) (IMX_GPIO_VBASE(n)+IMX_GPIO_DR_OFFSET)
#define IMX_GPIO_GDIR(n) (IMX_GPIO_VBASE(n)+IMX_GPIO_GDIR_OFFSET)
#define IMX_GPIO_PSR(n) (IMX_GPIO_VBASE(n)+IMX_GPIO_PSR_OFFSET)
#define IMX_GPIO_ICR1(n) (IMX_GPIO_VBASE(n)+IMX_GPIO_ICR1_OFFSET)
#define IMX_GPIO_ICR2(n) (IMX_GPIO_VBASE(n)+IMX_GPIO_ICR2_OFFSET)
#define IMX_GPIO_IMR(n) (IMX_GPIO_VBASE(n)+IMX_GPIO_IMR_OFFSET)
#define IMX_GPIO_ISR(n) (IMX_GPIO_VBASE(n)+IMX_GPIO_ISR_OFFSET)
#define IMX_GPIO_EDGE(n) (IMX_GPIO_VBASE(n)+IMX_GPIO_EDGE_OFFSET)
#define IMX_GPIO1_DR (IMX_GPIO1_VBASE+IMX_GPIO_DR_OFFSET)
#define IMX_GPIO1_GDIR (IMX_GPIO1_VBASE+IMX_GPIO_GDIR_OFFSET)
#define IMX_GPIO1_PSR (IMX_GPIO1_VBASE+IMX_GPIO_PSR_OFFSET)
#define IMX_GPIO1_ICR1 (IMX_GPIO1_VBASE+IMX_GPIO_ICR1_OFFSET)
#define IMX_GPIO1_ICR2 (IMX_GPIO1_VBASE+IMX_GPIO_ICR2_OFFSET)
#define IMX_GPIO1_IMR (IMX_GPIO1_VBASE+IMX_GPIO_IMR_OFFSET)
#define IMX_GPIO1_ISR (IMX_GPIO1_VBASE+IMX_GPIO_ISR_OFFSET)
#define IMX_GPIO1_EDGE (IMX_GPIO1_VBASE+IMX_GPIO_EDGE_OFFSET)
#define IMX_GPIO2_DR (IMX_GPIO2_VBASE+IMX_GPIO_DR_OFFSET)
#define IMX_GPIO2_GDIR (IMX_GPIO2_VBASE+IMX_GPIO_GDIR_OFFSET)
#define IMX_GPIO2_PSR (IMX_GPIO2_VBASE+IMX_GPIO_PSR_OFFSET)
#define IMX_GPIO2_ICR1 (IMX_GPIO2_VBASE+IMX_GPIO_ICR1_OFFSET)
#define IMX_GPIO2_ICR2 (IMX_GPIO2_VBASE+IMX_GPIO_ICR2_OFFSET)
#define IMX_GPIO2_IMR (IMX_GPIO2_VBASE+IMX_GPIO_IMR_OFFSET)
#define IMX_GPIO2_ISR (IMX_GPIO2_VBASE+IMX_GPIO_ISR_OFFSET)
#define IMX_GPIO2_EDGE (IMX_GPIO2_VBASE+IMX_GPIO_EDGE_OFFSET)
#define IMX_GPIO3_DR (IMX_GPIO3_VBASE+IMX_GPIO_DR_OFFSET)
#define IMX_GPIO3_GDIR (IMX_GPIO3_VBASE+IMX_GPIO_GDIR_OFFSET)
#define IMX_GPIO3_PSR (IMX_GPIO3_VBASE+IMX_GPIO_PSR_OFFSET)
#define IMX_GPIO3_ICR1 (IMX_GPIO3_VBASE+IMX_GPIO_ICR1_OFFSET)
#define IMX_GPIO3_ICR2 (IMX_GPIO3_VBASE+IMX_GPIO_ICR2_OFFSET)
#define IMX_GPIO3_IMR (IMX_GPIO3_VBASE+IMX_GPIO_IMR_OFFSET)
#define IMX_GPIO3_ISR (IMX_GPIO3_VBASE+IMX_GPIO_ISR_OFFSET)
#define IMX_GPIO3_EDGE (IMX_GPIO3_VBASE+IMX_GPIO_EDGE_OFFSET)
#define IMX_GPIO4_DR (IMX_GPIO4_VBASE+IMX_GPIO_DR_OFFSET)
#define IMX_GPIO4_GDIR (IMX_GPIO4_VBASE+IMX_GPIO_GDIR_OFFSET)
#define IMX_GPIO4_PSR (IMX_GPIO4_VBASE+IMX_GPIO_PSR_OFFSET)
#define IMX_GPIO4_ICR1 (IMX_GPIO4_VBASE+IMX_GPIO_ICR1_OFFSET)
#define IMX_GPIO4_ICR2 (IMX_GPIO4_VBASE+IMX_GPIO_ICR2_OFFSET)
#define IMX_GPIO4_IMR (IMX_GPIO4_VBASE+IMX_GPIO_IMR_OFFSET)
#define IMX_GPIO4_ISR (IMX_GPIO4_VBASE+IMX_GPIO_ISR_OFFSET)
#define IMX_GPIO4_EDGE (IMX_GPIO4_VBASE+IMX_GPIO_EDGE_OFFSET)
#define IMX_GPIO5_DR (IMX_GPIO5_VBASE+IMX_GPIO_DR_OFFSET)
#define IMX_GPIO5_GDIR (IMX_GPIO5_VBASE+IMX_GPIO_GDIR_OFFSET)
#define IMX_GPIO5_PSR (IMX_GPIO5_VBASE+IMX_GPIO_PSR_OFFSET)
#define IMX_GPIO5_ICR1 (IMX_GPIO5_VBASE+IMX_GPIO_ICR1_OFFSET)
#define IMX_GPIO5_ICR2 (IMX_GPIO5_VBASE+IMX_GPIO_ICR2_OFFSET)
#define IMX_GPIO5_IMR (IMX_GPIO5_VBASE+IMX_GPIO_IMR_OFFSET)
#define IMX_GPIO5_ISR (IMX_GPIO5_VBASE+IMX_GPIO_ISR_OFFSET)
#define IMX_GPIO5_EDGE (IMX_GPIO5_VBASE+IMX_GPIO_EDGE_OFFSET)
#define IMX_GPIO6_DR (IMX_GPIO6_VBASE+IMX_GPIO_DR_OFFSET)
#define IMX_GPIO6_GDIR (IMX_GPIO6_VBASE+IMX_GPIO_GDIR_OFFSET)
#define IMX_GPIO6_PSR (IMX_GPIO6_VBASE+IMX_GPIO_PSR_OFFSET)
#define IMX_GPIO6_ICR1 (IMX_GPIO6_VBASE+IMX_GPIO_ICR1_OFFSET)
#define IMX_GPIO6_ICR2 (IMX_GPIO6_VBASE+IMX_GPIO_ICR2_OFFSET)
#define IMX_GPIO6_IMR (IMX_GPIO6_VBASE+IMX_GPIO_IMR_OFFSET)
#define IMX_GPIO6_ISR (IMX_GPIO6_VBASE+IMX_GPIO_ISR_OFFSET)
#define IMX_GPIO6_EDGE (IMX_GPIO6_VBASE+IMX_GPIO_EDGE_OFFSET)
#define IMX_GPIO7_DR (IMX_GPIO7_VBASE+IMX_GPIO_DR_OFFSET)
#define IMX_GPIO7_GDIR (IMX_GPIO7_VBASE+IMX_GPIO_GDIR_OFFSET)
#define IMX_GPIO7_PSR (IMX_GPIO7_VBASE+IMX_GPIO_PSR_OFFSET)
#define IMX_GPIO7_ICR1 (IMX_GPIO7_VBASE+IMX_GPIO_ICR1_OFFSET)
#define IMX_GPIO7_ICR2 (IMX_GPIO7_VBASE+IMX_GPIO_ICR2_OFFSET)
#define IMX_GPIO7_IMR (IMX_GPIO7_VBASE+IMX_GPIO_IMR_OFFSET)
#define IMX_GPIO7_ISR (IMX_GPIO7_VBASE+IMX_GPIO_ISR_OFFSET)
#define IMX_GPIO7_EDGE (IMX_GPIO7_VBASE+IMX_GPIO_EDGE_OFFSET)
/* GPIO Register Bit Definitions ********************************************/
/* Most registers are laid out simply with one bit per pin */
#define GPIO_PIN(n) (1 << (n)) /* Bit n: Pin n, n=0-31 */
/* GPIO interrupt configuration register 1/2 */
#define GPIO_ICR_INDEX(n) (((n) >> 4) & 1)
#define GPIO_ICR_OFFSET(n) (GPIO_ICR1_OFFSET + (GPIO_ICR_INDEX(n) << 2))
#define GPIO_ICR_LOWLEVEL 0 /* Interrupt is low-level sensitive */
#define GPIO_ICR_HIGHLEVEL 1 /* Interrupt is high-level sensitive */
#define GPIO_ICR_RISINGEDGE 2 /* Interrupt is rising-edge sensitive */
#define GPIO_ICR_FALLINGEDGE 3 /* Interrupt is falling-edge sensitive */
#define GPIO_ICR_SHIFT(n) (((n) & 15) << 1)
#define GPIO_ICR_MASK(n) (3 << GPIO_ICR_SHIFT(n))
#define GPIO_ICR(i,n) ((uint32_t)(i) << GPIO_ICR_SHIFT(n))
#endif /* __ARCH_ARM_SRC_IMX6_HARDWARE_IMX_GPIO_H */
|
a59d5c10e46625ea90a5ea6b05234d22f30a9dd8
|
526b17ad25eec622b8f266034df3506ca1580ce6
|
/cups/getdevices.c
|
a3554064094845fa9f48304eb6372e4edf1440ed
|
[
"LLVM-exception",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"EPL-1.0",
"GPL-2.0-only",
"LGPL-2.0-only"
] |
permissive
|
apple/cups
|
906903c936f9ec702e50dcd9971ec71af90a56fb
|
ec055da6794984133d48cc376f04e10af62b64dc
|
refs/heads/master
| 2023-08-24T17:53:09.249969
| 2022-06-27T16:22:46
| 2022-06-27T16:22:46
| 44,137,852
| 1,875
| 570
|
Apache-2.0
| 2023-01-19T21:23:20
| 2015-10-12T22:33:18
|
C
|
UTF-8
|
C
| false
| false
| 7,756
|
c
|
getdevices.c
|
/*
* cupsGetDevices implementation for CUPS.
*
* Copyright 2008-2016 by Apple Inc.
*
* Licensed under Apache License v2.0. See the file "LICENSE" for more information.
*/
/*
* Include necessary headers...
*/
#include "cups-private.h"
#include "debug-internal.h"
#include "adminutil.h"
/*
* 'cupsGetDevices()' - Get available printer devices.
*
* This function sends a CUPS-Get-Devices request and streams the discovered
* devices to the specified callback function. The "timeout" parameter controls
* how long the request lasts, while the "include_schemes" and "exclude_schemes"
* parameters provide comma-delimited lists of backends to include or omit from
* the request respectively.
*
* This function is deprecated with the IPP printer discovery functionality
* being provided by the @link cupsEnumDests@ and @cupsGetDests@ functions.
*
* @deprecated@
*/
ipp_status_t /* O - Request status - @code IPP_OK@ on success. */
cupsGetDevices(
http_t *http, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
int timeout, /* I - Timeout in seconds or @code CUPS_TIMEOUT_DEFAULT@ */
const char *include_schemes, /* I - Comma-separated URI schemes to include or @code CUPS_INCLUDE_ALL@ */
const char *exclude_schemes, /* I - Comma-separated URI schemes to exclude or @code CUPS_EXCLUDE_NONE@ */
cups_device_cb_t callback, /* I - Callback function */
void *user_data) /* I - User data pointer */
{
ipp_t *request, /* CUPS-Get-Devices request */
*response; /* CUPS-Get-Devices response */
ipp_attribute_t *attr; /* Current attribute */
const char *device_class, /* device-class value */
*device_id, /* device-id value */
*device_info, /* device-info value */
*device_location, /* device-location value */
*device_make_and_model, /* device-make-and-model value */
*device_uri; /* device-uri value */
int blocking; /* Current blocking-IO mode */
cups_option_t option; /* in/exclude-schemes option */
http_status_t status; /* HTTP status of request */
ipp_state_t state; /* IPP response state */
/*
* Range check input...
*/
DEBUG_printf(("cupsGetDevices(http=%p, timeout=%d, include_schemes=\"%s\", exclude_schemes=\"%s\", callback=%p, user_data=%p)", (void *)http, timeout, include_schemes, exclude_schemes, (void *)callback, user_data));
if (!callback)
return (IPP_STATUS_ERROR_INTERNAL);
if (!http)
http = _cupsConnect();
if (!http)
return (IPP_STATUS_ERROR_SERVICE_UNAVAILABLE);
/*
* Create a CUPS-Get-Devices request...
*/
request = ippNewRequest(IPP_OP_CUPS_GET_DEVICES);
if (timeout > 0)
ippAddInteger(request, IPP_TAG_OPERATION, IPP_TAG_INTEGER, "timeout",
timeout);
if (include_schemes)
{
option.name = "include-schemes";
option.value = (char *)include_schemes;
cupsEncodeOptions2(request, 1, &option, IPP_TAG_OPERATION);
}
if (exclude_schemes)
{
option.name = "exclude-schemes";
option.value = (char *)exclude_schemes;
cupsEncodeOptions2(request, 1, &option, IPP_TAG_OPERATION);
}
/*
* Send the request and do any necessary authentication...
*/
do
{
DEBUG_puts("2cupsGetDevices: Sending request...");
status = cupsSendRequest(http, request, "/", ippLength(request));
DEBUG_puts("2cupsGetDevices: Waiting for response status...");
while (status == HTTP_STATUS_CONTINUE)
status = httpUpdate(http);
if (status != HTTP_STATUS_OK)
{
httpFlush(http);
if (status == HTTP_STATUS_UNAUTHORIZED)
{
/*
* See if we can do authentication...
*/
DEBUG_puts("2cupsGetDevices: Need authorization...");
if (!cupsDoAuthentication(http, "POST", "/"))
httpReconnect2(http, 30000, NULL);
else
{
status = HTTP_STATUS_CUPS_AUTHORIZATION_CANCELED;
break;
}
}
#ifdef HAVE_SSL
else if (status == HTTP_STATUS_UPGRADE_REQUIRED)
{
/*
* Force a reconnect with encryption...
*/
DEBUG_puts("2cupsGetDevices: Need encryption...");
if (!httpReconnect2(http, 30000, NULL))
httpEncryption(http, HTTP_ENCRYPTION_REQUIRED);
}
#endif /* HAVE_SSL */
}
}
while (status == HTTP_STATUS_UNAUTHORIZED ||
status == HTTP_STATUS_UPGRADE_REQUIRED);
DEBUG_printf(("2cupsGetDevices: status=%d", status));
ippDelete(request);
if (status != HTTP_STATUS_OK)
{
_cupsSetHTTPError(status);
return (cupsLastError());
}
/*
* Read the response in non-blocking mode...
*/
blocking = httpGetBlocking(http);
httpBlocking(http, 0);
response = ippNew();
device_class = NULL;
device_id = NULL;
device_info = NULL;
device_location = "";
device_make_and_model = NULL;
device_uri = NULL;
attr = NULL;
DEBUG_puts("2cupsGetDevices: Reading response...");
do
{
if ((state = ippRead(http, response)) == IPP_STATE_ERROR)
break;
DEBUG_printf(("2cupsGetDevices: state=%d, response->last=%p", state, (void *)response->last));
if (!response->attrs)
continue;
while (attr != response->last)
{
if (!attr)
attr = response->attrs;
else
attr = attr->next;
DEBUG_printf(("2cupsGetDevices: attr->name=\"%s\", attr->value_tag=%d",
attr->name, attr->value_tag));
if (!attr->name)
{
if (device_class && device_id && device_info && device_make_and_model &&
device_uri)
(*callback)(device_class, device_id, device_info,
device_make_and_model, device_uri, device_location,
user_data);
device_class = NULL;
device_id = NULL;
device_info = NULL;
device_location = "";
device_make_and_model = NULL;
device_uri = NULL;
}
else if (!strcmp(attr->name, "device-class") &&
attr->value_tag == IPP_TAG_KEYWORD)
device_class = attr->values[0].string.text;
else if (!strcmp(attr->name, "device-id") &&
attr->value_tag == IPP_TAG_TEXT)
device_id = attr->values[0].string.text;
else if (!strcmp(attr->name, "device-info") &&
attr->value_tag == IPP_TAG_TEXT)
device_info = attr->values[0].string.text;
else if (!strcmp(attr->name, "device-location") &&
attr->value_tag == IPP_TAG_TEXT)
device_location = attr->values[0].string.text;
else if (!strcmp(attr->name, "device-make-and-model") &&
attr->value_tag == IPP_TAG_TEXT)
device_make_and_model = attr->values[0].string.text;
else if (!strcmp(attr->name, "device-uri") &&
attr->value_tag == IPP_TAG_URI)
device_uri = attr->values[0].string.text;
}
}
while (state != IPP_STATE_DATA);
DEBUG_printf(("2cupsGetDevices: state=%d, response->last=%p", state, (void *)response->last));
if (device_class && device_id && device_info && device_make_and_model &&
device_uri)
(*callback)(device_class, device_id, device_info,
device_make_and_model, device_uri, device_location, user_data);
/*
* Set the IPP status and return...
*/
httpBlocking(http, blocking);
httpFlush(http);
attr = ippFindAttribute(response, "status-message", IPP_TAG_TEXT);
DEBUG_printf(("cupsGetDevices: status-code=%s, status-message=\"%s\"",
ippErrorString(response->request.status.status_code),
attr ? attr->values[0].string.text : ""));
_cupsSetError(response->request.status.status_code,
attr ? attr->values[0].string.text : ippErrorString(response->request.status.status_code), 0);
ippDelete(response);
return (cupsLastError());
}
|
c361a8124fe92449c006198176a186ed2861dfc8
|
19a9f2c19bcb81c4a14ba17831d3098de7731fb5
|
/ncarview/src/lib/libctrans/devices.c
|
630afad0408bb4e2632f63aa3bdf73579681ee22
|
[
"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
| 23,686
|
c
|
devices.c
|
/*
* $Id: devices.c,v 1.17 2008-07-27 03:18:43 haley Exp $
*/
/************************************************************************
* *
* The use of this Software is governed by a License Agreement. *
* *
************************************************************************/
/***********************************************************************
* *
* Copyright (C) 1990 *
* University Corporation for Atmospheric Research *
* All Rights Reserved *
* *
* NCAR View V3.01 - UNIX Release *
* *
***********************************************************************/
/*
* devices.c:
*
* Author John Clyne (clyne@redcloud.ucar.edu)
*
* Date Mon Nov 28 14:45:24 MST 1988
*
* This file contains the devices ctrans supports. To
* add a new device begin here by adding the device and its functions
* to the jump table
*/
#include <stdio.h>
#include <ncarg/cgm_tools.h>
#include "cgmc.h"
#define DEVICES
#include "devices.h"
int devicenum = (sizeof(devices)/sizeof(struct device));
/*
* Declarations for all the function in the Jump Table
*/
/*
* The functions for the GraphCap and FontCap processing
* also the funtions for setting the default-table values.
*/
/* Class 0 */
int BegMF(), EndMF(), BegPic(), BegPicBody(), EndPic(), ClearDevice();
/* Class 1 */
int MFVersion(), MFDesc(), VDCType(), IntergerPrec(), RealPrec(),
IndexPrec(),
ColrPrec(), ColrIndexPrec(), MaxColrIndex(), ColrValueExt(), MFElemList(),
MFDefaults(), FontList(), CharSetList(), CharCoding();
/* Class 2 */
int ScaleMode(), ColrMode(), LineWidthMode(), MarkerSizeMode(), EdgeWidthMode(),
VDCExt(), BackColr();
/* Class 3 */
int VDCIntergerPrec(), VDCRealPrec(), AuxColr(), Transparency(), ClipRect(),
Clip();
/* Class 4 */
int PolyLine(), DisjtLine(), PolyMarker(), Text(), RestrText(), ApndText(),
Polygon(), PolygonSet(), CellArray(), GDP(), Rect(), Circle(), Arc3Pt(),
Arc3PtClose(), ArcCtr(), ArcCtrClose(), Ellipse(), EllipArc(),
EllipArcClose();
/* Class 5 */
int LineIndex(), LineType(), LineWidth(), LineColr(), MarkerIndex(),
MarkerType(), MarkerSize(), MarkerColr(), TextIndex(), TextFontIndex(),
TextPrec(), CharExpan(), CharSpace(), TextColr(), CharHeight(), CharOri(),
TextPath(), TextAlign(), CharSetIndex(), AltCharSetIndex(), FillIndex(),
IntStyle(), FillColr(), HatchIndex(), PatIndex(), EdgeIndex(), EdgeType(),
EdgeWidth(), EdgeColr(), EdgeVis(), FillRefPt(), PatTable(), PatSize(),
ColrTable(), ASF();
/* Class 6 */
int Escape();
/* Class 7 */
int Message(), ApplData();
/*
* raster
*
*/
/* Class 0 */
int Ras_BegMF(), Ras_EndMF(), Ras_BegPic(), Ras_BegPicBody(),
Ras_EndPic(), Ras_ClearDevice();
/* Class 4 */
int Ras_PolyMarker(), Ras_CellArray();
/* Class 5 */
#ifdef X11
/*
* X11
*
* The functions that inturn call the X11 library
* note: some functions do not exist because the interface
* uses the gcap version. This is true most often when a CGM
* command sets defaults
*/
/* Class 0 */
int X11_BegMF(), X11_EndMF(), X11_BegPic(), X11_BegPicBody(), X11_EndPic(),
X11_ClearDevice();
/* Class 1 */
int X11_MFDesc(), X11_MFElemList(), X11_MFDefaults(),
X11_CharSetList();
/* Class 2 */
/* Class 3 */
int X11_AuxColr();
/* Class 4 */
int X11_PolyLine(), X11_DisjtLine(), X11_PolyMarker(), X11_RestrText(),
X11_ApndText(), X11_Polygon(), X11_PolygonSet(), X11_CellArray(), X11_GDP(),
X11_Rect(), X11_Circle(), X11_Arc3Pt(), X11_Arc3PtClose(), X11_ArcCtr(),
X11_ArcCtrClose(), X11_Ellipse(), X11_EllipArc(), X11_EllipArcClose();
/* Class 5 */
/* Class 6 */
int X11_Escape();
/* Class 7 */
int X11_Message(), X11_ApplData();
#endif /* X11 */
#ifdef CTXT
/*
* The functions for the Clear Text driver
*/
/* Class 0 */
int CTXT_NoOp(), CTXT_BegMF(), CTXT_EndMF(), CTXT_BegPic(),
CTXT_BegPicBody(), CTXT_EndPic(), CTXT_ClearDevice();
/* Class 1 */
int CTXT_MFVersion(), CTXT_MFDesc(), CTXT_VDCType(),CTXT_IntergerPrec(),
CTXT_RealPrec(), CTXT_IndexPrec(), CTXT_ColrPrec(),
CTXT_ColrIndexPrec(), CTXT_MaxColrIndex(), CTXT_ColrValueExt(),
CTXT_MFElemList(), CTXT_MFDefaults(), CTXT_FontList(),
CTXT_CharSetList(), CTXT_CharCoding();
/* Class 2 */
int CTXT_ScaleMode(), CTXT_ColrMode(), CTXT_LineWidthMode(),
CTXT_MarkerSizeMode(), CTXT_EdgeWidthMode(), CTXT_VDCExt(),
CTXT_BackColr();
/* Class 3 */
int CTXT_VDCIntergerPrec(), CTXT_VDCRealPrec(), CTXT_AuxColr(),
CTXT_Transparency(), CTXT_ClipRect(), CTXT_Clip();
/* Class 4 */
int CTXT_PolyLine(), CTXT_DisjtLine(), CTXT_PolyMarker(), CTXT_Text(),
CTXT_RestrText(), CTXT_ApndText(), CTXT_Polygon(),
CTXT_PolygonSet(), CTXT_CellArray(), CTXT_GDP(), CTXT_Rect(),
CTXT_Circle(), CTXT_Arc3Pt(), CTXT_Arc3PtClose(), CTXT_ArcCtr(),
CTXT_ArcCtrClose(), CTXT_Ellipse(), CTXT_EllipArc(),
CTXT_EllipArcClose();
/* Class 5 */
int CTXT_LineIndex(), CTXT_LineType(), CTXT_LineWidth(),CTXT_LineColr(),
CTXT_MarkerIndex(), CTXT_MarkerType(), CTXT_MarkerSize(),
CTXT_MarkerColr(), CTXT_TextIndex(), CTXT_TextFontIndex(),
CTXT_TextPrec(), CTXT_CharExpan(), CTXT_CharSpace(),CTXT_TextColr(),
CTXT_CharHeight(), CTXT_CharOri(), CTXT_TextPath(),CTXT_TextAlign(),
CTXT_CharSetIndex(), CTXT_AltCharSetIndex(), CTXT_FillIndex(),
CTXT_IntStyle(), CTXT_FillColr(), CTXT_HatchIndex(),CTXT_PatIndex(),
CTXT_EdgeIndex(), CTXT_EdgeType(), CTXT_EdgeWidth(),CTXT_EdgeColr(),
CTXT_EdgeVis(), CTXT_FillRefPt(), CTXT_PatTable(), CTXT_PatSize(),
CTXT_ColrTable(), CTXT_ASF();
/* Class 6 */
int CTXT_Escape();
/* Class 7 */
int CTXT_Message(), CTXT_ApplData();
#endif /* CTXT */
#ifdef SunV
/*
*
* The Sun SunView driver
*
*/
/* class 1 */
int SunV_BegMF(), SunV_EndMF(), SunV_BegPic(), SunV_BegPicBody(),
SunV_EndPic(), SunV_ClearDevice();
/* Class 4 */
int SunV_PolyLine(), SunV_PolyMarker(), SunV_Polygon(), SunV_CellArray();
/* Class 5 */
int SunV_ColrTable();
#endif
#ifdef SunR
/*
*
* The Sun raster filter
*
*/
/* class 1 */
int SunR_BegMF(), SunR_EndMF(), SunR_BegPic(), SunR_BegPicBody(),
SunR_EndPic(), SunR_ClearDevice();
/* Class 4 */
int SunR_PolyLine(), SunR_PolyMarker(), SunR_Polygon(), SunR_CellArray();
/* Class 5 */
int SunR_ColrTable();
#endif
/*ARGSUSED*/
int noop(c)
CGMC *c;
{
return(0);
}
/*
* The Jumptable
*/
int (*cmdtab[][MAXCLASS+1][MAXFUNCPERCLASS+1])() = {
{
/* Class 0 */
{
noop, BegMF, EndMF, BegPic, BegPicBody,
EndPic, ClearDevice, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL,
},
/* Class 1 */
{
NULL, MFVersion, MFDesc, VDCType, IntergerPrec,
RealPrec, IndexPrec, ColrPrec, ColrIndexPrec, MaxColrIndex,
ColrValueExt, MFElemList, MFDefaults, FontList, CharSetList,
CharCoding, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
},
/* Class 2 */
{
NULL, ScaleMode, ColrMode, LineWidthMode, MarkerSizeMode,
EdgeWidthMode, VDCExt, BackColr, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
},
/* Class 3 */
{
NULL, VDCIntergerPrec, VDCRealPrec, AuxColr, Transparency,
ClipRect, Clip, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
},
/* Class 4 */
{
NULL, PolyLine, DisjtLine, PolyMarker, Text,
RestrText, ApndText, Polygon, PolygonSet, CellArray,
GDP, Rect, Circle, Arc3Pt, Arc3PtClose,
ArcCtr, ArcCtrClose, Ellipse, EllipArc, EllipArcClose,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
},
/* Class 5 */
{
NULL, LineIndex, LineType, LineWidth, LineColr,
MarkerIndex, MarkerType, MarkerSize, MarkerColr, TextIndex,
TextFontIndex, TextPrec, CharExpan, CharSpace, TextColr,
CharHeight, CharOri, TextPath, TextAlign, CharSetIndex,
AltCharSetIndex, FillIndex, IntStyle, FillColr, HatchIndex,
PatIndex, EdgeIndex, EdgeType, EdgeWidth, EdgeColr,
EdgeVis, FillRefPt, PatTable, PatSize, ColrTable,
ASF,
},
/* Class 6 */
{
NULL, Escape, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
},
/* Class 7 */
{
NULL, Message, ApplData, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
}
},
/* The functions */
{
/* Class 0 */
{
noop, Ras_BegMF, Ras_EndMF, Ras_BegPic, Ras_BegPicBody,
Ras_EndPic, Ras_ClearDevice, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
},
/* Class 1 */
{
NULL, MFVersion, MFDesc, VDCType, IntergerPrec,
RealPrec, IndexPrec,ColrPrec,ColrIndexPrec,MaxColrIndex,
ColrValueExt,MFElemList,MFDefaults,FontList,
CharSetList, CharCoding, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
},
/* Class 2 */
{
NULL, ScaleMode, ColrMode, LineWidthMode, MarkerSizeMode,
EdgeWidthMode, VDCExt, BackColr, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
},
/* Class 3 */
{
NULL, VDCIntergerPrec, VDCRealPrec, AuxColr, Transparency,
ClipRect, Clip, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
},
/* Class 4 */
{
NULL, PolyLine, DisjtLine, Ras_PolyMarker, Text,
RestrText, ApndText, Polygon, PolygonSet, Ras_CellArray,
GDP, Rect, Circle, Arc3Pt, Arc3PtClose,
ArcCtr, ArcCtrClose, Ellipse, EllipArc, EllipArcClose,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
},
/* Class 5 */
{
NULL, LineIndex, LineType, LineWidth, LineColr,
MarkerIndex,MarkerType,MarkerSize,MarkerColr,
TextIndex, TextFontIndex, TextPrec, CharExpan,
CharSpace, TextColr, CharHeight, CharOri,
TextPath, TextAlign, CharSetIndex, AltCharSetIndex,
FillIndex,IntStyle,FillColr,HatchIndex,
PatIndex, EdgeIndex, EdgeType, EdgeWidth, EdgeColr,
EdgeVis, FillRefPt, PatTable, PatSize, ColrTable,
ASF,
},
/* Class 6 */
{
NULL, Escape, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
},
/* Class 7 */
{
NULL, Message, ApplData, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
}
},
#ifdef X11
/* The X11_ functions
*
* note the following functions do not exist because they
* are handled by the coresponding graph cap version of the
* function:
*
* X11_VDCType(), X11_IntegerPrec(), X11_RealPrec(),
* X11_IndexPrec(), X11_ColrPrec(), X11_ColrIndexPrec(),
* X11_MaxColrIndex(), X11_ColrValueExt(), X11_CharCoding()
*
* Class 2
* X11_ScaleMode(), X11_ColrMode(), X11_LineWidthMode(),
* X11_MarkerSizeMode(), X11_EdgeWidthMode(), X11_VDCExt()
*
* Class 3
* X11_VDCIntegerPrec(), X11_VDCRealPrec(), X11_Transpanrecy()
* X11_ClipRect(), X11_Clip()
*
* Class 4
* X11_text()
*
* Class 5
* X11_LineIndex(), X11_LineType() X11_LineWidth(), X11_LineColr()
* X11_MarkerIndex(), X11_MarkerType() X11_MarkerSize()
* X11_MarkerColour(), X11_TextIndex(), X11_TextFontIndex()
* X11_TextPrec() X11_CharExpan(), X11_CharSpace(), X11_TextColr()
* X11_CharHeight(), X11_CharOri() X11_TextPath() X11_TextAlign()
* X11_CharSetIndex(), X11_AltCharSetIndex(), X11_FillIndex()
* X11_IntStyle() X11_Fill_colr() X11_HatchIndex() X11_PatIndex()
* X11_EdgeIndex(), X11_EdgeType(), X11_EdgeWidth() X11_EdgeColr()
* X11_EdgeVis() X11_FillRefPt(), X11_PatSize()
*/
{
/* Class 0 */
{
noop, X11_BegMF, X11_EndMF, X11_BegPic, X11_BegPicBody,
X11_EndPic, X11_ClearDevice, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
},
/* Class 1 */
{
NULL, MFVersion, X11_MFDesc, VDCType, IntergerPrec,
RealPrec, IndexPrec, ColrPrec, ColrIndexPrec, MaxColrIndex,
ColrValueExt, X11_MFElemList, X11_MFDefaults, FontList,
X11_CharSetList, CharCoding, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
},
/* Class 2 */
{
NULL, ScaleMode, ColrMode, LineWidthMode, MarkerSizeMode,
EdgeWidthMode, VDCExt, BackColr, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
},
/* Class 3 */
{
NULL, VDCIntergerPrec, VDCRealPrec, X11_AuxColr, Transparency,
ClipRect, Clip, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
},
/* Class 4 */
{
NULL, X11_PolyLine, X11_DisjtLine, X11_PolyMarker, Text,
X11_RestrText, X11_ApndText, X11_Polygon, X11_PolygonSet, X11_CellArray,
X11_GDP, X11_Rect, X11_Circle, X11_Arc3Pt, X11_Arc3PtClose,
X11_ArcCtr, X11_ArcCtrClose, X11_Ellipse, X11_EllipArc, X11_EllipArcClose,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
},
/* Class 5 */
{
NULL, LineIndex, LineType, LineWidth, LineColr,
MarkerIndex,MarkerType,MarkerSize,MarkerColr,
TextIndex, TextFontIndex, TextPrec, CharExpan,
CharSpace, TextColr, CharHeight, CharOri,
TextPath, TextAlign, CharSetIndex, AltCharSetIndex,
FillIndex,IntStyle,FillColr,HatchIndex,
PatIndex, EdgeIndex, EdgeType, EdgeWidth, EdgeColr,
EdgeVis, FillRefPt, PatTable, PatSize, ColrTable,
ASF,
},
/* Class 6 */
{
NULL, X11_Escape, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
},
/* Class 7 */
{
NULL, X11_Message, X11_ApplData, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
}
},
#endif /* X11 */
#ifdef CTXT
/*
* The Clear Text portion of the jump table
*/
{
/* Class 0 */
{
CTXT_NoOp, CTXT_BegMF, CTXT_EndMF, CTXT_BegPic, CTXT_BegPicBody,
CTXT_EndPic, CTXT_ClearDevice, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
},
/* Class 1 */
{
NULL, CTXT_MFVersion, CTXT_MFDesc, CTXT_VDCType, CTXT_IntergerPrec,
CTXT_RealPrec, CTXT_IndexPrec, CTXT_ColrPrec, CTXT_ColrIndexPrec,
CTXT_MaxColrIndex, CTXT_ColrValueExt, CTXT_MFElemList,
CTXT_MFDefaults, CTXT_FontList, CTXT_CharSetList, CTXT_CharCoding,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
},
/* Class 2 */
{
NULL, CTXT_ScaleMode, CTXT_ColrMode, CTXT_LineWidthMode,
CTXT_MarkerSizeMode, CTXT_EdgeWidthMode, CTXT_VDCExt,
CTXT_BackColr, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
},
/* Class 3 */
{
NULL, CTXT_VDCIntergerPrec, CTXT_VDCRealPrec, CTXT_AuxColr,
CTXT_Transparency, CTXT_ClipRect, CTXT_Clip, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL,
},
/* Class 4 */
{
NULL, CTXT_PolyLine, CTXT_DisjtLine, CTXT_PolyMarker, CTXT_Text,
CTXT_RestrText, CTXT_ApndText, CTXT_Polygon, CTXT_PolygonSet,
CTXT_CellArray, CTXT_GDP, CTXT_Rect, CTXT_Circle, CTXT_Arc3Pt,
CTXT_Arc3PtClose, CTXT_ArcCtr, CTXT_ArcCtrClose, CTXT_Ellipse,
CTXT_EllipArc, CTXT_EllipArcClose, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
},
/* Class 5 */
{
NULL, CTXT_LineIndex, CTXT_LineType, CTXT_LineWidth, CTXT_LineColr,
CTXT_MarkerIndex,CTXT_MarkerType,CTXT_MarkerSize,CTXT_MarkerColr,
CTXT_TextIndex, CTXT_TextFontIndex, CTXT_TextPrec, CTXT_CharExpan,
CTXT_CharSpace, CTXT_TextColr, CTXT_CharHeight, CTXT_CharOri,
CTXT_TextPath, CTXT_TextAlign, CTXT_CharSetIndex,
CTXT_AltCharSetIndex, CTXT_FillIndex,CTXT_IntStyle,CTXT_FillColr,
CTXT_HatchIndex, CTXT_PatIndex, CTXT_EdgeIndex, CTXT_EdgeType,
CTXT_EdgeWidth, CTXT_EdgeColr, CTXT_EdgeVis, CTXT_FillRefPt,
CTXT_PatTable, CTXT_PatSize, CTXT_ColrTable, CTXT_ASF,
},
/* Class 6 */
{
NULL, CTXT_Escape, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL,
},
/* Class 7 */
{
NULL, CTXT_Message, CTXT_ApplData, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL,
}
},
#endif /* CTXT */
#ifdef SunV
{
/* Class 0 */
{
noop, SunV_BegMF, SunV_EndMF, SunV_BegPic, SunV_BegPicBody,
SunV_EndPic, SunV_ClearDevice, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
},
/* Class 1 */
{
NULL, MFVersion, MFDesc, VDCType, IntergerPrec,
RealPrec, IndexPrec, ColrPrec, ColrIndexPrec, MaxColrIndex,
ColrValueExt, MFElemList, MFDefaults, FontList,
CharSetList, CharCoding, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
},
/* Class 2 */
{
NULL, ScaleMode, ColrMode, LineWidthMode, MarkerSizeMode,
EdgeWidthMode, VDCExt, BackColr, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
},
/* Class 3 */
{
NULL, VDCIntergerPrec, VDCRealPrec, AuxColr, Transparency,
ClipRect, Clip, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
},
/* Class 4 */
{
NULL, SunV_PolyLine, DisjtLine, SunV_PolyMarker, Text,
RestrText, ApndText, SunV_Polygon, PolygonSet, SunV_CellArray,
GDP, Rect, Circle, Arc3Pt, Arc3PtClose,
ArcCtr, ArcCtrClose, Ellipse, EllipArc, EllipArcClose,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
},
/* Class 5 */
{
NULL, LineIndex, LineType, LineWidth, LineColr,
MarkerIndex,MarkerType,MarkerSize,MarkerColr,
TextIndex, TextFontIndex, TextPrec, CharExpan,
CharSpace, TextColr, CharHeight, CharOri,
TextPath, TextAlign, CharSetIndex, AltCharSetIndex,
FillIndex,IntStyle,FillColr,HatchIndex,
PatIndex, EdgeIndex, EdgeType, EdgeWidth, EdgeColr,
EdgeVis, FillRefPt, PatTable, PatSize, SunV_ColrTable,
ASF,
},
/* Class 6 */
{
NULL, Escape, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
},
/* Class 7 */
{
NULL, Message, ApplData, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
}
},
#endif
#ifdef SunR
{
/* Class 0 */
{
noop, SunR_BegMF, SunR_EndMF, SunR_BegPic, SunR_BegPicBody,
SunR_EndPic, SunR_ClearDevice, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
},
/* Class 1 */
{
NULL, MFVersion, MFDesc, VDCType, IntergerPrec,
RealPrec, IndexPrec, ColrPrec, ColrIndexPrec, MaxColrIndex,
ColrValueExt, MFElemList, MFDefaults, FontList,
CharSetList, CharCoding, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
},
/* Class 2 */
{
NULL, ScaleMode, ColrMode, LineWidthMode, MarkerSizeMode,
EdgeWidthMode, VDCExt, BackColr, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
},
/* Class 3 */
{
NULL, VDCIntergerPrec, VDCRealPrec, AuxColr, Transparency,
ClipRect, Clip, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
},
/* Class 4 */
{
NULL, SunR_PolyLine, DisjtLine, SunR_PolyMarker, Text,
RestrText, ApndText, SunR_Polygon, PolygonSet, SunR_CellArray,
GDP, Rect, Circle, Arc3Pt, Arc3PtClose,
ArcCtr, ArcCtrClose, Ellipse, EllipArc, EllipArcClose,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
},
/* Class 5 */
{
NULL, LineIndex, LineType, LineWidth, LineColr,
MarkerIndex,MarkerType,MarkerSize,MarkerColr,
TextIndex, TextFontIndex, TextPrec, CharExpan,
CharSpace, TextColr, CharHeight, CharOri,
TextPath, TextAlign, CharSetIndex, AltCharSetIndex,
FillIndex,IntStyle,FillColr,HatchIndex,
PatIndex, EdgeIndex, EdgeType, EdgeWidth, EdgeColr,
EdgeVis, FillRefPt, PatTable, PatSize, SunR_ColrTable,
ASF,
},
/* Class 6 */
{
NULL, Escape, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
},
/* Class 7 */
{
NULL, Message, ApplData, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL,
}
},
#endif
};
|
e20bef237b77cf01760d3bd93b0e43166f2cbd75
|
80258571b9a9603e1053b57befd8b24916302ea3
|
/src/timing.h
|
f0d9e04c1e1ae32682cb6263e2e433d51c693d4a
|
[
"MIT"
] |
permissive
|
91861/wayst
|
3c01c8266d628a6d954574870b0d1b4684b0f110
|
5cf1cbf7137f37e1bf459c4a3e2890fcf56d4152
|
refs/heads/master
| 2023-08-17T07:56:58.692463
| 2023-08-13T12:49:23
| 2023-08-13T12:49:23
| 245,501,055
| 288
| 13
|
MIT
| 2021-10-03T13:27:10
| 2020-03-06T19:30:41
|
C
|
UTF-8
|
C
| false
| false
| 17,007
|
h
|
timing.h
|
/* See LICENSE for license information. */
#pragma once
#define _GNU_SOURCE
#include <math.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <time.h>
#include "util.h"
#include "vector.h"
#define MS_IN_NSECS 1000000
#define SEC_IN_MS 1000
#define SEC_IN_NSECS 1000000000
typedef struct timespec TimePoint;
static inline TimePoint TimePoint_now()
{
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return t;
}
static inline void TimePoint_add(TimePoint* self, TimePoint offset)
{
self->tv_sec += offset.tv_sec;
self->tv_nsec += offset.tv_nsec;
if (self->tv_nsec >= SEC_IN_NSECS) {
self->tv_nsec -= SEC_IN_NSECS;
++self->tv_sec;
}
}
static inline TimePoint TimePoint_add_ms(TimePoint t, uint32_t ms_offset)
{
TimePoint offset = { .tv_sec = ms_offset / SEC_IN_MS,
.tv_nsec = (ms_offset % SEC_IN_MS) * MS_IN_NSECS };
TimePoint_add(&t, offset);
return t;
}
static inline int64_t TimePoint_get_secs(TimePoint* self)
{
return (int64_t)self->tv_nsec / SEC_IN_NSECS + self->tv_sec;
}
static inline int64_t TimePoint_get_min(TimePoint* self)
{
return TimePoint_get_secs(self) / 60;
}
static inline int64_t TimePoint_get_hour(TimePoint* self)
{
return TimePoint_get_min(self) / 60;
}
static inline int64_t TimePoint_get_nsecs(TimePoint self)
{
return self.tv_nsec + self.tv_sec * SEC_IN_NSECS;
}
static inline int64_t TimePoint_get_ms(TimePoint self)
{
return (((int64_t)self.tv_nsec) + ((int64_t)self.tv_sec) * SEC_IN_NSECS) / MS_IN_NSECS;
}
static inline void TimePoint_subtract(TimePoint* self, TimePoint other)
{
self->tv_sec -= other.tv_sec;
if (self->tv_nsec < other.tv_nsec) {
--self->tv_sec;
int64_t rest = other.tv_nsec - self->tv_nsec;
self->tv_nsec = SEC_IN_NSECS - rest;
} else {
self->tv_nsec -= other.tv_nsec;
}
}
/**
* Create a time point in the future */
static inline TimePoint TimePoint_ms_from_now(uint32_t ms_offset)
{
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
TimePoint offset = { .tv_sec = ms_offset / SEC_IN_MS,
.tv_nsec = (ms_offset % SEC_IN_MS) * MS_IN_NSECS };
TimePoint_add(&t, offset);
return t;
}
/**
* Create a time point in the future */
static inline TimePoint TimePoint_s_from_now(uint32_t s_offset)
{
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
TimePoint_add(&t, (TimePoint){ .tv_sec = s_offset, .tv_nsec = 0 });
return t;
}
static inline int64_t TimePoint_is_nsecs_ahead(TimePoint t)
{
TimePoint_subtract(&t, TimePoint_now());
return TimePoint_get_nsecs(t);
}
static inline int64_t TimePoint_ms_in_the_future(TimePoint t)
{
TimePoint_subtract(&t, TimePoint_now());
return TimePoint_get_ms(t);
}
static inline int64_t TimePoint_ms_in_the_past(TimePoint t)
{
TimePoint n = TimePoint_now();
TimePoint_subtract(&n, t);
return TimePoint_get_ms(n);
}
static inline bool TimePoint_is_earlier(TimePoint t, TimePoint other)
{
return ((t.tv_sec < other.tv_sec) || (t.tv_sec == other.tv_sec && t.tv_nsec < other.tv_nsec));
}
#define TimePoint_is_later(t, other) (!TimePoint_is_earlier(t, other))
static inline TimePoint TimePoint_min(TimePoint a, TimePoint b)
{
return TimePoint_is_earlier(a, b) ? a : b;
}
static inline TimePoint TimePoint_max(TimePoint a, TimePoint b)
{
return TimePoint_is_earlier(a, b) ? b : a;
}
/**
* Check if given time point was reached */
static inline bool TimePoint_passed(TimePoint t)
{
return TimePoint_is_earlier(t, TimePoint_now());
}
/**
* A pair of 'TimePoints', allows you to check the position of a time
* point in relation to them. */
typedef struct
{
TimePoint start, end;
} TimeSpan;
static inline TimeSpan TimeSpan_new(TimePoint start, TimePoint end)
{
return (TimeSpan){ .start = start, .end = end };
}
static inline TimeSpan TimeSpan_from_now_to(TimePoint end)
{
return (TimeSpan){ .start = TimePoint_now(), .end = end };
}
static inline TimeSpan TimeSpan_from_now_to_ms_from_now(uint32_t ms_offset)
{
return (TimeSpan){ .start = TimePoint_now(), .end = TimePoint_ms_from_now(ms_offset) };
}
static inline bool TimeSpan_point_is_within(TimeSpan* self, TimePoint point)
{
return TimePoint_is_later(point, self->start) && TimePoint_is_earlier(point, self->end);
}
static inline bool TimeSpan_is_active_now(TimeSpan* self)
{
return TimeSpan_point_is_within(self, TimePoint_now());
}
static inline double TimeSpan_get_fraction_for(TimeSpan* self, TimePoint point)
{
TimePoint point_minus_start = point, end_minus_start = self->end;
TimePoint_subtract(&point_minus_start, self->start);
TimePoint_subtract(&end_minus_start, self->start);
return (double)TimePoint_get_nsecs(point_minus_start) /
(double)TimePoint_get_nsecs(end_minus_start);
}
static inline float TimeSpan_get_fraction_now(TimeSpan* self)
{
return TimeSpan_get_fraction_for(self, TimePoint_now());
}
static inline double TimeSpan_get_fraction_clamped_for(TimeSpan* self, TimePoint point)
{
float result = TimeSpan_get_fraction_for(self, point);
return result < 0.0 ? 0.0 : result > 1.0 ? 1.0 : result;
}
static inline double TimeSpan_get_fraction_clamped_now(TimeSpan* self)
{
return TimeSpan_get_fraction_clamped_for(self, TimePoint_now());
}
static inline TimePoint TimeSpan_get_duration(const TimeSpan* self)
{
TimePoint tmp = self->end;
TimePoint_subtract(&tmp, self->start);
return tmp;
}
/**
* Caller should free() */
static char* TimeSpan_duration_string_approx(const TimeSpan* self)
{
TimePoint tmp = TimeSpan_get_duration(self);
int64_t major, minor;
char* retval;
if ((major = TimePoint_get_hour(&tmp)) > 1) {
minor = TimePoint_get_min(&tmp) - 60 * major;
retval = asprintf("%luh %lumin", major, minor);
} else if ((major = TimePoint_get_min(&tmp)) > 1) {
minor = TimePoint_get_secs(&tmp) - 60 * major;
retval = asprintf("%lum %lus", major, minor);
} else if ((major = TimePoint_get_secs(&tmp)) > 1) {
minor = TimePoint_get_ms(tmp) - 1000 * major;
retval = asprintf("%lus %lums", major, minor);
} else {
retval = asprintf("%lums", TimePoint_get_ms(tmp));
}
return retval;
}
typedef uint8_t Timer;
typedef enum
{
TIMER_TYPE_TWEEN,
TIMER_TYPE_POINT,
} timer_type_e;
typedef enum
{
TWEEN_INTERPOLATION_TYPE_LINEAR,
TWEEN_INTERPOLATION_TYPE_LINEAR_INV,
TWEEN_INTERPOLATION_TYPE_LINEAR_IN_OUT,
TWEEN_INTERPOLATION_TYPE_SIN_IN,
TWEEN_INTERPOLATION_TYPE_SIN_EASE,
TWEEN_INTERPOLATION_TYPE_SIN_IN_OUT,
TWEEN_INTERPOLATION_TYPE_POW2,
TWEEN_INTERPOLATION_TYPE_POW2_INV,
TWEEN_INTERPOLATION_TYPE_POW4,
TWEEN_INTERPOLATION_TYPE_POW4_INV,
} tween_interpolation_type_e;
static double apply_tween_interpolation(double value, tween_interpolation_type_e type)
{
switch (type) {
case TWEEN_INTERPOLATION_TYPE_LINEAR:
return value;
case TWEEN_INTERPOLATION_TYPE_LINEAR_INV:
return 1.0 - value;
case TWEEN_INTERPOLATION_TYPE_LINEAR_IN_OUT:
return value < 0.5 ? value * 2.0 : value * -2.0 + 2.0;
case TWEEN_INTERPOLATION_TYPE_SIN_IN:
return sin(value * M_PI_2);
case TWEEN_INTERPOLATION_TYPE_SIN_EASE:
return 1.0 - cos(value * M_PI);
case TWEEN_INTERPOLATION_TYPE_SIN_IN_OUT:
return 0.5 - cos(value * M_PI * 2.0) / 2.0;
case TWEEN_INTERPOLATION_TYPE_POW2:
return pow(value, 2.0);
case TWEEN_INTERPOLATION_TYPE_POW2_INV:
return pow(1.0 - value, 2.0);
case TWEEN_INTERPOLATION_TYPE_POW4:
return pow(value, 4.0);
case TWEEN_INTERPOLATION_TYPE_POW4_INV:
return pow(1.0 - value, 4.0);
}
ASSERT_UNREACHABLE;
}
typedef void (*point_timer_completed_callback_func_t)(void*);
typedef void (*tween_timer_updated_callback_func_t)(void*, double fraction, bool completed);
typedef struct
{
union
{
struct tween_timer_data
{
tween_timer_updated_callback_func_t updated_callback;
TimeSpan time_span;
tween_interpolation_type_e interpolation;
} tween_data;
struct point_timer_data
{
point_timer_completed_callback_func_t completed_callback;
TimePoint trigger_time;
} point_data;
} data;
timer_type_e type : 2;
bool completed : 1;
} timer_data_t;
DEF_VECTOR(timer_data_t, NULL);
typedef struct
{
Vector_timer_data_t timers;
void* user_data;
} TimerManager;
static TimerManager TimerManager_new(void* user_data)
{
return (TimerManager){
.timers = Vector_new_with_capacity_timer_data_t(8),
.user_data = user_data,
};
}
static Timer TimerManager_create_timer(TimerManager* self, timer_type_e type, void* callback)
{
timer_data_t tmr = {
.type = type,
.completed = true,
};
switch (type) {
case TIMER_TYPE_POINT:
tmr.data.point_data = (struct point_timer_data){
.trigger_time = { 0, 0 },
.completed_callback = callback,
};
break;
case TIMER_TYPE_TWEEN:
tmr.data.tween_data = (struct tween_timer_data){
.time_span = {
.start = {0,0},
.end = {0,0},
},
.updated_callback = callback,
.interpolation = TWEEN_INTERPOLATION_TYPE_LINEAR,
};
break;
}
Vector_push_timer_data_t(&self->timers, tmr);
return self->timers.size - 1;
}
static inline void TimerManager_set_interpolation_func(TimerManager* self,
Timer timer,
tween_interpolation_type_e interpolation)
{
ASSERT(self->timers.size > timer, "exists");
timer_data_t* tmr = Vector_at_timer_data_t(&self->timers, timer);
ASSERT(tmr && tmr->type == TIMER_TYPE_TWEEN, "is tween type");
tmr->data.tween_data.interpolation = interpolation;
}
static bool TimerManager_is_pending(TimerManager* self, Timer timer)
{
ASSERT(self->timers.size > timer, "exists");
timer_data_t* tmr = Vector_at_timer_data_t(&self->timers, timer);
return !tmr->completed;
}
static void TimerManager_cancel(TimerManager* self, Timer timer)
{
ASSERT(self->timers.size > timer, "exists");
timer_data_t* tmr = Vector_at_timer_data_t(&self->timers, timer);
tmr->completed = true;
}
static bool TimerManager_is_tween_tmrating(TimerManager* self, Timer animation)
{
ASSERT(self->timers.size > animation, "exists");
timer_data_t* tmr = Vector_at_timer_data_t(&self->timers, animation);
ASSERT(tmr && tmr->type == TIMER_TYPE_TWEEN, "is tween type");
return tmr->completed ? false : TimeSpan_is_active_now(&tmr->data.tween_data.time_span);
}
static double _TimerManager_get_tween_fraction_for_data(TimerManager* self, timer_data_t* data)
{
return apply_tween_interpolation(
TimeSpan_get_fraction_clamped_now(&data->data.tween_data.time_span),
data->data.tween_data.interpolation);
}
static double TimerManager_get_tween_fraction(TimerManager* self, Timer timer)
{
ASSERT(self->timers.size > timer, "exists");
timer_data_t* tmr = Vector_at_timer_data_t(&self->timers, timer);
ASSERT(tmr && tmr->type == TIMER_TYPE_TWEEN, "is tween type");
return _TimerManager_get_tween_fraction_for_data(self, tmr);
}
static void TimerManager_schedule_point(TimerManager* self, Timer timer, TimePoint time)
{
ASSERT(self->timers.size > timer, "exists");
timer_data_t* tmr = Vector_at_timer_data_t(&self->timers, timer);
ASSERT(tmr && tmr->type == TIMER_TYPE_POINT, "is point type");
tmr->data.point_data.trigger_time = time;
tmr->completed = false;
}
static void TimerManager_schedule_tween(TimerManager* self,
Timer timer,
TimePoint begin_time,
TimePoint end_time)
{
ASSERT(self->timers.size > timer, "exists");
timer_data_t* tmr = Vector_at_timer_data_t(&self->timers, timer);
ASSERT(tmr && tmr->type == TIMER_TYPE_TWEEN, "is tween type");
tmr->data.tween_data.time_span = (TimeSpan){ begin_time, end_time };
tmr->completed = false;
}
static inline void TimerManager_schedule_tween_from_now(TimerManager* self,
Timer timer,
TimePoint end_time)
{
TimerManager_schedule_tween(self, timer, TimePoint_now(), end_time);
}
static inline void TimerManager_schedule_tween_to_ms(TimerManager* self,
Timer timer,
int32_t offset_ms)
{
TimerManager_schedule_tween_from_now(self, timer, TimePoint_ms_from_now(offset_ms));
}
static inline void TimerManager_update(TimerManager* self)
{
for (timer_data_t* i = NULL; (i = Vector_iter_timer_data_t(&self->timers, i));) {
if (i->completed) {
continue;
}
switch (i->type) {
case TIMER_TYPE_POINT: {
if (TimePoint_passed(i->data.point_data.trigger_time)) {
i->completed = true;
i->data.point_data.completed_callback(self->user_data);
}
} break;
case TIMER_TYPE_TWEEN: {
if (TimeSpan_is_active_now(&i->data.tween_data.time_span)) {
i->data.tween_data.updated_callback(
self->user_data,
_TimerManager_get_tween_fraction_for_data(self, i),
false);
} else if (TimePoint_passed(i->data.tween_data.time_span.end)) {
i->completed = true;
i->data.tween_data.updated_callback(self->user_data, 1.0, true);
}
} break;
}
}
}
typedef struct
{
TimePoint* payload;
} time_point_ptr_t;
#define TIME_POINT_PTR(tp) (&(time_point_ptr_t){ .payload = tp })
#define TIMER_MANAGER_NO_ACTION_PENDING INT64_MIN
__attribute__((sentinel)) static int64_t
TimerManager_get_next_action_ms(TimerManager* self, time_point_ptr_t* external_frame, ...)
{
int64_t ret = TIMER_MANAGER_NO_ACTION_PENDING;
TimePoint next_frame_point = { 0, 0 };
bool has_next_frame = false;
TimePoint now = TimePoint_now();
for (timer_data_t* i = NULL; (i = Vector_iter_timer_data_t(&self->timers, i));) {
if (!ret) {
return 0;
}
if (i->completed) {
continue;
}
switch (i->type) {
case TIMER_TYPE_POINT: {
next_frame_point = !has_next_frame ? i->data.point_data.trigger_time
: TimePoint_min(i->data.point_data.trigger_time,
next_frame_point);
has_next_frame = true;
} break;
case TIMER_TYPE_TWEEN: {
if (TimeSpan_point_is_within(&i->data.tween_data.time_span, now)) {
has_next_frame = true;
ret = 0;
next_frame_point = now;
} else {
next_frame_point =
!has_next_frame
? i->data.tween_data.time_span.start
: TimePoint_min(i->data.tween_data.time_span.start, next_frame_point);
has_next_frame = true;
}
} break;
}
}
va_list ap;
time_point_ptr_t* tw = external_frame;
va_start(ap, external_frame);
if (tw && tw->payload) {
do {
if (tw && tw->payload) {
if (has_next_frame && TimePoint_is_earlier(*tw->payload, next_frame_point)) {
next_frame_point = *tw->payload;
} else {
next_frame_point = *tw->payload;
has_next_frame = true;
}
}
} while ((tw = va_arg(ap, time_point_ptr_t*)));
}
va_end(ap);
if (!has_next_frame) {
return TIMER_MANAGER_NO_ACTION_PENDING;
} else {
int64_t nfp = TimePoint_ms_in_the_future(next_frame_point);
return MAX(0, nfp);
}
}
static void TimerManager_destroy(TimerManager* self)
{
Vector_destroy_timer_data_t(&self->timers);
}
|
02d9a2355ece909b77a6890612f3fbea90378d7f
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/u-boot_new/drivers/mmc/sdhci.c
|
3125d13ba3ce8e8e2552248e41c059bd31e5fb3c
|
[
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"GPL-2.0-or-later"
] |
permissive
|
OLIMEX/DIY-LAPTOP
|
ae82f4ee79c641d9aee444db9a75f3f6709afa92
|
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
|
refs/heads/rel3
| 2023-08-04T01:54:19.483792
| 2023-04-03T07:18:12
| 2023-04-03T07:18:12
| 80,094,055
| 507
| 92
|
Apache-2.0
| 2023-04-03T07:05:59
| 2017-01-26T07:25:50
|
C
|
UTF-8
|
C
| false
| false
| 13,076
|
c
|
sdhci.c
|
/*
* Copyright 2011, Marvell Semiconductor Inc.
* Lei Wen <leiwen@marvell.com>
*
* SPDX-License-Identifier: GPL-2.0+
*
* Back ported to the 8xx platform (from the 8260 platform) by
* Murray.Jensen@cmst.csiro.au, 27-Jan-01.
*/
#include <common.h>
#include <malloc.h>
#include <mmc.h>
#include <sdhci.h>
void *aligned_buffer;
static void sdhci_reset(struct sdhci_host *host, u8 mask)
{
unsigned long timeout;
/* Wait max 100 ms */
timeout = 100;
sdhci_writeb(host, mask, SDHCI_SOFTWARE_RESET);
while (sdhci_readb(host, SDHCI_SOFTWARE_RESET) & mask) {
if (timeout == 0) {
printf("%s: Reset 0x%x never completed.\n",
__func__, (int)mask);
return;
}
timeout--;
udelay(1000);
}
}
static void sdhci_cmd_done(struct sdhci_host *host, struct mmc_cmd *cmd)
{
int i;
if (cmd->resp_type & MMC_RSP_136) {
/* CRC is stripped so we need to do some shifting. */
for (i = 0; i < 4; i++) {
cmd->response[i] = sdhci_readl(host,
SDHCI_RESPONSE + (3-i)*4) << 8;
if (i != 3)
cmd->response[i] |= sdhci_readb(host,
SDHCI_RESPONSE + (3-i)*4-1);
}
} else {
cmd->response[0] = sdhci_readl(host, SDHCI_RESPONSE);
}
}
static void sdhci_transfer_pio(struct sdhci_host *host, struct mmc_data *data)
{
int i;
char *offs;
for (i = 0; i < data->blocksize; i += 4) {
offs = data->dest + i;
if (data->flags == MMC_DATA_READ)
*(u32 *)offs = sdhci_readl(host, SDHCI_BUFFER);
else
sdhci_writel(host, *(u32 *)offs, SDHCI_BUFFER);
}
}
static int sdhci_transfer_data(struct sdhci_host *host, struct mmc_data *data,
unsigned int start_addr)
{
unsigned int stat, rdy, mask, timeout, block = 0;
#ifdef CONFIG_MMC_SDMA
unsigned char ctrl;
ctrl = sdhci_readb(host, SDHCI_HOST_CONTROL);
ctrl &= ~SDHCI_CTRL_DMA_MASK;
sdhci_writeb(host, ctrl, SDHCI_HOST_CONTROL);
#endif
timeout = 1000000;
rdy = SDHCI_INT_SPACE_AVAIL | SDHCI_INT_DATA_AVAIL;
mask = SDHCI_DATA_AVAILABLE | SDHCI_SPACE_AVAILABLE;
do {
stat = sdhci_readl(host, SDHCI_INT_STATUS);
if (stat & SDHCI_INT_ERROR) {
printf("%s: Error detected in status(0x%X)!\n",
__func__, stat);
return -1;
}
if (stat & rdy) {
if (!(sdhci_readl(host, SDHCI_PRESENT_STATE) & mask))
continue;
sdhci_writel(host, rdy, SDHCI_INT_STATUS);
sdhci_transfer_pio(host, data);
data->dest += data->blocksize;
if (++block >= data->blocks)
break;
}
#ifdef CONFIG_MMC_SDMA
if (stat & SDHCI_INT_DMA_END) {
sdhci_writel(host, SDHCI_INT_DMA_END, SDHCI_INT_STATUS);
start_addr &= ~(SDHCI_DEFAULT_BOUNDARY_SIZE - 1);
start_addr += SDHCI_DEFAULT_BOUNDARY_SIZE;
sdhci_writel(host, start_addr, SDHCI_DMA_ADDRESS);
}
#endif
if (timeout-- > 0)
udelay(10);
else {
printf("%s: Transfer data timeout\n", __func__);
return -1;
}
} while (!(stat & SDHCI_INT_DATA_END));
return 0;
}
/*
* No command will be sent by driver if card is busy, so driver must wait
* for card ready state.
* Every time when card is busy after timeout then (last) timeout value will be
* increased twice but only if it doesn't exceed global defined maximum.
* Each function call will use last timeout value. Max timeout can be redefined
* in board config file.
*/
#ifndef CONFIG_SDHCI_CMD_MAX_TIMEOUT
#define CONFIG_SDHCI_CMD_MAX_TIMEOUT 3200
#endif
#define CONFIG_SDHCI_CMD_DEFAULT_TIMEOUT 100
int sdhci_send_command(struct mmc *mmc, struct mmc_cmd *cmd,
struct mmc_data *data)
{
struct sdhci_host *host = mmc->priv;
unsigned int stat = 0;
int ret = 0;
int trans_bytes = 0, is_aligned = 1;
u32 mask, flags, mode;
unsigned int time = 0, start_addr = 0;
unsigned int retry = 10000;
int mmc_dev = mmc->block_dev.dev;
/* Timeout unit - ms */
static unsigned int cmd_timeout = CONFIG_SDHCI_CMD_DEFAULT_TIMEOUT;
sdhci_writel(host, SDHCI_INT_ALL_MASK, SDHCI_INT_STATUS);
mask = SDHCI_CMD_INHIBIT | SDHCI_DATA_INHIBIT;
/* We shouldn't wait for data inihibit for stop commands, even
though they might use busy signaling */
if (cmd->cmdidx == MMC_CMD_STOP_TRANSMISSION)
mask &= ~SDHCI_DATA_INHIBIT;
while (sdhci_readl(host, SDHCI_PRESENT_STATE) & mask) {
if (time >= cmd_timeout) {
printf("%s: MMC: %d busy ", __func__, mmc_dev);
if (2 * cmd_timeout <= CONFIG_SDHCI_CMD_MAX_TIMEOUT) {
cmd_timeout += cmd_timeout;
printf("timeout increasing to: %u ms.\n",
cmd_timeout);
} else {
puts("timeout.\n");
return COMM_ERR;
}
}
time++;
udelay(1000);
}
mask = SDHCI_INT_RESPONSE;
if (!(cmd->resp_type & MMC_RSP_PRESENT))
flags = SDHCI_CMD_RESP_NONE;
else if (cmd->resp_type & MMC_RSP_136)
flags = SDHCI_CMD_RESP_LONG;
else if (cmd->resp_type & MMC_RSP_BUSY) {
flags = SDHCI_CMD_RESP_SHORT_BUSY;
mask |= SDHCI_INT_DATA_END;
} else
flags = SDHCI_CMD_RESP_SHORT;
if (cmd->resp_type & MMC_RSP_CRC)
flags |= SDHCI_CMD_CRC;
if (cmd->resp_type & MMC_RSP_OPCODE)
flags |= SDHCI_CMD_INDEX;
if (data)
flags |= SDHCI_CMD_DATA;
/* Set Transfer mode regarding to data flag */
if (data != 0) {
sdhci_writeb(host, 0xe, SDHCI_TIMEOUT_CONTROL);
mode = SDHCI_TRNS_BLK_CNT_EN;
trans_bytes = data->blocks * data->blocksize;
if (data->blocks > 1)
mode |= SDHCI_TRNS_MULTI;
if (data->flags == MMC_DATA_READ)
mode |= SDHCI_TRNS_READ;
#ifdef CONFIG_MMC_SDMA
if (data->flags == MMC_DATA_READ)
start_addr = (unsigned int)data->dest;
else
start_addr = (unsigned int)data->src;
if ((host->quirks & SDHCI_QUIRK_32BIT_DMA_ADDR) &&
(start_addr & 0x7) != 0x0) {
is_aligned = 0;
start_addr = (unsigned int)aligned_buffer;
if (data->flags != MMC_DATA_READ)
memcpy(aligned_buffer, data->src, trans_bytes);
}
sdhci_writel(host, start_addr, SDHCI_DMA_ADDRESS);
mode |= SDHCI_TRNS_DMA;
#endif
sdhci_writew(host, SDHCI_MAKE_BLKSZ(SDHCI_DEFAULT_BOUNDARY_ARG,
data->blocksize),
SDHCI_BLOCK_SIZE);
sdhci_writew(host, data->blocks, SDHCI_BLOCK_COUNT);
sdhci_writew(host, mode, SDHCI_TRANSFER_MODE);
}
sdhci_writel(host, cmd->cmdarg, SDHCI_ARGUMENT);
#ifdef CONFIG_MMC_SDMA
flush_cache(start_addr, trans_bytes);
#endif
sdhci_writew(host, SDHCI_MAKE_CMD(cmd->cmdidx, flags), SDHCI_COMMAND);
do {
stat = sdhci_readl(host, SDHCI_INT_STATUS);
if (stat & SDHCI_INT_ERROR)
break;
if (--retry == 0)
break;
} while ((stat & mask) != mask);
if (retry == 0) {
if (host->quirks & SDHCI_QUIRK_BROKEN_R1B)
return 0;
else {
printf("%s: Timeout for status update!\n", __func__);
return TIMEOUT;
}
}
if ((stat & (SDHCI_INT_ERROR | mask)) == mask) {
sdhci_cmd_done(host, cmd);
sdhci_writel(host, mask, SDHCI_INT_STATUS);
} else
ret = -1;
if (!ret && data)
ret = sdhci_transfer_data(host, data, start_addr);
if (host->quirks & SDHCI_QUIRK_WAIT_SEND_CMD)
udelay(1000);
stat = sdhci_readl(host, SDHCI_INT_STATUS);
sdhci_writel(host, SDHCI_INT_ALL_MASK, SDHCI_INT_STATUS);
if (!ret) {
if ((host->quirks & SDHCI_QUIRK_32BIT_DMA_ADDR) &&
!is_aligned && (data->flags == MMC_DATA_READ))
memcpy(data->dest, aligned_buffer, trans_bytes);
return 0;
}
sdhci_reset(host, SDHCI_RESET_CMD);
sdhci_reset(host, SDHCI_RESET_DATA);
if (stat & SDHCI_INT_TIMEOUT)
return TIMEOUT;
else
return COMM_ERR;
}
static int sdhci_set_clock(struct mmc *mmc, unsigned int clock)
{
struct sdhci_host *host = mmc->priv;
unsigned int div, clk, timeout;
sdhci_writew(host, 0, SDHCI_CLOCK_CONTROL);
if (clock == 0)
return 0;
if (SDHCI_GET_VERSION(host) >= SDHCI_SPEC_300) {
/* Version 3.00 divisors must be a multiple of 2. */
if (mmc->cfg->f_max <= clock)
div = 1;
else {
for (div = 2; div < SDHCI_MAX_DIV_SPEC_300; div += 2) {
if ((mmc->cfg->f_max / div) <= clock)
break;
}
}
} else {
/* Version 2.00 divisors must be a power of 2. */
for (div = 1; div < SDHCI_MAX_DIV_SPEC_200; div *= 2) {
if ((mmc->cfg->f_max / div) <= clock)
break;
}
}
div >>= 1;
if (host->set_clock)
host->set_clock(host->index, div);
clk = (div & SDHCI_DIV_MASK) << SDHCI_DIVIDER_SHIFT;
clk |= ((div & SDHCI_DIV_HI_MASK) >> SDHCI_DIV_MASK_LEN)
<< SDHCI_DIVIDER_HI_SHIFT;
clk |= SDHCI_CLOCK_INT_EN;
sdhci_writew(host, clk, SDHCI_CLOCK_CONTROL);
/* Wait max 20 ms */
timeout = 20;
while (!((clk = sdhci_readw(host, SDHCI_CLOCK_CONTROL))
& SDHCI_CLOCK_INT_STABLE)) {
if (timeout == 0) {
printf("%s: Internal clock never stabilised.\n",
__func__);
return -1;
}
timeout--;
udelay(1000);
}
clk |= SDHCI_CLOCK_CARD_EN;
sdhci_writew(host, clk, SDHCI_CLOCK_CONTROL);
return 0;
}
static void sdhci_set_power(struct sdhci_host *host, unsigned short power)
{
u8 pwr = 0;
if (power != (unsigned short)-1) {
switch (1 << power) {
case MMC_VDD_165_195:
pwr = SDHCI_POWER_180;
break;
case MMC_VDD_29_30:
case MMC_VDD_30_31:
pwr = SDHCI_POWER_300;
break;
case MMC_VDD_32_33:
case MMC_VDD_33_34:
pwr = SDHCI_POWER_330;
break;
}
}
if (pwr == 0) {
sdhci_writeb(host, 0, SDHCI_POWER_CONTROL);
return;
}
if (host->quirks & SDHCI_QUIRK_NO_SIMULT_VDD_AND_POWER)
sdhci_writeb(host, pwr, SDHCI_POWER_CONTROL);
pwr |= SDHCI_POWER_ON;
sdhci_writeb(host, pwr, SDHCI_POWER_CONTROL);
}
void sdhci_set_ios(struct mmc *mmc)
{
u32 ctrl;
struct sdhci_host *host = mmc->priv;
if (host->set_control_reg)
host->set_control_reg(host);
if (mmc->clock != host->clock)
sdhci_set_clock(mmc, mmc->clock);
/* Set bus width */
ctrl = sdhci_readb(host, SDHCI_HOST_CONTROL);
if (mmc->bus_width == 8) {
ctrl &= ~SDHCI_CTRL_4BITBUS;
if ((SDHCI_GET_VERSION(host) >= SDHCI_SPEC_300) ||
(host->quirks & SDHCI_QUIRK_USE_WIDE8))
ctrl |= SDHCI_CTRL_8BITBUS;
} else {
if (SDHCI_GET_VERSION(host) >= SDHCI_SPEC_300)
ctrl &= ~SDHCI_CTRL_8BITBUS;
if (mmc->bus_width == 4)
ctrl |= SDHCI_CTRL_4BITBUS;
else
ctrl &= ~SDHCI_CTRL_4BITBUS;
}
if (mmc->clock > 26000000)
ctrl |= SDHCI_CTRL_HISPD;
else
ctrl &= ~SDHCI_CTRL_HISPD;
if (host->quirks & SDHCI_QUIRK_NO_HISPD_BIT)
ctrl &= ~SDHCI_CTRL_HISPD;
sdhci_writeb(host, ctrl, SDHCI_HOST_CONTROL);
}
int sdhci_init(struct mmc *mmc)
{
struct sdhci_host *host = mmc->priv;
if ((host->quirks & SDHCI_QUIRK_32BIT_DMA_ADDR) && !aligned_buffer) {
aligned_buffer = memalign(8, 512*1024);
if (!aligned_buffer) {
printf("%s: Aligned buffer alloc failed!!!\n",
__func__);
return -1;
}
}
sdhci_set_power(host, fls(mmc->cfg->voltages) - 1);
if (host->quirks & SDHCI_QUIRK_NO_CD) {
unsigned int status;
sdhci_writel(host, SDHCI_CTRL_CD_TEST_INS | SDHCI_CTRL_CD_TEST,
SDHCI_HOST_CONTROL);
status = sdhci_readl(host, SDHCI_PRESENT_STATE);
while ((!(status & SDHCI_CARD_PRESENT)) ||
(!(status & SDHCI_CARD_STATE_STABLE)) ||
(!(status & SDHCI_CARD_DETECT_PIN_LEVEL)))
status = sdhci_readl(host, SDHCI_PRESENT_STATE);
}
/* Enable only interrupts served by the SD controller */
sdhci_writel(host, SDHCI_INT_DATA_MASK | SDHCI_INT_CMD_MASK,
SDHCI_INT_ENABLE);
/* Mask all sdhci interrupt sources */
sdhci_writel(host, 0x0, SDHCI_SIGNAL_ENABLE);
return 0;
}
static const struct mmc_ops sdhci_ops = {
.send_cmd = sdhci_send_command,
.set_ios = sdhci_set_ios,
.init = sdhci_init,
};
int add_sdhci(struct sdhci_host *host, u32 max_clk, u32 min_clk)
{
unsigned int caps;
host->cfg.name = host->name;
host->cfg.ops = &sdhci_ops;
caps = sdhci_readl(host, SDHCI_CAPABILITIES);
#ifdef CONFIG_MMC_SDMA
if (!(caps & SDHCI_CAN_DO_SDMA)) {
printf("%s: Your controller doesn't support SDMA!!\n",
__func__);
return -1;
}
#endif
if (max_clk)
host->cfg.f_max = max_clk;
else {
if (SDHCI_GET_VERSION(host) >= SDHCI_SPEC_300)
host->cfg.f_max = (caps & SDHCI_CLOCK_V3_BASE_MASK)
>> SDHCI_CLOCK_BASE_SHIFT;
else
host->cfg.f_max = (caps & SDHCI_CLOCK_BASE_MASK)
>> SDHCI_CLOCK_BASE_SHIFT;
host->cfg.f_max *= 1000000;
}
if (host->cfg.f_max == 0) {
printf("%s: Hardware doesn't specify base clock frequency\n",
__func__);
return -1;
}
if (min_clk)
host->cfg.f_min = min_clk;
else {
if (SDHCI_GET_VERSION(host) >= SDHCI_SPEC_300)
host->cfg.f_min = host->cfg.f_max /
SDHCI_MAX_DIV_SPEC_300;
else
host->cfg.f_min = host->cfg.f_max /
SDHCI_MAX_DIV_SPEC_200;
}
host->cfg.voltages = 0;
if (caps & SDHCI_CAN_VDD_330)
host->cfg.voltages |= MMC_VDD_32_33 | MMC_VDD_33_34;
if (caps & SDHCI_CAN_VDD_300)
host->cfg.voltages |= MMC_VDD_29_30 | MMC_VDD_30_31;
if (caps & SDHCI_CAN_VDD_180)
host->cfg.voltages |= MMC_VDD_165_195;
if (host->quirks & SDHCI_QUIRK_BROKEN_VOLTAGE)
host->cfg.voltages |= host->voltages;
host->cfg.host_caps = MMC_MODE_HS | MMC_MODE_HS_52MHz | MMC_MODE_4BIT;
if (SDHCI_GET_VERSION(host) >= SDHCI_SPEC_300) {
if (caps & SDHCI_CAN_DO_8BIT)
host->cfg.host_caps |= MMC_MODE_8BIT;
}
if (host->host_caps)
host->cfg.host_caps |= host->host_caps;
host->cfg.b_max = CONFIG_SYS_MMC_MAX_BLK_COUNT;
sdhci_reset(host, SDHCI_RESET_ALL);
host->mmc = mmc_create(&host->cfg, host);
if (host->mmc == NULL) {
printf("%s: mmc create fail!\n", __func__);
return -1;
}
return 0;
}
|
ab20b29251463e949a087e9c239cd8dc956700aa
|
e1cddfd754d952134e72dfd03522c5ea4fb6008e
|
/src/tools/perftool/cpelstate.c
|
78d9c9752fd702efb9f876bbc583daf68848685c
|
[
"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
| 22,856
|
c
|
cpelstate.c
|
/*
*------------------------------------------------------------------
* Copyright (c) 2006-2016 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 <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <ctype.h>
#include <vppinfra/clib.h>
#include <vppinfra/vec.h>
#include <vppinfra/hash.h>
#include <pwd.h>
#include <stdarg.h>
#include <time.h>
#include "cpel.h"
#include <math.h>
char *time_format = "%.03d:%.02d:%.02d:%.03d:%.03d ";
static char version[] = "cpelstate 2.0h";
#define USEC_PER_MS 1000LL
#define USEC_PER_SECOND (1000*USEC_PER_MS)
#define USEC_PER_MINUTE (60*USEC_PER_SECOND)
#define USEC_PER_HOUR (60*USEC_PER_MINUTE)
uword *the_strtab_hash; /* (name, base-VA) hash of all string tables */
uword *the_evtdef_hash; /* (event-id, event-definition) hash */
uword *the_trackdef_hash; /* (track-id, track-definition) hash */
f64 ticks_per_us;
u32 state_event_code = 1; /* default: XR thread-on-cpu */
int exclude_kernel_from_summary_stats=1;
int summary_stats_only;
int scatterplot;
u8 *name_filter;
typedef enum {
SORT_MAX_TIME=1,
SORT_MAX_OCCURRENCES,
SORT_NAME,
} sort_t;
sort_t sort_type = SORT_MAX_TIME;
int widest_name_format=5;
int widest_track_format=5;
typedef struct bound_event_ {
u32 event_code;
u8 *event_str;
u8 *datum_str;
u32 is_strtab_ref;
} bound_event_t;
bound_event_t *bound_events;
typedef struct bound_track_ {
u32 track;
u8 *track_str;
u64 *ticks_in_state; /* vector of state occurrences */
f64 mean_ticks_in_state;
f64 variance_ticks_in_state;
f64 total_ticks_in_state;
} bound_track_t;
bound_track_t *bound_tracks;
void fatal(char *s)
{
fprintf(stderr, "%s", s);
exit(1);
}
typedef enum {
PASS1=1,
PASS2=2,
} pass_t;
typedef struct {
int (*pass1)(cpel_section_header_t *, int, FILE *);
int (*pass2)(cpel_section_header_t *, int, FILE *);
} section_processor_t;
int bad_section(cpel_section_header_t *sh, int verbose, FILE *ofp)
{
fprintf(ofp, "Bad (type 0) section, skipped...\n");
return(0);
}
int noop_pass(cpel_section_header_t *sh, int verbose, FILE *ofp)
{
return(0);
}
int strtab_pass1(cpel_section_header_t *sh, int verbose, FILE *ofp)
{
uword *p;
u8 *strtab_data_area = (u8 *)(sh+1);
/* Multiple string tables with the same name are Bad... */
p = hash_get_mem(the_strtab_hash, strtab_data_area);
if (p) {
fprintf(ofp, "Duplicate string table name %s", strtab_data_area);
}
/*
* Looks funny, but we really do want key = first string in the
* table, value = address(first string in the table)
*/
hash_set_mem(the_strtab_hash, strtab_data_area, strtab_data_area);
if (verbose) {
fprintf(ofp, "String Table %s\n", strtab_data_area);
}
return(0);
}
int evtdef_pass1(cpel_section_header_t *sh, int verbose, FILE *ofp)
{
int i, nevents;
event_definition_section_header_t *edh;
event_definition_t *ep;
u8 *this_strtab;
u32 event_code;
uword *p;
bound_event_t *bp;
int thislen;
edh = (event_definition_section_header_t *)(sh+1);
nevents = ntohl(edh->number_of_event_definitions);
if (verbose) {
fprintf(ofp, "Event Definition Section: %d definitions\n",
nevents);
}
p = hash_get_mem(the_strtab_hash, edh->string_table_name);
if (!p) {
fprintf(ofp, "Fatal: couldn't find string table\n");
return(1);
}
this_strtab = (u8 *)p[0];
ep = (event_definition_t *)(edh+1);
for (i = 0; i < nevents; i++) {
event_code = ntohl(ep->event);
p = hash_get(the_evtdef_hash, event_code);
if (p) {
fprintf(ofp, "Event %d redefined, retain first definition\n",
event_code);
continue;
}
vec_add2(bound_events, bp, 1);
bp->event_code = event_code;
bp->event_str = this_strtab + ntohl(ep->event_format);
bp->datum_str = this_strtab + ntohl(ep->datum_format);
bp->is_strtab_ref = 0;
/* Decide if the datum format is a %s format => strtab reference */
{
int j;
int seen_percent=0;
for (j = 0; j < strlen((char *)(bp->datum_str)); j++) {
if (bp->datum_str[j] == '%'){
seen_percent=1;
continue;
}
if (seen_percent && bp->datum_str[j] == 's') {
bp->is_strtab_ref = 1;
}
}
}
hash_set(the_evtdef_hash, event_code, bp - bound_events);
thislen = strlen((char *)bp->event_str);
if (thislen > widest_name_format)
widest_name_format = thislen;
ep++;
}
return (0);
}
int trackdef_pass1(cpel_section_header_t *sh, int verbose, FILE *ofp)
{
int i, nevents;
track_definition_section_header_t *tdh;
track_definition_t *tp;
u8 *this_strtab;
u32 track_code;
uword *p;
bound_track_t *btp;
int thislen;
tdh = (track_definition_section_header_t *)(sh+1);
nevents = ntohl(tdh->number_of_track_definitions);
if (verbose) {
fprintf(ofp, "Track Definition Section: %d definitions\n",
nevents);
}
p = hash_get_mem(the_strtab_hash, tdh->string_table_name);
if (!p) {
fprintf(ofp, "Fatal: couldn't find string table\n");
return(1);
}
this_strtab = (u8 *)p[0];
tp = (track_definition_t *)(tdh+1);
for (i = 0; i < nevents; i++) {
track_code = ntohl(tp->track);
p = hash_get(the_trackdef_hash, track_code);
if (p) {
fprintf(ofp, "track %d redefined, retain first definition\n",
track_code);
continue;
}
vec_add2(bound_tracks, btp, 1);
btp->track = track_code;
btp->track_str = this_strtab + ntohl(tp->track_format);
hash_set(the_trackdef_hash, track_code, btp - bound_tracks);
thislen = strlen((char *)(btp->track_str));
if (thislen > widest_track_format)
widest_track_format = thislen;
tp++;
}
return (0);
}
int unsupported_pass (cpel_section_header_t *sh, int verbose, FILE *ofp)
{
if (verbose) {
fprintf(ofp, "Unsupported type %d section\n",
ntohl(sh->section_type));
}
return(0);
}
int event_pass2(cpel_section_header_t *sh, int verbose, FILE *ofp)
{
event_section_header_t *eh;
u32 track_code;
int nevents;
int i;
uword *p;
event_entry_t *ep;
u64 now;
u32 time0, time1;
bound_track_t generic_track;
u32 last_track_code;
u64 state_start_ticks=0;
u64 ticks_in_state;
bound_track_t *state_track=0;
int in_state=0;
generic_track.track_str = (u8 *) "%d";
last_track_code = 0xdeafbeef;
eh = (event_section_header_t *)(sh+1);
nevents = ntohl(eh->number_of_events);
ticks_per_us = ((double)ntohl(eh->clock_ticks_per_second))/1e6;
if (verbose) {
fprintf(ofp, "%.3f ticks_per_us\n", ticks_per_us);
}
ep = (event_entry_t *)(eh+1);
p = hash_get_mem(the_strtab_hash, eh->string_table_name);
if (!p) {
fprintf(ofp, "Fatal: couldn't find string table\n");
return(1);
}
for (i = 0; i < nevents; i++) {
time0 = ntohl (ep->time[0]);
time1 = ntohl (ep->time[1]);
now = (((u64) time0)<<32) | time1;
/* Found the state-change event ? */
if (ntohl(ep->event_code) == state_event_code) {
/*
* Add a ticks-in-state record, unless
* this is the "prime mover" event instance
*/
if (in_state) {
ticks_in_state = now - state_start_ticks;
vec_add1(state_track->ticks_in_state, ticks_in_state);
}
/* switch to now-current track */
state_start_ticks = now;
track_code = ntohl(ep->track);
if (track_code != last_track_code) {
p = hash_get(the_trackdef_hash, track_code);
if (p) {
state_track = &bound_tracks[p[0]];
} else {
state_track = &generic_track;
}
last_track_code = track_code;
}
in_state = 1;
}
ep++;
}
return(0);
}
/*
* Note: If necessary, add passes / columns to this table to
* handle section order dependencies.
*/
section_processor_t processors[CPEL_NUM_SECTION_TYPES+1] =
{
{bad_section, noop_pass}, /* type 0 -- f**ked */
{strtab_pass1, noop_pass}, /* type 1 -- STRTAB */
{unsupported_pass, noop_pass}, /* type 2 -- SYMTAB */
{evtdef_pass1, noop_pass}, /* type 3 -- EVTDEF */
{trackdef_pass1, noop_pass}, /* type 4 -- TRACKDEF */
{noop_pass, event_pass2}, /* type 5 -- EVENTS */
};
int process_section(cpel_section_header_t *sh, int verbose, FILE *ofp,
pass_t pass)
{
u32 type;
type = ntohl(sh->section_type);
int rv;
int (*fp)(cpel_section_header_t *, int, FILE *);
if (type > CPEL_NUM_SECTION_TYPES) {
fprintf(stderr, "Unknown section type %d\n", type);
return(1);
}
switch(pass) {
case PASS1:
fp = processors[type].pass1;
break;
case PASS2:
fp = processors[type].pass2;
break;
default:
fprintf(stderr, "Unknown pass %d\n", pass);
return(1);
}
rv = (*fp)(sh, verbose, ofp);
return(rv);
}
int cpel_dump_file_header(cpel_file_header_t *fh, int verbose, FILE *ofp)
{
time_t file_time;
if (verbose) {
fprintf(ofp, "CPEL file: %s-endian, version %d\n",
((fh->endian_version & CPEL_FILE_LITTLE_ENDIAN) ?
"little" : "big"),
fh->endian_version & CPEL_FILE_VERSION_MASK);
file_time = ntohl(fh->file_date);
fprintf(ofp, "File created %s", ctime(&file_time));
fprintf(ofp, "File has %d sections\n",
ntohs(fh->nsections));
}
return(0);
}
int cpel_dump(u8 *cpel, int verbose, FILE *ofp)
{
cpel_file_header_t *fh;
cpel_section_header_t *sh;
u16 nsections;
u32 section_size;
int i;
/* First, the file header */
fh = (cpel_file_header_t *)cpel;
if (fh->endian_version != CPEL_FILE_VERSION) {
if (fh->endian_version & CPEL_FILE_LITTLE_ENDIAN) {
fprintf(stderr, "Little endian data format not supported\n");
return(1);
}
fprintf(stderr, "Unsupported file version 0x%x\n",
fh->endian_version);
return(1);
}
cpel_dump_file_header(fh, verbose, ofp);
nsections = ntohs(fh->nsections);
/*
* Take two passes through the file. PASS1 builds
* data structures, PASS2 actually dumps the file.
* Just in case the sections are in an unobvious order.
*/
sh = (cpel_section_header_t *)(fh+1);
for (i = 0; i < nsections; i++) {
section_size = ntohl(sh->data_length);
if(verbose) {
fprintf(ofp, "Section type %d, size %d\n", ntohl(sh->section_type),
section_size);
}
if(process_section(sh, verbose, ofp, PASS1))
return(1);
sh++;
sh = (cpel_section_header_t *)(((u8 *)sh)+section_size);
}
sh = (cpel_section_header_t *)(fh+1);
for (i = 0; i < nsections; i++) {
if(process_section(sh, verbose, ofp, PASS2))
return(1);
section_size = ntohl(sh->data_length);
sh++;
sh = (cpel_section_header_t *)(((u8 *)sh)+section_size);
}
return(0);
}
void compute_state_statistics(int verbose, FILE *ofp)
{
int i, j;
bound_track_t *bp;
f64 fticks;
/* Across the bound tracks */
for (i = 0; i < vec_len(bound_tracks); i++) {
bp = &bound_tracks[i];
bp->mean_ticks_in_state = 0.0;
bp->variance_ticks_in_state = 0.0;
bp->total_ticks_in_state = 0.0;
for (j = 0; j < vec_len(bp->ticks_in_state); j++) {
bp->total_ticks_in_state += (f64) bp->ticks_in_state[j];
}
/* Compute mean */
if (vec_len(bp->ticks_in_state)) {
bp->mean_ticks_in_state = bp->total_ticks_in_state /
((f64) vec_len(bp->ticks_in_state));
}
/* Accumulate sum: (Xi-Xbar)**2 */
for (j = 0; j < vec_len(bp->ticks_in_state); j++) {
fticks = bp->ticks_in_state[j];
bp->variance_ticks_in_state +=
(fticks - bp->mean_ticks_in_state)*
(fticks - bp->mean_ticks_in_state);
}
/* Compute s**2, the unbiased estimator of sigma**2 */
if (vec_len(bp->ticks_in_state) > 1) {
bp->variance_ticks_in_state /= (f64)
(vec_len(bp->ticks_in_state)-1);
}
}
}
int track_compare_max (const void *arg1, const void *arg2)
{
bound_track_t *a1 = (bound_track_t *)arg1;
bound_track_t *a2 = (bound_track_t *)arg2;
f64 v1, v2;
v1 = a1->total_ticks_in_state;
v2 = a2->total_ticks_in_state;
if (v1 < v2)
return (1);
else if (v1 == v2)
return (0);
else return (-1);
}
int track_compare_occurrences (const void *arg1, const void *arg2)
{
bound_track_t *a1 = (bound_track_t *)arg1;
bound_track_t *a2 = (bound_track_t *)arg2;
f64 v1, v2;
v1 = (f64) vec_len(a1->ticks_in_state);
v2 = (f64) vec_len(a2->ticks_in_state);
if (v1 < v2)
return (1);
else if (v1 == v2)
return (0);
else return (-1);
}
int track_compare_name (const void *arg1, const void *arg2)
{
bound_track_t *a1 = (bound_track_t *)arg1;
bound_track_t *a2 = (bound_track_t *)arg2;
return (strcmp((char *)(a1->track_str), (char *)(a2->track_str)));
}
void sort_state_statistics(sort_t type, FILE *ofp)
{
int (*compare)(const void *, const void *)=0;
if (summary_stats_only)
return;
switch(type) {
case SORT_MAX_TIME:
fprintf(ofp, "Results sorted by max time in state.\n");
compare = track_compare_max;
break;
case SORT_MAX_OCCURRENCES:
fprintf(ofp, "Results sorted by max occurrences of state.\n");
compare = track_compare_occurrences;
break;
case SORT_NAME:
compare = track_compare_name;
fprintf(ofp, "Results sorted by process-id/name/thread ID\n");
break;
default:
fatal("sort type not set?");
}
qsort (bound_tracks, vec_len(bound_tracks),
sizeof (bound_track_t), compare);
}
void print_state_statistics(int verbose, FILE *ofp)
{
int i,j;
u8 *trackpad;
bound_track_t *bp;
f64 total_time = 0.0;
f64 total_switches = 0.0;
trackpad = format(0, "%%-%ds ", widest_track_format);
vec_add1(trackpad, 0);
if (!summary_stats_only) {
fprintf(ofp, (char *)trackpad, "ProcThread");
fprintf(ofp, " Mean(us) Stdev(us) Total(us) N\n");
}
for (i = 0; i < vec_len(bound_tracks); i++) {
bp = &bound_tracks[i];
if (bp->mean_ticks_in_state == 0.0)
continue;
if (name_filter &&
strncmp((char *)(bp->track_str), (char *)name_filter,
strlen((char *)name_filter)))
continue;
/*
* Exclude kernel threads (e.g. idle thread) from
* state statistics
*/
if (exclude_kernel_from_summary_stats &&
!strncmp((char *)(bp->track_str), "kernel ", 7))
continue;
total_switches += (f64) vec_len(bp->ticks_in_state);
if (!summary_stats_only) {
fprintf(ofp, (char *) trackpad, bp->track_str);
fprintf(ofp, "%10.3f +- %10.3f",
bp->mean_ticks_in_state / ticks_per_us,
sqrt(bp->variance_ticks_in_state)
/ (f64) ticks_per_us);
fprintf(ofp, "%12.3f",
bp->total_ticks_in_state / ticks_per_us);
fprintf(ofp, "%8d\n", (int)vec_len(bp->ticks_in_state));
}
if (scatterplot) {
for (j = 0; j < vec_len(bp->ticks_in_state); j++) {
fprintf(ofp, "%.3f\n",
(f64)bp->ticks_in_state[j] / ticks_per_us);
}
}
total_time += bp->total_ticks_in_state;
}
if (!summary_stats_only)
fprintf(ofp, "\n");
fprintf(ofp, "Note: the following statistics %s kernel-thread activity.\n",
exclude_kernel_from_summary_stats ? "exclude" : "include");
if (name_filter)
fprintf(ofp,
"Note: only pid/proc/threads matching '%s' are included.\n",
name_filter);
fprintf(ofp,
"Total runtime: %10.3f (us), Total state switches: %.0f\n",
total_time / ticks_per_us, total_switches);
fprintf(ofp, "Average time in state: %10.3f (us)\n",
(total_time / total_switches) / ticks_per_us);
}
char *mapfile (char *file)
{
struct stat statb;
char *rv;
int maphfile;
size_t mapfsize;
maphfile = open (file, O_RDONLY);
if (maphfile < 0)
{
fprintf (stderr, "Couldn't read %s, skipping it...\n", file);
return (NULL);
}
if (fstat (maphfile, &statb) < 0)
{
fprintf (stderr, "Couldn't get size of %s, skipping it...\n", file);
return (NULL);
}
/* Don't try to mmap directories, FIFOs, semaphores, etc. */
if (! (statb.st_mode & S_IFREG)) {
fprintf (stderr, "%s is not a regular file, skipping it...\n", file);
return (NULL);
}
mapfsize = statb.st_size;
if (mapfsize < 3)
{
fprintf (stderr, "%s zero-length, skipping it...\n", file);
close (maphfile);
return (NULL);
}
rv = mmap (0, mapfsize, PROT_READ, MAP_SHARED, maphfile, 0);
if (rv == 0)
{
fprintf (stderr, "%s problem mapping, I quit...\n", file);
exit (-1);
}
close (maphfile);
return (rv);
}
/*
* main
*/
int main (int argc, char **argv)
{
char *cpel_file = 0;
char *outputfile = 0;
FILE *ofp;
char *cpel;
int verbose=0;
int curarg=1;
while (curarg < argc) {
if (!strncmp(argv[curarg], "--input-file", 3)) {
curarg++;
if (curarg < argc) {
cpel_file = argv[curarg];
curarg++;
continue;
}
fatal("Missing filename after --input-file\n");
}
if (!strncmp(argv[curarg], "--output-file", 3)) {
curarg ++;
if (curarg < argc) {
outputfile = argv[curarg];
curarg ++;
continue;
}
fatal("Missing filename after --output-file\n");
}
if (!strncmp(argv[curarg], "--verbose", 3)) {
curarg++;
verbose++;
continue;
}
if (!strncmp(argv[curarg], "--scatterplot", 4)) {
curarg++;
scatterplot=1;
continue;
}
if (!strncmp(argv[curarg], "--state-event", 4)) {
curarg++;
if (curarg < argc) {
state_event_code = atol(argv[curarg]);
curarg ++;
continue;
}
fatal("Missing integer after --state-event\n");
}
if (!strncmp(argv[curarg], "--max-time-sort", 7)) {
sort_type = SORT_MAX_TIME;
curarg++;
continue;
}
if (!strncmp(argv[curarg], "--max-occurrence-sort", 7)) {
sort_type = SORT_MAX_OCCURRENCES;
curarg++;
continue;
}
if (!strncmp(argv[curarg], "--name-sort", 3)) {
sort_type = SORT_NAME;
curarg++;
continue;
}
if (!strncmp(argv[curarg], "--kernel-included", 3)) {
exclude_kernel_from_summary_stats = 0;
curarg++;
continue;
}
if (!strncmp(argv[curarg], "--summary", 3)) {
summary_stats_only=1;
curarg++;
continue;
}
if (!strncmp(argv[curarg], "--filter", 3)) {
curarg ++;
if (curarg < argc) {
name_filter = (u8 *)argv[curarg];
curarg ++;
continue;
}
fatal("Missing filter string after --filter\n");
}
usage:
fprintf(stderr,
"cpelstate --input-file <filename> [--output-file <filename>]\n");
fprintf(stderr,
" [--state-event <decimal>] [--verbose]\n");
fprintf(stderr,
" [--max-time-sort(default) | --max-occurrence-sort |\n");
fprintf(stderr,
" --name-sort-sort] [--kernel-included]\n");
fprintf(stderr,
" [--summary-stats-only] [--scatterplot]\n");
fprintf(stderr, "%s\n", version);
exit(1);
}
if (cpel_file == 0)
goto usage;
cpel = mapfile(cpel_file);
if (cpel == 0) {
fprintf(stderr, "Couldn't map %s...\n", cpel_file);
exit(1);
}
if (!outputfile) {
ofp = fdopen(1, "w");
if (ofp == NULL) {
fprintf(stderr, "Couldn't fdopen(1)?\n");
exit(1);
}
} else {
ofp = fopen(outputfile, "w");
if (ofp == NULL) {
fprintf(stderr, "Couldn't create %s...\n", outputfile);
exit(1);
}
}
the_strtab_hash = hash_create_string (0, sizeof (uword));
the_evtdef_hash = hash_create (0, sizeof (uword));
the_trackdef_hash = hash_create (0, sizeof (uword));
if (cpel_dump((u8 *) cpel, verbose, ofp)) {
if (outputfile)
unlink(outputfile);
}
compute_state_statistics(verbose, ofp);
sort_state_statistics(sort_type, ofp);
print_state_statistics(verbose, ofp);
fclose(ofp);
return(0);
}
|
9b20cc745fda173812bec0ca75215d26713241cd
|
78dc9f153549b281be709227bc9897931b06260d
|
/generation/WinSDK/RecompiledIdlHeaders/um/wct.h
|
d3441432da3965b4d321353d90d3f8ea6dc87470
|
[
"MIT"
] |
permissive
|
microsoft/win32metadata
|
dff35b4fe904d556162cee5133294c4498f1a79a
|
5bf233f04d45f7a697e112e9639722551103eb07
|
refs/heads/main
| 2023-09-01T19:51:22.972899
| 2023-08-30T21:39:44
| 2023-08-30T21:39:44
| 270,838,404
| 1,240
| 107
|
NOASSERTION
| 2023-09-14T18:49:44
| 2020-06-08T21:52:10
|
C++
|
UTF-8
|
C
| false
| false
| 3,497
|
h
|
wct.h
|
/*++
Copyright (c) 2004 Microsoft Corporation
Module Name:
wct.h
Abstract:
Private interfaces for thread wait chain traversal.
History:
12/01/2004 sdoll Created.
--*/
#if _MSC_VER > 1000
#pragma once
#endif
#include <winapifamily.h>
#pragma region Desktop Family
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
#ifdef __cplusplus
extern "C" {
#endif
typedef enum _WCT_OBJECT_TYPE
{
WctCriticalSectionType = 1,
WctSendMessageType,
WctMutexType,
WctAlpcType,
WctComType,
WctThreadWaitType,
WctProcessWaitType,
WctThreadType,
WctComActivationType,
WctUnknownType,
WctSocketIoType,
WctSmbIoType,
WctMaxType
} WCT_OBJECT_TYPE;
typedef enum _WCT_OBJECT_STATUS
{
WctStatusNoAccess = 1, // ACCESS_DENIED for this object
WctStatusRunning, // Thread status
WctStatusBlocked, // Thread status
WctStatusPidOnly, // Thread status
WctStatusPidOnlyRpcss, // Thread status
WctStatusOwned, // Dispatcher object status
WctStatusNotOwned, // Dispatcher object status
WctStatusAbandoned, // Dispatcher object status
WctStatusUnknown, // All objects
WctStatusError, // All objects
WctStatusMax
} WCT_OBJECT_STATUS;
// Max. number of nodes in the wait chain
#define WCT_MAX_NODE_COUNT 16
#define WCT_OBJNAME_LENGTH 128
typedef struct _WAITCHAIN_NODE_INFO
{
WCT_OBJECT_TYPE ObjectType;
WCT_OBJECT_STATUS ObjectStatus;
union {
struct {
WCHAR ObjectName[WCT_OBJNAME_LENGTH];
LARGE_INTEGER Timeout; // Not implemented in v1
BOOL Alertable; // Not implemented in v1
} LockObject;
struct {
DWORD ProcessId;
DWORD ThreadId;
DWORD WaitTime;
DWORD ContextSwitches;
} ThreadObject;
};
} WAITCHAIN_NODE_INFO, *PWAITCHAIN_NODE_INFO;
typedef LPVOID HWCT;
typedef VOID (CALLBACK *PWAITCHAINCALLBACK) (
HWCT WctHandle,
DWORD_PTR Context,
DWORD CallbackStatus,
LPDWORD NodeCount,
PWAITCHAIN_NODE_INFO NodeInfoArray,
LPBOOL IsCycle
);
#define WCT_ASYNC_OPEN_FLAG 0x1
#define WCTP_OPEN_ALL_FLAGS (WCT_ASYNC_OPEN_FLAG)
_Check_return_
WINADVAPI
HWCT WINAPI
OpenThreadWaitChainSession (
_In_ DWORD Flags,
_In_opt_ PWAITCHAINCALLBACK callback
);
WINADVAPI
VOID WINAPI
CloseThreadWaitChainSession (
_In_ HWCT WctHandle
);
#define WCT_OUT_OF_PROC_FLAG 0x1
#define WCT_OUT_OF_PROC_COM_FLAG 0x2
#define WCT_OUT_OF_PROC_CS_FLAG 0x4
#define WCT_NETWORK_IO_FLAG 0x8
#define WCTP_GETINFO_ALL_FLAGS (WCT_OUT_OF_PROC_FLAG|WCT_OUT_OF_PROC_COM_FLAG|WCT_OUT_OF_PROC_CS_FLAG)
_Check_return_
WINADVAPI
BOOL WINAPI
GetThreadWaitChain (
_In_ HWCT WctHandle,
_In_opt_ DWORD_PTR Context,
_In_ DWORD Flags,
_In_ DWORD ThreadId,
_Inout_ LPDWORD NodeCount,
_Out_writes_(*NodeCount) PWAITCHAIN_NODE_INFO NodeInfoArray,
_Out_ LPBOOL IsCycle
);
typedef HRESULT (*PCOGETCALLSTATE)(int, PULONG);
typedef HRESULT (*PCOGETACTIVATIONSTATE)(GUID, DWORD, DWORD*);
WINADVAPI
VOID WINAPI
RegisterWaitChainCOMCallback (
_In_ PCOGETCALLSTATE CallStateCallback,
_In_ PCOGETACTIVATIONSTATE ActivationStateCallback
);
#ifdef __cplusplus
}
#endif
#endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) */
#pragma endregion
|
b0cefd0989a75cee66032b0b448bf03e5784c86a
|
010279e2ba272d09e9d2c4e903722e5faba2cf7a
|
/contrib/restricted/libffi/src/prep_cif.c
|
06c65440361392007a24aee7d6d437cab2583197
|
[
"Apache-2.0",
"GPL-2.0-only",
"MIT"
] |
permissive
|
catboost/catboost
|
854c1a1f439a96f1ae6b48e16644be20aa04dba2
|
f5042e35b945aded77b23470ead62d7eacefde92
|
refs/heads/master
| 2023-09-01T12:14:14.174108
| 2023-09-01T10:01:01
| 2023-09-01T10:22:12
| 97,556,265
| 8,012
| 1,425
|
Apache-2.0
| 2023-09-11T03:32:32
| 2017-07-18T05:29:04
|
Python
|
UTF-8
|
C
| false
| false
| 7,837
|
c
|
prep_cif.c
|
/* -----------------------------------------------------------------------
prep_cif.c - Copyright (c) 2011, 2012 Anthony Green
Copyright (c) 1996, 1998, 2007 Red Hat, 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 <ffi.h>
#include <ffi_common.h>
#include <stdlib.h>
/* Round up to FFI_SIZEOF_ARG. */
#define STACK_ARG_SIZE(x) FFI_ALIGN(x, FFI_SIZEOF_ARG)
/* Perform machine independent initialization of aggregate type
specifications. */
static ffi_status initialize_aggregate(ffi_type *arg, size_t *offsets)
{
ffi_type **ptr;
if (UNLIKELY(arg == NULL || arg->elements == NULL))
return FFI_BAD_TYPEDEF;
arg->size = 0;
arg->alignment = 0;
ptr = &(arg->elements[0]);
if (UNLIKELY(ptr == 0))
return FFI_BAD_TYPEDEF;
while ((*ptr) != NULL)
{
if (UNLIKELY(((*ptr)->size == 0)
&& (initialize_aggregate((*ptr), NULL) != FFI_OK)))
return FFI_BAD_TYPEDEF;
/* Perform a sanity check on the argument type */
FFI_ASSERT_VALID_TYPE(*ptr);
arg->size = FFI_ALIGN(arg->size, (*ptr)->alignment);
if (offsets)
*offsets++ = arg->size;
arg->size += (*ptr)->size;
arg->alignment = (arg->alignment > (*ptr)->alignment) ?
arg->alignment : (*ptr)->alignment;
ptr++;
}
/* Structure size includes tail padding. This is important for
structures that fit in one register on ABIs like the PowerPC64
Linux ABI that right justify small structs in a register.
It's also needed for nested structure layout, for example
struct A { long a; char b; }; struct B { struct A x; char y; };
should find y at an offset of 2*sizeof(long) and result in a
total size of 3*sizeof(long). */
arg->size = FFI_ALIGN (arg->size, arg->alignment);
/* On some targets, the ABI defines that structures have an additional
alignment beyond the "natural" one based on their elements. */
#ifdef FFI_AGGREGATE_ALIGNMENT
if (FFI_AGGREGATE_ALIGNMENT > arg->alignment)
arg->alignment = FFI_AGGREGATE_ALIGNMENT;
#endif
if (arg->size == 0)
return FFI_BAD_TYPEDEF;
else
return FFI_OK;
}
#ifndef __CRIS__
/* The CRIS ABI specifies structure elements to have byte
alignment only, so it completely overrides this functions,
which assumes "natural" alignment and padding. */
/* Perform machine independent ffi_cif preparation, then call
machine dependent routine. */
/* For non variadic functions isvariadic should be 0 and
nfixedargs==ntotalargs.
For variadic calls, isvariadic should be 1 and nfixedargs
and ntotalargs set as appropriate. nfixedargs must always be >=1 */
ffi_status FFI_HIDDEN ffi_prep_cif_core(ffi_cif *cif, ffi_abi abi,
unsigned int isvariadic,
unsigned int nfixedargs,
unsigned int ntotalargs,
ffi_type *rtype, ffi_type **atypes)
{
unsigned bytes = 0;
unsigned int i;
ffi_type **ptr;
FFI_ASSERT(cif != NULL);
FFI_ASSERT((!isvariadic) || (nfixedargs >= 1));
FFI_ASSERT(nfixedargs <= ntotalargs);
if (! (abi > FFI_FIRST_ABI && abi < FFI_LAST_ABI))
return FFI_BAD_ABI;
cif->abi = abi;
cif->arg_types = atypes;
cif->nargs = ntotalargs;
cif->rtype = rtype;
cif->flags = 0;
#ifdef _M_ARM64
cif->is_variadic = isvariadic;
#endif
#if HAVE_LONG_DOUBLE_VARIANT
ffi_prep_types (abi);
#endif
/* Initialize the return type if necessary */
if ((cif->rtype->size == 0)
&& (initialize_aggregate(cif->rtype, NULL) != FFI_OK))
return FFI_BAD_TYPEDEF;
#ifndef FFI_TARGET_HAS_COMPLEX_TYPE
if (rtype->type == FFI_TYPE_COMPLEX)
abort();
#endif
/* Perform a sanity check on the return type */
FFI_ASSERT_VALID_TYPE(cif->rtype);
/* x86, x86-64 and s390 stack space allocation is handled in prep_machdep. */
#if !defined FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION
/* Make space for the return structure pointer */
if (cif->rtype->type == FFI_TYPE_STRUCT
#ifdef TILE
&& (cif->rtype->size > 10 * FFI_SIZEOF_ARG)
#endif
#ifdef XTENSA
&& (cif->rtype->size > 16)
#endif
#ifdef NIOS2
&& (cif->rtype->size > 8)
#endif
)
bytes = STACK_ARG_SIZE(sizeof(void*));
#endif
for (ptr = cif->arg_types, i = cif->nargs; i > 0; i--, ptr++)
{
/* Initialize any uninitialized aggregate type definitions */
if (((*ptr)->size == 0)
&& (initialize_aggregate((*ptr), NULL) != FFI_OK))
return FFI_BAD_TYPEDEF;
#ifndef FFI_TARGET_HAS_COMPLEX_TYPE
if ((*ptr)->type == FFI_TYPE_COMPLEX)
abort();
#endif
/* Perform a sanity check on the argument type, do this
check after the initialization. */
FFI_ASSERT_VALID_TYPE(*ptr);
#if !defined FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION
{
/* Add any padding if necessary */
if (((*ptr)->alignment - 1) & bytes)
bytes = (unsigned)FFI_ALIGN(bytes, (*ptr)->alignment);
#ifdef TILE
if (bytes < 10 * FFI_SIZEOF_ARG &&
bytes + STACK_ARG_SIZE((*ptr)->size) > 10 * FFI_SIZEOF_ARG)
{
/* An argument is never split between the 10 parameter
registers and the stack. */
bytes = 10 * FFI_SIZEOF_ARG;
}
#endif
#ifdef XTENSA
if (bytes <= 6*4 && bytes + STACK_ARG_SIZE((*ptr)->size) > 6*4)
bytes = 6*4;
#endif
bytes += (unsigned int)STACK_ARG_SIZE((*ptr)->size);
}
#endif
}
cif->bytes = bytes;
/* Perform machine dependent cif processing */
#ifdef FFI_TARGET_SPECIFIC_VARIADIC
if (isvariadic)
return ffi_prep_cif_machdep_var(cif, nfixedargs, ntotalargs);
#endif
return ffi_prep_cif_machdep(cif);
}
#endif /* not __CRIS__ */
ffi_status ffi_prep_cif(ffi_cif *cif, ffi_abi abi, unsigned int nargs,
ffi_type *rtype, ffi_type **atypes)
{
return ffi_prep_cif_core(cif, abi, 0, nargs, nargs, rtype, atypes);
}
ffi_status ffi_prep_cif_var(ffi_cif *cif,
ffi_abi abi,
unsigned int nfixedargs,
unsigned int ntotalargs,
ffi_type *rtype,
ffi_type **atypes)
{
return ffi_prep_cif_core(cif, abi, 1, nfixedargs, ntotalargs, rtype, atypes);
}
#if FFI_CLOSURES
ffi_status
ffi_prep_closure (ffi_closure* closure,
ffi_cif* cif,
void (*fun)(ffi_cif*,void*,void**,void*),
void *user_data)
{
return ffi_prep_closure_loc (closure, cif, fun, user_data, closure);
}
#endif
ffi_status
ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type, size_t *offsets)
{
if (! (abi > FFI_FIRST_ABI && abi < FFI_LAST_ABI))
return FFI_BAD_ABI;
if (struct_type->type != FFI_TYPE_STRUCT)
return FFI_BAD_TYPEDEF;
#if HAVE_LONG_DOUBLE_VARIANT
ffi_prep_types (abi);
#endif
return initialize_aggregate(struct_type, offsets);
}
|
8dc7503798b053e86aa6beab2e054a6662ee15d3
|
8b99ca6b04516ce93b0bea35335e0e57029ac498
|
/io/png_write/WritePng.c
|
4bf0451e2bc9b4a4e4194a9b029710565387dc58
|
[
"MIT"
] |
permissive
|
dmtrKovalenko/odiff
|
4840a90875e93b6101e0dcd0fc885f336ff33a34
|
f5789358f2a90571fec0b98063cc0b2ac83330a6
|
refs/heads/main
| 2023-09-04T17:28:01.134340
| 2023-08-24T20:21:16
| 2023-08-24T20:21:16
| 310,022,924
| 1,732
| 77
|
MIT
| 2023-08-24T20:21:18
| 2020-11-04T14:15:02
|
Reason
|
UTF-8
|
C
| false
| false
| 2,582
|
c
|
WritePng.c
|
#define CAML_NAME_SPACE
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <caml/memory.h>
#include <caml/fail.h>
#include <caml/bigarray.h>
#include <spng.h>
char *concat(const char *s1, const char *s2)
{
char *result = malloc(strlen(s1) + strlen(s2) + 1); // +1 for the null-terminator
if (result == NULL)
{
caml_failwith("Can not concat strings");
}
strcpy(result, s1);
strcat(result, s2);
return result;
}
value write_png_bigarray(value filename_val, value bigarray, value width_val, value height_val)
{
CAMLparam4(filename_val, bigarray, width_val, height_val);
int width = Int_val(width_val);
int height = Int_val(height_val);
const char *data = Caml_ba_data_val(bigarray);
const char *filename = String_val(filename_val);
FILE *fp;
if ((fp = fopen(filename, "wb")) == NULL)
{
char *err = strerror(errno);
char *message = concat("Can not write diff output. fopen error: ", err);
caml_failwith(message);
free(err);
free(message);
}
int result = 0;
uint8_t bit_depth = 8;
uint8_t color_type = SPNG_COLOR_TYPE_TRUECOLOR_ALPHA;
uint8_t compression_method = 0;
uint8_t filter_method = SPNG_FILTER_NONE;
uint8_t interlace_method = SPNG_INTERLACE_NONE;
size_t out_size = width * height * 4;
size_t out_width = out_size / height;
spng_ctx *ctx = spng_ctx_new(SPNG_CTX_ENCODER);
struct spng_ihdr ihdr = {
width,
height,
bit_depth,
color_type,
compression_method,
filter_method,
interlace_method,
};
result = spng_set_ihdr(ctx, &ihdr);
if (result)
{
spng_ctx_free(ctx);
fclose(fp);
caml_failwith(spng_strerror(result));
}
result = spng_set_option(ctx, SPNG_FILTER_CHOICE, SPNG_DISABLE_FILTERING);
if (result)
{
spng_ctx_free(ctx);
fclose(fp);
caml_failwith(spng_strerror(result));
}
result = spng_set_png_file(ctx, fp);
if (result)
{
fclose(fp);
spng_ctx_free(ctx);
caml_failwith(spng_strerror(result));
}
result = spng_encode_image(ctx, 0, 0, SPNG_FMT_PNG, SPNG_ENCODE_PROGRESSIVE);
if (result)
{
fclose(fp);
spng_ctx_free(ctx);
caml_failwith(spng_strerror(result));
}
for (int i = 0; i < ihdr.height; i++)
{
const char *row = data + out_width * i;
result = spng_encode_scanline(ctx, row, out_width);
if (result)
break;
}
if (result != SPNG_EOI)
{
spng_ctx_free(ctx);
fclose(fp);
caml_failwith(spng_strerror(result));
}
spng_ctx_free(ctx);
fclose(fp);
CAMLreturn(Val_unit);
}
|
b6220d4a9698d8a6d4ae15681bf97a47fcfdae79
|
99bdb3251fecee538e0630f15f6574054dfc1468
|
/bsp/samd21/sam_d2x_asflib/sam0/drivers/slcd/slcd_callback.c
|
9b300aded11fbad3f08c581072e40dca09a90e95
|
[
"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
| 3,761
|
c
|
slcd_callback.c
|
/**
*
* \file
*
* \brief SAM Segment Liquid Crystal Display(SLCD) Controller.
*
* Copyright (c) 2015 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 4. This software may only be redistributed and used in connection with an
* Atmel microcontroller product.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \asf_license_stop
*
*/
/*
* Support and FAQ: visit <a href="http://www.atmel.com/design-support/">Atmel Support</a>
*/
#include "slcd.h"
#include "slcd_callback.h"
/**
* \internal
* \brief slcd callback function pointer
*/
slcd_callback_t slcd_callback_pointer[SLCD_CALLBACK_TYPE_NUM];
/**
* \brief Registers a callback
*
* Registers a callback function which is implemented by the user.
*
* \note The callback must be enabled by \ref slcd_enable_callback,
* in order for the interrupt handler to call it when the conditions for the
* callback type is met.
*
* \param[in] callback_func Pointer to callback function
* \param[in] callback_type Callback type given by an enum
*
* \retval STATUS_OK The function exited successfully
* \retval STATUS_ERR_INVALID_ARG If an invalid callback type was supplied
*/
enum status_code slcd_register_callback(
const slcd_callback_t callback,
const enum slcd_callback_type type)
{
if (type >= SLCD_CALLBACK_TYPE_NUM){
return STATUS_ERR_INVALID_ARG;
}
slcd_callback_pointer[type] = callback;
return STATUS_OK;
}
/**
* \brief Unregisters a callback
*
* Unregisters a callback function implemented by the user.
*
* \param[in] callback_type Callback type given by an enum
*
* \retval STATUS_OK The function exited successfully
* \retval STATUS_ERR_INVALID_ARG If an invalid callback type was supplied
*/
enum status_code slcd_unregister_callback(
const slcd_callback_t callback,
const enum slcd_callback_type type)
{
if (type >= SLCD_CALLBACK_TYPE_NUM){
return STATUS_ERR_INVALID_ARG;
}
slcd_callback_pointer[type] = NULL;
return STATUS_OK;
}
/**
* \internal The SLCD interrupt handler.
*/
void SLCD_Handler(void)
{
uint32_t status = SLCD->INTFLAG.reg;
for (uint8_t i = 0; i < SLCD_CALLBACK_TYPE_NUM; i++) {
if (status & (1 << i)) {
/* Clear the INTFLAG anyway */
SLCD->INTFLAG.reg = 1 << i;
if (slcd_callback_pointer[i]) {
slcd_callback_pointer[i]((enum slcd_callback_type)i);
}
}
}
}
|
d749c645e3124d5a68cf0fdc3b54243826feda19
|
6832a9c81b16ead373325f70fb97753d6a211539
|
/src/wrapped/wrappedsdl2.c
|
201fc684cdbfa5331a65b1535293ef03080c5601
|
[
"MIT"
] |
permissive
|
ptitSeb/box86
|
2d3a0c4574905ff8d9dc7b5afb5444a273832bd6
|
ad934455c1b40feeebe5e6bd09b9063519102859
|
refs/heads/master
| 2023-08-22T05:30:54.331500
| 2023-08-20T13:01:58
| 2023-08-20T13:01:58
| 164,844,546
| 2,877
| 294
|
MIT
| 2023-07-27T11:19:10
| 2019-01-09T10:49:32
|
C
|
UTF-8
|
C
| false
| false
| 29,645
|
c
|
wrappedsdl2.c
|
#define _GNU_SOURCE /* See feature_test_macros(7) */
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dlfcn.h>
#include <stdarg.h>
#include "wrappedlibs.h"
#include "debug.h"
#include "wrapper.h"
#include "bridge.h"
#include "callback.h"
#include "librarian.h"
#include "librarian/library_private.h"
#include "emu/x86emu_private.h"
#include "box86context.h"
#include "sdl2rwops.h"
#include "myalign.h"
#include "threads.h"
#include "gltools.h"
#include "generated/wrappedsdl2defs.h"
static void* my_glhandle = NULL;
// DL functions from wrappedlibdl.c
void* my_dlopen(x86emu_t* emu, void *filename, int flag);
int my_dlclose(x86emu_t* emu, void *handle);
void* my_dlsym(x86emu_t* emu, void *handle, void *symbol);
static int sdl_Yes() { return 1;}
static int sdl_No() { return 0;}
int EXPORT my2_SDL_Has3DNow() __attribute__((alias("sdl_No")));
int EXPORT my2_SDL_Has3DNowExt() __attribute__((alias("sdl_No")));
int EXPORT my2_SDL_HasAltiVec() __attribute__((alias("sdl_No")));
int EXPORT my2_SDL_HasMMX() __attribute__((alias("sdl_Yes")));
int EXPORT my2_SDL_HasMMXExt() __attribute__((alias("sdl_Yes")));
int EXPORT my2_SDL_HasNEON() __attribute__((alias("sdl_No"))); // No neon in x86 ;)
int EXPORT my2_SDL_HasRDTSC() __attribute__((alias("sdl_Yes")));
int EXPORT my2_SDL_HasSSE() __attribute__((alias("sdl_Yes")));
int EXPORT my2_SDL_HasSSE2() __attribute__((alias("sdl_Yes")));
int EXPORT my2_SDL_HasSSE3() __attribute__((alias("sdl_Yes")));
int EXPORT my2_SDL_HasSSE41() __attribute__((alias("sdl_No")));
int EXPORT my2_SDL_HasSSE42() __attribute__((alias("sdl_No")));
typedef struct {
int32_t freq;
uint16_t format;
uint8_t channels;
uint8_t silence;
uint16_t samples;
uint16_t padding;
uint32_t size;
void (*callback)(void *userdata, uint8_t *stream, int32_t len);
void *userdata;
} SDL2_AudioSpec;
typedef struct {
uint8_t data[16];
} SDL_JoystickGUID;
typedef union {
SDL_JoystickGUID guid;
uint32_t u[4];
} SDL_JoystickGUID_Helper;
typedef struct
{
uint32_t bindType; // enum
union
{
int button;
int axis;
struct {
int hat;
int hat_mask;
} hat;
} value;
} SDL_GameControllerButtonBind;
const char* sdl2Name = "libSDL2-2.0.so.0";
#define LIBNAME sdl2
typedef void (*vFv_t)();
typedef void (*vFiupp_t)(int32_t, uint32_t, void*, void*);
typedef int32_t (*iFpLpp_t)(void*, size_t, void*, void*);
typedef int32_t (*iFpupp_t)(void*, uint32_t, void*, void*);
#define ADDED_FUNCTIONS() \
GO(SDL_Quit, vFv_t) \
GO(SDL_AllocRW, sdl2_allocrw) \
GO(SDL_FreeRW, sdl2_freerw) \
GO(SDL_LogMessageV, vFiupp_t)
#include "generated/wrappedsdl2types.h"
#include "wrappercallback.h"
#define SUPER() \
GO(0) \
GO(1) \
GO(2) \
GO(3) \
GO(4)
// Timer
#define GO(A) \
static uintptr_t my_Timer_fct_##A = 0; \
static uint32_t my_Timer_##A(uint32_t a, void* b) \
{ \
return (uint32_t)RunFunctionFmt(my_Timer_fct_##A, "up", a, b); \
}
SUPER()
#undef GO
static void* find_Timer_Fct(void* fct)
{
if(!fct) return NULL;
void* p;
if((p = GetNativeFnc((uintptr_t)fct))) return p;
#define GO(A) if(my_Timer_fct_##A == (uintptr_t)fct) return my_Timer_##A;
SUPER()
#undef GO
#define GO(A) if(my_Timer_fct_##A == 0) {my_Timer_fct_##A = (uintptr_t)fct; return my_Timer_##A; }
SUPER()
#undef GO
printf_log(LOG_NONE, "Warning, no more slot for SDL2 Timer callback\n");
return NULL;
}
// AudioCallback
#define GO(A) \
static uintptr_t my_AudioCallback_fct_##A = 0; \
static void my_AudioCallback_##A(void* a, void* b, int c) \
{ \
RunFunctionFmt(my_AudioCallback_fct_##A, "ppi", a, b, c); \
}
SUPER()
#undef GO
static void* find_AudioCallback_Fct(void* fct)
{
if(!fct) return NULL;
void* p;
if((p = GetNativeFnc((uintptr_t)fct))) return p;
#define GO(A) if(my_AudioCallback_fct_##A == (uintptr_t)fct) return my_AudioCallback_##A;
SUPER()
#undef GO
#define GO(A) if(my_AudioCallback_fct_##A == 0) {my_AudioCallback_fct_##A = (uintptr_t)fct; return my_AudioCallback_##A; }
SUPER()
#undef GO
printf_log(LOG_NONE, "Warning, no more slot for SDL2 AudioCallback callback\n");
return NULL;
}
// eventfilter
#define GO(A) \
static uintptr_t my_eventfilter_fct_##A = 0; \
static int my_eventfilter_##A(void* userdata, void* event) \
{ \
return (int)RunFunctionFmt(my_eventfilter_fct_##A, "pp", userdata, event); \
}
SUPER()
#undef GO
static void* find_eventfilter_Fct(void* fct)
{
if(!fct) return NULL;
void* p;
if((p = GetNativeFnc((uintptr_t)fct))) return p;
#define GO(A) if(my_eventfilter_fct_##A == (uintptr_t)fct) return my_eventfilter_##A;
SUPER()
#undef GO
#define GO(A) if(my_eventfilter_fct_##A == 0) {my_eventfilter_fct_##A = (uintptr_t)fct; return my_eventfilter_##A; }
SUPER()
#undef GO
printf_log(LOG_NONE, "Warning, no more slot for SDL2 eventfilter callback\n");
return NULL;
}
static void* reverse_eventfilter_Fct(void* fct)
{
if(!fct) return fct;
if(CheckBridged(my_lib->w.bridge, fct))
return (void*)CheckBridged(my_lib->w.bridge, fct);
#define GO(A) if(my_eventfilter_##A == fct) return (void*)my_eventfilter_fct_##A;
SUPER()
#undef GO
return (void*)AddBridge(my_lib->w.bridge, iFpp, fct, 0, NULL);
}
// LogOutput
#define GO(A) \
static uintptr_t my_LogOutput_fct_##A = 0; \
static void my_LogOutput_##A(void* a, int b, int c, void* d) \
{ \
RunFunctionFmt(my_LogOutput_fct_##A, "piip", a, b, c, d); \
}
SUPER()
#undef GO
static void* find_LogOutput_Fct(void* fct)
{
if(!fct) return fct;
if(GetNativeFnc((uintptr_t)fct)) return GetNativeFnc((uintptr_t)fct);
#define GO(A) if(my_LogOutput_fct_##A == (uintptr_t)fct) return my_LogOutput_##A;
SUPER()
#undef GO
#define GO(A) if(my_LogOutput_fct_##A == 0) {my_LogOutput_fct_##A = (uintptr_t)fct; return my_LogOutput_##A; }
SUPER()
#undef GO
printf_log(LOG_NONE, "Warning, no more slot for SDL2 LogOutput callback\n");
return NULL;
}
static void* reverse_LogOutput_Fct(void* fct)
{
if(!fct) return fct;
if(CheckBridged(my_lib->w.bridge, fct))
return (void*)CheckBridged(my_lib->w.bridge, fct);
#define GO(A) if(my_LogOutput_##A == fct) return (void*)my_LogOutput_fct_##A;
SUPER()
#undef GO
return (void*)AddBridge(my_lib->w.bridge, vFpiip, fct, 0, NULL);
}
#undef SUPER
// TODO: track the memory for those callback
EXPORT int32_t my2_SDL_OpenAudio(x86emu_t* emu, void* d, void* o)
{
(void)emu;
SDL2_AudioSpec *desired = (SDL2_AudioSpec*)d;
// create a callback
void *fnc = (void*)desired->callback;
desired->callback = find_AudioCallback_Fct(fnc);
int ret = my->SDL_OpenAudio(desired, (SDL2_AudioSpec*)o);
if (ret!=0) {
// error, clean the callback...
desired->callback = fnc;
return ret;
}
// put back stuff in place?
desired->callback = fnc;
return ret;
}
EXPORT int32_t my2_SDL_OpenAudioDevice(x86emu_t* emu, void* device, int32_t iscapture, void* d, void* o, int32_t allowed)
{
(void)emu;
SDL2_AudioSpec *desired = (SDL2_AudioSpec*)d;
// create a callback
void *fnc = (void*)desired->callback;
desired->callback = find_AudioCallback_Fct(fnc);
int ret = my->SDL_OpenAudioDevice(device, iscapture, desired, (SDL2_AudioSpec*)o, allowed);
if (ret<=0) {
// error, clean the callback...
desired->callback = fnc;
return ret;
}
// put back stuff in place?
desired->callback = fnc;
return ret;
}
EXPORT void *my2_SDL_LoadFile_RW(x86emu_t* emu, void* a, void* b, int c)
{
SDL2_RWops_t *rw = RWNativeStart2(emu, (SDL2_RWops_t*)a);
void* r = my->SDL_LoadFile_RW(rw, b, c);
if(c==0)
RWNativeEnd2(rw);
return r;
}
EXPORT void *my2_SDL_LoadBMP_RW(x86emu_t* emu, void* a, int b)
{
SDL2_RWops_t *rw = RWNativeStart2(emu, (SDL2_RWops_t*)a);
void* r = my->SDL_LoadBMP_RW(rw, b);
if(b==0)
RWNativeEnd2(rw);
return r;
}
EXPORT int32_t my2_SDL_SaveBMP_RW(x86emu_t* emu, void* a, void* b, int c)
{
SDL2_RWops_t *rw = RWNativeStart2(emu, (SDL2_RWops_t*)a);
int32_t r = my->SDL_SaveBMP_RW(rw, b, c);
if(c==0)
RWNativeEnd2(rw);
return r;
}
EXPORT void *my2_SDL_LoadWAV_RW(x86emu_t* emu, void* a, int b, void* c, void* d, void* e)
{
SDL2_RWops_t *rw = RWNativeStart2(emu, (SDL2_RWops_t*)a);
void* r = my->SDL_LoadWAV_RW(rw, b, c, d, e);
if(b==0)
RWNativeEnd2(rw);
return r;
}
EXPORT int32_t my2_SDL_GameControllerAddMappingsFromRW(x86emu_t* emu, void* a, int b)
{
SDL2_RWops_t *rw = RWNativeStart2(emu, (SDL2_RWops_t*)a);
int32_t r = my->SDL_GameControllerAddMappingsFromRW(rw, b);
if(b==0)
RWNativeEnd2(rw);
return r;
}
EXPORT uint32_t my2_SDL_ReadU8(x86emu_t* emu, void* a)
{
SDL2_RWops_t *rw = RWNativeStart2(emu, (SDL2_RWops_t*)a);
uint32_t r = my->SDL_ReadU8(rw);
RWNativeEnd2(rw);
return r;
}
EXPORT uint32_t my2_SDL_ReadBE16(x86emu_t* emu, void* a)
{
SDL2_RWops_t *rw = RWNativeStart2(emu, (SDL2_RWops_t*)a);
uint32_t r = my->SDL_ReadBE16(rw);
RWNativeEnd2(rw);
return r;
}
EXPORT uint32_t my2_SDL_ReadBE32(x86emu_t* emu, void* a)
{
SDL2_RWops_t *rw = RWNativeStart2(emu, (SDL2_RWops_t*)a);
uint32_t r = my->SDL_ReadBE32(rw);
RWNativeEnd2(rw);
return r;
}
EXPORT uint64_t my2_SDL_ReadBE64(x86emu_t* emu, void* a)
{
SDL2_RWops_t *rw = RWNativeStart2(emu, (SDL2_RWops_t*)a);
uint64_t r = my->SDL_ReadBE64(rw);
RWNativeEnd2(rw);
return r;
}
EXPORT uint32_t my2_SDL_ReadLE16(x86emu_t* emu, void* a)
{
SDL2_RWops_t *rw = RWNativeStart2(emu, (SDL2_RWops_t*)a);
uint32_t r = my->SDL_ReadLE16(rw);
RWNativeEnd2(rw);
return r;
}
EXPORT uint32_t my2_SDL_ReadLE32(x86emu_t* emu, void* a)
{
SDL2_RWops_t *rw = RWNativeStart2(emu, (SDL2_RWops_t*)a);
uint32_t r = my->SDL_ReadLE32(rw);
RWNativeEnd2(rw);
return r;
}
EXPORT uint64_t my2_SDL_ReadLE64(x86emu_t* emu, void* a)
{
SDL2_RWops_t *rw = RWNativeStart2(emu, (SDL2_RWops_t*)a);
uint64_t r = my->SDL_ReadLE64(rw);
RWNativeEnd2(rw);
return r;
}
EXPORT uint32_t my2_SDL_WriteU8(x86emu_t* emu, void* a, uint8_t v)
{
SDL2_RWops_t *rw = RWNativeStart2(emu, (SDL2_RWops_t*)a);
uint32_t r = my->SDL_WriteU8(rw, v);
RWNativeEnd2(rw);
return r;
}
EXPORT uint32_t my2_SDL_WriteBE16(x86emu_t* emu, void* a, uint16_t v)
{
SDL2_RWops_t *rw = RWNativeStart2(emu, (SDL2_RWops_t*)a);
uint32_t r = my->SDL_WriteBE16(rw, v);
RWNativeEnd2(rw);
return r;
}
EXPORT uint32_t my2_SDL_WriteBE32(x86emu_t* emu, void* a, uint32_t v)
{
SDL2_RWops_t *rw = RWNativeStart2(emu, (SDL2_RWops_t*)a);
uint32_t r = my->SDL_WriteBE32(rw, v);
RWNativeEnd2(rw);
return r;
}
EXPORT uint32_t my2_SDL_WriteBE64(x86emu_t* emu, void* a, uint64_t v)
{
SDL2_RWops_t *rw = RWNativeStart2(emu, (SDL2_RWops_t*)a);
uint32_t r = my->SDL_WriteBE64(rw, v);
RWNativeEnd2(rw);
return r;
}
EXPORT uint32_t my2_SDL_WriteLE16(x86emu_t* emu, void* a, uint16_t v)
{
SDL2_RWops_t *rw = RWNativeStart2(emu, (SDL2_RWops_t*)a);
uint32_t r = my->SDL_WriteLE16(rw, v);
RWNativeEnd2(rw);
return r;
}
EXPORT uint32_t my2_SDL_WriteLE32(x86emu_t* emu, void* a, uint32_t v)
{
SDL2_RWops_t *rw = RWNativeStart2(emu, (SDL2_RWops_t*)a);
uint32_t r = my->SDL_WriteLE32(rw, v);
RWNativeEnd2(rw);
return r;
}
EXPORT uint32_t my2_SDL_WriteLE64(x86emu_t* emu, void* a, uint64_t v)
{
SDL2_RWops_t *rw = RWNativeStart2(emu, (SDL2_RWops_t*)a);
uint32_t r = my->SDL_WriteLE64(rw, v);
RWNativeEnd2(rw);
return r;
}
EXPORT void *my2_SDL_RWFromConstMem(x86emu_t* emu, void* a, int b)
{
void* r = my->SDL_RWFromConstMem(a, b);
return AddNativeRW2(emu, (SDL2_RWops_t*)r);
}
EXPORT void *my2_SDL_RWFromFP(x86emu_t* emu, void* a, int b)
{
void* r = my->SDL_RWFromFP(a, b);
return AddNativeRW2(emu, (SDL2_RWops_t*)r);
}
EXPORT void *my2_SDL_RWFromFile(x86emu_t* emu, void* a, void* b)
{
void* r = my->SDL_RWFromFile(a, b);
return AddNativeRW2(emu, (SDL2_RWops_t*)r);
}
EXPORT void *my2_SDL_RWFromMem(x86emu_t* emu, void* a, int b)
{
void* r = my->SDL_RWFromMem(a, b);
return AddNativeRW2(emu, (SDL2_RWops_t*)r);
}
EXPORT int64_t my2_SDL_RWseek(x86emu_t* emu, void* a, int64_t offset, int32_t whence)
{
SDL2_RWops_t *rw = RWNativeStart2(emu, (SDL2_RWops_t*)a);
int64_t ret = RWNativeSeek2(rw, offset, whence);
RWNativeEnd2(rw);
return ret;
}
EXPORT int64_t my2_SDL_RWsize(x86emu_t* emu, void* a)
{
SDL2_RWops_t *rw = RWNativeStart2(emu, (SDL2_RWops_t*)a);
int64_t ret = my->SDL_RWsize(rw);
RWNativeEnd2(rw);
return ret;
}
EXPORT int64_t my2_SDL_RWtell(x86emu_t* emu, void* a)
{
SDL2_RWops_t *rw = RWNativeStart2(emu, (SDL2_RWops_t*)a);
int64_t ret = RWNativeSeek2(rw, 0, 1); //1 == RW_SEEK_CUR
RWNativeEnd2(rw);
return ret;
}
EXPORT uint32_t my2_SDL_RWread(x86emu_t* emu, void* a, void* ptr, uint32_t size, uint32_t maxnum)
{
SDL2_RWops_t *rw = RWNativeStart2(emu, (SDL2_RWops_t*)a);
uint32_t ret = RWNativeRead2(rw, ptr, size, maxnum);
RWNativeEnd2(rw);
return ret;
}
EXPORT uint32_t my2_SDL_RWwrite(x86emu_t* emu, void* a, const void* ptr, uint32_t size, uint32_t maxnum)
{
SDL2_RWops_t *rw = RWNativeStart2(emu, (SDL2_RWops_t*)a);
uint32_t ret = RWNativeWrite2(rw, ptr, size, maxnum);
RWNativeEnd2(rw);
return ret;
}
EXPORT int my2_SDL_RWclose(x86emu_t* emu, void* a)
{
SDL2_RWops_t *rw = RWNativeStart2(emu, (SDL2_RWops_t*)a);
return RWNativeClose2(rw);
}
EXPORT int my2_SDL_SaveAllDollarTemplates(x86emu_t* emu, void* a)
{
SDL2_RWops_t *rw = RWNativeStart2(emu, (SDL2_RWops_t*)a);
uint32_t ret = my->SDL_SaveAllDollarTemplates(rw);
RWNativeEnd2(rw);
return ret;
}
EXPORT int my2_SDL_SaveDollarTemplate(x86emu_t* emu, int gesture, void* a)
{
SDL2_RWops_t *rw = RWNativeStart2(emu, (SDL2_RWops_t*)a);
uint32_t ret = my->SDL_SaveDollarTemplate(gesture, rw);
RWNativeEnd2(rw);
return ret;
}
EXPORT void *my2_SDL_AddTimer(x86emu_t* emu, uint32_t a, void* f, void* p)
{
(void)emu;
return my->SDL_AddTimer(a, find_Timer_Fct(f), p);
}
EXPORT int my2_SDL_RemoveTimer(x86emu_t* emu, void *t)
{
(void)emu;
return my->SDL_RemoveTimer(t);
}
EXPORT void my2_SDL_SetEventFilter(x86emu_t* emu, void* p, void* userdata)
{
(void)emu;
my->SDL_SetEventFilter(find_eventfilter_Fct(p), userdata);
}
EXPORT int my2_SDL_GetEventFilter(x86emu_t* emu, void** f, void* userdata)
{
(void)emu;
int ret = my->SDL_GetEventFilter(f, userdata);
*f = reverse_eventfilter_Fct(*f);
return ret;
}
EXPORT void my2_SDL_LogGetOutputFunction(x86emu_t* emu, void** f, void* arg)
{
(void)emu;
my->SDL_LogGetOutputFunction(f, arg);
if(*f) *f = reverse_LogOutput_Fct(*f);
}
EXPORT void my2_SDL_LogSetOutputFunction(x86emu_t* emu, void* f, void* arg)
{
(void)emu;
my->SDL_LogSetOutputFunction(find_LogOutput_Fct(f), arg);
}
EXPORT int my2_SDL_vsnprintf(x86emu_t* emu, void* buff, uint32_t s, void * fmt, void * b) {
#ifndef NOALIGN
// need to align on arm
myStackAlign((const char*)fmt, b, emu->scratch);
PREPARE_VALIST;
void* f = vsnprintf;
return ((iFpLpp_t)f)(buff, s, fmt, VARARGS);
#else
(void)emu;
return vsnprintf(buff, s, fmt, b);
#endif
}
EXPORT void* my2_SDL_CreateThread(x86emu_t* emu, void* f, void* n, void* p)
{
void* et = NULL;
return my->SDL_CreateThread(my_prepare_thread(emu, f, p, 0, &et), n, et);
}
EXPORT int my2_SDL_snprintf(x86emu_t* emu, void* buff, uint32_t s, void * fmt, void * b) {
#ifndef NOALIGN
// need to align on arm
myStackAlign((const char*)fmt, b, emu->scratch);
PREPARE_VALIST;
void* f = vsnprintf;
return ((iFpLpp_t)f)(buff, s, fmt, VARARGS);
#else
(void)emu;
return vsnprintf((char*)buff, s, (char*)fmt, b);
#endif
}
static int get_sdl_priv(x86emu_t* emu, const char *sym_str, void **w, void **f)
{
#define GO(sym, _w) \
else if (strcmp(#sym, sym_str) == 0) \
{ \
*w = _w; \
*f = dlsym(emu->context->sdl2lib->w.lib, #sym); \
return *f != NULL; \
}
#define GO2(sym, _w, sym2) \
else if (strcmp(#sym, sym_str) == 0) \
{ \
*w = _w; \
*f = dlsym(emu->context->sdl2lib->w.lib, #sym2); \
return *f != NULL; \
}
#define GOM(sym, _w) \
else if (strcmp(#sym, sym_str) == 0) \
{ \
*w = _w; \
*f = dlsym(emu->context->box86lib, "my2_"#sym); \
return *f != NULL; \
}
#define GOS(sym, _w) GOM(sym, _w)
#define DATA
if(0);
#include "wrappedsdl2_private.h"
#undef GO
#undef GOM
#undef GO2
#undef GOS
#undef DATA
return 0;
}
int EXPORT my2_SDL_DYNAPI_entry(x86emu_t* emu, uint32_t version, uintptr_t *table, uint32_t tablesize)
{
uint32_t i = 0;
uintptr_t tab[tablesize];
int r = my->SDL_DYNAPI_entry(version, tab, tablesize);
(void)r;
#define SDL_DYNAPI_PROC(ret, sym, args, parms, ...) \
if (i < tablesize) { \
void *w = NULL; \
void *f = NULL; \
if (get_sdl_priv(emu, #sym, &w, &f)) { \
table[i] = AddCheckBridge(my_lib->w.bridge, w, f, 0, #sym); \
} \
else \
table[i] = (uintptr_t)NULL; \
printf_log(LOG_DEBUG, "SDL_DYNAPI_entry: %s => %p (%p)\n", #sym, (void*)table[i], f); \
i++; \
}
#include "SDL_dynapi_procs.h"
return 0;
}
EXPORT void *my2_SDL_CreateWindow(x86emu_t* emu, const char *title, int x, int y, int w, int h, uint32_t flags)
{
#ifdef GOA_CLONE
// For GO Advance clones, ignores the requested resolution and just uses the entire screen
x = y = 0;
w = h = -1;
#endif
// Set BOX86_FORCE_ES=MN or BOX86_FORCE_ES=M to force a specific OpenGL ES version.
// M = major version, N = minor version
const char *force_es = getenv("BOX86_FORCE_ES");
if (force_es && *force_es && (force_es[0] != '0')) {
#define SDL_GL_CONTEXT_PROFILE_MASK 21
#define SDL_GL_CONTEXT_PROFILE_ES 4
#define SDL_GL_CONTEXT_MAJOR_VERSION 17
#define SDL_GL_CONTEXT_MINOR_VERSION 18
#define SDL_WINDOW_OPENGL 2
// Is BOX86_FORCE_ES incorrectly formatted?
if (!isdigit(force_es[0]) || (force_es[1] != '\0' && !isdigit(force_es[1]))) {
printf_log(LOG_NONE, "Warning: ignoring malformed BOX86_FORCE_ES.\n");
} else {
int (*SDL_GL_SetAttribute_p)(uint32_t, int) = dlsym(emu->context->sdl2lib->w.lib, "SDL_GL_SetAttribute");
SDL_GL_SetAttribute_p(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
SDL_GL_SetAttribute_p(SDL_GL_CONTEXT_MAJOR_VERSION, force_es[0] - '0');
SDL_GL_SetAttribute_p(SDL_GL_CONTEXT_MINOR_VERSION, force_es[1] ? (force_es[1] - '0') : 0);
flags |= SDL_WINDOW_OPENGL;
}
}
return my->SDL_CreateWindow((void*)title, x, y, w, h, flags);
}
char EXPORT *my2_SDL_GetBasePath(x86emu_t* emu) {
char* p = strdup(emu->context->fullpath);
char* b = strrchr(p, '/');
if(b)
*(b+1) = '\0';
return p;
}
EXPORT void my2_SDL_LogCritical(x86emu_t* emu, int32_t cat, void* fmt, void *b) {
// SDL_LOG_PRIORITY_CRITICAL == 6
#ifndef NOALIGN
myStackAlign((const char*)fmt, b, emu->scratch);
PREPARE_VALIST;
my->SDL_LogMessageV(cat, 6, fmt, VARARGS);
#else
(void)emu;
my->SDL_LogMessageV(cat, 6, fmt, b);
#endif
}
EXPORT void my2_SDL_LogError(x86emu_t* emu, int32_t cat, void* fmt, void *b) {
// SDL_LOG_PRIORITY_ERROR == 5
#ifndef NOALIGN
myStackAlign((const char*)fmt, b, emu->scratch);
PREPARE_VALIST;
my->SDL_LogMessageV(cat, 5, fmt, VARARGS);
#else
(void)emu;
my->SDL_LogMessageV(cat, 5, fmt, b);
#endif
}
EXPORT void my2_SDL_LogWarn(x86emu_t* emu, int32_t cat, void* fmt, void *b) {
// SDL_LOG_PRIORITY_WARN == 4
#ifndef NOALIGN
myStackAlign((const char*)fmt, b, emu->scratch);
PREPARE_VALIST;
my->SDL_LogMessageV(cat, 4, fmt, VARARGS);
#else
(void)emu;
my->SDL_LogMessageV(cat, 4, fmt, b);
#endif
}
EXPORT void my2_SDL_LogInfo(x86emu_t* emu, int32_t cat, void* fmt, void *b) {
// SDL_LOG_PRIORITY_INFO == 3
#ifndef NOALIGN
myStackAlign((const char*)fmt, b, emu->scratch);
PREPARE_VALIST;
my->SDL_LogMessageV(cat, 3, fmt, VARARGS);
#else
(void)emu;
my->SDL_LogMessageV(cat, 3, fmt, b);
#endif
}
EXPORT void my2_SDL_LogDebug(x86emu_t* emu, int32_t cat, void* fmt, void *b) {
// SDL_LOG_PRIORITY_DEBUG == 2
#ifndef NOALIGN
myStackAlign((const char*)fmt, b, emu->scratch);
PREPARE_VALIST;
my->SDL_LogMessageV(cat, 2, fmt, VARARGS);
#else
(void)emu;
my->SDL_LogMessageV(cat, 2, fmt, b);
#endif
}
EXPORT void my2_SDL_LogVerbose(x86emu_t* emu, int32_t cat, void* fmt, void *b) {
// SDL_LOG_PRIORITY_VERBOSE == 1
#ifndef NOALIGN
myStackAlign((const char*)fmt, b, emu->scratch);
PREPARE_VALIST;
my->SDL_LogMessageV(cat, 1, fmt, VARARGS);
#else
(void)emu;
my->SDL_LogMessageV(cat, 1, fmt, b);
#endif
}
EXPORT void my2_SDL_Log(x86emu_t* emu, void* fmt, void *b) {
// SDL_LOG_PRIORITY_INFO == 3
// SDL_LOG_CATEGORY_APPLICATION == 0
#ifndef NOALIGN
myStackAlign((const char*)fmt, b, emu->scratch);
PREPARE_VALIST;
my->SDL_LogMessageV(0, 3, fmt, VARARGS);
#else
(void)emu;
my->SDL_LogMessageV(0, 3, fmt, b);
#endif
}
EXPORT void* my2_SDL_GL_GetProcAddress(x86emu_t* emu, void* name)
{
khint_t k;
const char* rname = (const char*)name;
static int lib_checked = 0;
if(!lib_checked) {
lib_checked = 1;
// check if libGL is loaded, load it if not (helps some Haxe games, like DeadCells or Nuclear Blaze)
if(!my_glhandle && !GetLibInternal(box86_libGL?box86_libGL:"libGL.so.1"))
// use a my_dlopen to actually open that lib, like SDL2 is doing...
my_glhandle = my_dlopen(emu, box86_libGL?box86_libGL:"libGL.so.1", RTLD_LAZY|RTLD_GLOBAL);
}
return getGLProcAddress(emu, (glprocaddress_t)my->SDL_GL_GetProcAddress, rname);
}
#define nb_once 16
typedef void(*sdl2_tls_dtor)(void*);
static uintptr_t dtor_emu[nb_once] = {0};
static void tls_dtor_callback(int n, void* a)
{
if(dtor_emu[n]) {
RunFunctionFmt(dtor_emu[n], "p", a);
}
}
#define GO(N) \
void tls_dtor_callback_##N(void* a) \
{ \
tls_dtor_callback(N, a); \
}
GO(0)
GO(1)
GO(2)
GO(3)
GO(4)
GO(5)
GO(6)
GO(7)
GO(8)
GO(9)
GO(10)
GO(11)
GO(12)
GO(13)
GO(14)
GO(15)
#undef GO
static const sdl2_tls_dtor dtor_cb[nb_once] = {
tls_dtor_callback_0, tls_dtor_callback_1, tls_dtor_callback_2, tls_dtor_callback_3
,tls_dtor_callback_4, tls_dtor_callback_5, tls_dtor_callback_6, tls_dtor_callback_7
,tls_dtor_callback_8, tls_dtor_callback_9, tls_dtor_callback_10,tls_dtor_callback_11
,tls_dtor_callback_12,tls_dtor_callback_13,tls_dtor_callback_14,tls_dtor_callback_15
};
EXPORT int32_t my2_SDL_TLSSet(x86emu_t* emu, uint32_t id, void* value, void* dtor)
{
(void)emu;
if(!dtor)
return my->SDL_TLSSet(id, value, NULL);
int n = 0;
while (n<nb_once) {
if(!dtor_emu[n] || (dtor_emu[n])==((uintptr_t)dtor)) {
dtor_emu[n] = (uintptr_t)dtor;
return my->SDL_TLSSet(id, value, dtor_cb[n]);
}
++n;
}
printf_log(LOG_NONE, "Error: SDL2 SDL_TLSSet with destructor: no more slot!\n");
//emu->quit = 1;
return -1;
}
EXPORT void* my2_SDL_JoystickGetDeviceGUID(x86emu_t* emu, void* p, int32_t idx)
{
(void)emu;
*(SDL_JoystickGUID*)p = my->SDL_JoystickGetDeviceGUID(idx);
return p;
}
EXPORT void* my2_SDL_JoystickGetGUID(x86emu_t* emu, void* p, void* joystick)
{
(void)emu;
*(SDL_JoystickGUID*)p = my->SDL_JoystickGetGUID(joystick);
return p;
}
EXPORT void* my2_SDL_JoystickGetGUIDFromString(x86emu_t* emu, void* p, void* pchGUID)
{
(void)emu;
*(SDL_JoystickGUID*)p = my->SDL_JoystickGetGUIDFromString(pchGUID);
return p;
}
EXPORT void* my2_SDL_GameControllerGetBindForAxis(x86emu_t* emu, void* p, void* controller, int32_t axis)
{
(void)emu;
*(SDL_GameControllerButtonBind*)p = my->SDL_GameControllerGetBindForAxis(controller, axis);
return p;
}
EXPORT void* my2_SDL_GameControllerGetBindForButton(x86emu_t* emu, void* p, void* controller, int32_t button)
{
(void)emu;
*(SDL_GameControllerButtonBind*)p = my->SDL_GameControllerGetBindForButton(controller, button);
return p;
}
EXPORT void my2_SDL_AddEventWatch(x86emu_t* emu, void* p, void* userdata)
{
(void)emu;
my->SDL_AddEventWatch(find_eventfilter_Fct(p), userdata);
}
EXPORT void my2_SDL_DelEventWatch(x86emu_t* emu, void* p, void* userdata)
{
(void)emu;
my->SDL_DelEventWatch(find_eventfilter_Fct(p), userdata);
}
EXPORT void* my2_SDL_LoadObject(x86emu_t* emu, void* sofile)
{
return my_dlopen(emu, sofile, 0); // TODO: check correct flag value...
}
EXPORT void my2_SDL_UnloadObject(x86emu_t* emu, void* handle)
{
my_dlclose(emu, handle);
}
EXPORT void* my2_SDL_LoadFunction(x86emu_t* emu, void* handle, void* name)
{
return my_dlsym(emu, handle, name);
}
EXPORT void my2_SDL_GetJoystickGUIDInfo(x86emu_t* emu, uint32_t a, uint32_t b, uint32_t c, uint32_t d, uint16_t* vendor, uint16_t* product, uint16_t* version)
{
(void)emu;
if(my->SDL_GetJoystickGUIDInfo) {
SDL_JoystickGUID_Helper guid;
guid.u[0] = a;
guid.u[1] = b;
guid.u[2] = c;
guid.u[3] = d;
my->SDL_GetJoystickGUIDInfo(guid.guid, vendor, product, version);
} else {
// dummy, set everything to "unknown"
if(vendor) *vendor = 0;
if(product) *product = 0;
if(version) *version = 0;
}
}
EXPORT int32_t my2_SDL_IsJoystickPS4(x86emu_t* emu, uint16_t vendor, uint16_t product_id)
{
(void)emu;
if(my->SDL_IsJoystickPS4)
return my->SDL_IsJoystickPS4(vendor, product_id);
// fallback
return 0;
}
EXPORT int32_t my2_SDL_IsJoystickNintendoSwitchPro(x86emu_t* emu, uint16_t vendor, uint16_t product_id)
{
(void)emu;
if(my->SDL_IsJoystickNintendoSwitchPro)
return my->SDL_IsJoystickNintendoSwitchPro(vendor, product_id);
// fallback
return 0;
}
EXPORT int32_t my2_SDL_IsJoystickSteamController(x86emu_t* emu, uint16_t vendor, uint16_t product_id)
{
(void)emu;
if(my->SDL_IsJoystickSteamController)
return my->SDL_IsJoystickSteamController(vendor, product_id);
// fallback
return 0;
}
EXPORT int32_t my2_SDL_IsJoystickXbox360(x86emu_t* emu, uint16_t vendor, uint16_t product_id)
{
(void)emu;
if(my->SDL_IsJoystickXbox360)
return my->SDL_IsJoystickXbox360(vendor, product_id);
// fallback
return 0;
}
EXPORT int32_t my2_SDL_IsJoystickXboxOne(x86emu_t* emu, uint16_t vendor, uint16_t product_id)
{
(void)emu;
if(my->SDL_IsJoystickXboxOne)
return my->SDL_IsJoystickXboxOne(vendor, product_id);
// fallback
return 0;
}
EXPORT int32_t my2_SDL_IsJoystickXInput(x86emu_t* emu, SDL_JoystickGUID p)
{
(void)emu;
if(my->SDL_IsJoystickXInput)
return my->SDL_IsJoystickXInput(p);
// fallback
return 0;
}
EXPORT int32_t my2_SDL_IsJoystickHIDAPI(x86emu_t* emu, SDL_JoystickGUID p)
{
(void)emu;
if(my->SDL_IsJoystickHIDAPI)
return my->SDL_IsJoystickHIDAPI(p);
// fallback
return 0;
}
void* my_vkGetInstanceProcAddr(x86emu_t* emu, void* device, void* name);
EXPORT void* my2_SDL_Vulkan_GetVkGetInstanceProcAddr(x86emu_t* emu)
{
if(!emu->context->vkprocaddress)
emu->context->vkprocaddress = (vkprocaddress_t)my->SDL_Vulkan_GetVkGetInstanceProcAddr();
if(emu->context->vkprocaddress)
return (void*)AddCheckBridge(my_lib->w.bridge, pFEpp, my_vkGetInstanceProcAddr, 0, "vkGetInstanceProcAddr");
return NULL;
}
#define CUSTOM_INIT \
box86->sdl2lib = lib; \
getMy(lib); \
box86->sdl2allocrw = my->SDL_AllocRW; \
box86->sdl2freerw = my->SDL_FreeRW; \
SETALT(my2_); \
setNeededLibs(lib, 4, \
"libdl.so.2", \
"libm.so.6", \
"librt.so.1", \
"libpthread.so.0");
#define CUSTOM_FINI \
my->SDL_Quit(); \
if(my_glhandle) my_dlclose(thread_get_emu(), my_glhandle); \
my_glhandle = NULL; \
freeMy(); \
my_context->sdl2lib = NULL; \
my_context->sdl2allocrw = NULL; \
my_context->sdl2freerw = NULL;
#include "wrappedlib_init.h"
|
dfcb4d41630da996a7135ed502f20a2cb2fda51e
|
ed98b77f3f09b392e68a0d59c48eec299e883bb9
|
/src/scip/struct_reopt.h
|
3399881c0f772fac3830e3a3e848a07dd5c293c8
|
[
"Apache-2.0"
] |
permissive
|
scipopt/scip
|
c8ddbe7cdec0a3af5a230c04b74b76ffacbdcc33
|
dc856a4c966ea50bd5f52c58d7be4fea33706f4c
|
refs/heads/master
| 2023-08-19T11:39:12.578790
| 2023-08-15T20:05:58
| 2023-08-15T20:05:58
| 342,522,859
| 262
| 46
|
NOASSERTION
| 2023-08-03T07:37:45
| 2021-02-26T09:16:17
|
C
|
UTF-8
|
C
| false
| false
| 12,830
|
h
|
struct_reopt.h
|
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* */
/* This file is part of the program and library */
/* SCIP --- Solving Constraint Integer Programs */
/* */
/* Copyright (c) 2002-2023 Zuse Institute Berlin (ZIB) */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* */
/* You should have received a copy of the Apache-2.0 license */
/* along with SCIP; see the file LICENSE. If not visit scipopt.org. */
/* */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**@file struct_reopt.h
* @ingroup INTERNALAPI
* @brief data structures for collecting reoptimization information
* @author Jakob Witzig
*/
/*---+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----+----9----+----0----+----1----+----2*/
#ifndef __SCIP_STRUCT_REOPT_H__
#define __SCIP_STRUCT_REOPT_H__
#include "scip/def.h"
#include "scip/type_clock.h"
#include "scip/type_cons.h"
#include "scip/type_history.h"
#include "scip/type_lp.h"
#include "scip/type_misc.h"
#include "scip/type_reopt.h"
#include "scip/type_sol.h"
#include "scip/type_var.h"
#ifdef __cplusplus
extern "C" {
#endif
/** nodes of SCIP_SolTree */
struct SCIP_SolNode
{
SCIP_SOL* sol; /**< the stored solution */
SCIP_SOLNODE* father; /**< pointer to the parent node */
SCIP_SOLNODE* child; /**< pointer to left most child node, i.e., node representing the variable
* with smallest solution value
*/
SCIP_SOLNODE* sibling; /**< pointer to next sibling node */
SCIP_Real value; /**< solution value represented by this node */
SCIP_Bool updated; /**< flag if the solution is already updated
* w.r.t. the new objective function */
#ifndef NDEBUG
SCIP_VAR* var; /**< variable represented by this node */
#endif
};
/** tree for solution */
struct SCIP_SolTree
{
SCIP_SOLNODE*** sols; /**< array of arrays of solutions of the reoptimization runs */
SCIP_SOLNODE* root; /**< root node of the solution tree */
int* solssize; /**< size of sols[x] arrays */
int* nsols; /**< number of solutions stored in sols[x] array */
};
/** data for constraints to split nodes during reoptimization */
struct SCIP_ReoptConsData
{
SCIP_VAR** vars; /**< array of variables */
SCIP_Real* vals; /**< array of variable coefficients or bounds */
SCIP_BOUNDTYPE* boundtypes; /**< array of variable bounds */
SCIP_Real lhs; /**< left hand side of the constraint */
SCIP_Real rhs; /**< right hand side of the constraint */
REOPT_CONSTYPE constype; /**< type of the constraint */
SCIP_Bool linear; /**< TRUE, iff the constraint is linear, otherwise the constraint is of
* type bounddisjunction
*/
int varssize; /**< available size in the arrays */
int nvars; /**< number of entries in the arrays */
};
/** nodes of SCIP_ReoptTree */
struct SCIP_ReoptNode
{
SCIP_REOPTCONSDATA** conss; /**< array of constraints added to the node, i.e., logic-or constraints */
SCIP_VAR** vars; /**< variables along the branching path up to the next stored node */
SCIP_VAR** afterdualvars; /**< variables along the branching path after the first decision based on dual information */
SCIP_REOPTCONSDATA* dualredscur; /**< dual reductions that need to be reconstructed the current round */
SCIP_REOPTCONSDATA* dualredsnex; /**< dual reductions that need to be reconstructed the next round */
SCIP_BOUNDTYPE* varboundtypes; /**< boundtypes along the branching path up to the next stored node */
SCIP_BOUNDTYPE* afterdualvarboundtypes; /**< boundtypes along the branching path after the first dual information */
SCIP_Real* varbounds; /**< bounds along the branching path up to the next stored node */
SCIP_Real* afterdualvarbounds; /**< bounds along the branching path after the first decision based on dual information */
SCIP_Real lowerbound; /**< the last lowerbound of this node in the previous iteration */
SCIP_Bool dualreds; /**< flag whether dual reduction were performed */
int nvars; /**< number of branching decisions up to the next stored node */
int varssize; /**< size of allocated memory */
int nafterdualvars; /**< number of branching decisions after the first dual information */
int afterdualvarssize; /**< size of allocated memory */
int nchilds; /**< number of child nodes */
int allocchildmem; /**< allocated memory for child nodes */
int nconss; /**< number of added constraints */
int consssize; /**< allocated memory for constraints */
unsigned int* childids; /**< array of child nodes that need to be reoptimized */
unsigned int parentID:29; /**< id of the stored parent node */
unsigned int reopttype:3; /**< reason for storing the node */
};
/* tree to store the current search tree */
struct SCIP_ReoptTree
{
SCIP_REOPTNODE** reoptnodes; /**< array of SCIP_REOPTNODE */
SCIP_QUEUE* openids; /**< queue of open positions in the reoptnodes array */
int nreoptnodes; /**< number of saved nodes */
int nfeasnodes; /**< number of feasible nodes in the current run */
int ntotalfeasnodes; /**< number of feasible nodes over all runs */
int ninfnodes; /**< number of (LP-)infeasible nodes in the current run */
int ntotalinfnodes; /**< number of (LP-)infeasible nodes over all runs */
int nprunednodes; /**< number of pruned nodes in the current run */
int ntotalprunednodes; /**< number of pruned nodes over all runs */
int ncutoffreoptnodes; /**< number of cut off reoptimized nodes in the current run */
int ntotalcutoffreoptnodes; /**< number of cut off reoptimized nodes over all runs */
SCIP_Bool initialized; /**< is the data structure initialized? */
unsigned int reoptnodessize; /**< size of allocated memory for the reoptnodes array and the openid queue */
};
/** reoptimization data and solution storage */
struct SCIP_Reopt
{
SCIP_SOL** prevbestsols; /**< list of best solutions of all previous rounds */
SCIP_Real** objs; /**< list of objective coefficients */
SCIP_HISTORY*** varhistory; /**< collected variable history */
SCIP_REOPTCONSDATA** glbconss; /**< global constraints that need to be added at the beginning of the next iteration */
SCIP_REOPTCONSDATA* dualreds; /**< dual reductions that probably need to be reconstructed at this node */
SCIP_REOPTTREE* reopttree; /**< data structure to store the current reoptimization search tree */
SCIP_SOLTREE* soltree; /**< tree to handle all saved solutions */
SCIP_RANDNUMGEN* randnumgen; /**< random number generator */
SCIP_CLOCK* savingtime; /**< time needed to store the nodes */
SCIP_CONS** addedconss; /**< array of added constraints */
SCIP_Real simtolastobj; /**< similarity to the last objective function */
SCIP_Real simtofirstobj; /**< similarity to the first objective function */
SCIP_Longint lastbranched; /**< number of the last branched node */
SCIP_Longint lastseennode; /**< node number of the last caught event */
int nobjvars; /**< number of variables in the objective function */
int addedconsssize; /**< size of addedconss array */
int naddedconss; /**< number of constraints added */
SCIP_Bool objhaschanged; /**< TRUE iff the objective fucntion has changd */
SCIP_Bool consadded; /**< TRUE iff a constraint was added */
int nactiveconss; /**< number of active constraints stored in activeconss */
SCIP_CONS** activeconss; /**< storage for active constraints */
int nmaxactiveconss; /**< maximal number of active constraints stored in activeconss */
/* hashmaps to track global bound reductions and constraints deletion during presolving */
SCIP_HASHMAP* glblb; /**< global lower bounds after presolving of the first problem */
SCIP_HASHMAP* glbub; /**< global upper bounds after presolving of the first problem */
SCIP_HASHSET* activeconssset; /**< set of all active constraints after presolving the first problem */
/* data structure to track decisions based on dual information */
SCIP_Longint currentnode; /**< number of the current node */
int run; /**< number of the current reoptimization run */
int runsize; /**< allocated memory for runs */
int firstobj; /**< first non empty objective function */
int noptsolsbyreoptsol; /**< number of successive optimal solutions found by heur_reoptsols */
int nglbconss; /**< number of stored global constraints */
int allocmemglbconss; /**< allocated memory for global constraints */
int ncheckedsols; /**< number of updated solutions by reoptsols */
int nimprovingsols; /**< number of improving solutions found by reoptsols */
int nglbrestarts; /**< number of global restarts */
int ntotallocrestarts; /**< number of local restarts over all runs */
int nlocrestarts; /**< number of local restarts in the current iteration */
int firstrestart; /**< run with the first global restart or -1 of no restart */
int lastrestart; /**< run with the last global restart or -1 if no restart */
};
#ifdef __cplusplus
}
#endif
#endif
|
d9bd3f73e25f3837d5ed508b1e1cee65794d69c0
|
e73547787354afd9b717ea57fe8dd0695d161821
|
/include/mapfs/kzn_05_hit.h
|
d445c07baab5bd335b802299ed756510acf260cc
|
[] |
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,046
|
h
|
kzn_05_hit.h
|
#define COLLIDER_Root 0x15
#define COLLIDER_g13 0x14
#define COLLIDER_g17 0x13
#define COLLIDER_o143 0x12
#define COLLIDER_o142 0x11
#define COLLIDER_g16 0x10
#define COLLIDER_o141 0xF
#define COLLIDER_o140 0xE
#define COLLIDER_o139 0xD
#define COLLIDER_g15 0xC
#define COLLIDER_o138 0xB
#define COLLIDER_deilit1 0xA
#define COLLIDER_deili1 0x9
#define COLLIDER_o135 0x8
#define COLLIDER_deilit2 0x7
#define COLLIDER_deili2 0x6
#define COLLIDER_g14 0x5
#define COLLIDER_o132 0x4
#define COLLIDER_o131 0x3
#define COLLIDER_o130 0x2
#define COLLIDER_o129 0x1
#define COLLIDER_o128 0x0
#define ZONE_Root 0x5
#define ZONE_Default 0x4
#define ZONE_o69 0x3
#define ZONE_o68 0x2
#define ZONE_o59 0x1
#define ZONE_o18 0x0
|
70bacf0e0fb2172593a65490119568912080f19b
|
b0f08154e3eebc7d8465efc57597e52d08d69c18
|
/src/connection/connection_list_cl.h
|
c214fdf464b388fdd994d78518ea57e98c0de21e
|
[
"BSD-3-Clause",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
CUBRID/cubrid
|
8f71a0010243b72e43ba887d229210650f4e901e
|
3b952af33230839a1b561a78ecd4b773374b66f8
|
refs/heads/develop
| 2023-08-18T19:16:30.987583
| 2023-08-18T08:18:05
| 2023-08-18T08:18:05
| 52,080,367
| 287
| 294
|
NOASSERTION
| 2023-09-14T21:29:09
| 2016-02-19T10:25:32
|
C
|
UTF-8
|
C
| false
| false
| 1,730
|
h
|
connection_list_cl.h
|
/*
* Copyright 2008 Search Solution Corporation
* Copyright 2016 CUBRID Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/*
* connection_list_cl.h -
*/
#ifndef _CONNECTION_LIST_CL_H_
#define _CONNECTION_LIST_CL_H_
#ident "$Id$"
#include "connection_defs.h"
extern void css_queue_unexpected_data_packet (CSS_CONN_ENTRY * conn, unsigned short request_id, char *header, int size,
int rc);
extern void css_queue_unexpected_error_packet (CSS_CONN_ENTRY * conn, unsigned short request_id, char *header, int size,
int rc);
extern void css_queue_unexpected_packet (int type, CSS_CONN_ENTRY * conn, unsigned short request_id,
NET_HEADER * header, int size);
extern int css_queue_user_data_buffer (CSS_CONN_ENTRY * conn, unsigned short request_id, int size, char *buffer);
extern CSS_QUEUE_ENTRY *css_find_queue_entry (CSS_QUEUE_ENTRY * header, unsigned int key);
extern void css_queue_remove_header_entry_ptr (CSS_QUEUE_ENTRY ** anchor, CSS_QUEUE_ENTRY * entry);
extern void css_queue_remove_header_entry (CSS_QUEUE_ENTRY ** anchor, unsigned short request_id);
extern void css_queue_remove_header (CSS_QUEUE_ENTRY ** anchor);
#endif /* _CONNECTION_LIST_CL_H_ */
|
6e2f69b3230f4869106cfdcf5ba95394681992ac
|
1c92d2c1fb2ed9a4bf6a9c9f1875bb5fff546086
|
/bus/controller.h
|
956d74571e52fd862adfc20bb2fdd82b5849eb58
|
[] |
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,463
|
h
|
controller.h
|
//
// bus/controller.h: System bus controller.
//
// 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.
//
#ifndef __bus_controller_h__
#define __bus_controller_h__
#include "common.h"
#include "bus/memorymap.h"
#include <setjmp.h>
struct ai_controller;
struct dd_controller;
struct pi_controller;
struct ri_controller;
struct si_controller;
struct vi_controller;
struct rdp;
struct rsp;
struct vr4300;
struct bus_controller {
struct ai_controller *ai;
struct dd_controller *dd;
struct pi_controller *pi;
struct ri_controller *ri;
struct si_controller *si;
struct vi_controller *vi;
struct rdp *rdp;
struct rsp *rsp;
struct vr4300 *vr4300;
// For resolving physical address ranges to devices.
struct memory_map map;
// Allows to to pop back out into device_run during simulation.
// Kind of a hack to put this in with the device "bus", but at
// least everyone gets access to it this way.
jmp_buf unwind_data;
};
cen64_cold int bus_init(struct bus_controller *bus, int dd_present);
// General-purpose accessor functions.
cen64_flatten cen64_hot int bus_read_word(const struct bus_controller *bus,
uint32_t address, uint32_t *word);
cen64_flatten cen64_hot int bus_write_word(struct bus_controller *bus,
uint32_t address, uint32_t word, uint32_t dqm);
#endif
|
7ecadc3988705672348c5d15242365cd1bc77eef
|
8551168c7b71c31eebad0f9b0c71eebbcc743000
|
/src/include/game/acosfasinf.h
|
d870f88f599dcb7039f9ebbe85d9e9d55a44d487
|
[
"MIT"
] |
permissive
|
n64decomp/perfect_dark
|
0db80e8ecba74741b959962e55c835a91c920f44
|
0235a971d6fb1a0d4421856d5a65aa8067bd4658
|
refs/heads/master
| 2023-08-31T04:27:53.864767
| 2023-08-29T11:36:58
| 2023-08-29T11:36:58
| 241,214,589
| 452
| 47
|
MIT
| 2023-08-21T08:53:40
| 2020-02-17T21:46:45
|
C
|
UTF-8
|
C
| false
| false
| 171
|
h
|
acosfasinf.h
|
#ifndef _IN_GAME_ACOSFASINF_H
#define _IN_GAME_ACOSFASINF_H
#include <ultra64.h>
#include "data.h"
#include "types.h"
f32 acosf(f32 value);
f32 asinf(f32 value);
#endif
|
0093d2f96ac88fbd60fb242e69fe932c21984c12
|
fb47ab6337a71029dee71933e449cf7f6805fc0f
|
/external/platform/lpc15xx/lpcopen/lpc_chip_15xx/inc/usbd/usbd_rom_api.h
|
b00bb52f6ebb1825e5246ae43a92327e78516da1
|
[
"MIT"
] |
permissive
|
littlekernel/lk
|
7e7ba50b87b1f2e0b6e2f052c59249825c91975b
|
30dc320054f70910e1c1ee40a6948ee99672acec
|
refs/heads/master
| 2023-09-02T00:47:52.203963
| 2023-06-21T22:42:35
| 2023-06-21T22:42:35
| 3,058,456
| 3,077
| 618
|
MIT
| 2023-08-30T09:41:31
| 2011-12-27T19:19:36
|
C
|
UTF-8
|
C
| false
| false
| 4,183
|
h
|
usbd_rom_api.h
|
/***********************************************************************
* $Id:: mw_usbd_rom_api.h 331 2012-08-09 18:54:34Z usb10131 $
*
* Project: USB device ROM Stack
*
* Description:
* ROM API Module definitions.
*
***********************************************************************
* Copyright(C) 2011, NXP Semiconductor
* All rights reserved.
*
* Software that is described herein is for illustrative purposes only
* which provides customers with programming information regarding the
* products. This software is supplied "AS IS" without any warranties.
* NXP Semiconductors assumes no responsibility or liability for the
* use of the software, conveys no license or title under any patent,
* copyright, or mask work right to the product. NXP Semiconductors
* reserves the right to make changes in the software without
* notification. NXP Semiconductors also make no representation or
* warranty that such application will be suitable for the specified
* use without further testing or modification.
**********************************************************************/
#ifndef __MW_USBD_ROM_API_H
#define __MW_USBD_ROM_API_H
/** \file
* \brief ROM API for USB device stack.
*
* Definition of functions exported by ROM based USB device stack.
*
*/
#include "error.h"
#include "usbd.h"
#include "usbd_hw.h"
#include "usbd_core.h"
#include "usbd_mscuser.h"
#include "usbd_dfuuser.h"
#include "usbd_hiduser.h"
#include "usbd_cdcuser.h"
/** \brief Main USBD API functions structure.
* \ingroup Group_USBD
*
* This structure contains pointer to various USB Device stack's sub-module
* function tables. This structure is used as main entry point to access
* various methods (grouped in sub-modules) exposed by ROM based USB device
* stack.
*
*/
typedef struct USBD_API
{
const USBD_HW_API_T* hw; /**< Pointer to function table which exposes functions
which interact directly with USB device stack's core
layer.*/
const USBD_CORE_API_T* core; /**< Pointer to function table which exposes functions
which interact directly with USB device controller
hardware.*/
const USBD_MSC_API_T* msc; /**< Pointer to function table which exposes functions
provided by MSC function driver module.
*/
const USBD_DFU_API_T* dfu; /**< Pointer to function table which exposes functions
provided by DFU function driver module.
*/
const USBD_HID_API_T* hid; /**< Pointer to function table which exposes functions
provided by HID function driver module.
*/
const USBD_CDC_API_T* cdc; /**< Pointer to function table which exposes functions
provided by CDC-ACM function driver module.
*/
const uint32_t* reserved6; /**< Reserved for future function driver module.
*/
const uint32_t version; /**< Version identifier of USB ROM stack. The version is
defined as 0x0CHDMhCC where each nibble represents version
number of the corresponding component.
CC - 7:0 - 8bit core version number
h - 11:8 - 4bit hardware interface version number
M - 15:12 - 4bit MSC class module version number
D - 19:16 - 4bit DFU class module version number
H - 23:20 - 4bit HID class module version number
C - 27:24 - 4bit CDC class module version number
H - 31:28 - 4bit reserved
*/
} USBD_API_T;
/* Applications using USBD ROM API should define this instance. The pointer should be assigned a value computed based on chip definitions. */
extern const USBD_API_T* g_pUsbApi;
#define USBD_API g_pUsbApi
#endif /*__MW_USBD_ROM_API_H*/
|
8f2dff2195bbbb97886939548c4d18268dde5e70
|
4805a71711625735215cc1a773a85712be305b59
|
/tests/run/complex_numbers_c89_T398.h
|
716da82374f6c7f8284321e91e97574d068e57ab
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
cython/cython
|
0a75b75b7eaf19eeedaaebca9d49adb603e3e8f5
|
6ba3daf319d94058de74e8e7f53f932092b38441
|
refs/heads/master
| 2023-09-04T11:09:56.569277
| 2023-09-04T07:45:47
| 2023-09-04T07:45:47
| 1,099,265
| 8,352
| 1,704
|
Apache-2.0
| 2023-09-14T06:33:34
| 2010-11-21T07:44:20
|
Python
|
UTF-8
|
C
| false
| false
| 26
|
h
|
complex_numbers_c89_T398.h
|
#define CYTHON_CCOMPLEX 0
|
e88678121d7c04a04cd92279b9b24117dc2ad0ad
|
c7c73566784a7896100e993606e1bd8fdd0ea94e
|
/dtool/src/parser-inc/mathematics.h
|
7be59e75ee3e2924600a4dc6bccec559ba22dbad
|
[
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
panda3d/panda3d
|
c3f94df2206ff7cfe4a3b370777a56fb11a07926
|
160ba090a5e80068f61f34fc3d6f49dbb6ad52c5
|
refs/heads/master
| 2023-08-21T13:23:16.904756
| 2021-04-11T22:55:33
| 2023-08-06T06:09:32
| 13,212,165
| 4,417
| 1,072
|
NOASSERTION
| 2023-09-09T19:26:14
| 2013-09-30T10:20:25
|
C++
|
UTF-8
|
C
| false
| false
| 96
|
h
|
mathematics.h
|
#ifndef MATHEMATICS_H
#define MATHEMATICS_H
#include "rational.h"
#endif /* MATHEMATICS_H */
|
1f6af48ac0c8f663e357189011519d475c8743ef
|
0744dcc5394cebf57ebcba343747af6871b67017
|
/apps/shell/tash_main.c
|
577f07ea7535e0d0cf197654ae1702f6abfb8f1d
|
[
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] |
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
| 14,177
|
c
|
tash_main.c
|
/****************************************************************************
*
* Copyright 2016 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.
*
****************************************************************************/
/// @file tash_main.c
/// @brief Main functions of TinyAra SHell (TASH)
#include <string.h>
#include <stdio.h>
#include <stdbool.h>
#include <sys/types.h>
#include <pthread.h>
#include <fcntl.h>
#include <errno.h>
#if !defined(CONFIG_DISABLE_POLL)
#include <sys/select.h>
#endif
#ifdef CONFIG_SECURED_TASH
#include <mbedtls/sha256.h>
#endif
#include <tinyara/ascii.h>
#include "tash_internal.h"
enum tash_input_state_e {
IN_VOID,
IN_WORD,
IN_QUOTE,
IN_APOSTROPHE
};
/* Following defines are fixed to avoid many configuration variables for TASH */
#define TASH_TOKEN_MAX (32)
#ifdef CONFIG_TASH
#define TASH_TRY_MAXCNT (5)
#if !defined(CONFIG_DISABLE_POLL)
#define SELECT_TIMEOUT_SECS (6)
#define SELECT_TIMEOUT_USECS (0)
#endif
#define TASH_TASK_STACKSIZE (4096)
#define TASH_TASK_PRIORITY (125)
#define TASH_PROMPT "TASH>>"
#endif /* CONFIG_TASH */
static int tash_running = FALSE;
#if TASH_MAX_STORE > 0
static void tash_clear_line(int fd, int len)
{
if (write(fd, (const void *)"\r", sizeof("\r")) <= 0) {
shdbg("TASH: echo failed (errno = %d)\n", get_errno());
}
for (int i = 0; i < len; ++i) {
if (write(fd, (const void *)" ", sizeof(" ")) <= 0) {
shdbg("TASH: echo failed (errno = %d)\n", get_errno());
}
}
}
#endif
static void tash_print_cmd(int fd, char *cmd, int pos)
{
if (write(fd, (const void *)"\r", sizeof("\r")) <= 0) {
shdbg("TASH: echo failed (errno = %d)\n", get_errno());
}
if (write(fd, (const void *)TASH_PROMPT, sizeof(TASH_PROMPT)) <= 0) {
shdbg("TASH: echo failed (errno = %d)\n", get_errno());
}
if (write(fd, (const void *)cmd, pos) <= 0) {
shdbg("TASH: echo failed (errno = %d)\n", get_errno());
}
}
static void tash_remove_char(char *char_pos)
{
int remaining;
/* Get a length of string remained */
remaining = strlen(char_pos + 1);
/* Add one for NULL */
remaining++;
/* remove character from buffer */
memmove(char_pos, char_pos + 1, remaining);
}
#ifdef CONFIG_TASH
/** @brief Read the input command
* @ingroup tash
*/
char *tash_read_input_line(int fd)
{
#define SKIP_NEXT_CHAR(n) char_idx += (n)
#define PREV_CHAR buffer[pos - 1]
#define CURR_CHAR buffer[pos]
#define NEXT_CHAR buffer[pos + 1]
#define NEXTNEXT_CHAR buffer[pos + 2]
int bufsize = TASH_LINEBUFLEN;
int pos = 0;
int nbytes;
int char_idx;
bool is_tab_pressed = false;
#if TASH_MAX_STORE > 0
bool is_esc_pressed = false;
bool prepare_direction_key = false;
bool is_direction_pressed = false;
char direction;
int prev_cmd_len = 0;
#endif
#if !defined(CONFIG_DISABLE_POLL)
fd_set tfd;
struct timeval stimeout;
stimeout.tv_sec = SELECT_TIMEOUT_SECS;
stimeout.tv_usec = SELECT_TIMEOUT_USECS;
#endif
char *buffer = tash_alloc(sizeof(char) * bufsize);
if (!buffer) {
shdbg("TASH: input buffer alloc failed\n");
return NULL;
}
memset(buffer, 0x0, bufsize);
do {
#if !defined(CONFIG_DISABLE_POLL)
FD_ZERO(&tfd);
FD_SET(fd, &tfd);
if ((select(fd + 1, &tfd, NULL, NULL, &stimeout)) && FD_ISSET(fd, &tfd)) {
#endif
/* read characters */
nbytes = read(fd, &buffer[pos], (bufsize - pos));
if (nbytes < 0) {
shdbg("TASH: can not read uart\n");
return buffer;
}
for (char_idx = 0; char_idx < nbytes; char_idx++) {
if ((CURR_CHAR == ASCII_BS) || (CURR_CHAR == ASCII_DEL)) {
/* Back space or Del key - delete previous character */
int valid_char_pos = pos + 1;
if (pos > 0) {
pos--;
/* Update screen */
if (write(fd, "\b \b", 3) <= 0) {
shdbg("TASH: echo failed (errno = %d)\n", get_errno());
}
}
if ((NEXT_CHAR != 0x0) && (valid_char_pos < TASH_LINEBUFLEN)) {
memmove(&CURR_CHAR, &NEXT_CHAR, (bufsize - valid_char_pos));
}
is_tab_pressed = false;
is_esc_pressed = false;
prev_cmd_len = pos;
} else if (CURR_CHAR == ASCII_TAB) {
/* TAB key - Auto-complete the command functionality */
if (pos > 0 && tash_do_autocomplete(buffer, &pos, is_tab_pressed) == true) {
tash_print_cmd(fd, buffer, pos);
prev_cmd_len = pos;
}
is_tab_pressed = true;
is_esc_pressed = false;
}
#if TASH_MAX_STORE > 0
/* ASCII_ESC + ASCII_LBRACKET + ASCII_A is the UP key (direction)
* ASCII_ESC + ASCII_LBRACKET + ASCII_B is the DOWN key (direction)
*/
else if (CURR_CHAR == ASCII_ESC) {
if (NEXT_CHAR == ASCII_LBRACKET) {
if ((NEXTNEXT_CHAR == ASCII_A) || (NEXTNEXT_CHAR == ASCII_B)) {
is_direction_pressed = true;
direction = NEXTNEXT_CHAR;
SKIP_NEXT_CHAR(2);
} else {
prepare_direction_key = true;
}
NEXT_CHAR = ASCII_NUL;
} else {
is_esc_pressed = true;
}
CURR_CHAR = ASCII_NUL;
is_tab_pressed = false;
} else if (is_esc_pressed) {
if (CURR_CHAR == ASCII_LBRACKET) {
if ((NEXT_CHAR == ASCII_A) || (NEXT_CHAR == ASCII_B)) {
is_direction_pressed = true;
direction = NEXT_CHAR;
SKIP_NEXT_CHAR(1);
} else {
prepare_direction_key = true;
}
CURR_CHAR = ASCII_NUL;
} else {
shvdbg("TASH: Not support\n");
}
CURR_CHAR = ASCII_NUL;
is_tab_pressed = false;
is_esc_pressed = false;
} else if (prepare_direction_key) {
if ((CURR_CHAR == ASCII_A) || (CURR_CHAR == ASCII_B)) {
is_direction_pressed = true;
direction = CURR_CHAR;
} else {
shvdbg("TASH: Not support\n");
}
CURR_CHAR = ASCII_NUL;
is_tab_pressed = false;
is_esc_pressed = false;
prepare_direction_key = false;
}
#endif
else {
if (CURR_CHAR == ASCII_CR) {
CURR_CHAR = ASCII_LF;
}
#ifdef CONFIG_SECURED_TASH
if (tash_running || CURR_CHAR == ASCII_LF) {
#endif
/* echo */
if (write(fd, &CURR_CHAR, 1) <= 0) {
shdbg("TASH: echo failed (errno = %d)\n", get_errno());
}
#ifdef CONFIG_SECURED_TASH
} else if (write(fd, "*", 1) <= 0) {
shdbg("TASH: echo failed (errno = %d)\n", get_errno());
}
#endif
pos++;
if (pos >= TASH_LINEBUFLEN) {
printf("\nTASH: length of input character is too long, maximum length is %d\n", TASH_LINEBUFLEN);
buffer[0] = ASCII_NUL;
return buffer;
}
is_tab_pressed = false;
is_esc_pressed = false;
prev_cmd_len = pos;
}
}
#if TASH_MAX_STORE > 0
if (is_direction_pressed) {
if (tash_search_cmd(buffer, &pos, direction) == true) {
tash_clear_line(fd, sizeof(TASH_PROMPT) + prev_cmd_len);
tash_print_cmd(fd, buffer, pos);
prev_cmd_len = pos;
}
is_direction_pressed = false;
}
#endif
#if !defined(CONFIG_DISABLE_POLL)
}
#endif
} while (PREV_CHAR != ASCII_LF);
PREV_CHAR = ASCII_NUL;
return buffer;
}
static int tash_open_console(void)
{
int cnt = 0;
int ret;
do {
ret = open("/dev/console", O_RDWR);
if (ret > 0) {
break;
}
#ifndef CONFIG_DISABLE_SIGNALS
usleep(20);
#endif
if (cnt == TASH_TRY_MAXCNT) {
shdbg("TASH: can not open uart, tried (%d) times\n", cnt);
ret = ERROR;
}
} while (cnt++ < TASH_TRY_MAXCNT);
return ret;
}
/** @brief TASH loop
* @ingroup tash
*/
static int tash_main(int argc, char *argv[])
{
char *line_buff;
int fd;
int nbytes;
int ret = OK;
ret = tash_init();
if (ret == ERROR) {
exit(EXIT_FAILURE);
}
fd = tash_open_console();
if (fd < 0) {
exit(EXIT_FAILURE);
}
#ifdef CONFIG_SECURED_TASH
tash_check_security(fd);
#endif
tash_running = TRUE;
do {
nbytes = write(fd, (const void *)TASH_PROMPT, sizeof(TASH_PROMPT));
if (nbytes <= 0) {
shdbg("TASH: prompt is not displayed (errno = %d)\n", get_errno());
#ifndef CONFIG_DISABLE_SIGNALS
usleep(20);
#endif
continue;
}
line_buff = tash_read_input_line(fd);
shvdbg("TASH: input string (%s)\n", line_buff);
tash_execute_cmdline(line_buff);
tash_free(line_buff);
} while (tash_running);
(void)close(fd);
return 0; /* TBD: For now, it always returns success */
}
int tash_start(void)
{
int pid;
int errcode;
pid = task_create("tash", TASH_TASK_PRIORITY, TASH_TASK_STACKSIZE, tash_main, (FAR char *const *)NULL);
if (pid < 0) {
errcode = errno;
DEBUGASSERT(errcode > 0);
return -errcode;
}
return pid;
}
void tash_stop(void)
{
tash_running = FALSE;
}
#endif /* CONFIG_TASH */
int tash_execute_cmdline(char *buff)
{
int argc;
char *argv[TASH_TOKEN_MAX];
enum tash_input_state_e state;
bool has_nextcmd = false;
int ret = OK;
#if TASH_MAX_STORE > 0
/* Find, verify the exclamation command and replace it to real command */
if (check_exclam_cmd(buff) == ERROR) {
*buff = ASCII_NUL;
return ERROR;
}
/* Save the input command into history command buffer */
tash_store_cmd(buff);
#endif
do {
for (argc = 0, argv[argc] = NULL, has_nextcmd = false, state = IN_VOID; *buff && argc < TASH_TOKEN_MAX - 1 && has_nextcmd == false; buff++) {
switch (state) {
case IN_VOID:
switch (*buff) {
case ASCII_SPACE:
/* ignore, do nothing */
break;
case ASCII_HASH:
/* following string is a comment, let's quit parsing */
has_nextcmd = false;
*buff = ASCII_NUL;
*(buff + 1) = ASCII_NUL;
break;
case ASCII_APOSTROPHE:
/* Argument is starting with opening single quotation mark */
state = IN_APOSTROPHE;
argv[argc++] = buff + 1;
break;
case ASCII_QUOTE:
/* Argument is starting with opening double quotation mark */
state = IN_QUOTE;
argv[argc++] = buff + 1;
break;
case ASCII_SEMICOLON:
if (argc) {
/* Even semicolon comes in IN_VOID state, (argc != 0) means there is saved commands already.
* Let's set the has_nextcmd true to check continuous command at next loop
* and execute current as ASCII_LF.
*/
has_nextcmd = true;
} else {
/* Only semicolon comes without command.
* Let's feedback the failure.
*/
printf("syntax error near unexpected token ';'\n");
return ERROR;
}
case ASCII_LF:
/* Command is finished, excute it */
*buff = ASCII_NUL;
break;
default:
state = IN_WORD;
argv[argc++] = buff;
break;
}
break;
case IN_QUOTE:
if (*buff == '"') {
if (*(buff - 1) == ASCII_BACKSLASH) {
/* # character, need to remove a backslash */
tash_remove_char(buff - 1);
} else {
/* closing double quotation mark, need to remove quotation mark */
tash_remove_char(buff);
state = IN_WORD;
}
buff--;
}
break;
case IN_APOSTROPHE:
if (*buff == (char)ASCII_APOSTROPHE) {
if (*(buff - 1) == ASCII_BACKSLASH) {
/* # character, need to remove a backslash */
tash_remove_char(buff - 1);
} else {
/* closing single quotation mark, need to remove quotation mark */
tash_remove_char(buff);
state = IN_WORD;
}
buff--;
}
break;
case IN_WORD:
switch (*buff) {
case ASCII_SPACE:
/* end of argument */
state = IN_VOID;
*buff = '\0';
break;
case ASCII_APOSTROPHE:
if (*(buff - 1) == ASCII_BACKSLASH) {
/* # character, need to remove a backslash */
tash_remove_char(buff - 1);
} else {
/* opening single quotation mark, need to remove quotation mark */
tash_remove_char(buff);
state = IN_APOSTROPHE;
}
buff--;
break;
case ASCII_QUOTE:
if (*(buff - 1) == ASCII_BACKSLASH) {
/* # character, need to remove a backslash */
tash_remove_char(buff - 1);
} else {
/* opening double quotation mark, need to remove quotation mark */
tash_remove_char(buff);
state = IN_QUOTE;
}
buff--;
break;
case ASCII_SEMICOLON:
/* Set the has_nextcmd true to check contiuouse command and execute current as ASCII_LF */
has_nextcmd = true;
case ASCII_LF:
/* Command is finished, excute it */
*buff = ASCII_NUL;
break;
default:
/* do nothing */
break;
}
break;
}
}
/* unclosed quotation */
if (state == IN_QUOTE) {
shdbg("TASH: unclosed double quotation mark\n");
argc = 0;
}
if (state == IN_APOSTROPHE) {
shdbg("TASH: unclosed single quotation mark\n");
argc = 0;
}
/* make a null at end of argv */
argv[argc] = NULL;
/* excute a command if it is valid */
if (argc > 0) {
ret = tash_execute_cmd(argv, argc);
}
} while (has_nextcmd == true);
return ret;
}
|
73312111e81043f890efd1b27369e1c3ddab0777
|
5ed4f58304033044e3a259f2a678328de4696692
|
/src/spawn.c
|
24b75b9a3027b76ca85a401ba250ab2f15590783
|
[
"Unlicense",
"LicenseRef-scancode-public-domain"
] |
permissive
|
troglobit/mg
|
a971a04a1610f93d57636f1253760684ea7b29a9
|
46dca121b1d67758ee06809d8eb72d0b9d6def65
|
refs/heads/master
| 2023-08-21T22:52:12.135823
| 2023-08-13T15:31:28
| 2023-08-13T15:31:28
| 58,325,928
| 333
| 39
|
Unlicense
| 2023-08-09T23:59:32
| 2016-05-08T18:41:56
|
C
|
UTF-8
|
C
| false
| false
| 944
|
c
|
spawn.c
|
/* $OpenBSD: spawn.c,v 1.11 2006/08/01 22:16:03 jason Exp $ */
/* This file is in the public domain. */
/*
* Spawn. Actually just suspends Mg.
* Assumes POSIX job control.
*/
#include <signal.h>
#include <stdio.h>
#include "ttydef.h"
#include "def.h"
/*
* This causes mg to send itself a stop signal. It assumes the parent
* shell supports POSIX job control. If the terminal supports an alternate
* screen, we will switch to it.
*/
int
spawncli(int f, int n)
{
sigset_t oset;
/* Very similar to what vttidy() does. */
ttcolor(CTEXT);
ttnowindow();
ttmove(nrow - 1, 0);
if (epresf != FALSE) {
tteeol();
epresf = FALSE;
}
if (ttcooked() == FALSE)
return (FALSE);
/* Exit application mode and tidy. */
tttidy();
ttflush();
(void)sigprocmask(SIG_SETMASK, NULL, &oset);
(void)kill(0, SIGTSTP);
(void)sigprocmask(SIG_SETMASK, &oset, NULL);
ttreinit();
/* Force repaint. */
sgarbf = TRUE;
return (ttraw());
}
|
febb8a3d84b5a1e0144e93817084592edb86ee2d
|
99bdb3251fecee538e0630f15f6574054dfc1468
|
/bsp/bouffalo_lab/libraries/bl_mcu_sdk/drivers/soc/bl702/std/startup/system_bl702.c
|
979eaa160bca0929450398d32d67e918d5e2bb7c
|
[
"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
| 3,651
|
c
|
system_bl702.c
|
/**
* @file system_bl702.c
* @brief
*
* Copyright (c) 2021 Bouffalolab team
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
*/
#include "bl702_glb.h"
#include "bl702_hbn.h"
#include "bl702_aon.h"
#include <arch/risc-v/e24/clic.h>
void SystemInit(void)
{
uint32_t *p;
uint8_t i;
uint32_t tmpVal = 0;
uint8_t flashCfg = 0;
uint8_t psramCfg = 0;
uint8_t isInternalFlash = 0;
uint8_t isInternalPsram = 0;
/* global IRQ disable */
__disable_irq();
tmpVal = BL_RD_REG(PDS_BASE, PDS_INT);
tmpVal |= (1 << 8); /*mask pds wakeup*/
tmpVal |= (1 << 10); /*mask rf done*/
tmpVal |= (1 << 11); /*mask pll done*/
tmpVal &= ~(0xff << 16); /*mask all pds wakeup source int*/
BL_WR_REG(PDS_BASE, PDS_INT, tmpVal);
/* GLB_Set_EM_Sel(GLB_EM_0KB); */
tmpVal = BL_RD_REG(GLB_BASE, GLB_SEAM_MISC);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_EM_SEL, 0x00); //GLB_EM_0KB
BL_WR_REG(GLB_BASE, GLB_SEAM_MISC, tmpVal);
/* Restore default setting*/
/* GLB_UART_Sig_Swap_Set(UART_SIG_SWAP_NONE); */
tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_UART_SWAP_SET, 0x00); //UART_SIG_SWAP_NONE
BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal);
/* CLear all interrupt */
p = (uint32_t *)(CLIC_HART0_BASE + CLIC_INTIE_OFFSET);
for (i = 0; i < (IRQn_LAST + 3) / 4; i++) {
p[i] = 0;
}
p = (uint32_t *)(CLIC_HART0_BASE + CLIC_INTIP_OFFSET);
for (i = 0; i < (IRQn_LAST + 3) / 4; i++) {
p[i] = 0;
}
/* SF io select from efuse value */
tmpVal = BL_RD_WORD(0x40007074);
flashCfg = ((tmpVal >> 26) & 7);
psramCfg = ((tmpVal >> 24) & 3);
if (flashCfg == 1 || flashCfg == 2) {
isInternalFlash = 1;
} else {
isInternalFlash = 0;
}
if (psramCfg == 1) {
isInternalPsram = 1;
} else {
isInternalPsram = 0;
}
tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO);
if (isInternalFlash == 1 && isInternalPsram == 0) {
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CFG_GPIO_USE_PSRAM_IO, 0x3f);
} else {
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CFG_GPIO_USE_PSRAM_IO, 0x00);
}
BL_WR_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO, tmpVal);
BL_WR_REG(GLB_BASE, GLB_UART_SIG_SEL_0, 0xffffffff);
/* init bor for all platform */
// HBN_BOR_CFG_Type borCfg = { 0 /* pu_bor */, 0 /* irq_bor_en */, 1 /* bor_vth */, 0 /* bor_sel */ };
// HBN_Set_BOR_Cfg(&borCfg);
/* dcdc 1.8v -> 1.5v */
tmpVal = BL_RD_REG(AON_BASE, AON_DCDC18_TOP_0);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_DCDC18_VOUT_SEL_AON, 0xC);
tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_DCDC18_VPFM_AON, 0x3);
BL_WR_REG(AON_BASE, AON_DCDC18_TOP_0, tmpVal);
}
void System_Post_Init(void)
{
PDS_Trim_RC32M();
HBN_Trim_RC32K();
/* global IRQ enable */
__enable_irq();
}
|
1e70885def747ecd202ddef595a6a30a6974a7e0
|
7744859512f027ef0da8b1bde0f8518e631b98eb
|
/soh/assets/scenes/indoors/nakaniwa/nakaniwa_room_0.h
|
3edbfb0cb377fa6df7453664d2a7dd99a496fb0e
|
[] |
no_license
|
HarbourMasters/Shipwright
|
7f70b9470e4f9a117f3fe2d6e4deb776b8742182
|
0e7c6585239c0d7ea2c039b8b8cb7eaedf8928a9
|
refs/heads/develop
| 2023-08-31T20:50:56.253521
| 2023-08-30T17:34:06
| 2023-08-30T17:34:06
| 472,575,717
| 2,104
| 459
| null | 2023-09-14T20:29:01
| 2022-03-22T01:42:52
|
C
|
UTF-8
|
C
| false
| false
| 7,662
|
h
|
nakaniwa_room_0.h
|
#pragma once
#include "align_asset_macro.h"
#define dnakaniwa_room_0DL_007178 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0DL_007178"
static const ALIGN_ASSET(2) char nakaniwa_room_0DL_007178[] = dnakaniwa_room_0DL_007178;
#define dnakaniwa_room_0Tex_012618 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Tex_012618"
static const ALIGN_ASSET(2) char nakaniwa_room_0Tex_012618[] = dnakaniwa_room_0Tex_012618;
#define dnakaniwa_room_0Tex_00F618 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Tex_00F618"
static const ALIGN_ASSET(2) char nakaniwa_room_0Tex_00F618[] = dnakaniwa_room_0Tex_00F618;
#define dnakaniwa_room_0Tex_00CE18 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Tex_00CE18"
static const ALIGN_ASSET(2) char nakaniwa_room_0Tex_00CE18[] = dnakaniwa_room_0Tex_00CE18;
#define dnakaniwa_room_0Tex_00C618 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Tex_00C618"
static const ALIGN_ASSET(2) char nakaniwa_room_0Tex_00C618[] = dnakaniwa_room_0Tex_00C618;
#define dnakaniwa_room_0Tex_00FE18 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Tex_00FE18"
static const ALIGN_ASSET(2) char nakaniwa_room_0Tex_00FE18[] = dnakaniwa_room_0Tex_00FE18;
#define dnakaniwa_room_0Tex_011E18 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Tex_011E18"
static const ALIGN_ASSET(2) char nakaniwa_room_0Tex_011E18[] = dnakaniwa_room_0Tex_011E18;
#define dnakaniwa_room_0Tex_010618 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Tex_010618"
static const ALIGN_ASSET(2) char nakaniwa_room_0Tex_010618[] = dnakaniwa_room_0Tex_010618;
#define dnakaniwa_room_0Tex_00EE18 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Tex_00EE18"
static const ALIGN_ASSET(2) char nakaniwa_room_0Tex_00EE18[] = dnakaniwa_room_0Tex_00EE18;
#define dnakaniwa_room_0Tex_00DE18 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Tex_00DE18"
static const ALIGN_ASSET(2) char nakaniwa_room_0Tex_00DE18[] = dnakaniwa_room_0Tex_00DE18;
#define dnakaniwa_room_0Tex_008418 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Tex_008418"
static const ALIGN_ASSET(2) char nakaniwa_room_0Tex_008418[] = dnakaniwa_room_0Tex_008418;
#define dnakaniwa_room_0Tex_008218 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Tex_008218"
static const ALIGN_ASSET(2) char nakaniwa_room_0Tex_008218[] = dnakaniwa_room_0Tex_008218;
#define dnakaniwa_room_0Tex_007618 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Tex_007618"
static const ALIGN_ASSET(2) char nakaniwa_room_0Tex_007618[] = dnakaniwa_room_0Tex_007618;
#define dnakaniwa_room_0Tex_007418 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Tex_007418"
static const ALIGN_ASSET(2) char nakaniwa_room_0Tex_007418[] = dnakaniwa_room_0Tex_007418;
#define dnakaniwa_room_0Tex_007218 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Tex_007218"
static const ALIGN_ASSET(2) char nakaniwa_room_0Tex_007218[] = dnakaniwa_room_0Tex_007218;
#define dnakaniwa_room_0Tex_007A18 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Tex_007A18"
static const ALIGN_ASSET(2) char nakaniwa_room_0Tex_007A18[] = dnakaniwa_room_0Tex_007A18;
#define dnakaniwa_room_0Tex_008618 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Tex_008618"
static const ALIGN_ASSET(2) char nakaniwa_room_0Tex_008618[] = dnakaniwa_room_0Tex_008618;
#define dnakaniwa_room_0Tex_007818 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Tex_007818"
static const ALIGN_ASSET(2) char nakaniwa_room_0Tex_007818[] = dnakaniwa_room_0Tex_007818;
#define dnakaniwa_room_0Tex_009E18 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Tex_009E18"
static const ALIGN_ASSET(2) char nakaniwa_room_0Tex_009E18[] = dnakaniwa_room_0Tex_009E18;
#define dnakaniwa_room_0Tex_00E618 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Tex_00E618"
static const ALIGN_ASSET(2) char nakaniwa_room_0Tex_00E618[] = dnakaniwa_room_0Tex_00E618;
#define dnakaniwa_room_0Tex_013618 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Tex_013618"
static const ALIGN_ASSET(2) char nakaniwa_room_0Tex_013618[] = dnakaniwa_room_0Tex_013618;
#define dnakaniwa_room_0Tex_011618 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Tex_011618"
static const ALIGN_ASSET(2) char nakaniwa_room_0Tex_011618[] = dnakaniwa_room_0Tex_011618;
#define dnakaniwa_room_0Tex_013E18 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Tex_013E18"
static const ALIGN_ASSET(2) char nakaniwa_room_0Tex_013E18[] = dnakaniwa_room_0Tex_013E18;
#define dnakaniwa_room_0Tex_010E18 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Tex_010E18"
static const ALIGN_ASSET(2) char nakaniwa_room_0Tex_010E18[] = dnakaniwa_room_0Tex_010E18;
#define dnakaniwa_room_0Tex_012E18 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Tex_012E18"
static const ALIGN_ASSET(2) char nakaniwa_room_0Tex_012E18[] = dnakaniwa_room_0Tex_012E18;
#define dnakaniwa_room_0Tex_00B618 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Tex_00B618"
static const ALIGN_ASSET(2) char nakaniwa_room_0Tex_00B618[] = dnakaniwa_room_0Tex_00B618;
#define dnakaniwa_room_0Tex_00A618 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Tex_00A618"
static const ALIGN_ASSET(2) char nakaniwa_room_0Tex_00A618[] = dnakaniwa_room_0Tex_00A618;
#define dnakaniwa_room_0Tex_008E18 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Tex_008E18"
static const ALIGN_ASSET(2) char nakaniwa_room_0Tex_008E18[] = dnakaniwa_room_0Tex_008E18;
#define dnakaniwa_room_0DL_014E98 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0DL_014E98"
static const ALIGN_ASSET(2) char nakaniwa_room_0DL_014E98[] = dnakaniwa_room_0DL_014E98;
#define dnakaniwa_room_0Tex_0166C0 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Tex_0166C0"
static const ALIGN_ASSET(2) char nakaniwa_room_0Tex_0166C0[] = dnakaniwa_room_0Tex_0166C0;
#define dnakaniwa_room_0Tex_016EC0 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Tex_016EC0"
static const ALIGN_ASSET(2) char nakaniwa_room_0Tex_016EC0[] = dnakaniwa_room_0Tex_016EC0;
#define dnakaniwa_room_0Tex_0156C0 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Tex_0156C0"
static const ALIGN_ASSET(2) char nakaniwa_room_0Tex_0156C0[] = dnakaniwa_room_0Tex_0156C0;
#define dnakaniwa_room_0Tex_014EC0 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Tex_014EC0"
static const ALIGN_ASSET(2) char nakaniwa_room_0Tex_014EC0[] = dnakaniwa_room_0Tex_014EC0;
#define dnakaniwa_room_0Set_000120DL_007178 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Set_000120DL_007178"
static const ALIGN_ASSET(2) char nakaniwa_room_0Set_000120DL_007178[] = dnakaniwa_room_0Set_000120DL_007178;
#define dnakaniwa_room_0Set_000120DL_014E98 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Set_000120DL_014E98"
static const ALIGN_ASSET(2) char nakaniwa_room_0Set_000120DL_014E98[] = dnakaniwa_room_0Set_000120DL_014E98;
#define dnakaniwa_room_0Set_0001B0DL_007178 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Set_0001B0DL_007178"
static const ALIGN_ASSET(2) char nakaniwa_room_0Set_0001B0DL_007178[] = dnakaniwa_room_0Set_0001B0DL_007178;
#define dnakaniwa_room_0Set_0001B0DL_014E98 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Set_0001B0DL_014E98"
static const ALIGN_ASSET(2) char nakaniwa_room_0Set_0001B0DL_014E98[] = dnakaniwa_room_0Set_0001B0DL_014E98;
#define dnakaniwa_room_0Set_000240DL_007178 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Set_000240DL_007178"
static const ALIGN_ASSET(2) char nakaniwa_room_0Set_000240DL_007178[] = dnakaniwa_room_0Set_000240DL_007178;
#define dnakaniwa_room_0Set_000240DL_014E98 "__OTR__scenes/nonmq/nakaniwa_scene/nakaniwa_room_0Set_000240DL_014E98"
static const ALIGN_ASSET(2) char nakaniwa_room_0Set_000240DL_014E98[] = dnakaniwa_room_0Set_000240DL_014E98;
|
70dff4a012e18e20979c38c201425079f49d5310
|
7d7900e1c25b729fc8c208673a449c0520ba466e
|
/lib/CL/clSetKernelExecInfo.c
|
0cd9e280ad32d07e1ff9bdc939890349047eaa6b
|
[
"MIT",
"BSD-2-Clause"
] |
permissive
|
pocl/pocl
|
384091e15c8f6abf29fd2c6deace34a7de5a6ac6
|
5a99e12d0bb78427ad948ac368589135507f1b59
|
refs/heads/main
| 2023-09-02T14:16:21.381680
| 2023-08-21T12:13:47
| 2023-08-21T12:13:47
| 12,292,999
| 775
| 250
|
MIT
| 2023-09-14T06:50:34
| 2013-08-22T09:26:12
|
C
|
UTF-8
|
C
| false
| false
| 4,412
|
c
|
clSetKernelExecInfo.c
|
/* OpenCL runtime library: clSetKernelExecInfo()
Copyright (c) 2015 Michal Babej / Tampere University of Technology
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 "pocl_cl.h"
#include "pocl_util.h"
CL_API_ENTRY cl_int CL_API_CALL
POname(clSetKernelExecInfo)(cl_kernel kernel,
cl_kernel_exec_info param_name,
size_t param_value_size,
const void *param_value) CL_API_SUFFIX__VERSION_1_0
{
POCL_RETURN_ERROR_COND ((!IS_CL_OBJECT_VALID (kernel)), CL_INVALID_KERNEL);
switch (param_name)
{
case CL_KERNEL_EXEC_INFO_SVM_PTRS:
case CL_KERNEL_EXEC_INFO_SVM_FINE_GRAIN_SYSTEM:
{
cl_device_id dev = kernel->context->svm_allocdev;
POCL_RETURN_ERROR_ON ((dev == NULL), CL_INVALID_OPERATION,
"no devices in the context associated with"
" kernel support SVM\n");
cl_device_id realdev = pocl_real_dev (dev);
cl_uint program_device_i = CL_UINT_MAX;
for (unsigned i = 0; i < kernel->program->num_devices; ++i)
{
if (kernel->program->devices[i] == realdev)
{
program_device_i = i;
break;
}
}
POCL_RETURN_ERROR_ON ((program_device_i == CL_UINT_MAX),
CL_INVALID_KERNEL,
"Can't find the kernel for this device\n");
POCL_RETURN_ERROR_ON (
(realdev->ops->set_kernel_exec_info_ext == NULL),
CL_INVALID_OPERATION,
"This device doesn't support clSetKernelExecInfo\n");
return realdev->ops->set_kernel_exec_info_ext (
realdev, program_device_i, kernel, param_name, param_value_size,
param_value);
}
case CL_KERNEL_EXEC_INFO_USM_PTRS_INTEL:
case CL_KERNEL_EXEC_INFO_INDIRECT_HOST_ACCESS_INTEL:
case CL_KERNEL_EXEC_INFO_INDIRECT_DEVICE_ACCESS_INTEL:
case CL_KERNEL_EXEC_INFO_INDIRECT_SHARED_ACCESS_INTEL:
{
cl_device_id dev = kernel->context->usm_allocdev;
POCL_RETURN_ERROR_ON ((dev == NULL), CL_INVALID_OPERATION,
"no devices in the context associated with"
" kernel support USM\n");
cl_device_id realdev = pocl_real_dev (dev);
cl_uint program_device_i = CL_UINT_MAX;
for (unsigned i = 0; i < kernel->program->num_devices; ++i)
{
if (kernel->program->devices[i] == realdev)
{
program_device_i = i;
break;
}
}
POCL_RETURN_ERROR_ON ((program_device_i == CL_UINT_MAX),
CL_INVALID_KERNEL,
"Can't find the kernel for this device\n");
POCL_RETURN_ERROR_ON (
(realdev->ops->set_kernel_exec_info_ext == NULL),
CL_INVALID_OPERATION,
"This device doesn't support clSetKernelExecInfo\n");
return realdev->ops->set_kernel_exec_info_ext (
realdev, program_device_i, kernel, param_name, param_value_size,
param_value);
}
default:
POCL_RETURN_ERROR_ON (1, CL_INVALID_VALUE,
"Given param_name(%u) is not valid\n", param_name);
}
}
POsym(clSetKernelExecInfo)
|
9b79ef59837c38854b68989b3f87878691c2e1ca
|
2c73a693c2b3c162eae2ab94f649d8c4494878ba
|
/components/network/paho.mqtt.c/src/MQTTPacketOut.h
|
d9625544b45a51710efa27265380097110dc75bb
|
[
"MIT"
] |
permissive
|
openLuat/LuatOS
|
185e1e140aed908434168133571ddcafe98f4e12
|
4b29d5121ab4f7133630331e8502c526c7856897
|
refs/heads/master
| 2023-08-23T04:57:23.263539
| 2023-08-23T04:46:46
| 2023-08-23T04:46:46
| 230,403,844
| 378
| 93
|
MIT
| 2021-12-17T02:19:30
| 2019-12-27T08:29:19
|
C
|
UTF-8
|
C
| false
| false
| 1,734
|
h
|
MQTTPacketOut.h
|
/*******************************************************************************
* Copyright (c) 2009, 2018 IBM Corp.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* https://www.eclipse.org/legal/epl-2.0/
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Ian Craggs - initial API and implementation and/or initial documentation
* Ian Craggs, Allan Stockdill-Mander - SSL updates
* Ian Craggs - MQTT 3.1.1 support
* Ian Craggs - MQTT 5.0 support
*******************************************************************************/
#if !defined(MQTTPACKETOUT_H)
#define MQTTPACKETOUT_H
#include "MQTTPacket.h"
int MQTTPacket_send_connect(Clients* client, int MQTTVersion,
MQTTProperties* connectProperties, MQTTProperties* willProperties);
void* MQTTPacket_connack(int MQTTVersion, unsigned char aHeader, char* data, size_t datalen);
void MQTTPacket_freeConnack(Connack* pack);
int MQTTPacket_send_pingreq(networkHandles* net, const char* clientID);
int MQTTPacket_send_subscribe(List* topics, List* qoss, MQTTSubscribe_options* opts, MQTTProperties* props,
int msgid, int dup, Clients* client);
void* MQTTPacket_suback(int MQTTVersion, unsigned char aHeader, char* data, size_t datalen);
int MQTTPacket_send_unsubscribe(List* topics, MQTTProperties* props, int msgid, int dup, Clients* client);
void* MQTTPacket_unsuback(int MQTTVersion, unsigned char aHeader, char* data, size_t datalen);
#endif
|
2466f5aad609167b122968762263672ca41f6bb0
|
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
|
/sys/kern/sys_sched.c
|
c76bcb3543c116fe20e32748220e03a79c017251
|
[] |
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
| 16,249
|
c
|
sys_sched.c
|
/* $NetBSD: sys_sched.c,v 1.50 2023/04/09 09:18:09 riastradh Exp $ */
/*
* Copyright (c) 2008, 2011 Mindaugas Rasiukevicius <rmind at NetBSD 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.
*/
/*
* System calls relating to the scheduler.
*
* Lock order:
*
* cpu_lock ->
* proc_lock ->
* proc_t::p_lock ->
* lwp_t::lwp_lock
*
* TODO:
* - Handle pthread_setschedprio() as defined by POSIX;
*/
#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: sys_sched.c,v 1.50 2023/04/09 09:18:09 riastradh Exp $");
#include <sys/param.h>
#include <sys/cpu.h>
#include <sys/kauth.h>
#include <sys/kmem.h>
#include <sys/lwp.h>
#include <sys/mutex.h>
#include <sys/proc.h>
#include <sys/pset.h>
#include <sys/sched.h>
#include <sys/syscallargs.h>
#include <sys/sysctl.h>
#include <sys/systm.h>
#include <sys/types.h>
#include <sys/unistd.h>
static struct sysctllog *sched_sysctl_log;
static kauth_listener_t sched_listener;
/*
* Convert user priority or the in-kernel priority or convert the current
* priority to the appropriate range according to the policy change.
*/
static pri_t
convert_pri(lwp_t *l, int policy, pri_t pri)
{
/* Convert user priority to the in-kernel */
if (pri != PRI_NONE) {
/* Only for real-time threads */
KASSERT(pri >= SCHED_PRI_MIN);
KASSERT(pri <= SCHED_PRI_MAX);
KASSERT(policy != SCHED_OTHER);
return PRI_USER_RT + pri;
}
/* Neither policy, nor priority change */
if (l->l_class == policy)
return l->l_priority;
/* Time-sharing -> real-time */
if (l->l_class == SCHED_OTHER) {
KASSERT(policy == SCHED_FIFO || policy == SCHED_RR);
return PRI_USER_RT;
}
/* Real-time -> time-sharing */
if (policy == SCHED_OTHER) {
KASSERT(l->l_class == SCHED_FIFO || l->l_class == SCHED_RR);
/*
* this is a bit arbitrary because the priority is dynamic
* for SCHED_OTHER threads and will likely be changed by
* the scheduler soon anyway.
*/
return l->l_priority - PRI_USER_RT;
}
/* Real-time -> real-time */
return l->l_priority;
}
int
do_sched_setparam(pid_t pid, lwpid_t lid, int policy,
const struct sched_param *params)
{
struct proc *p;
struct lwp *t;
pri_t pri;
u_int lcnt;
int error;
error = 0;
pri = params->sched_priority;
/* If no parameters specified, just return (this should not happen) */
if (pri == PRI_NONE && policy == SCHED_NONE)
return 0;
/* Validate scheduling class */
if (policy != SCHED_NONE && (policy < SCHED_OTHER || policy > SCHED_RR))
return EINVAL;
/* Validate priority */
if (pri != PRI_NONE && (pri < SCHED_PRI_MIN || pri > SCHED_PRI_MAX))
return EINVAL;
if (pid != 0) {
/* Find the process */
mutex_enter(&proc_lock);
p = proc_find(pid);
if (p == NULL) {
mutex_exit(&proc_lock);
return ESRCH;
}
mutex_enter(p->p_lock);
mutex_exit(&proc_lock);
/* Disallow modification of system processes */
if ((p->p_flag & PK_SYSTEM) != 0) {
mutex_exit(p->p_lock);
return EPERM;
}
} else {
/* Use the calling process */
p = curlwp->l_proc;
mutex_enter(p->p_lock);
}
/* Find the LWP(s) */
lcnt = 0;
LIST_FOREACH(t, &p->p_lwps, l_sibling) {
pri_t kpri;
int lpolicy;
if (lid && lid != t->l_lid)
continue;
lcnt++;
lwp_lock(t);
lpolicy = (policy == SCHED_NONE) ? t->l_class : policy;
/* Disallow setting of priority for SCHED_OTHER threads */
if (lpolicy == SCHED_OTHER && pri != PRI_NONE) {
lwp_unlock(t);
error = EINVAL;
break;
}
/* Convert priority, if needed */
kpri = convert_pri(t, lpolicy, pri);
/* Check the permission */
error = kauth_authorize_process(kauth_cred_get(),
KAUTH_PROCESS_SCHEDULER_SETPARAM, p, t, KAUTH_ARG(lpolicy),
KAUTH_ARG(kpri));
if (error) {
lwp_unlock(t);
break;
}
/* Set the scheduling class, change the priority */
t->l_class = lpolicy;
lwp_changepri(t, kpri);
lwp_unlock(t);
}
mutex_exit(p->p_lock);
return (lcnt == 0) ? ESRCH : error;
}
/*
* Set scheduling parameters.
*/
int
sys__sched_setparam(struct lwp *l, const struct sys__sched_setparam_args *uap,
register_t *retval)
{
/* {
syscallarg(pid_t) pid;
syscallarg(lwpid_t) lid;
syscallarg(int) policy;
syscallarg(const struct sched_param *) params;
} */
struct sched_param params;
int error;
/* Get the parameters from the user-space */
error = copyin(SCARG(uap, params), ¶ms, sizeof(params));
if (error)
goto out;
error = do_sched_setparam(SCARG(uap, pid), SCARG(uap, lid),
SCARG(uap, policy), ¶ms);
out:
return error;
}
/*
* do_sched_getparam:
*
* if lid=0, returns the parameter of the first LWP in the process.
*/
int
do_sched_getparam(pid_t pid, lwpid_t lid, int *policy,
struct sched_param *params)
{
struct sched_param lparams;
struct lwp *t;
int error, lpolicy;
if (pid < 0 || lid < 0)
return EINVAL;
t = lwp_find2(pid, lid); /* acquire p_lock */
if (t == NULL)
return ESRCH;
/* Check the permission */
error = kauth_authorize_process(kauth_cred_get(),
KAUTH_PROCESS_SCHEDULER_GETPARAM, t->l_proc, NULL, NULL, NULL);
if (error != 0) {
mutex_exit(t->l_proc->p_lock);
return error;
}
lwp_lock(t);
lparams.sched_priority = t->l_priority;
lpolicy = t->l_class;
lwp_unlock(t);
mutex_exit(t->l_proc->p_lock);
/*
* convert to the user-visible priority value.
* it's an inversion of convert_pri().
*
* the SCHED_OTHER case is a bit arbitrary given that
* - we don't allow setting the priority.
* - the priority is dynamic.
*/
switch (lpolicy) {
case SCHED_OTHER:
lparams.sched_priority -= PRI_USER;
break;
case SCHED_RR:
case SCHED_FIFO:
lparams.sched_priority -= PRI_USER_RT;
break;
}
if (policy != NULL)
*policy = lpolicy;
if (params != NULL)
*params = lparams;
return error;
}
/*
* Get scheduling parameters.
*/
int
sys__sched_getparam(struct lwp *l, const struct sys__sched_getparam_args *uap,
register_t *retval)
{
/* {
syscallarg(pid_t) pid;
syscallarg(lwpid_t) lid;
syscallarg(int *) policy;
syscallarg(struct sched_param *) params;
} */
struct sched_param params;
int error, policy;
error = do_sched_getparam(SCARG(uap, pid), SCARG(uap, lid), &policy,
¶ms);
if (error)
goto out;
error = copyout(¶ms, SCARG(uap, params), sizeof(params));
if (error == 0 && SCARG(uap, policy) != NULL)
error = copyout(&policy, SCARG(uap, policy), sizeof(int));
out:
return error;
}
/*
* Allocate the CPU set, and get it from userspace.
*/
static int
genkcpuset(kcpuset_t **dset, const cpuset_t *sset, size_t size)
{
kcpuset_t *kset;
int error;
kcpuset_create(&kset, true);
error = kcpuset_copyin(sset, kset, size);
if (error) {
kcpuset_unuse(kset, NULL);
} else {
*dset = kset;
}
return error;
}
/*
* Set affinity.
*/
int
sys__sched_setaffinity(struct lwp *l,
const struct sys__sched_setaffinity_args *uap, register_t *retval)
{
/* {
syscallarg(pid_t) pid;
syscallarg(lwpid_t) lid;
syscallarg(size_t) size;
syscallarg(const cpuset_t *) cpuset;
} */
kcpuset_t *kcset, *kcpulst = NULL;
struct cpu_info *ici, *ci;
struct proc *p;
struct lwp *t;
CPU_INFO_ITERATOR cii;
bool alloff;
lwpid_t lid;
u_int lcnt;
int error;
error = genkcpuset(&kcset, SCARG(uap, cpuset), SCARG(uap, size));
if (error)
return error;
/*
* Traverse _each_ CPU to:
* - Check that CPUs in the mask have no assigned processor set.
* - Check that at least one CPU from the mask is online.
* - Find the first target CPU to migrate.
*
* To avoid the race with CPU online/offline calls and processor sets,
* cpu_lock will be locked for the entire operation.
*/
ci = NULL;
alloff = false;
mutex_enter(&cpu_lock);
for (CPU_INFO_FOREACH(cii, ici)) {
struct schedstate_percpu *ispc;
if (!kcpuset_isset(kcset, cpu_index(ici))) {
continue;
}
ispc = &ici->ci_schedstate;
/* Check that CPU is not in the processor-set */
if (ispc->spc_psid != PS_NONE) {
error = EPERM;
goto out;
}
/* Skip offline CPUs */
if (ispc->spc_flags & SPCF_OFFLINE) {
alloff = true;
continue;
}
/* Target CPU to migrate */
if (ci == NULL) {
ci = ici;
}
}
if (ci == NULL) {
if (alloff) {
/* All CPUs in the set are offline */
error = EPERM;
goto out;
}
/* Empty set */
kcpuset_unuse(kcset, &kcpulst);
kcset = NULL;
}
if (SCARG(uap, pid) != 0) {
/* Find the process */
mutex_enter(&proc_lock);
p = proc_find(SCARG(uap, pid));
if (p == NULL) {
mutex_exit(&proc_lock);
error = ESRCH;
goto out;
}
mutex_enter(p->p_lock);
mutex_exit(&proc_lock);
/* Disallow modification of system processes. */
if ((p->p_flag & PK_SYSTEM) != 0) {
mutex_exit(p->p_lock);
error = EPERM;
goto out;
}
} else {
/* Use the calling process */
p = l->l_proc;
mutex_enter(p->p_lock);
}
/*
* Check the permission.
*/
error = kauth_authorize_process(l->l_cred,
KAUTH_PROCESS_SCHEDULER_SETAFFINITY, p, NULL, NULL, NULL);
if (error != 0) {
mutex_exit(p->p_lock);
goto out;
}
/* Iterate through LWP(s). */
lcnt = 0;
lid = SCARG(uap, lid);
LIST_FOREACH(t, &p->p_lwps, l_sibling) {
if (lid && lid != t->l_lid) {
continue;
}
lwp_lock(t);
/* No affinity for zombie LWPs. */
if (t->l_stat == LSZOMB) {
lwp_unlock(t);
continue;
}
/* First, release existing affinity, if any. */
if (t->l_affinity) {
kcpuset_unuse(t->l_affinity, &kcpulst);
}
if (kcset) {
/*
* Hold a reference on affinity mask, assign mask to
* LWP and migrate it to another CPU (unlocks LWP).
*/
kcpuset_use(kcset);
t->l_affinity = kcset;
lwp_migrate(t, ci);
} else {
/* Old affinity mask is released, just clear. */
t->l_affinity = NULL;
lwp_unlock(t);
}
lcnt++;
}
mutex_exit(p->p_lock);
if (lcnt == 0) {
error = ESRCH;
}
out:
mutex_exit(&cpu_lock);
/*
* Drop the initial reference (LWPs, if any, have the ownership now),
* and destroy whatever is in the G/C list, if filled.
*/
if (kcset) {
kcpuset_unuse(kcset, &kcpulst);
}
if (kcpulst) {
kcpuset_destroy(kcpulst);
}
return error;
}
/*
* Get affinity.
*/
int
sys__sched_getaffinity(struct lwp *l,
const struct sys__sched_getaffinity_args *uap, register_t *retval)
{
/* {
syscallarg(pid_t) pid;
syscallarg(lwpid_t) lid;
syscallarg(size_t) size;
syscallarg(cpuset_t *) cpuset;
} */
struct lwp *t;
kcpuset_t *kcset;
int error;
if (SCARG(uap, pid) < 0 || SCARG(uap, lid) < 0)
return EINVAL;
error = genkcpuset(&kcset, SCARG(uap, cpuset), SCARG(uap, size));
if (error)
return error;
/* Locks the LWP */
t = lwp_find2(SCARG(uap, pid), SCARG(uap, lid));
if (t == NULL) {
error = ESRCH;
goto out;
}
/* Check the permission */
if (kauth_authorize_process(l->l_cred,
KAUTH_PROCESS_SCHEDULER_GETAFFINITY, t->l_proc, NULL, NULL, NULL)) {
mutex_exit(t->l_proc->p_lock);
error = EPERM;
goto out;
}
lwp_lock(t);
if (t->l_affinity) {
kcpuset_copy(kcset, t->l_affinity);
} else {
kcpuset_zero(kcset);
}
lwp_unlock(t);
mutex_exit(t->l_proc->p_lock);
error = kcpuset_copyout(kcset, SCARG(uap, cpuset), SCARG(uap, size));
out:
kcpuset_unuse(kcset, NULL);
return error;
}
/*
* Priority protection for PTHREAD_PRIO_PROTECT. This is a weak
* analogue of priority inheritance: temp raise the priority
* of the caller when accessing a protected resource.
*/
int
sys__sched_protect(struct lwp *l,
const struct sys__sched_protect_args *uap, register_t *retval)
{
/* {
syscallarg(int) priority;
syscallarg(int *) opriority;
} */
int error;
pri_t pri;
KASSERT(l->l_inheritedprio == -1);
KASSERT(l->l_auxprio == -1 || l->l_auxprio == l->l_protectprio);
pri = SCARG(uap, priority);
error = 0;
lwp_lock(l);
if (pri == -1) {
/* back out priority changes */
switch(l->l_protectdepth) {
case 0:
error = EINVAL;
break;
case 1:
l->l_protectdepth = 0;
l->l_protectprio = -1;
l->l_auxprio = -1;
break;
default:
l->l_protectdepth--;
break;
}
} else if (pri < 0) {
/* Just retrieve the current value, for debugging */
if (l->l_protectprio == -1)
error = ENOENT;
else
*retval = l->l_protectprio - PRI_USER_RT;
} else if (__predict_false(pri < SCHED_PRI_MIN ||
pri > SCHED_PRI_MAX || l->l_priority > pri + PRI_USER_RT)) {
/* must fail if existing priority is higher */
error = EPERM;
} else {
/* play along but make no changes if not a realtime LWP. */
l->l_protectdepth++;
pri += PRI_USER_RT;
if (__predict_true(l->l_class != SCHED_OTHER &&
pri > l->l_protectprio)) {
l->l_protectprio = pri;
l->l_auxprio = pri;
}
}
lwp_unlock(l);
return error;
}
/*
* Yield.
*/
int
sys_sched_yield(struct lwp *l, const void *v, register_t *retval)
{
yield();
return 0;
}
/*
* Sysctl nodes and initialization.
*/
static void
sysctl_sched_setup(struct sysctllog **clog)
{
const struct sysctlnode *node = NULL;
sysctl_createv(clog, 0, NULL, NULL,
CTLFLAG_PERMANENT|CTLFLAG_IMMEDIATE,
CTLTYPE_INT, "posix_sched",
SYSCTL_DESCR("Version of IEEE Std 1003.1 and its "
"Process Scheduling option to which the "
"system attempts to conform"),
NULL, _POSIX_PRIORITY_SCHEDULING, NULL, 0,
CTL_KERN, CTL_CREATE, CTL_EOL);
sysctl_createv(clog, 0, NULL, &node,
CTLFLAG_PERMANENT,
CTLTYPE_NODE, "sched",
SYSCTL_DESCR("Scheduler options"),
NULL, 0, NULL, 0,
CTL_KERN, CTL_CREATE, CTL_EOL);
if (node == NULL)
return;
sysctl_createv(clog, 0, &node, NULL,
CTLFLAG_PERMANENT | CTLFLAG_IMMEDIATE,
CTLTYPE_INT, "pri_min",
SYSCTL_DESCR("Minimal POSIX real-time priority"),
NULL, SCHED_PRI_MIN, NULL, 0,
CTL_CREATE, CTL_EOL);
sysctl_createv(clog, 0, &node, NULL,
CTLFLAG_PERMANENT | CTLFLAG_IMMEDIATE,
CTLTYPE_INT, "pri_max",
SYSCTL_DESCR("Maximal POSIX real-time priority"),
NULL, SCHED_PRI_MAX, NULL, 0,
CTL_CREATE, CTL_EOL);
}
static int
sched_listener_cb(kauth_cred_t cred, kauth_action_t action, void *cookie,
void *arg0, void *arg1, void *arg2, void *arg3)
{
struct proc *p;
int result;
result = KAUTH_RESULT_DEFER;
p = arg0;
switch (action) {
case KAUTH_PROCESS_SCHEDULER_GETPARAM:
if (kauth_cred_uidmatch(cred, p->p_cred))
result = KAUTH_RESULT_ALLOW;
break;
case KAUTH_PROCESS_SCHEDULER_SETPARAM:
if (kauth_cred_uidmatch(cred, p->p_cred)) {
struct lwp *l;
int policy;
pri_t priority;
l = arg1;
policy = (int)(unsigned long)arg2;
priority = (pri_t)(unsigned long)arg3;
if ((policy == l->l_class ||
(policy != SCHED_FIFO && policy != SCHED_RR)) &&
priority <= l->l_priority)
result = KAUTH_RESULT_ALLOW;
}
break;
case KAUTH_PROCESS_SCHEDULER_GETAFFINITY:
result = KAUTH_RESULT_ALLOW;
break;
case KAUTH_PROCESS_SCHEDULER_SETAFFINITY:
/* Privileged; we let the secmodel handle this. */
break;
default:
break;
}
return result;
}
void
sched_init(void)
{
sysctl_sched_setup(&sched_sysctl_log);
sched_listener = kauth_listen_scope(KAUTH_SCOPE_PROCESS,
sched_listener_cb, NULL);
}
|
968a9d93319262147b443e2064f333097726583b
|
ff2180134ad76ce50d9b9a162edf035c3914ab4a
|
/port/arduino/adapter/oc_config.h
|
c08e633070dead36eeb1a8175d119b3575188756
|
[
"Apache-2.0",
"BSD-2-Clause",
"BSD-3-Clause"
] |
permissive
|
iotivity/iotivity-lite
|
4ddddfc7d76766d1c5e94d81dd26e28f8cb4a940
|
1597367d65bad60a26511775ee47e5496186ddca
|
refs/heads/master
| 2023-08-16T18:09:54.615426
| 2023-08-09T19:05:42
| 2023-08-09T19:05:42
| 171,529,940
| 143
| 80
|
Apache-2.0
| 2023-09-14T07:31:04
| 2019-02-19T18:47:09
|
C
|
UTF-8
|
C
| false
| false
| 3,364
|
h
|
oc_config.h
|
/******************************************************************
*
* Copyright 2018 iThemba LABS 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.
*
******************************************************************/
#ifndef CONFIG_H
#define CONFIG_H
/* Time resolution */
#include <TimeLib.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
#define OCF_MCAST_PORT_UNSECURED (5683)
#define OCF_PORT_UNSECURED (56789)
#define OCF_PORT_SECURED (42536)
/** Multicast IP address.*/
#define OCF_IPv4_MULTICAST "224.0.1.187"
typedef uint32_t oc_clock_time_t;
#define OC_CLOCK_CONF_TICKS_PER_SECOND (1)
#define MBEDTLS_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA256 0xFF00
/* Security Layer */
/* Max inactivity timeout before tearing down DTLS connection */
#define OC_DTLS_INACTIVITY_TIMEOUT (5000)
/* Add request history for deduplicate UDP/DTLS messages */
#define OC_REQUEST_HISTORY
/* Add support observable for oic/res */
//#define OC_DISCOVERY_RESOURCE_OBSERVABLE
/* Maximum size of uri for a collection resource */
//#define OC_MAX_COLLECTIONS_INSTANCE_URI_SIZE (64)
/* If we selected support for dynamic memory allocation */
#ifdef OC_DYNAMIC_ALLOCATION
#define OC_BLOCK_WISE
#define OC_COLLECTIONS // why? i got this error: api/oc_ri.c:1064:10: error:
// 'resource_is_collection' undeclared (first use in this
// function)
/* Enable reallocation during encoding the representation to cbor */
//#define OC_REP_ENCODING_REALLOC
#else /* OC_DYNAMIC_ALLOCATION */
#define OC_BYTES_POOL_SIZE (2000)
#define OC_INTS_POOL_SIZE (100)
#define OC_DOUBLES_POOL_SIZE (2)
/* Server-side parameters */
/* Maximum number of server resources */
#define OC_MAX_APP_RESOURCES (4)
/* Common parameters */
/* Prescriptive lower layers MTU size, enable block-wise transfers */
#define OC_BLOCK_WISE_SET_MTU (700)
#define OC_BLOCK_WISE
/* Maximum size of request/response payloads */
#ifndef OC_DYNAMIC_ALLOCATION
#define OC_MAX_APP_DATA_SIZE (800)
#endif
/* Maximum number of concurrent requests */
#define OC_MAX_NUM_CONCURRENT_REQUESTS (3)
/* Maximum number of nodes in a payload tree structure */
#define OC_MAX_NUM_REP_OBJECTS (15)
/* Number of devices on the OCF platform */
#define OC_MAX_NUM_DEVICES (1)
/* Maximum number of endpoints */
#define OC_MAX_NUM_ENDPOINTS (4)
/* Security layer */
/* Maximum number of authorized clients */
#define OC_MAX_NUM_SUBJECTS (2)
/* Maximum number of concurrent (D)TLS sessions */
#define OC_MAX_TLS_PEERS (1)
/* Maximal number of callbacks invoked before a dynamic resource is deleted */
#define OC_MAX_ON_DELETE_RESOURCE_CBS (2)
#endif /* !OC_DYNAMIC_ALLOCATION */
/* Wipe device name during reset, when oic/con is enabled */
/* Default: Wipe name */
#define OC_WIPE_NAME (1)
#ifdef __cplusplus
}
#endif
#endif /* CONFIG_H */
|
6e2147ea8b9522adb65dc0a10c5ecb045b238923
|
35c04ea32351dc95bc18d46e5c70dda9c1e08668
|
/Examples/CodeWarrior/FRDM-KL25Z/Freedom_Accel/Sources/MMA8451.c
|
7c501ef5ffb0bd16a3d4192634822a3ef71b4dfc
|
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
ErichStyger/mcuoneclipse
|
0f8e7a2056a26ed79d9d4a0afd64777ff0b2b2fe
|
04ad311b11860ae5f8285316010961a87fa06d0c
|
refs/heads/master
| 2023-08-28T22:54:08.501719
| 2023-08-25T15:11:44
| 2023-08-25T15:11:44
| 7,446,094
| 620
| 1,191
|
NOASSERTION
| 2020-10-16T03:13:28
| 2013-01-04T19:38:12
|
Batchfile
|
UTF-8
|
C
| false
| false
| 1,391
|
c
|
MMA8451.c
|
#if 0
/*
* MMA8451.c
*
* Created on: Mar 30, 2013
* Author: Erich Styger
*/
#include "MMA8451.h"
#include "GI2C1.h"
/* External 3-axis accelerometer control register addresses */
#define MMA8451_CTRL_REG_1 0x2A
/* MMA8451 3-axis accelerometer control register bit masks */
#define MMA8451_ACTIVE_BIT_MASK 0x01
#define MMA8451_F_READ_BIT_MASK 0x02
/* External 3-axis accelerometer data register addresses */
#define MMA8451_OUT_X_MSB 0x01
#define MMA8451_OUT_X_LSB 0x02
#define MMA8451_OUT_Y_MSB 0x03
#define MMA8451_OUT_Y_LSB 0x04
#define MMA8451_OUT_Z_MSB 0x05
#define MMA8451_OUT_Z_LSB 0x06
#define MMA8451_I2C_ADDR (0x1D) /* SA0=1 */
//#define MMA8451_I2C_ADDR (0x1C) /* SA0=0 */
uint8_t MMA8451_GetRaw8XYZ(uint8_t xyz[3]) {
static const uint8_t addr = MMA8451_OUT_X_MSB;
return GI2C1_ReadAddress(MMA8451_I2C_ADDR, (uint8_t*)&addr, sizeof(addr), &xyz[0], sizeof(xyz));
}
uint8_t MMA8451_Deinit(void) {
/* nothing to do */
return ERR_OK;
}
uint8_t MMA8451_Init(void) {
static const uint8_t addr = MMA8451_CTRL_REG_1;
static const uint8_t data = MMA8451_F_READ_BIT_MASK|MMA8451_ACTIVE_BIT_MASK;
/* F_READ: Fast read mode, data format limited to single byte (auto increment counter will skip LSB)
* ACTIVE: Full scale selection
*/
return GI2C1_WriteAddress(MMA8451_I2C_ADDR, (uint8_t*)&addr, sizeof(addr), (uint8_t*)&data, sizeof(data));
}
#endif
|
9f55ea3b832c07d23c75a79ce3ae970caee041e5
|
f9e7d65cb784c01a0200145ba8d289afe41d4a56
|
/chip/mt8192_scp/uart_regs.h
|
1a421a413beac8826ef3e9a6eed01e5e4950f7bc
|
[
"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
| 2,946
|
h
|
uart_regs.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.
*/
/* SCP UART module registers */
#ifndef __CROS_EC_UART_REGS_H
#define __CROS_EC_UART_REGS_H
#include "registers.h"
/* DLAB (Divisor Latch Access Bit) == 0 */
/* (Read) receiver buffer register */
#define UART_RBR(n) UART_REG(n, 0)
/* (Write) transmitter holding register */
#define UART_THR(n) UART_REG(n, 0)
/* (Write) interrupt enable register */
#define UART_IER(n) UART_REG(n, 1)
#define UART_IER_RDI BIT(0) /* received data */
#define UART_IER_THRI BIT(1) /* THR empty */
#define UART_IER_RLSI BIT(2) /* receiver LSR change */
#define UART_IER_MSI BIT(3) /* MSR change */
/* (Read) interrupt identification register */
#define UART_IIR(n) UART_REG(n, 2)
#define UART_IIR_ID_MASK 0x0e
#define UART_IIR_MSI 0x00 /* modem status change */
#define UART_IIR_NO_INT 0x01 /* no int pending */
#define UART_IIR_THRI 0x02 /* THR empty */
#define UART_IIR_RDI 0x04 /* received data available */
#define UART_IIR_RLSI 0x06 /* line status change */
/* (Write) FIFO control register */
#define UART_FCR(n) UART_REG(n, 2)
#define UART_FCR_ENABLE_FIFO BIT(0) /* enable FIFO */
#define UART_FCR_CLEAR_RCVR BIT(1) /* clear receive FIFO */
#define UART_FCR_CLEAR_XMIT BIT(2) /* clear transmit FIFO */
#define UART_FCR_DMA_SELECT BIT(3) /* select DMA mode */
/* (Write) line control register */
#define UART_LCR(n) UART_REG(n, 3)
#define UART_LCR_WLEN5 0 /* word length 5 bits */
#define UART_LCR_WLEN6 1
#define UART_LCR_WLEN7 2
#define UART_LCR_WLEN8 3
#define UART_LCR_STOP BIT(2) /* stop bits: 1bit, 2bits */
#define UART_LCR_PARITY BIT(3) /* parity enable */
#define UART_LCR_EPAR BIT(4) /* even parity */
#define UART_LCR_SPAR BIT(5) /* stick parity */
#define UART_LCR_SBC BIT(6) /* set break control */
#define UART_LCR_DLAB BIT(7) /* divisor latch access */
/* (Write) modem control register */
#define UART_MCR(n) UART_REG(n, 4)
/* (Read) line status register */
#define UART_LSR(n) UART_REG(n, 5)
#define UART_LSR_DR BIT(0) /* data ready */
#define UART_LSR_OE BIT(1) /* overrun error */
#define UART_LSR_PE BIT(2) /* parity error */
#define UART_LSR_FE BIT(3) /* frame error */
#define UART_LSR_BI BIT(4) /* break interrupt */
#define UART_LSR_THRE BIT(5) /* THR empty */
#define UART_LSR_TEMT BIT(6) /* THR empty, line idle */
#define UART_LSR_FIFOE BIT(7) /* FIFO error */
/* (Read) modem status register */
#define UART_MSR(n) UART_REG(n, 6)
/* (Read/Write) scratch register */
#define UART_SCR(n) UART_REG(n, 7)
/* DLAB == 1 */
/* (Write) divisor latch */
#define UART_DLL(n) UART_REG(n, 0)
#define UART_DLH(n) UART_REG(n, 1)
/* MTK extension */
#define UART_HIGHSPEED(n) UART_REG(n, 9)
#endif /* __CROS_EC_UART_REGS_H */
|
8acbc0591b1fbcfc3e744eab55dee515575ad749
|
34a2f46aeb01db43c4e04b879c1d096ddc34e8ae
|
/ext/better_html_ext/parser.h
|
633ca309463deea2be7c9b701349e38b51c24f70
|
[
"MIT"
] |
permissive
|
Shopify/better-html
|
abd6b9109eebef76c6f6f14de3a9a2a3cdd688de
|
6bed0a92226c9510515705cae100f088f496d029
|
refs/heads/main
| 2023-09-04T19:10:52.184780
| 2023-06-28T18:00:31
| 2023-06-28T18:00:31
| 60,442,615
| 253
| 30
|
MIT
| 2023-06-28T18:00:35
| 2016-06-05T04:08:48
|
Ruby
|
UTF-8
|
C
| false
| false
| 1,969
|
h
|
parser.h
|
#pragma once
#include "tokenizer.h"
enum parser_context {
PARSER_NONE,
PARSER_SOLIDUS_OR_TAG_NAME,
PARSER_TAG_NAME,
PARSER_TAG,
PARSER_ATTRIBUTE_NAME,
PARSER_ATTRIBUTE_WHITESPACE_OR_EQUAL,
PARSER_ATTRIBUTE_WHITESPACE_OR_VALUE,
PARSER_ATTRIBUTE_QUOTED_VALUE,
PARSER_SPACE_AFTER_ATTRIBUTE,
PARSER_ATTRIBUTE_UNQUOTED_VALUE,
PARSER_TAG_END,
PARSER_COMMENT,
PARSER_CDATA,
};
struct parser_document_error_t {
char *message;
long unsigned int pos;
long unsigned int mb_pos;
long unsigned int line_number;
long unsigned int column_number;
};
struct parser_document_t {
long unsigned int length;
char *data;
long unsigned int line_number;
long unsigned int column_number;
int enc_index;
long unsigned int mb_length;
};
struct token_reference_t {
enum token_type type;
long unsigned int start;
long unsigned int mb_start;
long unsigned int length;
long unsigned int line_number;
long unsigned int column_number;
};
struct parser_tag_t {
struct token_reference_t name;
int self_closing;
};
struct parser_attribute_t {
struct token_reference_t name;
struct token_reference_t value;
int is_quoted;
};
struct parser_rawtext_t {
struct token_reference_t text;
};
struct parser_comment_t {
struct token_reference_t text;
};
struct parser_cdata_t {
struct token_reference_t text;
};
struct parser_t
{
struct tokenizer_t tk;
struct parser_document_t doc;
size_t errors_count;
struct parser_document_error_t *errors;
enum parser_context context;
struct parser_tag_t tag;
struct parser_attribute_t attribute;
struct parser_rawtext_t rawtext;
struct parser_comment_t comment;
struct parser_cdata_t cdata;
};
void Init_html_tokenizer_parser(VALUE mHtmlTokenizer);
extern const rb_data_type_t ht_parser_data_type;
#define Parser_Get_Struct(obj, sval) TypedData_Get_Struct(obj, struct parser_t, &ht_parser_data_type, sval)
#define PARSE_AGAIN return 1
#define PARSE_DONE return 0
|
a076fead6a1ef173e9d10eaa8e82e243b95551b1
|
352515ca3375deb1a893d1e236ba4dd17a3b97a4
|
/rcl/src/rcl/guard_condition.c
|
62974347d1f2f767b790032baf90f6dcf2d5e358
|
[
"Apache-2.0"
] |
permissive
|
ros2/rcl
|
9bd7d31e5ca12ae12a1090294a2348fad0a562d4
|
41b83c8ebfe8344a80c0093083b7abdfded79337
|
refs/heads/rolling
| 2023-09-01T17:45:40.871185
| 2023-08-28T17:49:55
| 2023-08-28T17:49:55
| 31,091,419
| 117
| 183
|
Apache-2.0
| 2023-09-11T13:19:40
| 2015-02-21T00:06:40
|
C++
|
UTF-8
|
C
| false
| false
| 6,411
|
c
|
guard_condition.c
|
// Copyright 2015 Open Source Robotics Foundation, 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.
#ifdef __cplusplus
extern "C"
{
#endif
#include "rcl/guard_condition.h"
#include "rcl/error_handling.h"
#include "rcl/rcl.h"
#include "rmw/error_handling.h"
#include "rmw/rmw.h"
#include "./context_impl.h"
struct rcl_guard_condition_impl_s
{
rmw_guard_condition_t * rmw_handle;
bool allocated_rmw_guard_condition;
rcl_guard_condition_options_t options;
};
rcl_guard_condition_t
rcl_get_zero_initialized_guard_condition()
{
static rcl_guard_condition_t null_guard_condition = {
.context = 0,
.impl = 0
};
return null_guard_condition;
}
rcl_ret_t
__rcl_guard_condition_init_from_rmw_impl(
rcl_guard_condition_t * guard_condition,
const rmw_guard_condition_t * rmw_guard_condition,
rcl_context_t * context,
const rcl_guard_condition_options_t options)
{
// This function will create an rmw_guard_condition if the parameter is null.
// Perform argument validation.
const rcl_allocator_t * allocator = &options.allocator;
RCL_CHECK_ALLOCATOR_WITH_MSG(allocator, "invalid allocator", return RCL_RET_INVALID_ARGUMENT);
RCL_CHECK_ARGUMENT_FOR_NULL(guard_condition, RCL_RET_INVALID_ARGUMENT);
// Ensure the guard_condition handle is zero initialized.
if (guard_condition->impl) {
RCL_SET_ERROR_MSG("guard_condition already initialized, or memory was unintialized");
return RCL_RET_ALREADY_INIT;
}
// Make sure rcl has been initialized.
RCL_CHECK_ARGUMENT_FOR_NULL(context, RCL_RET_INVALID_ARGUMENT);
if (!rcl_context_is_valid(context)) {
RCL_SET_ERROR_MSG(
"the given context is not valid, "
"either rcl_init() was not called or rcl_shutdown() was called.");
return RCL_RET_NOT_INIT;
}
// Allocate space for the guard condition impl.
guard_condition->impl = (rcl_guard_condition_impl_t *)allocator->allocate(
sizeof(rcl_guard_condition_impl_t), allocator->state);
if (!guard_condition->impl) {
RCL_SET_ERROR_MSG("allocating memory failed");
return RCL_RET_BAD_ALLOC;
}
// Create the rmw guard condition.
if (rmw_guard_condition) {
// If given, just assign (cast away const).
guard_condition->impl->rmw_handle = (rmw_guard_condition_t *)rmw_guard_condition;
guard_condition->impl->allocated_rmw_guard_condition = false;
} else {
// Otherwise create one.
guard_condition->impl->rmw_handle = rmw_create_guard_condition(&(context->impl->rmw_context));
if (!guard_condition->impl->rmw_handle) {
// Deallocate impl and exit.
allocator->deallocate(guard_condition->impl, allocator->state);
guard_condition->impl = NULL;
RCL_SET_ERROR_MSG(rmw_get_error_string().str);
return RCL_RET_ERROR;
}
guard_condition->impl->allocated_rmw_guard_condition = true;
}
// Copy options into impl.
guard_condition->impl->options = options;
return RCL_RET_OK;
}
rcl_ret_t
rcl_guard_condition_init(
rcl_guard_condition_t * guard_condition,
rcl_context_t * context,
const rcl_guard_condition_options_t options)
{
// NULL indicates "create a new rmw guard condition".
return __rcl_guard_condition_init_from_rmw_impl(guard_condition, NULL, context, options);
}
rcl_ret_t
rcl_guard_condition_init_from_rmw(
rcl_guard_condition_t * guard_condition,
const rmw_guard_condition_t * rmw_guard_condition,
rcl_context_t * context,
const rcl_guard_condition_options_t options)
{
return __rcl_guard_condition_init_from_rmw_impl(
guard_condition, rmw_guard_condition, context, options);
}
rcl_ret_t
rcl_guard_condition_fini(rcl_guard_condition_t * guard_condition)
{
// Perform argument validation.
RCL_CHECK_ARGUMENT_FOR_NULL(guard_condition, RCL_RET_INVALID_ARGUMENT);
rcl_ret_t result = RCL_RET_OK;
if (guard_condition->impl) {
// assuming the allocator is valid because it is checked in rcl_guard_condition_init()
rcl_allocator_t allocator = guard_condition->impl->options.allocator;
if (guard_condition->impl->rmw_handle && guard_condition->impl->allocated_rmw_guard_condition) {
if (rmw_destroy_guard_condition(guard_condition->impl->rmw_handle) != RMW_RET_OK) {
RCL_SET_ERROR_MSG(rmw_get_error_string().str);
result = RCL_RET_ERROR;
}
}
allocator.deallocate(guard_condition->impl, allocator.state);
guard_condition->impl = NULL;
}
return result;
}
rcl_guard_condition_options_t
rcl_guard_condition_get_default_options()
{
// !!! MAKE SURE THAT CHANGES TO THESE DEFAULTS ARE REFLECTED IN THE HEADER DOC STRING
static rcl_guard_condition_options_t default_options;
default_options.allocator = rcl_get_default_allocator();
return default_options;
}
rcl_ret_t
rcl_trigger_guard_condition(rcl_guard_condition_t * guard_condition)
{
const rcl_guard_condition_options_t * options = rcl_guard_condition_get_options(guard_condition);
if (!options) {
return RCL_RET_INVALID_ARGUMENT; // error already set
}
// Trigger the guard condition.
if (rmw_trigger_guard_condition(guard_condition->impl->rmw_handle) != RMW_RET_OK) {
RCL_SET_ERROR_MSG(rmw_get_error_string().str);
return RCL_RET_ERROR;
}
return RCL_RET_OK;
}
const rcl_guard_condition_options_t *
rcl_guard_condition_get_options(const rcl_guard_condition_t * guard_condition)
{
// Perform argument validation.
RCL_CHECK_ARGUMENT_FOR_NULL(guard_condition, NULL);
RCL_CHECK_FOR_NULL_WITH_MSG(
guard_condition->impl,
"guard condition implementation is invalid",
return NULL);
return &guard_condition->impl->options;
}
rmw_guard_condition_t *
rcl_guard_condition_get_rmw_handle(const rcl_guard_condition_t * guard_condition)
{
const rcl_guard_condition_options_t * options = rcl_guard_condition_get_options(guard_condition);
if (!options) {
return NULL; // error already set
}
return guard_condition->impl->rmw_handle;
}
#ifdef __cplusplus
}
#endif
|
1795f54b12d5da8aba6c2245fc982e7c10857e47
|
9de18ef120a8ae68483b866c1d4c7b9c2fbef46e
|
/third_party/libcutils/rust/cutils.h
|
9b78af631e46486b44ce5183f9604a40d448c92b
|
[
"Apache-2.0",
"BSD-2-Clause",
"LicenseRef-scancode-free-unknown"
] |
permissive
|
google/orbit
|
02a5b4556cd2f979f377b87c24dd2b0a90dff1e2
|
68c4ae85a6fe7b91047d020259234f7e4961361c
|
refs/heads/main
| 2023-09-03T13:14:49.830576
| 2023-08-25T06:28:36
| 2023-08-25T06:28:36
| 104,358,587
| 2,680
| 325
|
BSD-2-Clause
| 2023-08-25T06:28:37
| 2017-09-21T14:28:35
|
C++
|
UTF-8
|
C
| false
| false
| 91
|
h
|
cutils.h
|
#pragma once
#include <cutils/multiuser.h>
#include <private/android_filesystem_config.h>
|
d5cc154c6cf3c935ae450d99852a38515ce22583
|
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
|
/sys/arch/hpcmips/dev/plumiobus.c
|
d45eed11cf1ba03dfd45084238695fc46501cc3f
|
[] |
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
| 7,169
|
c
|
plumiobus.c
|
/* $NetBSD: plumiobus.c,v 1.19 2022/01/24 09:14:37 andvar Exp $ */
/*-
* Copyright (c) 1999, 2000 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by UCHIYAMA Yasushi.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: plumiobus.c,v 1.19 2022/01/24 09:14:37 andvar Exp $");
#define PLUMIOBUSDEBUG
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/device.h>
#include <sys/kmem.h>
#include <machine/bus.h>
#include <machine/intr.h>
#include <hpcmips/tx/tx39var.h>
#include <hpcmips/dev/plumvar.h>
#include <hpcmips/dev/plumicuvar.h>
#include <hpcmips/dev/plumpowervar.h>
#include <hpcmips/dev/plumiobusreg.h>
#include <hpcmips/dev/plumiobusvar.h>
#include "locators.h"
#ifdef PLUMIOBUSDEBUG
int plumiobus_debug = 0;
#define DPRINTF(arg) if (plumiobus_debug) printf arg;
#define DPRINTFN(n, arg) if (plumiobus_debug > (n)) printf arg;
#else
#define DPRINTF(arg)
#define DPRINTFN(n, arg)
#endif
int plumiobus_match(device_t, cfdata_t, void *);
void plumiobus_attach(device_t, device_t, void *);
int plumiobus_print(void *, const char *);
int plumiobus_search(device_t, cfdata_t , const int *, void *);
struct plumisa_resource {
int pr_irq;
bus_space_tag_t pr_iot;
int pr_enabled;
};
struct plumiobus_softc {
plum_chipset_tag_t sc_pc;
bus_space_tag_t sc_regt;
bus_space_handle_t sc_regh;
bus_space_tag_t sc_iot;
bus_space_handle_t sc_ioh;
struct plumisa_resource sc_isa[PLUM_IOBUS_IO5CSMAX];
};
CFATTACH_DECL_NEW(plumiobus, sizeof(struct plumiobus_softc),
plumiobus_match, plumiobus_attach, NULL, NULL);
bus_space_tag_t __plumiobus_subregion(bus_space_tag_t, bus_addr_t,
bus_size_t);
#ifdef PLUMIOBUSDEBUG
void plumiobus_dump(struct plumiobus_softc *);
#endif
int
plumiobus_match(device_t parent, cfdata_t cf, void *aux)
{
return (1);
}
void
plumiobus_attach(device_t parent, device_t self, void *aux)
{
struct plum_attach_args *pa = aux;
struct plumiobus_softc *sc = device_private(self);
struct plumisa_resource *pr;
sc->sc_pc = pa->pa_pc;
sc->sc_regt = pa->pa_regt;
sc->sc_iot = pa->pa_iot;
if (bus_space_map(sc->sc_regt, PLUM_IOBUS_REGBASE,
PLUM_IOBUS_REGSIZE, 0, &sc->sc_regh)) {
printf(": register map failed.\n");
return;
}
printf("\n");
plum_power_establish(sc->sc_pc, PLUM_PWR_IO5);
/* Address space <-> IRQ mapping */
pr = &sc->sc_isa[IO5CS0];
pr->pr_irq = PLUM_INT_EXT5IO0;
pr->pr_iot = __plumiobus_subregion(
sc->sc_iot,
PLUM_IOBUS_IOBASE + PLUM_IOBUS_IO5CS0BASE,
PLUM_IOBUS_IO5SIZE);
pr = &sc->sc_isa[IO5CS1];
pr->pr_irq = PLUM_INT_EXT5IO1;
pr->pr_iot = __plumiobus_subregion(
sc->sc_iot,
PLUM_IOBUS_IOBASE + PLUM_IOBUS_IO5CS1BASE,
PLUM_IOBUS_IO5SIZE);
pr = &sc->sc_isa[IO5CS2];
pr->pr_irq = PLUM_INT_EXT5IO2;
pr->pr_iot = __plumiobus_subregion(
sc->sc_iot,
PLUM_IOBUS_IOBASE + PLUM_IOBUS_IO5CS2BASE,
PLUM_IOBUS_IO5SIZE);
pr = &sc->sc_isa[IO5CS3];
pr->pr_irq = PLUM_INT_EXT5IO3;
pr->pr_iot = __plumiobus_subregion(
sc->sc_iot,
PLUM_IOBUS_IOBASE + PLUM_IOBUS_IO5CS3BASE,
PLUM_IOBUS_IO5SIZE);
pr = &sc->sc_isa[IO5CS4];
pr->pr_irq = PLUM_INT_EXT3IO0; /* XXX */
pr->pr_iot = __plumiobus_subregion(
sc->sc_iot,
PLUM_IOBUS_IOBASE + PLUM_IOBUS_IO5CS4BASE,
PLUM_IOBUS_IO5SIZE);
pr = &sc->sc_isa[IO5NCS];
pr->pr_irq = PLUM_INT_EXT3IO1;
pr->pr_iot = __plumiobus_subregion(
sc->sc_iot,
PLUM_IOBUS_IOBASE + PLUM_IOBUS_IO5CS5BASE,
PLUM_IOBUS_IO5SIZE);
#ifdef PLUMIOBUSDEBUG
plumiobus_dump(sc);
#endif
config_search(self, NULL,
CFARGS(.search = plumiobus_search));
}
/* XXX something kludge */
bus_space_tag_t
__plumiobus_subregion(bus_space_tag_t t, bus_addr_t ofs, bus_size_t size)
{
struct hpcmips_bus_space *hbs;
hbs = kmem_alloc(sizeof(*hbs), KM_SLEEP);
*hbs = *t;
hbs->t_base += ofs;
hbs->t_size = size;
return (hbs);
}
int
plumiobus_search(device_t parent, cfdata_t cf, const int *ldesc, void *aux)
{
struct plumiobus_softc *sc = device_private(parent);
struct plumiobus_attach_args pba;
int slot;
/* Disallow wildcarded IO5CS slot */
if (cf->cf_loc[PLUMIOBUSIFCF_SLOT] == PLUMIOBUSIFCF_SLOT_DEFAULT) {
printf("plumiobus_search: wildcarded slot, skipping\n");
return (0);
}
slot = pba.pba_slot = cf->cf_loc[PLUMIOBUSIFCF_SLOT];
pba.pba_pc = sc->sc_pc;
pba.pba_iot = sc->sc_isa[slot].pr_iot;
pba.pba_irq = sc->sc_isa[slot].pr_irq;
pba.pba_busname = "plumisab";
if (!(sc->sc_isa[slot].pr_enabled) && /* not attached slot */
config_probe(parent, cf, &pba)) {
config_attach(parent, cf, &pba, plumiobus_print, CFARGS_NONE);
sc->sc_isa[slot].pr_enabled = 1;
}
return (0);
}
int
plumiobus_print(void *aux, const char *pnp)
{
return (pnp ? QUIET : UNCONF);
}
#ifdef PLUMIOBUSDEBUG
void
plumiobus_dump(struct plumiobus_softc *sc)
{
bus_space_tag_t regt = sc->sc_regt;
bus_space_handle_t regh = sc->sc_regh;
plumreg_t reg;
int i, wait;
reg = plum_conf_read(regt, regh, PLUM_IOBUS_IOXBSZ_REG);
printf("8bit port:");
for (i = 0; i < 6; i++) {
if (reg & (1 << i)) {
printf(" IO5CS%d", i);
}
}
printf("\n");
reg = PLUM_IOBUS_IOXCCNT_MASK &
plum_conf_read(regt, regh, PLUM_IOBUS_IOXCCNT_REG);
printf(" # of wait to become from the access beginning: %d clock\n",
reg + 1);
reg = plum_conf_read(regt, regh, PLUM_IOBUS_IOXACNT_REG);
printf(" # of wait in access clock: ");
for (i = 0; i < 5; i++) {
wait = (reg >> (i * PLUM_IOBUS_IOXACNT_SHIFT))
& PLUM_IOBUS_IOXACNT_MASK;
printf("[CS%d:%d] ", i, wait + 1);
}
printf("\n");
reg = PLUM_IOBUS_IOXSCNT_MASK &
plum_conf_read(regt, regh, PLUM_IOBUS_IOXSCNT_REG);
printf(" # of wait during access by I/O bus : %d clock\n", reg + 1);
reg = plum_conf_read(regt, regh, PLUM_IOBUS_IDEMODE_REG);
if (reg & PLUM_IOBUS_IDEMODE) {
printf("IO5CS3,4 IDE mode\n");
}
}
#endif /* PLUMIOBUSDEBUG */
|
cfd745e5e1eb4fc2154fa9b08df4f35dd6c3b42f
|
632f6f14abb1dbdf86aca1506b8012392bef2a41
|
/source/hic_hal/nxp/lpc4322/RTE_Driver/SCU_LPC43xx.c
|
146b2b7ae02c1b834fe7a2590789ef110d83bf8b
|
[
"Apache-2.0"
] |
permissive
|
ARMmbed/DAPLink
|
a34f7ce41d6bfc38d49283766a03280f52322f2a
|
19f797fa6396b726250c57eb9be80245a5f877dd
|
refs/heads/main
| 2023-08-23T20:37:22.744671
| 2023-06-29T19:36:00
| 2023-08-16T16:39:58
| 24,571,059
| 1,865
| 883
|
Apache-2.0
| 2023-08-16T16:39:59
| 2014-09-28T21:38:24
|
C
|
UTF-8
|
C
| false
| false
| 5,283
|
c
|
SCU_LPC43xx.c
|
/* --------------------------------------------------------------------------
* Copyright (c) 2013-2019 Arm Limited (or its affiliates). All
* rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*
* $Date: 30. April 2019
* $Revision: V1.2
*
* Project: SCU Driver for NXP LPC43xx
* -------------------------------------------------------------------------- */
/* History:
* Version 1.1
* - Corrected SCU_SFSCLKx(clk_pin) and SCU_ENAIOx(n) macros
* Version 1.0
* - Initial release
*/
#include "LPC43xx.h"
#include "SCU_LPC43xx.h"
#define PORT_OFFSET ( 0x80 )
#define PIN_OFFSET ( 0x04 )
#define SCU_SFSPx(port, pin) (*((volatile uint32_t *) ((LPC_SCU_BASE + PORT_OFFSET * port + PIN_OFFSET * pin))))
#define SCU_SFSCLKx(clk_pin) (*((volatile uint32_t *) (&(LPC_SCU->SFSCLK_0) + clk_pin)))
#define SCU_ENAIOx(n) (*((volatile uint32_t *) (&(LPC_SCU->ENAIO0) + n)))
/**
\fn int32_t SCU_PinConfiguare (uint8_t port, uint8_t pin, uint32_t pin_cfg)
\brief Set pin function and electrical characteristics
\param[in] port Port number (0..15)
\param[in] pin Pin number (0..31)
\param[in] pin_cfg pin_cfg configuration bit mask
- \b 0: function succeeded
- \b -1: function failed
*/
int32_t SCU_PinConfigure (uint8_t port, uint8_t pin, uint32_t pin_cfg) {
if ((port > 15) || (pin > 31)) return -1;
SCU_SFSPx(port, pin) = pin_cfg;
return 0;
}
/**
\fn int32_t SCU_CLK_PinConfigure (uint8_t clk_pin, uint32_t pin_cfg)
\brief Set pin function and electrical characteristics for CLK pins
\param[in] clk_pin Clock pin number should be 0..3
\param[in] pin_cfg pin_cfg
- \b 0: function succeeded
- \b -1: function failed
*/
int32_t SCU_CLK_PinConfigure (uint8_t pin_clk, uint32_t pin_cfg) {
if (pin_clk > 3) return -1;
SCU_SFSCLKx(pin_clk) = pin_cfg;
return 0;
}
/**
\fn int32_t SCU_USB1_PinConfigure (uint32_t USB1_pin_cfg)
\brief Pin configuration for USB1 USB_DP/USBDM pins
\param[in] USB1_pin_cfg USB1_pin_cfg configuration bit mask
- \b 0: function succeeded
- \b -1: function failed
*/
int32_t SCU_USB1_PinConfigure (uint32_t USB1_pin_cfg) {
LPC_SCU->SFSUSB = USB1_pin_cfg;
return 0;
}
/**
\fn int32_t SCU_I2C_PinConfigure (uint32_t I2C_mode)
\brief Set I2C pin configuration
\param[in] I2C_mode: SCU_I2C_PIN_MODE_DISABLED
SCU_I2C_PIN_MODE_STANDARD_FAST
SCU_I2C_PIN_MODE_FAST_PLUS
- \b 0: function succeeded
- \b -1: function failed
*/
int32_t SCU_I2C_PinConfigure (uint32_t I2C_mode) {
switch (I2C_mode) {
case SCU_I2C_PIN_MODE_DISABLED: break;
case SCU_I2C_PIN_MODE_STANDARD_FAST: break;
case SCU_I2C_PIN_MODE_FAST_PLUS: break;
default: return -1;
}
LPC_SCU->SFSI2C0 = I2C_mode;
return 0;
}
/**
\fn int32_t SCU_ADC_ChannelPinConfigure (uint8_t ADC_num, uint8_t channel, uint32_t cmd)
\brief ADC Channel configuration
\param[in] ADC_num: 0 = ADC0, 1 = ADC1
\param[in] channel: channel number 0..7
\param[in] cmd: 1 - enabled, 0 - disabled
- \b 0: function succeeded
- \b -1: function failed
*/
int32_t SCU_ADC_ChannelPinConfigure (uint8_t ADC_num, uint8_t channel, uint32_t cmd) {
if ((ADC_num > 1) || (channel > 7) || (cmd > 1)) return -1;
cmd ? (SCU_ENAIOx(ADC_num) |= (1 << channel)) : (SCU_ENAIOx(ADC_num) &= ~(1 << channel));
return 0;
}
/**
\fn int32_t SCU_DAC_PinConfigure (uint32_t cmd)
\brief Analog function on P4_4
\param[in] cmd: 1 - enabled, 0 - disabled
- \b 0: function succeeded
- \b -1: function failed
*/
int32_t SCU_DAC_PinConfigure (uint32_t cmd) {
if (cmd > 1) return -1;
cmd ? (LPC_SCU->ENAIO2 |= SCU_ENAIO2_DAC) : (LPC_SCU->ENAIO2 &= ~SCU_ENAIO2_DAC);
return 0;
}
/**
\fn int32_t SCU_PinInterruptSourceSelect (uint8_t pin_int, uint8_t port, uint8_t pin)
\brief Select interrupt source pin
\param[in] pin_int: pin interrupt 0..7
\param[in] port: GPIO port number 0..7
\param[in] pin: GPIO pin number 0..31
\returns
- \b 0: function succeeded
- \b -1: function failed
*/
int32_t SCU_PinInterruptSourceSelect (uint8_t pin_int, uint8_t port, uint8_t pin) {
if ((port > 7) || (pin > 31) || (pin_int > 7)) return -1;
if (pin_int < 4) {
LPC_SCU->PINTSEL0 &= ~(0xFFUL << (8 * pin_int));
LPC_SCU->PINTSEL0 |= ((uint32_t)(pin | (port << 5)) << (8 * pin_int));
} else {
pin_int -= 4;
LPC_SCU->PINTSEL1 &= ~(0xFFUL << (8 * pin_int));
LPC_SCU->PINTSEL1 |= ((uint32_t)(pin | (port << 5)) << (8 * pin_int));
}
return 0;
}
|
8849b09faddfd7d32b465131720736a2a4dcd617
|
0781549584321df513b2615711a3f6ed0005d2ce
|
/spark-server/server/Test/TestDependency/skynet/skynet-src/socket_server.c
|
ddee29431c698937293dc15650dd0a4349dcfe31
|
[
"MIT"
] |
permissive
|
Manistein/SparkServer
|
f476c6fca1bf2fd692d9a9debb838244c551d1af
|
7b2f295ee5f95de48e453aedb0a79ab0b35dd6ac
|
refs/heads/master
| 2023-05-12T17:22:31.437530
| 2023-04-26T07:33:23
| 2023-04-26T07:33:23
| 182,103,174
| 227
| 53
|
MIT
| 2022-12-08T05:29:03
| 2019-04-18T14:30:08
|
C
|
UTF-8
|
C
| false
| false
| 50,373
|
c
|
socket_server.c
|
#include "skynet.h"
#include "socket_server.h"
#include "socket_poll.h"
#include "atomic.h"
#include "spinlock.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/tcp.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include <assert.h>
#include <string.h>
#define MAX_INFO 128
// MAX_SOCKET will be 2^MAX_SOCKET_P
#define MAX_SOCKET_P 16
#define MAX_EVENT 64
#define MIN_READ_BUFFER 64
#define SOCKET_TYPE_INVALID 0
#define SOCKET_TYPE_RESERVE 1
#define SOCKET_TYPE_PLISTEN 2
#define SOCKET_TYPE_LISTEN 3
#define SOCKET_TYPE_CONNECTING 4
#define SOCKET_TYPE_CONNECTED 5
#define SOCKET_TYPE_HALFCLOSE 6
#define SOCKET_TYPE_PACCEPT 7
#define SOCKET_TYPE_BIND 8
#define MAX_SOCKET (1<<MAX_SOCKET_P)
#define PRIORITY_HIGH 0
#define PRIORITY_LOW 1
#define HASH_ID(id) (((unsigned)id) % MAX_SOCKET)
#define ID_TAG16(id) ((id>>MAX_SOCKET_P) & 0xffff)
#define PROTOCOL_TCP 0
#define PROTOCOL_UDP 1
#define PROTOCOL_UDPv6 2
#define PROTOCOL_UNKNOWN 255
#define UDP_ADDRESS_SIZE 19 // ipv6 128bit + port 16bit + 1 byte type
#define MAX_UDP_PACKAGE 65535
// EAGAIN and EWOULDBLOCK may be not the same value.
#if (EAGAIN != EWOULDBLOCK)
#define AGAIN_WOULDBLOCK EAGAIN : case EWOULDBLOCK
#else
#define AGAIN_WOULDBLOCK EAGAIN
#endif
#define WARNING_SIZE (1024*1024)
struct write_buffer {
struct write_buffer * next;
void *buffer;
char *ptr;
int sz;
bool userobject;
uint8_t udp_address[UDP_ADDRESS_SIZE];
};
#define SIZEOF_TCPBUFFER (offsetof(struct write_buffer, udp_address[0]))
#define SIZEOF_UDPBUFFER (sizeof(struct write_buffer))
struct wb_list {
struct write_buffer * head;
struct write_buffer * tail;
};
struct socket_stat {
uint64_t rtime;
uint64_t wtime;
uint64_t read;
uint64_t write;
};
struct socket {
uintptr_t opaque;
struct wb_list high;
struct wb_list low;
int64_t wb_size;
struct socket_stat stat;
volatile uint32_t sending;
int fd;
int id;
uint8_t protocol;
uint8_t type;
uint16_t udpconnecting;
int64_t warn_size;
union {
int size;
uint8_t udp_address[UDP_ADDRESS_SIZE];
} p;
struct spinlock dw_lock;
int dw_offset;
const void * dw_buffer;
size_t dw_size;
};
struct socket_server {
volatile uint64_t time;
int recvctrl_fd;
int sendctrl_fd;
int checkctrl;
poll_fd event_fd;
int alloc_id;
int event_n;
int event_index;
struct socket_object_interface soi;
struct event ev[MAX_EVENT];
struct socket slot[MAX_SOCKET];
char buffer[MAX_INFO];
uint8_t udpbuffer[MAX_UDP_PACKAGE];
fd_set rfds;
};
struct request_open {
int id;
int port;
uintptr_t opaque;
char host[1];
};
struct request_send {
int id;
int sz;
char * buffer;
};
struct request_send_udp {
struct request_send send;
uint8_t address[UDP_ADDRESS_SIZE];
};
struct request_setudp {
int id;
uint8_t address[UDP_ADDRESS_SIZE];
};
struct request_close {
int id;
int shutdown;
uintptr_t opaque;
};
struct request_listen {
int id;
int fd;
uintptr_t opaque;
char host[1];
};
struct request_bind {
int id;
int fd;
uintptr_t opaque;
};
struct request_start {
int id;
uintptr_t opaque;
};
struct request_setopt {
int id;
int what;
int value;
};
struct request_udp {
int id;
int fd;
int family;
uintptr_t opaque;
};
/*
The first byte is TYPE
S Start socket
B Bind socket
L Listen socket
K Close socket
O Connect to (Open)
X Exit
D Send package (high)
P Send package (low)
A Send UDP package
T Set opt
U Create UDP socket
C set udp address
Q query info
*/
struct request_package {
uint8_t header[8]; // 6 bytes dummy
union {
char buffer[256];
struct request_open open;
struct request_send send;
struct request_send_udp send_udp;
struct request_close close;
struct request_listen listen;
struct request_bind bind;
struct request_start start;
struct request_setopt setopt;
struct request_udp udp;
struct request_setudp set_udp;
} u;
uint8_t dummy[256];
};
union sockaddr_all {
struct sockaddr s;
struct sockaddr_in v4;
struct sockaddr_in6 v6;
};
struct send_object {
void * buffer;
int sz;
void (*free_func)(void *);
};
#define MALLOC skynet_malloc
#define FREE skynet_free
struct socket_lock {
struct spinlock *lock;
int count;
};
static inline void
socket_lock_init(struct socket *s, struct socket_lock *sl) {
sl->lock = &s->dw_lock;
sl->count = 0;
}
static inline void
socket_lock(struct socket_lock *sl) {
if (sl->count == 0) {
spinlock_lock(sl->lock);
}
++sl->count;
}
static inline int
socket_trylock(struct socket_lock *sl) {
if (sl->count == 0) {
if (!spinlock_trylock(sl->lock))
return 0; // lock failed
}
++sl->count;
return 1;
}
static inline void
socket_unlock(struct socket_lock *sl) {
--sl->count;
if (sl->count <= 0) {
assert(sl->count == 0);
spinlock_unlock(sl->lock);
}
}
static inline bool
send_object_init(struct socket_server *ss, struct send_object *so, void *object, int sz) {
if (sz < 0) {
so->buffer = ss->soi.buffer(object);
so->sz = ss->soi.size(object);
so->free_func = ss->soi.free;
return true;
} else {
so->buffer = object;
so->sz = sz;
so->free_func = FREE;
return false;
}
}
static inline void
write_buffer_free(struct socket_server *ss, struct write_buffer *wb) {
if (wb->userobject) {
ss->soi.free(wb->buffer);
} else {
FREE(wb->buffer);
}
FREE(wb);
}
static void
socket_keepalive(int fd) {
int keepalive = 1;
setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive , sizeof(keepalive));
}
static int
reserve_id(struct socket_server *ss) {
int i;
for (i=0;i<MAX_SOCKET;i++) {
int id = ATOM_INC(&(ss->alloc_id));
if (id < 0) {
id = ATOM_AND(&(ss->alloc_id), 0x7fffffff);
}
struct socket *s = &ss->slot[HASH_ID(id)];
if (s->type == SOCKET_TYPE_INVALID) {
if (ATOM_CAS(&s->type, SOCKET_TYPE_INVALID, SOCKET_TYPE_RESERVE)) {
s->id = id;
s->protocol = PROTOCOL_UNKNOWN;
// socket_server_udp_connect may inc s->udpconncting directly (from other thread, before new_fd),
// so reset it to 0 here rather than in new_fd.
s->udpconnecting = 0;
s->fd = -1;
return id;
} else {
// retry
--i;
}
}
}
return -1;
}
static inline void
clear_wb_list(struct wb_list *list) {
list->head = NULL;
list->tail = NULL;
}
struct socket_server *
socket_server_create(uint64_t time) {
int i;
int fd[2];
poll_fd efd = sp_create();
if (sp_invalid(efd)) {
fprintf(stderr, "socket-server: create event pool failed.\n");
return NULL;
}
if (pipe(fd)) {
sp_release(efd);
fprintf(stderr, "socket-server: create socket pair failed.\n");
return NULL;
}
if (sp_add(efd, fd[0], NULL)) {
// add recvctrl_fd to event poll
fprintf(stderr, "socket-server: can't add server fd to event pool.\n");
close(fd[0]);
close(fd[1]);
sp_release(efd);
return NULL;
}
struct socket_server *ss = MALLOC(sizeof(*ss));
ss->time = time;
ss->event_fd = efd;
ss->recvctrl_fd = fd[0];
ss->sendctrl_fd = fd[1];
ss->checkctrl = 1;
for (i=0;i<MAX_SOCKET;i++) {
struct socket *s = &ss->slot[i];
s->type = SOCKET_TYPE_INVALID;
clear_wb_list(&s->high);
clear_wb_list(&s->low);
spinlock_init(&s->dw_lock);
}
ss->alloc_id = 0;
ss->event_n = 0;
ss->event_index = 0;
memset(&ss->soi, 0, sizeof(ss->soi));
FD_ZERO(&ss->rfds);
assert(ss->recvctrl_fd < FD_SETSIZE);
return ss;
}
void
socket_server_updatetime(struct socket_server *ss, uint64_t time) {
ss->time = time;
}
static void
free_wb_list(struct socket_server *ss, struct wb_list *list) {
struct write_buffer *wb = list->head;
while (wb) {
struct write_buffer *tmp = wb;
wb = wb->next;
write_buffer_free(ss, tmp);
}
list->head = NULL;
list->tail = NULL;
}
static void
free_buffer(struct socket_server *ss, const void * buffer, int sz) {
struct send_object so;
send_object_init(ss, &so, (void *)buffer, sz);
so.free_func((void *)buffer);
}
static void
force_close(struct socket_server *ss, struct socket *s, struct socket_lock *l, struct socket_message *result) {
result->id = s->id;
result->ud = 0;
result->data = NULL;
result->opaque = s->opaque;
if (s->type == SOCKET_TYPE_INVALID) {
return;
}
assert(s->type != SOCKET_TYPE_RESERVE);
free_wb_list(ss,&s->high);
free_wb_list(ss,&s->low);
if (s->type != SOCKET_TYPE_PACCEPT && s->type != SOCKET_TYPE_PLISTEN) {
sp_del(ss->event_fd, s->fd);
}
socket_lock(l);
if (s->type != SOCKET_TYPE_BIND) {
if (close(s->fd) < 0) {
perror("close socket:");
}
}
s->type = SOCKET_TYPE_INVALID;
if (s->dw_buffer) {
free_buffer(ss, s->dw_buffer, s->dw_size);
s->dw_buffer = NULL;
}
socket_unlock(l);
}
void
socket_server_release(struct socket_server *ss) {
int i;
struct socket_message dummy;
for (i=0;i<MAX_SOCKET;i++) {
struct socket *s = &ss->slot[i];
struct socket_lock l;
socket_lock_init(s, &l);
if (s->type != SOCKET_TYPE_RESERVE) {
force_close(ss, s, &l, &dummy);
}
spinlock_destroy(&s->dw_lock);
}
close(ss->sendctrl_fd);
close(ss->recvctrl_fd);
sp_release(ss->event_fd);
FREE(ss);
}
static inline void
check_wb_list(struct wb_list *s) {
assert(s->head == NULL);
assert(s->tail == NULL);
}
static struct socket *
new_fd(struct socket_server *ss, int id, int fd, int protocol, uintptr_t opaque, bool add) {
struct socket * s = &ss->slot[HASH_ID(id)];
assert(s->type == SOCKET_TYPE_RESERVE);
if (add) {
if (sp_add(ss->event_fd, fd, s)) {
s->type = SOCKET_TYPE_INVALID;
return NULL;
}
}
s->id = id;
s->fd = fd;
s->sending = ID_TAG16(id) << 16 | 0;
s->protocol = protocol;
s->p.size = MIN_READ_BUFFER;
s->opaque = opaque;
s->wb_size = 0;
s->warn_size = 0;
check_wb_list(&s->high);
check_wb_list(&s->low);
s->dw_buffer = NULL;
s->dw_size = 0;
memset(&s->stat, 0, sizeof(s->stat));
return s;
}
static inline void
stat_read(struct socket_server *ss, struct socket *s, int n) {
s->stat.read += n;
s->stat.rtime = ss->time;
}
static inline void
stat_write(struct socket_server *ss, struct socket *s, int n) {
s->stat.write += n;
s->stat.wtime = ss->time;
}
// return -1 when connecting
static int
open_socket(struct socket_server *ss, struct request_open * request, struct socket_message *result) {
int id = request->id;
result->opaque = request->opaque;
result->id = id;
result->ud = 0;
result->data = NULL;
struct socket *ns;
int status;
struct addrinfo ai_hints;
struct addrinfo *ai_list = NULL;
struct addrinfo *ai_ptr = NULL;
char port[16];
sprintf(port, "%d", request->port);
memset(&ai_hints, 0, sizeof( ai_hints ) );
ai_hints.ai_family = AF_UNSPEC;
ai_hints.ai_socktype = SOCK_STREAM;
ai_hints.ai_protocol = IPPROTO_TCP;
status = getaddrinfo( request->host, port, &ai_hints, &ai_list );
if ( status != 0 ) {
result->data = (void *)gai_strerror(status);
goto _failed;
}
int sock= -1;
for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next ) {
sock = socket( ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol );
if ( sock < 0 ) {
continue;
}
socket_keepalive(sock);
sp_nonblocking(sock);
status = connect( sock, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
if ( status != 0 && errno != EINPROGRESS) {
close(sock);
sock = -1;
continue;
}
break;
}
if (sock < 0) {
result->data = strerror(errno);
goto _failed;
}
ns = new_fd(ss, id, sock, PROTOCOL_TCP, request->opaque, true);
if (ns == NULL) {
close(sock);
result->data = "reach skynet socket number limit";
goto _failed;
}
if(status == 0) {
ns->type = SOCKET_TYPE_CONNECTED;
struct sockaddr * addr = ai_ptr->ai_addr;
void * sin_addr = (ai_ptr->ai_family == AF_INET) ? (void*)&((struct sockaddr_in *)addr)->sin_addr : (void*)&((struct sockaddr_in6 *)addr)->sin6_addr;
if (inet_ntop(ai_ptr->ai_family, sin_addr, ss->buffer, sizeof(ss->buffer))) {
result->data = ss->buffer;
}
freeaddrinfo( ai_list );
return SOCKET_OPEN;
} else {
ns->type = SOCKET_TYPE_CONNECTING;
sp_write(ss->event_fd, ns->fd, ns, true);
}
freeaddrinfo( ai_list );
return -1;
_failed:
freeaddrinfo( ai_list );
ss->slot[HASH_ID(id)].type = SOCKET_TYPE_INVALID;
return SOCKET_ERR;
}
static int
send_list_tcp(struct socket_server *ss, struct socket *s, struct wb_list *list, struct socket_lock *l, struct socket_message *result) {
while (list->head) {
struct write_buffer * tmp = list->head;
for (;;) {
ssize_t sz = write(s->fd, tmp->ptr, tmp->sz);
if (sz < 0) {
switch(errno) {
case EINTR:
continue;
case AGAIN_WOULDBLOCK:
return -1;
}
force_close(ss,s,l,result);
return SOCKET_CLOSE;
}
stat_write(ss,s,(int)sz);
s->wb_size -= sz;
if (sz != tmp->sz) {
tmp->ptr += sz;
tmp->sz -= sz;
return -1;
}
break;
}
list->head = tmp->next;
write_buffer_free(ss,tmp);
}
list->tail = NULL;
return -1;
}
static socklen_t
udp_socket_address(struct socket *s, const uint8_t udp_address[UDP_ADDRESS_SIZE], union sockaddr_all *sa) {
int type = (uint8_t)udp_address[0];
if (type != s->protocol)
return 0;
uint16_t port = 0;
memcpy(&port, udp_address+1, sizeof(uint16_t));
switch (s->protocol) {
case PROTOCOL_UDP:
memset(&sa->v4, 0, sizeof(sa->v4));
sa->s.sa_family = AF_INET;
sa->v4.sin_port = port;
memcpy(&sa->v4.sin_addr, udp_address + 1 + sizeof(uint16_t), sizeof(sa->v4.sin_addr)); // ipv4 address is 32 bits
return sizeof(sa->v4);
case PROTOCOL_UDPv6:
memset(&sa->v6, 0, sizeof(sa->v6));
sa->s.sa_family = AF_INET6;
sa->v6.sin6_port = port;
memcpy(&sa->v6.sin6_addr, udp_address + 1 + sizeof(uint16_t), sizeof(sa->v6.sin6_addr)); // ipv6 address is 128 bits
return sizeof(sa->v6);
}
return 0;
}
static void
drop_udp(struct socket_server *ss, struct socket *s, struct wb_list *list, struct write_buffer *tmp) {
s->wb_size -= tmp->sz;
list->head = tmp->next;
if (list->head == NULL)
list->tail = NULL;
write_buffer_free(ss,tmp);
}
static int
send_list_udp(struct socket_server *ss, struct socket *s, struct wb_list *list, struct socket_message *result) {
while (list->head) {
struct write_buffer * tmp = list->head;
union sockaddr_all sa;
socklen_t sasz = udp_socket_address(s, tmp->udp_address, &sa);
if (sasz == 0) {
fprintf(stderr, "socket-server : udp (%d) type mismatch.\n", s->id);
drop_udp(ss, s, list, tmp);
return -1;
}
int err = sendto(s->fd, tmp->ptr, tmp->sz, 0, &sa.s, sasz);
if (err < 0) {
switch(errno) {
case EINTR:
case AGAIN_WOULDBLOCK:
return -1;
}
fprintf(stderr, "socket-server : udp (%d) sendto error %s.\n",s->id, strerror(errno));
drop_udp(ss, s, list, tmp);
return -1;
}
stat_write(ss,s,tmp->sz);
s->wb_size -= tmp->sz;
list->head = tmp->next;
write_buffer_free(ss,tmp);
}
list->tail = NULL;
return -1;
}
static int
send_list(struct socket_server *ss, struct socket *s, struct wb_list *list, struct socket_lock *l, struct socket_message *result) {
if (s->protocol == PROTOCOL_TCP) {
return send_list_tcp(ss, s, list, l, result);
} else {
return send_list_udp(ss, s, list, result);
}
}
static inline int
list_uncomplete(struct wb_list *s) {
struct write_buffer *wb = s->head;
if (wb == NULL)
return 0;
return (void *)wb->ptr != wb->buffer;
}
static void
raise_uncomplete(struct socket * s) {
struct wb_list *low = &s->low;
struct write_buffer *tmp = low->head;
low->head = tmp->next;
if (low->head == NULL) {
low->tail = NULL;
}
// move head of low list (tmp) to the empty high list
struct wb_list *high = &s->high;
assert(high->head == NULL);
tmp->next = NULL;
high->head = high->tail = tmp;
}
static inline int
send_buffer_empty(struct socket *s) {
return (s->high.head == NULL && s->low.head == NULL);
}
/*
Each socket has two write buffer list, high priority and low priority.
1. send high list as far as possible.
2. If high list is empty, try to send low list.
3. If low list head is uncomplete (send a part before), move the head of low list to empty high list (call raise_uncomplete) .
4. If two lists are both empty, turn off the event. (call check_close)
*/
static int
send_buffer_(struct socket_server *ss, struct socket *s, struct socket_lock *l, struct socket_message *result) {
assert(!list_uncomplete(&s->low));
// step 1
if (send_list(ss,s,&s->high,l,result) == SOCKET_CLOSE) {
return SOCKET_CLOSE;
}
if (s->high.head == NULL) {
// step 2
if (s->low.head != NULL) {
if (send_list(ss,s,&s->low,l,result) == SOCKET_CLOSE) {
return SOCKET_CLOSE;
}
// step 3
if (list_uncomplete(&s->low)) {
raise_uncomplete(s);
return -1;
}
if (s->low.head)
return -1;
}
// step 4
assert(send_buffer_empty(s) && s->wb_size == 0);
sp_write(ss->event_fd, s->fd, s, false);
if (s->type == SOCKET_TYPE_HALFCLOSE) {
force_close(ss, s, l, result);
return SOCKET_CLOSE;
}
if(s->warn_size > 0){
s->warn_size = 0;
result->opaque = s->opaque;
result->id = s->id;
result->ud = 0;
result->data = NULL;
return SOCKET_WARNING;
}
}
return -1;
}
static int
send_buffer(struct socket_server *ss, struct socket *s, struct socket_lock *l, struct socket_message *result) {
if (!socket_trylock(l))
return -1; // blocked by direct write, send later.
if (s->dw_buffer) {
// add direct write buffer before high.head
struct write_buffer * buf = MALLOC(SIZEOF_TCPBUFFER);
struct send_object so;
buf->userobject = send_object_init(ss, &so, (void *)s->dw_buffer, s->dw_size);
buf->ptr = (char*)so.buffer+s->dw_offset;
buf->sz = so.sz - s->dw_offset;
buf->buffer = (void *)s->dw_buffer;
s->wb_size+=buf->sz;
if (s->high.head == NULL) {
s->high.head = s->high.tail = buf;
buf->next = NULL;
} else {
buf->next = s->high.head;
s->high.head = buf;
}
s->dw_buffer = NULL;
}
int r = send_buffer_(ss,s,l,result);
socket_unlock(l);
return r;
}
static struct write_buffer *
append_sendbuffer_(struct socket_server *ss, struct wb_list *s, struct request_send * request, int size) {
struct write_buffer * buf = MALLOC(size);
struct send_object so;
buf->userobject = send_object_init(ss, &so, request->buffer, request->sz);
buf->ptr = (char*)so.buffer;
buf->sz = so.sz;
buf->buffer = request->buffer;
buf->next = NULL;
if (s->head == NULL) {
s->head = s->tail = buf;
} else {
assert(s->tail != NULL);
assert(s->tail->next == NULL);
s->tail->next = buf;
s->tail = buf;
}
return buf;
}
static inline void
append_sendbuffer_udp(struct socket_server *ss, struct socket *s, int priority, struct request_send * request, const uint8_t udp_address[UDP_ADDRESS_SIZE]) {
struct wb_list *wl = (priority == PRIORITY_HIGH) ? &s->high : &s->low;
struct write_buffer *buf = append_sendbuffer_(ss, wl, request, SIZEOF_UDPBUFFER);
memcpy(buf->udp_address, udp_address, UDP_ADDRESS_SIZE);
s->wb_size += buf->sz;
}
static inline void
append_sendbuffer(struct socket_server *ss, struct socket *s, struct request_send * request) {
struct write_buffer *buf = append_sendbuffer_(ss, &s->high, request, SIZEOF_TCPBUFFER);
s->wb_size += buf->sz;
}
static inline void
append_sendbuffer_low(struct socket_server *ss,struct socket *s, struct request_send * request) {
struct write_buffer *buf = append_sendbuffer_(ss, &s->low, request, SIZEOF_TCPBUFFER);
s->wb_size += buf->sz;
}
/*
When send a package , we can assign the priority : PRIORITY_HIGH or PRIORITY_LOW
If socket buffer is empty, write to fd directly.
If write a part, append the rest part to high list. (Even priority is PRIORITY_LOW)
Else append package to high (PRIORITY_HIGH) or low (PRIORITY_LOW) list.
*/
static int
send_socket(struct socket_server *ss, struct request_send * request, struct socket_message *result, int priority, const uint8_t *udp_address) {
int id = request->id;
struct socket * s = &ss->slot[HASH_ID(id)];
struct send_object so;
send_object_init(ss, &so, request->buffer, request->sz);
if (s->type == SOCKET_TYPE_INVALID || s->id != id
|| s->type == SOCKET_TYPE_HALFCLOSE
|| s->type == SOCKET_TYPE_PACCEPT) {
so.free_func(request->buffer);
return -1;
}
if (s->type == SOCKET_TYPE_PLISTEN || s->type == SOCKET_TYPE_LISTEN) {
fprintf(stderr, "socket-server: write to listen fd %d.\n", id);
so.free_func(request->buffer);
return -1;
}
if (send_buffer_empty(s) && s->type == SOCKET_TYPE_CONNECTED) {
if (s->protocol == PROTOCOL_TCP) {
append_sendbuffer(ss, s, request); // add to high priority list, even priority == PRIORITY_LOW
} else {
// udp
if (udp_address == NULL) {
udp_address = s->p.udp_address;
}
union sockaddr_all sa;
socklen_t sasz = udp_socket_address(s, udp_address, &sa);
if (sasz == 0) {
// udp type mismatch, just drop it.
fprintf(stderr, "socket-server: udp socket (%d) type mistach.\n", id);
so.free_func(request->buffer);
return -1;
}
int n = sendto(s->fd, so.buffer, so.sz, 0, &sa.s, sasz);
if (n != so.sz) {
append_sendbuffer_udp(ss,s,priority,request,udp_address);
} else {
stat_write(ss,s,n);
so.free_func(request->buffer);
return -1;
}
}
sp_write(ss->event_fd, s->fd, s, true);
} else {
if (s->protocol == PROTOCOL_TCP) {
if (priority == PRIORITY_LOW) {
append_sendbuffer_low(ss, s, request);
} else {
append_sendbuffer(ss, s, request);
}
} else {
if (udp_address == NULL) {
udp_address = s->p.udp_address;
}
append_sendbuffer_udp(ss,s,priority,request,udp_address);
}
}
if (s->wb_size >= WARNING_SIZE && s->wb_size >= s->warn_size) {
s->warn_size = s->warn_size == 0 ? WARNING_SIZE *2 : s->warn_size*2;
result->opaque = s->opaque;
result->id = s->id;
result->ud = s->wb_size%1024 == 0 ? s->wb_size/1024 : s->wb_size/1024 + 1;
result->data = NULL;
return SOCKET_WARNING;
}
return -1;
}
static int
listen_socket(struct socket_server *ss, struct request_listen * request, struct socket_message *result) {
int id = request->id;
int listen_fd = request->fd;
struct socket *s = new_fd(ss, id, listen_fd, PROTOCOL_TCP, request->opaque, false);
if (s == NULL) {
goto _failed;
}
s->type = SOCKET_TYPE_PLISTEN;
return -1;
_failed:
close(listen_fd);
result->opaque = request->opaque;
result->id = id;
result->ud = 0;
result->data = "reach skynet socket number limit";
ss->slot[HASH_ID(id)].type = SOCKET_TYPE_INVALID;
return SOCKET_ERR;
}
static inline int
nomore_sending_data(struct socket *s) {
return send_buffer_empty(s) && s->dw_buffer == NULL && (s->sending & 0xffff) == 0;
}
static int
close_socket(struct socket_server *ss, struct request_close *request, struct socket_message *result) {
int id = request->id;
struct socket * s = &ss->slot[HASH_ID(id)];
if (s->type == SOCKET_TYPE_INVALID || s->id != id) {
result->id = id;
result->opaque = request->opaque;
result->ud = 0;
result->data = NULL;
return SOCKET_CLOSE;
}
struct socket_lock l;
socket_lock_init(s, &l);
if (!nomore_sending_data(s)) {
int type = send_buffer(ss,s,&l,result);
// type : -1 or SOCKET_WARNING or SOCKET_CLOSE, SOCKET_WARNING means nomore_sending_data
if (type != -1 && type != SOCKET_WARNING)
return type;
}
if (request->shutdown || nomore_sending_data(s)) {
force_close(ss,s,&l,result);
result->id = id;
result->opaque = request->opaque;
return SOCKET_CLOSE;
}
s->type = SOCKET_TYPE_HALFCLOSE;
return -1;
}
static int
bind_socket(struct socket_server *ss, struct request_bind *request, struct socket_message *result) {
int id = request->id;
result->id = id;
result->opaque = request->opaque;
result->ud = 0;
struct socket *s = new_fd(ss, id, request->fd, PROTOCOL_TCP, request->opaque, true);
if (s == NULL) {
result->data = "reach skynet socket number limit";
return SOCKET_ERR;
}
sp_nonblocking(request->fd);
s->type = SOCKET_TYPE_BIND;
result->data = "binding";
return SOCKET_OPEN;
}
static int
start_socket(struct socket_server *ss, struct request_start *request, struct socket_message *result) {
int id = request->id;
result->id = id;
result->opaque = request->opaque;
result->ud = 0;
result->data = NULL;
struct socket *s = &ss->slot[HASH_ID(id)];
if (s->type == SOCKET_TYPE_INVALID || s->id !=id) {
result->data = "invalid socket";
return SOCKET_ERR;
}
struct socket_lock l;
socket_lock_init(s, &l);
if (s->type == SOCKET_TYPE_PACCEPT || s->type == SOCKET_TYPE_PLISTEN) {
if (sp_add(ss->event_fd, s->fd, s)) {
force_close(ss, s, &l, result);
result->data = strerror(errno);
return SOCKET_ERR;
}
s->type = (s->type == SOCKET_TYPE_PACCEPT) ? SOCKET_TYPE_CONNECTED : SOCKET_TYPE_LISTEN;
s->opaque = request->opaque;
result->data = "start";
return SOCKET_OPEN;
} else if (s->type == SOCKET_TYPE_CONNECTED) {
// todo: maybe we should send a message SOCKET_TRANSFER to s->opaque
s->opaque = request->opaque;
result->data = "transfer";
return SOCKET_OPEN;
}
// if s->type == SOCKET_TYPE_HALFCLOSE , SOCKET_CLOSE message will send later
return -1;
}
static void
setopt_socket(struct socket_server *ss, struct request_setopt *request) {
int id = request->id;
struct socket *s = &ss->slot[HASH_ID(id)];
if (s->type == SOCKET_TYPE_INVALID || s->id !=id) {
return;
}
int v = request->value;
setsockopt(s->fd, IPPROTO_TCP, request->what, &v, sizeof(v));
}
static void
block_readpipe(int pipefd, void *buffer, int sz) {
for (;;) {
int n = read(pipefd, buffer, sz);
if (n<0) {
if (errno == EINTR)
continue;
fprintf(stderr, "socket-server : read pipe error %s.\n",strerror(errno));
return;
}
// must atomic read from a pipe
assert(n == sz);
return;
}
}
static int
has_cmd(struct socket_server *ss) {
struct timeval tv = {0,0};
int retval;
FD_SET(ss->recvctrl_fd, &ss->rfds);
retval = select(ss->recvctrl_fd+1, &ss->rfds, NULL, NULL, &tv);
if (retval == 1) {
return 1;
}
return 0;
}
static void
add_udp_socket(struct socket_server *ss, struct request_udp *udp) {
int id = udp->id;
int protocol;
if (udp->family == AF_INET6) {
protocol = PROTOCOL_UDPv6;
} else {
protocol = PROTOCOL_UDP;
}
struct socket *ns = new_fd(ss, id, udp->fd, protocol, udp->opaque, true);
if (ns == NULL) {
close(udp->fd);
ss->slot[HASH_ID(id)].type = SOCKET_TYPE_INVALID;
return;
}
ns->type = SOCKET_TYPE_CONNECTED;
memset(ns->p.udp_address, 0, sizeof(ns->p.udp_address));
}
static int
set_udp_address(struct socket_server *ss, struct request_setudp *request, struct socket_message *result) {
int id = request->id;
struct socket *s = &ss->slot[HASH_ID(id)];
if (s->type == SOCKET_TYPE_INVALID || s->id !=id) {
return -1;
}
int type = request->address[0];
if (type != s->protocol) {
// protocol mismatch
result->opaque = s->opaque;
result->id = s->id;
result->ud = 0;
result->data = "protocol mismatch";
return SOCKET_ERR;
}
if (type == PROTOCOL_UDP) {
memcpy(s->p.udp_address, request->address, 1+2+4); // 1 type, 2 port, 4 ipv4
} else {
memcpy(s->p.udp_address, request->address, 1+2+16); // 1 type, 2 port, 16 ipv6
}
ATOM_DEC(&s->udpconnecting);
return -1;
}
static inline void
inc_sending_ref(struct socket *s, int id) {
if (s->protocol != PROTOCOL_TCP)
return;
for (;;) {
uint32_t sending = s->sending;
if ((sending >> 16) == ID_TAG16(id)) {
if ((sending & 0xffff) == 0xffff) {
// s->sending may overflow (rarely), so busy waiting here for socket thread dec it. see issue #794
continue;
}
// inc sending only matching the same socket id
if (ATOM_CAS(&s->sending, sending, sending + 1))
return;
// atom inc failed, retry
} else {
// socket id changed, just return
return;
}
}
}
static inline void
dec_sending_ref(struct socket_server *ss, int id) {
struct socket * s = &ss->slot[HASH_ID(id)];
// Notice: udp may inc sending while type == SOCKET_TYPE_RESERVE
if (s->id == id && s->protocol == PROTOCOL_TCP) {
assert((s->sending & 0xffff) != 0);
ATOM_DEC(&s->sending);
}
}
// return type
static int
ctrl_cmd(struct socket_server *ss, struct socket_message *result) {
int fd = ss->recvctrl_fd;
// the length of message is one byte, so 256+8 buffer size is enough.
uint8_t buffer[256];
uint8_t header[2];
block_readpipe(fd, header, sizeof(header));
int type = header[0];
int len = header[1];
block_readpipe(fd, buffer, len);
// ctrl command only exist in local fd, so don't worry about endian.
switch (type) {
case 'S':
return start_socket(ss,(struct request_start *)buffer, result);
case 'B':
return bind_socket(ss,(struct request_bind *)buffer, result);
case 'L':
return listen_socket(ss,(struct request_listen *)buffer, result);
case 'K':
return close_socket(ss,(struct request_close *)buffer, result);
case 'O':
return open_socket(ss, (struct request_open *)buffer, result);
case 'X':
result->opaque = 0;
result->id = 0;
result->ud = 0;
result->data = NULL;
return SOCKET_EXIT;
case 'D':
case 'P': {
int priority = (type == 'D') ? PRIORITY_HIGH : PRIORITY_LOW;
struct request_send * request = (struct request_send *) buffer;
int ret = send_socket(ss, request, result, priority, NULL);
dec_sending_ref(ss, request->id);
return ret;
}
case 'A': {
struct request_send_udp * rsu = (struct request_send_udp *)buffer;
return send_socket(ss, &rsu->send, result, PRIORITY_HIGH, rsu->address);
}
case 'C':
return set_udp_address(ss, (struct request_setudp *)buffer, result);
case 'T':
setopt_socket(ss, (struct request_setopt *)buffer);
return -1;
case 'U':
add_udp_socket(ss, (struct request_udp *)buffer);
return -1;
default:
fprintf(stderr, "socket-server: Unknown ctrl %c.\n",type);
return -1;
};
return -1;
}
// return -1 (ignore) when error
static int
forward_message_tcp(struct socket_server *ss, struct socket *s, struct socket_lock *l, struct socket_message * result) {
int sz = s->p.size;
char * buffer = MALLOC(sz);
int n = (int)read(s->fd, buffer, sz);
if (n<0) {
FREE(buffer);
switch(errno) {
case EINTR:
break;
case AGAIN_WOULDBLOCK:
fprintf(stderr, "socket-server: EAGAIN capture.\n");
break;
default:
// close when error
force_close(ss, s, l, result);
result->data = strerror(errno);
return SOCKET_ERR;
}
return -1;
}
if (n==0) {
FREE(buffer);
force_close(ss, s, l, result);
return SOCKET_CLOSE;
}
if (s->type == SOCKET_TYPE_HALFCLOSE) {
// discard recv data
FREE(buffer);
return -1;
}
stat_read(ss,s,n);
if (n == sz) {
s->p.size *= 2;
} else if (sz > MIN_READ_BUFFER && n*2 < sz) {
s->p.size /= 2;
}
result->opaque = s->opaque;
result->id = s->id;
result->ud = n;
result->data = buffer;
return SOCKET_DATA;
}
static int
gen_udp_address(int protocol, union sockaddr_all *sa, uint8_t * udp_address) {
int addrsz = 1;
udp_address[0] = (uint8_t)protocol;
if (protocol == PROTOCOL_UDP) {
memcpy(udp_address+addrsz, &sa->v4.sin_port, sizeof(sa->v4.sin_port));
addrsz += sizeof(sa->v4.sin_port);
memcpy(udp_address+addrsz, &sa->v4.sin_addr, sizeof(sa->v4.sin_addr));
addrsz += sizeof(sa->v4.sin_addr);
} else {
memcpy(udp_address+addrsz, &sa->v6.sin6_port, sizeof(sa->v6.sin6_port));
addrsz += sizeof(sa->v6.sin6_port);
memcpy(udp_address+addrsz, &sa->v6.sin6_addr, sizeof(sa->v6.sin6_addr));
addrsz += sizeof(sa->v6.sin6_addr);
}
return addrsz;
}
static int
forward_message_udp(struct socket_server *ss, struct socket *s, struct socket_lock *l, struct socket_message * result) {
union sockaddr_all sa;
socklen_t slen = sizeof(sa);
int n = recvfrom(s->fd, ss->udpbuffer,MAX_UDP_PACKAGE,0,&sa.s,&slen);
if (n<0) {
switch(errno) {
case EINTR:
case AGAIN_WOULDBLOCK:
break;
default:
// close when error
force_close(ss, s, l, result);
result->data = strerror(errno);
return SOCKET_ERR;
}
return -1;
}
stat_read(ss,s,n);
uint8_t * data;
if (slen == sizeof(sa.v4)) {
if (s->protocol != PROTOCOL_UDP)
return -1;
data = MALLOC(n + 1 + 2 + 4);
gen_udp_address(PROTOCOL_UDP, &sa, data + n);
} else {
if (s->protocol != PROTOCOL_UDPv6)
return -1;
data = MALLOC(n + 1 + 2 + 16);
gen_udp_address(PROTOCOL_UDPv6, &sa, data + n);
}
memcpy(data, ss->udpbuffer, n);
result->opaque = s->opaque;
result->id = s->id;
result->ud = n;
result->data = (char *)data;
return SOCKET_UDP;
}
static int
report_connect(struct socket_server *ss, struct socket *s, struct socket_lock *l, struct socket_message *result) {
int error;
socklen_t len = sizeof(error);
int code = getsockopt(s->fd, SOL_SOCKET, SO_ERROR, &error, &len);
if (code < 0 || error) {
force_close(ss,s,l, result);
if (code >= 0)
result->data = strerror(error);
else
result->data = strerror(errno);
return SOCKET_ERR;
} else {
s->type = SOCKET_TYPE_CONNECTED;
result->opaque = s->opaque;
result->id = s->id;
result->ud = 0;
if (nomore_sending_data(s)) {
sp_write(ss->event_fd, s->fd, s, false);
}
union sockaddr_all u;
socklen_t slen = sizeof(u);
if (getpeername(s->fd, &u.s, &slen) == 0) {
void * sin_addr = (u.s.sa_family == AF_INET) ? (void*)&u.v4.sin_addr : (void *)&u.v6.sin6_addr;
if (inet_ntop(u.s.sa_family, sin_addr, ss->buffer, sizeof(ss->buffer))) {
result->data = ss->buffer;
return SOCKET_OPEN;
}
}
result->data = NULL;
return SOCKET_OPEN;
}
}
static int
getname(union sockaddr_all *u, char *buffer, size_t sz) {
char tmp[INET6_ADDRSTRLEN];
void * sin_addr = (u->s.sa_family == AF_INET) ? (void*)&u->v4.sin_addr : (void *)&u->v6.sin6_addr;
int sin_port = ntohs((u->s.sa_family == AF_INET) ? u->v4.sin_port : u->v6.sin6_port);
if (inet_ntop(u->s.sa_family, sin_addr, tmp, sizeof(tmp))) {
snprintf(buffer, sz, "%s:%d", tmp, sin_port);
return 1;
} else {
buffer[0] = '\0';
return 0;
}
}
// return 0 when failed, or -1 when file limit
static int
report_accept(struct socket_server *ss, struct socket *s, struct socket_message *result) {
union sockaddr_all u;
socklen_t len = sizeof(u);
int client_fd = accept(s->fd, &u.s, &len);
if (client_fd < 0) {
if (errno == EMFILE || errno == ENFILE) {
result->opaque = s->opaque;
result->id = s->id;
result->ud = 0;
result->data = strerror(errno);
return -1;
} else {
return 0;
}
}
int id = reserve_id(ss);
if (id < 0) {
close(client_fd);
return 0;
}
socket_keepalive(client_fd);
sp_nonblocking(client_fd);
struct socket *ns = new_fd(ss, id, client_fd, PROTOCOL_TCP, s->opaque, false);
if (ns == NULL) {
close(client_fd);
return 0;
}
// accept new one connection
stat_read(ss,s,1);
ns->type = SOCKET_TYPE_PACCEPT;
result->opaque = s->opaque;
result->id = s->id;
result->ud = id;
result->data = NULL;
if (getname(&u, ss->buffer, sizeof(ss->buffer))) {
result->data = ss->buffer;
}
return 1;
}
static inline void
clear_closed_event(struct socket_server *ss, struct socket_message * result, int type) {
if (type == SOCKET_CLOSE || type == SOCKET_ERR) {
int id = result->id;
int i;
for (i=ss->event_index; i<ss->event_n; i++) {
struct event *e = &ss->ev[i];
struct socket *s = e->s;
if (s) {
if (s->type == SOCKET_TYPE_INVALID && s->id == id) {
e->s = NULL;
break;
}
}
}
}
}
// return type
int
socket_server_poll(struct socket_server *ss, struct socket_message * result, int * more) {
for (;;) {
if (ss->checkctrl) {
if (has_cmd(ss)) {
int type = ctrl_cmd(ss, result);
if (type != -1) {
clear_closed_event(ss, result, type);
return type;
} else
continue;
} else {
ss->checkctrl = 0;
}
}
if (ss->event_index == ss->event_n) {
ss->event_n = sp_wait(ss->event_fd, ss->ev, MAX_EVENT);
ss->checkctrl = 1;
if (more) {
*more = 0;
}
ss->event_index = 0;
if (ss->event_n <= 0) {
ss->event_n = 0;
if (errno == EINTR) {
continue;
}
return -1;
}
}
struct event *e = &ss->ev[ss->event_index++];
struct socket *s = e->s;
if (s == NULL) {
// dispatch pipe message at beginning
continue;
}
struct socket_lock l;
socket_lock_init(s, &l);
switch (s->type) {
case SOCKET_TYPE_CONNECTING:
return report_connect(ss, s, &l, result);
case SOCKET_TYPE_LISTEN: {
int ok = report_accept(ss, s, result);
if (ok > 0) {
return SOCKET_ACCEPT;
} if (ok < 0 ) {
return SOCKET_ERR;
}
// when ok == 0, retry
break;
}
case SOCKET_TYPE_INVALID:
fprintf(stderr, "socket-server: invalid socket\n");
break;
default:
if (e->read) {
int type;
if (s->protocol == PROTOCOL_TCP) {
type = forward_message_tcp(ss, s, &l, result);
} else {
type = forward_message_udp(ss, s, &l, result);
if (type == SOCKET_UDP) {
// try read again
--ss->event_index;
return SOCKET_UDP;
}
}
if (e->write && type != SOCKET_CLOSE && type != SOCKET_ERR) {
// Try to dispatch write message next step if write flag set.
e->read = false;
--ss->event_index;
}
if (type == -1)
break;
return type;
}
if (e->write) {
int type = send_buffer(ss, s, &l, result);
if (type == -1)
break;
return type;
}
if (e->error) {
// close when error
int error;
socklen_t len = sizeof(error);
int code = getsockopt(s->fd, SOL_SOCKET, SO_ERROR, &error, &len);
const char * err = NULL;
if (code < 0) {
err = strerror(errno);
} else if (error != 0) {
err = strerror(error);
} else {
err = "Unknown error";
}
force_close(ss, s, &l, result);
result->data = (char *)err;
return SOCKET_ERR;
}
if(e->eof) {
force_close(ss, s, &l, result);
return SOCKET_CLOSE;
}
break;
}
}
}
static void
send_request(struct socket_server *ss, struct request_package *request, char type, int len) {
request->header[6] = (uint8_t)type;
request->header[7] = (uint8_t)len;
for (;;) {
ssize_t n = write(ss->sendctrl_fd, &request->header[6], len+2);
if (n<0) {
if (errno != EINTR) {
fprintf(stderr, "socket-server : send ctrl command error %s.\n", strerror(errno));
}
continue;
}
assert(n == len+2);
return;
}
}
static int
open_request(struct socket_server *ss, struct request_package *req, uintptr_t opaque, const char *addr, int port) {
int len = strlen(addr);
if (len + sizeof(req->u.open) >= 256) {
fprintf(stderr, "socket-server : Invalid addr %s.\n",addr);
return -1;
}
int id = reserve_id(ss);
if (id < 0)
return -1;
req->u.open.opaque = opaque;
req->u.open.id = id;
req->u.open.port = port;
memcpy(req->u.open.host, addr, len);
req->u.open.host[len] = '\0';
return len;
}
int
socket_server_connect(struct socket_server *ss, uintptr_t opaque, const char * addr, int port) {
struct request_package request;
int len = open_request(ss, &request, opaque, addr, port);
if (len < 0)
return -1;
send_request(ss, &request, 'O', sizeof(request.u.open) + len);
return request.u.open.id;
}
static inline int
can_direct_write(struct socket *s, int id) {
return s->id == id && nomore_sending_data(s) && s->type == SOCKET_TYPE_CONNECTED && s->udpconnecting == 0;
}
// return -1 when error, 0 when success
int
socket_server_send(struct socket_server *ss, int id, const void * buffer, int sz) {
struct socket * s = &ss->slot[HASH_ID(id)];
if (s->id != id || s->type == SOCKET_TYPE_INVALID) {
free_buffer(ss, buffer, sz);
return -1;
}
struct socket_lock l;
socket_lock_init(s, &l);
if (can_direct_write(s,id) && socket_trylock(&l)) {
// may be we can send directly, double check
if (can_direct_write(s,id)) {
// send directly
struct send_object so;
send_object_init(ss, &so, (void *)buffer, sz);
ssize_t n;
if (s->protocol == PROTOCOL_TCP) {
n = write(s->fd, so.buffer, so.sz);
} else {
union sockaddr_all sa;
socklen_t sasz = udp_socket_address(s, s->p.udp_address, &sa);
if (sasz == 0) {
fprintf(stderr, "socket-server : set udp (%d) address first.\n", id);
socket_unlock(&l);
so.free_func((void *)buffer);
return -1;
}
n = sendto(s->fd, so.buffer, so.sz, 0, &sa.s, sasz);
}
if (n<0) {
// ignore error, let socket thread try again
n = 0;
}
stat_write(ss,s,n);
if (n == so.sz) {
// write done
socket_unlock(&l);
so.free_func((void *)buffer);
return 0;
}
// write failed, put buffer into s->dw_* , and let socket thread send it. see send_buffer()
s->dw_buffer = buffer;
s->dw_size = sz;
s->dw_offset = n;
sp_write(ss->event_fd, s->fd, s, true);
socket_unlock(&l);
return 0;
}
socket_unlock(&l);
}
inc_sending_ref(s, id);
struct request_package request;
request.u.send.id = id;
request.u.send.sz = sz;
request.u.send.buffer = (char *)buffer;
send_request(ss, &request, 'D', sizeof(request.u.send));
return 0;
}
// return -1 when error, 0 when success
int
socket_server_send_lowpriority(struct socket_server *ss, int id, const void * buffer, int sz) {
struct socket * s = &ss->slot[HASH_ID(id)];
if (s->id != id || s->type == SOCKET_TYPE_INVALID) {
free_buffer(ss, buffer, sz);
return -1;
}
inc_sending_ref(s, id);
struct request_package request;
request.u.send.id = id;
request.u.send.sz = sz;
request.u.send.buffer = (char *)buffer;
send_request(ss, &request, 'P', sizeof(request.u.send));
return 0;
}
void
socket_server_exit(struct socket_server *ss) {
struct request_package request;
send_request(ss, &request, 'X', 0);
}
void
socket_server_close(struct socket_server *ss, uintptr_t opaque, int id) {
struct request_package request;
request.u.close.id = id;
request.u.close.shutdown = 0;
request.u.close.opaque = opaque;
send_request(ss, &request, 'K', sizeof(request.u.close));
}
void
socket_server_shutdown(struct socket_server *ss, uintptr_t opaque, int id) {
struct request_package request;
request.u.close.id = id;
request.u.close.shutdown = 1;
request.u.close.opaque = opaque;
send_request(ss, &request, 'K', sizeof(request.u.close));
}
// return -1 means failed
// or return AF_INET or AF_INET6
static int
do_bind(const char *host, int port, int protocol, int *family) {
int fd;
int status;
int reuse = 1;
struct addrinfo ai_hints;
struct addrinfo *ai_list = NULL;
char portstr[16];
if (host == NULL || host[0] == 0) {
host = "0.0.0.0"; // INADDR_ANY
}
sprintf(portstr, "%d", port);
memset( &ai_hints, 0, sizeof( ai_hints ) );
ai_hints.ai_family = AF_UNSPEC;
if (protocol == IPPROTO_TCP) {
ai_hints.ai_socktype = SOCK_STREAM;
} else {
assert(protocol == IPPROTO_UDP);
ai_hints.ai_socktype = SOCK_DGRAM;
}
ai_hints.ai_protocol = protocol;
status = getaddrinfo( host, portstr, &ai_hints, &ai_list );
if ( status != 0 ) {
return -1;
}
*family = ai_list->ai_family;
fd = socket(*family, ai_list->ai_socktype, 0);
if (fd < 0) {
goto _failed_fd;
}
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void *)&reuse, sizeof(int))==-1) {
goto _failed;
}
status = bind(fd, (struct sockaddr *)ai_list->ai_addr, ai_list->ai_addrlen);
if (status != 0)
goto _failed;
freeaddrinfo( ai_list );
return fd;
_failed:
close(fd);
_failed_fd:
freeaddrinfo( ai_list );
return -1;
}
static int
do_listen(const char * host, int port, int backlog) {
int family = 0;
int listen_fd = do_bind(host, port, IPPROTO_TCP, &family);
if (listen_fd < 0) {
return -1;
}
if (listen(listen_fd, backlog) == -1) {
close(listen_fd);
return -1;
}
return listen_fd;
}
int
socket_server_listen(struct socket_server *ss, uintptr_t opaque, const char * addr, int port, int backlog) {
int fd = do_listen(addr, port, backlog);
if (fd < 0) {
return -1;
}
struct request_package request;
int id = reserve_id(ss);
if (id < 0) {
close(fd);
return id;
}
request.u.listen.opaque = opaque;
request.u.listen.id = id;
request.u.listen.fd = fd;
send_request(ss, &request, 'L', sizeof(request.u.listen));
return id;
}
int
socket_server_bind(struct socket_server *ss, uintptr_t opaque, int fd) {
struct request_package request;
int id = reserve_id(ss);
if (id < 0)
return -1;
request.u.bind.opaque = opaque;
request.u.bind.id = id;
request.u.bind.fd = fd;
send_request(ss, &request, 'B', sizeof(request.u.bind));
return id;
}
void
socket_server_start(struct socket_server *ss, uintptr_t opaque, int id) {
struct request_package request;
request.u.start.id = id;
request.u.start.opaque = opaque;
send_request(ss, &request, 'S', sizeof(request.u.start));
}
void
socket_server_nodelay(struct socket_server *ss, int id) {
struct request_package request;
request.u.setopt.id = id;
request.u.setopt.what = TCP_NODELAY;
request.u.setopt.value = 1;
send_request(ss, &request, 'T', sizeof(request.u.setopt));
}
void
socket_server_userobject(struct socket_server *ss, struct socket_object_interface *soi) {
ss->soi = *soi;
}
// UDP
int
socket_server_udp(struct socket_server *ss, uintptr_t opaque, const char * addr, int port) {
int fd;
int family;
if (port != 0 || addr != NULL) {
// bind
fd = do_bind(addr, port, IPPROTO_UDP, &family);
if (fd < 0) {
return -1;
}
} else {
family = AF_INET;
fd = socket(family, SOCK_DGRAM, 0);
if (fd < 0) {
return -1;
}
}
sp_nonblocking(fd);
int id = reserve_id(ss);
if (id < 0) {
close(fd);
return -1;
}
struct request_package request;
request.u.udp.id = id;
request.u.udp.fd = fd;
request.u.udp.opaque = opaque;
request.u.udp.family = family;
send_request(ss, &request, 'U', sizeof(request.u.udp));
return id;
}
int
socket_server_udp_send(struct socket_server *ss, int id, const struct socket_udp_address *addr, const void *buffer, int sz) {
struct socket * s = &ss->slot[HASH_ID(id)];
if (s->id != id || s->type == SOCKET_TYPE_INVALID) {
free_buffer(ss, buffer, sz);
return -1;
}
const uint8_t *udp_address = (const uint8_t *)addr;
int addrsz;
switch (udp_address[0]) {
case PROTOCOL_UDP:
addrsz = 1+2+4; // 1 type, 2 port, 4 ipv4
break;
case PROTOCOL_UDPv6:
addrsz = 1+2+16; // 1 type, 2 port, 16 ipv6
break;
default:
free_buffer(ss, buffer, sz);
return -1;
}
struct socket_lock l;
socket_lock_init(s, &l);
if (can_direct_write(s,id) && socket_trylock(&l)) {
// may be we can send directly, double check
if (can_direct_write(s,id)) {
// send directly
struct send_object so;
send_object_init(ss, &so, (void *)buffer, sz);
union sockaddr_all sa;
socklen_t sasz = udp_socket_address(s, udp_address, &sa);
if (sasz == 0) {
socket_unlock(&l);
so.free_func((void *)buffer);
return -1;
}
int n = sendto(s->fd, so.buffer, so.sz, 0, &sa.s, sasz);
if (n >= 0) {
// sendto succ
stat_write(ss,s,n);
socket_unlock(&l);
so.free_func((void *)buffer);
return 0;
}
}
socket_unlock(&l);
// let socket thread try again, udp doesn't care the order
}
struct request_package request;
request.u.send_udp.send.id = id;
request.u.send_udp.send.sz = sz;
request.u.send_udp.send.buffer = (char *)buffer;
memcpy(request.u.send_udp.address, udp_address, addrsz);
send_request(ss, &request, 'A', sizeof(request.u.send_udp.send)+addrsz);
return 0;
}
int
socket_server_udp_connect(struct socket_server *ss, int id, const char * addr, int port) {
struct socket * s = &ss->slot[HASH_ID(id)];
if (s->id != id || s->type == SOCKET_TYPE_INVALID) {
return -1;
}
struct socket_lock l;
socket_lock_init(s, &l);
socket_lock(&l);
if (s->id != id || s->type == SOCKET_TYPE_INVALID) {
socket_unlock(&l);
return -1;
}
ATOM_INC(&s->udpconnecting);
socket_unlock(&l);
int status;
struct addrinfo ai_hints;
struct addrinfo *ai_list = NULL;
char portstr[16];
sprintf(portstr, "%d", port);
memset( &ai_hints, 0, sizeof( ai_hints ) );
ai_hints.ai_family = AF_UNSPEC;
ai_hints.ai_socktype = SOCK_DGRAM;
ai_hints.ai_protocol = IPPROTO_UDP;
status = getaddrinfo(addr, portstr, &ai_hints, &ai_list );
if ( status != 0 ) {
return -1;
}
struct request_package request;
request.u.set_udp.id = id;
int protocol;
if (ai_list->ai_family == AF_INET) {
protocol = PROTOCOL_UDP;
} else if (ai_list->ai_family == AF_INET6) {
protocol = PROTOCOL_UDPv6;
} else {
freeaddrinfo( ai_list );
return -1;
}
int addrsz = gen_udp_address(protocol, (union sockaddr_all *)ai_list->ai_addr, request.u.set_udp.address);
freeaddrinfo( ai_list );
send_request(ss, &request, 'C', sizeof(request.u.set_udp) - sizeof(request.u.set_udp.address) +addrsz);
return 0;
}
const struct socket_udp_address *
socket_server_udp_address(struct socket_server *ss, struct socket_message *msg, int *addrsz) {
uint8_t * address = (uint8_t *)(msg->data + msg->ud);
int type = address[0];
switch(type) {
case PROTOCOL_UDP:
*addrsz = 1+2+4;
break;
case PROTOCOL_UDPv6:
*addrsz = 1+2+16;
break;
default:
return NULL;
}
return (const struct socket_udp_address *)address;
}
struct socket_info *
socket_info_create(struct socket_info *last) {
struct socket_info *si = skynet_malloc(sizeof(*si));
memset(si, 0 , sizeof(*si));
si->next = last;
return si;
}
void
socket_info_release(struct socket_info *si) {
while (si) {
struct socket_info *temp = si;
si = si->next;
skynet_free(temp);
}
}
static int
query_info(struct socket *s, struct socket_info *si) {
union sockaddr_all u;
socklen_t slen = sizeof(u);
switch (s->type) {
case SOCKET_TYPE_BIND:
si->type = SOCKET_INFO_BIND;
si->name[0] = '\0';
break;
case SOCKET_TYPE_LISTEN:
si->type = SOCKET_INFO_LISTEN;
if (getsockname(s->fd, &u.s, &slen) == 0) {
getname(&u, si->name, sizeof(si->name));
}
break;
case SOCKET_TYPE_CONNECTED:
if (s->protocol == PROTOCOL_TCP) {
si->type = SOCKET_INFO_TCP;
if (getpeername(s->fd, &u.s, &slen) == 0) {
getname(&u, si->name, sizeof(si->name));
}
} else {
si->type = SOCKET_INFO_UDP;
if (udp_socket_address(s, s->p.udp_address, &u)) {
getname(&u, si->name, sizeof(si->name));
}
}
break;
default:
return 0;
}
si->id = s->id;
si->opaque = (uint64_t)s->opaque;
si->read = s->stat.read;
si->write = s->stat.write;
si->rtime = s->stat.rtime;
si->wtime = s->stat.wtime;
si->wbuffer = s->wb_size;
return 1;
}
struct socket_info *
socket_server_info(struct socket_server *ss) {
int i;
struct socket_info * si = NULL;
for (i=0;i<MAX_SOCKET;i++) {
struct socket * s = &ss->slot[i];
int id = s->id;
struct socket_info temp;
if (query_info(s, &temp) && s->id == id) {
// socket_server_info may call in different thread, so check socket id again
si = socket_info_create(si);
temp.next = si->next;
*si = temp;
}
}
return si;
}
|
24967674e2a49eb811967dd7c63772971690fb26
|
9de0cec678bc4a3bec2b4adabef9f39ff5b4afac
|
/PWG/muon/aaf/PWGmuonaafLinkDef.h
|
ee31145154b8b3891c7a1d535e94a3c827c08961
|
[] |
permissive
|
alisw/AliPhysics
|
91bf1bd01ab2af656a25ff10b25e618a63667d3e
|
5df28b2b415e78e81273b0d9bf5c1b99feda3348
|
refs/heads/master
| 2023-08-31T20:41:44.927176
| 2023-08-31T14:51:12
| 2023-08-31T14:51:12
| 61,661,378
| 129
| 1,150
|
BSD-3-Clause
| 2023-09-14T18:48:45
| 2016-06-21T19:31:29
|
C++
|
UTF-8
|
C
| false
| false
| 699
|
h
|
PWGmuonaafLinkDef.h
|
#ifdef __CINT__
#pragma link off all globals;
#pragma link off all classes;
#pragma link off all functions;
#pragma link C++ namespace AAF;
#pragma link C++ function AAF::FILTER_ESDMUON;
#pragma link C++ function AAF::FILTER_RAWMUON;
#pragma link C++ namespace AAF::RAWMUON;
#pragma link C++ function AAF::RAWMUON::CheckFile;
#pragma link C++ function AAF::RAWMUON::DisableBranches;
#pragma link C++ function AAF::FILTER_AODMUONWITHTRACKLETS;
#pragma link C++ function AAF::FILTER_AODMUONONLY_PP2015;
#pragma link C++ function AAF::FILTER_AODMUONONLY_PBPB2015;
#pragma link C++ function AAF::FILTER_AODMUONONLY_PBPB2015_WITHMULTSEL;
#pragma link C++ function AAF::FILTER_ESD2AODMUON;
#endif
|
c553a1c10156a51f4074c904dcc926688d3195e2
|
96df46515663aee49a753171fb3b07d74c8ef72f
|
/bindgen-tests/tests/headers/convert-floats.h
|
08d9fe0bd2d9665ef02d174d09d602e149d174c6
|
[
"BSD-3-Clause"
] |
permissive
|
rust-lang/rust-bindgen
|
05273ad4d385ce0b5a2315859f8c7c453c150db6
|
820ca42982fe77d5504f7a0534a3de6db6a1d703
|
refs/heads/main
| 2023-08-30T19:59:33.017994
| 2023-08-15T18:01:02
| 2023-08-15T18:01:02
| 61,728,459
| 2,874
| 391
|
BSD-3-Clause
| 2023-09-12T20:32:46
| 2016-06-22T15:05:51
|
Rust
|
UTF-8
|
C
| false
| false
| 174
|
h
|
convert-floats.h
|
// bindgen-flags: --no-convert-floats
struct foo {
float bar, baz;
double bazz;
long double* bazzz;
float _Complex complexFloat;
double _Complex complexDouble;
};
|
e9950d7bef6d9eecd610f220d27227451d253fcc
|
ec6a71b57ebe88538269197fd16bede6bc2062ae
|
/erts/emulator/beam/erl_port_task.h
|
dfc9b4416ce8500b4a5e27efcdf04066badd9eda
|
[
"Apache-2.0"
] |
permissive
|
erlang/otp
|
7c6e88ca955bd6a3ede1530154c80e8ce449a370
|
334589af62a8db25a81afba2ecc50f33ff69ddb8
|
refs/heads/master
| 2023-08-30T23:37:28.061328
| 2023-08-30T04:20:48
| 2023-08-30T04:20:48
| 374,927
| 9,920
| 3,018
|
Apache-2.0
| 2023-09-14T10:37:26
| 2009-11-16T17:17:57
|
Erlang
|
UTF-8
|
C
| false
| false
| 7,983
|
h
|
erl_port_task.h
|
/*
* %CopyrightBegin%
*
* Copyright Ericsson AB 2006-2020. 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.
*
* %CopyrightEnd%
*/
/*
* Description: Scheduling of port tasks
*
* Author: Rickard Green
*/
#ifndef ERTS_PORT_TASK_H_BASIC_TYPES__
#define ERTS_PORT_TASK_H_BASIC_TYPES__
#include "erl_sys_driver.h"
#include "erl_threads.h"
#define ERL_PORT_GET_PORT_TYPE_ONLY__
#include "erl_port.h"
#undef ERL_PORT_GET_PORT_TYPE_ONLY__
typedef erts_atomic_t ErtsPortTaskHandle;
#endif
#ifndef ERTS_PORT_TASK_ONLY_BASIC_TYPES__
#ifndef ERL_PORT_TASK_H__
#define ERL_PORT_TASK_H__
#include "erl_poll.h"
#undef ERTS_INCLUDE_SCHEDULER_INTERNALS
#if (defined(ERL_PROCESS_C__) \
|| defined(ERL_PORT_TASK_C__) \
|| defined(ERL_IO_C__) \
|| (ERTS_GLB_INLINE_INCL_FUNC_DEF \
&& defined(ERTS_DO_INCL_GLB_INLINE_FUNC_DEF)))
#define ERTS_INCLUDE_SCHEDULER_INTERNALS
#endif
#define ERTS_PT_FLG_WAIT_BUSY (1 << 0)
#define ERTS_PT_FLG_SIG_DEP (1 << 1)
#define ERTS_PT_FLG_NOSUSPEND (1 << 2)
#define ERTS_PT_FLG_REF (1 << 3)
#define ERTS_PT_FLG_BAD_OUTPUT (1 << 4)
typedef enum {
ERTS_PORT_TASK_INPUT = 0,
ERTS_PORT_TASK_OUTPUT = 1,
ERTS_PORT_TASK_TIMEOUT,
ERTS_PORT_TASK_DIST_CMD,
ERTS_PORT_TASK_PROC_SIG
} ErtsPortTaskType;
#define ERTS_PTS_FLG_IN_RUNQ (((erts_aint32_t) 1) << 0)
#define ERTS_PTS_FLG_EXEC (((erts_aint32_t) 1) << 1)
#define ERTS_PTS_FLG_HAVE_TASKS (((erts_aint32_t) 1) << 2)
#define ERTS_PTS_FLG_EXIT (((erts_aint32_t) 1) << 3)
#define ERTS_PTS_FLG_BUSY_PORT (((erts_aint32_t) 1) << 4)
#define ERTS_PTS_FLG_BUSY_PORT_Q (((erts_aint32_t) 1) << 5)
#define ERTS_PTS_FLG_CHK_UNSET_BUSY_PORT_Q (((erts_aint32_t) 1) << 6)
#define ERTS_PTS_FLG_HAVE_BUSY_TASKS (((erts_aint32_t) 1) << 7)
#define ERTS_PTS_FLG_HAVE_NS_TASKS (((erts_aint32_t) 1) << 8)
#define ERTS_PTS_FLG_PARALLELISM (((erts_aint32_t) 1) << 9)
#define ERTS_PTS_FLG_FORCE_SCHED (((erts_aint32_t) 1) << 10)
#define ERTS_PTS_FLG_EXITING (((erts_aint32_t) 1) << 11)
#define ERTS_PTS_FLG_EXEC_IMM (((erts_aint32_t) 1) << 12)
#define ERTS_PTS_FLGS_BUSY \
(ERTS_PTS_FLG_BUSY_PORT | ERTS_PTS_FLG_BUSY_PORT_Q)
#define ERTS_PTS_FLGS_FORCE_SCHEDULE_OP \
(ERTS_PTS_FLG_EXIT \
| ERTS_PTS_FLG_HAVE_BUSY_TASKS \
| ERTS_PTS_FLG_HAVE_TASKS \
| ERTS_PTS_FLG_EXEC \
| ERTS_PTS_FLG_EXEC_IMM \
| ERTS_PTS_FLG_FORCE_SCHED \
| ERTS_PTS_FLG_EXITING)
#define ERTS_PORT_TASK_DEFAULT_BUSY_PORT_Q_HIGH 8192
#define ERTS_PORT_TASK_DEFAULT_BUSY_PORT_Q_LOW 4096
typedef struct {
ErlDrvSizeT high;
erts_atomic_t low;
erts_atomic_t size;
} ErtsPortTaskBusyPortQ;
typedef struct ErtsPortTask_ ErtsPortTask;
typedef struct ErtsPortTaskBusyCallerTable_ ErtsPortTaskBusyCallerTable;
typedef struct ErtsPortTaskHandleList_ ErtsPortTaskHandleList;
typedef struct {
Port *next;
struct {
struct {
struct {
ErtsPortTask *first;
ErtsPortTask *last;
ErtsPortTaskBusyCallerTable *table;
ErtsPortTaskHandleList *nosuspend;
} busy;
ErtsPortTask *first;
} local;
struct {
ErtsPortTask *first;
ErtsPortTask *last;
} in;
ErtsPortTaskBusyPortQ *bpq;
} taskq;
erts_atomic32_t flags;
erts_mtx_t mtx;
} ErtsPortTaskSched;
ERTS_GLB_INLINE void erts_port_task_handle_init(ErtsPortTaskHandle *pthp);
ERTS_GLB_INLINE int erts_port_task_is_scheduled(ErtsPortTaskHandle *pthp);
ERTS_GLB_INLINE void erts_port_task_pre_init_sched(ErtsPortTaskSched *ptsp,
ErtsPortTaskBusyPortQ *bpq);
ERTS_GLB_INLINE void erts_port_task_init_sched(ErtsPortTaskSched *ptsp,
Eterm id);
ERTS_GLB_INLINE void erts_port_task_fini_sched(ErtsPortTaskSched *ptsp);
ERTS_GLB_INLINE void erts_port_task_sched_lock(ErtsPortTaskSched *ptsp);
ERTS_GLB_INLINE void erts_port_task_sched_unlock(ErtsPortTaskSched *ptsp);
ERTS_GLB_INLINE int erts_port_task_sched_lock_is_locked(ErtsPortTaskSched *ptsp);
ERTS_GLB_INLINE void erts_port_task_sched_enter_exiting_state(ErtsPortTaskSched *ptsp);
#if defined(ERTS_INCLUDE_SCHEDULER_INTERNALS) && ERTS_POLL_USE_SCHEDULER_POLLING
ERTS_GLB_INLINE int erts_port_task_have_outstanding_io_tasks(void);
/* NOTE: Do not access any of the exported variables directly */
extern erts_atomic_t erts_port_task_outstanding_io_tasks;
#endif
#if ERTS_GLB_INLINE_INCL_FUNC_DEF
ERTS_GLB_INLINE void
erts_port_task_handle_init(ErtsPortTaskHandle *pthp)
{
erts_atomic_init_nob(pthp, (erts_aint_t) NULL);
}
ERTS_GLB_INLINE int
erts_port_task_is_scheduled(ErtsPortTaskHandle *pthp)
{
return ((void *) erts_atomic_read_acqb(pthp)) != NULL;
}
ERTS_GLB_INLINE void erts_port_task_pre_init_sched(ErtsPortTaskSched *ptsp,
ErtsPortTaskBusyPortQ *bpq)
{
if (bpq) {
erts_aint_t low = (erts_aint_t) ERTS_PORT_TASK_DEFAULT_BUSY_PORT_Q_LOW;
erts_atomic_init_nob(&bpq->low, low);
bpq->high = (ErlDrvSizeT) ERTS_PORT_TASK_DEFAULT_BUSY_PORT_Q_HIGH;
erts_atomic_init_nob(&bpq->size, (erts_aint_t) 0);
}
ptsp->taskq.bpq = bpq;
}
ERTS_GLB_INLINE void
erts_port_task_init_sched(ErtsPortTaskSched *ptsp, Eterm instr_id)
{
const char *lock_str = "port_sched_lock";
ptsp->next = NULL;
ptsp->taskq.local.busy.first = NULL;
ptsp->taskq.local.busy.last = NULL;
ptsp->taskq.local.busy.table = NULL;
ptsp->taskq.local.busy.nosuspend = NULL;
ptsp->taskq.local.first = NULL;
ptsp->taskq.in.first = NULL;
ptsp->taskq.in.last = NULL;
erts_atomic32_init_nob(&ptsp->flags, 0);
erts_mtx_init(&ptsp->mtx, lock_str, instr_id, ERTS_LOCK_FLAGS_CATEGORY_IO);
}
ERTS_GLB_INLINE void
erts_port_task_sched_lock(ErtsPortTaskSched *ptsp)
{
erts_mtx_lock(&ptsp->mtx);
}
ERTS_GLB_INLINE void
erts_port_task_sched_unlock(ErtsPortTaskSched *ptsp)
{
erts_mtx_unlock(&ptsp->mtx);
}
ERTS_GLB_INLINE int
erts_port_task_sched_lock_is_locked(ErtsPortTaskSched *ptsp)
{
#if defined(ERTS_ENABLE_LOCK_CHECK)
return erts_lc_mtx_is_locked(&ptsp->mtx);
#else
return 0;
#endif
}
ERTS_GLB_INLINE void
erts_port_task_fini_sched(ErtsPortTaskSched *ptsp)
{
erts_mtx_destroy(&ptsp->mtx);
}
ERTS_GLB_INLINE void
erts_port_task_sched_enter_exiting_state(ErtsPortTaskSched *ptsp)
{
erts_atomic32_read_bor_nob(&ptsp->flags, ERTS_PTS_FLG_EXITING);
}
#if defined(ERTS_INCLUDE_SCHEDULER_INTERNALS) && ERTS_POLL_USE_SCHEDULER_POLLING
ERTS_GLB_INLINE int
erts_port_task_have_outstanding_io_tasks(void)
{
return (erts_atomic_read_acqb(&erts_port_task_outstanding_io_tasks)
!= 0);
}
#endif
#endif
#ifdef ERTS_INCLUDE_SCHEDULER_INTERNALS
void erts_port_task_execute(ErtsRunQueue *, Port **);
void erts_port_task_init(void);
#endif
/* generated for 'port_task' quick allocator */
void erts_port_task_pre_alloc_init_thread(void);
void erts_port_task_tmp_handle_detach(ErtsPortTaskHandle *);
int erts_port_task_abort(ErtsPortTaskHandle *);
void erts_port_task_abort_nosuspend_tasks(Port *);
int erts_port_task_schedule(Eterm,
ErtsPortTaskHandle *,
ErtsPortTaskType,
...);
void erts_port_task_free_port(Port *);
ErtsProc2PortSigData *erts_port_task_alloc_p2p_sig_data(void);
ErtsProc2PortSigData *erts_port_task_alloc_p2p_sig_data_extra(size_t extra, void **extra_ptr);
void erts_port_task_free_p2p_sig_data(ErtsProc2PortSigData *sigdp);
void erts_enqueue_port(ErtsRunQueue *rq, Port *pp);
Port *erts_dequeue_port(ErtsRunQueue *rq);
#undef ERTS_INCLUDE_SCHEDULER_INTERNALS
#endif /* ERL_PORT_TASK_H__ */
#endif /* ERTS_PORT_TASK_ONLY_BASIC_TYPES__ */
|
4c8a1627d3277eddf317903f5821143f501731bf
|
e9454d56c6fdd3389b7590aa0cbe96eef716d8f4
|
/SimTKmath/Integrators/src/CPodes/sundials/src/cpodes/cpodes.c
|
c18c6d8efba15a870cf1bf27a0677389ee1289b6
|
[
"Apache-2.0"
] |
permissive
|
simbody/simbody
|
b2ca134c6d91e5fe4da93fc22aaf86cdbdeff658
|
0d671660c4e97f26566da040eaa57089fab81192
|
refs/heads/master
| 2023-09-01T09:33:29.968397
| 2023-08-31T16:51:49
| 2023-08-31T16:51:49
| 12,146,969
| 2,186
| 539
|
Apache-2.0
| 2023-09-05T17:15:38
| 2013-08-16T00:21:53
|
C++
|
UTF-8
|
C
| false
| false
| 118,728
|
c
|
cpodes.c
|
/*
* -----------------------------------------------------------------
* $Revision: 1.9 $
* $Date: 2007/10/26 21:51:29 $
* -----------------------------------------------------------------
* Programmer: Radu Serban @ LLNL
* -----------------------------------------------------------------
* Copyright (c) 2006, The Regents of the University of California.
* Produced at the Lawrence Livermore National Laboratory.
* All rights reserved.
* For details, see the LICENSE file.
* -----------------------------------------------------------------
* This is the implementation file for the main CPODES integrator.
* It is independent of the CPODES linear solver in use.
* -----------------------------------------------------------------
*
* CONTENTS
*
* Exported functions:
* CPodeCreate - create CPODES solver object
* CPodeInit - initialize solver
* CPodeReInit - re-initialize solver
* CPodeProjInit - initialize internal projection algorithm
* CPodeProjDefine - initialize user-provided projection
* CPode - main solver function
* CPodeGetDky - dense output function
* CPodeFree - memory deallocation
*
* Private functions
* - Memory allocation/deallocation and initialization functions
* - Initial step size evaluation functions
* - Main step function
* - LMM-related functions
* - Nonlinear and error test failure handlers
* - Successful step completion functions
* - BDF stability limit detection functions
* - Projection functions
* - Internal error weight evaluation functions
* - Error reporting functions
*/
/*
* =================================================================
* IMPORTED HEADER FILES
* =================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "cpodes_private.h"
#include <sundials/sundials_math.h>
/*
* =================================================================
* FUNCTION SPECIFIC CONSTANTS
* =================================================================
*/
/*
* Algorithmic constants
* ---------------------
*/
/* constants used in estimating an initial step size */
#define HLB_FACTOR RCONST(100.0)
#define HUB_FACTOR RCONST(0.1)
#define H_BIAS HALF
#define H_MAXITERS 4
/* constants used in taking a step */
#define THRESH RCONST(1.5)
#define ETAMX1 RCONST(10000.0)
#define ETAMX2 RCONST(10.0)
#define ETAMX3 RCONST(10.0)
#define ETAMXF RCONST(0.2)
#define ETAMIN RCONST(0.1)
#define ADDON RCONST(0.000001)
#define BIAS1 RCONST(6.0)
#define BIAS2 RCONST(6.0)
#define BIAS3 RCONST(10.0)
/*
* =================================================================
* PROTOTYPES FOR PRIVATE FUNCTIONS
* =================================================================
*/
/* Memory allocation/deallocation and initialization functions */
static booleantype cpCheckNvector(N_Vector tmpl);
static booleantype cpAllocVectors(CPodeMem cp_mem, N_Vector tmpl, int tol);
static void cpFreeVectors(CPodeMem cp_mem);
static booleantype cpProjAlloc(CPodeMem cp_mem, N_Vector c_tmpl, N_Vector s_tmpl);
static void cpProjFree(CPodeMem cp_mem);
static booleantype cpQuadAlloc(CPodeMem cp_mem, N_Vector q_tmpl);
static void cpQuadFree(CPodeMem cp_mem);
static int cpInitialSetup(CPodeMem cp_mem);
/* Initial step size evaluation functions */
static int cpHin(CPodeMem cp_mem, realtype tout);
static realtype cpUpperBoundH0(CPodeMem cp_mem, realtype tdist);
static int cpHinExpl(CPodeMem cp_mem, realtype hlb, realtype hub, int sign, realtype *h0);
static int cpYppNorm(CPodeMem cp_mem, realtype hg, realtype *yppnorm);
static int cpHinImpl(CPodeMem cp_mem, realtype tdist, realtype *h0);
/* Main step function */
static int cpStep(CPodeMem cp_mem);
/* Functions acting on Nordsieck history array */
static void cpPredict(CPodeMem cp_mem);
static void cpCorrect(CPodeMem cp_mem);
/* Quadrature correction function */
static int cpQuadNls(CPodeMem cp_mem, realtype saved_t, int *ncfPtr);
/* LMM-related functions */
static void cpAdjustParams(CPodeMem cp_mem);
static void cpAdjustOrder(CPodeMem cp_mem, int deltaq);
static void cpAdjustAdams(CPodeMem cp_mem, int deltaq);
static void cpAdjustBDF(CPodeMem cp_mem, int deltaq);
static void cpIncreaseBDF(CPodeMem cp_mem);
static void cpDecreaseBDF(CPodeMem cp_mem);
static void cpSet(CPodeMem cp_mem);
static void cpSetAdams(CPodeMem cp_mem);
static realtype cpAdamsStart(CPodeMem cp_mem, realtype m[]);
static void cpAdamsFinish(CPodeMem cp_mem, realtype m[], realtype M[], realtype hsum);
static realtype cpAltSum(int iend, realtype a[], int k);
static void cpSetBDF(CPodeMem cp_mem);
static void cpSetTqBDF(CPodeMem cp_mem, realtype hsum, realtype alpha0,
realtype alpha0_hat, realtype xi_inv, realtype xistar_inv);
/* Error test function */
static int cpDoErrorTest(CPodeMem cp_mem, realtype saved_t, realtype acor_norm,
int *nefPtr, realtype *dsmPtr);
/* Successful step completion functions */
static void cpCompleteStep(CPodeMem cp_mem);
static void cpPrepareNextStep(CPodeMem cp_mem, realtype dsm);
static void cpSetEta(CPodeMem cp_mem);
static realtype cpComputeEtaqm1(CPodeMem cp_mem);
static realtype cpComputeEtaqp1(CPodeMem cp_mem);
static void cpChooseEta(CPodeMem cp_mem);
static int cpHandleFailure(CPodeMem cp_mem,int flag);
/* BDF stability limit detection functions */
static void cpBDFStab(CPodeMem cp_mem);
static int cpSLdet(CPodeMem cp_mem);
/* Internal error weight evaluation functions */
static int cpEwtSetSS(CPodeMem cp_mem, N_Vector ycur, N_Vector weight);
static int cpEwtSetSV(CPodeMem cp_mem, N_Vector ycur, N_Vector weight);
static int cpQuadEwtSet(CPodeMem cp_mem, N_Vector qcur, N_Vector weightQ);
static int cpQuadEwtSetSS(CPodeMem cp_mem, N_Vector qcur, N_Vector weightQ);
static int cpQuadEwtSetSV(CPodeMem cp_mem, N_Vector qcur, N_Vector weightQ);
/* Function for combined norms */
static realtype cpQuadUpdateNorm(CPodeMem cp_mem, realtype old_nrm,
N_Vector xQ, N_Vector wQ);
static realtype cpQuadUpdateDsm(CPodeMem cp_mem, realtype old_dsm,
realtype dsmQ);
/* Error reporting functions */
static void cpErrHandler(int error_code, const char *module,
const char *function, char *msg, void *data);
/*
* =================================================================
* EXPORTED FUNCTIONS
* =================================================================
*/
/*
* CPodeCreate
*
* CPodeCreate creates an internal memory block for a problem to
* be solved by CPODES.
* If successful, CPodeCreate returns a pointer to the problem memory.
* This pointer should be passed to CPodeInit.
* If an initialization error occurs, CPodeCreate prints an error
* message to standard err and returns NULL.
*/
void *CPodeCreate(int ode_type, int lmm_type, int nls_type)
{
int maxord;
CPodeMem cp_mem;
/* Test inputs */
if ((ode_type != CP_EXPL) && (ode_type != CP_IMPL)) {
cpProcessError(NULL, 0, "CPODES", "CPodeCreate", MSGCP_BAD_ODE);
return(NULL);
}
if ((lmm_type != CP_ADAMS) && (lmm_type != CP_BDF)) {
cpProcessError(NULL, 0, "CPODES", "CPodeCreate", MSGCP_BAD_LMM);
return(NULL);
}
if ((nls_type != CP_FUNCTIONAL) && (nls_type != CP_NEWTON)) {
cpProcessError(NULL, 0, "CPODES", "CPodeCreate", MSGCP_BAD_NLS);
return(NULL);
}
if ((ode_type == CP_IMPL) && (nls_type == CP_FUNCTIONAL)) {
cpProcessError(NULL, 0, "CPODES", "CPodeCreate", MSGCP_BAD_ODE_NLS);
return(NULL);
}
/* Allocate space for solver object */
cp_mem = NULL;
cp_mem = (CPodeMem) malloc(sizeof(struct CPodeMemRec));
if (cp_mem == NULL) {
cpProcessError(NULL, 0, "CPODES", "CPodeCreate", MSGCP_CPMEM_FAIL);
return(NULL);
}
maxord = (lmm_type == CP_ADAMS) ? ADAMS_Q_MAX : BDF_Q_MAX;
/* Copy input parameters into cp_mem */
cp_mem->cp_ode_type = ode_type;
cp_mem->cp_lmm_type = lmm_type;
cp_mem->cp_nls_type = nls_type;
/* Set uround */
cp_mem->cp_uround = UNIT_ROUNDOFF;
/* Initialize required values */
cp_mem->cp_fi = NULL;
cp_mem->cp_fe = NULL;
cp_mem->cp_f_data = NULL;
/* Set default values for integrator optional inputs */
cp_mem->cp_efun = cpEwtSet;
cp_mem->cp_e_data = (void *) cp_mem;
cp_mem->cp_ehfun = cpErrHandler;
cp_mem->cp_eh_data = (void *) cp_mem;
cp_mem->cp_errfp = stderr;
cp_mem->cp_qmax = maxord;
cp_mem->cp_mxstep = MXSTEP_DEFAULT;
cp_mem->cp_mxhnil = MXHNIL_DEFAULT;
cp_mem->cp_sldeton = FALSE;
cp_mem->cp_hin = ZERO;
cp_mem->cp_hmin = HMIN_DEFAULT;
cp_mem->cp_hmax_inv = HMAX_INV_DEFAULT;
cp_mem->cp_tstopset = FALSE;
cp_mem->cp_maxcor = NLS_MAXCOR;
cp_mem->cp_maxnef = MXNEF;
cp_mem->cp_maxncf = MXNCF;
cp_mem->cp_nlscoef = NLS_TEST_COEF;
/* Set the linear solver addresses to NULL. */
cp_mem->cp_linit = NULL;
cp_mem->cp_lsetup = NULL;
cp_mem->cp_lsolve = NULL;
cp_mem->cp_lfree = NULL;
cp_mem->cp_lmem = NULL;
cp_mem->cp_lsetup_exists = FALSE;
/* Initialize projection variables */
cp_mem->cp_proj_enabled = FALSE;
cp_mem->cp_proj_type = CP_PROJ_INTERNAL;
cp_mem->cp_cnstr_type = CP_CNSTR_NONLIN;
cp_mem->cp_cfun = NULL;
cp_mem->cp_c_data = NULL;
cp_mem->cp_pfun = NULL;
cp_mem->cp_p_data = NULL;
cp_mem->cp_prjcoef = PRJ_TEST_COEF;
cp_mem->cp_maxcorP = PRJ_MAXCOR;
cp_mem->cp_project_err = TRUE;
cp_mem->cp_test_cnstr = FALSE;
cp_mem->cp_proj_freq = 1;
cp_mem->cp_lsetupP_freq = PRJ_MSBLS;
cp_mem->cp_maxnpf = MXNPF;
/* Initialize quadrature variables */
cp_mem->cp_quadr = FALSE;
cp_mem->cp_qfun = NULL;
cp_mem->cp_q_data = NULL;
cp_mem->cp_errconQ = FALSE;
/* Set the linear solver addresses to NULL. */
cp_mem->cp_linitP = NULL;
cp_mem->cp_lsetupP = NULL;
cp_mem->cp_lsolveP = NULL;
cp_mem->cp_lfreeP = NULL;
cp_mem->cp_lmemP = NULL;
cp_mem->cp_lsetupP_exists = FALSE;
/* Initialize root finding variables */
cp_mem->cp_doRootfinding = FALSE;
cp_mem->cp_nrtfn = 0;
cp_mem->cp_glo = NULL;
cp_mem->cp_ghi = NULL;
cp_mem->cp_grout = NULL;
cp_mem->cp_gactive = NULL;
cp_mem->cp_iroots = NULL;
cp_mem->cp_rootdir = NULL;
cp_mem->cp_gfun = NULL;
cp_mem->cp_g_data = NULL;
/* Set the saved value qmax_alloc */
cp_mem->cp_qmax_alloc = maxord;
cp_mem->cp_qmax_allocQ = maxord;
/* Initialize lrw and liw */
cp_mem->cp_lrw = 58 + 2*L_MAX + NUM_TESTS;
cp_mem->cp_liw = 40;
/* No mallocs have been done yet */
cp_mem->cp_MallocDone = FALSE;
cp_mem->cp_VabstolMallocDone = FALSE;
cp_mem->cp_projMallocDone = FALSE;
cp_mem->cp_quadMallocDone = FALSE;
cp_mem->cp_VabstolQMallocDone = FALSE;
cp_mem->cp_rootMallocDone = FALSE;
/* Return pointer to CPODES memory block */
return((void *)cp_mem);
}
/*-----------------------------------------------------------------*/
#define ode_type (cp_mem->cp_ode_type)
#define lmm_type (cp_mem->cp_lmm_type)
#define nls_type (cp_mem->cp_nls_type)
#define lrw (cp_mem->cp_lrw)
#define liw (cp_mem->cp_liw)
/*-----------------------------------------------------------------*/
/*
* CPodeInit
*
* CPodeInit allocates and initializes memory for a problem. All
* problem inputs are checked for errors. If any error occurs during
* initialization, it is reported to the file whose file pointer is
* errfp and an error flag is returned. Otherwise, it returns CP_SUCCESS
*/
int CPodeInit(void *cpode_mem,
void *fun, void *f_data,
realtype t0, N_Vector y0, N_Vector yp0,
int tol_type, realtype reltol, void *abstol)
{
CPodeMem cp_mem;
booleantype nvectorOK, allocOK, neg_abstol;
long int lrw1, liw1;
int i,k;
/* Check cpode_mem */
if (cpode_mem==NULL) {
cpProcessError(NULL, CP_MEM_NULL, "CPODES", "CPodeInit", MSGCP_NO_MEM);
return(CP_MEM_NULL);
}
cp_mem = (CPodeMem) cpode_mem;
/* Check for legal input parameters */
if (fun == NULL) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "CPodeInit", MSGCP_NULL_F);
return(CP_ILL_INPUT);
}
if (y0==NULL) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "CPodeInit", MSGCP_NULL_Y0);
return(CP_ILL_INPUT);
}
if ( (ode_type==CP_IMPL) && (yp0==NULL) ) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "CPodeInit", MSGCP_NULL_YP0);
return(CP_ILL_INPUT);
}
if ((tol_type != CP_SS) && (tol_type != CP_SV) && (tol_type != CP_WF)) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "CPodeInit", MSGCP_BAD_ITOL);
return(CP_ILL_INPUT);
}
/* Test if all required vector operations are implemented */
nvectorOK = cpCheckNvector(y0);
if(!nvectorOK) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "CPodeInit", MSGCP_BAD_NVECTOR);
return(CP_ILL_INPUT);
}
/* Test tolerances */
if (tol_type != CP_WF) {
if (abstol == NULL) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "CPodeInit", MSGCP_NULL_ABSTOL);
return(CP_ILL_INPUT);
}
if (reltol < ZERO) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "CPodeInit", MSGCP_BAD_RELTOL);
return(CP_ILL_INPUT);
}
if (tol_type == CP_SS)
neg_abstol = (*((realtype *)abstol) < ZERO);
else
neg_abstol = (N_VMin((N_Vector)abstol) < ZERO);
if (neg_abstol) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "CPodeInit", MSGCP_BAD_ABSTOL);
return(CP_ILL_INPUT);
}
}
/* Set space requirements for one N_Vector */
if (y0->ops->nvspace != NULL) {
N_VSpace(y0, &lrw1, &liw1);
} else {
lrw1 = 0;
liw1 = 0;
}
cp_mem->cp_lrw1 = lrw1;
cp_mem->cp_liw1 = liw1;
/* Allocate the vectors (using y0 as a template) */
allocOK = cpAllocVectors(cp_mem, y0, tol_type);
if (!allocOK) {
cpProcessError(cp_mem, CP_MEM_FAIL, "CPODES", "CPodeInit", MSGCP_MEM_FAIL);
return(CP_MEM_FAIL);
}
/*
* All error checking is complete at this point
*/
/* Copy tolerances into memory */
cp_mem->cp_tol_type = tol_type;
cp_mem->cp_reltol = reltol;
if (tol_type == CP_SS) {
cp_mem->cp_Sabstol = *((realtype *)abstol);
} else if (tol_type == CP_SV) {
N_VScale(ONE, (N_Vector)abstol, cp_mem->cp_Vabstol);
}
/* Copy the input parameters into CPODES state */
if (ode_type == CP_EXPL) cp_mem->cp_fe = (CPRhsFn) fun;
else cp_mem->cp_fi = (CPResFn) fun;
cp_mem->cp_f_data = f_data;
cp_mem->cp_tn = t0;
/* Set step parameters */
cp_mem->cp_q = 1;
cp_mem->cp_L = 2;
cp_mem->cp_qwait = cp_mem->cp_L;
cp_mem->cp_etamax = ETAMX1;
cp_mem->cp_qu = 0;
cp_mem->cp_hu = ZERO;
cp_mem->cp_tolsf = ONE;
/* Initialize the history array zn */
N_VScale(ONE, y0, cp_mem->cp_zn[0]);
if(ode_type==CP_IMPL) N_VScale(ONE, yp0, cp_mem->cp_zn[1]);
/* Initialize all the counters */
cp_mem->cp_nst = 0;
cp_mem->cp_nfe = 0;
cp_mem->cp_ncfn = 0;
cp_mem->cp_netf = 0;
cp_mem->cp_nni = 0;
cp_mem->cp_nsetups = 0;
cp_mem->cp_nhnil = 0;
cp_mem->cp_nstlset = 0;
cp_mem->cp_nscon = 0;
cp_mem->cp_nge = 0;
cp_mem->cp_irfnd = 0;
cp_mem->cp_nproj = 0;
cp_mem->cp_nprf = 0;
cp_mem->cp_nce = 0;
cp_mem->cp_nstlprj = 0;
cp_mem->cp_nsetupsP = 0;
cp_mem->cp_first_proj = TRUE;
/* Initialize other integrator optional outputs */
cp_mem->cp_h0u = ZERO;
cp_mem->cp_next_h = ZERO;
cp_mem->cp_next_q = 0;
/*
* Initialize Stablilty Limit Detection data.
* NOTE: We do this even if stab lim det was not turned on yet.
* This way, the user can turn it on at any later time.
*/
cp_mem->cp_nor = 0;
for (i = 1; i <= 5; i++)
for (k = 1; k <= 3; k++)
cp_mem->cp_ssdat[i-1][k-1] = ZERO;
/* Problem has been successfully initialized */
cp_mem->cp_MallocDone = TRUE;
return(CP_SUCCESS);
}
/*-----------------------------------------------------------------*/
#define lrw1 (cp_mem->cp_lrw1)
#define liw1 (cp_mem->cp_liw1)
/*-----------------------------------------------------------------*/
/*
* CPodeReInit
*
* CPodeReInit re-initializes CPODE's memory for a problem, assuming
* it has already been allocated in a prior CPodeInit call.
* All problem specification inputs are checked for errors.
* If any error occurs during initialization, it is reported to the
* file whose file pointer is errfp.
* The return value is CP_SUCCESS = 0 if no errors occurred, or
* a negative value otherwise.
*/
int CPodeReInit(void *cpode_mem,
void *fun, void *f_data,
realtype t0, N_Vector y0, N_Vector yp0,
int tol_type, realtype reltol, void *abstol)
{
CPodeMem cp_mem;
booleantype neg_abstol;
int i,k;
/* Check cpode_mem */
if (cpode_mem==NULL) {
cpProcessError(NULL, CP_MEM_NULL, "CPODES", "CPodeReInit", MSGCP_NO_MEM);
return(CP_MEM_NULL);
}
cp_mem = (CPodeMem) cpode_mem;
/* Check if cpode_mem was allocated */
if (cp_mem->cp_MallocDone == FALSE) {
cpProcessError(cp_mem, CP_NO_MALLOC, "CPODES", "CPodeReInit", MSGCP_NO_MALLOC);
return(CP_NO_MALLOC);
}
/* Check for legal input parameters */
if (fun == NULL) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "CPodeReInit", MSGCP_NULL_F);
return(CP_ILL_INPUT);
}
if (y0 == NULL) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "CPodeReInit", MSGCP_NULL_Y0);
return(CP_ILL_INPUT);
}
if ( (ode_type==CP_IMPL) && (yp0==NULL) ) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "CPodeReInit", MSGCP_NULL_YP0);
return(CP_ILL_INPUT);
}
if ((tol_type != CP_SS) && (tol_type != CP_SV) && (tol_type != CP_WF)) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "CPodeReInit", MSGCP_BAD_ITOL);
return(CP_ILL_INPUT);
}
/* Test tolerances */
if (tol_type != CP_WF) {
if (abstol == NULL) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "CPodeReInit", MSGCP_NULL_ABSTOL);
return(CP_ILL_INPUT);
}
if (reltol < ZERO) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "CPodeReInit", MSGCP_BAD_RELTOL);
return(CP_ILL_INPUT);
}
if (tol_type == CP_SS) {
neg_abstol = (*((realtype *)abstol) < ZERO);
} else {
neg_abstol = (N_VMin((N_Vector)abstol) < ZERO);
}
if (neg_abstol) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "CPodeReInit", MSGCP_BAD_ABSTOL);
return(CP_ILL_INPUT);
}
}
/*
* All error checking is complete at this point
*/
/* Copy tolerances into memory */
cp_mem->cp_tol_type = tol_type;
cp_mem->cp_reltol = reltol;
if (tol_type == CP_SS) {
cp_mem->cp_Sabstol = *((realtype *)abstol);
} else if (tol_type == CP_SV) {
if ( !(cp_mem->cp_VabstolMallocDone) ) {
cp_mem->cp_Vabstol = N_VClone(y0);
lrw += lrw1;
liw += liw1;
cp_mem->cp_VabstolMallocDone = TRUE;
}
N_VScale(ONE, (N_Vector)abstol, cp_mem->cp_Vabstol);
}
/* Copy the input parameters into CPODES state */
if (ode_type == CP_EXPL) cp_mem->cp_fe = (CPRhsFn) fun;
else cp_mem->cp_fi = (CPResFn) fun;
cp_mem->cp_f_data = f_data;
cp_mem->cp_tn = t0;
/* Set step parameters */
cp_mem->cp_q = 1;
cp_mem->cp_L = 2;
cp_mem->cp_qwait = cp_mem->cp_L;
cp_mem->cp_etamax = ETAMX1;
cp_mem->cp_qu = 0;
cp_mem->cp_hu = ZERO;
cp_mem->cp_tolsf = ONE;
/* Initialize the history array zn */
N_VScale(ONE, y0, cp_mem->cp_zn[0]);
if(ode_type==CP_IMPL) N_VScale(ONE, yp0, cp_mem->cp_zn[1]);
/* Initialize all the counters */
cp_mem->cp_nst = 0;
cp_mem->cp_nfe = 0;
cp_mem->cp_ncfn = 0;
cp_mem->cp_netf = 0;
cp_mem->cp_nni = 0;
cp_mem->cp_nsetups = 0;
cp_mem->cp_nhnil = 0;
cp_mem->cp_nstlset = 0;
cp_mem->cp_nscon = 0;
cp_mem->cp_nge = 0;
cp_mem->cp_irfnd = 0;
cp_mem->cp_nproj = 0;
cp_mem->cp_nprf = 0;
cp_mem->cp_nce = 0;
cp_mem->cp_nstlprj = 0;
cp_mem->cp_nsetupsP = 0;
cp_mem->cp_first_proj = TRUE;
/* Initialize other integrator optional outputs */
cp_mem->cp_h0u = ZERO;
cp_mem->cp_next_h = ZERO;
cp_mem->cp_next_q = 0;
/* Initialize Stablilty Limit Detection data */
cp_mem->cp_nor = 0;
for (i = 1; i <= 5; i++)
for (k = 1; k <= 3; k++)
cp_mem->cp_ssdat[i-1][k-1] = ZERO;
/* Problem has been successfully re-initialized */
return(CP_SUCCESS);
}
/*-----------------------------------------------------------------*/
/*
* CPodeProjInit
*
*/
int CPodeProjInit(void *cpode_mem, int proj_norm,
int cnstr_type, CPCnstrFn cfun, void *c_data,
N_Vector ctol)
{
CPodeMem cp_mem;
booleantype allocOK;
/* Check cpode_mem */
if (cpode_mem==NULL) {
cpProcessError(NULL, CP_MEM_NULL, "CPODES", "CPodeProjInit", MSGCP_NO_MEM);
return(CP_MEM_NULL);
}
cp_mem = (CPodeMem) cpode_mem;
/* Check if cpode_mem was allocated */
if (cp_mem->cp_MallocDone == FALSE) {
cpProcessError(cp_mem, CP_NO_MALLOC, "CPODES", "CPodeProjInit", MSGCP_NO_MALLOC);
return(CP_NO_MALLOC);
}
/* Check for legal input parameters */
if ((proj_norm != CP_PROJ_L2NORM) && (proj_norm != CP_PROJ_ERRNORM) ) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "CPodeProjInit", MSGCP_BAD_NORM);
return(CP_ILL_INPUT);
}
if ((cnstr_type != CP_CNSTR_LIN) && (cnstr_type != CP_CNSTR_NONLIN) ) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "CPodeProjInit", MSGCP_BAD_CNSTR);
return(CP_ILL_INPUT);
}
if (cfun == NULL) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "CPodeProjInit", MSGCP_NULL_C);
return(CP_ILL_INPUT);
}
if (ctol == NULL) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "CPodeProjInit", MSGCP_CTOL_NULL);
return(CP_ILL_INPUT);
}
/* Allocate memory for vectors used in the projection algorithm,
using ctol and tempv as templates */
if (!cp_mem->cp_projMallocDone) {
allocOK = cpProjAlloc(cp_mem, ctol, cp_mem->cp_tempv);
if (!allocOK) {
cpProcessError(cp_mem, CP_MEM_FAIL, "CPODES", "CPodeProjInit", MSGCP_MEM_FAIL);
return(CP_MEM_FAIL);
}
cp_mem->cp_projMallocDone = TRUE;
}
/* Set variable values in CPODES memory block */
cp_mem->cp_proj_norm = proj_norm;
cp_mem->cp_cnstr_type = cnstr_type;
cp_mem->cp_cfun = cfun;
cp_mem->cp_c_data = c_data;
/* Copy 1/ctol into memory */
N_VScale(ONE, ctol, cp_mem->cp_ctol);
N_VInv(cp_mem->cp_ctol, cp_mem->cp_ctol);
/* internal projection is now enabled */
cp_mem->cp_proj_type = CP_PROJ_INTERNAL;
cp_mem->cp_proj_enabled = TRUE;
return(CP_SUCCESS);
}
/*
* CPodeProjDefine
*/
int CPodeProjDefine(void *cpode_mem, CPProjFn pfun, void *p_data)
{
CPodeMem cp_mem;
if (cpode_mem==NULL) {
cpProcessError(NULL, CP_MEM_NULL, "CPODES", "CPodeProjDefine", MSGCP_NO_MEM);
return(CP_MEM_NULL);
}
cp_mem = (CPodeMem) cpode_mem;
cp_mem->cp_pfun = pfun;
cp_mem->cp_p_data = p_data;
/* user-defined projection is now enabled */
cp_mem->cp_proj_type = CP_PROJ_USER;
cp_mem->cp_proj_enabled = TRUE;
return(CP_SUCCESS);
}
/*-----------------------------------------------------------------*/
/*
* CPodeQuadInit
*
* CPodeQuadInit allocates and initializes quadrature related
* memory for a problem. All problem specification inputs are
* checked for errors. If any error occurs during initialization,
* it is reported to the error handler function.
* The return value is CP_SUCCESS = 0 if no errors occurred, or
* a negative value otherwise.
*/
int CPodeQuadInit(void *cpode_mem, CPQuadFn qfun, void *q_data, N_Vector q0)
{
CPodeMem cp_mem;
booleantype allocOK;
long int lrw1Q, liw1Q;
/* Check cpode_mem */
if (cpode_mem==NULL) {
cpProcessError(NULL, CP_MEM_NULL, "CPODES", "CPodeQuadInit", MSGCP_NO_MEM);
return(CP_MEM_NULL);
}
cp_mem = (CPodeMem) cpode_mem;
/* Set space requirements for one N_Vector */
N_VSpace(q0, &lrw1Q, &liw1Q);
cp_mem->cp_lrw1Q = lrw1Q;
cp_mem->cp_liw1Q = liw1Q;
/* Allocate the vectors (using q0 as a template) */
allocOK = cpQuadAlloc(cp_mem, q0);
if (!allocOK) {
cpProcessError(cp_mem, CP_MEM_FAIL, "CPODES", "CPodeQuadInit", MSGCP_MEM_FAIL);
return(CP_MEM_FAIL);
}
/* Initialize znQ[0] in the history array */
N_VScale(ONE, q0, cp_mem->cp_znQ[0]);
/* Copy the input parameters into CPODES state */
cp_mem->cp_qfun = qfun;
cp_mem->cp_q_data = q_data;
/* Initialize counters */
cp_mem->cp_nqe = 0;
cp_mem->cp_netfQ = 0;
/* Quadrature integration turned ON */
cp_mem->cp_quadr = TRUE;
cp_mem->cp_quadMallocDone = TRUE;
/* Quadrature initialization was successful */
return(CP_SUCCESS);
}
/*-----------------------------------------------------------------*/
#define lrw1Q (cp_mem->cp_lrw1Q)
#define liw1Q (cp_mem->cp_liw1Q)
/*-----------------------------------------------------------------*/
/*
* CPodeQuadReInit
*
* CPodeQuadReInit re-initializes CPODES's quadrature related memory
* for a problem, assuming it has already been allocated in prior
* calls to CPodeMalloc and CPodeQuadInit.
* All problem specification inputs are checked for errors.
* If any error occurs during initialization, it is reported to the
* error handler function.
* The return value is CP_SUCCESS = 0 if no errors occurred, or
* a negative value otherwise.
*/
int CPodeQuadReInit(void *cpode_mem, CPQuadFn qfun, void *q_data, N_Vector q0)
{
CPodeMem cp_mem;
/* Check cpode_mem */
if (cpode_mem==NULL) {
cpProcessError(NULL, CP_MEM_NULL, "CPODES", "CPodeQuadReInit", MSGCP_NO_MEM);
return(CP_MEM_NULL);
}
cp_mem = (CPodeMem) cpode_mem;
/* Ckeck if quadrature was initialized? */
if (cp_mem->cp_quadMallocDone == FALSE) {
cpProcessError(cp_mem, CP_NO_QUAD, "CPODES", "CPodeQuadReInit", MSGCP_NO_QUAD);
return(CP_NO_QUAD);
}
/* Initialize znQ[0] in the history array */
N_VScale(ONE, q0, cp_mem->cp_znQ[0]);
/* Copy the input parameters into CPODES state */
cp_mem->cp_qfun = qfun;
cp_mem->cp_q_data = q_data;
/* Initialize counters */
cp_mem->cp_nqe = 0;
cp_mem->cp_netfQ = 0;
/* Quadrature integration turned ON */
cp_mem->cp_quadr = TRUE;
/* Quadrature re-initialization was successful */
return(CP_SUCCESS);
}
/*
* =================================================================
* READIBILITY REPLACEMENTS
* =================================================================
*/
#define fi (cp_mem->cp_fi)
#define fe (cp_mem->cp_fe)
#define f_data (cp_mem->cp_f_data)
#define efun (cp_mem->cp_efun)
#define e_data (cp_mem->cp_e_data)
#define qmax (cp_mem->cp_qmax)
#define mxstep (cp_mem->cp_mxstep)
#define mxhnil (cp_mem->cp_mxhnil)
#define sldeton (cp_mem->cp_sldeton)
#define hin (cp_mem->cp_hin)
#define hmin (cp_mem->cp_hmin)
#define hmax_inv (cp_mem->cp_hmax_inv)
#define istop (cp_mem->cp_istop)
#define tstop (cp_mem->cp_tstop)
#define tstopset (cp_mem->cp_tstopset)
#define maxncf (cp_mem->cp_maxncf)
#define maxnef (cp_mem->cp_maxnef)
#define nlscoef (cp_mem->cp_nlscoef)
#define tol_type (cp_mem->cp_tol_type)
#define reltol (cp_mem->cp_reltol)
#define Sabstol (cp_mem->cp_Sabstol)
#define Vabstol (cp_mem->cp_Vabstol)
#define uround (cp_mem->cp_uround)
#define zn (cp_mem->cp_zn)
#define ewt (cp_mem->cp_ewt)
#define y (cp_mem->cp_y)
#define yp (cp_mem->cp_yp)
#define acor (cp_mem->cp_acor)
#define tempv (cp_mem->cp_tempv)
#define ftemp (cp_mem->cp_ftemp)
#define q (cp_mem->cp_q)
#define qprime (cp_mem->cp_qprime)
#define next_q (cp_mem->cp_next_q)
#define qwait (cp_mem->cp_qwait)
#define L (cp_mem->cp_L)
#define h (cp_mem->cp_h)
#define hprime (cp_mem->cp_hprime)
#define next_h (cp_mem->cp_next_h)
#define eta (cp_mem->cp_eta)
#define etaqm1 (cp_mem->cp_etaqm1)
#define etaq (cp_mem->cp_etaq)
#define etaqp1 (cp_mem->cp_etaqp1)
#define nscon (cp_mem->cp_nscon)
#define hscale (cp_mem->cp_hscale)
#define tn (cp_mem->cp_tn)
#define tau (cp_mem->cp_tau)
#define tq (cp_mem->cp_tq)
#define l (cp_mem->cp_l)
#define p (cp_mem->cp_p)
#define rl1 (cp_mem->cp_rl1)
#define gamma (cp_mem->cp_gamma)
#define gammap (cp_mem->cp_gammap)
#define gamrat (cp_mem->cp_gamrat)
#define acnrm (cp_mem->cp_acnrm)
#define etamax (cp_mem->cp_etamax)
#define nst (cp_mem->cp_nst)
#define nfe (cp_mem->cp_nfe)
#define ncfn (cp_mem->cp_ncfn)
#define netf (cp_mem->cp_netf)
#define nhnil (cp_mem->cp_nhnil)
#define qu (cp_mem->cp_qu)
#define hu (cp_mem->cp_hu)
#define saved_tq5 (cp_mem->cp_saved_tq5)
#define indx_acor (cp_mem->cp_indx_acor)
#define tolsf (cp_mem->cp_tolsf)
#define lsetup_exists (cp_mem->cp_lsetup_exists)
#define nor (cp_mem->cp_nor)
#define ssdat (cp_mem->cp_ssdat)
#define proj_enabled (cp_mem->cp_proj_enabled)
#define proj_freq (cp_mem->cp_proj_freq)
#define proj_type (cp_mem->cp_proj_type)
#define cnstr_type (cp_mem->cp_cnstr_type)
#define cfun (cp_mem->cp_cfun)
#define c_data (cp_mem->cp_c_data)
#define pfun (cp_mem->cp_pfun)
#define p_data (cp_mem->cp_p_data)
#define yC (cp_mem->cp_yC)
#define acorP (cp_mem->cp_acorP)
#define errP (cp_mem->cp_errP)
#define ctol (cp_mem->cp_ctol)
#define ctemp (cp_mem->cp_ctemp)
#define tempvP1 (cp_mem->cp_tempvP1)
#define tempvP2 (cp_mem->cp_tempvP2)
#define nstlprj (cp_mem->cp_nstlprj)
#define applyProj (cp_mem->cp_applyProj)
#define quadr (cp_mem->cp_quadr)
#define qfun (cp_mem->cp_qfun)
#define q_data (cp_mem->cp_q_data)
#define errconQ (cp_mem->cp_errconQ)
#define tol_typeQ (cp_mem->cp_tol_typeQ)
#define reltolQ (cp_mem->cp_reltolQ)
#define SabstolQ (cp_mem->cp_SabstolQ)
#define VabstolQ (cp_mem->cp_VabstolQ)
#define znQ (cp_mem->cp_znQ)
#define ewtQ (cp_mem->cp_ewtQ)
#define acorQ (cp_mem->cp_acorQ)
#define yQ (cp_mem->cp_yQ)
#define tempvQ (cp_mem->cp_tempvQ)
#define acnrmQ (cp_mem->cp_acnrmQ)
#define nqe (cp_mem->cp_nqe)
#define netfQ (cp_mem->cp_netfQ)
#define quadMallocDone (cp_mem->cp_quadMallocDone)
#define doRootfinding (cp_mem->cp_doRootfinding)
#define tlo (cp_mem->cp_tlo)
#define thi (cp_mem->cp_thi)
#define tretlast (cp_mem->cp_tretlast)
#define toutc (cp_mem->cp_toutc)
#define taskc (cp_mem->cp_taskc)
#define irfnd (cp_mem->cp_irfnd)
/*-----------------------------------------------------------------*/
/*
* CPode
*
* This routine is the main driver of the CPODES package.
*
* It integrates over a time interval defined by the user, by calling
* cpStep to do internal time steps.
*
* The first time that CPode is called for a successfully initialized
* problem, it computes a tentative initial step size h.
*
* CPode supports four modes, specified by mode: CP_NORMAL, CP_ONE_STEP,
* CP_NORMAL_TSTOP, and CP_ONE_STEP_TSTOP.
* In the CP_NORMAL mode, the solver steps until it reaches or passes tout
* and then interpolates to obtain y(tout).
* In the CP_ONE_STEP mode, it takes one internal step and returns.
* CP_NORMAL_TSTOP and CP_ONE_STEP_TSTOP are similar to CP_NORMAL and CP_ONE_STEP,
* respectively, but the integration never proceeds past tstop (which
* must have been defined through a call to CPodeSetStopTime).
*/
int CPode(void *cpode_mem, realtype tout, realtype *tret,
N_Vector yout, N_Vector ypout, int mode)
{
CPodeMem cp_mem;
long int nstloc;
int retval, hflag, kflag, istate, ier, task, irfndp;
realtype troundoff, rh, nrm;
/*
* -------------------------------------
* 1. Check and process inputs
* -------------------------------------
*/
/* Check if cpode_mem exists */
if (cpode_mem == NULL) {
cpProcessError(NULL, CP_MEM_NULL, "CPODES", "CPode", MSGCP_NO_MEM);
return(CP_MEM_NULL);
}
cp_mem = (CPodeMem) cpode_mem;
/* Check if cpode_mem was allocated */
if (cp_mem->cp_MallocDone == FALSE) {
cpProcessError(cp_mem, CP_NO_MALLOC, "CPODES", "CPode", MSGCP_NO_MALLOC);
return(CP_NO_MALLOC);
}
/* Check for yout != NULL */
if (yout == NULL) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "CPode", MSGCP_YOUT_NULL);
return(CP_ILL_INPUT);
}
y = yout;
/* Check for ypout != NULL */
if (ypout == NULL ) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "CPode", MSGCP_YPOUT_NULL);
return(CP_ILL_INPUT);
}
yp = ypout;
/* Check for tret != NULL */
if (tret == NULL) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "CPode", MSGCP_TRET_NULL);
return(CP_ILL_INPUT);
}
/* Check for valid mode */
if ((mode != CP_NORMAL) &&
(mode != CP_ONE_STEP) &&
(mode != CP_NORMAL_TSTOP) &&
(mode != CP_ONE_STEP_TSTOP) ) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "CPode", MSGCP_BAD_MODE);
return(CP_ILL_INPUT);
}
/* Split mode into task and istop */
if ((mode == CP_NORMAL_TSTOP) || (mode == CP_ONE_STEP_TSTOP)) {
if ( tstopset == FALSE ) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "CPode", MSGCP_NO_TSTOP);
return(CP_ILL_INPUT);
}
istop = TRUE;
} else {
istop = FALSE;
}
if ((mode == CP_NORMAL) || (mode == CP_NORMAL_TSTOP)) {
task = CP_NORMAL; toutc = tout;
} else {
task = CP_ONE_STEP;
}
taskc = task;
/*
* ----------------------------------------
* 2. Initializations performed only at
* the first step (nst=0):
* - initial setup
* - compute initial step size
* - check for approach to tstop
* - check for approach to a root
* - scale zn[1] by h
* ----------------------------------------
*/
if (nst == 0) {
/* Initial setup */
ier = cpInitialSetup(cp_mem);
if (ier!= CP_SUCCESS) return(ier);
/* In CP_EXPL mode, call fun at (t0, y0) to set zn[1] = f'(t0,y0) */
if (ode_type == CP_EXPL) {
retval = fe(tn, zn[0], zn[1], f_data);
nfe++;
if (retval < 0) {
cpProcessError(cp_mem, CP_ODEFUNC_FAIL, "CPODES", "CPode", MSGCP_ODEFUNC_FAILED, tn);
return(CP_ODEFUNC_FAIL);
}
if (retval > 0) {
cpProcessError(cp_mem, CP_FIRST_ODEFUNC_ERR, "CPODES", "CPode", MSGCP_ODEFUNC_FIRST);
return(CP_FIRST_ODEFUNC_ERR);
}
}
/* If computing any quadratures, call qfun at (t0,y0) to set znQ[1] = q'(t0,y0) */
if (quadr) {
retval = qfun(tn, zn[0], znQ[1], q_data);
nqe++;
if (retval < 0) {
cpProcessError(cp_mem, CP_QUADFUNC_FAIL, "CPODES", "CPode", MSGCP_QUADFUNC_FAILED, tn);
return(CP_QUADFUNC_FAIL);
}
if (retval > 0) {
cpProcessError(cp_mem, CP_FIRST_QUADFUNC_ERR, "CPODES", "CPode", MSGCP_QUADFUNC_FIRST);
return(CP_FIRST_QUADFUNC_ERR);
}
}
/* Set initial h (from H0 or cpHin). */
h = hin;
if ( (h != ZERO) && ((tout-tn)*h < ZERO) ) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "CPode", MSGCP_BAD_H0);
return(CP_ILL_INPUT);
}
if (h == ZERO) {
hflag = cpHin(cp_mem, tout);
if (hflag != CP_SUCCESS) {
istate = cpHandleFailure(cp_mem, hflag);
return(istate);
}
}
rh = ABS(h)*hmax_inv;
if (rh > ONE) h /= rh;
if (ABS(h) < hmin) h *= hmin/ABS(h);
/* Check for approach to tstop */
if (istop) {
if ( (tstop - tn)*h < ZERO ) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "CPode", MSGCP_BAD_TSTOP, tn);
return(CP_ILL_INPUT);
}
if ( (tn + h - tstop)*h > ZERO )
h = (tstop - tn)*(ONE-FOUR*uround);
}
cp_mem->cp_h0u = h;
/* Check for zeros of root function g at and near t0. If found at t0 we'll
advance time a little to see whether the zeroes go away. If not, we'll
deactivate the g's that stay zero. On return we will have marked the
end of the "previous" rootfinding interval as thi, with ghi=g(thi). */
if (doRootfinding) {
retval = cpRcheck1(cp_mem);
if (retval == CP_RTFUNC_FAIL) {
cpProcessError(cp_mem, CP_RTFUNC_FAIL, "CPODES", "cpRcheck1", MSGCP_RTFUNC_FAILED, tn);
return(CP_RTFUNC_FAIL);
}
}
/* Scale zn[1] and (if needed) znQ[1] by h */
hscale = h;
hprime = h;
N_VScale(h, zn[1], zn[1]);
if (quadr) N_VScale(h, znQ[1], znQ[1]);
}
/*
* ------------------------------------------------------
* 3. At following steps, perform stop tests:
* - check for root in last step
* - check if we passed tstop
* - check if we passed tout (NORMAL mode)
* - check if current tn was returned (ONE_STEP mode)
* - check if we are close to tstop
* (adjust step size if needed)
* -------------------------------------------------------
*/
if (nst > 0) {
/* Estimate an infinitesimal time interval to be used as
a roundoff for time quantities (based on current time
and step size) */
troundoff = FUZZ_FACTOR*uround*(ABS(tn) + ABS(h));
/* First, check for a root in the last step taken, other than the
last root found, if any. If task = CP_ONE_STEP and y(tn) was not
returned because of an intervening root, return y(tn) now. */
if (doRootfinding) {
irfndp = irfnd;
/* This may find a root at the start of the interval in which case
(tlo,thi] brackets it and glo and ghi are set. If no root then thi and
ghi are set ready for the call to cpRcheck3(). */
retval = cpRcheck2(cp_mem);
if (retval == CP_RTFUNC_FAIL) {
cpProcessError(cp_mem, CP_RTFUNC_FAIL, "CPODES", "cpRcheck2", MSGCP_RTFUNC_FAILED, tlo);
return(CP_RTFUNC_FAIL);
} else if (retval == RTFOUND) {
tretlast = *tret = thi;
return(CP_ROOT_RETURN);
}
/* If tn is distinct from tretlast (within roundoff),
check remaining interval for roots */
if ( ABS(tn - tretlast) > troundoff ) {
/* Search for a root between the old thi and tn, updating tlo,thi. */
retval = cpRcheck3(cp_mem);
if (retval == CP_SUCCESS) { /* no root found */
irfnd = 0;
if ((irfndp == 1) && (task == CP_ONE_STEP)) {
tretlast = *tret = tn;
cpGetSolution(cp_mem, tn, yout, ypout);
return(CP_SUCCESS);
}
} else if (retval == RTFOUND) { /* a new root was found */
irfnd = 1;
tretlast = *tret = thi;
return(CP_ROOT_RETURN);
} else if (retval == CP_RTFUNC_FAIL) { /* g failed */
cpProcessError(cp_mem, CP_RTFUNC_FAIL, "CPODES", "cpRcheck3", MSGCP_RTFUNC_FAILED, thi);
return(CP_RTFUNC_FAIL);
}
}
} /* end of root stop check */
/* Test for tn past tstop */
if ( istop && ((tstop - tn)*h < ZERO) ) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "CPode", MSGCP_BAD_TSTOP, tn);
return(CP_ILL_INPUT);
}
/* In CP_NORMAL mode, test if tout was reached */
if ( (task == CP_NORMAL) && ((tn-tout)*h >= ZERO) ) {
tretlast = *tret = tout;
ier = cpGetSolution(cp_mem, tout, yout, ypout);
if (ier != CP_SUCCESS) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "CPode", MSGCP_BAD_TOUT, tout);
return(CP_ILL_INPUT);
}
return(CP_SUCCESS);
}
/* In CP_ONE_STEP mode, test if tn was returned */
if ( task == CP_ONE_STEP && ABS(tn - tretlast) > troundoff ) {
tretlast = *tret = tn;
cpGetSolution(cp_mem, tn, yout, ypout);
return(CP_SUCCESS);
}
/* Test for tn at tstop or near tstop */
if ( istop ) {
if ( ABS(tn - tstop) <= troundoff) {
ier = cpGetSolution(cp_mem, tstop, yout, ypout);
if (ier != CP_SUCCESS) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "CPode", MSGCP_BAD_TSTOP, tn);
return(CP_ILL_INPUT);
}
tretlast = *tret = tstop;
return(CP_TSTOP_RETURN);
}
/* If next step would overtake tstop, adjust stepsize */
if ( (tn + hprime - tstop)*h > ZERO ) {
hprime = (tstop - tn)*(ONE-FOUR*uround);
eta = hprime/h;
}
}
}
/*
* --------------------------------------------------
* 4. Looping point for internal steps
*
* 4.1. check for errors (too many steps, too much
* accuracy requested, step size too small)
* 4.2. take a new step (call cpStep)
* 4.3. stop on error
* 4.4. perform stop tests:
* - check for root in last step
* - check if tout was passed
* - check if close to tstop
* - check if in ONE_STEP mode (must return)
* --------------------------------------------------
*/
nstloc = 0;
loop {
next_h = h;
next_q = q;
/* Reset and check ewt, ewtQ */
if (nst > 0) {
ier = efun(zn[0], ewt, e_data);
if (ier != 0) {
if (tol_type == CP_WF) cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "CPode", MSGCP_EWT_NOW_FAIL, tn);
else cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "CPode", MSGCP_EWT_NOW_BAD, tn);
istate = CP_ILL_INPUT;
tretlast = *tret = tn;
cpGetSolution(cp_mem, tn, yout, ypout);
break;
}
if (quadr && errconQ) {
ier = cpQuadEwtSet(cp_mem, znQ[0], ewtQ);
if(ier != 0) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "CPode", MSGCP_EWTQ_NOW_BAD, tn);
istate = CP_ILL_INPUT;
tretlast = *tret = tn;
N_VScale(ONE, zn[0], yout);
break;
}
}
}
/* Check for too many steps */
if (nstloc >= mxstep) {
cpProcessError(cp_mem, CP_TOO_MUCH_WORK, "CPODES", "CPode", MSGCP_MAX_STEPS, tn);
istate = CP_TOO_MUCH_WORK;
tretlast = *tret = tn;
cpGetSolution(cp_mem, tn, yout, ypout);
break;
}
/* Check for too much accuracy requested */
nrm = N_VWrmsNorm(zn[0], ewt);
if (quadr && errconQ) nrm = cpQuadUpdateNorm(cp_mem, nrm, znQ[0], ewtQ);
tolsf = uround * nrm;
if (tolsf > ONE) {
cpProcessError(cp_mem, CP_TOO_MUCH_ACC, "CPODES", "CPode", MSGCP_TOO_MUCH_ACC, tn);
istate = CP_TOO_MUCH_ACC;
tretlast = *tret = tn;
cpGetSolution(cp_mem, tn, yout, ypout);
tolsf *= TWO;
break;
} else {
tolsf = ONE;
}
/* Check for h below roundoff level in tn */
if (tn + h == tn) {
nhnil++;
if (nhnil <= mxhnil)
cpProcessError(cp_mem, CP_WARNING, "CPODES", "CPode", MSGCP_HNIL, tn, h);
if (nhnil == mxhnil)
cpProcessError(cp_mem, CP_WARNING, "CPODES", "CPode", MSGCP_HNIL_DONE);
}
/* Call cpStep to take a step */
kflag = cpStep(cp_mem);
/* Process failed step cases, and exit loop */
if (kflag != CP_SUCCESS) {
istate = cpHandleFailure(cp_mem, kflag);
tretlast = *tret = tn;
cpGetSolution(cp_mem, tn, yout, ypout);
break;
}
nstloc++;
/* Check for root in step just taken. */
if (doRootfinding) {
/* This will move tlo up to the previous thi, then move thi to the
end of the current step and then use (tlo,thi] as the initial search
interval. */
retval = cpRcheck3(cp_mem);
if (retval == RTFOUND) { /* A new root was found */
irfnd = 1;
istate = CP_ROOT_RETURN;
tretlast = *tret = thi;
break;
} else if (retval == CP_RTFUNC_FAIL) { /* g failed */
cpProcessError(cp_mem, CP_RTFUNC_FAIL, "CPODES", "cpRcheck3", MSGCP_RTFUNC_FAILED, thi);
istate = CP_RTFUNC_FAIL;
break;
}
}
/* In NORMAL mode, check if tout reached */
if ( (task == CP_NORMAL) && (tn-tout)*h >= ZERO ) {
istate = CP_SUCCESS;
tretlast = *tret = tout;
(void) cpGetSolution(cp_mem, tout, yout, ypout);
next_q = qprime;
next_h = hprime;
break;
}
/* Check if tn is at tstop or near tstop */
if ( istop ) {
troundoff = FUZZ_FACTOR*uround*(ABS(tn) + ABS(h));
if ( ABS(tn - tstop) <= troundoff) {
(void) cpGetSolution(cp_mem, tstop, yout, ypout);
tretlast = *tret = tstop;
istate = CP_TSTOP_RETURN;
break;
}
if ( (tn + hprime - tstop)*h > ZERO ) {
hprime = (tstop - tn)*(ONE-FOUR*uround);
eta = hprime/h;
}
}
/* In ONE_STEP mode, copy y and exit loop */
if (task == CP_ONE_STEP) {
istate = CP_SUCCESS;
tretlast = *tret = tn;
cpGetSolution(cp_mem, tn, yout, ypout);
next_q = qprime;
next_h = hprime;
break;
}
} /* end looping for internal steps */
return(istate);
}
/*-----------------------------------------------------------------*/
/*
* CPodeGetDky
*
* This routine computes the k-th derivative of the interpolating
* polynomial at the time t and stores the result in the vector dky.
* The formula is:
* q
* dky = SUM c(j,k) * (t - tn)^(j-k) * h^(-j) * zn[j] ,
* j=k
* where c(j,k) = j*(j-1)*...*(j-k+1), q is the current order, and
* zn[j] is the j-th column of the Nordsieck history array.
*
*/
int CPodeGetDky(void *cpode_mem, realtype t, int k, N_Vector dky)
{
realtype s, c, r;
realtype tfuzz, tp, tn1;
int i, j;
CPodeMem cp_mem;
/* Check all inputs for legality */
if (cpode_mem == NULL) {
cpProcessError(NULL, CP_MEM_NULL, "CPODES", "CPodeGetDky", MSGCP_NO_MEM);
return(CP_MEM_NULL);
}
cp_mem = (CPodeMem) cpode_mem;
if (dky == NULL) {
cpProcessError(cp_mem, CP_BAD_DKY, "CPODES", "CPodeGetDky", MSGCP_NULL_DKY);
return(CP_BAD_DKY);
}
if ((k < 0) || (k > q)) {
cpProcessError(cp_mem, CP_BAD_K, "CPODES", "CPodeGetDky", MSGCP_BAD_K);
return(CP_BAD_K);
}
/* Allow for some slack */
tfuzz = FUZZ_FACTOR * uround * (ABS(tn) + ABS(hu));
if (hu < ZERO) tfuzz = -tfuzz;
tp = tn - hu - tfuzz;
tn1 = tn + tfuzz;
if ((t-tp)*(t-tn1) > ZERO) {
cpProcessError(cp_mem, CP_BAD_T, "CPODES", "CPodeGetDky", MSGCP_BAD_T, t, tn-hu, tn);
return(CP_BAD_T);
}
/* Sum the differentiated interpolating polynomial */
s = (t - tn) / h;
for (j=q; j >= k; j--) {
c = ONE;
for (i=j; i >= j-k+1; i--) c *= i;
if (j == q) {
N_VScale(c, zn[q], dky);
} else {
N_VLinearSum(c, zn[j], s, dky, dky);
}
}
if (k == 0) return(CP_SUCCESS);
r = RPowerI(h,-k);
N_VScale(r, dky, dky);
return(CP_SUCCESS);
}
/*
* CPodeGetQuad
*
* This routine extracts quadrature solution into yQout.
* This is just a wrapper that calls CPodeGetQuadDky with k=0
*/
int CPodeGetQuad(void *cpode_mem, realtype t, N_Vector yQout)
{
return(CPodeGetQuadDky(cpode_mem,t,0,yQout));
}
/*
* CPodeGetQuadDky
*
* CPodeQuadDky computes the kth derivative of the yQ function at
* time t, where tn-hu <= t <= tn, tn denotes the current
* internal time reached, and hu is the last internal step size
* successfully used by the solver. The user may request
* k=0, 1, ..., qu, where qu is the current order.
* The derivative vector is returned in dky. This vector
* must be allocated by the caller. It is only legal to call this
* function after a successful return from CPode with quadrature
* computation enabled.
*/
int CPodeGetQuadDky(void *cpode_mem, realtype t, int k, N_Vector dkyQ)
{
realtype s, c, r;
realtype tfuzz, tp, tn1;
int i, j;
CPodeMem cp_mem;
/* Check all inputs for legality */
if (cpode_mem == NULL) {
cpProcessError(NULL, CP_MEM_NULL, "CPODES", "CPodeGetQuadDky", MSGCP_NO_MEM);
return(CP_MEM_NULL);
}
cp_mem = (CPodeMem) cpode_mem;
if(quadr != TRUE) {
cpProcessError(cp_mem, CP_NO_QUAD, "CPODES", "CPodeGetQuadDky", MSGCP_NO_QUAD);
return(CP_NO_QUAD);
}
if (dkyQ == NULL) {
cpProcessError(cp_mem, CP_BAD_DKY, "CPODES", "CPodeGetQuadDky", MSGCP_NULL_DKY);
return(CP_BAD_DKY);
}
if ((k < 0) || (k > q)) {
cpProcessError(cp_mem, CP_BAD_K, "CPODES", "CPodeGetQuadDky", MSGCP_BAD_K);
return(CP_BAD_K);
}
/* Allow for some slack */
tfuzz = FUZZ_FACTOR * uround * (ABS(tn) + ABS(hu));
if (hu < ZERO) tfuzz = -tfuzz;
tp = tn - hu - tfuzz;
tn1 = tn + tfuzz;
if ((t-tp)*(t-tn1) > ZERO) {
cpProcessError(cp_mem, CP_BAD_T, "CPODES", "CPodeGetQuadDky", MSGCP_BAD_T);
return(CP_BAD_T);
}
/* Sum the differentiated interpolating polynomial */
s = (t - tn) / h;
for (j=q; j >= k; j--) {
c = ONE;
for (i=j; i >= j-k+1; i--) c *= i;
if (j == q) {
N_VScale(c, znQ[q], dkyQ);
} else {
N_VLinearSum(c, znQ[j], s, dkyQ, dkyQ);
}
}
if (k == 0) return(CP_SUCCESS);
r = RPowerI(h,-k);
N_VScale(r, dkyQ, dkyQ);
return(CP_SUCCESS);
}
/*
* CPodeFree
*
* This routine frees the problem memory allocated by CPodeInit.
* Such memory includes all the vectors allocated by cpAllocVectors,
* and the memory lmem for the linear solver (deallocated by a call
* to lfree).
*/
void CPodeFree(void **cpode_mem)
{
CPodeMem cp_mem;
if (*cpode_mem == NULL) return;
cp_mem = (CPodeMem) (*cpode_mem);
if (cp_mem->cp_MallocDone) cpFreeVectors(cp_mem);
CPodeQuadFree(cp_mem);
if (nls_type == CP_NEWTON && cp_mem->cp_lfree != NULL)
cp_mem->cp_lfree(cp_mem);
if (cp_mem->cp_lfreeP != NULL)
cp_mem->cp_lfreeP(cp_mem);
if (cp_mem->cp_rootMallocDone) cpRootFree(cp_mem);
if (cp_mem->cp_projMallocDone) cpProjFree(cp_mem);
free(*cpode_mem);
*cpode_mem = NULL;
}
/*
* CPodeQuadFree
*
* CPodeQuadFree frees the problem memory in cpode_mem allocated
* for quadrature integration. Its only argument is the pointer
* cpode_mem returned by CPodeCreate.
*/
void CPodeQuadFree(void *cpode_mem)
{
CPodeMem cp_mem;
if (cpode_mem == NULL) return;
cp_mem = (CPodeMem) cpode_mem;
if(quadMallocDone) {
cpQuadFree(cp_mem);
quadMallocDone = FALSE;
quadr = FALSE;
}
}
/*
* =================================================================
* PRIVATE FUNCTIONS
* =================================================================
*/
/*
* -----------------------------------------------------------------
* Memory allocation/deallocation and initialization functions
* -----------------------------------------------------------------
*/
/*
* cpCheckNvector
* This routine checks if all required vector operations are present.
* If any of them is missing it returns FALSE.
*/
static booleantype cpCheckNvector(N_Vector tmpl)
{
if((tmpl->ops->nvclone == NULL) ||
(tmpl->ops->nvdestroy == NULL) ||
(tmpl->ops->nvlinearsum == NULL) ||
(tmpl->ops->nvconst == NULL) ||
(tmpl->ops->nvprod == NULL) ||
(tmpl->ops->nvdiv == NULL) ||
(tmpl->ops->nvscale == NULL) ||
(tmpl->ops->nvabs == NULL) ||
(tmpl->ops->nvinv == NULL) ||
(tmpl->ops->nvaddconst == NULL) ||
(tmpl->ops->nvmaxnorm == NULL) ||
(tmpl->ops->nvwrmsnorm == NULL) ||
(tmpl->ops->nvmin == NULL))
return(FALSE);
else
return(TRUE);
}
/*
* cpAllocVectors
*
* This routine allocates the CPODES vectors ewt, acor, tempv, ftemp,
* and zn[0], ..., zn[maxord]. If tol_type=CP_SV, it also allocates
* space for Vabstol. If all memory allocations are successful,
* cpAllocVectors returns TRUE. Otherwise all allocated memory is
* freed and cpAllocVectors returns FALSE. This routine also sets the
* optional outputs lrw and liw, which are (respectively) the lengths
* of the real and integer work spaces allocated here.
*/
static booleantype cpAllocVectors(CPodeMem cp_mem, N_Vector tmpl, int tol)
{
int i, j;
/* Allocate ewt, acor, tempv, ftemp */
ewt = N_VClone(tmpl);
if (ewt == NULL) return(FALSE);
acor = N_VClone(tmpl);
if (acor == NULL) {
N_VDestroy(ewt);
return(FALSE);
}
tempv = N_VClone(tmpl);
if (tempv == NULL) {
N_VDestroy(ewt);
N_VDestroy(acor);
return(FALSE);
}
ftemp = N_VClone(tmpl);
if (ftemp == NULL) {
N_VDestroy(tempv);
N_VDestroy(ewt);
N_VDestroy(acor);
return(FALSE);
}
/* Allocate zn[0] ... zn[qmax] */
for (j=0; j <= qmax; j++) {
zn[j] = N_VClone(tmpl);
if (zn[j] == NULL) {
N_VDestroy(ewt);
N_VDestroy(acor);
N_VDestroy(tempv);
N_VDestroy(ftemp);
for (i=0; i < j; i++) N_VDestroy(zn[i]);
return(FALSE);
}
}
/* Update solver workspace lengths */
lrw += (qmax + 5)*lrw1;
liw += (qmax + 5)*liw1;
if (tol == CP_SV) {
Vabstol = N_VClone(tmpl);
if (Vabstol == NULL) {
N_VDestroy(ewt);
N_VDestroy(acor);
N_VDestroy(tempv);
N_VDestroy(ftemp);
for (i=0; i <= qmax; i++) N_VDestroy(zn[i]);
return(FALSE);
}
lrw += lrw1;
liw += liw1;
cp_mem->cp_VabstolMallocDone = TRUE;
}
/* Store the value of qmax used here */
cp_mem->cp_qmax_alloc = qmax;
return(TRUE);
}
/*
* cpFreeVectors
*
* This routine frees the CPODES vectors allocated in cpAllocVectors.
*/
static void cpFreeVectors(CPodeMem cp_mem)
{
int j, maxord;
maxord = cp_mem->cp_qmax_alloc;
N_VDestroy(ewt);
N_VDestroy(acor);
N_VDestroy(tempv);
N_VDestroy(ftemp);
for(j=0; j <= maxord; j++) N_VDestroy(zn[j]);
lrw -= (maxord + 5)*lrw1;
liw -= (maxord + 5)*liw1;
if (cp_mem->cp_VabstolMallocDone) {
N_VDestroy(Vabstol);
lrw -= lrw1;
liw -= liw1;
}
}
/*
* cpProjAlloc allocates memory for the internal projection functions.
*/
static booleantype cpProjAlloc(CPodeMem cp_mem, N_Vector c_tmpl, N_Vector s_tmpl)
{
/* Vectors cloned from c_tmpl (length M) */
ctol = N_VClone(c_tmpl);
if (ctol == NULL) return(FALSE);
ctemp = N_VClone(c_tmpl);
if (ctemp == NULL) {
N_VDestroy(ctol);
return(FALSE);
}
tempvP1 = N_VClone(c_tmpl);
if (tempvP1 == NULL) {
N_VDestroy(ctol);
N_VDestroy(ctemp);
return(FALSE);
}
tempvP2 = N_VClone(c_tmpl);
if (tempvP2 == NULL) {
N_VDestroy(ctol);
N_VDestroy(ctemp);
N_VDestroy(tempvP1);
return(FALSE);
}
/* Vectors cloned from s_tmpl (length N) */
acorP = N_VClone(s_tmpl);
if (acorP == NULL) {
N_VDestroy(ctol);
N_VDestroy(ctemp);
N_VDestroy(tempvP1);
N_VDestroy(tempvP2);
return(FALSE);
}
yC = N_VClone(s_tmpl);
if (yC == NULL) {
N_VDestroy(ctol);
N_VDestroy(ctemp);
N_VDestroy(tempvP1);
N_VDestroy(tempvP2);
N_VDestroy(acorP);
return(FALSE);
}
errP = N_VClone(s_tmpl);
if (errP == NULL) {
N_VDestroy(ctol);
N_VDestroy(ctemp);
N_VDestroy(tempvP1);
N_VDestroy(tempvP2);
N_VDestroy(acorP);
N_VDestroy(yC);
return(FALSE);
}
return(TRUE);
}
/*
* cpProjFree frees the memory allocated in cpProjAlloc.
*/
static void cpProjFree(CPodeMem cp_mem)
{
N_VDestroy(ctol);
N_VDestroy(ctemp);
N_VDestroy(tempvP1);
N_VDestroy(tempvP2);
N_VDestroy(acorP);
N_VDestroy(yC);
N_VDestroy(errP);
lrw -= lrw1;
liw -= liw1;
}
/*
* cpQuadAlloc allocates memory for the quadrature integration
*
* NOTE: Space for ewtQ is allocated even when errconQ=FALSE,
* although in this case, ewtQ is never used. The reason for this
* decision is to allow the user to re-initialize the quadrature
* computation with errconQ=TRUE, after an initialization with
* errconQ=FALSE, without new memory allocation within
* CPodeQuadReInit.
*/
static booleantype cpQuadAlloc(CPodeMem cp_mem, N_Vector q_tmpl)
{
int i, j;
/* Allocate ewtQ */
ewtQ = N_VClone(q_tmpl);
if (ewtQ == NULL) {
return(FALSE);
}
/* Allocate acorQ */
acorQ = N_VClone(q_tmpl);
if (acorQ == NULL) {
N_VDestroy(ewtQ);
return(FALSE);
}
/* Allocate yQ */
yQ = N_VClone(q_tmpl);
if (yQ == NULL) {
N_VDestroy(ewtQ);
N_VDestroy(acorQ);
return(FALSE);
}
/* Allocate tempvQ */
tempvQ = N_VClone(q_tmpl);
if (tempvQ == NULL) {
N_VDestroy(ewtQ);
N_VDestroy(acorQ);
N_VDestroy(yQ);
return(FALSE);
}
/* Allocate zQn[0] ... zQn[maxord] */
for (j=0; j <= qmax; j++) {
znQ[j] = N_VClone(q_tmpl);
if (znQ[j] == NULL) {
N_VDestroy(ewtQ);
N_VDestroy(acorQ);
N_VDestroy(yQ);
N_VDestroy(tempvQ);
for (i=0; i < j; i++) N_VDestroy(znQ[i]);
return(FALSE);
}
}
/* Store the value of qmax used here */
cp_mem->cp_qmax_allocQ = qmax;
/* Update solver workspace lengths */
lrw += (qmax + 5)*lrw1Q;
liw += (qmax + 5)*liw1Q;
return(TRUE);
}
/*
* cpQuadFree frees the memory allocated in cpQuadAlloc.
*/
static void cpQuadFree(CPodeMem cp_mem)
{
int j, maxord;
maxord = cp_mem->cp_qmax_allocQ;
N_VDestroy(ewtQ);
N_VDestroy(acorQ);
N_VDestroy(yQ);
N_VDestroy(tempvQ);
for (j=0; j<=maxord; j++) N_VDestroy(znQ[j]);
lrw -= (maxord + 5)*lrw1Q;
liw -= (maxord + 5)*liw1Q;
if (cp_mem->cp_VabstolQMallocDone) {
N_VDestroy(VabstolQ);
lrw -= lrw1Q;
liw -= liw1Q;
}
cp_mem->cp_VabstolQMallocDone = FALSE;
}
/*
* cpInitialSetup
*
* This routine performs input consistency checks at the first step.
* If needed, it also checks the linear solver module and calls the
* linear solver initialization routine.
*/
static int cpInitialSetup(CPodeMem cp_mem)
{
int ier;
/* Did the user provide efun? */
if (tol_type != CP_WF) {
efun = cpEwtSet;
e_data = (void *)cp_mem;
} else {
if (efun == NULL) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "cpInitialSetup", MSGCP_NO_EFUN);
return(CP_ILL_INPUT);
}
}
/* Evaluate error weights at initial time */
ier = efun(zn[0], ewt, e_data);
if (ier != 0) {
if (tol_type == CP_WF) cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "cpInitialSetup", MSGCP_EWT_FAIL);
else cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "cpInitialSetup", MSGCP_BAD_EWT);
return(CP_ILL_INPUT);
}
/* Evaluate quadrature error weights */
if (quadr && errconQ) {
ier = cpQuadEwtSet(cp_mem, znQ[0], ewtQ);
if (ier != 0) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "CPInitialSetup", MSGCP_BAD_EWTQ);
return(CP_ILL_INPUT);
}
}
if (!quadr) errconQ = FALSE;
/* Check if lsolve function exists (if needed)
and call linit function (if it exists) */
if (nls_type == CP_NEWTON) {
if (cp_mem->cp_lsolve == NULL) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "cpInitialSetup", MSGCP_LSOLVE_NULL);
return(CP_ILL_INPUT);
}
if (cp_mem->cp_linit != NULL) {
ier = cp_mem->cp_linit(cp_mem);
if (ier != 0) {
cpProcessError(cp_mem, CP_LINIT_FAIL, "CPODES", "cpInitialSetup", MSGCP_LINIT_FAIL);
return(CP_LINIT_FAIL);
}
}
}
/* Tests related to coordinate projection */
if (proj_enabled) {
switch (proj_type) {
case CP_PROJ_USER:
/* Check if user provided the projection function */
if ( pfun == NULL ) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "cpInitialSetup", MSGCP_NO_PFUN);
return(CP_ILL_INPUT);
}
break;
case CP_PROJ_INTERNAL:
/* Check if user provided the constraint function */
if (cfun == NULL) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "cpInitialSetup", MSGCP_NO_CFUN);
return(CP_ILL_INPUT);
}
/* Check lsolveP exists */
if ( cp_mem->cp_lsolveP == NULL) {
cpProcessError(cp_mem, CP_ILL_INPUT, "CPODES", "cpInitialSetup", MSGCP_PLSOLVE_NULL);
return(CP_ILL_INPUT);
}
/* Call linitP if it exists */
if ( cp_mem->cp_linitP != NULL ) {
ier = cp_mem->cp_linitP(cp_mem);
if (ier != 0) {
cpProcessError(cp_mem, CP_LINIT_FAIL, "CPODES", "cpInitialSetup", MSGCP_PLINIT_FAIL);
return(CP_PLINIT_FAIL);
}
}
break;
}
}
return(CP_SUCCESS);
}
/*
* -----------------------------------------------------------------
* Initial step size evaluation functions
* -----------------------------------------------------------------
*/
/*
* cpHin
*
* This routine computes a tentative initial step size h0.
* If tout is too close to tn (= t0), then cpHin returns CP_TOO_CLOSE
* and h remains uninitialized.
*
*/
static int cpHin(CPodeMem cp_mem, realtype tout)
{
int sign, retval;
realtype hlb, hub, hg, h0;
realtype tdiff, tdist, tround;
/* If tout is too close to tn, give up */
if ((tdiff = tout-tn) == ZERO) return(CP_TOO_CLOSE);
sign = (tdiff > ZERO) ? 1 : -1;
tdist = ABS(tdiff);
tround = uround * MAX(ABS(tn), ABS(tout));
if (tdist < TWO*tround) return(CP_TOO_CLOSE);
/* Set lower and upper bounds on h0*/
hlb = HLB_FACTOR * tround;
hub = cpUpperBoundH0(cp_mem, tdist);
/* Compute geometric mean of lower and upper bounds */
hg = RSqrt(hlb*hub);
/* If the bounds cross each other, use hg as initial step size */
if (hub < hlb) {
if (sign == -1) h = -hg;
else h = hg;
return(CP_SUCCESS);
}
/* Estimate initial step size */
if (ode_type == CP_EXPL) retval = cpHinExpl(cp_mem, hlb, hub, sign, &h0);
else retval = cpHinImpl(cp_mem, tdist, &h0);
/* Apply bounds and attach sign */
if (h0 < hlb) h0 = hlb;
if (h0 > hub) h0 = hub;
if (sign == -1) h0 = -h0;
h = h0;
return(retval);
}
/*
* cpUpperBoundH0
*
* This routine sets an upper bound on abs(h0) based on
* tdist = tn - t0 and the values of y[i]/y'[i] and yQ[i]/yQ'[i].
*/
static realtype cpUpperBoundH0(CPodeMem cp_mem, realtype tdist)
{
realtype hub_inv, hubQ_inv, hub;
N_Vector temp1, temp2;
N_Vector tempQ1, tempQ2;
/*
* Bound based on |y0|/|y0'| -- allow at most an increase of
* HUB_FACTOR in y0 (based on a forward Euler step). The weight
* factor is used as a safeguard against zero components in y0.
*/
temp1 = tempv;
temp2 = acor;
N_VAbs(zn[0], temp2);
efun(zn[0], temp1, e_data);
N_VInv(temp1, temp1);
N_VLinearSum(HUB_FACTOR, temp2, ONE, temp1, temp1);
N_VAbs(zn[1], temp2);
N_VDiv(temp2, temp1, temp1);
hub_inv = N_VMaxNorm(temp1);
/* Bound based on |yQ|/|yQ'| */
if (quadr && errconQ) {
tempQ1 = tempvQ;
tempQ2 = acorQ;
N_VAbs(znQ[0], tempQ2);
cpQuadEwtSet(cp_mem, znQ[0], tempQ1);
N_VInv(tempQ1, tempQ1);
N_VLinearSum(HUB_FACTOR, tempQ2, ONE, tempQ1, tempQ1);
N_VAbs(znQ[1], tempQ2);
N_VDiv(tempQ2, tempQ1, tempQ1);
hubQ_inv = N_VMaxNorm(tempQ1);
if (hubQ_inv > hub_inv) hub_inv = hubQ_inv;
}
/*
* bound based on tdist -- allow at most a step of magnitude
* HUB_FACTOR * tdist
*/
hub = HUB_FACTOR*tdist;
/* Use the smaler of the two */
if (hub*hub_inv > ONE) hub = ONE/hub_inv;
return(hub);
}
/*
* cpHinExpl
*
* This routine computes a tentative initial step size h0.
* If the ODE function fails unrecoverably, cpHinExpl returns CP_ODEFUNC_FAIL.
* If the ODE function fails recoverably too many times and recovery is
* not possible, cpHinExpl returns CP_REPTD_ODEFUNC_ERR.
* Otherwise, cpHinExpl sets h0 to the chosen value and returns CP_SUCCESS.
*
* The algorithm used seeks to find h0 as a solution of
* (WRMS norm of (h0^2 ypp / 2)) = 1,
* where ypp = estimated second derivative of y.
*
* We start with an initial estimate equal to the geometric mean of the
* lower and upper bounds on the step size.
*
* Loop up to H_MAXITERS times to find h0.
* Stop if new and previous values differ by a factor < 2.
* Stop if hnew/hg > 2 after one iteration, as this probably means
* that the ypp value is bad because of cancellation error.
*
* For each new proposed hg, we allow H_MAXITERS attempts to
* resolve a possible recoverable failure from f() by reducing
* the proposed stepsize by a factor of 0.2. If a legal stepsize
* still cannot be found, fall back on a previous value if possible,
* or else return CP_REPTD_ODEFUNC_ERR.
*
* Finally, we apply a bias (0.5).
*/
static int cpHinExpl(CPodeMem cp_mem, realtype hlb, realtype hub, int sign, realtype *h0)
{
int retval, count1, count2;
realtype hg, hgs, hs, hnew, hrat, yppnorm;
booleantype hgOK, hnewOK;
/* Initial estimate = geometric mean of computed bounds */
hg = RSqrt(hlb*hub);
/* Outer loop */
hnewOK = FALSE;
hs = hg; /* safeguard against 'uninitialized variable' warning */
for(count1 = 1; count1 <= H_MAXITERS; count1++) {
/* Attempts to estimate ypp */
hgOK = FALSE;
for (count2 = 1; count2 <= H_MAXITERS; count2++) {
hgs = hg*sign;
retval = cpYppNorm(cp_mem, hgs, &yppnorm);
/* If fun() or qfun() failed unrecoverably, give up */
if (retval < 0) return(retval);
/* If successful, we can use ypp */
if (retval == CP_SUCCESS) {hgOK = TRUE; break;}
/* fun() or qfun() failed recoverably; cut step size and test it again */
hg *= PT2;
}
/* If fun() or qfun() failed recoverably H_MAXITERS times */
if (!hgOK) {
/* Exit if this is the first or second pass. No recovery possible */
if (count1 <= 2) {
if (retval == ODEFUNC_RECVR) return(CP_REPTD_ODEFUNC_ERR);
if (retval == QUADFUNC_RECVR) return(CP_REPTD_QUADFUNC_ERR);
}
/* We have a fall-back option. The value hs is a previous hnew which
passed through f(). Use it and break */
hnew = hs;
break;
}
/* The proposed step size is feasible. Save it. */
hs = hg;
/* If the stopping criteria was met, or if this is the last pass, stop */
if ( (hnewOK) || (count1 == H_MAXITERS)) {hnew = hg; break;}
/* Propose new step size */
hnew = (yppnorm*hub*hub > TWO) ? RSqrt(TWO/yppnorm) : RSqrt(hg*hub);
hrat = hnew/hg;
/* Accept hnew if it does not differ from hg by more than a factor of 2 */
if ((hrat > HALF) && (hrat < TWO)) {
hnewOK = TRUE;
}
/* After one pass, if ypp seems to be bad, use fall-back value. */
if ((count1 > 1) && (hrat > TWO)) {
hnew = hg;
hnewOK = TRUE;
}
/* Send this value back through f() */
hg = hnew;
}
/* Apply bias factor */
*h0 = H_BIAS*hnew;
return(CP_SUCCESS);
}
/*
* cpYppNorm
*
* When the ODE is given in explicit form, this routine computes
* an estimate of the second derivative of y using a difference
* quotient, and returns its WRMS norm.
*/
static int cpYppNorm(CPodeMem cp_mem, realtype hg, realtype *yppnorm)
{
int retval;
/* y <- h*y'(t) + y(t) */
N_VLinearSum(hg, zn[1], ONE, zn[0], y);
/* tempv <- fun(t+h, h*y'(t)+y(t)) */
retval = fe(tn+hg, y, tempv, f_data);
nfe++;
if (retval < 0) return(CP_ODEFUNC_FAIL);
if (retval > 0) return(ODEFUNC_RECVR);
/* tempvQ <- qfun(t+h, h*y'(t)+y(t)) */
if (quadr && errconQ) {
retval = qfun(tn+hg, y, tempvQ, q_data);
nqe++;
if (retval < 0) return(CP_QUADFUNC_FAIL);
if (retval > 0) return(QUADFUNC_RECVR);
}
/* tempv <- fun(t+h, h*y'(t)+y(t)) - y'(t) */
/* tempv <- ypp */
N_VLinearSum(ONE, tempv, -ONE, zn[1], tempv);
N_VScale(ONE/hg, tempv, tempv);
/* tempvQ <- qfun(t+h, h*y'(t)+y(t)) - yQ'(t) */
/* tempvQ <- yQdd */
if (quadr && errconQ) {
N_VLinearSum(ONE, tempvQ, -ONE, znQ[1], tempvQ);
N_VScale(ONE/hg, tempvQ, tempvQ);
}
/* Estimate ||y''|| */
*yppnorm = N_VWrmsNorm(tempv, ewt);
if (quadr && errconQ) *yppnorm = cpQuadUpdateNorm(cp_mem, *yppnorm, tempvQ, ewtQ);
return(CP_SUCCESS);
}
/*
* cpHinImpl
*
* For ODE systems given in implicit form, use
* h0 = min ( 0.001 * tdist , 0.5 / ||yp(t0)||_wrms , 0.5 / ||yQp(t0)||_wrms )
*/
static int cpHinImpl(CPodeMem cp_mem, realtype tdist, realtype *h0)
{
realtype ypnorm;
*h0 = PT001 * tdist;
ypnorm = N_VWrmsNorm(zn[1], ewt);
if (quadr && errconQ) ypnorm = cpQuadUpdateNorm(cp_mem, ypnorm, znQ[1], ewtQ);
if (ypnorm > HALF/(*h0)) *h0 = HALF/ypnorm;
return(CP_SUCCESS);
}
/*
* -----------------------------------------------------------------
* Main step function
* -----------------------------------------------------------------
*/
/*
* cpStep
*
* This routine performs one internal cpode step, from tn to tn + h.
* It calls other routines to do all the work.
*
* The main operations done here are as follows:
* - preliminary adjustments if a new step size was chosen;
* - prediction of the Nordsieck history array zn at tn + h;
* - setting of multistep method coefficients and test quantities;
* - solution of the nonlinear system;
* - testing the local error;
* - updating zn and other state data if successful;
* - resetting stepsize and order for the next step.
* - if SLDET is on, check for stability, reduce order if necessary.
* On a failure in the nonlinear system solution or error test, the
* step may be reattempted, depending on the nature of the failure.
*/
static int cpStep(CPodeMem cp_mem)
{
realtype saved_t, dsm, dsmQ;
int ncf, npf, nef;
int nflag, kflag, pflag, eflag, qflag;
booleantype doProjection;
saved_t = tn;
ncf = npf = nef = 0;
nflag = FIRST_CALL;
#ifdef CPODES_DEBUG
printf("\nStep # %ld t = %lg\n",nst,tn);
#endif
/* If the step size was changed, adjust method parameters */
if ((nst > 0) && (hprime != h)) {
#ifdef CPODES_DEBUG
printf(" Adjust parameters\n");
printf(" qprime = %d hprime = %g\n", qprime, hprime);
#endif
cpAdjustParams(cp_mem);
#ifdef CPODES_DEBUG
printf(" Done adjust parameters\n");
#endif
}
/* Looping point for attempts to take a step */
loop {
/* Prediction */
cpPredict(cp_mem);
cpSet(cp_mem);
#ifdef CPODES_DEBUG
printf(" Predict\n");
#endif
/* Solve the nonlinear system to correct the states */
#ifdef CPODES_DEBUG
printf(" Nonlinear solver\n");
#endif
kflag = cpNls(cp_mem, nflag, saved_t, &ncf);
#ifdef CPODES_DEBUG
printf(" Nonlinear solver return flag = %d\n",kflag);
#endif
if (kflag == PREDICT_AGAIN) {
/* If we need to predict again, set nflag=PREV_CONV_FAIL */
nflag = PREV_CONV_FAIL;
continue;
} else if (kflag != CP_SUCCESS) {
/* Recovery is not possible. */
return(kflag);
}
/* Nonlinear solve successful */
ncf = 0;
/* Do we need to perform projection? */
#ifdef CPODES_DEBUG
printf(" Perform projection? ");
#endif
doProjection = proj_enabled && (proj_freq > 0) &&
( (nst==0) || (nst >= nstlprj + proj_freq) );
applyProj = FALSE;
#ifdef CPODES_DEBUG
printf("%d\n",doProjection);
#endif
/* If needed, perform the projection step */
if ( doProjection ) {
#ifdef CPODE_DEBUG
printf(" Projection\n");
#endif
pflag = cpDoProjection(cp_mem, saved_t, &npf);
#ifdef CPODES_DEBUG
printf(" Projection return flag = %d\n",pflag);
#endif
if (pflag == PREDICT_AGAIN) {
/* If we need to predict again, set nflag=PREV_PROJ_FAIL */
nflag = PREV_PROJ_FAIL;
continue;
} else if (pflag != CP_SUCCESS) {
/* Recovery is not possible. */
return(pflag);
}
/* Projection successful */
npf = 0;
}
/* Perform error test */
#ifdef CPODES_DEBUG
printf(" Error test\n");
#endif
eflag = cpDoErrorTest(cp_mem, saved_t, acnrm, &nef, &dsm);
#ifdef CPODES_DEBUG
printf(" Error test return flag = %d\n",eflag);
#endif
if (eflag == PREDICT_AGAIN) {
/* If we need to predict again set nflag=PREV_ERR_FAIL */
nflag = PREV_ERR_FAIL;
continue;
} else if (eflag != CP_SUCCESS) {
/* Recovery is not possible */
return(eflag);
}
/* State error test successful */
nef = 0;
/* Deal with quadrature variables if needed */
if (quadr) {
/* Correct quadrature variables */
#ifdef CPODES_DEBUG
printf(" Correct quadratures\n");
#endif
qflag = cpQuadNls(cp_mem, saved_t, &ncf);
#ifdef CPODES_DEBUG
printf(" Correct quadratures return flag = %d\n",qflag);
#endif
if (qflag == PREDICT_AGAIN) {
/* If we need to predict again, set nflag=PREV_CONV_FAIL */
nflag = PREV_CONV_FAIL;
continue;
} else if (qflag != CP_SUCCESS) {
/* Recovery is not possible. */
return(qflag);
}
/* Quadrature correction successful */
ncf = 0;
/* If needed, perform error test on quadrature variables */
if (errconQ) {
#ifdef CPODES_DEBUG
printf(" Quadratures error test\n");
#endif
eflag = cpDoErrorTest(cp_mem, saved_t, acnrmQ, &nef, &dsmQ);
#ifdef CPODES_DEBUG
printf(" Quadratures error test return flag = %d\n",eflag);
#endif
if (eflag == PREDICT_AGAIN) {
/* If we need to predict again set nflag=PREV_ERR_FAIL */
nflag = PREV_ERR_FAIL;
continue;
} else if (eflag != CP_SUCCESS) {
/* Recovery is not possible */
return(eflag);
}
/* Quadrature error test successful */
nef = 0;
/* Update 'dsm' with 'dsmQ' (to be used in cpPrepareNextStep) */
dsm = cpQuadUpdateDsm(cp_mem, dsm, dsmQ);
}
}
/* Everything went fine. Make final updates and exit loop */
nstlprj = nst;
break;
}
/* Apply corrections to Nordsieck history arrays,
* update data, and
* consider change of step and/or order. */
cpCorrect(cp_mem);
cpCompleteStep(cp_mem);
cpPrepareNextStep(cp_mem, dsm);
/* If Stablilty Limit Detection is turned on
* check if order must be reduced */
if (sldeton) cpBDFStab(cp_mem);
etamax = (nst <= SMALL_NST) ? ETAMX2 : ETAMX3;
/* Finally, we rescale the acor array to be
* the estimated local error vector. */
N_VScale(ONE/tq[2], acor, acor);
if (quadr) N_VScale(ONE/tq[2], acorQ, acorQ);
return(CP_SUCCESS);
}
/*
* cpGetSolution
*
* This routine evaluates y(t) and y'(t) as the value and derivative of
* the interpolating polynomial at the independent variable t, and stores
* the results in the vectors yret and ypret.
*
* The formulas are:
* q
* yret = zn[0] + SUM (t - tn)^j * h^(-j) * zn[j] ,
* j=1
* and
* q
* ypret = SUM j * (t - tn)^(j-1) * h^(-j) * zn[j] ,
* j=1
*
* This function is called by CPode() with t = tout, t = tn, or t = tstop.
*
*/
int cpGetSolution(void *cpode_mem, realtype t, N_Vector yret, N_Vector ypret)
{
realtype s, c, d;
realtype tfuzz, tp, tn1;
int j;
CPodeMem cp_mem;
cp_mem = (CPodeMem) cpode_mem;
/* Allow for some slack */
tfuzz = FUZZ_FACTOR * uround * (ABS(tn) + ABS(hu));
if (hu < ZERO) tfuzz = -tfuzz;
tp = tn - hu - tfuzz;
tn1 = tn + tfuzz;
if ((t-tp)*(t-tn1) > ZERO) return(CP_BAD_T);
/* Initialize yret = zn[0] and ypret = 0 */
N_VScale(ONE, zn[0], yret);
N_VConst(ZERO, ypret);
/* Accumulate multiples of columns zn[j] into yret and ypret. */
s = (t - tn) / h;
c = s;
d = ONE/h;
for (j=1; j<=q; j++) {
N_VLinearSum(ONE, yret, c, zn[j], yret);
N_VLinearSum(ONE, ypret, d, zn[j], ypret);
d = (j+1)*c/h;
c *= s;
}
return(CP_SUCCESS);
}
/*
* -----------------------------------------------------------------
* Functions acting on the Nordsieck history array
* -----------------------------------------------------------------
*/
/*
* cpPredict
*
* This routine advances tn by the tentative step size h, and computes
* the predicted array z_n(0), which is overwritten on zn.
* The prediction of zn is done by repeated additions.
* In TSTOP mode, it is possible for tn + h to be past tstop by roundoff,
* and in that case, we reset tn (after incrementing by h) to tstop.
*/
static void cpPredict(CPodeMem cp_mem)
{
int j, k;
tn += h;
if (istop) {
if ((tn - tstop)*h > ZERO) tn = tstop;
}
for (k = 1; k <= q; k++)
for (j = q; j >= k; j--)
N_VLinearSum(ONE, zn[j-1], ONE, zn[j], zn[j-1]);
if (quadr) {
for (k = 1; k <= q; k++)
for (j = q; j >= k; j--)
N_VLinearSum(ONE, znQ[j-1], ONE, znQ[j], znQ[j-1]);
}
}
/*
* cpRescale
*
* This routine rescales the Nordsieck array by multiplying the
* jth column zn[j] by eta^j, j = 1, ..., q. Then the value of
* h is rescaled by eta, and hscale is reset to h.
*
* This function is used in cpNls, cpDoProjection, and cpDoerrorTest
*/
void cpRescale(CPodeMem cp_mem)
{
int j;
realtype factor;
factor = eta;
for (j=1; j <= q; j++) {
N_VScale(factor, zn[j], zn[j]);
if (quadr) N_VScale(factor, znQ[j], znQ[j]);
factor *= eta;
}
h = hscale * eta;
next_h = h;
hscale = h;
nscon = 0;
}
/*
* cpRestore
*
* This routine restores the value of tn to saved_t and undoes the
* prediction. After execution of cpRestore, the Nordsieck array zn has
* the same values as before the call to cpPredict.
*
* This function is used in cpNls, cpDoProjection, and cpDoerrorTest
*/
void cpRestore(CPodeMem cp_mem, realtype saved_t)
{
int j, k;
tn = saved_t;
for (k = 1; k <= q; k++)
for (j = q; j >= k; j--)
N_VLinearSum(ONE, zn[j-1], -ONE, zn[j], zn[j-1]);
if (quadr) {
for (k = 1; k <= q; k++)
for (j = q; j >= k; j--)
N_VLinearSum(ONE, znQ[j-1], -ONE, znQ[j], znQ[j-1]);
}
}
/*
* cpCorrect
*
* This routine applies the corrections to the zn array.
* The correction to zn is done by repeated additions.
*/
static void cpCorrect(CPodeMem cp_mem)
{
int j;
for (j=0; j <= q; j++)
N_VLinearSum(l[j], acor, ONE, zn[j], zn[j]);
if (applyProj) {
for (j=0; j <= q; j++)
N_VLinearSum(p[j], acorP, ONE, zn[j], zn[j]);
}
if (quadr) {
for (j=0; j <= q; j++)
N_VLinearSum(l[j], acorQ, ONE, znQ[j], znQ[j]);
}
}
/*
* -----------------------------------------------------------------
* Quadrature correction function
* -----------------------------------------------------------------
*/
/*
* cpQuadNls
*
* This function attempts to correct the quadrature variables.
*
* The only way this function can fail is through the user's quad
* function. If quad fails unrecoverably we return immediately. If
* it fails with a recoverable error, we consider a new prediction.
*
* We count any failure here as a convergence failure (we do not
* distinguish these from convergence failures in the nonlinear
* solver for the state correction).
*
* NOTE: This is technically not a nonlinear solver, but this name is
* used to reflect the similarity to cpNls.
*/
static int cpQuadNls(CPodeMem cp_mem, realtype saved_t, int *ncfPtr)
{
int retval;
/* Save quadrature correction in acorQ */
retval = qfun(tn, y, acorQ, q_data);
nqe++;
if (retval == 0) {
/* Find correction */
N_VLinearSum(h, acorQ, -ONE, znQ[1], acorQ);
N_VScale(rl1, acorQ, acorQ);
/* Compute its WRMS norm */
acnrmQ = N_VWrmsNorm(acorQ, ewtQ);
/* Apply correction to quadrature variables */
N_VLinearSum(ONE, znQ[0], ONE, acorQ, yQ);
return(CP_SUCCESS);
}
/* Increment ncfn and restore zn */
ncfn++;
cpRestore(cp_mem, saved_t);
if (retval < 0) return(CP_QUADFUNC_FAIL);
/* At this point, qfun had a recoverable error; increment ncf */
(*ncfPtr)++;
etamax = ONE;
/* If we had maxncf failures or |h| = hmin,
return CP_REPTD_QUADFUNC_ERR. */
if ((ABS(h) <= hmin*ONEPSM) || (*ncfPtr == maxncf))
return(CP_REPTD_QUADFUNC_ERR);
/* Reduce step size; return to reattempt the step */
eta = MAX(ETACF, hmin / ABS(h));
cpRescale(cp_mem);
return(PREDICT_AGAIN);
}
/*
* -----------------------------------------------------------------
* LMM-related functions
* -----------------------------------------------------------------
*/
/*
* cpAdjustParams
*
* This routine is called when a change in step size was decided upon,
* and it handles the required adjustments to the history array zn.
* If there is to be a change in order, we call cpAdjustOrder and reset
* q, L = q+1, and qwait. Then in any case, we call cpRescale, which
* resets h and rescales the Nordsieck array.
*/
static void cpAdjustParams(CPodeMem cp_mem)
{
if (qprime != q) {
cpAdjustOrder(cp_mem, qprime-q);
q = qprime;
L = q+1;
qwait = L;
}
cpRescale(cp_mem);
}
/*
* cpAdjustOrder
*
* This routine is a high level routine which handles an order
* change by an amount deltaq (= +1 or -1). If a decrease in order
* is requested and q==2, then the routine returns immediately.
* Otherwise cpAdjustAdams or cpAdjustBDF is called to handle the
* order change (depending on the value of lmm_type).
*/
static void cpAdjustOrder(CPodeMem cp_mem, int deltaq)
{
if ((q==2) && (deltaq != 1)) return;
switch(lmm_type){
case CP_ADAMS:
cpAdjustAdams(cp_mem, deltaq);
break;
case CP_BDF:
cpAdjustBDF(cp_mem, deltaq);
break;
}
}
/*
* cpAdjustAdams
*
* This routine adjusts the history array on a change of order q by
* deltaq, in the case that lmm_type == CP_ADAMS.
*/
static void cpAdjustAdams(CPodeMem cp_mem, int deltaq)
{
int i, j;
realtype xi, hsum;
/* On an order increase, set new column of zn to zero and return */
if (deltaq==1) {
N_VConst(ZERO, zn[L]);
if (quadr) N_VConst(ZERO, znQ[L]);
return;
}
/*
* On an order decrease, each zn[j] is adjusted by a multiple of zn[q].
* The coeffs. in the adjustment are the coeffs. of the polynomial:
* x
* q * INT { u * ( u + xi_1 ) * ... * ( u + xi_{q-2} ) } du
* 0
* where xi_j = [t_n - t_(n-j)]/h => xi_0 = 0
*/
for (i=0; i <= qmax; i++) l[i] = ZERO;
l[1] = ONE;
hsum = ZERO;
for (j=1; j <= q-2; j++) {
hsum += tau[j];
xi = hsum / hscale;
for (i=j+1; i >= 1; i--) l[i] = l[i]*xi + l[i-1];
}
for (j=1; j <= q-2; j++) l[j+1] = q * (l[j] / (j+1));
for (j=2; j < q; j++)
N_VLinearSum(-l[j], zn[q], ONE, zn[j], zn[j]);
if (quadr) {
for (j=2; j < q; j++)
N_VLinearSum(-l[j], znQ[q], ONE, znQ[j], znQ[j]);
}
}
/*
* cpAdjustBDF
*
* This is a high level routine which handles adjustments to the
* history array on a change of order by deltaq in the case that
* lmm_type == CP_BDF. cpAdjustBDF calls cpIncreaseBDF if deltaq = +1 and
* cpDecreaseBDF if deltaq = -1 to do the actual work.
*/
static void cpAdjustBDF(CPodeMem cp_mem, int deltaq)
{
switch(deltaq) {
case 1 :
cpIncreaseBDF(cp_mem);
return;
case -1:
cpDecreaseBDF(cp_mem);
return;
}
}
/*
* cpIncreaseBDF
*
* This routine adjusts the history array on an increase in the
* order q in the case that lmm_type == CP_BDF.
* A new column zn[q+1] is set equal to a multiple of the saved
* vector (= acor) in zn[indx_acor]. Then each zn[j] is adjusted by
* a multiple of zn[q+1]. The coefficients in the adjustment are the
* coefficients of the polynomial x*x*(x+xi_1)*...*(x+xi_j),
* where xi_j = [t_n - t_(n-j)]/h.
*/
static void cpIncreaseBDF(CPodeMem cp_mem)
{
realtype alpha0, alpha1, prod, xi, xiold, hsum, A1;
int i, j;
for (i=0; i <= qmax; i++) l[i] = ZERO;
l[2] = alpha1 = prod = xiold = ONE;
alpha0 = -ONE;
hsum = hscale;
if (q > 1) {
for (j=1; j < q; j++) {
hsum += tau[j+1];
xi = hsum / hscale;
prod *= xi;
alpha0 -= ONE / (j+1);
alpha1 += ONE / xi;
for (i=j+2; i >= 2; i--) l[i] = l[i]*xiold + l[i-1];
xiold = xi;
}
}
A1 = (-alpha0 - alpha1) / prod;
/*
* zn[indx_acor] contains the value Delta_n = y_n - y_n(0)
* This value was stored there at the previous successful
* step (in cpCompleteStep)
*
* A1 contains dbar = (1/xi* - 1/xi_q)/prod(xi_j)
*/
N_VScale(A1, zn[indx_acor], zn[L]);
for (j=2; j <= q; j++)
N_VLinearSum(l[j], zn[L], ONE, zn[j], zn[j]);
if (quadr) {
N_VScale(A1, znQ[indx_acor], znQ[L]);
for (j=2; j <= q; j++)
N_VLinearSum(l[j], znQ[L], ONE, znQ[j], znQ[j]);
}
}
/*
* cpDecreaseBDF
*
* This routine adjusts the history array on a decrease in the
* order q in the case that lmm_type == CP_BDF.
* Each zn[j] is adjusted by a multiple of zn[q]. The coefficients
* in the adjustment are the coefficients of the polynomial
* x*x*(x+xi_1)*...*(x+xi_j), where xi_j = [t_n - t_(n-j)]/h.
*/
static void cpDecreaseBDF(CPodeMem cp_mem)
{
realtype hsum, xi;
int i, j;
for (i=0; i <= qmax; i++) l[i] = ZERO;
l[2] = ONE;
hsum = ZERO;
for(j=1; j <= q-2; j++) {
hsum += tau[j];
xi = hsum /hscale;
for (i=j+2; i >= 2; i--) l[i] = l[i]*xi + l[i-1];
}
for(j=2; j < q; j++)
N_VLinearSum(-l[j], zn[q], ONE, zn[j], zn[j]);
if (quadr) {
for (j=2; j < q; j++)
N_VLinearSum(-l[j], znQ[q], ONE, znQ[j], znQ[j]);
}
}
/*
* cpSet
*
* This routine is a high level routine which calls cpSetAdams or
* cpSetBDF to set the coefficients l of the polynomial Lambda
* (used in applying the NLS correction to zn), the coefficients p
* of the polynomial Phi (used in applying the projection correction
* to zn), the test quantity array tq (used in the NLS convergence
* test and in the error test), and the related variables rl1, gamma,
* and gamrat.
*/
static void cpSet(CPodeMem cp_mem)
{
switch(lmm_type) {
case CP_ADAMS:
cpSetAdams(cp_mem);
break;
case CP_BDF:
cpSetBDF(cp_mem);
break;
}
rl1 = ONE / l[1];
gamma = h * rl1;
if (nst == 0) gammap = gamma;
gamrat = (nst > 0) ? gamma / gammap : ONE; /* protect x / x != 1.0 */
}
/*
* cpSetAdams
*
* This routine handles the computation of l, p, and tq for the
* case lmm_type == CP_ADAMS.
*
* The components of the array l are the coefficients of a
* polynomial Lambda(x) = l_0 + l_1 x + ... + l_q x^q, that
* satisfies the following q+1 conditions:
* Lambda(-1) = 0, Lambda(0) = 1
* Lambda'(-xi_i) = 0, i=1,2,...,q-1.
* Here x = [t - t_n] /h and xi_i = [t_n - t_(n-i)] / h.
*
* For the Adams case, the polynomial Phi(x) is identical to Lambda(x)
* and therefore p_i = l_i, i=0,1,2,...,q.
*
* The array tq is set to test quantities used in the convergence
* test, the error test, and the selection of h at a new order.
*/
static void cpSetAdams(CPodeMem cp_mem)
{
realtype m[L_MAX], M[3], hsum;
int i;
if (q == 1) {
l[0] = l[1] = tq[1] = tq[5] = ONE;
tq[2] = TWO;
tq[3] = TWELVE;
tq[4] = nlscoef * tq[2]; /* = 0.1 * tq[2] */
} else {
hsum = cpAdamsStart(cp_mem, m);
M[0] = cpAltSum(q-1, m, 1);
M[1] = cpAltSum(q-1, m, 2);
cpAdamsFinish(cp_mem, m, M, hsum);
}
for(i=0; i<=q; i++) p[i] = l[i];
return;
}
/*
* cpAdamsStart
*
* This routine generates in m[] the coefficients of the product
* polynomial needed for the Adams l and tq coefficients for q > 1.
*/
static realtype cpAdamsStart(CPodeMem cp_mem, realtype m[])
{
realtype hsum, xi_inv, sum;
int i, j;
hsum = h;
m[0] = ONE;
for (i=1; i <= q; i++) m[i] = ZERO;
for (j=1; j < q; j++) {
if ((j==q-1) && (qwait == 1)) {
sum = cpAltSum(q-2, m, 2);
tq[1] = m[q-2] / (q * sum);
}
xi_inv = h / hsum;
for (i=j; i >= 1; i--) m[i] += m[i-1] * xi_inv;
hsum += tau[j];
/* The m[i] are coefficients of product(1 to j) (1 + x/xi_i) */
}
return(hsum);
}
/*
* cpAdamsFinish
*
* This routine completes the calculation of the Adams l and tq.
*/
static void cpAdamsFinish(CPodeMem cp_mem, realtype m[], realtype M[], realtype hsum)
{
int i;
realtype M0_inv, xi, xi_inv;
M0_inv = ONE / M[0];
l[0] = ONE;
for (i=1; i <= q; i++) l[i] = M0_inv * (m[i-1] / i);
xi = hsum / h;
xi_inv = ONE / xi;
tq[2] = xi * M[0] / M[1];
tq[5] = xi / l[q];
if (qwait == 1) {
for (i=q; i >= 1; i--) m[i] += m[i-1] * xi_inv;
M[2] = cpAltSum(q, m, 2);
tq[3] = L * M[0] / M[2];
}
tq[4] = nlscoef * tq[2];
}
/*
* cpAltSum
*
* cpAltSum returns the value of the alternating sum
* sum (i= 0 ... iend) [ (-1)^i * (a[i] / (i + k)) ].
* If iend < 0 then cpAltSum returns 0.
* This operation is needed to compute the integral, from -1 to 0,
* of a polynomial x^(k-1) M(x) given the coefficients of M(x).
*/
static realtype cpAltSum(int iend, realtype a[], int k)
{
int i, sign;
realtype sum;
if (iend < 0) return(ZERO);
sum = ZERO;
sign = 1;
for (i=0; i <= iend; i++) {
sum += sign * (a[i] / (i+k));
sign = -sign;
}
return(sum);
}
/*
* cpSetBDF
*
* This routine computes the coefficients l and tq in the case
* lmm_type == CP_BDF. cpSetBDF calls cpSetTqBDF to set the test
* quantity array tq.
*
* The components of the array l are the coefficients of a
* polynomial Lambda(x) = l_0 + l_1 x + ... + l_q x^q, given by
* q-1
* Lambda(x) = (1 + x / xi*_q) * PRODUCT (1 + x / xi_i)
* i=1
*
* The components of the array p are the coefficients of a
* polynomial Phi(x) = p_0 + p_1 x + ... + p_q x^q, given by
* q
* Phi(x) = PRODUCT (1 + x / xi_i)
* i=1
*
* Here x = [t - t_n] /h and xi_i = [t_n - t_(n-i)] / h.
*
* The array tq is set to test quantities used in the convergence
* test, the error test, and the selection of h at a new order.
*/
static void cpSetBDF(CPodeMem cp_mem)
{
realtype alpha0, alpha0_hat, xi_inv, xistar_inv, hsum;
int i,j;
l[0] = l[1] = ONE;
p[0] = p[1] = ONE;
xi_inv = xistar_inv = ONE;
for (i=2; i <= q; i++) {
l[i] = ZERO;
p[i] = ZERO;
}
alpha0 = alpha0_hat = -ONE;
hsum = h;
if (q > 1) {
for (j=2; j < q; j++) {
hsum += tau[j-1];
xi_inv = h / hsum;
alpha0 -= ONE / j;
/* The l[i] and p[i] are coefficients of product(1 to j) (1 + x/xi_i) */
for(i=j; i >= 1; i--) {
l[i] += l[i-1]*xi_inv;
p[i] += p[i-1]*xi_inv;
}
}
/* j = q */
alpha0 -= ONE / q;
xistar_inv = -l[1] - alpha0;
hsum += tau[q-1];
xi_inv = h / hsum;
alpha0_hat = -l[1] - xi_inv;
for (i=q; i >= 1; i--) {
l[i] += l[i-1]*xistar_inv;
p[i] += p[i-1]*xi_inv;
}
}
cpSetTqBDF(cp_mem, hsum, alpha0, alpha0_hat, xi_inv, xistar_inv);
}
/*
* cpSetTqBDF
*
* This routine sets the test quantity array tq in the case
* lmm_type == CP_BDF.
*/
static void cpSetTqBDF(CPodeMem cp_mem, realtype hsum, realtype alpha0,
realtype alpha0_hat, realtype xi_inv, realtype xistar_inv)
{
realtype A1, A2, A3, A4, A5, A6;
realtype C, CPrime, CPrimePrime;
A1 = ONE - alpha0_hat + alpha0;
A2 = ONE + q * A1;
tq[2] = ABS(alpha0 * (A2 / A1));
tq[5] = ABS((A2) / (l[q] * xi_inv/xistar_inv));
if (qwait == 1) {
C = xistar_inv / l[q];
A3 = alpha0 + ONE / q;
A4 = alpha0_hat + xi_inv;
CPrime = A3 / (ONE - A4 + A3);
tq[1] = ABS(CPrime / C);
hsum += tau[q];
xi_inv = h / hsum;
A5 = alpha0 - (ONE / (q+1));
A6 = alpha0_hat - xi_inv;
CPrimePrime = A2 / (ONE - A6 + A5);
tq[3] = ABS(CPrimePrime * xi_inv * (q+2) * A5);
}
tq[4] = nlscoef * tq[2];
}
/*
* -----------------------------------------------------------------
* Error test
* -----------------------------------------------------------------
*/
/*
* cpDoErrorTest
*
* This routine performs the local error test. It is called to test
* both the sates and the quadrature variables, with different values
* of acor_norm and dsmPtr.
*
* The weighted local error norm dsm is loaded into *dsmPtr, and
* we test whether dsm <= 1.
*
* If the test passes, cpDoErrorTest returns CP_SUCCESS.
*
* If the test fails, we undo the step just taken (call cpRestore) and
*
* - if maxnef error test failures have occurred or if ABS(h) = hmin,
* we return CP_ERR_FAILURE.
*
* - if more than MXNEF1 error test failures have occurred, an order
* reduction is forced. If already at order 1, restart by reloading
* zn from scratch.
*
* - otherwise, set return PREDICT_AGAIN, telling cpStep to retry the
* step (with nflag = PREV_ERR_FAIL).
*
* Note that we lump all error test failures together (i.e. we do not
* distinguish between failures due to states or to quadratures).
*/
static int cpDoErrorTest(CPodeMem cp_mem, realtype saved_t, realtype acor_norm,
int *nefPtr, realtype *dsmPtr)
{
realtype dsm;
/* If est. local error norm dsm passes test, return CP_SUCCESS */
dsm = acor_norm / tq[2];
*dsmPtr = dsm;
#ifdef CPODES_DEBUG
printf(" dsm = %lg\n",dsm);
#endif
if (dsm <= ONE) return(CP_SUCCESS);
/* Test failed: increment counters and restore zn array */
(*nefPtr)++;
netf++;
cpRestore(cp_mem, saved_t);
/* At maxnef failures or |h| = hmin, return CP_ERR_FAILURE */
if ((ABS(h) <= hmin*ONEPSM) || (*nefPtr == maxnef)) return(CP_ERR_FAILURE);
/* Set etamax = 1 to prevent step size increase at end of this step */
etamax = ONE;
/* Set h ratio eta from dsm, rescale, and return for retry of step */
if (*nefPtr <= MXNEF1) {
eta = ONE / (RPowerR(BIAS2*dsm,ONE/L) + ADDON);
eta = MAX(ETAMIN, MAX(eta, hmin / ABS(h)));
if (*nefPtr >= SMALL_NEF) eta = MIN(eta, ETAMXF);
cpRescale(cp_mem);
return(PREDICT_AGAIN);
}
/* After MXNEF1 failures, force an order reduction and retry step */
if (q > 1) {
eta = MAX(ETAMIN, hmin / ABS(h));
cpAdjustOrder(cp_mem,-1);
L = q;
q--;
qwait = L;
cpRescale(cp_mem);
return(PREDICT_AGAIN);
}
/* If already at order 1, restart: reload zn from scratch */
eta = MAX(ETAMIN, hmin / ABS(h));
h *= eta;
next_h = h;
hscale = h;
qwait = LONG_WAIT;
nscon = 0;
N_VScale(eta, zn[1], zn[1]);
if (quadr) N_VScale(eta, znQ[1], znQ[1]);
return(PREDICT_AGAIN);
}
/*
* -----------------------------------------------------------------
* Successful step completion functions
* -----------------------------------------------------------------
*/
/*
* cpCompleteStep
*
* This routine performs various update operations when the solution
* has passed the local error test.
* We increment the step counter nst, record the values hu and qu,
* and update the tau array.
* The tau[i] are the last q values of h, with tau[1] the most recent.
* The counter qwait is decremented, and if qwait == 1 (and q < qmax)
* we save acor and tq[5] for a possible order increase.
*/
static void cpCompleteStep(CPodeMem cp_mem)
{
int i;
nst++;
nscon++;
hu = h;
qu = q;
for (i=q; i >= 2; i--) tau[i] = tau[i-1];
if ((q==1) && (nst > 1)) tau[2] = tau[1];
tau[1] = h;
/* If necessary, store Delta_n in zn[qmax] to be used in order increase
*
* This actually will be Delta_{n-1} in the ELTE at q+1 since it happens at
* the next to last step of order q before a possible one at order q+1
*/
qwait--;
if ((qwait == 1) && (q != qmax)) {
N_VScale(ONE, acor, zn[qmax]);
if (quadr) N_VScale(ONE, acorQ, znQ[qmax]);
saved_tq5 = tq[5];
indx_acor = qmax;
}
}
/*
* CPprepareNextStep
*
* This routine handles the setting of stepsize and order for the
* next step -- hprime and qprime. Along with hprime, it sets the
* ratio eta = hprime/h. It also updates other state variables
* related to a change of step size or order.
*/
static void cpPrepareNextStep(CPodeMem cp_mem, realtype dsm)
{
/* If etamax = 1, defer step size or order changes */
if (etamax == ONE) {
qwait = MAX(qwait, 2);
qprime = q;
hprime = h;
eta = ONE;
return;
}
/* etaq is the ratio of new to old h at the current order */
etaq = ONE /(RPowerR(BIAS2*dsm,ONE/L) + ADDON);
/* If no order change, adjust eta and acor in cpSetEta and return */
if (qwait != 0) {
eta = etaq;
qprime = q;
cpSetEta(cp_mem);
return;
}
/* If qwait = 0, consider an order change. etaqm1 and etaqp1 are
the ratios of new to old h at orders q-1 and q+1, respectively.
cpChooseEta selects the largest; cpSetEta adjusts eta and acor */
qwait = 2;
etaqm1 = cpComputeEtaqm1(cp_mem);
etaqp1 = cpComputeEtaqp1(cp_mem);
cpChooseEta(cp_mem);
cpSetEta(cp_mem);
}
/*
* CPsetEta
*
* This routine adjusts the value of eta according to the various
* heuristic limits and the optional input hmax.
*/
static void cpSetEta(CPodeMem cp_mem)
{
/* If eta below the threshold THRESH, reject a change of step size */
if (eta < THRESH) {
eta = ONE;
hprime = h;
} else {
/* Limit eta by etamax and hmax, then set hprime */
eta = MIN(eta, etamax);
eta /= MAX(ONE, ABS(h)*hmax_inv*eta);
hprime = h * eta;
if (qprime < q) nscon = 0;
}
}
/*
* cpComputeEtaqm1
*
* This routine computes and returns the value of etaqm1 for a
* possible decrease in order by 1.
*/
static realtype cpComputeEtaqm1(CPodeMem cp_mem)
{
realtype ddn;
etaqm1 = ZERO;
if (q > 1) {
ddn = N_VWrmsNorm(zn[q], ewt) / tq[1];
if ( quadr && errconQ) ddn = cpQuadUpdateNorm(cp_mem, ddn, znQ[q], ewtQ);
etaqm1 = ONE/(RPowerR(BIAS1*ddn, ONE/q) + ADDON);
}
return(etaqm1);
}
/*
* cpComputeEtaqp1
*
* This routine computes and returns the value of etaqp1 for a
* possible increase in order by 1.
*/
static realtype cpComputeEtaqp1(CPodeMem cp_mem)
{
realtype dup, cquot;
etaqp1 = ZERO;
if (q != qmax) {
cquot = (tq[5] / saved_tq5) * RPowerI(h/tau[2], L);
N_VLinearSum(-cquot, zn[qmax], ONE, acor, tempv);
dup = N_VWrmsNorm(tempv, ewt);
if ( quadr && errconQ ) {
N_VLinearSum(-cquot, znQ[qmax], ONE, acorQ, tempvQ);
dup = cpQuadUpdateNorm(cp_mem, dup, tempvQ, ewtQ);
}
dup = dup / tq[3];
etaqp1 = ONE / (RPowerR(BIAS3*dup, ONE/(L+1)) + ADDON);
}
return(etaqp1);
}
/*
* cpChooseEta
* Given etaqm1, etaq, etaqp1 (the values of eta for qprime =
* q - 1, q, or q + 1, respectively), this routine chooses the
* maximum eta value, sets eta to that value, and sets qprime to the
* corresponding value of q. If there is a tie, the preference
* order is to (1) keep the same order, then (2) decrease the order,
* and finally (3) increase the order. If the maximum eta value
* is below the threshold THRESH, the order is kept unchanged and
* eta is set to 1.
*/
static void cpChooseEta(CPodeMem cp_mem)
{
realtype etam;
etam = MAX(etaqm1, MAX(etaq, etaqp1));
if (etam < THRESH) {
eta = ONE;
qprime = q;
return;
}
if (etam == etaq) {
eta = etaq;
qprime = q;
} else if (etam == etaqm1) {
eta = etaqm1;
qprime = q - 1;
} else {
eta = etaqp1;
qprime = q + 1;
if (lmm_type == CP_BDF) {
/*
* Store Delta_n in zn[qmax] to be used in order increase
*
* This happens at the last step of order q before an increase
* to order q+1, so it represents Delta_n in the ELTE at q+1
*/
N_VScale(ONE, acor, zn[qmax]);
if (quadr && errconQ) N_VScale(ONE, acorQ, znQ[qmax]);
}
}
}
/*
* cpHandleFailure
*
* This routine prints error messages for all cases of failure by
* cpHin and cpStep. It returns to CPode the value that CPode is
* to return to the user.
*/
static int cpHandleFailure(CPodeMem cp_mem, int flag)
{
/* Depending on flag, print error message and return error flag */
switch (flag) {
case CP_ERR_FAILURE:
cpProcessError(cp_mem, CP_ERR_FAILURE, "CPODES", "CPode", MSGCP_ERR_FAILS, tn, h);
break;
case CP_CONV_FAILURE:
cpProcessError(cp_mem, CP_CONV_FAILURE, "CPODES", "CPode", MSGCP_CONV_FAILS, tn, h);
break;
case CP_LSETUP_FAIL:
cpProcessError(cp_mem, CP_LSETUP_FAIL, "CPODES", "CPode", MSGCP_SETUP_FAILED, tn);
break;
case CP_LSOLVE_FAIL:
cpProcessError(cp_mem, CP_LSOLVE_FAIL, "CPODES", "CPode", MSGCP_SOLVE_FAILED, tn);
break;
case CP_ODEFUNC_FAIL:
cpProcessError(cp_mem, CP_ODEFUNC_FAIL, "CPODES", "CPode", MSGCP_ODEFUNC_FAILED, tn);
break;
case CP_UNREC_ODEFUNC_ERR:
cpProcessError(cp_mem, CP_UNREC_ODEFUNC_ERR, "CPODES", "CPode", MSGCP_ODEFUNC_UNREC, tn);
break;
case CP_REPTD_ODEFUNC_ERR:
cpProcessError(cp_mem, CP_REPTD_ODEFUNC_ERR, "CPODES", "CPode", MSGCP_ODEFUNC_REPTD, tn);
break;
case CP_RTFUNC_FAIL:
cpProcessError(cp_mem, CP_RTFUNC_FAIL, "CPODES", "CPode", MSGCP_RTFUNC_FAILED, tn);
break;
case CP_TOO_CLOSE:
cpProcessError(cp_mem, CP_TOO_CLOSE, "CPODES", "CPode", MSGCP_TOO_CLOSE);
break;
case CP_PROJ_FAILURE:
cpProcessError(cp_mem, CP_PROJ_FAILURE, "CPODES", "CPode", MSGCP_PROJ_FAILS, tn, h);
break;
case CP_CNSTRFUNC_FAIL:
cpProcessError(cp_mem, CP_CNSTRFUNC_FAIL, "CPODES", "CPode", MSGCP_CNSTRFUNC_FAILED, tn);
break;
case CP_REPTD_CNSTRFUNC_ERR:
cpProcessError(cp_mem, CP_REPTD_CNSTRFUNC_ERR, "CPODES", "CPode", MSGCP_CNSTRFUNC_REPTD, tn);
break;
case CP_PROJFUNC_FAIL:
cpProcessError(cp_mem, CP_PROJFUNC_FAIL, "CPODES", "CPode", MSGCP_PROJFUNC_FAILED, tn);
break;
case CP_REPTD_PROJFUNC_ERR:
cpProcessError(cp_mem, CP_REPTD_PROJFUNC_ERR, "CPODES", "CPode", MSGCP_PROJFUNC_REPTD, tn);
break;
case CP_PLSETUP_FAIL:
cpProcessError(cp_mem, CP_PLSETUP_FAIL, "CPODES", "CPode", MSGCP_PLSETUP_FAILED, tn);
break;
case CP_PLSOLVE_FAIL:
cpProcessError(cp_mem, CP_PLSOLVE_FAIL, "CPODES", "CPode", MSGCP_PLSOLVE_FAILED, tn);
break;
default:
return(CP_SUCCESS);
}
return(flag);
}
/*
* -----------------------------------------------------------------
* BDF stability limit detection functions
* -----------------------------------------------------------------
*/
/*
* cpBDFStab
*
* This routine handles the BDF Stability Limit Detection Algorithm
* STALD. It is called if lmm_type = CP_BDF and the SLDET option is on.
* If the order is 3 or more, the required norm data is saved.
* If a decision to reduce order has not already been made, and
* enough data has been saved, cpSLdet is called. If it signals
* a stability limit violation, the order is reduced, and the step
* size is reset accordingly.
*/
void cpBDFStab(CPodeMem cp_mem)
{
int i,k, ldflag, factorial;
realtype sq, sqm1, sqm2;
/* If order is 3 or greater, then save scaled derivative data,
push old data down in i, then add current values to top. */
if (q >= 3) {
for (k = 1; k <= 3; k++)
{ for (i = 5; i >= 2; i--) ssdat[i][k] = ssdat[i-1][k]; }
factorial = 1;
for (i = 1; i <= q-1; i++) factorial *= i;
sq = factorial*q*(q+1)*acnrm/tq[5];
sqm1 = factorial*q*N_VWrmsNorm(zn[q], ewt);
sqm2 = factorial*N_VWrmsNorm(zn[q-1], ewt);
ssdat[1][1] = sqm2*sqm2;
ssdat[1][2] = sqm1*sqm1;
ssdat[1][3] = sq*sq;
}
if (qprime >= q) {
/* If order is 3 or greater, and enough ssdat has been saved,
nscon >= q+5, then call stability limit detection routine. */
if ( (q >= 3) && (nscon >= q+5) ) {
ldflag = cpSLdet(cp_mem);
if (ldflag > 3) {
/* A stability limit violation is indicated by
a return flag of 4, 5, or 6.
Reduce new order. */
qprime = q-1;
eta = etaqm1;
eta = MIN(eta,etamax);
eta = eta/MAX(ONE,ABS(h)*hmax_inv*eta);
hprime = h*eta;
nor = nor + 1;
}
}
}
else {
/* Otherwise, let order increase happen, and
reset stability limit counter, nscon. */
nscon = 0;
}
}
/*
* cpSLdet
*
* This routine detects stability limitation using stored scaled
* derivatives data. cpSLdet returns the magnitude of the
* dominate characteristic root, rr. The presents of a stability
* limit is indicated by rr > "something a little less then 1.0",
* and a positive kflag. This routine should only be called if
* order is greater than or equal to 3, and data has been collected
* for 5 time steps.
*
* Returned values:
* kflag = 1 -> Found stable characteristic root, normal matrix case
* kflag = 2 -> Found stable characteristic root, quartic solution
* kflag = 3 -> Found stable characteristic root, quartic solution,
* with Newton correction
* kflag = 4 -> Found stability violation, normal matrix case
* kflag = 5 -> Found stability violation, quartic solution
* kflag = 6 -> Found stability violation, quartic solution,
* with Newton correction
*
* kflag < 0 -> No stability limitation,
* or could not compute limitation.
*
* kflag = -1 -> Min/max ratio of ssdat too small.
* kflag = -2 -> For normal matrix case, vmax > vrrt2*vrrt2
* kflag = -3 -> For normal matrix case, The three ratios
* are inconsistent.
* kflag = -4 -> Small coefficient prevents elimination of quartics.
* kflag = -5 -> R value from quartics not consistent.
* kflag = -6 -> No corrected root passes test on qk values
* kflag = -7 -> Trouble solving for sigsq.
* kflag = -8 -> Trouble solving for B, or R via B.
* kflag = -9 -> R via sigsq[k] disagrees with R from data.
*/
static int cpSLdet(CPodeMem cp_mem)
{
int i, k, j, it, kmin, kflag = 0;
realtype rat[5][4], rav[4], qkr[4], sigsq[4], smax[4], ssmax[4];
realtype drr[4], rrc[4],sqmx[4], qjk[4][4], vrat[5], qc[6][4], qco[6][4];
realtype rr, rrcut, vrrtol, vrrt2, sqtol, rrtol;
realtype smink, smaxk, sumrat, sumrsq, vmin, vmax, drrmax, adrr;
realtype tem, sqmax, saqk, qp, s, sqmaxk, saqj, sqmin;
realtype rsa, rsb, rsc, rsd, rd1a, rd1b, rd1c;
realtype rd2a, rd2b, rd3a, cest1, corr1;
realtype ratp, ratm, qfac1, qfac2, bb, rrb;
/* The following are cutoffs and tolerances used by this routine */
rrcut = RCONST(0.98);
vrrtol = RCONST(1.0e-4);
vrrt2 = RCONST(5.0e-4);
sqtol = RCONST(1.0e-3);
rrtol = RCONST(1.0e-2);
rr = ZERO;
/* Index k corresponds to the degree of the interpolating polynomial. */
/* k = 1 -> q-1 */
/* k = 2 -> q */
/* k = 3 -> q+1 */
/* Index i is a backward-in-time index, i = 1 -> current time, */
/* i = 2 -> previous step, etc */
/* get maxima, minima, and variances, and form quartic coefficients */
for (k=1; k<=3; k++) {
smink = ssdat[1][k];
smaxk = ZERO;
for (i=1; i<=5; i++) {
smink = MIN(smink,ssdat[i][k]);
smaxk = MAX(smaxk,ssdat[i][k]);
}
if (smink < TINY*smaxk) {
kflag = -1;
return(kflag);
}
smax[k] = smaxk;
ssmax[k] = smaxk*smaxk;
sumrat = ZERO;
sumrsq = ZERO;
for (i=1; i<=4; i++) {
rat[i][k] = ssdat[i][k]/ssdat[i+1][k];
sumrat = sumrat + rat[i][k];
sumrsq = sumrsq + rat[i][k]*rat[i][k];
}
rav[k] = PT25 * sumrat;
vrat[k] = ABS(PT25*sumrsq - rav[k]*rav[k]);
qc[5][k] = ssdat[1][k]*ssdat[3][k] - ssdat[2][k]*ssdat[2][k];
qc[4][k] = ssdat[2][k]*ssdat[3][k] - ssdat[1][k]*ssdat[4][k];
qc[3][k] = ZERO;
qc[2][k] = ssdat[2][k]*ssdat[5][k] - ssdat[3][k]*ssdat[4][k];
qc[1][k] = ssdat[4][k]*ssdat[4][k] - ssdat[3][k]*ssdat[5][k];
for (i=1; i<=5; i++) {
qco[i][k] = qc[i][k];
}
} /* End of k loop */
/* Isolate normal or nearly-normal matrix case. Three quartic will
have common or nearly-common roots in this case.
Return a kflag = 1 if this procedure works. If three root
differ more than vrrt2, return error kflag = -3. */
vmin = MIN(vrat[1],MIN(vrat[2],vrat[3]));
vmax = MAX(vrat[1],MAX(vrat[2],vrat[3]));
if(vmin < vrrtol*vrrtol) {
if (vmax > vrrt2*vrrt2) {
kflag = -2;
return(kflag);
} else {
rr = (rav[1] + rav[2] + rav[3])/THREE;
drrmax = ZERO;
for(k = 1;k<=3;k++) {
adrr = ABS(rav[k] - rr);
drrmax = MAX(drrmax, adrr);
}
if (drrmax > vrrt2) {
kflag = -3;
}
kflag = 1;
/* can compute charactistic root, drop to next section */
}
} else {
/* use the quartics to get rr. */
if (ABS(qco[1][1]) < TINY*ssmax[1]) {
kflag = -4;
return(kflag);
}
tem = qco[1][2]/qco[1][1];
for(i=2; i<=5; i++) {
qco[i][2] = qco[i][2] - tem*qco[i][1];
}
qco[1][2] = ZERO;
tem = qco[1][3]/qco[1][1];
for(i=2; i<=5; i++) {
qco[i][3] = qco[i][3] - tem*qco[i][1];
}
qco[1][3] = ZERO;
if (ABS(qco[2][2]) < TINY*ssmax[2]) {
kflag = -4;
return(kflag);
}
tem = qco[2][3]/qco[2][2];
for(i=3; i<=5; i++) {
qco[i][3] = qco[i][3] - tem*qco[i][2];
}
if (ABS(qco[4][3]) < TINY*ssmax[3]) {
kflag = -4;
return(kflag);
}
rr = -qco[5][3]/qco[4][3];
if (rr < TINY || rr > HUNDRED) {
kflag = -5;
return(kflag);
}
for(k=1; k<=3; k++) {
qkr[k] = qc[5][k] + rr*(qc[4][k] + rr*rr*(qc[2][k] + rr*qc[1][k]));
}
sqmax = ZERO;
for(k=1; k<=3; k++) {
saqk = ABS(qkr[k])/ssmax[k];
if (saqk > sqmax) sqmax = saqk;
}
if (sqmax < sqtol) {
kflag = 2;
/* can compute charactistic root, drop to "given rr,etc" */
} else {
/* do Newton corrections to improve rr. */
for(it=1; it<=3; it++) {
for(k=1; k<=3; k++) {
qp = qc[4][k] + rr*rr*(THREE*qc[2][k] + rr*FOUR*qc[1][k]);
drr[k] = ZERO;
if (ABS(qp) > TINY*ssmax[k]) drr[k] = -qkr[k]/qp;
rrc[k] = rr + drr[k];
}
for(k=1; k<=3; k++) {
s = rrc[k];
sqmaxk = ZERO;
for(j=1; j<=3; j++) {
qjk[j][k] = qc[5][j] + s*(qc[4][j] +
s*s*(qc[2][j] + s*qc[1][j]));
saqj = ABS(qjk[j][k])/ssmax[j];
if (saqj > sqmaxk) sqmaxk = saqj;
}
sqmx[k] = sqmaxk;
}
sqmin = sqmx[1]; kmin = 1;
for(k=2; k<=3; k++) {
if (sqmx[k] < sqmin) {
kmin = k;
sqmin = sqmx[k];
}
}
rr = rrc[kmin];
if (sqmin < sqtol) {
kflag = 3;
/* can compute charactistic root */
/* break out of Newton correction loop and drop to "given rr,etc" */
break;
} else {
for(j=1; j<=3; j++) {
qkr[j] = qjk[j][kmin];
}
}
} /* end of Newton correction loop */
if (sqmin > sqtol) {
kflag = -6;
return(kflag);
}
} /* end of if (sqmax < sqtol) else */
} /* end of if(vmin < vrrtol*vrrtol) else, quartics to get rr. */
/* given rr, find sigsq[k] and verify rr. */
/* All positive kflag drop to this section */
for(k=1; k<=3; k++) {
rsa = ssdat[1][k];
rsb = ssdat[2][k]*rr;
rsc = ssdat[3][k]*rr*rr;
rsd = ssdat[4][k]*rr*rr*rr;
rd1a = rsa - rsb;
rd1b = rsb - rsc;
rd1c = rsc - rsd;
rd2a = rd1a - rd1b;
rd2b = rd1b - rd1c;
rd3a = rd2a - rd2b;
if (ABS(rd1b) < TINY*smax[k]) {
kflag = -7;
return(kflag);
}
cest1 = -rd3a/rd1b;
if (cest1 < TINY || cest1 > FOUR) {
kflag = -7;
return(kflag);
}
corr1 = (rd2b/cest1)/(rr*rr);
sigsq[k] = ssdat[3][k] + corr1;
}
if (sigsq[2] < TINY) {
kflag = -8;
return(kflag);
}
ratp = sigsq[3]/sigsq[2];
ratm = sigsq[1]/sigsq[2];
qfac1 = PT25 * (q*q - ONE);
qfac2 = TWO/(q - ONE);
bb = ratp*ratm - ONE - qfac1*ratp;
tem = ONE - qfac2*bb;
if (ABS(tem) < TINY) {
kflag = -8;
return(kflag);
}
rrb = ONE/tem;
if (ABS(rrb - rr) > rrtol) {
kflag = -9;
return(kflag);
}
/* Check to see if rr is above cutoff rrcut */
if (rr > rrcut) {
if (kflag == 1) kflag = 4;
if (kflag == 2) kflag = 5;
if (kflag == 3) kflag = 6;
}
/* All positive kflag returned at this point */
return(kflag);
}
/*
* -----------------------------------------------------------------
* Internal error weight evaluation functions
* -----------------------------------------------------------------
*/
/*
* cpEwtSet
*
* This routine is responsible for setting the error weight vector ewt,
* according to tol_type, as follows:
*
* (1) ewt[i] = 1 / (reltol * ABS(ycur[i]) + *abstol), i=0,...,neq-1
* if tol_type = CP_SS
* (2) ewt[i] = 1 / (reltol * ABS(ycur[i]) + abstol[i]), i=0,...,neq-1
* if tol_type = CP_SV
*
* cpEwtSet returns 0 if ewt is successfully set as above to a
* positive vector and -1 otherwise. In the latter case, ewt is
* considered undefined.
*
* All the real work is done in the routines cpEwtSetSS, cpEwtSetSV.
*/
int cpEwtSet(N_Vector ycur, N_Vector weight, void *edata)
{
CPodeMem cp_mem;
int flag = 0;
/* edata points to cp_mem here */
cp_mem = (CPodeMem) edata;
switch(tol_type) {
case CP_SS:
flag = cpEwtSetSS(cp_mem, ycur, weight);
break;
case CP_SV:
flag = cpEwtSetSV(cp_mem, ycur, weight);
break;
}
return(flag);
}
/*
* cpEwtSetSS
*
* This routine sets ewt as described above in the case tol_type = CP_SS.
* It tests for non-positive components before inverting. cpEwtSetSS
* returns 0 if ewt is successfully set to a positive vector
* and -1 otherwise. In the latter case, ewt is considered undefined.
*/
static int cpEwtSetSS(CPodeMem cp_mem, N_Vector ycur, N_Vector weight)
{
N_VAbs(ycur, tempv);
N_VScale(reltol, tempv, tempv);
N_VAddConst(tempv, Sabstol, tempv);
if (N_VMin(tempv) <= ZERO) return(-1);
N_VInv(tempv, weight);
return(0);
}
/*
* cpEwtSetSV
*
* This routine sets ewt as described above in the case tol_type = CP_SV.
* It tests for non-positive components before inverting. cpEwtSetSV
* returns 0 if ewt is successfully set to a positive vector
* and -1 otherwise. In the latter case, ewt is considered undefined.
*/
static int cpEwtSetSV(CPodeMem cp_mem, N_Vector ycur, N_Vector weight)
{
N_VAbs(ycur, tempv);
N_VLinearSum(reltol, tempv, ONE, Vabstol, tempv);
if (N_VMin(tempv) <= ZERO) return(-1);
N_VInv(tempv, weight);
return(0);
}
/*
* cpQuadEwtSet
*
*/
static int cpQuadEwtSet(CPodeMem cp_mem, N_Vector qcur, N_Vector weightQ)
{
int flag=0;
switch (tol_typeQ) {
case CP_SS:
flag = cpQuadEwtSetSS(cp_mem, qcur, weightQ);
break;
case CP_SV:
flag = cpQuadEwtSetSV(cp_mem, qcur, weightQ);
break;
}
return(flag);
}
/*
* cpQuadEwtSetSS
*
*/
static int cpQuadEwtSetSS(CPodeMem cp_mem, N_Vector qcur, N_Vector weightQ)
{
N_VAbs(qcur, tempvQ);
N_VScale(reltolQ, tempvQ, tempvQ);
N_VAddConst(tempvQ, SabstolQ, tempvQ);
if (N_VMin(tempvQ) <= ZERO) return(-1);
N_VInv(tempvQ, weightQ);
return(0);
}
/*
* cpQuadEwtSetSV
*
*/
static int cpQuadEwtSetSV(CPodeMem cp_mem, N_Vector qcur, N_Vector weightQ)
{
N_VAbs(qcur, tempvQ);
N_VLinearSum(reltolQ, tempvQ, ONE, VabstolQ, tempvQ);
if (N_VMin(tempvQ) <= ZERO) return(-1);
N_VInv(tempvQ, weightQ);
return(0);
}
/*
* -----------------------------------------------------------------
* Updated WRMS norms
* -----------------------------------------------------------------
*/
/*
* cpQuadUpdateNorm
*
* Updates the norm old_nrm to account for all quadratures.
*/
static realtype cpQuadUpdateNorm(CPodeMem cp_mem, realtype old_nrm,
N_Vector xQ, N_Vector wQ)
{
realtype qnrm;
qnrm = N_VWrmsNorm(xQ, wQ);
if (old_nrm > qnrm) return(old_nrm);
else return(qnrm);
}
/*
* cpQuadUpdateDsm
*
* This routine updates the local error norm dsm with quadrature
* related information. Used only if quadratures are computed
* with FULL error control.
*
* Returns the maximum over the wheighted local error norms.
*/
static realtype cpQuadUpdateDsm(CPodeMem cp_mem, realtype old_dsm,
realtype dsmQ)
{
if ( old_dsm > dsmQ ) return(old_dsm);
else return(dsmQ);
}
/*
* -----------------------------------------------------------------
* Error reporting functions
* -----------------------------------------------------------------
*/
/*
* cpProcessError is a high level error handling function
* - if cp_mem==NULL it prints the error message to stderr
* - otherwise, it sets-up and calls the error hadling function
* pointed to by cp_ehfun
*/
#define ehfun (cp_mem->cp_ehfun)
#define eh_data (cp_mem->cp_eh_data)
void cpProcessError(CPodeMem cp_mem,
int error_code, const char *module, const char *fname,
const char *msgfmt, ...)
{
va_list ap;
char msg[256];
/* Initialize the argument pointer variable
(msgfmt is the last required argument to cpProcessError) */
va_start(ap, msgfmt);
if (cp_mem == NULL) { /* We write to stderr */
#ifndef NO_FPRINTF_OUTPUT
fprintf(stderr, "\n[%s ERROR] %s\n ", module, fname);
fprintf(stderr, msgfmt, 0); // extra arg avoids gcc warnings
fprintf(stderr, "\n\n");
#endif
} else { /* We can call ehfun */
/* Compose the message */
vsprintf(msg, msgfmt, ap);
/* Call ehfun */
ehfun(error_code, module, fname, msg, eh_data);
}
/* Finalize argument processing */
va_end(ap);
return;
}
/* cpErrHandler is the default error handling function.
It sends the error message to the stream pointed to by cp_errfp */
#define errfp (cp_mem->cp_errfp)
static void cpErrHandler(int error_code, const char *module,
const char *function, char *msg, void *data)
{
CPodeMem cp_mem;
char err_type[10];
/* data points to cp_mem here */
cp_mem = (CPodeMem) data;
if (error_code == CP_WARNING)
sprintf(err_type,"WARNING");
else
sprintf(err_type,"ERROR");
#ifndef NO_FPRINTF_OUTPUT
if (errfp!=NULL) {
fprintf(errfp,"\n[%s %s] %s\n",module,err_type,function);
fprintf(errfp," %s\n\n",msg);
}
#endif
return;
}
|
0458291830038c38775eda77b8ab2d78617a95e5
|
9eedaea06306b20520151321854f989a73c7daf8
|
/src/events/scancodes_linux.h
|
d9c478c9317a41981504f294f133d1a6a2a7c4ed
|
[
"Zlib"
] |
permissive
|
libsdl-org/SDL
|
cf56bdc8a9e198e9735201674118c822d0e3edf3
|
8387fae698745969ce366c4de9bcc1b4a364a7dd
|
refs/heads/main
| 2023-09-04T06:58:34.316952
| 2023-09-03T15:11:13
| 2023-09-03T15:11:13
| 330,008,801
| 6,912
| 1,605
|
Zlib
| 2023-09-13T19:12:26
| 2021-01-15T19:55:54
|
C
|
UTF-8
|
C
| false
| false
| 51,716
|
h
|
scancodes_linux.h
|
/*
Simple DirectMedia Layer
Copyright (C) 1997-2023 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "SDL_internal.h"
/* Linux virtual key code to SDL_Keycode mapping table
Sources:
- Linux kernel source input.h
*/
/* *INDENT-OFF* */ /* clang-format off */
static SDL_Scancode const linux_scancode_table[] = {
/* 0, 0x000 */ SDL_SCANCODE_UNKNOWN, /* KEY_RESERVED */
/* 1, 0x001 */ SDL_SCANCODE_ESCAPE, /* KEY_ESC */
/* 2, 0x002 */ SDL_SCANCODE_1, /* KEY_1 */
/* 3, 0x003 */ SDL_SCANCODE_2, /* KEY_2 */
/* 4, 0x004 */ SDL_SCANCODE_3, /* KEY_3 */
/* 5, 0x005 */ SDL_SCANCODE_4, /* KEY_4 */
/* 6, 0x006 */ SDL_SCANCODE_5, /* KEY_5 */
/* 7, 0x007 */ SDL_SCANCODE_6, /* KEY_6 */
/* 8, 0x008 */ SDL_SCANCODE_7, /* KEY_7 */
/* 9, 0x009 */ SDL_SCANCODE_8, /* KEY_8 */
/* 10, 0x00a */ SDL_SCANCODE_9, /* KEY_9 */
/* 11, 0x00b */ SDL_SCANCODE_0, /* KEY_0 */
/* 12, 0x00c */ SDL_SCANCODE_MINUS, /* KEY_MINUS */
/* 13, 0x00d */ SDL_SCANCODE_EQUALS, /* KEY_EQUAL */
/* 14, 0x00e */ SDL_SCANCODE_BACKSPACE, /* KEY_BACKSPACE */
/* 15, 0x00f */ SDL_SCANCODE_TAB, /* KEY_TAB */
/* 16, 0x010 */ SDL_SCANCODE_Q, /* KEY_Q */
/* 17, 0x011 */ SDL_SCANCODE_W, /* KEY_W */
/* 18, 0x012 */ SDL_SCANCODE_E, /* KEY_E */
/* 19, 0x013 */ SDL_SCANCODE_R, /* KEY_R */
/* 20, 0x014 */ SDL_SCANCODE_T, /* KEY_T */
/* 21, 0x015 */ SDL_SCANCODE_Y, /* KEY_Y */
/* 22, 0x016 */ SDL_SCANCODE_U, /* KEY_U */
/* 23, 0x017 */ SDL_SCANCODE_I, /* KEY_I */
/* 24, 0x018 */ SDL_SCANCODE_O, /* KEY_O */
/* 25, 0x019 */ SDL_SCANCODE_P, /* KEY_P */
/* 26, 0x01a */ SDL_SCANCODE_LEFTBRACKET, /* KEY_LEFTBRACE */
/* 27, 0x01b */ SDL_SCANCODE_RIGHTBRACKET, /* KEY_RIGHTBRACE */
/* 28, 0x01c */ SDL_SCANCODE_RETURN, /* KEY_ENTER */
/* 29, 0x01d */ SDL_SCANCODE_LCTRL, /* KEY_LEFTCTRL */
/* 30, 0x01e */ SDL_SCANCODE_A, /* KEY_A */
/* 31, 0x01f */ SDL_SCANCODE_S, /* KEY_S */
/* 32, 0x020 */ SDL_SCANCODE_D, /* KEY_D */
/* 33, 0x021 */ SDL_SCANCODE_F, /* KEY_F */
/* 34, 0x022 */ SDL_SCANCODE_G, /* KEY_G */
/* 35, 0x023 */ SDL_SCANCODE_H, /* KEY_H */
/* 36, 0x024 */ SDL_SCANCODE_J, /* KEY_J */
/* 37, 0x025 */ SDL_SCANCODE_K, /* KEY_K */
/* 38, 0x026 */ SDL_SCANCODE_L, /* KEY_L */
/* 39, 0x027 */ SDL_SCANCODE_SEMICOLON, /* KEY_SEMICOLON */
/* 40, 0x028 */ SDL_SCANCODE_APOSTROPHE, /* KEY_APOSTROPHE */
/* 41, 0x029 */ SDL_SCANCODE_GRAVE, /* KEY_GRAVE */
/* 42, 0x02a */ SDL_SCANCODE_LSHIFT, /* KEY_LEFTSHIFT */
/* 43, 0x02b */ SDL_SCANCODE_BACKSLASH, /* KEY_BACKSLASH */
/* 44, 0x02c */ SDL_SCANCODE_Z, /* KEY_Z */
/* 45, 0x02d */ SDL_SCANCODE_X, /* KEY_X */
/* 46, 0x02e */ SDL_SCANCODE_C, /* KEY_C */
/* 47, 0x02f */ SDL_SCANCODE_V, /* KEY_V */
/* 48, 0x030 */ SDL_SCANCODE_B, /* KEY_B */
/* 49, 0x031 */ SDL_SCANCODE_N, /* KEY_N */
/* 50, 0x032 */ SDL_SCANCODE_M, /* KEY_M */
/* 51, 0x033 */ SDL_SCANCODE_COMMA, /* KEY_COMMA */
/* 52, 0x034 */ SDL_SCANCODE_PERIOD, /* KEY_DOT */
/* 53, 0x035 */ SDL_SCANCODE_SLASH, /* KEY_SLASH */
/* 54, 0x036 */ SDL_SCANCODE_RSHIFT, /* KEY_RIGHTSHIFT */
/* 55, 0x037 */ SDL_SCANCODE_KP_MULTIPLY, /* KEY_KPASTERISK */
/* 56, 0x038 */ SDL_SCANCODE_LALT, /* KEY_LEFTALT */
/* 57, 0x039 */ SDL_SCANCODE_SPACE, /* KEY_SPACE */
/* 58, 0x03a */ SDL_SCANCODE_CAPSLOCK, /* KEY_CAPSLOCK */
/* 59, 0x03b */ SDL_SCANCODE_F1, /* KEY_F1 */
/* 60, 0x03c */ SDL_SCANCODE_F2, /* KEY_F2 */
/* 61, 0x03d */ SDL_SCANCODE_F3, /* KEY_F3 */
/* 62, 0x03e */ SDL_SCANCODE_F4, /* KEY_F4 */
/* 63, 0x03f */ SDL_SCANCODE_F5, /* KEY_F5 */
/* 64, 0x040 */ SDL_SCANCODE_F6, /* KEY_F6 */
/* 65, 0x041 */ SDL_SCANCODE_F7, /* KEY_F7 */
/* 66, 0x042 */ SDL_SCANCODE_F8, /* KEY_F8 */
/* 67, 0x043 */ SDL_SCANCODE_F9, /* KEY_F9 */
/* 68, 0x044 */ SDL_SCANCODE_F10, /* KEY_F10 */
/* 69, 0x045 */ SDL_SCANCODE_NUMLOCKCLEAR, /* KEY_NUMLOCK */
/* 70, 0x046 */ SDL_SCANCODE_SCROLLLOCK, /* KEY_SCROLLLOCK */
/* 71, 0x047 */ SDL_SCANCODE_KP_7, /* KEY_KP7 */
/* 72, 0x048 */ SDL_SCANCODE_KP_8, /* KEY_KP8 */
/* 73, 0x049 */ SDL_SCANCODE_KP_9, /* KEY_KP9 */
/* 74, 0x04a */ SDL_SCANCODE_KP_MINUS, /* KEY_KPMINUS */
/* 75, 0x04b */ SDL_SCANCODE_KP_4, /* KEY_KP4 */
/* 76, 0x04c */ SDL_SCANCODE_KP_5, /* KEY_KP5 */
/* 77, 0x04d */ SDL_SCANCODE_KP_6, /* KEY_KP6 */
/* 78, 0x04e */ SDL_SCANCODE_KP_PLUS, /* KEY_KPPLUS */
/* 79, 0x04f */ SDL_SCANCODE_KP_1, /* KEY_KP1 */
/* 80, 0x050 */ SDL_SCANCODE_KP_2, /* KEY_KP2 */
/* 81, 0x051 */ SDL_SCANCODE_KP_3, /* KEY_KP3 */
/* 82, 0x052 */ SDL_SCANCODE_KP_0, /* KEY_KP0 */
/* 83, 0x053 */ SDL_SCANCODE_KP_PERIOD, /* KEY_KPDOT */
/* 84, 0x054 */ SDL_SCANCODE_UNKNOWN,
/* 85, 0x055 */ SDL_SCANCODE_LANG5, /* KEY_ZENKAKUHANKAKU */
/* 86, 0x056 */ SDL_SCANCODE_NONUSBACKSLASH, /* KEY_102ND */
/* 87, 0x057 */ SDL_SCANCODE_F11, /* KEY_F11 */
/* 88, 0x058 */ SDL_SCANCODE_F12, /* KEY_F12 */
/* 89, 0x059 */ SDL_SCANCODE_INTERNATIONAL1, /* KEY_RO */
/* 90, 0x05a */ SDL_SCANCODE_LANG3, /* KEY_KATAKANA */
/* 91, 0x05b */ SDL_SCANCODE_LANG4, /* KEY_HIRAGANA */
/* 92, 0x05c */ SDL_SCANCODE_INTERNATIONAL4, /* KEY_HENKAN */
/* 93, 0x05d */ SDL_SCANCODE_INTERNATIONAL2, /* KEY_KATAKANAHIRAGANA */
/* 94, 0x05e */ SDL_SCANCODE_INTERNATIONAL5, /* KEY_MUHENKAN */
/* 95, 0x05f */ SDL_SCANCODE_INTERNATIONAL5, /* KEY_KPJPCOMMA */
/* 96, 0x060 */ SDL_SCANCODE_KP_ENTER, /* KEY_KPENTER */
/* 97, 0x061 */ SDL_SCANCODE_RCTRL, /* KEY_RIGHTCTRL */
/* 98, 0x062 */ SDL_SCANCODE_KP_DIVIDE, /* KEY_KPSLASH */
/* 99, 0x063 */ SDL_SCANCODE_SYSREQ, /* KEY_SYSRQ */
/* 100, 0x064 */ SDL_SCANCODE_RALT, /* KEY_RIGHTALT */
/* 101, 0x065 */ SDL_SCANCODE_UNKNOWN, /* KEY_LINEFEED */
/* 102, 0x066 */ SDL_SCANCODE_HOME, /* KEY_HOME */
/* 103, 0x067 */ SDL_SCANCODE_UP, /* KEY_UP */
/* 104, 0x068 */ SDL_SCANCODE_PAGEUP, /* KEY_PAGEUP */
/* 105, 0x069 */ SDL_SCANCODE_LEFT, /* KEY_LEFT */
/* 106, 0x06a */ SDL_SCANCODE_RIGHT, /* KEY_RIGHT */
/* 107, 0x06b */ SDL_SCANCODE_END, /* KEY_END */
/* 108, 0x06c */ SDL_SCANCODE_DOWN, /* KEY_DOWN */
/* 109, 0x06d */ SDL_SCANCODE_PAGEDOWN, /* KEY_PAGEDOWN */
/* 110, 0x06e */ SDL_SCANCODE_INSERT, /* KEY_INSERT */
/* 111, 0x06f */ SDL_SCANCODE_DELETE, /* KEY_DELETE */
/* 112, 0x070 */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO */
/* 113, 0x071 */ SDL_SCANCODE_MUTE, /* KEY_MUTE */
/* 114, 0x072 */ SDL_SCANCODE_VOLUMEDOWN, /* KEY_VOLUMEDOWN */
/* 115, 0x073 */ SDL_SCANCODE_VOLUMEUP, /* KEY_VOLUMEUP */
/* 116, 0x074 */ SDL_SCANCODE_POWER, /* KEY_POWER */
/* 117, 0x075 */ SDL_SCANCODE_KP_EQUALS, /* KEY_KPEQUAL */
/* 118, 0x076 */ SDL_SCANCODE_KP_PLUSMINUS, /* KEY_KPPLUSMINUS */
/* 119, 0x077 */ SDL_SCANCODE_PAUSE, /* KEY_PAUSE */
/* 120, 0x078 */ SDL_SCANCODE_UNKNOWN, /* KEY_SCALE */
/* 121, 0x079 */ SDL_SCANCODE_KP_COMMA, /* KEY_KPCOMMA */
/* 122, 0x07a */ SDL_SCANCODE_LANG1, /* KEY_HANGEUL */
/* 123, 0x07b */ SDL_SCANCODE_LANG2, /* KEY_HANJA */
/* 124, 0x07c */ SDL_SCANCODE_INTERNATIONAL3, /* KEY_YEN */
/* 125, 0x07d */ SDL_SCANCODE_LGUI, /* KEY_LEFTMETA */
/* 126, 0x07e */ SDL_SCANCODE_RGUI, /* KEY_RIGHTMETA */
/* 127, 0x07f */ SDL_SCANCODE_APPLICATION, /* KEY_COMPOSE */
/* 128, 0x080 */ SDL_SCANCODE_STOP, /* KEY_STOP */
/* 129, 0x081 */ SDL_SCANCODE_AGAIN, /* KEY_AGAIN */
/* 130, 0x082 */ SDL_SCANCODE_UNKNOWN, /* KEY_PROPS */
/* 131, 0x083 */ SDL_SCANCODE_UNDO, /* KEY_UNDO */
/* 132, 0x084 */ SDL_SCANCODE_UNKNOWN, /* KEY_FRONT */
/* 133, 0x085 */ SDL_SCANCODE_COPY, /* KEY_COPY */
/* 134, 0x086 */ SDL_SCANCODE_UNKNOWN, /* KEY_OPEN */
/* 135, 0x087 */ SDL_SCANCODE_PASTE, /* KEY_PASTE */
/* 136, 0x088 */ SDL_SCANCODE_FIND, /* KEY_FIND */
/* 137, 0x089 */ SDL_SCANCODE_CUT, /* KEY_CUT */
/* 138, 0x08a */ SDL_SCANCODE_HELP, /* KEY_HELP */
/* 139, 0x08b */ SDL_SCANCODE_MENU, /* KEY_MENU */
/* 140, 0x08c */ SDL_SCANCODE_CALCULATOR, /* KEY_CALC */
/* 141, 0x08d */ SDL_SCANCODE_UNKNOWN, /* KEY_SETUP */
/* 142, 0x08e */ SDL_SCANCODE_SLEEP, /* KEY_SLEEP */
/* 143, 0x08f */ SDL_SCANCODE_UNKNOWN, /* KEY_WAKEUP */
/* 144, 0x090 */ SDL_SCANCODE_UNKNOWN, /* KEY_FILE */
/* 145, 0x091 */ SDL_SCANCODE_UNKNOWN, /* KEY_SENDFILE */
/* 146, 0x092 */ SDL_SCANCODE_UNKNOWN, /* KEY_DELETEFILE */
/* 147, 0x093 */ SDL_SCANCODE_UNKNOWN, /* KEY_XFER */
/* 148, 0x094 */ SDL_SCANCODE_APP1, /* KEY_PROG1 */
/* 149, 0x095 */ SDL_SCANCODE_APP2, /* KEY_PROG2 */
/* 150, 0x096 */ SDL_SCANCODE_WWW, /* KEY_WWW */
/* 151, 0x097 */ SDL_SCANCODE_UNKNOWN, /* KEY_MSDOS */
/* 152, 0x098 */ SDL_SCANCODE_UNKNOWN, /* KEY_COFFEE */
/* 153, 0x099 */ SDL_SCANCODE_UNKNOWN, /* KEY_ROTATE_DISPLAY */
/* 154, 0x09a */ SDL_SCANCODE_UNKNOWN, /* KEY_CYCLEWINDOWS */
/* 155, 0x09b */ SDL_SCANCODE_MAIL, /* KEY_MAIL */
/* 156, 0x09c */ SDL_SCANCODE_AC_BOOKMARKS, /* KEY_BOOKMARKS */
/* 157, 0x09d */ SDL_SCANCODE_COMPUTER, /* KEY_COMPUTER */
/* 158, 0x09e */ SDL_SCANCODE_AC_BACK, /* KEY_BACK */
/* 159, 0x09f */ SDL_SCANCODE_AC_FORWARD, /* KEY_FORWARD */
/* 160, 0x0a0 */ SDL_SCANCODE_UNKNOWN, /* KEY_CLOSECD */
/* 161, 0x0a1 */ SDL_SCANCODE_EJECT, /* KEY_EJECTCD */
/* 162, 0x0a2 */ SDL_SCANCODE_EJECT, /* KEY_EJECTCLOSECD */
/* 163, 0x0a3 */ SDL_SCANCODE_AUDIONEXT, /* KEY_NEXTSONG */
/* 164, 0x0a4 */ SDL_SCANCODE_AUDIOPLAY, /* KEY_PLAYPAUSE */
/* 165, 0x0a5 */ SDL_SCANCODE_AUDIOPREV, /* KEY_PREVIOUSSONG */
/* 166, 0x0a6 */ SDL_SCANCODE_AUDIOSTOP, /* KEY_STOPCD */
/* 167, 0x0a7 */ SDL_SCANCODE_UNKNOWN, /* KEY_RECORD */
/* 168, 0x0a8 */ SDL_SCANCODE_AUDIOREWIND, /* KEY_REWIND */
/* 169, 0x0a9 */ SDL_SCANCODE_UNKNOWN, /* KEY_PHONE */
/* 170, 0x0aa */ SDL_SCANCODE_UNKNOWN, /* KEY_ISO */
/* 171, 0x0ab */ SDL_SCANCODE_UNKNOWN, /* KEY_CONFIG */
/* 172, 0x0ac */ SDL_SCANCODE_AC_HOME, /* KEY_HOMEPAGE */
/* 173, 0x0ad */ SDL_SCANCODE_AC_REFRESH, /* KEY_REFRESH */
/* 174, 0x0ae */ SDL_SCANCODE_UNKNOWN, /* KEY_EXIT */
/* 175, 0x0af */ SDL_SCANCODE_UNKNOWN, /* KEY_MOVE */
/* 176, 0x0b0 */ SDL_SCANCODE_UNKNOWN, /* KEY_EDIT */
/* 177, 0x0b1 */ SDL_SCANCODE_UNKNOWN, /* KEY_SCROLLUP */
/* 178, 0x0b2 */ SDL_SCANCODE_UNKNOWN, /* KEY_SCROLLDOWN */
/* 179, 0x0b3 */ SDL_SCANCODE_KP_LEFTPAREN, /* KEY_KPLEFTPAREN */
/* 180, 0x0b4 */ SDL_SCANCODE_KP_RIGHTPAREN, /* KEY_KPRIGHTPAREN */
/* 181, 0x0b5 */ SDL_SCANCODE_UNKNOWN, /* KEY_NEW */
/* 182, 0x0b6 */ SDL_SCANCODE_AGAIN, /* KEY_REDO */
/* 183, 0x0b7 */ SDL_SCANCODE_F13, /* KEY_F13 */
/* 184, 0x0b8 */ SDL_SCANCODE_F14, /* KEY_F14 */
/* 185, 0x0b9 */ SDL_SCANCODE_F15, /* KEY_F15 */
/* 186, 0x0ba */ SDL_SCANCODE_F16, /* KEY_F16 */
/* 187, 0x0bb */ SDL_SCANCODE_F17, /* KEY_F17 */
/* 188, 0x0bc */ SDL_SCANCODE_F18, /* KEY_F18 */
/* 189, 0x0bd */ SDL_SCANCODE_F19, /* KEY_F19 */
/* 190, 0x0be */ SDL_SCANCODE_F20, /* KEY_F20 */
/* 191, 0x0bf */ SDL_SCANCODE_F21, /* KEY_F21 */
/* 192, 0x0c0 */ SDL_SCANCODE_F22, /* KEY_F22 */
/* 193, 0x0c1 */ SDL_SCANCODE_F23, /* KEY_F23 */
/* 194, 0x0c2 */ SDL_SCANCODE_F24, /* KEY_F24 */
/* 195, 0x0c3 */ SDL_SCANCODE_UNKNOWN,
/* 196, 0x0c4 */ SDL_SCANCODE_UNKNOWN,
/* 197, 0x0c5 */ SDL_SCANCODE_UNKNOWN,
/* 198, 0x0c6 */ SDL_SCANCODE_UNKNOWN,
/* 199, 0x0c7 */ SDL_SCANCODE_UNKNOWN,
/* 200, 0x0c8 */ SDL_SCANCODE_AUDIOPLAY, /* KEY_PLAYCD */
/* 201, 0x0c9 */ SDL_SCANCODE_UNKNOWN, /* KEY_PAUSECD */
/* 202, 0x0ca */ SDL_SCANCODE_UNKNOWN, /* KEY_PROG3 */
/* 203, 0x0cb */ SDL_SCANCODE_UNKNOWN, /* KEY_PROG4 */
/* 204, 0x0cc */ SDL_SCANCODE_UNKNOWN, /* KEY_ALL_APPLICATIONS */
/* 205, 0x0cd */ SDL_SCANCODE_UNKNOWN, /* KEY_SUSPEND */
/* 206, 0x0ce */ SDL_SCANCODE_UNKNOWN, /* KEY_CLOSE */
/* 207, 0x0cf */ SDL_SCANCODE_AUDIOPLAY, /* KEY_PLAY */
/* 208, 0x0d0 */ SDL_SCANCODE_AUDIOFASTFORWARD, /* KEY_FASTFORWARD */
/* 209, 0x0d1 */ SDL_SCANCODE_UNKNOWN, /* KEY_BASSBOOST */
/* 210, 0x0d2 */ SDL_SCANCODE_PRINTSCREEN, /* KEY_PRINT */
/* 211, 0x0d3 */ SDL_SCANCODE_UNKNOWN, /* KEY_HP */
/* 212, 0x0d4 */ SDL_SCANCODE_UNKNOWN, /* KEY_CAMERA */
/* 213, 0x0d5 */ SDL_SCANCODE_UNKNOWN, /* KEY_SOUND */
/* 214, 0x0d6 */ SDL_SCANCODE_UNKNOWN, /* KEY_QUESTION */
/* 215, 0x0d7 */ SDL_SCANCODE_MAIL, /* KEY_EMAIL */
/* 216, 0x0d8 */ SDL_SCANCODE_UNKNOWN, /* KEY_CHAT */
/* 217, 0x0d9 */ SDL_SCANCODE_AC_SEARCH, /* KEY_SEARCH */
/* 218, 0x0da */ SDL_SCANCODE_UNKNOWN, /* KEY_CONNECT */
/* 219, 0x0db */ SDL_SCANCODE_UNKNOWN, /* KEY_FINANCE */
/* 220, 0x0dc */ SDL_SCANCODE_UNKNOWN, /* KEY_SPORT */
/* 221, 0x0dd */ SDL_SCANCODE_UNKNOWN, /* KEY_SHOP */
/* 222, 0x0de */ SDL_SCANCODE_ALTERASE, /* KEY_ALTERASE */
/* 223, 0x0df */ SDL_SCANCODE_CANCEL, /* KEY_CANCEL */
/* 224, 0x0e0 */ SDL_SCANCODE_BRIGHTNESSDOWN, /* KEY_BRIGHTNESSDOWN */
/* 225, 0x0e1 */ SDL_SCANCODE_BRIGHTNESSUP, /* KEY_BRIGHTNESSUP */
/* 226, 0x0e2 */ SDL_SCANCODE_MEDIASELECT, /* KEY_MEDIA */
/* 227, 0x0e3 */ SDL_SCANCODE_DISPLAYSWITCH, /* KEY_SWITCHVIDEOMODE */
/* 228, 0x0e4 */ SDL_SCANCODE_KBDILLUMTOGGLE, /* KEY_KBDILLUMTOGGLE */
/* 229, 0x0e5 */ SDL_SCANCODE_KBDILLUMDOWN, /* KEY_KBDILLUMDOWN */
/* 230, 0x0e6 */ SDL_SCANCODE_KBDILLUMUP, /* KEY_KBDILLUMUP */
/* 231, 0x0e7 */ SDL_SCANCODE_UNKNOWN, /* KEY_SEND */
/* 232, 0x0e8 */ SDL_SCANCODE_UNKNOWN, /* KEY_REPLY */
/* 233, 0x0e9 */ SDL_SCANCODE_UNKNOWN, /* KEY_FORWARDMAIL */
/* 234, 0x0ea */ SDL_SCANCODE_UNKNOWN, /* KEY_SAVE */
/* 235, 0x0eb */ SDL_SCANCODE_UNKNOWN, /* KEY_DOCUMENTS */
/* 236, 0x0ec */ SDL_SCANCODE_UNKNOWN, /* KEY_BATTERY */
/* 237, 0x0ed */ SDL_SCANCODE_UNKNOWN, /* KEY_BLUETOOTH */
/* 238, 0x0ee */ SDL_SCANCODE_UNKNOWN, /* KEY_WLAN */
/* 239, 0x0ef */ SDL_SCANCODE_UNKNOWN, /* KEY_UWB */
/* 240, 0x0f0 */ SDL_SCANCODE_UNKNOWN, /* KEY_UNKNOWN */
/* 241, 0x0f1 */ SDL_SCANCODE_UNKNOWN, /* KEY_VIDEO_NEXT */
/* 242, 0x0f2 */ SDL_SCANCODE_UNKNOWN, /* KEY_VIDEO_PREV */
/* 243, 0x0f3 */ SDL_SCANCODE_UNKNOWN, /* KEY_BRIGHTNESS_CYCLE */
/* 244, 0x0f4 */ SDL_SCANCODE_UNKNOWN, /* KEY_BRIGHTNESS_AUTO */
/* 245, 0x0f5 */ SDL_SCANCODE_UNKNOWN, /* KEY_DISPLAY_OFF */
/* 246, 0x0f6 */ SDL_SCANCODE_UNKNOWN, /* KEY_WWAN */
/* 247, 0x0f7 */ SDL_SCANCODE_UNKNOWN, /* KEY_RFKILL */
/* 248, 0x0f8 */ SDL_SCANCODE_UNKNOWN, /* KEY_MICMUTE */
/* 249, 0x0f9 */ SDL_SCANCODE_UNKNOWN,
/* 250, 0x0fa */ SDL_SCANCODE_UNKNOWN,
/* 251, 0x0fb */ SDL_SCANCODE_UNKNOWN,
/* 252, 0x0fc */ SDL_SCANCODE_UNKNOWN,
/* 253, 0x0fd */ SDL_SCANCODE_UNKNOWN,
/* 254, 0x0fe */ SDL_SCANCODE_UNKNOWN,
/* 255, 0x0ff */ SDL_SCANCODE_UNKNOWN,
#if 0 /* We don't have any mapped scancodes after this point (yet) */
/* 256, 0x100 */ SDL_SCANCODE_UNKNOWN,
/* 257, 0x101 */ SDL_SCANCODE_UNKNOWN,
/* 258, 0x102 */ SDL_SCANCODE_UNKNOWN,
/* 259, 0x103 */ SDL_SCANCODE_UNKNOWN,
/* 260, 0x104 */ SDL_SCANCODE_UNKNOWN,
/* 261, 0x105 */ SDL_SCANCODE_UNKNOWN,
/* 262, 0x106 */ SDL_SCANCODE_UNKNOWN,
/* 263, 0x107 */ SDL_SCANCODE_UNKNOWN,
/* 264, 0x108 */ SDL_SCANCODE_UNKNOWN,
/* 265, 0x109 */ SDL_SCANCODE_UNKNOWN,
/* 266, 0x10a */ SDL_SCANCODE_UNKNOWN,
/* 267, 0x10b */ SDL_SCANCODE_UNKNOWN,
/* 268, 0x10c */ SDL_SCANCODE_UNKNOWN,
/* 269, 0x10d */ SDL_SCANCODE_UNKNOWN,
/* 270, 0x10e */ SDL_SCANCODE_UNKNOWN,
/* 271, 0x10f */ SDL_SCANCODE_UNKNOWN,
/* 272, 0x110 */ SDL_SCANCODE_UNKNOWN,
/* 273, 0x111 */ SDL_SCANCODE_UNKNOWN,
/* 274, 0x112 */ SDL_SCANCODE_UNKNOWN,
/* 275, 0x113 */ SDL_SCANCODE_UNKNOWN,
/* 276, 0x114 */ SDL_SCANCODE_UNKNOWN,
/* 277, 0x115 */ SDL_SCANCODE_UNKNOWN,
/* 278, 0x116 */ SDL_SCANCODE_UNKNOWN,
/* 279, 0x117 */ SDL_SCANCODE_UNKNOWN,
/* 280, 0x118 */ SDL_SCANCODE_UNKNOWN,
/* 281, 0x119 */ SDL_SCANCODE_UNKNOWN,
/* 282, 0x11a */ SDL_SCANCODE_UNKNOWN,
/* 283, 0x11b */ SDL_SCANCODE_UNKNOWN,
/* 284, 0x11c */ SDL_SCANCODE_UNKNOWN,
/* 285, 0x11d */ SDL_SCANCODE_UNKNOWN,
/* 286, 0x11e */ SDL_SCANCODE_UNKNOWN,
/* 287, 0x11f */ SDL_SCANCODE_UNKNOWN,
/* 288, 0x120 */ SDL_SCANCODE_UNKNOWN,
/* 289, 0x121 */ SDL_SCANCODE_UNKNOWN,
/* 290, 0x122 */ SDL_SCANCODE_UNKNOWN,
/* 291, 0x123 */ SDL_SCANCODE_UNKNOWN,
/* 292, 0x124 */ SDL_SCANCODE_UNKNOWN,
/* 293, 0x125 */ SDL_SCANCODE_UNKNOWN,
/* 294, 0x126 */ SDL_SCANCODE_UNKNOWN,
/* 295, 0x127 */ SDL_SCANCODE_UNKNOWN,
/* 296, 0x128 */ SDL_SCANCODE_UNKNOWN,
/* 297, 0x129 */ SDL_SCANCODE_UNKNOWN,
/* 298, 0x12a */ SDL_SCANCODE_UNKNOWN,
/* 299, 0x12b */ SDL_SCANCODE_UNKNOWN,
/* 300, 0x12c */ SDL_SCANCODE_UNKNOWN,
/* 301, 0x12d */ SDL_SCANCODE_UNKNOWN,
/* 302, 0x12e */ SDL_SCANCODE_UNKNOWN,
/* 303, 0x12f */ SDL_SCANCODE_UNKNOWN,
/* 304, 0x130 */ SDL_SCANCODE_UNKNOWN,
/* 305, 0x131 */ SDL_SCANCODE_UNKNOWN,
/* 306, 0x132 */ SDL_SCANCODE_UNKNOWN,
/* 307, 0x133 */ SDL_SCANCODE_UNKNOWN,
/* 308, 0x134 */ SDL_SCANCODE_UNKNOWN,
/* 309, 0x135 */ SDL_SCANCODE_UNKNOWN,
/* 310, 0x136 */ SDL_SCANCODE_UNKNOWN,
/* 311, 0x137 */ SDL_SCANCODE_UNKNOWN,
/* 312, 0x138 */ SDL_SCANCODE_UNKNOWN,
/* 313, 0x139 */ SDL_SCANCODE_UNKNOWN,
/* 314, 0x13a */ SDL_SCANCODE_UNKNOWN,
/* 315, 0x13b */ SDL_SCANCODE_UNKNOWN,
/* 316, 0x13c */ SDL_SCANCODE_UNKNOWN,
/* 317, 0x13d */ SDL_SCANCODE_UNKNOWN,
/* 318, 0x13e */ SDL_SCANCODE_UNKNOWN,
/* 319, 0x13f */ SDL_SCANCODE_UNKNOWN,
/* 320, 0x140 */ SDL_SCANCODE_UNKNOWN,
/* 321, 0x141 */ SDL_SCANCODE_UNKNOWN,
/* 322, 0x142 */ SDL_SCANCODE_UNKNOWN,
/* 323, 0x143 */ SDL_SCANCODE_UNKNOWN,
/* 324, 0x144 */ SDL_SCANCODE_UNKNOWN,
/* 325, 0x145 */ SDL_SCANCODE_UNKNOWN,
/* 326, 0x146 */ SDL_SCANCODE_UNKNOWN,
/* 327, 0x147 */ SDL_SCANCODE_UNKNOWN,
/* 328, 0x148 */ SDL_SCANCODE_UNKNOWN,
/* 329, 0x149 */ SDL_SCANCODE_UNKNOWN,
/* 330, 0x14a */ SDL_SCANCODE_UNKNOWN,
/* 331, 0x14b */ SDL_SCANCODE_UNKNOWN,
/* 332, 0x14c */ SDL_SCANCODE_UNKNOWN,
/* 333, 0x14d */ SDL_SCANCODE_UNKNOWN,
/* 334, 0x14e */ SDL_SCANCODE_UNKNOWN,
/* 335, 0x14f */ SDL_SCANCODE_UNKNOWN,
/* 336, 0x150 */ SDL_SCANCODE_UNKNOWN,
/* 337, 0x151 */ SDL_SCANCODE_UNKNOWN,
/* 338, 0x152 */ SDL_SCANCODE_UNKNOWN,
/* 339, 0x153 */ SDL_SCANCODE_UNKNOWN,
/* 340, 0x154 */ SDL_SCANCODE_UNKNOWN,
/* 341, 0x155 */ SDL_SCANCODE_UNKNOWN,
/* 342, 0x156 */ SDL_SCANCODE_UNKNOWN,
/* 343, 0x157 */ SDL_SCANCODE_UNKNOWN,
/* 344, 0x158 */ SDL_SCANCODE_UNKNOWN,
/* 345, 0x159 */ SDL_SCANCODE_UNKNOWN,
/* 346, 0x15a */ SDL_SCANCODE_UNKNOWN,
/* 347, 0x15b */ SDL_SCANCODE_UNKNOWN,
/* 348, 0x15c */ SDL_SCANCODE_UNKNOWN,
/* 349, 0x15d */ SDL_SCANCODE_UNKNOWN,
/* 350, 0x15e */ SDL_SCANCODE_UNKNOWN,
/* 351, 0x15f */ SDL_SCANCODE_UNKNOWN,
/* 352, 0x160 */ SDL_SCANCODE_UNKNOWN, /* KEY_OK */
/* 353, 0x161 */ SDL_SCANCODE_UNKNOWN, /* KEY_SELECT */
/* 354, 0x162 */ SDL_SCANCODE_UNKNOWN, /* KEY_GOTO */
/* 355, 0x163 */ SDL_SCANCODE_UNKNOWN, /* KEY_CLEAR */
/* 356, 0x164 */ SDL_SCANCODE_UNKNOWN, /* KEY_POWER2 */
/* 357, 0x165 */ SDL_SCANCODE_UNKNOWN, /* KEY_OPTION */
/* 358, 0x166 */ SDL_SCANCODE_UNKNOWN, /* KEY_INFO */
/* 359, 0x167 */ SDL_SCANCODE_UNKNOWN, /* KEY_TIME */
/* 360, 0x168 */ SDL_SCANCODE_UNKNOWN, /* KEY_VENDOR */
/* 361, 0x169 */ SDL_SCANCODE_UNKNOWN, /* KEY_ARCHIVE */
/* 362, 0x16a */ SDL_SCANCODE_UNKNOWN, /* KEY_PROGRAM */
/* 363, 0x16b */ SDL_SCANCODE_UNKNOWN, /* KEY_CHANNEL */
/* 364, 0x16c */ SDL_SCANCODE_UNKNOWN, /* KEY_FAVORITES */
/* 365, 0x16d */ SDL_SCANCODE_UNKNOWN, /* KEY_EPG */
/* 366, 0x16e */ SDL_SCANCODE_UNKNOWN, /* KEY_PVR */
/* 367, 0x16f */ SDL_SCANCODE_UNKNOWN, /* KEY_MHP */
/* 368, 0x170 */ SDL_SCANCODE_UNKNOWN, /* KEY_LANGUAGE */
/* 369, 0x171 */ SDL_SCANCODE_UNKNOWN, /* KEY_TITLE */
/* 370, 0x172 */ SDL_SCANCODE_UNKNOWN, /* KEY_SUBTITLE */
/* 371, 0x173 */ SDL_SCANCODE_UNKNOWN, /* KEY_ANGLE */
/* 372, 0x174 */ SDL_SCANCODE_UNKNOWN, /* KEY_FULL_SCREEN */
/* 373, 0x175 */ SDL_SCANCODE_UNKNOWN, /* KEY_MODE */
/* 374, 0x176 */ SDL_SCANCODE_UNKNOWN, /* KEY_KEYBOARD */
/* 375, 0x177 */ SDL_SCANCODE_UNKNOWN, /* KEY_ASPECT_RATIO */
/* 376, 0x178 */ SDL_SCANCODE_UNKNOWN, /* KEY_PC */
/* 377, 0x179 */ SDL_SCANCODE_UNKNOWN, /* KEY_TV */
/* 378, 0x17a */ SDL_SCANCODE_UNKNOWN, /* KEY_TV2 */
/* 379, 0x17b */ SDL_SCANCODE_UNKNOWN, /* KEY_VCR */
/* 380, 0x17c */ SDL_SCANCODE_UNKNOWN, /* KEY_VCR2 */
/* 381, 0x17d */ SDL_SCANCODE_UNKNOWN, /* KEY_SAT */
/* 382, 0x17e */ SDL_SCANCODE_UNKNOWN, /* KEY_SAT2 */
/* 383, 0x17f */ SDL_SCANCODE_UNKNOWN, /* KEY_CD */
/* 384, 0x180 */ SDL_SCANCODE_UNKNOWN, /* KEY_TAPE */
/* 385, 0x181 */ SDL_SCANCODE_UNKNOWN, /* KEY_RADIO */
/* 386, 0x182 */ SDL_SCANCODE_UNKNOWN, /* KEY_TUNER */
/* 387, 0x183 */ SDL_SCANCODE_UNKNOWN, /* KEY_PLAYER */
/* 388, 0x184 */ SDL_SCANCODE_UNKNOWN, /* KEY_TEXT */
/* 389, 0x185 */ SDL_SCANCODE_UNKNOWN, /* KEY_DVD */
/* 390, 0x186 */ SDL_SCANCODE_UNKNOWN, /* KEY_AUX */
/* 391, 0x187 */ SDL_SCANCODE_UNKNOWN, /* KEY_MP3 */
/* 392, 0x188 */ SDL_SCANCODE_UNKNOWN, /* KEY_AUDIO */
/* 393, 0x189 */ SDL_SCANCODE_UNKNOWN, /* KEY_VIDEO */
/* 394, 0x18a */ SDL_SCANCODE_UNKNOWN, /* KEY_DIRECTORY */
/* 395, 0x18b */ SDL_SCANCODE_UNKNOWN, /* KEY_LIST */
/* 396, 0x18c */ SDL_SCANCODE_UNKNOWN, /* KEY_MEMO */
/* 397, 0x18d */ SDL_SCANCODE_UNKNOWN, /* KEY_CALENDAR */
/* 398, 0x18e */ SDL_SCANCODE_UNKNOWN, /* KEY_RED */
/* 399, 0x18f */ SDL_SCANCODE_UNKNOWN, /* KEY_GREEN */
/* 400, 0x190 */ SDL_SCANCODE_UNKNOWN, /* KEY_YELLOW */
/* 401, 0x191 */ SDL_SCANCODE_UNKNOWN, /* KEY_BLUE */
/* 402, 0x192 */ SDL_SCANCODE_UNKNOWN, /* KEY_CHANNELUP */
/* 403, 0x193 */ SDL_SCANCODE_UNKNOWN, /* KEY_CHANNELDOWN */
/* 404, 0x194 */ SDL_SCANCODE_UNKNOWN, /* KEY_FIRST */
/* 405, 0x195 */ SDL_SCANCODE_UNKNOWN, /* KEY_LAST */
/* 406, 0x196 */ SDL_SCANCODE_UNKNOWN, /* KEY_AB */
/* 407, 0x197 */ SDL_SCANCODE_UNKNOWN, /* KEY_NEXT */
/* 408, 0x198 */ SDL_SCANCODE_UNKNOWN, /* KEY_RESTART */
/* 409, 0x199 */ SDL_SCANCODE_UNKNOWN, /* KEY_SLOW */
/* 410, 0x19a */ SDL_SCANCODE_UNKNOWN, /* KEY_SHUFFLE */
/* 411, 0x19b */ SDL_SCANCODE_UNKNOWN, /* KEY_BREAK */
/* 412, 0x19c */ SDL_SCANCODE_UNKNOWN, /* KEY_PREVIOUS */
/* 413, 0x19d */ SDL_SCANCODE_UNKNOWN, /* KEY_DIGITS */
/* 414, 0x19e */ SDL_SCANCODE_UNKNOWN, /* KEY_TEEN */
/* 415, 0x19f */ SDL_SCANCODE_UNKNOWN, /* KEY_TWEN */
/* 416, 0x1a0 */ SDL_SCANCODE_UNKNOWN, /* KEY_VIDEOPHONE */
/* 417, 0x1a1 */ SDL_SCANCODE_UNKNOWN, /* KEY_GAMES */
/* 418, 0x1a2 */ SDL_SCANCODE_UNKNOWN, /* KEY_ZOOMIN */
/* 419, 0x1a3 */ SDL_SCANCODE_UNKNOWN, /* KEY_ZOOMOUT */
/* 420, 0x1a4 */ SDL_SCANCODE_UNKNOWN, /* KEY_ZOOMRESET */
/* 421, 0x1a5 */ SDL_SCANCODE_UNKNOWN, /* KEY_WORDPROCESSOR */
/* 422, 0x1a6 */ SDL_SCANCODE_UNKNOWN, /* KEY_EDITOR */
/* 423, 0x1a7 */ SDL_SCANCODE_UNKNOWN, /* KEY_SPREADSHEET */
/* 424, 0x1a8 */ SDL_SCANCODE_UNKNOWN, /* KEY_GRAPHICSEDITOR */
/* 425, 0x1a9 */ SDL_SCANCODE_UNKNOWN, /* KEY_PRESENTATION */
/* 426, 0x1aa */ SDL_SCANCODE_UNKNOWN, /* KEY_DATABASE */
/* 427, 0x1ab */ SDL_SCANCODE_UNKNOWN, /* KEY_NEWS */
/* 428, 0x1ac */ SDL_SCANCODE_UNKNOWN, /* KEY_VOICEMAIL */
/* 429, 0x1ad */ SDL_SCANCODE_UNKNOWN, /* KEY_ADDRESSBOOK */
/* 430, 0x1ae */ SDL_SCANCODE_UNKNOWN, /* KEY_MESSENGER */
/* 431, 0x1af */ SDL_SCANCODE_UNKNOWN, /* KEY_DISPLAYTOGGLE */
/* 432, 0x1b0 */ SDL_SCANCODE_UNKNOWN, /* KEY_SPELLCHECK */
/* 433, 0x1b1 */ SDL_SCANCODE_UNKNOWN, /* KEY_LOGOFF */
/* 434, 0x1b2 */ SDL_SCANCODE_UNKNOWN, /* KEY_DOLLAR */
/* 435, 0x1b3 */ SDL_SCANCODE_UNKNOWN, /* KEY_EURO */
/* 436, 0x1b4 */ SDL_SCANCODE_UNKNOWN, /* KEY_FRAMEBACK */
/* 437, 0x1b5 */ SDL_SCANCODE_UNKNOWN, /* KEY_FRAMEFORWARD */
/* 438, 0x1b6 */ SDL_SCANCODE_UNKNOWN, /* KEY_CONTEXT_MENU */
/* 439, 0x1b7 */ SDL_SCANCODE_UNKNOWN, /* KEY_MEDIA_REPEAT */
/* 440, 0x1b8 */ SDL_SCANCODE_UNKNOWN, /* KEY_10CHANNELSUP */
/* 441, 0x1b9 */ SDL_SCANCODE_UNKNOWN, /* KEY_10CHANNELSDOWN */
/* 442, 0x1ba */ SDL_SCANCODE_UNKNOWN, /* KEY_IMAGES */
/* 443, 0x1bb */ SDL_SCANCODE_UNKNOWN,
/* 444, 0x1bc */ SDL_SCANCODE_UNKNOWN, /* KEY_NOTIFICATION_CENTER */
/* 445, 0x1bd */ SDL_SCANCODE_UNKNOWN, /* KEY_PICKUP_PHONE */
/* 446, 0x1be */ SDL_SCANCODE_UNKNOWN, /* KEY_HANGUP_PHONE */
/* 447, 0x1bf */ SDL_SCANCODE_UNKNOWN,
/* 448, 0x1c0 */ SDL_SCANCODE_UNKNOWN, /* KEY_DEL_EOL */
/* 449, 0x1c1 */ SDL_SCANCODE_UNKNOWN, /* KEY_DEL_EOS */
/* 450, 0x1c2 */ SDL_SCANCODE_UNKNOWN, /* KEY_INS_LINE */
/* 451, 0x1c3 */ SDL_SCANCODE_UNKNOWN, /* KEY_DEL_LINE */
/* 452, 0x1c4 */ SDL_SCANCODE_UNKNOWN,
/* 453, 0x1c5 */ SDL_SCANCODE_UNKNOWN,
/* 454, 0x1c6 */ SDL_SCANCODE_UNKNOWN,
/* 455, 0x1c7 */ SDL_SCANCODE_UNKNOWN,
/* 456, 0x1c8 */ SDL_SCANCODE_UNKNOWN,
/* 457, 0x1c9 */ SDL_SCANCODE_UNKNOWN,
/* 458, 0x1ca */ SDL_SCANCODE_UNKNOWN,
/* 459, 0x1cb */ SDL_SCANCODE_UNKNOWN,
/* 460, 0x1cc */ SDL_SCANCODE_UNKNOWN,
/* 461, 0x1cd */ SDL_SCANCODE_UNKNOWN,
/* 462, 0x1ce */ SDL_SCANCODE_UNKNOWN,
/* 463, 0x1cf */ SDL_SCANCODE_UNKNOWN,
/* 464, 0x1d0 */ SDL_SCANCODE_UNKNOWN, /* KEY_FN */
/* 465, 0x1d1 */ SDL_SCANCODE_UNKNOWN, /* KEY_FN_ESC */
/* 466, 0x1d2 */ SDL_SCANCODE_UNKNOWN, /* KEY_FN_F1 */
/* 467, 0x1d3 */ SDL_SCANCODE_UNKNOWN, /* KEY_FN_F2 */
/* 468, 0x1d4 */ SDL_SCANCODE_UNKNOWN, /* KEY_FN_F3 */
/* 469, 0x1d5 */ SDL_SCANCODE_UNKNOWN, /* KEY_FN_F4 */
/* 470, 0x1d6 */ SDL_SCANCODE_UNKNOWN, /* KEY_FN_F5 */
/* 471, 0x1d7 */ SDL_SCANCODE_UNKNOWN, /* KEY_FN_F6 */
/* 472, 0x1d8 */ SDL_SCANCODE_UNKNOWN, /* KEY_FN_F7 */
/* 473, 0x1d9 */ SDL_SCANCODE_UNKNOWN, /* KEY_FN_F8 */
/* 474, 0x1da */ SDL_SCANCODE_UNKNOWN, /* KEY_FN_F9 */
/* 475, 0x1db */ SDL_SCANCODE_UNKNOWN, /* KEY_FN_F10 */
/* 476, 0x1dc */ SDL_SCANCODE_UNKNOWN, /* KEY_FN_F11 */
/* 477, 0x1dd */ SDL_SCANCODE_UNKNOWN, /* KEY_FN_F12 */
/* 478, 0x1de */ SDL_SCANCODE_UNKNOWN, /* KEY_FN_1 */
/* 479, 0x1df */ SDL_SCANCODE_UNKNOWN, /* KEY_FN_2 */
/* 480, 0x1e0 */ SDL_SCANCODE_UNKNOWN, /* KEY_FN_D */
/* 481, 0x1e1 */ SDL_SCANCODE_UNKNOWN, /* KEY_FN_E */
/* 482, 0x1e2 */ SDL_SCANCODE_UNKNOWN, /* KEY_FN_F */
/* 483, 0x1e3 */ SDL_SCANCODE_UNKNOWN, /* KEY_FN_S */
/* 484, 0x1e4 */ SDL_SCANCODE_UNKNOWN, /* KEY_FN_B */
/* 485, 0x1e5 */ SDL_SCANCODE_UNKNOWN, /* KEY_FN_RIGHT_SHIFT */
/* 486, 0x1e6 */ SDL_SCANCODE_UNKNOWN,
/* 487, 0x1e7 */ SDL_SCANCODE_UNKNOWN,
/* 488, 0x1e8 */ SDL_SCANCODE_UNKNOWN,
/* 489, 0x1e9 */ SDL_SCANCODE_UNKNOWN,
/* 490, 0x1ea */ SDL_SCANCODE_UNKNOWN,
/* 491, 0x1eb */ SDL_SCANCODE_UNKNOWN,
/* 492, 0x1ec */ SDL_SCANCODE_UNKNOWN,
/* 493, 0x1ed */ SDL_SCANCODE_UNKNOWN,
/* 494, 0x1ee */ SDL_SCANCODE_UNKNOWN,
/* 495, 0x1ef */ SDL_SCANCODE_UNKNOWN,
/* 496, 0x1f0 */ SDL_SCANCODE_UNKNOWN,
/* 497, 0x1f1 */ SDL_SCANCODE_UNKNOWN, /* KEY_BRL_DOT1 */
/* 498, 0x1f2 */ SDL_SCANCODE_UNKNOWN, /* KEY_BRL_DOT2 */
/* 499, 0x1f3 */ SDL_SCANCODE_UNKNOWN, /* KEY_BRL_DOT3 */
/* 500, 0x1f4 */ SDL_SCANCODE_UNKNOWN, /* KEY_BRL_DOT4 */
/* 501, 0x1f5 */ SDL_SCANCODE_UNKNOWN, /* KEY_BRL_DOT5 */
/* 502, 0x1f6 */ SDL_SCANCODE_UNKNOWN, /* KEY_BRL_DOT6 */
/* 503, 0x1f7 */ SDL_SCANCODE_UNKNOWN, /* KEY_BRL_DOT7 */
/* 504, 0x1f8 */ SDL_SCANCODE_UNKNOWN, /* KEY_BRL_DOT8 */
/* 505, 0x1f9 */ SDL_SCANCODE_UNKNOWN, /* KEY_BRL_DOT9 */
/* 506, 0x1fa */ SDL_SCANCODE_UNKNOWN, /* KEY_BRL_DOT10 */
/* 507, 0x1fb */ SDL_SCANCODE_UNKNOWN,
/* 508, 0x1fc */ SDL_SCANCODE_UNKNOWN,
/* 509, 0x1fd */ SDL_SCANCODE_UNKNOWN,
/* 510, 0x1fe */ SDL_SCANCODE_UNKNOWN,
/* 511, 0x1ff */ SDL_SCANCODE_UNKNOWN,
/* 512, 0x200 */ SDL_SCANCODE_UNKNOWN, /* KEY_NUMERIC_0 */
/* 513, 0x201 */ SDL_SCANCODE_UNKNOWN, /* KEY_NUMERIC_1 */
/* 514, 0x202 */ SDL_SCANCODE_UNKNOWN, /* KEY_NUMERIC_2 */
/* 515, 0x203 */ SDL_SCANCODE_UNKNOWN, /* KEY_NUMERIC_3 */
/* 516, 0x204 */ SDL_SCANCODE_UNKNOWN, /* KEY_NUMERIC_4 */
/* 517, 0x205 */ SDL_SCANCODE_UNKNOWN, /* KEY_NUMERIC_5 */
/* 518, 0x206 */ SDL_SCANCODE_UNKNOWN, /* KEY_NUMERIC_6 */
/* 519, 0x207 */ SDL_SCANCODE_UNKNOWN, /* KEY_NUMERIC_7 */
/* 520, 0x208 */ SDL_SCANCODE_UNKNOWN, /* KEY_NUMERIC_8 */
/* 521, 0x209 */ SDL_SCANCODE_UNKNOWN, /* KEY_NUMERIC_9 */
/* 522, 0x20a */ SDL_SCANCODE_UNKNOWN, /* KEY_NUMERIC_STAR */
/* 523, 0x20b */ SDL_SCANCODE_UNKNOWN, /* KEY_NUMERIC_POUND */
/* 524, 0x20c */ SDL_SCANCODE_UNKNOWN, /* KEY_NUMERIC_A */
/* 525, 0x20d */ SDL_SCANCODE_UNKNOWN, /* KEY_NUMERIC_B */
/* 526, 0x20e */ SDL_SCANCODE_UNKNOWN, /* KEY_NUMERIC_C */
/* 527, 0x20f */ SDL_SCANCODE_UNKNOWN, /* KEY_NUMERIC_D */
/* 528, 0x210 */ SDL_SCANCODE_UNKNOWN, /* KEY_CAMERA_FOCUS */
/* 529, 0x211 */ SDL_SCANCODE_UNKNOWN, /* KEY_WPS_BUTTON */
/* 530, 0x212 */ SDL_SCANCODE_UNKNOWN, /* KEY_TOUCHPAD_TOGGLE */
/* 531, 0x213 */ SDL_SCANCODE_UNKNOWN, /* KEY_TOUCHPAD_ON */
/* 532, 0x214 */ SDL_SCANCODE_UNKNOWN, /* KEY_TOUCHPAD_OFF */
/* 533, 0x215 */ SDL_SCANCODE_UNKNOWN, /* KEY_CAMERA_ZOOMIN */
/* 534, 0x216 */ SDL_SCANCODE_UNKNOWN, /* KEY_CAMERA_ZOOMOUT */
/* 535, 0x217 */ SDL_SCANCODE_UNKNOWN, /* KEY_CAMERA_UP */
/* 536, 0x218 */ SDL_SCANCODE_UNKNOWN, /* KEY_CAMERA_DOWN */
/* 537, 0x219 */ SDL_SCANCODE_UNKNOWN, /* KEY_CAMERA_LEFT */
/* 538, 0x21a */ SDL_SCANCODE_UNKNOWN, /* KEY_CAMERA_RIGHT */
/* 539, 0x21b */ SDL_SCANCODE_UNKNOWN, /* KEY_ATTENDANT_ON */
/* 540, 0x21c */ SDL_SCANCODE_UNKNOWN, /* KEY_ATTENDANT_OFF */
/* 541, 0x21d */ SDL_SCANCODE_UNKNOWN, /* KEY_ATTENDANT_TOGGLE */
/* 542, 0x21e */ SDL_SCANCODE_UNKNOWN, /* KEY_LIGHTS_TOGGLE */
/* 543, 0x21f */ SDL_SCANCODE_UNKNOWN,
/* 544, 0x220 */ SDL_SCANCODE_UNKNOWN,
/* 545, 0x221 */ SDL_SCANCODE_UNKNOWN,
/* 546, 0x222 */ SDL_SCANCODE_UNKNOWN,
/* 547, 0x223 */ SDL_SCANCODE_UNKNOWN,
/* 548, 0x224 */ SDL_SCANCODE_UNKNOWN,
/* 549, 0x225 */ SDL_SCANCODE_UNKNOWN,
/* 550, 0x226 */ SDL_SCANCODE_UNKNOWN,
/* 551, 0x227 */ SDL_SCANCODE_UNKNOWN,
/* 552, 0x228 */ SDL_SCANCODE_UNKNOWN,
/* 553, 0x229 */ SDL_SCANCODE_UNKNOWN,
/* 554, 0x22a */ SDL_SCANCODE_UNKNOWN,
/* 555, 0x22b */ SDL_SCANCODE_UNKNOWN,
/* 556, 0x22c */ SDL_SCANCODE_UNKNOWN,
/* 557, 0x22d */ SDL_SCANCODE_UNKNOWN,
/* 558, 0x22e */ SDL_SCANCODE_UNKNOWN,
/* 559, 0x22f */ SDL_SCANCODE_UNKNOWN,
/* 560, 0x230 */ SDL_SCANCODE_UNKNOWN, /* KEY_ALS_TOGGLE */
/* 561, 0x231 */ SDL_SCANCODE_UNKNOWN, /* KEY_ROTATE_LOCK_TOGGLE */
/* 562, 0x232 */ SDL_SCANCODE_UNKNOWN,
/* 563, 0x233 */ SDL_SCANCODE_UNKNOWN,
/* 564, 0x234 */ SDL_SCANCODE_UNKNOWN,
/* 565, 0x235 */ SDL_SCANCODE_UNKNOWN,
/* 566, 0x236 */ SDL_SCANCODE_UNKNOWN,
/* 567, 0x237 */ SDL_SCANCODE_UNKNOWN,
/* 568, 0x238 */ SDL_SCANCODE_UNKNOWN,
/* 569, 0x239 */ SDL_SCANCODE_UNKNOWN,
/* 570, 0x23a */ SDL_SCANCODE_UNKNOWN,
/* 571, 0x23b */ SDL_SCANCODE_UNKNOWN,
/* 572, 0x23c */ SDL_SCANCODE_UNKNOWN,
/* 573, 0x23d */ SDL_SCANCODE_UNKNOWN,
/* 574, 0x23e */ SDL_SCANCODE_UNKNOWN,
/* 575, 0x23f */ SDL_SCANCODE_UNKNOWN,
/* 576, 0x240 */ SDL_SCANCODE_UNKNOWN, /* KEY_BUTTONCONFIG */
/* 577, 0x241 */ SDL_SCANCODE_UNKNOWN, /* KEY_TASKMANAGER */
/* 578, 0x242 */ SDL_SCANCODE_UNKNOWN, /* KEY_JOURNAL */
/* 579, 0x243 */ SDL_SCANCODE_UNKNOWN, /* KEY_CONTROLPANEL */
/* 580, 0x244 */ SDL_SCANCODE_UNKNOWN, /* KEY_APPSELECT */
/* 581, 0x245 */ SDL_SCANCODE_UNKNOWN, /* KEY_SCREENSAVER */
/* 582, 0x246 */ SDL_SCANCODE_UNKNOWN, /* KEY_VOICECOMMAND */
/* 583, 0x247 */ SDL_SCANCODE_UNKNOWN, /* KEY_ASSISTANT */
/* 584, 0x248 */ SDL_SCANCODE_UNKNOWN, /* KEY_KBD_LAYOUT_NEXT */
/* 585, 0x249 */ SDL_SCANCODE_UNKNOWN, /* KEY_EMOJI_PICKER */
/* 586, 0x24a */ SDL_SCANCODE_UNKNOWN, /* KEY_DICTATE */
/* 587, 0x24b */ SDL_SCANCODE_UNKNOWN,
/* 588, 0x24c */ SDL_SCANCODE_UNKNOWN,
/* 589, 0x24d */ SDL_SCANCODE_UNKNOWN,
/* 590, 0x24e */ SDL_SCANCODE_UNKNOWN,
/* 591, 0x24f */ SDL_SCANCODE_UNKNOWN,
/* 592, 0x250 */ SDL_SCANCODE_UNKNOWN, /* KEY_BRIGHTNESS_MIN */
/* 593, 0x251 */ SDL_SCANCODE_UNKNOWN, /* KEY_BRIGHTNESS_MAX */
/* 594, 0x252 */ SDL_SCANCODE_UNKNOWN,
/* 595, 0x253 */ SDL_SCANCODE_UNKNOWN,
/* 596, 0x254 */ SDL_SCANCODE_UNKNOWN,
/* 597, 0x255 */ SDL_SCANCODE_UNKNOWN,
/* 598, 0x256 */ SDL_SCANCODE_UNKNOWN,
/* 599, 0x257 */ SDL_SCANCODE_UNKNOWN,
/* 600, 0x258 */ SDL_SCANCODE_UNKNOWN,
/* 601, 0x259 */ SDL_SCANCODE_UNKNOWN,
/* 602, 0x25a */ SDL_SCANCODE_UNKNOWN,
/* 603, 0x25b */ SDL_SCANCODE_UNKNOWN,
/* 604, 0x25c */ SDL_SCANCODE_UNKNOWN,
/* 605, 0x25d */ SDL_SCANCODE_UNKNOWN,
/* 606, 0x25e */ SDL_SCANCODE_UNKNOWN,
/* 607, 0x25f */ SDL_SCANCODE_UNKNOWN,
/* 608, 0x260 */ SDL_SCANCODE_UNKNOWN, /* KEY_KBDINPUTASSIST_PREV */
/* 609, 0x261 */ SDL_SCANCODE_UNKNOWN, /* KEY_KBDINPUTASSIST_NEXT */
/* 610, 0x262 */ SDL_SCANCODE_UNKNOWN, /* KEY_KBDINPUTASSIST_PREVGROUP */
/* 611, 0x263 */ SDL_SCANCODE_UNKNOWN, /* KEY_KBDINPUTASSIST_NEXTGROUP */
/* 612, 0x264 */ SDL_SCANCODE_UNKNOWN, /* KEY_KBDINPUTASSIST_ACCEPT */
/* 613, 0x265 */ SDL_SCANCODE_UNKNOWN, /* KEY_KBDINPUTASSIST_CANCEL */
/* 614, 0x266 */ SDL_SCANCODE_UNKNOWN, /* KEY_RIGHT_UP */
/* 615, 0x267 */ SDL_SCANCODE_UNKNOWN, /* KEY_RIGHT_DOWN */
/* 616, 0x268 */ SDL_SCANCODE_UNKNOWN, /* KEY_LEFT_UP */
/* 617, 0x269 */ SDL_SCANCODE_UNKNOWN, /* KEY_LEFT_DOWN */
/* 618, 0x26a */ SDL_SCANCODE_UNKNOWN, /* KEY_ROOT_MENU */
/* 619, 0x26b */ SDL_SCANCODE_UNKNOWN, /* KEY_MEDIA_TOP_MENU */
/* 620, 0x26c */ SDL_SCANCODE_UNKNOWN, /* KEY_NUMERIC_11 */
/* 621, 0x26d */ SDL_SCANCODE_UNKNOWN, /* KEY_NUMERIC_12 */
/* 622, 0x26e */ SDL_SCANCODE_UNKNOWN, /* KEY_AUDIO_DESC */
/* 623, 0x26f */ SDL_SCANCODE_UNKNOWN, /* KEY_3D_MODE */
/* 624, 0x270 */ SDL_SCANCODE_UNKNOWN, /* KEY_NEXT_FAVORITE */
/* 625, 0x271 */ SDL_SCANCODE_UNKNOWN, /* KEY_STOP_RECORD */
/* 626, 0x272 */ SDL_SCANCODE_UNKNOWN, /* KEY_PAUSE_RECORD */
/* 627, 0x273 */ SDL_SCANCODE_UNKNOWN, /* KEY_VOD */
/* 628, 0x274 */ SDL_SCANCODE_UNKNOWN, /* KEY_UNMUTE */
/* 629, 0x275 */ SDL_SCANCODE_UNKNOWN, /* KEY_FASTREVERSE */
/* 630, 0x276 */ SDL_SCANCODE_UNKNOWN, /* KEY_SLOWREVERSE */
/* 631, 0x277 */ SDL_SCANCODE_UNKNOWN, /* KEY_DATA */
/* 632, 0x278 */ SDL_SCANCODE_UNKNOWN, /* KEY_ONSCREEN_KEYBOARD */
/* 633, 0x279 */ SDL_SCANCODE_UNKNOWN, /* KEY_PRIVACY_SCREEN_TOGGLE */
/* 634, 0x27a */ SDL_SCANCODE_UNKNOWN, /* KEY_SELECTIVE_SCREENSHOT */
/* 635, 0x27b */ SDL_SCANCODE_UNKNOWN,
/* 636, 0x27c */ SDL_SCANCODE_UNKNOWN,
/* 637, 0x27d */ SDL_SCANCODE_UNKNOWN,
/* 638, 0x27e */ SDL_SCANCODE_UNKNOWN,
/* 639, 0x27f */ SDL_SCANCODE_UNKNOWN,
/* 640, 0x280 */ SDL_SCANCODE_UNKNOWN,
/* 641, 0x281 */ SDL_SCANCODE_UNKNOWN,
/* 642, 0x282 */ SDL_SCANCODE_UNKNOWN,
/* 643, 0x283 */ SDL_SCANCODE_UNKNOWN,
/* 644, 0x284 */ SDL_SCANCODE_UNKNOWN,
/* 645, 0x285 */ SDL_SCANCODE_UNKNOWN,
/* 646, 0x286 */ SDL_SCANCODE_UNKNOWN,
/* 647, 0x287 */ SDL_SCANCODE_UNKNOWN,
/* 648, 0x288 */ SDL_SCANCODE_UNKNOWN,
/* 649, 0x289 */ SDL_SCANCODE_UNKNOWN,
/* 650, 0x28a */ SDL_SCANCODE_UNKNOWN,
/* 651, 0x28b */ SDL_SCANCODE_UNKNOWN,
/* 652, 0x28c */ SDL_SCANCODE_UNKNOWN,
/* 653, 0x28d */ SDL_SCANCODE_UNKNOWN,
/* 654, 0x28e */ SDL_SCANCODE_UNKNOWN,
/* 655, 0x28f */ SDL_SCANCODE_UNKNOWN,
/* 656, 0x290 */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO1 */
/* 657, 0x291 */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO2 */
/* 658, 0x292 */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO3 */
/* 659, 0x293 */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO4 */
/* 660, 0x294 */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO5 */
/* 661, 0x295 */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO6 */
/* 662, 0x296 */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO7 */
/* 663, 0x297 */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO8 */
/* 664, 0x298 */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO9 */
/* 665, 0x299 */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO10 */
/* 666, 0x29a */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO11 */
/* 667, 0x29b */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO12 */
/* 668, 0x29c */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO13 */
/* 669, 0x29d */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO14 */
/* 670, 0x29e */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO15 */
/* 671, 0x29f */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO16 */
/* 672, 0x2a0 */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO17 */
/* 673, 0x2a1 */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO18 */
/* 674, 0x2a2 */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO19 */
/* 675, 0x2a3 */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO20 */
/* 676, 0x2a4 */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO21 */
/* 677, 0x2a5 */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO22 */
/* 678, 0x2a6 */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO23 */
/* 679, 0x2a7 */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO24 */
/* 680, 0x2a8 */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO25 */
/* 681, 0x2a9 */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO26 */
/* 682, 0x2aa */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO27 */
/* 683, 0x2ab */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO28 */
/* 684, 0x2ac */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO29 */
/* 685, 0x2ad */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO30 */
/* 686, 0x2ae */ SDL_SCANCODE_UNKNOWN,
/* 687, 0x2af */ SDL_SCANCODE_UNKNOWN,
/* 688, 0x2b0 */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO_RECORD_START */
/* 689, 0x2b1 */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO_RECORD_STOP */
/* 690, 0x2b2 */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO_PRESET_CYCLE */
/* 691, 0x2b3 */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO_PRESET1 */
/* 692, 0x2b4 */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO_PRESET2 */
/* 693, 0x2b5 */ SDL_SCANCODE_UNKNOWN, /* KEY_MACRO_PRESET3 */
/* 694, 0x2b6 */ SDL_SCANCODE_UNKNOWN,
/* 695, 0x2b7 */ SDL_SCANCODE_UNKNOWN,
/* 696, 0x2b8 */ SDL_SCANCODE_UNKNOWN, /* KEY_KBD_LCD_MENU1 */
/* 697, 0x2b9 */ SDL_SCANCODE_UNKNOWN, /* KEY_KBD_LCD_MENU2 */
/* 698, 0x2ba */ SDL_SCANCODE_UNKNOWN, /* KEY_KBD_LCD_MENU3 */
/* 699, 0x2bb */ SDL_SCANCODE_UNKNOWN, /* KEY_KBD_LCD_MENU4 */
/* 700, 0x2bc */ SDL_SCANCODE_UNKNOWN, /* KEY_KBD_LCD_MENU5 */
/* 701, 0x2bd */ SDL_SCANCODE_UNKNOWN,
/* 702, 0x2be */ SDL_SCANCODE_UNKNOWN,
/* 703, 0x2bf */ SDL_SCANCODE_UNKNOWN,
/* 704, 0x2c0 */ SDL_SCANCODE_UNKNOWN,
/* 705, 0x2c1 */ SDL_SCANCODE_UNKNOWN,
/* 706, 0x2c2 */ SDL_SCANCODE_UNKNOWN,
/* 707, 0x2c3 */ SDL_SCANCODE_UNKNOWN,
/* 708, 0x2c4 */ SDL_SCANCODE_UNKNOWN,
/* 709, 0x2c5 */ SDL_SCANCODE_UNKNOWN,
/* 710, 0x2c6 */ SDL_SCANCODE_UNKNOWN,
/* 711, 0x2c7 */ SDL_SCANCODE_UNKNOWN,
/* 712, 0x2c8 */ SDL_SCANCODE_UNKNOWN,
/* 713, 0x2c9 */ SDL_SCANCODE_UNKNOWN,
/* 714, 0x2ca */ SDL_SCANCODE_UNKNOWN,
/* 715, 0x2cb */ SDL_SCANCODE_UNKNOWN,
/* 716, 0x2cc */ SDL_SCANCODE_UNKNOWN,
/* 717, 0x2cd */ SDL_SCANCODE_UNKNOWN,
/* 718, 0x2ce */ SDL_SCANCODE_UNKNOWN,
/* 719, 0x2cf */ SDL_SCANCODE_UNKNOWN,
/* 720, 0x2d0 */ SDL_SCANCODE_UNKNOWN,
/* 721, 0x2d1 */ SDL_SCANCODE_UNKNOWN,
/* 722, 0x2d2 */ SDL_SCANCODE_UNKNOWN,
/* 723, 0x2d3 */ SDL_SCANCODE_UNKNOWN,
/* 724, 0x2d4 */ SDL_SCANCODE_UNKNOWN,
/* 725, 0x2d5 */ SDL_SCANCODE_UNKNOWN,
/* 726, 0x2d6 */ SDL_SCANCODE_UNKNOWN,
/* 727, 0x2d7 */ SDL_SCANCODE_UNKNOWN,
/* 728, 0x2d8 */ SDL_SCANCODE_UNKNOWN,
/* 729, 0x2d9 */ SDL_SCANCODE_UNKNOWN,
/* 730, 0x2da */ SDL_SCANCODE_UNKNOWN,
/* 731, 0x2db */ SDL_SCANCODE_UNKNOWN,
/* 732, 0x2dc */ SDL_SCANCODE_UNKNOWN,
/* 733, 0x2dd */ SDL_SCANCODE_UNKNOWN,
/* 734, 0x2de */ SDL_SCANCODE_UNKNOWN,
/* 735, 0x2df */ SDL_SCANCODE_UNKNOWN,
/* 736, 0x2e0 */ SDL_SCANCODE_UNKNOWN,
/* 737, 0x2e1 */ SDL_SCANCODE_UNKNOWN,
/* 738, 0x2e2 */ SDL_SCANCODE_UNKNOWN,
/* 739, 0x2e3 */ SDL_SCANCODE_UNKNOWN,
/* 740, 0x2e4 */ SDL_SCANCODE_UNKNOWN,
/* 741, 0x2e5 */ SDL_SCANCODE_UNKNOWN,
/* 742, 0x2e6 */ SDL_SCANCODE_UNKNOWN,
/* 743, 0x2e7 */ SDL_SCANCODE_UNKNOWN,
/* 744, 0x2e8 */ SDL_SCANCODE_UNKNOWN,
/* 745, 0x2e9 */ SDL_SCANCODE_UNKNOWN,
/* 746, 0x2ea */ SDL_SCANCODE_UNKNOWN,
/* 747, 0x2eb */ SDL_SCANCODE_UNKNOWN,
/* 748, 0x2ec */ SDL_SCANCODE_UNKNOWN,
/* 749, 0x2ed */ SDL_SCANCODE_UNKNOWN,
/* 750, 0x2ee */ SDL_SCANCODE_UNKNOWN,
/* 751, 0x2ef */ SDL_SCANCODE_UNKNOWN,
/* 752, 0x2f0 */ SDL_SCANCODE_UNKNOWN,
/* 753, 0x2f1 */ SDL_SCANCODE_UNKNOWN,
/* 754, 0x2f2 */ SDL_SCANCODE_UNKNOWN,
/* 755, 0x2f3 */ SDL_SCANCODE_UNKNOWN,
/* 756, 0x2f4 */ SDL_SCANCODE_UNKNOWN,
/* 757, 0x2f5 */ SDL_SCANCODE_UNKNOWN,
/* 758, 0x2f6 */ SDL_SCANCODE_UNKNOWN,
/* 759, 0x2f7 */ SDL_SCANCODE_UNKNOWN,
/* 760, 0x2f8 */ SDL_SCANCODE_UNKNOWN,
/* 761, 0x2f9 */ SDL_SCANCODE_UNKNOWN,
/* 762, 0x2fa */ SDL_SCANCODE_UNKNOWN,
/* 763, 0x2fb */ SDL_SCANCODE_UNKNOWN,
/* 764, 0x2fc */ SDL_SCANCODE_UNKNOWN,
/* 765, 0x2fd */ SDL_SCANCODE_UNKNOWN,
/* 766, 0x2fe */ SDL_SCANCODE_UNKNOWN,
/* 767, 0x2ff */ SDL_SCANCODE_UNKNOWN, /* KEY_MAX */
#endif /* 0 */
};
#if 0 /* A shell script to update the Linux key names in this file */
#!/bin/bash
function get_keyname
{
value=$(echo "$1" | awk '{print $3}')
grep -F KEY_ /usr/include/linux/input-event-codes.h | while read line; do
read -ra fields <<<"$line"
if [ "${fields[2]}" = "$value" ]; then
echo "${fields[1]}"
return
fi
done
}
grep -F SDL_SCANCODE scancodes_linux.h | while read line; do
if [ $(echo "$line" | awk '{print NF}') -eq 5 ]; then
name=$(get_keyname "$line")
if [ "$name" != "" ]; then
echo " $line /* $name */"
continue
fi
fi
echo " $line"
done
#endif /* end script */
#if 0 /* A shell script to get comments from the Linux header for these keys */
#!/bin/bash
function get_comment
{
name=$(echo "$1" | awk '{print $7}')
if [ "$name" != "" ]; then
grep -E "$name\s" /usr/include/linux/input-event-codes.h | grep -F "/*" | sed 's,[^/]*/,/,'
fi
}
grep -F SDL_SCANCODE scancodes_linux.h | while read line; do
comment=$(get_comment "$line")
if [ "$comment" != "" ]; then
echo " $line $comment"
fi
done
#endif /* end script */
/* *INDENT-ON* */ /* clang-format on */
|
dc644a5597d69fa6d6eee0deb3b82ef5bc0b771b
|
e1d9c54e9925e30e388a255b53a93cccad0b94cb
|
/kubernetes/model/v1_label_selector.c
|
5739a34f07614a94e88667e4a139a373a2745721
|
[
"Apache-2.0",
"curl"
] |
permissive
|
kubernetes-client/c
|
dd4fd8095485c083e0f40f2b48159b1609a6141b
|
5ac5ff25e9809a92a48111b1f77574b6d040b711
|
refs/heads/master
| 2023-08-13T10:51:03.702497
| 2023-08-07T19:18:32
| 2023-08-07T19:18:32
| 247,958,425
| 127
| 47
|
Apache-2.0
| 2023-09-07T20:07:00
| 2020-03-17T11:59:05
|
C
|
UTF-8
|
C
| false
| false
| 6,208
|
c
|
v1_label_selector.c
|
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "v1_label_selector.h"
v1_label_selector_t *v1_label_selector_create(
list_t *match_expressions,
list_t* match_labels
) {
v1_label_selector_t *v1_label_selector_local_var = malloc(sizeof(v1_label_selector_t));
if (!v1_label_selector_local_var) {
return NULL;
}
v1_label_selector_local_var->match_expressions = match_expressions;
v1_label_selector_local_var->match_labels = match_labels;
return v1_label_selector_local_var;
}
void v1_label_selector_free(v1_label_selector_t *v1_label_selector) {
if(NULL == v1_label_selector){
return ;
}
listEntry_t *listEntry;
if (v1_label_selector->match_expressions) {
list_ForEach(listEntry, v1_label_selector->match_expressions) {
v1_label_selector_requirement_free(listEntry->data);
}
list_freeList(v1_label_selector->match_expressions);
v1_label_selector->match_expressions = NULL;
}
if (v1_label_selector->match_labels) {
list_ForEach(listEntry, v1_label_selector->match_labels) {
keyValuePair_t *localKeyValue = (keyValuePair_t*) listEntry->data;
free (localKeyValue->key);
free (localKeyValue->value);
keyValuePair_free(localKeyValue);
}
list_freeList(v1_label_selector->match_labels);
v1_label_selector->match_labels = NULL;
}
free(v1_label_selector);
}
cJSON *v1_label_selector_convertToJSON(v1_label_selector_t *v1_label_selector) {
cJSON *item = cJSON_CreateObject();
// v1_label_selector->match_expressions
if(v1_label_selector->match_expressions) {
cJSON *match_expressions = cJSON_AddArrayToObject(item, "matchExpressions");
if(match_expressions == NULL) {
goto fail; //nonprimitive container
}
listEntry_t *match_expressionsListEntry;
if (v1_label_selector->match_expressions) {
list_ForEach(match_expressionsListEntry, v1_label_selector->match_expressions) {
cJSON *itemLocal = v1_label_selector_requirement_convertToJSON(match_expressionsListEntry->data);
if(itemLocal == NULL) {
goto fail;
}
cJSON_AddItemToArray(match_expressions, itemLocal);
}
}
}
// v1_label_selector->match_labels
if(v1_label_selector->match_labels) {
cJSON *match_labels = cJSON_AddObjectToObject(item, "matchLabels");
if(match_labels == NULL) {
goto fail; //primitive map container
}
cJSON *localMapObject = match_labels;
listEntry_t *match_labelsListEntry;
if (v1_label_selector->match_labels) {
list_ForEach(match_labelsListEntry, v1_label_selector->match_labels) {
keyValuePair_t *localKeyValue = (keyValuePair_t*)match_labelsListEntry->data;
if(cJSON_AddStringToObject(localMapObject, localKeyValue->key, (char*)localKeyValue->value) == NULL)
{
goto fail;
}
}
}
}
return item;
fail:
if (item) {
cJSON_Delete(item);
}
return NULL;
}
v1_label_selector_t *v1_label_selector_parseFromJSON(cJSON *v1_label_selectorJSON){
v1_label_selector_t *v1_label_selector_local_var = NULL;
// define the local list for v1_label_selector->match_expressions
list_t *match_expressionsList = NULL;
// define the local map for v1_label_selector->match_labels
list_t *match_labelsList = NULL;
// v1_label_selector->match_expressions
cJSON *match_expressions = cJSON_GetObjectItemCaseSensitive(v1_label_selectorJSON, "matchExpressions");
if (match_expressions) {
cJSON *match_expressions_local_nonprimitive = NULL;
if(!cJSON_IsArray(match_expressions)){
goto end; //nonprimitive container
}
match_expressionsList = list_createList();
cJSON_ArrayForEach(match_expressions_local_nonprimitive,match_expressions )
{
if(!cJSON_IsObject(match_expressions_local_nonprimitive)){
goto end;
}
v1_label_selector_requirement_t *match_expressionsItem = v1_label_selector_requirement_parseFromJSON(match_expressions_local_nonprimitive);
list_addElement(match_expressionsList, match_expressionsItem);
}
}
// v1_label_selector->match_labels
cJSON *match_labels = cJSON_GetObjectItemCaseSensitive(v1_label_selectorJSON, "matchLabels");
if (match_labels) {
cJSON *match_labels_local_map = NULL;
if(!cJSON_IsObject(match_labels) && !cJSON_IsNull(match_labels))
{
goto end;//primitive map container
}
if(cJSON_IsObject(match_labels))
{
match_labelsList = list_createList();
keyValuePair_t *localMapKeyPair;
cJSON_ArrayForEach(match_labels_local_map, match_labels)
{
cJSON *localMapObject = match_labels_local_map;
if(!cJSON_IsString(localMapObject))
{
goto end;
}
localMapKeyPair = keyValuePair_create(strdup(localMapObject->string),strdup(localMapObject->valuestring));
list_addElement(match_labelsList , localMapKeyPair);
}
}
}
v1_label_selector_local_var = v1_label_selector_create (
match_expressions ? match_expressionsList : NULL,
match_labels ? match_labelsList : NULL
);
return v1_label_selector_local_var;
end:
if (match_expressionsList) {
listEntry_t *listEntry = NULL;
list_ForEach(listEntry, match_expressionsList) {
v1_label_selector_requirement_free(listEntry->data);
listEntry->data = NULL;
}
list_freeList(match_expressionsList);
match_expressionsList = NULL;
}
if (match_labelsList) {
listEntry_t *listEntry = NULL;
list_ForEach(listEntry, match_labelsList) {
keyValuePair_t *localKeyValue = (keyValuePair_t*) listEntry->data;
free(localKeyValue->key);
localKeyValue->key = NULL;
free(localKeyValue->value);
localKeyValue->value = NULL;
keyValuePair_free(localKeyValue);
localKeyValue = NULL;
}
list_freeList(match_labelsList);
match_labelsList = NULL;
}
return NULL;
}
|
99becdd28f46e3e16295a8fd43ff104328c7e249
|
d2d15560a3ca4f8146d9baec60d1ce6743b13633
|
/ext/qml/js_array.h
|
1242478efb9c0cbd31819e22fadd2cdd2195e754
|
[
"MIT"
] |
permissive
|
seanchas116/ruby-qml
|
4ecd3728962cb4f4ea8791bd91e9666825ce289f
|
569af4c31460d2946c18346dc94751c77b1d4dfc
|
refs/heads/master
| 2021-01-21T12:31:27.975059
| 2019-11-17T08:13:34
| 2019-11-17T08:13:34
| 21,888,221
| 141
| 20
|
MIT
| 2019-11-17T08:13:35
| 2014-07-16T05:35:33
|
Ruby
|
UTF-8
|
C
| false
| false
| 100
|
h
|
js_array.h
|
#pragma once
#include "js_object.h"
extern VALUE rbqml_cJSArray;
void rbqml_init_js_array(void);
|
bc2865dbb6189e495d63897a07b191a041a75027
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/drivers/media/rc/fintek-cir.h
|
82516a1d39b0777d7e591ef89f850b1cce1f1310
|
[
"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
| 6,651
|
h
|
fintek-cir.h
|
/*
* Driver for Feature Integration Technology Inc. (aka Fintek) LPC CIR
*
* Copyright (C) 2011 Jarod Wilson <jarod@redhat.com>
*
* Special thanks to Fintek for providing hardware and spec sheets.
* This driver is based upon the nuvoton, ite and ene drivers for
* similar hardware.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
#include <linux/spinlock.h>
#include <linux/ioctl.h>
/* platform driver name to register */
#define FINTEK_DRIVER_NAME "fintek-cir"
#define FINTEK_DESCRIPTION "Fintek LPC SuperIO Consumer IR Transceiver"
#define VENDOR_ID_FINTEK 0x1934
/* debugging module parameter */
static int debug;
#define fit_pr(level, text, ...) \
printk(level KBUILD_MODNAME ": " text, ## __VA_ARGS__)
#define fit_dbg(text, ...) \
if (debug) \
printk(KERN_DEBUG \
KBUILD_MODNAME ": " text "\n" , ## __VA_ARGS__)
#define fit_dbg_verbose(text, ...) \
if (debug > 1) \
printk(KERN_DEBUG \
KBUILD_MODNAME ": " text "\n" , ## __VA_ARGS__)
#define fit_dbg_wake(text, ...) \
if (debug > 2) \
printk(KERN_DEBUG \
KBUILD_MODNAME ": " text "\n" , ## __VA_ARGS__)
#define TX_BUF_LEN 256
#define RX_BUF_LEN 32
struct fintek_dev {
struct pnp_dev *pdev;
struct rc_dev *rdev;
spinlock_t fintek_lock;
/* for rx */
u8 buf[RX_BUF_LEN];
unsigned int pkts;
struct {
spinlock_t lock;
u8 buf[TX_BUF_LEN];
unsigned int buf_count;
unsigned int cur_buf_num;
wait_queue_head_t queue;
} tx;
/* Config register index/data port pair */
u8 cr_ip;
u8 cr_dp;
/* hardware I/O settings */
unsigned long cir_addr;
int cir_irq;
int cir_port_len;
/* hardware id */
u8 chip_major;
u8 chip_minor;
u16 chip_vendor;
u8 logical_dev_cir;
/* hardware features */
bool hw_learning_capable;
bool hw_tx_capable;
/* rx settings */
bool learning_enabled;
bool carrier_detect_enabled;
enum {
CMD_HEADER = 0,
SUBCMD,
CMD_DATA,
PARSE_IRDATA,
} parser_state;
u8 cmd, rem;
/* carrier period = 1 / frequency */
u32 carrier;
};
/* buffer packet constants, largely identical to mceusb.c */
#define BUF_PULSE_BIT 0x80
#define BUF_LEN_MASK 0x1f
#define BUF_SAMPLE_MASK 0x7f
#define BUF_COMMAND_HEADER 0x9f
#define BUF_COMMAND_MASK 0xe0
#define BUF_COMMAND_NULL 0x00
#define BUF_HW_CMD_HEADER 0xff
#define BUF_CMD_G_REVISION 0x0b
#define BUF_CMD_S_CARRIER 0x06
#define BUF_CMD_S_TIMEOUT 0x0c
#define BUF_CMD_SIG_END 0x01
#define BUF_CMD_S_TXMASK 0x08
#define BUF_CMD_S_RXSENSOR 0x14
#define BUF_RSP_PULSE_COUNT 0x15
#define CIR_SAMPLE_PERIOD 50
/*
* Configuration Register:
* Index Port
* Data Port
*/
#define CR_INDEX_PORT 0x2e
#define CR_DATA_PORT 0x2f
/* Possible alternate values, depends on how the chip is wired */
#define CR_INDEX_PORT2 0x4e
#define CR_DATA_PORT2 0x4f
/*
* GCR_CONFIG_PORT_SEL bit 4 specifies which Index Port value is
* active. 1 = 0x4e, 0 = 0x2e
*/
#define PORT_SEL_PORT_4E_EN 0x10
/* Extended Function Mode enable/disable magic values */
#define CONFIG_REG_ENABLE 0x87
#define CONFIG_REG_DISABLE 0xaa
/* Chip IDs found in CR_CHIP_ID_{HI,LO} */
#define CHIP_ID_HIGH_F71809U 0x04
#define CHIP_ID_LOW_F71809U 0x08
/*
* Global control regs we need to care about:
* Global Control def.
* Register name addr val. */
#define GCR_SOFTWARE_RESET 0x02 /* 0x00 */
#define GCR_LOGICAL_DEV_NO 0x07 /* 0x00 */
#define GCR_CHIP_ID_HI 0x20 /* 0x04 */
#define GCR_CHIP_ID_LO 0x21 /* 0x08 */
#define GCR_VENDOR_ID_HI 0x23 /* 0x19 */
#define GCR_VENDOR_ID_LO 0x24 /* 0x34 */
#define GCR_CONFIG_PORT_SEL 0x25 /* 0x01 */
#define GCR_KBMOUSE_WAKEUP 0x27
#define LOGICAL_DEV_DISABLE 0x00
#define LOGICAL_DEV_ENABLE 0x01
/* Logical device number of the CIR function */
#define LOGICAL_DEV_CIR_REV1 0x05
#define LOGICAL_DEV_CIR_REV2 0x08
/* CIR Logical Device (LDN 0x08) config registers */
#define CIR_CR_COMMAND_INDEX 0x04
#define CIR_CR_IRCS 0x05 /* Before host writes command to IR, host
must set to 1. When host finshes write
command to IR, host must clear to 0. */
#define CIR_CR_COMMAND_DATA 0x06 /* Host read or write comand data */
#define CIR_CR_CLASS 0x07 /* 0xff = rx-only, 0x66 = rx + 2 tx,
0x33 = rx + 1 tx */
#define CIR_CR_DEV_EN 0x30 /* bit0 = 1 enables CIR */
#define CIR_CR_BASE_ADDR_HI 0x60 /* MSB of CIR IO base addr */
#define CIR_CR_BASE_ADDR_LO 0x61 /* LSB of CIR IO base addr */
#define CIR_CR_IRQ_SEL 0x70 /* bits3-0 store CIR IRQ */
#define CIR_CR_PSOUT_STATUS 0xf1
#define CIR_CR_WAKE_KEY3_ADDR 0xf8
#define CIR_CR_WAKE_KEY3_CODE 0xf9
#define CIR_CR_WAKE_KEY3_DC 0xfa
#define CIR_CR_WAKE_CONTROL 0xfb
#define CIR_CR_WAKE_KEY12_ADDR 0xfc
#define CIR_CR_WAKE_KEY4_ADDR 0xfd
#define CIR_CR_WAKE_KEY5_ADDR 0xfe
#define CLASS_RX_ONLY 0xff
#define CLASS_RX_2TX 0x66
#define CLASS_RX_1TX 0x33
/* CIR device registers */
#define CIR_STATUS 0x00
#define CIR_RX_DATA 0x01
#define CIR_TX_CONTROL 0x02
#define CIR_TX_DATA 0x03
#define CIR_CONTROL 0x04
/* Bits to enable CIR wake */
#define LOGICAL_DEV_ACPI 0x01
#define LDEV_ACPI_WAKE_EN_REG 0xe8
#define ACPI_WAKE_EN_CIR_BIT 0x04
#define LDEV_ACPI_PME_EN_REG 0xf0
#define LDEV_ACPI_PME_CLR_REG 0xf1
#define ACPI_PME_CIR_BIT 0x02
#define LDEV_ACPI_STATE_REG 0xf4
#define ACPI_STATE_CIR_BIT 0x20
/*
* CIR status register (0x00):
* 7 - CIR_IRQ_EN (1 = enable CIR IRQ, 0 = disable)
* 3 - TX_FINISH (1 when TX finished, write 1 to clear)
* 2 - TX_UNDERRUN (1 on TX underrun, write 1 to clear)
* 1 - RX_TIMEOUT (1 on RX timeout, write 1 to clear)
* 0 - RX_RECEIVE (1 on RX receive, write 1 to clear)
*/
#define CIR_STATUS_IRQ_EN 0x80
#define CIR_STATUS_TX_FINISH 0x08
#define CIR_STATUS_TX_UNDERRUN 0x04
#define CIR_STATUS_RX_TIMEOUT 0x02
#define CIR_STATUS_RX_RECEIVE 0x01
#define CIR_STATUS_IRQ_MASK 0x0f
/*
* CIR TX control register (0x02):
* 7 - TX_START (1 to indicate TX start, auto-cleared when done)
* 6 - TX_END (1 to indicate TX data written to TX fifo)
*/
#define CIR_TX_CONTROL_TX_START 0x80
#define CIR_TX_CONTROL_TX_END 0x40
|
ecc2a625337ed6497e976f368435d3b61716be8c
|
8a87f5b889a9ce7d81421515f06d9c9cbf6ce64a
|
/3rdParty/V8/v7.9.317/third_party/icu/source/samples/layout/pflow.c
|
92d521ca6ee73da2cff24d6ce8867167ff3dd57f
|
[
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-unicode",
"ICU",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"NAIST-2003",
"MIT",
"bzip2-1.0.6",
"Apache-2.0",
"SunPro",
"Zlib",
"GPL-1.0-or-later",
"OpenSSL",
"ISC",
"LicenseRef-scancode-gutenberg-2020",
"GPL-2.0-only",
"CC0-1.0",
"BSL-1.0",
"LicenseRef-scancode-autoconf-simple-exception",
"LicenseRef-scancode-pcre",
"Bison-exception-2.2",
"JSON",
"Unlicense",
"BSD-4-Clause",
"Python-2.0",
"LGPL-2.1-or-later"
] |
permissive
|
arangodb/arangodb
|
0980625e76c56a2449d90dcb8d8f2c485e28a83b
|
43c40535cee37fc7349a21793dc33b1833735af5
|
refs/heads/devel
| 2023-08-31T09:34:47.451950
| 2023-08-31T07:25:02
| 2023-08-31T07:25:02
| 2,649,214
| 13,385
| 982
|
Apache-2.0
| 2023-09-14T17:02:16
| 2011-10-26T06:42:00
|
C++
|
UTF-8
|
C
| false
| false
| 9,490
|
c
|
pflow.c
|
/*
*
* © 2016 and later: Unicode, Inc. and others.
* License & terms of use: http://www.unicode.org/copyright.html#License
*
* (C) Copyright IBM Corp. 1998-2007 - All Rights Reserved
*
*/
#include "unicode/utypes.h"
#include "unicode/uchar.h"
#include "unicode/ubidi.h"
#include "unicode/ustring.h"
#include "layout/LETypes.h"
#include "layout/loengine.h"
#include "layout/playout.h"
#include "layout/plruns.h"
#include "pflow.h"
#include "arraymem.h"
#include "ucreader.h"
/*
* Move the line below out of this comment
* to add a locale run to the pl_paragraphs
* that are created.
#define TEST_LOCALE "zh_TW"
*/
#define MARGIN 10
#define LINE_GROW 32
#define PARA_GROW 8
#define CH_LF 0x000A
#define CH_CR 0x000D
#define CH_LSEP 0x2028
#define CH_PSEP 0x2029
struct pf_object
{
pl_paragraph **fParagraphLayout;
le_int32 fParagraphCount;
le_int32 fParagraphMax;
le_int32 fParagraphGrow;
le_int32 fLineCount;
le_int32 fLinesMax;
le_int32 fLinesGrow;
pl_line **fLines;
LEUnicode *fChars;
le_int32 fLineHeight;
le_int32 fAscent;
le_int32 fWidth;
le_int32 fHeight;
UBiDiLevel fParagraphLevel;
};
typedef struct pf_object pf_object;
static LEUnicode *skipLineEnd(LEUnicode *ptr)
{
if (ptr[0] == CH_CR && ptr[1] == CH_LF) {
ptr += 1;
}
return ptr + 1;
}
static le_int32 findFontRun(const pl_fontRuns *fontRuns, le_int32 offset)
{
le_int32 runCount = pl_getFontRunCount(fontRuns);
le_int32 run;
for (run = 0; run < runCount; run += 1) {
if (pl_getFontRunLimit(fontRuns, run) > offset) {
return run;
}
}
return -1;
}
static void subsetFontRuns(const pl_fontRuns *fontRuns, le_int32 start, le_int32 limit, pl_fontRuns *sub)
{
le_int32 startRun = findFontRun(fontRuns, start);
le_int32 endRun = findFontRun(fontRuns, limit - 1);
le_int32 run;
pl_resetFontRuns(sub);
for (run = startRun; run <= endRun; run += 1) {
const le_font *runFont = pl_getFontRunFont(fontRuns, run);
le_int32 runLimit = pl_getFontRunLimit(fontRuns, run) - start;
if (run == endRun) {
runLimit = limit - start;
}
pl_addFontRun(sub, runFont, runLimit);
}
}
pf_flow *pf_create(const LEUnicode chars[], le_int32 charCount, const pl_fontRuns *fontRuns, LEErrorCode *status)
{
pf_object *flow;
le_int32 ascent = 0;
le_int32 descent = 0;
le_int32 leading = 0;
pl_localeRuns *locales = NULL;
pl_fontRuns *fr;
LEUnicode *pStart;
static const LEUnicode separators[] = {CH_LF, CH_CR, CH_LSEP, CH_PSEP, 0x0000};
if (LE_FAILURE(*status)) {
return NULL;
}
flow = NEW_ARRAY(pf_object, 1);
flow->fParagraphLayout = NULL;
flow->fParagraphCount = 0;
flow->fParagraphMax = PARA_GROW;
flow->fParagraphGrow = PARA_GROW;
flow->fLineCount = 0;
flow->fLinesMax = LINE_GROW;
flow->fLinesGrow = LINE_GROW;
flow->fLines = NULL;
flow->fChars = NULL;
flow->fLineHeight = -1;
flow->fAscent = -1;
flow->fWidth = -1;
flow->fHeight = -1;
flow->fParagraphLevel = UBIDI_DEFAULT_LTR;
fr = pl_openEmptyFontRuns(0);
#ifdef TEST_LOCALE
locales = pl_openEmptyLocaleRuns(0);
#endif
flow->fLines = NEW_ARRAY(pl_line *, flow->fLinesMax);
flow->fParagraphLayout = NEW_ARRAY(pl_paragraph *, flow->fParagraphMax);
flow->fChars = NEW_ARRAY(LEUnicode, charCount + 1);
LE_ARRAY_COPY(flow->fChars, chars, charCount);
flow->fChars[charCount] = 0;
pStart = &flow->fChars[0];
while (*pStart != 0) {
LEUnicode *pEnd = u_strpbrk(pStart, separators);
le_int32 pAscent, pDescent, pLeading;
pl_paragraph *paragraphLayout = NULL;
if (pEnd == NULL) {
pEnd = &flow->fChars[charCount];
}
if (pEnd != pStart) {
subsetFontRuns(fontRuns, pStart - flow->fChars, pEnd - flow->fChars, fr);
#ifdef TEST_LOCALE
pl_resetLocaleRuns(locales);
pl_addLocaleRun(locales, TEST_LOCALE, pEnd - pStart);
#endif
paragraphLayout = pl_create(pStart, pEnd - pStart, fr, NULL, NULL, locales, flow->fParagraphLevel, FALSE, status);
if (LE_FAILURE(*status)) {
break; /* return? something else? */
}
if (flow->fParagraphLevel == UBIDI_DEFAULT_LTR) {
flow->fParagraphLevel = pl_getParagraphLevel(paragraphLayout);
}
pAscent = pl_getAscent(paragraphLayout);
pDescent = pl_getDescent(paragraphLayout);
pLeading = pl_getLeading(paragraphLayout);
if (pAscent > ascent) {
ascent = pAscent;
}
if (pDescent > descent) {
descent = pDescent;
}
if (pLeading > leading) {
leading = pLeading;
}
}
if (flow->fParagraphCount >= flow->fParagraphMax) {
flow->fParagraphLayout = (pl_paragraph **) GROW_ARRAY(flow->fParagraphLayout, flow->fParagraphMax + flow->fParagraphGrow);
flow->fParagraphMax += flow->fParagraphGrow;
}
flow->fParagraphLayout[flow->fParagraphCount++] = paragraphLayout;
if (*pEnd == 0) {
break;
}
pStart = skipLineEnd(pEnd);
}
flow->fLineHeight = ascent + descent + leading;
flow->fAscent = ascent;
pl_closeLocaleRuns(locales);
pl_closeFontRuns(fr);
return (pf_flow *) flow;
}
void pf_close(pf_flow *flow)
{
pf_object *obj = (pf_object *) flow;
le_int32 i;
for (i = 0; i < obj->fLineCount; i += 1) {
DELETE_ARRAY(obj->fLines[i]);
}
DELETE_ARRAY(obj->fLines);
for (i = 0; i < obj->fParagraphCount; i += 1) {
pl_close(obj->fParagraphLayout[i]);
}
DELETE_ARRAY(obj->fParagraphLayout);
DELETE_ARRAY(obj->fChars);
DELETE_ARRAY(obj);
}
le_int32 pf_getAscent(pf_flow *flow)
{
pf_object *obj = (pf_object *) flow;
return obj->fAscent;
}
le_int32 pf_getLineHeight(pf_flow *flow)
{
pf_object *obj = (pf_object *) flow;
return obj->fLineHeight;
}
le_int32 pf_getLineCount(pf_flow *flow)
{
pf_object *obj = (pf_object *) flow;
return obj->fLineCount;
}
static void addLine(pf_object *obj, pl_line *line)
{
if (obj->fLineCount >= obj->fLinesMax) {
obj->fLines = (pl_line **) GROW_ARRAY(obj->fLines, obj->fLinesMax + obj->fLinesGrow);
obj->fLinesMax += obj->fLinesGrow;
}
obj->fLines[obj->fLineCount++] = line;
}
void pf_breakLines(pf_flow *flow, le_int32 width, le_int32 height)
{
pf_object *obj = (pf_object *) flow;
le_int32 li, p;
float lineWidth;
pl_line *line;
obj->fHeight = height;
/* don't re-break if the width hasn't changed */
if (obj->fWidth == width) {
return;
}
obj->fWidth = width;
lineWidth = (float) (width - 2 * MARGIN);
/* Free the old Lines... */
for (li = 0; li < obj->fLineCount; li += 1) {
pl_closeLine(obj->fLines[li]);
}
obj->fLineCount = 0;
for (p = 0; p < obj->fParagraphCount; p += 1) {
pl_paragraph *paragraphLayout = obj->fParagraphLayout[p];
if (paragraphLayout != NULL) {
pl_reflow(paragraphLayout);
while ((line = pl_nextLine(paragraphLayout, lineWidth)) != NULL) {
addLine(obj, line);
}
} else {
addLine(obj, NULL);
}
}
}
void pf_draw(pf_flow *flow, rs_surface *surface, le_int32 firstLine, le_int32 lastLine)
{
pf_object *obj = (pf_object *) flow;
le_int32 li, x, y;
x = MARGIN;
y = obj->fAscent;
for (li = firstLine; li <= lastLine; li += 1) {
const pl_line *line = obj->fLines[li];
if (line != NULL) {
le_int32 runCount = pl_countLineRuns(line);
le_int32 run;
if (obj->fParagraphLevel == UBIDI_RTL) {
le_int32 lastX = pl_getLineWidth(line);
x = (obj->fWidth - lastX - MARGIN);
}
for (run = 0; run < runCount; run += 1) {
const pl_visualRun *visualRun = pl_getLineVisualRun(line, run);
le_int32 glyphCount = pl_getVisualRunGlyphCount(visualRun);
const le_font *font = pl_getVisualRunFont(visualRun);
const LEGlyphID *glyphs = pl_getVisualRunGlyphs(visualRun);
const float *positions = pl_getVisualRunPositions(visualRun);
rs_drawGlyphs(surface, font, glyphs, glyphCount, positions, x, y, obj->fWidth, obj->fHeight);
}
}
y += obj->fLineHeight;
}
}
pf_flow *pf_factory(const char *fileName, const le_font *font, gs_guiSupport *guiSupport)
{
LEErrorCode status = LE_NO_ERROR;
le_int32 charCount;
const UChar *text = uc_readFile(fileName, guiSupport, &charCount);
pl_fontRuns *fontRuns;
pf_flow *result = NULL;
if (text == NULL) {
return NULL;
}
fontRuns = pl_openEmptyFontRuns(0);
pl_addFontRun(fontRuns, font, charCount);
result = pf_create(text, charCount, fontRuns, &status);
if (LE_FAILURE(status)) {
pf_close(result);
result = NULL;
}
pl_closeFontRuns(fontRuns);
DELETE_ARRAY(text);
return result;
}
|
13e003f6630fb47bad8301b20a2c86d859e91f8b
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/drivers/video/backlight/tdo24m.c
|
18cdf466d50a5710ea73e0ae5d7ce34a5d188d83
|
[
"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
| 11,022
|
c
|
tdo24m.c
|
/*
* tdo24m - SPI-based drivers for Toppoly TDO24M series LCD panels
*
* Copyright (C) 2008 Marvell International Ltd.
* Eric Miao <eric.miao@marvell.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* publishhed by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/spi/spi.h>
#include <linux/spi/tdo24m.h>
#include <linux/fb.h>
#include <linux/lcd.h>
#include <linux/slab.h>
#define POWER_IS_ON(pwr) ((pwr) <= FB_BLANK_NORMAL)
#define TDO24M_SPI_BUFF_SIZE (4)
#define MODE_QVGA 0
#define MODE_VGA 1
struct tdo24m {
struct spi_device *spi_dev;
struct lcd_device *lcd_dev;
struct spi_message msg;
struct spi_transfer xfer;
uint8_t *buf;
int (*adj_mode)(struct tdo24m *lcd, int mode);
int color_invert;
int power;
int mode;
};
/* use bit 30, 31 as the indicator of command parameter number */
#define CMD0(x) ((0 << 30) | (x))
#define CMD1(x, x1) ((1 << 30) | ((x) << 9) | 0x100 | (x1))
#define CMD2(x, x1, x2) ((2 << 30) | ((x) << 18) | 0x20000 |\
((x1) << 9) | 0x100 | (x2))
#define CMD_NULL (-1)
static const uint32_t lcd_panel_reset[] = {
CMD0(0x1), /* reset */
CMD0(0x0), /* nop */
CMD0(0x0), /* nop */
CMD0(0x0), /* nop */
CMD_NULL,
};
static const uint32_t lcd_panel_on[] = {
CMD0(0x29), /* Display ON */
CMD2(0xB8, 0xFF, 0xF9), /* Output Control */
CMD0(0x11), /* Sleep out */
CMD1(0xB0, 0x16), /* Wake */
CMD_NULL,
};
static const uint32_t lcd_panel_off[] = {
CMD0(0x28), /* Display OFF */
CMD2(0xB8, 0x80, 0x02), /* Output Control */
CMD0(0x10), /* Sleep in */
CMD1(0xB0, 0x00), /* Deep stand by in */
CMD_NULL,
};
static const uint32_t lcd_vga_pass_through_tdo24m[] = {
CMD1(0xB0, 0x16),
CMD1(0xBC, 0x80),
CMD1(0xE1, 0x00),
CMD1(0x36, 0x50),
CMD1(0x3B, 0x00),
CMD_NULL,
};
static const uint32_t lcd_qvga_pass_through_tdo24m[] = {
CMD1(0xB0, 0x16),
CMD1(0xBC, 0x81),
CMD1(0xE1, 0x00),
CMD1(0x36, 0x50),
CMD1(0x3B, 0x22),
CMD_NULL,
};
static const uint32_t lcd_vga_transfer_tdo24m[] = {
CMD1(0xcf, 0x02), /* Blanking period control (1) */
CMD2(0xd0, 0x08, 0x04), /* Blanking period control (2) */
CMD1(0xd1, 0x01), /* CKV timing control on/off */
CMD2(0xd2, 0x14, 0x00), /* CKV 1,2 timing control */
CMD2(0xd3, 0x1a, 0x0f), /* OEV timing control */
CMD2(0xd4, 0x1f, 0xaf), /* ASW timing control (1) */
CMD1(0xd5, 0x14), /* ASW timing control (2) */
CMD0(0x21), /* Invert for normally black display */
CMD0(0x29), /* Display on */
CMD_NULL,
};
static const uint32_t lcd_qvga_transfer[] = {
CMD1(0xd6, 0x02), /* Blanking period control (1) */
CMD2(0xd7, 0x08, 0x04), /* Blanking period control (2) */
CMD1(0xd8, 0x01), /* CKV timing control on/off */
CMD2(0xd9, 0x00, 0x08), /* CKV 1,2 timing control */
CMD2(0xde, 0x05, 0x0a), /* OEV timing control */
CMD2(0xdf, 0x0a, 0x19), /* ASW timing control (1) */
CMD1(0xe0, 0x0a), /* ASW timing control (2) */
CMD0(0x21), /* Invert for normally black display */
CMD0(0x29), /* Display on */
CMD_NULL,
};
static const uint32_t lcd_vga_pass_through_tdo35s[] = {
CMD1(0xB0, 0x16),
CMD1(0xBC, 0x80),
CMD1(0xE1, 0x00),
CMD1(0x3B, 0x00),
CMD_NULL,
};
static const uint32_t lcd_qvga_pass_through_tdo35s[] = {
CMD1(0xB0, 0x16),
CMD1(0xBC, 0x81),
CMD1(0xE1, 0x00),
CMD1(0x3B, 0x22),
CMD_NULL,
};
static const uint32_t lcd_vga_transfer_tdo35s[] = {
CMD1(0xcf, 0x02), /* Blanking period control (1) */
CMD2(0xd0, 0x08, 0x04), /* Blanking period control (2) */
CMD1(0xd1, 0x01), /* CKV timing control on/off */
CMD2(0xd2, 0x00, 0x1e), /* CKV 1,2 timing control */
CMD2(0xd3, 0x14, 0x28), /* OEV timing control */
CMD2(0xd4, 0x28, 0x64), /* ASW timing control (1) */
CMD1(0xd5, 0x28), /* ASW timing control (2) */
CMD0(0x21), /* Invert for normally black display */
CMD0(0x29), /* Display on */
CMD_NULL,
};
static const uint32_t lcd_panel_config[] = {
CMD2(0xb8, 0xff, 0xf9), /* Output control */
CMD0(0x11), /* sleep out */
CMD1(0xba, 0x01), /* Display mode (1) */
CMD1(0xbb, 0x00), /* Display mode (2) */
CMD1(0x3a, 0x60), /* Display mode 18-bit RGB */
CMD1(0xbf, 0x10), /* Drive system change control */
CMD1(0xb1, 0x56), /* Booster operation setup */
CMD1(0xb2, 0x33), /* Booster mode setup */
CMD1(0xb3, 0x11), /* Booster frequency setup */
CMD1(0xb4, 0x02), /* Op amp/system clock */
CMD1(0xb5, 0x35), /* VCS voltage */
CMD1(0xb6, 0x40), /* VCOM voltage */
CMD1(0xb7, 0x03), /* External display signal */
CMD1(0xbd, 0x00), /* ASW slew rate */
CMD1(0xbe, 0x00), /* Dummy data for QuadData operation */
CMD1(0xc0, 0x11), /* Sleep out FR count (A) */
CMD1(0xc1, 0x11), /* Sleep out FR count (B) */
CMD1(0xc2, 0x11), /* Sleep out FR count (C) */
CMD2(0xc3, 0x20, 0x40), /* Sleep out FR count (D) */
CMD2(0xc4, 0x60, 0xc0), /* Sleep out FR count (E) */
CMD2(0xc5, 0x10, 0x20), /* Sleep out FR count (F) */
CMD1(0xc6, 0xc0), /* Sleep out FR count (G) */
CMD2(0xc7, 0x33, 0x43), /* Gamma 1 fine tuning (1) */
CMD1(0xc8, 0x44), /* Gamma 1 fine tuning (2) */
CMD1(0xc9, 0x33), /* Gamma 1 inclination adjustment */
CMD1(0xca, 0x00), /* Gamma 1 blue offset adjustment */
CMD2(0xec, 0x01, 0xf0), /* Horizontal clock cycles */
CMD_NULL,
};
static int tdo24m_writes(struct tdo24m *lcd, const uint32_t *array)
{
struct spi_transfer *x = &lcd->xfer;
const uint32_t *p = array;
uint32_t data;
int nparams, err = 0;
for (; *p != CMD_NULL; p++) {
if (!lcd->color_invert && *p == CMD0(0x21))
continue;
nparams = (*p >> 30) & 0x3;
data = *p << (7 - nparams);
switch (nparams) {
case 0:
lcd->buf[0] = (data >> 8) & 0xff;
lcd->buf[1] = data & 0xff;
break;
case 1:
lcd->buf[0] = (data >> 16) & 0xff;
lcd->buf[1] = (data >> 8) & 0xff;
lcd->buf[2] = data & 0xff;
break;
case 2:
lcd->buf[0] = (data >> 24) & 0xff;
lcd->buf[1] = (data >> 16) & 0xff;
lcd->buf[2] = (data >> 8) & 0xff;
lcd->buf[3] = data & 0xff;
break;
default:
continue;
}
x->len = nparams + 2;
err = spi_sync(lcd->spi_dev, &lcd->msg);
if (err)
break;
}
return err;
}
static int tdo24m_adj_mode(struct tdo24m *lcd, int mode)
{
switch (mode) {
case MODE_VGA:
tdo24m_writes(lcd, lcd_vga_pass_through_tdo24m);
tdo24m_writes(lcd, lcd_panel_config);
tdo24m_writes(lcd, lcd_vga_transfer_tdo24m);
break;
case MODE_QVGA:
tdo24m_writes(lcd, lcd_qvga_pass_through_tdo24m);
tdo24m_writes(lcd, lcd_panel_config);
tdo24m_writes(lcd, lcd_qvga_transfer);
break;
default:
return -EINVAL;
}
lcd->mode = mode;
return 0;
}
static int tdo35s_adj_mode(struct tdo24m *lcd, int mode)
{
switch (mode) {
case MODE_VGA:
tdo24m_writes(lcd, lcd_vga_pass_through_tdo35s);
tdo24m_writes(lcd, lcd_panel_config);
tdo24m_writes(lcd, lcd_vga_transfer_tdo35s);
break;
case MODE_QVGA:
tdo24m_writes(lcd, lcd_qvga_pass_through_tdo35s);
tdo24m_writes(lcd, lcd_panel_config);
tdo24m_writes(lcd, lcd_qvga_transfer);
break;
default:
return -EINVAL;
}
lcd->mode = mode;
return 0;
}
static int tdo24m_power_on(struct tdo24m *lcd)
{
int err;
err = tdo24m_writes(lcd, lcd_panel_on);
if (err)
goto out;
err = tdo24m_writes(lcd, lcd_panel_reset);
if (err)
goto out;
err = lcd->adj_mode(lcd, lcd->mode);
out:
return err;
}
static int tdo24m_power_off(struct tdo24m *lcd)
{
return tdo24m_writes(lcd, lcd_panel_off);
}
static int tdo24m_power(struct tdo24m *lcd, int power)
{
int ret = 0;
if (POWER_IS_ON(power) && !POWER_IS_ON(lcd->power))
ret = tdo24m_power_on(lcd);
else if (!POWER_IS_ON(power) && POWER_IS_ON(lcd->power))
ret = tdo24m_power_off(lcd);
if (!ret)
lcd->power = power;
return ret;
}
static int tdo24m_set_power(struct lcd_device *ld, int power)
{
struct tdo24m *lcd = lcd_get_data(ld);
return tdo24m_power(lcd, power);
}
static int tdo24m_get_power(struct lcd_device *ld)
{
struct tdo24m *lcd = lcd_get_data(ld);
return lcd->power;
}
static int tdo24m_set_mode(struct lcd_device *ld, struct fb_videomode *m)
{
struct tdo24m *lcd = lcd_get_data(ld);
int mode = MODE_QVGA;
if (m->xres == 640 || m->xres == 480)
mode = MODE_VGA;
if (lcd->mode == mode)
return 0;
return lcd->adj_mode(lcd, mode);
}
static struct lcd_ops tdo24m_ops = {
.get_power = tdo24m_get_power,
.set_power = tdo24m_set_power,
.set_mode = tdo24m_set_mode,
};
static int tdo24m_probe(struct spi_device *spi)
{
struct tdo24m *lcd;
struct spi_message *m;
struct spi_transfer *x;
struct tdo24m_platform_data *pdata;
enum tdo24m_model model;
int err;
pdata = spi->dev.platform_data;
if (pdata)
model = pdata->model;
else
model = TDO24M;
spi->bits_per_word = 8;
spi->mode = SPI_MODE_3;
err = spi_setup(spi);
if (err)
return err;
lcd = devm_kzalloc(&spi->dev, sizeof(struct tdo24m), GFP_KERNEL);
if (!lcd)
return -ENOMEM;
lcd->spi_dev = spi;
lcd->power = FB_BLANK_POWERDOWN;
lcd->mode = MODE_VGA; /* default to VGA */
lcd->buf = devm_kzalloc(&spi->dev, TDO24M_SPI_BUFF_SIZE, GFP_KERNEL);
if (lcd->buf == NULL)
return -ENOMEM;
m = &lcd->msg;
x = &lcd->xfer;
spi_message_init(m);
x->cs_change = 1;
x->tx_buf = &lcd->buf[0];
spi_message_add_tail(x, m);
switch (model) {
case TDO24M:
lcd->color_invert = 1;
lcd->adj_mode = tdo24m_adj_mode;
break;
case TDO35S:
lcd->adj_mode = tdo35s_adj_mode;
lcd->color_invert = 0;
break;
default:
dev_err(&spi->dev, "Unsupported model");
return -EINVAL;
}
lcd->lcd_dev = lcd_device_register("tdo24m", &spi->dev,
lcd, &tdo24m_ops);
if (IS_ERR(lcd->lcd_dev))
return PTR_ERR(lcd->lcd_dev);
spi_set_drvdata(spi, lcd);
err = tdo24m_power(lcd, FB_BLANK_UNBLANK);
if (err)
goto out_unregister;
return 0;
out_unregister:
lcd_device_unregister(lcd->lcd_dev);
return err;
}
static int tdo24m_remove(struct spi_device *spi)
{
struct tdo24m *lcd = spi_get_drvdata(spi);
tdo24m_power(lcd, FB_BLANK_POWERDOWN);
lcd_device_unregister(lcd->lcd_dev);
return 0;
}
#ifdef CONFIG_PM_SLEEP
static int tdo24m_suspend(struct device *dev)
{
struct tdo24m *lcd = dev_get_drvdata(dev);
return tdo24m_power(lcd, FB_BLANK_POWERDOWN);
}
static int tdo24m_resume(struct device *dev)
{
struct tdo24m *lcd = dev_get_drvdata(dev);
return tdo24m_power(lcd, FB_BLANK_UNBLANK);
}
#endif
static SIMPLE_DEV_PM_OPS(tdo24m_pm_ops, tdo24m_suspend, tdo24m_resume);
/* Power down all displays on reboot, poweroff or halt */
static void tdo24m_shutdown(struct spi_device *spi)
{
struct tdo24m *lcd = spi_get_drvdata(spi);
tdo24m_power(lcd, FB_BLANK_POWERDOWN);
}
static struct spi_driver tdo24m_driver = {
.driver = {
.name = "tdo24m",
.owner = THIS_MODULE,
.pm = &tdo24m_pm_ops,
},
.probe = tdo24m_probe,
.remove = tdo24m_remove,
.shutdown = tdo24m_shutdown,
};
module_spi_driver(tdo24m_driver);
MODULE_AUTHOR("Eric Miao <eric.miao@marvell.com>");
MODULE_DESCRIPTION("Driver for Toppoly TDO24M LCD Panel");
MODULE_LICENSE("GPL");
MODULE_ALIAS("spi:tdo24m");
|
f78d414d43256ef28df399bea6b09cf302da2a3e
|
53bf124408a1a34c64a95f9c116fd4dd3f4b7263
|
/ext/meryl/src/utility/src/utility/kmers-histogram.C
|
232807ec4c60da9049ec28622b45a607ee7790aa
|
[
"LicenseRef-scancode-public-domain",
"RSA-MD",
"MIT",
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
marbl/Winnowmap
|
611e591c5729f52a7c7175fcffe6eb5dd8f04860
|
45078cfa10de38a5521c21fb80d3ee3b06e4060d
|
refs/heads/master
| 2022-05-11T09:36:35.686463
| 2022-04-05T04:52:55
| 2022-04-05T04:52:55
| 239,658,722
| 194
| 17
| null | null | null | null |
UTF-8
|
C
| false
| false
| 5,115
|
c
|
kmers-histogram.C
|
/******************************************************************************
*
* This file is part of meryl-utility, a collection of miscellaneous code
* used by Meryl, Canu and others.
*
* This software is based on:
* 'Canu' v2.0 (https://github.com/marbl/canu)
* which is based on:
* 'Celera Assembler' r4587 (http://wgs-assembler.sourceforge.net)
* the 'kmer package' r1994 (http://kmer.sourceforge.net)
*
* Except as indicated otherwise, this is a 'United States Government Work',
* and is released in the public domain.
*
* File 'README.licenses' in the root directory of this distribution
* contains full conditions and disclaimers.
*/
#include "kmers.H"
merylHistogram::merylHistogram() {
_numUnique = 0;
_numDistinct = 0;
_numTotal = 0;
_histMax = 32 * 1024 * 1024; // 256 MB of histogram data.
_hist = new uint64 [_histMax];
for (uint64 ii=0; ii<_histMax; ii++)
_hist[ii] = 0;
_histLen = 0;
_histVs = NULL;
_histOs = NULL;
}
merylHistogram::~merylHistogram() {
delete [] _hist;
delete [] _histVs;
delete [] _histOs;
}
void
merylHistogram::clear(void) {
_numUnique = 0;
_numDistinct = 0;
_numTotal = 0;
for (uint64 ii=0; ii<_histMax; ii++)
_hist[ii] = 0;
_histBig.clear();
delete [] _histVs;
delete [] _histOs;
_histLen = 0;
_histVs = NULL;
_histOs = NULL;
}
void
merylHistogram::dump(stuffedBits *bits) {
// This only writes the latest version.
bits->setBinary(64, _numUnique);
bits->setBinary(64, _numDistinct);
bits->setBinary(64, _numTotal);
// Find the maximum value, and count how many values we have
// in the histogram.
uint64 numValues = _histBig.size();
for (uint32 ii=0; ii<_histMax; ii++)
if (_hist[ii] > 0)
numValues++;
bits->setBinary(64, numValues);
// Now the data!
for (uint32 ii=0; ii<_histMax; ii++) {
if (_hist[ii] > 0) {
bits->setBinary(64, ii); // Value
bits->setBinary(64, _hist[ii]); // Number of occurrences
}
}
for (auto it=_histBig.begin(); it != _histBig.end(); it++) {
bits->setBinary(64, it->first); // Value
bits->setBinary(64, it->second); // Number of occurrences
}
}
void
merylHistogram::dump(FILE *outFile) {
stuffedBits *bits = new stuffedBits;
dump(bits);
bits->dumpToFile(outFile);
delete bits;
}
void
merylHistogram::load_v01(stuffedBits *bits) {
uint32 histLast;
uint32 hbigLen;
_numUnique = bits->getBinary(64);
_numDistinct = bits->getBinary(64);
_numTotal = bits->getBinary(64);
histLast = bits->getBinary(32);
hbigLen = bits->getBinary(32);
//fprintf(stderr, "merylHistogram::load_v01()-- %lu %lu %lu %u %u\n",
// _numUnique, _numDistinct, _numTotal, histLast, hbigLen);
// Load the histogram values.
uint64 *hist = new uint64 [histLast + 1];
hist = bits->getBinary(64, histLast, hist);
// (over) allocate space for the histogram list.
_histVs = new uint64 [histLast + hbigLen + 1];
_histOs = new uint64 [histLast + hbigLen + 1];
// Convert the loaded hist[] into _histVs and _histOs.
_histLen = 0;
for (uint32 ii=0; ii<histLast; ii++) {
if (_hist[ii] > 0) {
_histVs[_histLen] = ii;
_histOs[_histLen] = hist[ii];
_histLen++;
}
}
delete [] hist;
#if 0
// If hbigLen isn't zero, we have the intermediate format, that lived for
// about a day, that stores large values too.
if (hbigLen > 0) {
for (uint64 ii=0; ii<hbigLen; ii++) {
_histVs[_histLen] = bits->getBinary(64);
_histOs[_histLen] = bits->getBinary(64);
_histLen++;
}
}
#endif
// Delete _hist to indicate we cannot accept new values.
delete [] _hist;
_hist = NULL;
}
void
merylHistogram::load_v03(stuffedBits *bits) {
_numUnique = bits->getBinary(64);
_numDistinct = bits->getBinary(64);
_numTotal = bits->getBinary(64);
_histLen = bits->getBinary(64);
//fprintf(stderr, "merylHistogram::load_v03()-- %lu %lu %lu %lu\n",
// _numUnique, _numDistinct, _numTotal, _histLen);
// Allocate space.
_histVs = new uint64 [_histLen];
_histOs = new uint64 [_histLen];
// Load the values into our list.
for (uint64 ii=0; ii<_histLen; ii++) {
_histVs[ii] = bits->getBinary(64);
_histOs[ii] = bits->getBinary(64);
}
// Delete _hist to indicate we cannot accept new values.
delete [] _hist;
_hist = NULL;
}
void
merylHistogram::load(stuffedBits *bits,
uint32 version) {
switch (version) {
case 1:
case 2:
load_v01(bits);
break;
case 3:
load_v03(bits);
break;
default:
fprintf(stderr, "merylHistogram::load()-- Unknown version %u\n", version), exit(1);
break;
}
}
void
merylHistogram::load(FILE *inFile,
uint32 version) {
stuffedBits *bits = new stuffedBits;
bits->loadFromFile(inFile);
load(bits, version);
delete bits;
}
|
23a2b471395f8fc8d569e7761aa82b7477e2dcce
|
de0c523399eaf24544f7c0cbd61fe8d3c69c84f8
|
/frida_mode/test/persistent_ret/testinstr.c
|
12365ceb76e779d5fad70b12dee7d58cdd6aca87
|
[
"Apache-2.0"
] |
permissive
|
AFLplusplus/AFLplusplus
|
d45b697b8f2f767d29f4d886a2f9c5bd9ad6c032
|
11a622c63d70c9ca16c9847418b88992139aa892
|
refs/heads/stable
| 2023-09-01T16:24:45.928708
| 2023-08-31T12:51:42
| 2023-08-31T12:51:42
| 189,044,704
| 3,470
| 872
|
Apache-2.0
| 2023-09-13T13:56:14
| 2019-05-28T14:29:06
|
C
|
UTF-8
|
C
| false
| false
| 2,089
|
c
|
testinstr.c
|
/*
american fuzzy lop++ - a trivial program to test the build
--------------------------------------------------------
Originally written by Michal Zalewski
Copyright 2014 Google Inc. All rights reserved.
Copyright 2019-2023 AFLplusplus Project. 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
*/
#include <fcntl.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void LLVMFuzzerTestOneInput(char *buf, int len) {
printf (">>> LLVMFuzzerTestOneInput >>>\n");
if (len < 1) return;
buf[len] = 0;
// we support three input cases
if (buf[0] == '0')
printf("Looks like a zero to me!\n");
else if (buf[0] == '1')
printf("Pretty sure that is a one!\n");
else
printf("Neither one or zero? How quaint!\n");
}
void slow() {
usleep(100000);
}
int main(int argc, char **argv) {
char * file;
int fd = -1;
off_t len;
char * buf = NULL;
size_t n_read;
int result = -1;
if (argc != 2) { return 1; }
do {
file = argv[1];
dprintf(STDERR_FILENO, "Running: %s\n", file);
fd = open(file, O_RDONLY);
if (fd < 0) {
perror("open");
break;
}
len = lseek(fd, 0, SEEK_END);
if (len < 0) {
perror("lseek (SEEK_END)");
break;
}
if (lseek(fd, 0, SEEK_SET) != 0) {
perror("lseek (SEEK_SET)");
break;
}
buf = malloc(len);
if (buf == NULL) {
perror("malloc");
break;
}
n_read = read(fd, buf, len);
if (n_read != len) {
perror("read");
break;
}
dprintf(STDERR_FILENO, "Running: %s: (%zd bytes)\n", file, n_read);
LLVMFuzzerTestOneInput(buf, len);
dprintf(STDERR_FILENO, "Done: %s: (%zd bytes)\n", file, n_read);
slow();
result = 0;
} while (false);
if (buf != NULL) { free(buf); }
if (fd != -1) { close(fd); }
return result;
}
|
20749da8822d0a7c3aeaa80974279090f28ac643
|
407bf0c6da807d74ee73a5b0f5b33e0bca502074
|
/src/utils.h
|
ee4ec5b29d9b1116c1aed72734d06830bf61c151
|
[
"Apache-2.0"
] |
permissive
|
containers/conmon
|
8b4e06b56b75c40a29565c42321ff6ba4ddc96f4
|
6d88cb3672a3dceeb4b045a92dc4d4285c9f4efd
|
refs/heads/main
| 2023-09-03T19:33:28.625554
| 2023-08-24T14:14:11
| 2023-08-30T14:09:01
| 144,288,854
| 357
| 123
|
Apache-2.0
| 2023-09-04T13:47:07
| 2018-08-10T13:21:43
|
C
|
UTF-8
|
C
| false
| false
| 5,774
|
h
|
utils.h
|
#pragma once
#if !defined(UTILS_H)
#define UTILS_H
#include <stdio.h>
#include <syslog.h>
#include <stdbool.h>
#include <unistd.h>
#include <glib.h>
#include <glib-unix.h>
#include <sys/uio.h>
#include <string.h>
/* stdpipe_t represents one of the std pipes (or NONE).
* Sync with const in container_attach.go */
typedef enum {
NO_PIPE,
STDIN_PIPE, /* unused */
STDOUT_PIPE,
STDERR_PIPE,
} stdpipe_t;
/* Different levels of logging */
typedef enum {
EXIT_LEVEL,
WARN_LEVEL,
INFO_LEVEL,
DEBUG_LEVEL,
TRACE_LEVEL,
} log_level_t;
// Default log level is Warning, This will be configured before any logging
// should happen
extern log_level_t log_level;
extern char *log_cid;
extern gboolean use_syslog;
#define _pexit(s) \
do { \
fprintf(stderr, "[conmon:e]: %s %s\n", s, strerror(errno)); \
if (use_syslog) \
syslog(LOG_ERR, "conmon %.20s <error>: %s %s\n", log_cid, s, strerror(errno)); \
_exit(EXIT_FAILURE); \
} while (0)
#define _pexitf(fmt, ...) \
do { \
fprintf(stderr, "[conmon:e]: " fmt " %s\n", ##__VA_ARGS__, strerror(errno)); \
if (use_syslog) \
syslog(LOG_ERR, "conmon %.20s <error>: " fmt ": %s\n", log_cid, ##__VA_ARGS__, strerror(errno)); \
_exit(EXIT_FAILURE); \
} while (0)
#define pexit(s) \
do { \
fprintf(stderr, "[conmon:e]: %s %s\n", s, strerror(errno)); \
if (use_syslog) \
syslog(LOG_ERR, "conmon %.20s <error>: %s %s\n", log_cid, s, strerror(errno)); \
exit(EXIT_FAILURE); \
} while (0)
#define pexitf(fmt, ...) \
do { \
fprintf(stderr, "[conmon:e]: " fmt " %s\n", ##__VA_ARGS__, strerror(errno)); \
if (use_syslog) \
syslog(LOG_ERR, "conmon %.20s <error>: " fmt ": %s\n", log_cid, ##__VA_ARGS__, strerror(errno)); \
exit(EXIT_FAILURE); \
} while (0)
#define pwarn(s) \
do { \
fprintf(stderr, "[conmon:w]: %s %s\n", s, strerror(errno)); \
if (use_syslog) \
syslog(LOG_INFO, "conmon %.20s <pwarn>: %s %s\n", log_cid, s, strerror(errno)); \
} while (0)
#define nexit(s) \
do { \
fprintf(stderr, "[conmon:e] %s\n", s); \
if (use_syslog) \
syslog(LOG_ERR, "conmon %.20s <error>: %s\n", log_cid, s); \
exit(EXIT_FAILURE); \
} while (0)
#define nexitf(fmt, ...) \
do { \
fprintf(stderr, "[conmon:e]: " fmt "\n", ##__VA_ARGS__); \
if (use_syslog) \
syslog(LOG_ERR, "conmon %.20s <error>: " fmt " \n", log_cid, ##__VA_ARGS__); \
exit(EXIT_FAILURE); \
} while (0)
#define nwarn(s) \
if (log_level >= WARN_LEVEL) { \
do { \
fprintf(stderr, "[conmon:w]: %s\n", s); \
if (use_syslog) \
syslog(LOG_INFO, "conmon %.20s <nwarn>: %s\n", log_cid, s); \
} while (0); \
}
#define nwarnf(fmt, ...) \
if (log_level >= WARN_LEVEL) { \
do { \
fprintf(stderr, "[conmon:w]: " fmt "\n", ##__VA_ARGS__); \
if (use_syslog) \
syslog(LOG_INFO, "conmon %.20s <nwarn>: " fmt " \n", log_cid, ##__VA_ARGS__); \
} while (0); \
}
#define ninfo(s) \
if (log_level >= INFO_LEVEL) { \
do { \
fprintf(stderr, "[conmon:i]: %s\n", s); \
if (use_syslog) \
syslog(LOG_INFO, "conmon %.20s <ninfo>: %s\n", log_cid, s); \
} while (0); \
}
#define ninfof(fmt, ...) \
if (log_level >= INFO_LEVEL) { \
do { \
fprintf(stderr, "[conmon:i]: " fmt "\n", ##__VA_ARGS__); \
if (use_syslog) \
syslog(LOG_INFO, "conmon %.20s <ninfo>: " fmt " \n", log_cid, ##__VA_ARGS__); \
} while (0); \
}
#define ndebug(s) \
if (log_level >= DEBUG_LEVEL) { \
do { \
fprintf(stderr, "[conmon:d]: %s\n", s); \
if (use_syslog) \
syslog(LOG_INFO, "conmon %.20s <ndebug>: %s\n", log_cid, s); \
} while (0); \
}
#define ndebugf(fmt, ...) \
if (log_level >= DEBUG_LEVEL) { \
do { \
fprintf(stderr, "[conmon:d]: " fmt "\n", ##__VA_ARGS__); \
if (use_syslog) \
syslog(LOG_INFO, "conmon %.20s <ndebug>: " fmt " \n", log_cid, ##__VA_ARGS__); \
} while (0); \
}
#define ntrace(s) \
if (log_level >= TRACE_LEVEL) { \
do { \
fprintf(stderr, "[conmon:d]: %s\n", s); \
if (use_syslog) \
syslog(LOG_INFO, "conmon %.20s <ntrace>: %s\n", log_cid, s); \
} while (0); \
}
#define ntracef(fmt, ...) \
if (log_level >= TRACE_LEVEL) { \
do { \
fprintf(stderr, "[conmon:d]: " fmt "\n", ##__VA_ARGS__); \
if (use_syslog) \
syslog(LOG_INFO, "conmon %.20s <ntrace>: " fmt " \n", log_cid, ##__VA_ARGS__); \
} while (0); \
}
/* Set the log level for this call. log level defaults to warning.
parse the string value of level_name to the appropriate log_level_t enum value
*/
void set_conmon_logs(char *level_name, char *cid_, gboolean syslog_, char *tag);
#define _cleanup_(x) __attribute__((cleanup(x)))
static inline void freep(void *p)
{
free(*(void **)p);
}
static inline void closep(int *fd)
{
if (*fd >= 0)
close(*fd);
*fd = -1;
}
static inline void fclosep(FILE **fp)
{
if (*fp)
fclose(*fp);
*fp = NULL;
}
static inline void gstring_free_cleanup(GString **string)
{
if (*string)
g_string_free(*string, TRUE);
}
static inline void gerror_free_cleanup(GError **err)
{
if (*err)
g_error_free(*err);
}
static inline void strv_cleanup(char ***strv)
{
if (strv)
g_strfreev(*strv);
}
static inline void hashtable_free_cleanup(GHashTable **tbl)
{
if (tbl)
g_hash_table_destroy(*tbl);
}
#define _cleanup_free_ _cleanup_(freep)
#define _cleanup_close_ _cleanup_(closep)
#define _cleanup_fclose_ _cleanup_(fclosep)
#define _cleanup_gstring_ _cleanup_(gstring_free_cleanup)
#define _cleanup_gerror_ _cleanup_(gerror_free_cleanup)
#define _cleanup_strv_ _cleanup_(strv_cleanup)
#define _cleanup_hashtable_ _cleanup_(hashtable_free_cleanup)
#define WRITEV_BUFFER_N_IOV 128
ssize_t write_all(int fd, const void *buf, size_t count);
int set_subreaper(gboolean enabled);
int set_pdeathsig(int sig);
int get_signal_descriptor();
void drop_signal_event(int fd);
#endif /* !defined(UTILS_H) */
|
864a305cf372c51e8417baaea52773a1dab9a883
|
b0f08154e3eebc7d8465efc57597e52d08d69c18
|
/src/heaplayers/customheaps.h
|
bbd1fa364b6fde619beaa7747850aec5c1dd88e4
|
[
"BSD-3-Clause",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
CUBRID/cubrid
|
8f71a0010243b72e43ba887d229210650f4e901e
|
3b952af33230839a1b561a78ecd4b773374b66f8
|
refs/heads/develop
| 2023-08-18T19:16:30.987583
| 2023-08-18T08:18:05
| 2023-08-18T08:18:05
| 52,080,367
| 287
| 294
|
NOASSERTION
| 2023-09-14T21:29:09
| 2016-02-19T10:25:32
|
C
|
UTF-8
|
C
| false
| false
| 1,552
|
h
|
customheaps.h
|
/*
* Copyright 2008 Search Solution Corporation
* Copyright 2016 CUBRID Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// -*- C++ -*-
#ifndef _CUSTOMHEAPS_H_
#define _CUSTOMHEAPS_H_
#include "config.h"
extern UINTPTR hl_register_fixed_heap (int chunk_size);
extern void hl_unregister_fixed_heap (UINTPTR heap_id);
extern void *hl_fixed_alloc (UINTPTR heap_id, size_t sz);
extern void hl_fixed_free (UINTPTR heap_id, void *ptr);
extern UINTPTR hl_register_ostk_heap (int chunk_size);
extern void hl_unregister_ostk_heap (UINTPTR heap_id);
extern void *hl_ostk_alloc (UINTPTR heap_id, size_t sz);
extern void hl_ostk_free (UINTPTR heap_id, void *ptr);
extern UINTPTR hl_register_lea_heap (void);
extern void hl_unregister_lea_heap (UINTPTR heap_id);
extern void *hl_lea_alloc (UINTPTR heap_id, size_t sz);
extern void *hl_lea_realloc (UINTPTR heap_id, void *ptr, size_t sz);
extern void hl_lea_free (UINTPTR heap_id, void *ptr);
extern void hl_clear_lea_heap (UINTPTR heap_id);
#endif /* _CUSTOMHEAPS_H_ */
|
18d48836253b844c8d13c87ea4a6f64427777a16
|
bb38c44037a99d0a12a12d92059678f2faebbc80
|
/src/include/nodes/parsenodes.h
|
fe7e86ae93d49cc538b0e07e94d30d1c6141ee97
|
[
"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
| 85,964
|
h
|
parsenodes.h
|
/* -------------------------------------------------------------------------
*
* parsenodes.h
* definitions for parse tree nodes
*
* Many of the node types used in parsetrees include a "location" field.
* This is a byte (not character) offset in the original source text, to be
* used for positioning an error cursor when there is an error related to
* the node. Access to the original source text is needed to make use of
* the location.
*
*
* Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
* Portions Copyright (c) 2010-2012 Postgres-XC Development Group
*
* src/include/nodes/parsenodes.h
*
* -------------------------------------------------------------------------
*/
#ifndef PARSENODES_H
#define PARSENODES_H
#include "nodes/bitmapset.h"
#include "nodes/params.h"
#include "nodes/primnodes.h"
#include "nodes/value.h"
#include "utils/relcache.h"
#include "utils/partcache.h"
#ifdef PGXC
#include "access/tupdesc.h"
#include "pgxc/locator.h"
#endif
#include "tcop/dest.h"
#include "nodes/parsenodes_common.h"
/*
* Relids
* Set of relation identifiers (indexes into the rangetable).
*/
typedef Bitmapset* Relids;
typedef enum RelOrientation {
REL_ORIENT_UNKNOWN,
REL_COL_ORIENTED, /* It represents CU sotre foramt also. */
REL_ROW_ORIENTED,
REL_PAX_ORIENTED,
REL_TIMESERIES_ORIENTED
} RelOrientation;
/*
* It keeps file system which the relatoin store.
* LOCAL_STORE represents local file system.
*/
typedef enum RelstoreType { LOCAL_STORE } RelstoreType;
#define SAMPLEARGSNUM 2
/* Method of tablesample */
typedef enum TableSampleType { SYSTEM_SAMPLE = 0, BERNOULLI_SAMPLE, HYBRID_SAMPLE } TableSampleType;
/*
* Grantable rights are encoded so that we can OR them together in a bitmask.
* The present representation of AclItem limits us to 16 distinct rights,
* even though AclMode is defined as uint32. See utils/acl.h.
*
* Caution: changing these codes breaks stored ACLs, hence forces initdb.
*/
typedef uint32 AclMode; /* a bitmask of privilege bits */
#define ACL_INSERT (1 << 0) /* for relations */
#define ACL_SELECT (1 << 1)
#define ACL_UPDATE (1 << 2)
#define ACL_DELETE (1 << 3)
#define ACL_TRUNCATE (1 << 4)
#define ACL_REFERENCES (1 << 5)
#define ACL_TRIGGER (1 << 6)
#define ACL_EXECUTE (1 << 7) /* for functions */
#define ACL_USAGE \
(1 << 8) /* for languages, namespaces, FDWs, and \
* servers */
#define ACL_CREATE (1 << 9) /* for namespaces and databases */
#define ACL_CREATE_TEMP (1 << 10) /* for databases */
#define ACL_CONNECT (1 << 11) /* for databases */
#define ACL_COMPUTE (1 << 12) /* for node group */
#define ACL_READ (1 << 13) /* for pg_directory */
#define ACL_WRITE (1 << 14) /* for pg_directory */
#define N_ACL_RIGHTS 15 /* 1 plus the last 1<<x */
#define ACL_NO_RIGHTS 0
/* Currently, SELECT ... FOR [KEY] UPDATE/FOR SHARE requires UPDATE privileges */
#define ACL_SELECT_FOR_UPDATE ACL_UPDATE
/* grantable rights for DDL operations */
#define ACL_ALTER ((1 << 0) | (1 << 15)) /* for all objects */
#define ACL_DROP ((1 << 1) | (1 << 15)) /* for all objects */
#define ACL_COMMENT ((1 << 2) | (1 << 15)) /* for all objects */
#define ACL_INDEX ((1 << 3) | (1 << 15)) /* for relations */
#define ACL_VACUUM ((1 << 4) | (1 << 15)) /* for relations */
#define N_ACL_DDL_RIGHTS 5 /* 1 plus the last 1<<x */
#define FLAG_FOR_DDL_ACL (1 << 15) /* add this flag to Aclitem when for grantable rights of DDL operations */
#define ACL_NO_DDL_RIGHTS ((AclMode)FLAG_FOR_DDL_ACL & 0xFFFF)
/****************************************************************************
* Supporting data structures for Parse Trees
*
* Most of these node types appear in raw parsetrees output by the grammar,
* and get transformed to something else by the analyzer. A few of them
* are used as-is in transformed querytrees.
****************************************************************************/
/*
* TableSampleClause - TABLESAMPLE appearing in a transformed FROM clause
*
* Unlike RangeTableSample, this is a subnode of the relevant RangeTblEntry.
*/
typedef struct TableSampleClause {
NodeTag type;
TableSampleType sampleType; /* Sample type, system or bernoulli. */
List* args; /* tablesample argument expression(s) */
Expr* repeatable; /* REPEATABLE expression, or NULL if none */
} TableSampleClause;
/****************************************************************************
* Nodes for a Query tree
****************************************************************************/
/* --------------------
* RangeTblEntry -
* A range table is a List of RangeTblEntry nodes.
*
* A range table entry may represent a plain relation, a sub-select in
* FROM, or the result of a JOIN clause. (Only explicit JOIN syntax
* produces an RTE, not the implicit join resulting from multiple FROM
* items. This is because we only need the RTE to deal with SQL features
* like outer joins and join-output-column aliasing.) Other special
* RTE types also exist, as indicated by RTEKind.
*
* Note that we consider RTE_RELATION to cover anything that has a pg_class
* entry. relkind distinguishes the sub-cases.
*
* alias is an Alias node representing the AS alias-clause attached to the
* FROM expression, or NULL if no clause.
*
* eref is the table reference name and column reference names (either
* real or aliases). Note that system columns (OID etc) are not included
* in the column list.
* eref->aliasname is required to be present, and should generally be used
* to identify the RTE for error messages etc.
*
* In RELATION RTEs, the colnames in both alias and eref are indexed by
* physical attribute number; this means there must be colname entries for
* dropped columns. When building an RTE we insert empty strings ("") for
* dropped columns. Note however that a stored rule may have nonempty
* colnames for columns dropped since the rule was created (and for that
* matter the colnames might be out of date due to column renamings).
* The same comments apply to FUNCTION RTEs when the function's return type
* is a named composite type.
*
* In JOIN RTEs, the colnames in both alias and eref are one-to-one with
* joinaliasvars entries. A JOIN RTE will omit columns of its inputs when
* those columns are known to be dropped at parse time. Again, however,
* a stored rule might contain entries for columns dropped since the rule
* was created. (This is only possible for columns not actually referenced
* in the rule.) When loading a stored rule, we replace the joinaliasvars
* items for any such columns with NULL Consts. (We can't simply delete
* them from the joinaliasvars list, because that would affect the attnums
* of Vars referencing the rest of the list.)
*
* inh is TRUE for relation references that should be expanded to include
* inheritance children, if the rel has any. This *must* be FALSE for
* RTEs other than RTE_RELATION entries.
*
* inFromCl marks those range variables that are listed in the FROM clause.
* It's false for RTEs that are added to a query behind the scenes, such
* as the NEW and OLD variables for a rule, or the subqueries of a UNION.
* This flag is not used anymore during parsing, since the parser now uses
* a separate "namespace" data structure to control visibility, but it is
* needed by ruleutils.c to determine whether RTEs should be shown in
* decompiled queries.
*
* requiredPerms and checkAsUser specify run-time access permissions
* checks to be performed at query startup. The user must have *all*
* of the permissions that are OR'd together in requiredPerms (zero
* indicates no permissions checking). If checkAsUser is not zero,
* then do the permissions checks using the access rights of that user,
* not the current effective user ID. (This allows rules to act as
* setuid gateways.) Permissions checks only apply to RELATION RTEs.
*
* For SELECT/INSERT/UPDATE permissions, if the user doesn't have
* table-wide permissions then it is sufficient to have the permissions
* on all columns identified in selectedCols (for SELECT) and/or
* modifiedCols (for INSERT/UPDATE; we can tell which from the query type).
* selectedCols and modifiedCols are bitmapsets, which cannot have negative
* integer members, so we subtract FirstLowInvalidHeapAttributeNumber from
* column numbers before storing them in these fields. A whole-row Var
* reference is represented by setting the bit for InvalidAttrNumber.
* --------------------
*/
typedef enum RTEKind {
RTE_RELATION, /* ordinary relation reference */
RTE_SUBQUERY, /* subquery in FROM */
RTE_JOIN, /* join */
RTE_FUNCTION, /* function in FROM */
RTE_VALUES, /* VALUES (<exprlist>), (<exprlist>), ... */
RTE_CTE, /* common table expr (WITH list element) */
#ifdef PGXC
RTE_REMOTE_DUMMY, /* RTEs created by remote plan reduction */
#endif /* PGXC */
RTE_RESULT /* RTE represents an empty FROM clause; such
* RTEs are added by the planner, they're not
* present during parsing or rewriting */
} RTEKind;
typedef struct RangeTblEntry {
NodeTag type;
RTEKind rtekind; /* see above */
/*
* XXX the fields applicable to only some rte kinds should be merged into
* a union. I didn't do this yet because the diffs would impact a lot of
* code that is being actively worked on.
*/
#ifdef PGXC
char* relname;
List* partAttrNum;
#endif
/*
* Fields valid for a plain relation RTE (else zero):
*/
Oid relid; /* OID of the relation */
Oid partitionOid; /*
* OID of a partition if relation is partitioned table.
* Select * from table_name partition (partition_name);
* or select * from table_name partition for (partition_key_value_list)
*/
bool isContainPartition; /* select from caluse whether contains partition
* if contains partition isContainPartition=true,
* otherwise isContainPartition=false
*/
Oid subpartitionOid; /*
* OID of a subpartition if relation is partitioned table.
* Select * from table_name subpartition (subpartition_name);
*/
bool isContainSubPartition; /* select from caluse whether contains subpartition
* if contains subpartition isContainSubPartition=true,
* otherwise isContainSubPartition=false
*/
Oid refSynOid; /* OID of synonym object if relation is referenced by some synonym object. */
List* partid_list;
char relkind; /* relation kind (see pg_class.relkind) */
bool isResultRel; /* used in target of SELECT INTO or similar */
TableSampleClause* tablesample; /* sampling method and parameters */
TimeCapsuleClause* timecapsule; /* user-specified time capsule point */
bool ispartrel; /* is it a partitioned table */
/* works just for _readRangeTblEntry(). set true if plan is running in the compute pool. */
bool ignoreResetRelid;
/*
* Fields valid for a subquery RTE (else NULL):
*/
Query* subquery; /* the sub-query */
bool security_barrier; /* subquery from security_barrier view */
/*
* Fields valid for a join RTE (else NULL/zero):
*
* joinaliasvars is a list of Vars or COALESCE expressions corresponding
* to the columns of the join result. An alias Var referencing column K
* of the join result can be replaced by the K'th element of joinaliasvars
* --- but to simplify the task of reverse-listing aliases correctly, we
* do not do that until planning time. In a Query loaded from a stored
* rule, it is also possible for joinaliasvars items to be NULL Consts,
* denoting columns dropped since the rule was made.
*/
JoinType jointype; /* type of join */
List* joinaliasvars; /* list of alias-var expansions */
/*
* Fields valid for a function RTE (else NULL):
*
* If the function returns RECORD, funccoltypes lists the column types
* declared in the RTE's column type specification, funccoltypmods lists
* their declared typmods, funccolcollations their collations. Otherwise,
* those fields are NIL.
*/
Node* funcexpr; /* expression tree for func call */
List* funccoltypes; /* OID list of column type OIDs */
List* funccoltypmods; /* integer list of column typmods */
List* funccolcollations; /* OID list of column collation OIDs */
/*
* Fields valid for a values RTE (else NIL):
*/
List* values_lists; /* list of expression lists */
List* values_collations; /* OID list of column collation OIDs */
/*
* Fields valid for a CTE RTE (else NULL/zero):
*/
char* ctename; /* name of the WITH list item */
Index ctelevelsup; /* number of query levels up */
bool self_reference; /* is this a recursive self-reference? */
bool cterecursive; /* is this a recursive cte */
List* ctecoltypes; /* OID list of column type OIDs */
List* ctecoltypmods; /* integer list of column typmods */
List* ctecolcollations; /* OID list of column collation OIDs */
bool swConverted; /* indicate the current CTE rangetable entry is converted
from StartWith ... Connect By clause */
List *origin_index; /* rewrite rtes of cte for startwith */
bool swAborted; /* RTE has been replaced by CTE */
bool swSubExist; /* under subquery contains startwith */
char locator_type; /* keep subplan/cte's locator type */
/*
* Fields valid in all RTEs:
*/
Alias* alias; /* user-written alias clause, if any */
Alias* eref; /* expanded reference names */
Alias* pname; /* partition name, if any */
List* plist;
bool lateral; /* subquery or function is marked LATERAL? */
bool inh; /* inheritance requested? */
bool inFromCl; /* present in FROM clause? */
AclMode requiredPerms; /* bitmask of required access permissions */
Oid checkAsUser; /* if valid, check access as this role */
Bitmapset* selectedCols; /* columns needing SELECT permission */
Bitmapset* modifiedCols; /* columns needing INSERT/UPDATE permission, not used in current version
* we split it to insertedCols and updatedCols for MERGEINTO
*/
Bitmapset* insertedCols; /* columns needing INSERT permission */
Bitmapset* updatedCols; /* columns needing UPDATE permission */
RelOrientation orientation; /* column oriented or row oriented */
bool is_ustore; /* is a ustore rel */
char* mainRelName;
char* mainRelNameSpace;
List* securityQuals; /* security barrier quals to apply */
/* For skew hint */
bool subquery_pull_up; /* mark that the subquery whether been pull up */
/*
* Indicate current RTE is correlated with a Recursive CTE, the flag is set in
* check_plan_correlation()
*/
bool correlated_with_recursive_cte;
/* For hash buckets */
bool relhasbucket; /* the rel has underlying buckets, get from pg_class */
bool isbucket; /* the sql only want some buckets from the rel */
int bucketmapsize;
List* buckets; /* the bucket id wanted */
bool isexcluded; /* the rel is the EXCLUDED relation for UPSERT */
/* For sublink in targetlist pull up */
bool sublink_pull_up; /* mark the subquery is sublink pulled up */
Bitmapset *extraUpdatedCols; /* generated columns being updated */
bool pulled_from_subquery; /* mark whether it is pulled-up from subquery to the current level, for upsert remote
query deparse */
List *partitionOidList; /*
* OIDs of a partition if relation is partitioned table.
* Select * from table_name partition (partition_name);
* or select * from table_name partition for (partition_key_value_list)
* or delete from table_name partition (partition_name, ...)
*/
List *subpartitionOidList; /*
* OIDs of a subpartition if relation is partitioned table.
* Select * from table_name subpartition (subpartition_name);
* or delete from table_name partition (partition_name, ...)
*/
} RangeTblEntry;
/*
* WithCheckOption -
* representation of WITH CHECK OPTION checks to be applied to new tuples
* when inserting/updating an auto-updatable view.
*/
typedef struct WithCheckOption {
NodeTag type;
char* viewname; /* name of view that specified the WCO */
Node* qual; /* constraint qual to check */
bool cascaded; /* true = WITH CASCADED CHECK OPTION */
Index rtindex; /* used when multiple modifying. It indicates the resultRelation
* to which this wco belongs */
} WithCheckOption;
/*
* SortGroupClause -
* representation of ORDER BY, GROUP BY, PARTITION BY,
* DISTINCT, DISTINCT ON items
*
* You might think that ORDER BY is only interested in defining ordering,
* and GROUP/DISTINCT are only interested in defining equality. However,
* one way to implement grouping is to sort and then apply a "uniq"-like
* filter. So it's also interesting to keep track of possible sort operators
* for GROUP/DISTINCT, and in particular to try to sort for the grouping
* in a way that will also yield a requested ORDER BY ordering. So we need
* to be able to compare ORDER BY and GROUP/DISTINCT lists, which motivates
* the decision to give them the same representation.
*
* tleSortGroupRef must match ressortgroupref of exactly one entry of the
* query's targetlist; that is the expression to be sorted or grouped by.
* eqop is the OID of the equality operator.
* sortop is the OID of the ordering operator (a "<" or ">" operator),
* or InvalidOid if not available.
* nulls_first means about what you'd expect. If sortop is InvalidOid
* then nulls_first is meaningless and should be set to false.
* hashable is TRUE if eqop is hashable (note this condition also depends
* on the datatype of the input expression).
*
* In an ORDER BY item, all fields must be valid. (The eqop isn't essential
* here, but it's cheap to get it along with the sortop, and requiring it
* to be valid eases comparisons to grouping items.) Note that this isn't
* actually enough information to determine an ordering: if the sortop is
* collation-sensitive, a collation OID is needed too. We don't store the
* collation in SortGroupClause because it's not available at the time the
* parser builds the SortGroupClause; instead, consult the exposed collation
* of the referenced targetlist expression to find out what it is.
*
* In a grouping item, eqop must be valid. If the eqop is a btree equality
* operator, then sortop should be set to a compatible ordering operator.
* We prefer to set eqop/sortop/nulls_first to match any ORDER BY item that
* the query presents for the same tlist item. If there is none, we just
* use the default ordering op for the datatype.
*
* If the tlist item's type has a hash opclass but no btree opclass, then
* we will set eqop to the hash equality operator, sortop to InvalidOid,
* and nulls_first to false. A grouping item of this kind can only be
* implemented by hashing, and of course it'll never match an ORDER BY item.
*
* The hashable flag is provided since we generally have the requisite
* information readily available when the SortGroupClause is constructed,
* and it's relatively expensive to get it again later. Note there is no
* need for a "sortable" flag since OidIsValid(sortop) serves the purpose.
*
* A query might have both ORDER BY and DISTINCT (or DISTINCT ON) clauses.
* In SELECT DISTINCT, the distinctClause list is as long or longer than the
* sortClause list, while in SELECT DISTINCT ON it's typically shorter.
* The two lists must match up to the end of the shorter one --- the parser
* rearranges the distinctClause if necessary to make this true. (This
* restriction ensures that only one sort step is needed to both satisfy the
* ORDER BY and set up for the Unique step. This is semantically necessary
* for DISTINCT ON, and presents no real drawback for DISTINCT.)
*/
typedef struct SortGroupClause {
NodeTag type;
Index tleSortGroupRef; /* reference into targetlist */
Oid eqop; /* the equality operator ('=' op) */
Oid sortop; /* the ordering operator ('<' op), or 0 */
bool nulls_first; /* do NULLs come before normal values? */
bool hashable; /* can eqop be implemented by hashing? */
bool groupSet; /* It will be set to true If this expr in group clause and not include
in all group clause when groupingSet is not null. It mean it's value can be altered. */
} SortGroupClause;
/*
* WindowClause -
* transformed representation of WINDOW and OVER clauses
*
* A parsed Query's windowClause list contains these structs. "name" is set
* if the clause originally came from WINDOW, and is NULL if it originally
* was an OVER clause (but note that we collapse out duplicate OVERs).
* partitionClause and orderClause are lists of SortGroupClause structs.
* winref is an ID number referenced by WindowFunc nodes; it must be unique
* among the members of a Query's windowClause list.
* When refname isn't null, the partitionClause is always copied from there;
* the orderClause might or might not be copied (see copiedOrder); the framing
* options are never copied, per spec.
*/
typedef struct WindowClause {
NodeTag type;
char* name; /* window name (NULL in an OVER clause) */
char* refname; /* referenced window name, if any */
List* partitionClause; /* PARTITION BY list */
List* orderClause; /* ORDER BY list */
int frameOptions; /* frame_clause options, see WindowDef */
Node* startOffset; /* expression for starting bound, if any */
Node* endOffset; /* expression for ending bound, if any */
Index winref; /* ID referenced by window functions */
bool copiedOrder; /* did we copy orderClause from refname? */
} WindowClause;
/*
* RowMarkClause -
* parser output representation of FOR [KEY] UPDATE/SHARE clauses
*
* Query.rowMarks contains a separate RowMarkClause node for each relation
* identified as a FOR [KEY] UPDATE/SHARE target. If one of these clauses
* is applied to a subquery, we generate RowMarkClauses for all normal and
* subquery rels in the subquery, but they are marked pushedDown = true to
* distinguish them from clauses that were explicitly written at this query
* level. Also, Query.hasForUpdate tells whether there were explicit FOR
* UPDATE/SHARE/KEY SHARE clauses in the current query level
*/
typedef struct RowMarkClause {
NodeTag type;
Index rti; /* range table index of target relation */
bool forUpdate; /* for compatibility, we reserve this filed but don't use it */
LockWaitPolicy waitPolicy; /* NOWAIT option */
int waitSec; /* WAIT time Sec */
bool pushedDown; /* pushed down from higher query level? */
LockClauseStrength strength;
} RowMarkClause;
/*
* - Brief: data structure in parse state to save StartWith clause in current subquery
* level, normally a StartWithTargetRelInfo indicates a RangeVar(rte-rel) e.g.
* baserel, subselect where we add StartWith transform needed information to
* construct a start-with clause
*/
typedef struct StartWithTargetRelInfo {
NodeTag type;
/* fields to describe original relation info */
char *relname;
char *aliasname;
char *ctename;
List *columns;
Node *tblstmt;
/* fields to record origin RTE related info */
RTEKind rtekind;
RangeTblEntry *rte;
RangeTblRef* rtr;
} StartWithTargetRelInfo;
/* Convenience macro to get the output tlist of a CTE's query */
#define GetCTETargetList(cte) \
(AssertMacro(IsA((cte)->ctequery, Query)), \
((Query*)(cte)->ctequery)->commandType == CMD_SELECT ? ((Query*)(cte)->ctequery)->targetList \
: ((Query*)(cte)->ctequery)->returningList)
/*****************************************************************************
* Optimizable Statements
*****************************************************************************/
/* ----------------------
* Set Operation node for post-analysis query trees
*
* After parse analysis, a SELECT with set operations is represented by a
* top-level Query node containing the leaf SELECTs as subqueries in its
* range table. Its setOperations field shows the tree of set operations,
* with leaf SelectStmt nodes replaced by RangeTblRef nodes, and internal
* nodes replaced by SetOperationStmt nodes. Information about the output
* column types is added, too. (Note that the child nodes do not necessarily
* produce these types directly, but we've checked that their output types
* can be coerced to the output column type.) Also, if it's not UNION ALL,
* information about the types' sort/group semantics is provided in the form
* of a SortGroupClause list (same representation as, eg, DISTINCT).
* The resolved common column collations are provided too; but note that if
* it's not UNION ALL, it's okay for a column to not have a common collation,
* so a member of the colCollations list could be InvalidOid even though the
* column has a collatable type.
* ----------------------
*/
typedef struct SetOperationStmt {
NodeTag type;
SetOperation op; /* type of set op */
bool all; /* ALL specified? */
Node* larg; /* left child */
Node* rarg; /* right child */
/* Eventually add fields for CORRESPONDING spec here */
/* Fields derived during parse analysis: */
List* colTypes; /* OID list of output column type OIDs */
List* colTypmods; /* integer list of output column typmods */
List* colCollations; /* OID list of output column collation OIDs */
List* groupClauses; /* a list of SortGroupClause's */
/* groupClauses is NIL if UNION ALL, but must be set otherwise */
} SetOperationStmt;
/*****************************************************************************
* Other Statements (no optimizations required)
*
* These are not touched by parser/analyze.c except to put them into
* the utilityStmt field of a Query. This is eventually passed to
* ProcessUtility (by-passing rewriting and planning). Some of the
* statements do need attention from parse analysis, and this is
* done by routines in parser/parse_utilcmd.c after ProcessUtility
* receives the command for execution.
*****************************************************************************/
/* ----------------------
* Alter Domain
*
* The fields are used in different ways by the different variants of
* this command.
* ----------------------
*/
typedef struct AlterDomainStmt {
NodeTag type;
char subtype; /*------------
* T = alter column default
* N = alter column drop not null
* O = alter column set not null
* C = add constraint
* X = drop constraint
* ------------
*/
List* typname; /* domain to work on */
char* name; /* column or constraint name to act on */
Node* def; /* definition of default or constraint */
DropBehavior behavior; /* RESTRICT or CASCADE for DROP cases */
bool missing_ok; /* skip error if missing? */
} AlterDomainStmt;
/* ----------------------
* Grant|Revoke Statement
* ----------------------
*/
typedef enum GrantTargetType {
ACL_TARGET_OBJECT, /* grant on specific named object(s) */
ACL_TARGET_ALL_IN_SCHEMA, /* grant on all objects in given schema(s) */
ACL_TARGET_DEFAULTS /* ALTER DEFAULT PRIVILEGES */
} GrantTargetType;
typedef enum GrantObjectType {
ACL_OBJECT_COLUMN, /* column */
ACL_OBJECT_RELATION, /* table, view */
ACL_OBJECT_SEQUENCE, /* sequence */
ACL_OBJECT_DATABASE, /* database */
ACL_OBJECT_DOMAIN, /* domain */
ACL_OBJECT_FDW, /* foreign-data wrapper */
ACL_OBJECT_FOREIGN_SERVER, /* foreign server */
ACL_OBJECT_FUNCTION, /* function */
ACL_OBJECT_PACKAGE, /* package */
ACL_OBJECT_LANGUAGE, /* procedural language */
ACL_OBJECT_LARGEOBJECT, /* largeobject */
ACL_OBJECT_NAMESPACE, /* namespace */
ACL_OBJECT_NODEGROUP, /* nodegroup */
ACL_OBJECT_TABLESPACE, /* tablespace */
ACL_OBJECT_TYPE, /* type */
ACL_OBJECT_DATA_SOURCE, /* data source */
ACL_OBJECT_GLOBAL_SETTING, /* Global Setting */
ACL_OBJECT_COLUMN_SETTING, /* Column Setting */
ACL_OBJECT_DIRECTORY /* directory */
} GrantObjectType;
typedef struct GrantStmt {
NodeTag type;
bool is_grant; /* true = GRANT, false = REVOKE */
GrantTargetType targtype; /* type of the grant target */
GrantObjectType objtype; /* kind of object being operated on */
List* objects; /* list of RangeVar nodes, FuncWithArgs nodes,
* or plain names (as Value strings) */
List* privileges; /* list of AccessPriv nodes */
/* privileges == NIL denotes ALL PRIVILEGES */
List* grantees; /* list of PrivGrantee nodes */
bool grant_option; /* grant or revoke grant option */
DropBehavior behavior; /* drop behavior (for REVOKE) */
} GrantStmt;
typedef struct PrivGrantee {
NodeTag type;
char* rolname; /* if NULL then PUBLIC */
} PrivGrantee;
/*
* An access privilege, with optional list of column names
* priv_name == NULL denotes ALL PRIVILEGES (only used with a column list)
* cols == NIL denotes "all columns"
* Note that simple "ALL PRIVILEGES" is represented as a NIL list, not
* an AccessPriv with both fields null.
*/
typedef struct AccessPriv {
NodeTag type;
char* priv_name; /* string name of privilege */
List* cols; /* list of Value strings */
} AccessPriv;
/* ----------------------
* Grant/Revoke Role Statement
*
* Note: because of the parsing ambiguity with the GRANT <privileges>
* statement, granted_roles is a list of AccessPriv; the execution code
* should complain if any column lists appear. grantee_roles is a list
* of role names, as Value strings.
* ----------------------
*/
typedef struct GrantRoleStmt {
NodeTag type;
List* granted_roles; /* list of roles to be granted/revoked */
List* grantee_roles; /* list of member roles to add/delete */
bool is_grant; /* true = GRANT, false = REVOKE */
bool admin_opt; /* with admin option */
char* grantor; /* set grantor to other than current role */
DropBehavior behavior; /* drop behavior (for REVOKE) */
} GrantRoleStmt;
/* ----------------------
* Grant/Revoke Database Privilege Statement
* ----------------------
*/
typedef struct GrantDbStmt {
NodeTag type;
bool is_grant; /* true = GRANT, false = REVOKE */
bool admin_opt; /* with admin option */
List* privileges; /* list of DbPriv nodes */
List* grantees; /* list of PrivGrantee nodes */
} GrantDbStmt;
typedef struct DbPriv {
NodeTag type;
char* db_priv_name; /* string name of sys privilege */
} DbPriv;
/* ----------------------
* Alter Default Privileges Statement
* ----------------------
*/
typedef struct AlterDefaultPrivilegesStmt {
NodeTag type;
List* options; /* list of DefElem */
GrantStmt* action; /* GRANT/REVOKE action (with objects=NIL) */
} AlterDefaultPrivilegesStmt;
/* ----------------------
* Show Statement
* ----------------------
*/
typedef struct VariableShowStmt {
NodeTag type;
char* name;
char* likename;
int offset;
int count;
} VariableShowStmt;
/* ----------------------
* Shutdown Statement
* ----------------------
*/
typedef struct ShutdownStmt {
NodeTag type;
char* mode;
} ShutdownStmt;
/* ----------
* Definitions for constraints in CreateStmt
*
* Note that column defaults are treated as a type of constraint,
* even though that's a bit odd semantically.
*
* For constraints that use expressions (CONSTR_CHECK, CONSTR_DEFAULT)
* we may have the expression in either "raw" form (an untransformed
* parse tree) or "cooked" form (the nodeToString representation of
* an executable expression tree), depending on how this Constraint
* node was created (by parsing, or by inheritance from an existing
* relation). We should never have both in the same node!
*
* FKCONSTR_ACTION_xxx values are stored into pg_constraint.confupdtype
* and pg_constraint.confdeltype columns; FKCONSTR_MATCH_xxx values are
* stored into pg_constraint.confmatchtype. Changing the code values may
* require an initdb!
*
* If skip_validation is true then we skip checking that the existing rows
* in the table satisfy the constraint, and just install the catalog entries
* for the constraint. A new FK constraint is marked as valid iff
* initially_valid is true. (Usually skip_validation and initially_valid
* are inverses, but we can set both true if the table is known empty.)
*
* Constraint attributes (DEFERRABLE etc) are initially represented as
* separate Constraint nodes for simplicity of parsing. parse_utilcmd.c makes
* a pass through the constraints list to insert the info into the appropriate
* Constraint node.
* ----------
*/
#define GetConstraintType(type) \
({ \
const char* tname = NULL; \
switch (type) { \
case CONSTR_NULL: \
tname = "NULL"; \
break; \
case CONSTR_NOTNULL: \
tname = "NOT NULL"; \
break; \
case CONSTR_DEFAULT: \
tname = "DEFAULT"; \
break; \
case CONSTR_CHECK: \
tname = "CHECK"; \
break; \
case CONSTR_PRIMARY: \
tname = "PRIMARY KEY"; \
break; \
case CONSTR_UNIQUE: \
tname = "UNIQUE"; \
break; \
case CONSTR_EXCLUSION: \
tname = "EXCLUSION"; \
break; \
case CONSTR_FOREIGN: \
tname = "FOREIGN KEY"; \
break; \
case CONSTR_CLUSTER: \
tname = "CLUSTER"; \
break; \
case CONSTR_ATTR_DEFERRABLE: \
tname = "ATTR DEFERRABLE"; \
break; \
case CONSTR_ATTR_NOT_DEFERRABLE: \
tname = "ATTR NOT DEFERRABLE"; \
break; \
case CONSTR_ATTR_DEFERRED: \
tname = "ATTR DEFERRED"; \
break; \
case CONSTR_ATTR_IMMEDIATE: \
tname = "ATTR IMMEDIATE"; \
break; \
case CONSTR_GENERATED: \
tname = "GENERATED COL"; \
break; \
case CONSTR_AUTO_INCREMENT: \
tname = "AUTO_INCREMENT"; \
break; \
} \
tname; \
})
/* ----------------------
* Create/Drop Table Space Statements
* ----------------------
*/
typedef struct CreateTableSpaceStmt {
NodeTag type;
char* tablespacename;
char* owner;
char* location;
char* maxsize;
List* options;
bool relative; /* location is relative to data directory */
} CreateTableSpaceStmt;
typedef struct DropTableSpaceStmt {
NodeTag type;
char* tablespacename;
bool missing_ok; /* skip error if missing? */
} DropTableSpaceStmt;
typedef struct AlterTableSpaceOptionsStmt {
NodeTag type;
char* tablespacename;
char* maxsize;
List* options;
bool isReset;
} AlterTableSpaceOptionsStmt;
/* ----------------------
* Create/Alter Extension Statements
* ----------------------
*/
typedef struct CreateExtensionStmt {
NodeTag type;
char* extname;
bool if_not_exists; /* just do nothing if it already exists? */
List* options; /* List of DefElem nodes */
} CreateExtensionStmt;
/* Only used for ALTER EXTENSION UPDATE; later might need an action field */
typedef struct AlterExtensionStmt {
NodeTag type;
char* extname;
List* options; /* List of DefElem nodes */
} AlterExtensionStmt;
typedef struct AlterExtensionContentsStmt {
NodeTag type;
char* extname; /* Extension's name */
int action; /* +1 = add object, -1 = drop object */
ObjectType objtype; /* Object's type */
List* objname; /* Qualified name of the object */
List* objargs; /* Arguments if needed (eg, for functions) */
} AlterExtensionContentsStmt;
/* ----------------------
* Create/Alter FOREIGN DATA WRAPPER Statements
* ----------------------
*/
typedef struct CreateFdwStmt {
NodeTag type;
char* fdwname; /* foreign-data wrapper name */
List* func_options; /* HANDLER/VALIDATOR options */
List* options; /* generic options to FDW */
} CreateFdwStmt;
typedef struct AlterFdwStmt {
NodeTag type;
char* fdwname; /* foreign-data wrapper name */
List* func_options; /* HANDLER/VALIDATOR options */
List* options; /* generic options to FDW */
} AlterFdwStmt;
/* ----------------------
* Create Weak Password Statements
* ----------------------
*/
typedef struct CreateWeakPasswordDictionaryStmt {
NodeTag type;
List* weak_password_string_list;
} CreateWeakPasswordDictionaryStmt;
/* ----------------------
* Drop Weak Password Statements
* ----------------------
*/
typedef struct DropWeakPasswordDictionaryStmt {
NodeTag type;
} DropWeakPasswordDictionaryStmt;
/* ----------------------
* Create/Alter FOREIGN SERVER Statements
* ----------------------
*/
typedef struct CreateForeignServerStmt {
NodeTag type;
char* servername; /* server name */
char* servertype; /* optional server type */
char* version; /* optional server version */
char* fdwname; /* FDW name */
List* options; /* generic options to server */
} CreateForeignServerStmt;
typedef struct AlterForeignServerStmt {
NodeTag type;
char* servername; /* server name */
char* version; /* optional server version */
List* options; /* generic options to server */
bool has_version; /* version specified */
} AlterForeignServerStmt;
/* ----------------------
* Create FOREIGN TABLE Statements
* ----------------------
*/
typedef struct ForeignPartState {
NodeTag type;
/* partition key of partitioned table , which is list of ColumnRef */
List* partitionKey;
} ForeignPartState;
struct DistributeBy;
typedef struct CreateForeignTableStmt {
CreateStmt base;
char* servername;
Node* error_relation;
List* options;
List* extOptions;
#ifdef PGXC
DistributeBy* distributeby;
#endif
bool write_only;
ForeignPartState* part_state;
} CreateForeignTableStmt;
#ifdef ENABLE_MOT
typedef struct AlterForeingTableCmd {
NodeTag type;
AlterTableType subtype;
Relation rel;
const char* name;
Node* def;
Oid colTypeOid;
Expr* defValue;
} AlterForeingTableCmd;
typedef struct RenameForeingTableCmd {
NodeTag type;
Oid relid;
ObjectType renameType;
char* oldname;
char* newname;
} RenameForeingTableCmd;
#endif
/* ----------------------
* Create/Drop USER MAPPING Statements
* ----------------------
*/
typedef struct CreateUserMappingStmt {
NodeTag type;
char* username; /* username or PUBLIC/CURRENT_USER */
char* servername; /* server name */
List* options; /* generic options to server */
} CreateUserMappingStmt;
typedef struct AlterUserMappingStmt {
NodeTag type;
char* username; /* username or PUBLIC/CURRENT_USER */
char* servername; /* server name */
List* options; /* generic options to server */
} AlterUserMappingStmt;
typedef struct DropUserMappingStmt {
NodeTag type;
char* username; /* username or PUBLIC/CURRENT_USER */
char* servername; /* server name */
bool missing_ok; /* ignore missing mappings */
} DropUserMappingStmt;
/* ----------------------
* Create Synonym Statement
* ----------------------
*/
typedef struct CreateSynonymStmt {
NodeTag type;
bool replace; /* T => replace if already exists */
List* synName; /* qualified name of synonym */
List* objName; /* referenced object name, eg. relation, view, function, procedure. */
} CreateSynonymStmt;
/* ----------------------
* Drop Synonym Statement
* ----------------------
*/
typedef struct DropSynonymStmt {
NodeTag type;
List* synName; /* qualified name of synonym */
DropBehavior behavior; /* RESTRICT or CASCADE behavior */
bool missing; /* skip error if a synonym is missing? */
} DropSynonymStmt;
/* ----------------------
* Create/Alter DATA SOURCE Statements
* ----------------------
*/
typedef struct CreateDataSourceStmt {
NodeTag type;
char* srcname; /* source name */
char* srctype; /* optional source type */
char* version; /* optional source version */
List* options; /* generic options to server */
} CreateDataSourceStmt;
typedef struct AlterDataSourceStmt {
NodeTag type;
char* srcname; /* source name */
char* srctype; /* optional source type */
char* version; /* optional source version */
List* options; /* generic options to source */
bool has_version; /* version specified */
} AlterDataSourceStmt;
/* ----------------------
* Create TRIGGER Statement
* ----------------------
*/
typedef struct CreateTrigStmt {
NodeTag type;
char* trigname; /* TRIGGER's name */
RangeVar* relation; /* relation trigger is on */
List* funcname; /* qual. name of function to call */
List* args; /* list of (T_String) Values or NIL */
bool row; /* ROW/STATEMENT */
/* timing uses the TRIGGER_TYPE bits defined in catalog/pg_trigger.h */
int16 timing; /* BEFORE, AFTER, or INSTEAD */
/* events uses the TRIGGER_TYPE bits defined in catalog/pg_trigger.h */
int16 events; /* "OR" of INSERT/UPDATE/DELETE/TRUNCATE */
List* columns; /* column names, or NIL for all columns */
Node* whenClause; /* qual expression, or NULL if none */
bool isconstraint; /* This is a constraint trigger */
/* The remaining fields are only used for constraint triggers */
bool deferrable; /* [NOT] DEFERRABLE */
bool initdeferred; /* INITIALLY {DEFERRED|IMMEDIATE} */
RangeVar* constrrel; /* opposite relation, if RI trigger */
FunctionSources* funcSource; /*mysql compatibility function body in begin... end */
char* definer; /*mysql compatibility define user */
char* trgordername; /* mysql compatibility trigger order {follows|precedes}*/
bool is_follows;
bool if_not_exists;
char* schemaname; /* mysql compatibility schema of new trigger, or NULL for default */
} CreateTrigStmt;
/* ----------------------
* Create PROCEDURAL LANGUAGE Statements
* ----------------------
*/
typedef struct CreatePLangStmt {
NodeTag type;
bool replace; /* T => replace if already exists */
char* plname; /* PL name */
List* plhandler; /* PL call handler function (qual. name) */
List* plinline; /* optional inline function (qual. name) */
List* plvalidator; /* optional validator function (qual. name) */
bool pltrusted; /* PL is trusted */
} CreatePLangStmt;
/* ----------------------
* Create/Alter/Drop Role Statements
*
* Note: these node types are also used for the backwards-compatible
* Create/Alter/Drop User/Group statements. In the ALTER and DROP cases
* there's really no need to distinguish what the original spelling was,
* but for CREATE we mark the type because the defaults vary.
* ----------------------
*/
typedef enum RoleStmtType { ROLESTMT_ROLE, ROLESTMT_USER, ROLESTMT_GROUP } RoleStmtType;
typedef struct CreateRoleStmt {
NodeTag type;
RoleStmtType stmt_type; /* ROLE/USER/GROUP */
char* role; /* role name */
List* options; /* List of DefElem nodes */
bool missing_ok; /* skip error if a role is exists */
} CreateRoleStmt;
/* ----------------------
* {Create|Alter} SEQUENCE Statement
* ----------------------
*/
typedef struct CreateSeqStmt {
NodeTag type;
RangeVar* sequence; /* the sequence to create */
List* options;
Oid ownerId; /* ID of owner, or InvalidOid for default */
#ifdef PGXC
bool is_serial; /* Indicates if this sequence is part of SERIAL process */
#endif
int64 uuid; /* UUID of the sequence, mark unique sequence globally */
bool canCreateTempSeq; /* create sequence when "create table (like )" */
bool is_large;
} CreateSeqStmt;
typedef struct AlterSeqStmt {
NodeTag type;
RangeVar* sequence; /* the sequence to alter */
List* options;
bool missing_ok; /* skip error if a role is missing? */
#ifdef PGXC
bool is_serial; /* Indicates if this sequence is part of SERIAL process */
#endif
bool is_large; /* Indicates if this is a large or normal sequence */
} AlterSeqStmt;
/* ----------------------
* Create {Aggregate|Operator|Type} Statement
* ----------------------
*/
typedef struct DefineStmt {
NodeTag type;
ObjectType kind; /* aggregate, operator, type */
bool oldstyle; /* hack to signal old CREATE AGG syntax */
List* defnames; /* qualified name (list of Value strings) */
List* args; /* a list of TypeName (if needed) */
List* definition; /* a list of DefElem */
} DefineStmt;
/* ----------------------
* Create Domain Statement
* ----------------------
*/
typedef struct CreateDomainStmt {
NodeTag type;
List* domainname; /* qualified name (list of Value strings) */
TypeName* typname; /* the base type */
CollateClause* collClause; /* untransformed COLLATE spec, if any */
List* constraints; /* constraints (list of Constraint nodes) */
} CreateDomainStmt;
/* ----------------------
* Create Operator Class Statement
* ----------------------
*/
typedef struct CreateOpClassStmt {
NodeTag type;
List* opclassname; /* qualified name (list of Value strings) */
List* opfamilyname; /* qualified name (ditto); NIL if omitted */
char* amname; /* name of index AM opclass is for */
TypeName* datatype; /* datatype of indexed column */
List* items; /* List of CreateOpClassItem nodes */
bool isDefault; /* Should be marked as default for type? */
} CreateOpClassStmt;
#define OPCLASS_ITEM_OPERATOR 1
#define OPCLASS_ITEM_FUNCTION 2
#define OPCLASS_ITEM_STORAGETYPE 3
typedef struct CreateOpClassItem {
NodeTag type;
int itemtype; /* see codes above */
/* fields used for an operator or function item: */
List* name; /* operator or function name */
List* args; /* argument types */
int number; /* strategy num or support proc num */
List* order_family; /* only used for ordering operators */
List* class_args; /* only used for functions */
/* fields used for a storagetype item: */
TypeName* storedtype; /* datatype stored in index */
} CreateOpClassItem;
/* ----------------------
* Create Operator Family Statement
* ----------------------
*/
typedef struct CreateOpFamilyStmt {
NodeTag type;
List* opfamilyname; /* qualified name (list of Value strings) */
char* amname; /* name of index AM opfamily is for */
} CreateOpFamilyStmt;
/* ----------------------
* Alter Operator Family Statement
* ----------------------
*/
typedef struct AlterOpFamilyStmt {
NodeTag type;
List* opfamilyname; /* qualified name (list of Value strings) */
char* amname; /* name of index AM opfamily is for */
bool isDrop; /* ADD or DROP the items? */
List* items; /* List of CreateOpClassItem nodes */
} AlterOpFamilyStmt;
#ifdef ENABLE_MOT
typedef struct DropForeignStmt {
NodeTag type;
char relkind;
Oid reloid;
Oid indexoid;
char* name;
} DropForeignStmt;
#endif
/* ----------------------
* Truncate Table Statement
* ----------------------
*/
typedef struct TruncateStmt {
NodeTag type;
List* relations; /* relations (RangeVars) to be truncated */
bool restart_seqs; /* restart owned sequences? */
DropBehavior behavior; /* RESTRICT or CASCADE behavior */
bool purge;
} TruncateStmt;
/* ----------------------
* Comment On Statement
* ----------------------
*/
typedef struct CommentStmt {
NodeTag type;
ObjectType objtype; /* Object's type */
List* objname; /* Qualified name of the object */
List* objargs; /* Arguments if needed (eg, for functions) */
char* comment; /* Comment to insert, or NULL to remove */
} CommentStmt;
/* ----------------------
* SECURITY LABEL Statement
* ----------------------
*/
typedef struct SecLabelStmt {
NodeTag type;
ObjectType objtype; /* Object's type */
List* objname; /* Qualified name of the object */
List* objargs; /* Arguments if needed (eg, for functions) */
char* provider; /* Label provider (or NULL) */
char* label; /* New security label to be assigned */
} SecLabelStmt;
/* ----------------------
* Close Portal Statement
* ----------------------
*/
typedef struct ClosePortalStmt {
NodeTag type;
char* portalname; /* name of the portal (cursor) */
/* NULL means CLOSE ALL */
} ClosePortalStmt;
/* ----------------------
* Fetch Statement (also Move)
* ----------------------
*/
typedef enum FetchDirection {
/* for these, howMany is how many rows to fetch; FETCH_ALL means ALL */
FETCH_FORWARD,
FETCH_BACKWARD,
/* for these, howMany indicates a position; only one row is fetched */
FETCH_ABSOLUTE,
FETCH_RELATIVE
} FetchDirection;
#define FETCH_ALL LONG_MAX
typedef struct FetchStmt {
NodeTag type;
FetchDirection direction; /* see above */
long howMany; /* number of rows, or position argument */
char* portalname; /* name of portal (cursor) */
bool ismove; /* TRUE if MOVE */
} FetchStmt;
/* ----------------------
* Create Index Statement
*
* This represents creation of an index and/or an associated constraint.
* If isconstraint is true, we should create a pg_constraint entry along
* with the index. But if indexOid isn't InvalidOid, we are not creating an
* index, just a UNIQUE/PKEY constraint using an existing index. isconstraint
* must always be true in this case, and the fields describing the index
* properties are empty.
* ----------------------
*/
typedef struct IndexStmt {
NodeTag type;
bool missing_ok; /* just do nothing if it already exists? */
char* schemaname; /* namespace of new index, or NULL for default */
char* idxname; /* name of new index, or NULL for default */
RangeVar* relation; /* relation to build index on */
char* accessMethod; /* name of access method (eg. btree) */
char* tableSpace; /* tablespace, or NULL for default */
List* indexParams; /* columns to index: a list of IndexElem */
List* indexIncludingParams; /* additional columns to index: a list of IndexElem */
List* options; /* WITH clause options: a list of DefElem */
Node* whereClause; /* qualification (partial-index predicate) */
List* excludeOpNames; /* exclusion operator names, or NIL if none */
char* idxcomment; /* comment to apply to index, or NULL */
Oid indexOid; /* OID of an existing index, if any */
Oid oldNode; /* relfilenode of existing storage, if any */
Oid oldPSortOid; /* oid of existing psort storage for col-storage, if any */
List* partIndexOldNodes; /* partition relfilenode of existing storage, if any */
List* partIndexOldPSortOid; /* partition psort oid, if any */
Node* partClause; /* partition index define */
bool* partIndexUsable; /* is partition index usable */
List* indexOptions; /* b compatiblity options */
/* @hdfs
* is a partitioned index? The foreign table dose not index. The isPartitioned
* value is false when relation is a foreign table.
*/
bool isPartitioned;
bool isGlobal; /* is GLOBAL partition index */
bool crossbucket; /* is crossbucket index */
bool unique; /* is index unique? */
bool primary; /* is index a primary key? */
bool isconstraint; /* is it for a pkey/unique constraint? */
bool deferrable; /* is the constraint DEFERRABLE? */
bool initdeferred; /* is the constraint INITIALLY DEFERRED? */
bool concurrent; /* should this be a concurrent index build? */
InformationalConstraint* inforConstraint; /* Soft constraint info, Currently only the HDFS foreign table support it
*/
/*
* Internal_flag is set to true when we use informational constraint feature,
* at the same time not_enforeced is also set to true.
*/
bool internal_flag;
/*
* For memory adapation, we will check the size of table before index create,
* but if it's constraint index during table creation, we don't need to do the size
* check, so set this flag to skip this
*/
bool skip_mem_check;
/* adaptive memory assigned for the stmt */
AdaptMem memUsage;
} IndexStmt;
typedef struct AlterFunctionStmt {
NodeTag type;
FuncWithArgs* func; /* name and args of function */
List* actions; /* list of DefElem */
} AlterFunctionStmt;
typedef struct InlineCodeBlock {
NodeTag type;
char* source_text; /* source text of anonymous code block */
Oid langOid; /* OID of selected language */
bool langIsTrusted; /* trusted property of the language */
bool atomic; /* Atomic execution context, does not allow transactions */
} InlineCodeBlock;
typedef struct CallContext
{
NodeTag type;
bool atomic; /* Atomic execution context, does not allow transactions */
} CallContext;
/* ----------------------
* ALTER object SET SCHEMA Statement
* ----------------------
*/
typedef struct AlterObjectSchemaStmt {
NodeTag type;
ObjectType objectType; /* OBJECT_TABLE, OBJECT_TYPE, etc */
RangeVar* relation; /* in case it's a table */
List* object; /* in case it's some other object */
List* objarg; /* argument types, if applicable */
char* addname; /* additional name if needed */
char* newschema; /* the new schema */
bool missing_ok; /* skip error if missing? */
} AlterObjectSchemaStmt;
/* ----------------------
* Alter Object Owner Statement
* ----------------------
*/
typedef struct AlterOwnerStmt {
NodeTag type;
ObjectType objectType; /* OBJECT_TABLE, OBJECT_TYPE, etc */
RangeVar* relation; /* in case it's a table */
List* object; /* in case it's some other object */
List* objarg; /* argument types, if applicable */
char* addname; /* additional name if needed */
char* newowner; /* the new owner */
} AlterOwnerStmt;
/* ----------------------
* Create Rule Statement
* ----------------------
*/
typedef struct RuleStmt {
NodeTag type;
RangeVar* relation; /* relation the rule is for */
char* rulename; /* name of the rule */
Node* whereClause; /* qualifications */
CmdType event; /* SELECT, INSERT, etc */
bool instead; /* is a 'do instead'? */
List* actions; /* the action statements */
bool replace; /* OR REPLACE */
char* sql_statement; /* used for resize rule */
} RuleStmt;
/* ----------------------
* Notify Statement
* ----------------------
*/
typedef struct NotifyStmt {
NodeTag type;
char* conditionname; /* condition name to notify */
char* payload; /* the payload string, or NULL if none */
} NotifyStmt;
/* ----------------------
* Listen Statement
* ----------------------
*/
typedef struct ListenStmt {
NodeTag type;
char* conditionname; /* condition name to listen on */
} ListenStmt;
/* ----------------------
* Unlisten Statement
* ----------------------
*/
typedef struct UnlistenStmt {
NodeTag type;
char* conditionname; /* name to unlisten on, or NULL for all */
} UnlistenStmt;
/* ----------------------
* Create Type Statement, composite types
* ----------------------
*/
typedef struct CompositeTypeStmt {
NodeTag type;
RangeVar* typevar; /* the composite type to be created */
List* coldeflist; /* list of ColumnDef nodes */
} CompositeTypeStmt;
/* ----------------------
* Create Type Statement, table of types
* ----------------------
*/
typedef struct TableOfTypeStmt {
NodeTag type;
List* typname; /* the table of type to be quoted */
TypeName* reftypname; /* the name of the type being referenced */
} TableOfTypeStmt;
/* ----------------------
* Create Type Statement, enum types
* ----------------------
*/
typedef struct CreateEnumStmt {
NodeTag type;
List* typname; /* qualified name (list of Value strings) */
List* vals; /* enum values (list of Value strings) */
} CreateEnumStmt;
/* ----------------------
* Create Type Statement, range types
* ----------------------
*/
typedef struct CreateRangeStmt {
NodeTag type;
List* typname; /* qualified name (list of Value strings) */
List* params; /* range parameters (list of DefElem) */
} CreateRangeStmt;
/* ----------------------
* Alter Type Statement, enum types
* ----------------------
*/
typedef struct AlterEnumStmt {
NodeTag type;
List* typname; /* qualified name (list of Value strings) */
char* oldVal; /* old enum value's name, if renaming */
char* newVal; /* new enum value's name */
char* newValNeighbor; /* neighboring enum value, if specified */
bool newValIsAfter; /* place new enum value after neighbor? */
bool skipIfNewValExists; /* no error if new already exists? */
} AlterEnumStmt;
/* ----------------------
* Load Statement
* ----------------------
*/
typedef enum LOAD_DATA_TYPE {
LOAD_DATA_APPEND,
LOAD_DATA_TRUNCATE,
LOAD_DATA_REPLACE,
LOAD_DATA_INSERT,
LOAD_DATA_UNKNOWN
} LOAD_DATA_TYPE;
typedef struct LoadWhenExpr {
NodeTag type;
int whentype; /* 0 poition 1 field name */
int start;
int end;
char *val;
const char *attname;
int attnum;
char *oper;
int operid;
} LoadWhenExpr;
typedef struct LoadStmt {
NodeTag type;
char* filename; /* file to load */
List *pre_load_options;
bool is_load_data;
bool is_only_special_filed;
// load data options
List *load_options;
// relation options
LOAD_DATA_TYPE load_type;
RangeVar *relation;
List *rel_options;
} LoadStmt;
/* ----------------------
* Createdb Statement
* ----------------------
*/
typedef struct CreatedbStmt {
NodeTag type;
char* dbname; /* name of database to create */
bool missing_ok; /* skip error if db is missing? */
List* options; /* List of DefElem nodes */
} CreatedbStmt;
/* ----------------------
* Alter Database
* ----------------------
*/
typedef struct AlterDatabaseStmt {
NodeTag type;
char* dbname; /* name of database to alter */
List* options; /* List of DefElem nodes */
} AlterDatabaseStmt;
/* ----------------------
* Dropdb Statement
* ----------------------
*/
typedef struct DropdbStmt {
NodeTag type;
char* dbname; /* database to drop */
bool missing_ok; /* skip error if db is missing? */
} DropdbStmt;
#ifndef ENABLE_MULTIPLE_NODES
/* ----------------------
* Alter System Statement
* ----------------------
*/
typedef struct AlterSystemStmt {
NodeTag type;
VariableSetStmt *setstmt; /* SET subcommand */
} AlterSystemStmt;
#endif
/* ----------------------
* Cluster Statement (support pbrown's cluster index implementation)
* ----------------------
*/
typedef struct ClusterStmt {
NodeTag type;
RangeVar* relation; /* relation being indexed, or NULL if all */
char* indexname; /* original index defined */
bool verbose; /* print progress info */
AdaptMem memUsage; /* adaptive memory assigned for the stmt */
} ClusterStmt;
/* ----------------------
* Vacuum and Analyze Statements
*
* Even though these are nominally two statements, it's convenient to use
* just one node type for both. Note that at least one of VACOPT_VACUUM
* and VACOPT_ANALYZE must be set in options. VACOPT_FREEZE is an internal
* convenience for the grammar and is not examined at runtime --- the
* freeze_min_age and freeze_table_age fields are what matter.
* ----------------------
*/
typedef enum VacuumOption {
VACOPT_VACUUM = 1 << 0, /* do VACUUM */
VACOPT_ANALYZE = 1 << 1, /* do ANALYZE */
VACOPT_VERBOSE = 1 << 2, /* print progress info */
VACOPT_FREEZE = 1 << 3, /* FREEZE option */
VACOPT_FULL = 1 << 4, /* FULL (non-concurrent) vacuum */
VACOPT_NOWAIT = 1 << 5, /* don't wait to get lock (autovacuum only) */
VACOPT_MERGE = 1 << 6, /* move data from delta table to main table */
VACOPT_MULTICOLUMN = 1 << 7,
VACOPT_VERIFY = 1 << 8, /* VERITY to check the data file */
VACOPT_FAST = 1 << 9, /* verify fast option */
VACOPT_COMPLETE = 1 << 10, /* verify complete option */
#ifdef ENABLE_MOT
VACOPT_AUTOVAC = 1 << 11, /* mark automatic vacuum initiation */
#endif
VACOPT_COMPACT = 1 << 30, /* compact hdfs file with invalid data just for DFS table */
VACOPT_HDFSDIRECTORY = 1 << 31 /* just clean empty hdfs directory */
} VacuumOption;
#define DEFAULT_SAMPLE_ROWCNT 30000
#define ANALYZE_MODE_MAX_NUM 4
#define GET_ESTTOTALROWCNTS_FLAG ((double)(-1.0))
#define INVALID_ESTTOTALROWS ((double)(-1.0))
/*
* Currently, the HDFS table need collect three statistics information
* in pg_statistic. we define AnalyzeMode enum strunct to realize global
* analyze.
* ANALYZENORMAL: Execute normal analyze command.
* ANALYZEDELTA: Collect only Delta table information when execute global analyze.
*/
typedef enum AnalyzeMode { ANALYZENORMAL = 0, ANALYZEDELTA = 2 } AnalyzeMode;
typedef struct GlobalStatInfoEx {
AnalyzeMode eAnalyzeMode; /* The mode of table whitch will collect stat info, normal table or HDFS table.
It need collect three statistics information for HDFS table. */
double sampleRate; /* CN compute it and send to DN. */
double secsamplerows; /* real sample rows num for second sampling. */
bool isReplication; /* the current relation is replication or not. */
bool exec_query; /* do query for dfs table and delta table to get sample or not according to the ratio with rows of
complex. */
double totalRowCnts; /* How many tuples receive from DN. */
int64 topRowCnts; /* Top tuple numbers receive from DN. */
int64 topMemSize; /* memory_size(KB)=com_size*oneTupleSize for DN, top memory size of all DNs for CN. */
int attnum; /* column num for current table. */
double dn1totalRowCnts; /* reltuples from DN1. */
double* dndistinct; /* stadndistinct for DN1 */
double* correlations; /* correlation of stats for DN1 */
int num_samples; /* how many sample rows receive from DN. */
HeapTuple* sampleRows; /* sample rows receive from DN. */
TupleDesc tupleDesc; /* sample row's tuple descriptor. */
} GlobalStatInfoEx;
struct SplitMap;
typedef struct VacuumStmt {
NodeTag type;
int options; /* OR of VacuumOption flags */
int flags; /* flags to distinguish partition or btree */
/* the values for this flags are in vacuum.h */
Oid rely_oid; /* for btree, it is the heap btree or it is InvalidOid */
int64 freeze_min_age; /* min freeze age, or -1 to use default */
int64 freeze_table_age; /* age at which to scan whole table */
RangeVar* relation; /* single table to process, or NULL */
List* va_cols; /* list of column names, or NIL for all */
Relation onepartrel; /* for tracing the opened relation */
Partition onepart; /* for tracing the opened partition */
Relation parentpartrel; /* for tracing the opened parent relation of a subpartition */
Partition parentpart; /* for tracing the opened parent partition of a subpartition */
bool issubpartition;
List* partList;
#ifdef PGXC
void* HDFSDnWorkFlow; /* @hdfs HDFSDnWorkFlow stores analyze operation related information */
#endif
bool isForeignTables; /* @hdfs This parameter is true when we run "analyze [verbose] foreign table;" command */
bool isPgFdwForeignTables; /* This parameter is true when the fdw of foreign table is gc_fdw */
#ifdef ENABLE_MOT
bool isMOTForeignTable;
#endif
unsigned int totalFileCnt; /* @hdfs The count of file to be sampled in analyze foreign table operation */
int nodeNo; /* @hdfs Which data node will do analyze operation,
@global stats: Other coordinators will get statistics from which coordinator node. */
/*
* @hdfs total number of Data nodes, we use this number to adjust reltuples cnt stored in pg_class
* eg: We do the operation "analyze tablename", we have x data nodes and tablename is a hdfs foreign
* table. Data node finish analyze command, CN get tuples number information from DN. This number
* is 1/x of the total tuples number. We adjust this number to the real one in CN.
*/
unsigned int DnCnt;
/*
* Add param for global stats.
*/
DestReceiver* dest; /* used to DN send sample rows to CN. */
int num_samples; /* how many sample rows receive from DN. */
HeapTuple* sampleRows; /* sample rows receive from DN. */
TupleDesc tupleDesc; /* sample row's tuple descriptor for normal table. */
int tableidx; /* set current index which table need to set sample rate or total row counts */
GlobalStatInfoEx pstGlobalStatEx[ANALYZE_MODE_MAX_NUM - 1]; /* the auxiliary info for global stats, it extend to
identify hdfs table. */
unsigned int orgCnNodeNo; /* the nodeId identify which CN receive analyze command from client, other CN need to get
stats from it. */
List* hdfsforeignMapDnList; /* identify some datanodes belone to split map used for CN get total reltuples from
them. */
bool sampleTableRequired; /* require sample table for get statistic. */
List* tmpSampleTblNameList; /* identify sample table name if under debugging. */
bool isAnalyzeTmpTable; /* true if analyze's table is temp table. */
#ifdef PGXC
DistributionType disttype; /* Distribution type for analyze's table. */
#endif
AdaptMem memUsage; /* adaptive memory assigned for the stmt */
Oid curVerifyRel; /* the current relation is for database mode to send remote query */
bool isCascade; /* used to verify table */
bool gpi_vacuumed;
} VacuumStmt;
/* Only support analyze, can not support vacuum analyze in transaction block. */
#define IS_ONLY_ANALYZE_TMPTABLE (((stmt)->isAnalyzeTmpTable) && !((stmt)->options & VACOPT_VACUUM))
#ifdef PGXC
/*
* ----------------------
* Barrier Statement
*/
typedef struct BarrierStmt {
NodeTag type;
char* id; /* User supplied barrier id, if any */
} BarrierStmt;
/*
* ----------------------
* Create Node statement
*/
typedef struct CreateNodeStmt {
NodeTag type;
char* node_name;
List* options;
} CreateNodeStmt;
/*
* ----------------------
* Alter Node statement
*/
typedef struct AlterNodeStmt {
NodeTag type;
char* node_name;
List* options;
} AlterNodeStmt;
typedef struct AlterCoordinatorStmt {
NodeTag type;
char* node_name;
char* set_value;
List* coor_nodes;
} AlterCoordinatorStmt;
/*
* ----------------------
* Drop Node statement
*/
typedef struct DropNodeStmt {
NodeTag type;
char* node_name;
bool missing_ok; /* skip error if db is missing? */
List* remote_nodes; /* specify where to drop node remotely */
} DropNodeStmt;
/*
* ----------------------
* Create Group statement
*/
typedef struct CreateGroupStmt {
NodeTag type;
char* group_name;
char* group_parent;
char* src_group_name;
List* nodes;
List* buckets;
int bucketcnt;
bool vcgroup;
} CreateGroupStmt;
/*
* ----------------------
* Alter Group statement
*/
typedef enum {
AG_SET_DEFAULT,
AG_SET_VCGROUP,
AG_SET_NOT_VCGROUP,
AG_SET_RENAME,
AG_SET_TABLE_GROUP,
AG_SET_BUCKETS,
AG_ADD_NODES,
AG_DELETE_NODES,
AG_RESIZE_GROUP,
AG_CONVERT_VCGROUP,
AG_SET_SEQ_ALLNODES,
AG_SET_SEQ_SELFNODES
} AlterGroupType;
typedef struct AlterGroupStmt {
NodeTag type;
char* group_name;
char* install_name;
List* nodes;
AlterGroupType alter_type;
} AlterGroupStmt;
/*
* ----------------------
* Drop Group statement
*/
typedef struct DropGroupStmt {
NodeTag type;
char* group_name;
char* src_group_name;
bool to_elastic_group;
} DropGroupStmt;
/*
* ----------------------
* Create Policy Label statement
*/
typedef struct CreatePolicyLabelStmt {
NodeTag type;
bool if_not_exists;
char* label_type;
char* label_name;
List* label_items;
} CreatePolicyLabelStmt;
/*
* ----------------------
* Alter Policy Label statement
*/
typedef struct AlterPolicyLabelStmt {
NodeTag type;
char* stmt_type;
char* label_name;
List* label_items;
} AlterPolicyLabelStmt;
/*
* ----------------------
* Drop Policy Label statement
*/
typedef struct DropPolicyLabelStmt {
NodeTag type;
bool if_exists;
List* label_names;
} DropPolicyLabelStmt;
/*
* ----------------------
*
*/
typedef struct PolicyFilterNode
{
NodeTag type;
char *node_type; /* operator or filter node */
char *op_value; /* for operator type node usage */
char *filter_type; /* for filter type node usage */
List *values; /* for filter type node usage */
bool has_not_operator; /* for filter type node usage */
Node *left; /* for operator type node usage */
Node *right; /* for operator type node usage */
} PolicyFilterNode;
/*
* ----------------------
* Create Audit Policy statement
*/
typedef struct CreateAuditPolicyStmt
{
NodeTag type;
bool if_not_exists;
char *policy_type;
char *policy_name;
List *policy_targets;
List *policy_filters;
bool policy_enabled;
} CreateAuditPolicyStmt;
/*
* ----------------------
* Alter Audit Policy statement
*/
typedef struct AlterAuditPolicyStmt
{
NodeTag type;
bool missing_ok;
char *policy_name;
char *policy_action;
char *policy_type;
List *policy_items;
List *policy_filters;
char *policy_comments;
Node *policy_enabled;
} AlterAuditPolicyStmt;
/*
* ----------------------
* Drop Audit Policy statement
*/
typedef struct DropAuditPolicyStmt
{
NodeTag type;
bool missing_ok;
List *policy_names;
} DropAuditPolicyStmt;
/*
* ----------------------
* Masking Policy Condition
*/
typedef struct MaskingPolicyCondition
{
NodeTag type;
RangeVar *fqdn;
char *_operator;
Node *arg;
} MaskingPolicyCondition;
/*
* ----------------------
* Create Masking Policy statement
*/
typedef struct CreateMaskingPolicyStmt
{
NodeTag type;
bool if_not_exists;
char *policy_name;
List *policy_data;
Node *policy_condition;
List *policy_filters;
bool policy_enabled;
} CreateMaskingPolicyStmt;
/*
* ----------------------
* Alter Masking Policy statement
*/
typedef struct AlterMaskingPolicyStmt
{
NodeTag type;
char *policy_name;
char *policy_action;
List *policy_items;
Node *policy_condition;
List *policy_filters;
char *policy_comments;
Node *policy_enabled;
} AlterMaskingPolicyStmt;
/*
* ----------------------
* Drop Masking Policy statement
*/
typedef struct DropMaskingPolicyStmt
{
NodeTag type;
bool if_exists;
List *policy_names;
} DropMaskingPolicyStmt;
typedef struct AlterSchemaStmt {
NodeTag type;
char *schemaname; /* the name of the schema to create */
char *authid; /* the owner of the created schema */
bool hasBlockChain; /* whether this schema has blockchain */
int charset;
char *collate;
} AlterSchemaStmt;
/*
* ----------------------
* Create Resource Pool statement
*/
typedef struct CreateResourcePoolStmt {
NodeTag type;
char* pool_name;
List* options;
} CreateResourcePoolStmt;
/*
* ----------------------
* Alter Resource Pool statement
*/
typedef struct AlterResourcePoolStmt {
NodeTag type;
char* pool_name;
List* options;
} AlterResourcePoolStmt;
/*
* ----------------------
* Drop Resource Pool statement
*/
typedef struct DropResourcePoolStmt {
NodeTag type;
bool missing_ok;
char* pool_name;
} DropResourcePoolStmt;
typedef struct AlterGlobalConfigStmt {
NodeTag type;
List* options;
} AlterGlobalConfigStmt;
typedef struct DropGlobalConfigStmt {
NodeTag type;
List* options;
} DropGlobalConfigStmt;
/*
* ----------------------
* Create Workload Group statement
*/
typedef struct CreateWorkloadGroupStmt {
NodeTag type;
char* group_name;
char* pool_name;
List* options;
} CreateWorkloadGroupStmt;
/*
* ----------------------
* Alter Workload Group statement
*/
typedef struct AlterWorkloadGroupStmt {
NodeTag type;
char* group_name;
char* pool_name;
List* options;
} AlterWorkloadGroupStmt;
/*
* ----------------------
* Drop Workload Group statement
*/
typedef struct DropWorkloadGroupStmt {
NodeTag type;
bool missing_ok;
char* group_name;
} DropWorkloadGroupStmt;
/*
* ----------------------
* Create App Workload Group Mapping statement
*/
typedef struct CreateAppWorkloadGroupMappingStmt {
NodeTag type;
char* app_name;
List* options;
} CreateAppWorkloadGroupMappingStmt;
/*
* ----------------------
* Alter App Workload Group Mapping statement
*/
typedef struct AlterAppWorkloadGroupMappingStmt {
NodeTag type;
char* app_name;
List* options;
} AlterAppWorkloadGroupMappingStmt;
/*
* ----------------------
* Drop App Workload Group Mapping statement
*/
typedef struct DropAppWorkloadGroupMappingStmt {
NodeTag type;
bool missing_ok;
char* app_name;
} DropAppWorkloadGroupMappingStmt;
#endif
struct PlanInformation;
/* ----------------------
* Explain Statement
*
* The "query" field is either a raw parse tree (SelectStmt, InsertStmt, etc)
* or a Query node if parse analysis has been done. Note that rewriting and
* planning of the query are always postponed until execution of EXPLAIN.
* ----------------------
*/
typedef struct ExplainStmt {
NodeTag type;
Node* statement; /* statement_id for EXPLAIN PLAN */
Node* query; /* the query (see comments above) */
List* options; /* list of DefElem nodes */
PlanInformation* planinfo;
} ExplainStmt;
/* ----------------------
* REFRESH MATERIALIZED VIEW Statement
* ----------------------
*/
typedef struct RefreshMatViewStmt
{
NodeTag type;
bool skipData; /* true for WITH NO DATA */
bool incremental; /* true for INCREMENTALLY */
RangeVar *relation; /* relation to insert into */
} RefreshMatViewStmt;
/* ----------------------
* Checkpoint Statement
* ----------------------
*/
typedef struct CheckPointStmt {
NodeTag type;
} CheckPointStmt;
/* ----------------------
* Discard Statement
* ----------------------
*/
typedef enum DiscardMode { DISCARD_ALL, DISCARD_PLANS, DISCARD_TEMP } DiscardMode;
typedef struct DiscardStmt {
NodeTag type;
DiscardMode target;
} DiscardStmt;
/* ----------------------
* LOCK Statement
* ----------------------
*/
typedef struct LockStmt {
NodeTag type;
List* relations; /* relations to lock */
int mode; /* lock mode */
bool nowait; /* no wait mode */
bool cancelable; /* send term to lock holder */
int waitSec; /* WAIT time Sec */
bool isLockTables; /* lock tables flag */
} LockStmt;
/* ----------------------
* SET CONSTRAINTS Statement
* ----------------------
*/
typedef struct ConstraintsSetStmt {
NodeTag type;
List* constraints; /* List of names as RangeVars */
bool deferred;
} ConstraintsSetStmt;
#ifdef ENABLE_MOT
typedef struct ReindexForeignStmt {
NodeTag type;
char relkind;
Oid reloid;
Oid indexoid;
char* name;
} ReindexForeignStmt;
#endif
/* ----------------------
* CREATE CONVERSION Statement
* ----------------------
*/
typedef struct CreateConversionStmt {
NodeTag type;
List* conversion_name; /* Name of the conversion */
char* for_encoding_name; /* source encoding name */
char* to_encoding_name; /* destination encoding name */
List* func_name; /* qualified conversion function name */
bool def; /* is this a default conversion? */
} CreateConversionStmt;
/* ----------------------
* CREATE CAST Statement
* ----------------------
*/
typedef struct CreateCastStmt {
NodeTag type;
TypeName* sourcetype;
TypeName* targettype;
FuncWithArgs* func;
CoercionContext context;
bool inout;
} CreateCastStmt;
/* ----------------------
* DEALLOCATE Statement
* ----------------------
*/
typedef struct DeallocateStmt {
NodeTag type;
char* name; /* The name of the plan to remove */
/* NULL means DEALLOCATE ALL */
} DeallocateStmt;
/*
* DROP OWNED statement
*/
typedef struct DropOwnedStmt {
NodeTag type;
List* roles;
DropBehavior behavior;
} DropOwnedStmt;
/*
* REASSIGN OWNED statement
*/
typedef struct ReassignOwnedStmt {
NodeTag type;
List* roles;
char* newrole;
} ReassignOwnedStmt;
/*
* TS Dictionary stmts: DefineStmt, RenameStmt and DropStmt are default
*/
typedef struct AlterTSDictionaryStmt {
NodeTag type;
List* dictname; /* qualified name (list of Value strings) */
List* options; /* List of DefElem nodes */
} AlterTSDictionaryStmt;
/*
* TS Configuration stmts: DefineStmt, RenameStmt and DropStmt are default
*/
typedef enum AlterTSConfigType
{
ALTER_TSCONFIG_ADD_MAPPING,
ALTER_TSCONFIG_ALTER_MAPPING_FOR_TOKEN,
ALTER_TSCONFIG_REPLACE_DICT,
ALTER_TSCONFIG_REPLACE_DICT_FOR_TOKEN,
ALTER_TSCONFIG_DROP_MAPPING
} AlterTSConfigType;
typedef struct AlterTSConfigurationStmt {
NodeTag type;
List* cfgname; /* qualified name (list of Value strings) */
AlterTSConfigType kind; /* ALTER_TSCONFIG_ADD_MAPPING, etc */
/*
* dicts will be non-NIL if ADD/ALTER MAPPING was specified. If dicts is
* NIL, but tokentype isn't, DROP MAPPING was specified.
*/
List* tokentype; /* list of Value strings */
List* dicts; /* list of list of Value strings */
List* cfoptions; /* list of configuration options */
bool override; /* if true - remove old variant */
bool replace; /* if true - replace dictionary by another */
bool missing_ok; /* for DROP - skip error if missing? */
bool is_reset; /* if true - reset options */
} AlterTSConfigurationStmt;
/*
* CLEAN CONNECTION statement
*/
typedef struct CleanConnStmt {
NodeTag type;
List* nodes; /* list of nodes dropped */
char* dbname; /* name of database to drop connections */
char* username; /* name of user whose connections are dropped */
bool is_coord; /* type of connections dropped */
bool is_force; /* option force */
bool is_check; /* option check */
} CleanConnStmt;
/*
* CreateTableLike Context
*/
typedef struct TableLikeCtx {
NodeTag type;
bits32 options; /* OR of TableLikeOption flags */
bool temp_table; /* temporary table or not */
bool hasoids; /* has oids or not */
List* columns; /* the list of ColumnDef */
List* ckconstraints;
List* comments;
List* cluster_keys;
PartitionState* partition;
List* inh_indexes;
List* reloptions;
} TableLikeCtx;
typedef struct CreateDirectoryStmt {
NodeTag type;
bool replace; /* T => replace if already exists */
char* directoryname; /* the name of directory to create */
char* owner; /* directory's owner */
char* location; /* the real path of directory */
} CreateDirectoryStmt;
typedef struct AlterDirectoryStmt {
NodeTag type;
char* directoryname; /* the name of directory to create */
char* owner; /* directory's owner */
char* location; /* the real path of directory */
List* options; /* list of options */
} AlterDirectoryStmt;
typedef struct DropDirectoryStmt {
NodeTag type;
char* directoryname; /* the name of directory to drop */
bool missing_ok; /* skip error if db is missing? */
} DropDirectoryStmt;
/* ----------------------
* DolphinCall Type Statement, call procedure
* ----------------------
*/
typedef struct DolphinCallStmt
{
NodeTag type;
FuncCall *funccall; /* procedure */
FuncExpr *funcexpr; /* transformCallstmt deal, only input args */
List *outargs; /* output args only be UserVar */
} DolphinCallStmt;
/* ----------------------
* Create Type Statement, set types
* ----------------------
*/
typedef struct CreateSetStmt {
NodeTag type;
TypeName *typname; /* type of column */
Oid set_collation;
} CreateSetStmt;
/* ----------------------
* Get Diagnostics Statement
* ----------------------
*/
enum {
COND_INFO_NUMBER,
COND_INFO_ROW_COUNT,
COND_INFO_CLASS_ORIGIN,
COND_INFO_SUBCLASS_ORIGIN,
COND_INFO_CONSTRAINT_CATALOG,
COND_INFO_CONSTRAINT_SCHEMA,
COND_INFO_CONSTRAINT_NAME,
COND_INFO_CATALOG_NAME,
COND_INFO_SCHEMA_NAME,
COND_INFO_TABLE_NAME,
COND_INFO_COLUMN_NAME,
COND_INFO_CURSOR_NAME,
COND_INFO_MESSAGE_TEXT,
COND_INFO_MYSQL_ERRNO,
COND_INFO_RETURNED_SQLSTATE
};
typedef struct CondInfo {
NodeTag type;
List *target;
int kind;
} CondInfo;
typedef struct GetDiagStmt {
NodeTag type;
List *condInfo;
bool hasCondNum;
List *condNum;
} GetDiagStmt;
#endif /* PARSENODES_H */
|
a81bdb4a433bb45207bb4cbb43ea33dcff80538f
|
99bdb3251fecee538e0630f15f6574054dfc1468
|
/bsp/hc32/libraries/hc32f460_ddl/midwares/hc32/usb/usb_device_lib/device_core/usb_dev_driver.h
|
2cb904a73c0334cd2f92c075114a55453dd5b4ef
|
[
"BSD-3-Clause",
"Apache-2.0",
"Zlib",
"LicenseRef-scancode-proprietary-license",
"MIT",
"X11",
"BSD-4-Clause-UC",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
RT-Thread/rt-thread
|
03a7c52c2aeb1b06a544143b0e803d72f47d1ece
|
3602f891211904a27dcbd51e5ba72fefce7326b2
|
refs/heads/master
| 2023-09-01T04:10:20.295801
| 2023-08-31T16:20:55
| 2023-08-31T16:20:55
| 7,408,108
| 9,599
| 5,805
|
Apache-2.0
| 2023-09-14T13:37:26
| 2013-01-02T14:49:21
|
C
|
UTF-8
|
C
| false
| false
| 3,342
|
h
|
usb_dev_driver.h
|
/**
*******************************************************************************
* @file usb_dev_driver.h
* @brief Peripheral Driver Header file
@verbatim
Change Logs:
Date Author Notes
2022-03-31 CDT First version
@endverbatim
*******************************************************************************
* Copyright (C) 2022, Xiaohua Semiconductor Co., Ltd. All rights reserved.
*
* This software component is licensed by XHSC under BSD 3-Clause license
* (the "License"); You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
*******************************************************************************
*/
#ifndef __USB_DEV_DRIVER_H__
#define __USB_DEV_DRIVER_H__
/* C binding of definitions if building with C++ compiler */
#ifdef __cplusplus
extern "C"
{
#endif
/*******************************************************************************
* Include files
******************************************************************************/
#include "usb_dev_def.h"
/**
* @addtogroup LL_USB_LIB
* @{
*/
/**
* @addtogroup LL_USB_DEV_CORE
* @{
*/
/*******************************************************************************
* Global type definitions ('typedef')
******************************************************************************/
/*******************************************************************************
* Global pre-processor symbols/macros ('#define')
******************************************************************************/
/*******************************************************************************
* Global variable definitions ('extern')
******************************************************************************/
/*******************************************************************************
Global function prototypes (definition in C source)
******************************************************************************/
extern void usb_initdev(usb_core_instance *pdev);
extern void usb_conndevctrl(usb_core_instance *pdev, uint8_t link);
extern void usb_addrset(usb_core_instance *pdev, uint8_t devaddr);
extern void usb_opendevep(usb_core_instance *pdev, uint8_t ep_addr, uint16_t ep_mps, uint8_t ep_type);
extern void usb_shutdevep(usb_core_instance *pdev, uint8_t ep_addr);
extern void usb_readytorx(usb_core_instance *pdev, uint8_t ep_addr, uint8_t *pbuf, uint16_t buf_len);
extern void usb_ep0outstart(usb_core_instance *pdev);
extern void usb_deveptx(usb_core_instance *pdev, uint8_t ep_addr, uint8_t *pbuf, uint32_t buf_len);
extern void usb_stalldevep(usb_core_instance *pdev, uint8_t epnum);
extern void usb_clrstall(usb_core_instance *pdev, uint8_t epnum);
extern void usb_flsdevep(usb_core_instance *pdev, uint8_t epnum);
extern uint32_t usb_devepstatusget(usb_core_instance *pdev, uint8_t epnum);
extern void usb_devepstatusset(usb_core_instance *pdev, uint8_t epnum, uint32_t status);
/**
* @}
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USB_DEV_DRIVER_H__ */
/*******************************************************************************
* EOF (not truncated)
******************************************************************************/
|
299cdbd00d6ffd6559da39e83c7395f2eae67648
|
9ceacf33fd96913cac7ef15492c126d96cae6911
|
/sys/arch/alpha/include/pcb.h
|
97fa2d77b09581d509e2b44902a9bd4b2eec4b05
|
[] |
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,259
|
h
|
pcb.h
|
/* $OpenBSD: pcb.h,v 1.11 2015/05/05 02:13:46 guenther Exp $ */
/* $NetBSD: pcb.h,v 1.5 1996/11/13 22:21:00 cgd Exp $ */
/*
* Copyright (c) 1994, 1995, 1996 Carnegie-Mellon University.
* All rights reserved.
*
* Author: Chris G. Demetriou
*
* Permission to use, copy, modify and distribute this software and
* its documentation is hereby granted, provided that both the copyright
* notice and this permission notice appear in all copies of the
* software, derivative works or modified versions, and any portions
* thereof, and that both notices appear in supporting documentation.
*
* CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
* CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
* FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
*
* Carnegie Mellon requests users of this software to return to
*
* Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
* School of Computer Science
* Carnegie Mellon University
* Pittsburgh PA 15213-3890
*
* any improvements or extensions that they make and grant Carnegie the
* rights to redistribute these changes.
*/
#ifndef _MACHINE_PCB_H_
#define _MACHINE_PCB_H_
#include <machine/frame.h>
#include <machine/reg.h>
#include <machine/alpha_cpu.h>
/*
* PCB: process control block
*
* In this case, the hardware structure that is the defining element
* for a process, and the additional state that must be saved by software
* on a context switch. Fields marked [HW] are mandated by hardware; fields
* marked [SW] are for the software.
*
* It's said in the VMS PALcode section of the AARM that the pcb address
* passed to the swpctx PALcode call has to be a physical address. Not
* knowing this (and trying a virtual) address proved this correct.
* So we cache the physical address of the pcb in the md_proc struct.
*/
struct pcb {
struct alpha_pcb pcb_hw; /* PALcode defined */
unsigned long pcb_context[9]; /* s[0-6], ra, ps [SW] */
struct fpreg pcb_fp; /* FP registers [SW] */
unsigned long pcb_onfault; /* for copy faults [SW] */
struct cpu_info *volatile pcb_fpcpu; /* CPU with our FP state[SW] */
};
#ifdef _KERNEL
void savectx(struct pcb *);
#endif
#endif /* _MACHINE_PCB_H_ */
|
451fe177f206e2a599ba2b50150ae5b1c75dfc81
|
035660e8cc10571ebbd0d4393fef063bb7eb98f6
|
/src/overlays/actors/ovl_En_Kakasi/z_en_kakasi.c
|
9e3e5682828bcc475efbae593f14c5616d1ed84d
|
[] |
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
| 46,846
|
c
|
z_en_kakasi.c
|
/*
* File: z_en_kakasi.c
* Overlay: ovl_En_Kakasi
* Description: Pierre the Scarecorw
*/
#include "prevent_bss_reordering.h"
#include "z_en_kakasi.h"
#include "objects/object_ka/object_ka.h"
#define FLAGS (ACTOR_FLAG_1 | ACTOR_FLAG_8 | ACTOR_FLAG_10 | ACTOR_FLAG_2000000)
#define THIS ((EnKakasi*)thisx)
void EnKakasi_Init(Actor* thisx, PlayState* play);
void EnKakasi_Destroy(Actor* thisx, PlayState* play);
void EnKakasi_Update(Actor* thisx, PlayState* play);
void EnKakasi_Draw(Actor* thisx, PlayState* play);
void EnKakasi_SetupPostSongLearnDialogue(EnKakasi* this, PlayState* play);
void EnKakasi_InitTimeSkipDialogue(EnKakasi* this);
void EnKakasi_SetupIdleStanding(EnKakasi* this);
s32 EnKakasi_ValidatePictograph(PlayState* play, Actor* thisx);
void EnKakasi_TimeSkipDialogue(EnKakasi* this, PlayState* play);
void EnKakasi_IdleStanding(EnKakasi* this, PlayState* play);
void EnKakasi_OcarinaRemark(EnKakasi* this, PlayState* play);
void EnKakasi_TeachingSong(EnKakasi* this, PlayState* play);
void EnKakasi_PostSongLearnTwirl(EnKakasi* this, PlayState* play);
void EnKakasi_PostSongLearnDialogue(EnKakasi* this, PlayState* play);
void EnKakasi_SetupDigAway(EnKakasi* this);
void EnKakasi_DiggingAway(EnKakasi* this, PlayState* play);
void EnKakasi_RisenDialogue(EnKakasi* this, PlayState* play);
void EnKakasi_SetupIdleUnderground(EnKakasi* this);
void EnKakasi_IdleUnderground(EnKakasi* this, PlayState* play);
void EnKakasi_SetupIdleRisen(EnKakasi* this);
void EnKakasi_IdleRisen(EnKakasi* this, PlayState* play);
void EnKakasi_SetupRiseOutOfGround(EnKakasi* this, PlayState* play);
void EnKakasi_RisingOutOfGround(EnKakasi* this, PlayState* play);
void EnKakasi_DancingRemark(EnKakasi* this, PlayState* play);
void EnKakasi_SetupDanceNightAway(EnKakasi* this);
void EnKakasi_DancingNightAway(EnKakasi* this, PlayState* play);
void EnKakasi_DoNothing(EnKakasi* this, PlayState* play);
void EnKakasi_RegularDialogue(EnKakasi* this, PlayState* play);
void EnKakasi_SetupSongTeach(EnKakasi* this, PlayState* play);
void EnKakasi_SetupDialogue(EnKakasi* this);
static ColliderCylinderInit D_80971D80 = {
{
COLTYPE_NONE,
AT_NONE,
AC_ON | AC_TYPE_PLAYER,
OC1_ON | OC1_TYPE_ALL,
OC2_TYPE_2,
COLSHAPE_CYLINDER,
},
{
ELEMTYPE_UNK0,
{ 0xF7CFFFFF, 0x00, 0x00 },
{ 0xF7CFFFFF, 0x00, 0x00 },
TOUCH_NONE | TOUCH_SFX_NORMAL,
BUMP_ON | BUMP_HOOKABLE,
OCELEM_ON,
},
{ 20, 70, 0, { 0, 0, 0 } },
};
ActorInit En_Kakasi_InitVars = {
ACTOR_EN_KAKASI,
ACTORCAT_NPC,
FLAGS,
OBJECT_KA,
sizeof(EnKakasi),
(ActorFunc)EnKakasi_Init,
(ActorFunc)EnKakasi_Destroy,
(ActorFunc)EnKakasi_Update,
(ActorFunc)EnKakasi_Draw,
};
Vec3f D_80971DCC[] = {
{ 0.0f, 60.0f, 60.0f }, { 40.0f, 40.0f, 50.0f }, { -40.0f, 40.0f, 50.0f },
{ 40.0f, 20.0f, 110.0f }, { -40.0f, 20.0f, 110.0f }, { 0.0f, 80.0f, 60.0f },
{ 50.0f, 40.0f, -30.0f }, { -50.0f, 40.0f, -30.0f }, { 0.0f, 50.0f, 60.0f },
};
Vec3f D_80971E38[] = {
{ 0.0f, 55.0f, 60.0f }, { 0.0f, 55.0f, 60.0f }, { -80.0f, 35.0f, 15.0f }, { 80.0f, 45.0f, 15.0f },
{ -10.0f, 35.0f, 65.0f }, { 0.0f, 110.0f, 180.0f }, { 0.0f, 60.0f, 70.0f }, { 0.0f, 60.0f, 70.0f },
{ -80.0f, 50.0f, 40.0f }, { 0.0f, -10.0f, 50.0f }, { 80.0f, 50.0f, 40.0f }, { 0.0f, 120.0f, 40.0f },
{ 0.0f, 28.0f, -50.0f }, { 0.0f, 60.0f, 50.0f }, { 0.0f, 80.0f, 160.0f },
};
Vec3f D_80971EEC[] = {
{ 12.0f, 1.0f, 2.0f }, { 12.0f, 1.0f, 2.0f }, { 2.0f, -6.0f, 0.0f }, { 12.0f, -6.0f, -10.0f },
{ -88.0f, 14.0, -10.0f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f },
{ 0.0f, -10.0f, 0.0f }, { 0.0f, -10.0f, 0.0f }, { 0.0f, -10.0f, 0.0f }, { 0.0f, -10.0f, 0.0f },
{ 0.0f, -10.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f },
};
Vec3f D_80971FA0[] = {
{ -50.0f, 160.0f, -40.0f }, { -50.0f, 160.0f, -40.0f }, { -20.0f, 80.0f, 60.0f },
{ 57.0f, 60.0f, 120.0f }, { 27.0f, 80.0f, 60.0f }, { -3.0f, 50.0f, 70.0f },
};
Vec3f D_80971FE8[] = {
{ 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, { -10.0f, -5.0f, 0.0f },
{ 10.0f, -10.0f, 7.0f }, { 20.0f, 5.0f, 2.0f }, { 10.0f, 5.0f, 2.0f },
};
// both use in digging away function
Vec3f D_80972030 = { -3.0f, 50.0f, 90.0f };
Vec3f D_8097203C = { 10.0f, -15.0f, 2.0f };
typedef enum {
/* 0 */ ENKAKASI_ANIM_ARMS_CROSSED_ROCKING, // arms crossed and rocking back and forth
/* 1 */ ENKAKASI_ANIM_SIDEWAYS_SHAKING,
/* 2 */ ENKAKASI_ANIM_HOPPING_REGULAR, // bounce bounce bounce (repeat)
/* 3 */ ENKAKASI_ANIM_SPIN_REACH_OFFER, // spin and then reaching toward player
/* 4 */ ENKAKASI_ANIM_TWIRL, // slower cinimatic twirl
/* 5 */ ENKAKASI_ANIM_ARMS_CROSSED_STILL, // arms crossed but still, also some noise sfx
/* 6 */ ENKAKASI_ANIM_WAVE, // "wave" short sideways shake, stops early, partial? unused?
/* 7 */ ENKAKASI_ANIM_SLOWROLL, // partial bounch, ends looking left, OFFER anim takes over
/* 8 */ ENKAKASI_ANIM_IDLE // slow stretching wiggle, ends in regular position
} EnKakasiAnimation;
static AnimationHeader* sAnimations[] = {
&object_ka_Anim_007444, &object_ka_Anim_00686C, &object_ka_Anim_0081A4,
&object_ka_Anim_007B90, &object_ka_Anim_0071EC, &object_ka_Anim_007444,
&object_ka_Anim_00686C, &object_ka_Anim_0081A4, &object_ka_Anim_000214,
};
static u8 sAnimationModes[] = {
ANIMMODE_LOOP, ANIMMODE_LOOP, ANIMMODE_LOOP, ANIMMODE_ONCE, ANIMMODE_ONCE,
ANIMMODE_ONCE, ANIMMODE_ONCE, ANIMMODE_ONCE, ANIMMODE_ONCE,
};
void EnKakasi_Destroy(Actor* thisx, PlayState* play) {
EnKakasi* this = THIS;
Collider_DestroyCylinder(play, &this->collider);
}
void EnKakasi_Init(Actor* thisx, PlayState* play) {
EnKakasi* this = THIS;
s32 csId;
s32 i;
Collider_InitAndSetCylinder(play, &this->collider, &this->picto.actor, &D_80971D80);
SkelAnime_InitFlex(play, &this->skelAnime, &object_ka_Skel_0065B0, &object_ka_Anim_000214, 0, 0, 0);
this->songSummonDist = KAKASI_GET_SUMMON_DISTANCE(&this->picto.actor) * 20.0f;
if (this->songSummonDist < 40.0f) {
this->songSummonDist = 40.0f;
}
this->unkHeight = (this->picto.actor.world.rot.z * 20.0f) + 60.0f;
this->picto.actor.world.rot.z = 0;
this->picto.actor.targetMode = 0;
if ((this->picto.actor.world.rot.x > 0) && (this->picto.actor.world.rot.x < 8)) {
this->picto.actor.targetMode = KAKASI_GET_TARGETMODE(thisx);
}
this->picto.actor.shape.rot.y = this->picto.actor.world.rot.y;
this->aboveGroundStatus = KAKASI_GET_ABOVE_GROUND(&this->picto.actor);
this->picto.actor.world.rot.x = 0;
this->picto.actor.flags |= ACTOR_FLAG_400;
this->picto.actor.colChkInfo.mass = MASS_IMMOVABLE;
Actor_SetScale(&this->picto.actor, 0.01f);
i = 0;
csId = this->picto.actor.csId;
while (csId != CS_ID_NONE) {
//! FAKE:
csId = CutsceneManager_GetAdditionalCsId(this->csIdList[i] = csId);
i++;
}
if (this->aboveGroundStatus != 0) {
if (CHECK_WEEKEVENTREG(WEEKEVENTREG_79_08)) {
this->aboveGroundStatus = ENKAKASI_ABOVE_GROUND_TYPE;
this->songSummonDist = 80.0f;
EnKakasi_SetupIdleUnderground(this);
} else {
Actor_SetFocus(&this->picto.actor, 60.0f);
this->picto.validationFunc = EnKakasi_ValidatePictograph;
if (CHECK_WEEKEVENTREG(WEEKEVENTREG_83_01)) {
EnKakasi_InitTimeSkipDialogue(this);
} else {
EnKakasi_SetupIdleStanding(this);
}
}
} else {
EnKakasi_SetupIdleUnderground(this);
}
}
void EnKakasi_ChangeAnim(EnKakasi* this, s32 animIndex) {
this->animIndex = animIndex;
this->animEndFrame = Animation_GetLastFrame(&sAnimations[this->animIndex]->common);
// 1: regular playback speed, 0: starting frame
Animation_Change(&this->skelAnime, sAnimations[this->animIndex], 1.0f, 0.0f, this->animEndFrame,
sAnimationModes[this->animIndex], -4.0f);
}
s32 EnKakasi_ValidatePictograph(PlayState* play, Actor* thisx) {
return Snap_ValidatePictograph(play, thisx, 0x7, &thisx->focus.pos, &thisx->shape.rot, 280.0f, 1800.0f, -1);
}
void EnKakasi_CheckAnimationSfx(EnKakasi* this) {
if ((this->animIndex == ENKAKASI_ANIM_SIDEWAYS_SHAKING) || (this->animIndex == ENKAKASI_ANIM_ARMS_CROSSED_STILL)) {
if (Animation_OnFrame(&this->skelAnime, 1.0f) || Animation_OnFrame(&this->skelAnime, 8.0f)) {
Actor_PlaySfx(&this->picto.actor, NA_SE_EV_KAKASHI_SWING);
}
}
if ((this->animIndex == ENKAKASI_ANIM_HOPPING_REGULAR) || (this->animIndex == ENKAKASI_ANIM_SLOWROLL)) {
if (Animation_OnFrame(&this->skelAnime, 4.0f) || Animation_OnFrame(&this->skelAnime, 8.0f)) {
Actor_PlaySfx(&this->picto.actor, NA_SE_EV_KAKASHI_SWING);
}
if (Animation_OnFrame(&this->skelAnime, 1.0f) || Animation_OnFrame(&this->skelAnime, 9.0f) ||
Animation_OnFrame(&this->skelAnime, 16.0f)) {
Actor_PlaySfx(&this->picto.actor, NA_SE_IT_KAKASHI_JUMP);
}
if (Animation_OnFrame(&this->skelAnime, 18.0f)) {
Actor_PlaySfx(&this->picto.actor, NA_SE_EV_KAKASHI_ROLL);
}
}
if ((this->animIndex == ENKAKASI_ANIM_SPIN_REACH_OFFER) || (this->animIndex == ENKAKASI_ANIM_TWIRL)) {
if (Animation_OnFrame(&this->skelAnime, 1.0f)) {
Actor_PlaySfx(&this->picto.actor, NA_SE_EV_KAKASH_LONGI_ROLL);
}
}
}
/*
* moves the player's position relative to scarecrow during song teach, also each frame of dance the night away
*/
void EnKakasi_CheckPlayerPosition(EnKakasi* this, PlayState* play) {
Player* player = GET_PLAYER(play);
if (play->sceneId == SCENE_8ITEMSHOP) {
player->actor.world.pos.x = -50.0f;
player->actor.world.pos.z = 155.0f;
} else if (play->sceneId == SCENE_TENMON_DAI) {
player->actor.world.pos.x = 60.0f;
player->actor.world.pos.z = -190.0f;
}
Math_SmoothStepToS(&player->actor.shape.rot.y, (this->picto.actor.yawTowardsPlayer + 0x8000), 5, 1000, 0);
}
/*
* this goes off every frame of dancing the night away, and song teaching
* something to do with cutscene camera?
*/
void func_8096FAAC(EnKakasi* this, PlayState* play) {
if (this->subCamId != SUB_CAM_ID_DONE) {
Math_ApproachF(&this->subCamEye.x, this->subCamEyeNext.x, 0.4f, 4.0f);
Math_ApproachF(&this->subCamEye.y, this->subCamEyeNext.y, 0.4f, 4.0f);
Math_ApproachF(&this->subCamEye.z, this->subCamEyeNext.z, 0.4f, 4.0f);
Math_ApproachF(&this->subCamAt.x, this->subCamAtNext.x, 0.4f, 4.0f);
Math_ApproachF(&this->subCamAt.y, this->subCamAtNext.y, 0.4f, 4.0f);
Math_ApproachF(&this->subCamAt.z, this->subCamAtNext.z, 0.4f, 4.0f);
Math_ApproachF(&this->subCamFov, this->subCamFovNext, 0.3f, 10.0f);
Play_SetCameraAtEye(play, this->subCamId, &this->subCamAt, &this->subCamEye);
Play_SetCameraFov(play, this->subCamId, this->subCamFov);
}
}
/*
* goes off every frame of song teach, but... doing what?
*/
void func_8096FBB8(EnKakasi* this, PlayState* play) {
if ((play->msgCtx.unk12048 == 0) || (play->msgCtx.unk12048 == 1) || (play->msgCtx.unk12048 == 2) ||
(play->msgCtx.unk12048 == 3) || (play->msgCtx.unk12048 == 4)) {
// why not 0 < x < 4? fewer branches
this->unk190++;
}
if ((this->unk190 != 0) && (this->animIndex != ENKAKASI_ANIM_SIDEWAYS_SHAKING)) {
EnKakasi_ChangeAnim(this, ENKAKASI_ANIM_SIDEWAYS_SHAKING);
}
if (this->unk190 > 8) {
this->unk190 = 8;
}
if (this->unk190 != 0) {
Math_ApproachF(&this->skelAnime.playSpeed, 1.0f, 0.1f, 0.2f);
this->picto.actor.shape.rot.y += 0x800;
}
}
void EnKakasi_InitTimeSkipDialogue(EnKakasi* this) {
EnKakasi_ChangeAnim(this, ENKAKASI_ANIM_SLOWROLL);
this->actionFunc = EnKakasi_TimeSkipDialogue;
}
void EnKakasi_TimeSkipDialogue(EnKakasi* this, PlayState* play) {
Player* player = GET_PLAYER(play);
if ((gSaveContext.respawnFlag != -4) && (gSaveContext.respawnFlag != -8)) {
if ((gSaveContext.save.time != CLOCK_TIME(6, 0)) && (gSaveContext.save.time != CLOCK_TIME(18, 0)) &&
!CHECK_EVENTINF(EVENTINF_17)) {
if (this->picto.actor.textId == 0) {
// dialogue after skipped time 'did you feel that? went by in an instant'
this->picto.actor.textId = 0x1653;
CLEAR_WEEKEVENTREG(WEEKEVENTREG_83_01);
this->talkState = TEXT_STATE_5;
player->stateFlags1 |= PLAYER_STATE1_20;
this->picto.actor.flags |= ACTOR_FLAG_10000;
}
if (Actor_ProcessTalkRequest(&this->picto.actor, &play->state)) {
player->stateFlags1 &= ~PLAYER_STATE1_20;
this->unkState196 = 2;
this->picto.actor.flags &= ~ACTOR_FLAG_10000;
this->actionFunc = EnKakasi_RegularDialogue;
} else {
Actor_OfferTalkExchange(&this->picto.actor, play, 9999.9f, 9999.9f, PLAYER_IA_MINUS1);
}
}
}
}
void EnKakasi_SetupIdleStanding(EnKakasi* this) {
this->unkState196 = 0;
this->actionFunc = EnKakasi_IdleStanding;
}
void EnKakasi_IdleStanding(EnKakasi* this, PlayState* play) {
u32 day = gSaveContext.save.day;
s16 x;
s16 y;
// first talk to scarecrow dialogue
this->picto.actor.textId = 0x1644;
if (func_800B8718(&this->picto.actor, &play->state)) {
this->skelAnime.playSpeed = 1.0f;
EnKakasi_SetupSongTeach(this, play);
return;
}
if (Actor_ProcessTalkRequest(&this->picto.actor, &play->state)) {
this->skelAnime.playSpeed = 1.0f;
EnKakasi_SetupDialogue(this);
return;
}
if (play->actorCtx.flags & ACTORCTX_FLAG_PICTO_BOX_ON) {
Actor_GetScreenPos(play, &this->picto.actor, &x, &y);
if ((this->picto.actor.projectedPos.z > -20.0f) && (x > 0) && (x < SCREEN_WIDTH) && (y > 0) &&
(y < SCREEN_HEIGHT) && (this->animIndex != ENKAKASI_ANIM_SIDEWAYS_SHAKING)) {
// faster shaking
EnKakasi_ChangeAnim(this, ENKAKASI_ANIM_SIDEWAYS_SHAKING);
this->skelAnime.playSpeed = 2.0f;
}
} else if (Player_GetMask(play) == PLAYER_MASK_KAMARO) {
if (this->animIndex != ENKAKASI_ANIM_SIDEWAYS_SHAKING) {
EnKakasi_ChangeAnim(this, ENKAKASI_ANIM_SIDEWAYS_SHAKING);
this->skelAnime.playSpeed = 2.0f;
}
} else if ((day == 3) && gSaveContext.save.isNight) {
this->skelAnime.playSpeed = 1.0f;
if (this->animIndex != ENKAKASI_ANIM_SIDEWAYS_SHAKING) {
EnKakasi_ChangeAnim(this, 1);
}
} else if (this->animIndex != ENKAKASI_ANIM_IDLE) {
EnKakasi_ChangeAnim(this, ENKAKASI_ANIM_IDLE);
}
if (this->picto.actor.xzDistToPlayer < 120.0f) {
Actor_OfferTalk(&this->picto.actor, play, 100.0f);
func_800B874C(&this->picto.actor, play, 100.0f, 80.0f);
}
}
void EnKakasi_SetupDialogue(EnKakasi* this) {
// bug? starts one animation then changes it a few lines down?
if (this->animIndex != ENKAKASI_ANIM_SIDEWAYS_SHAKING) {
EnKakasi_ChangeAnim(this, ENKAKASI_ANIM_SIDEWAYS_SHAKING);
}
this->talkState = TEXT_STATE_5;
this->unkState196 = 1;
EnKakasi_ChangeAnim(this, ENKAKASI_ANIM_SPIN_REACH_OFFER);
this->actionFunc = EnKakasi_RegularDialogue;
}
void EnKakasi_RegularDialogue(EnKakasi* this, PlayState* play) {
u32 day = gSaveContext.save.day;
f32 curFrame = this->skelAnime.curFrame;
Math_SmoothStepToS(&this->picto.actor.shape.rot.y, this->picto.actor.yawTowardsPlayer, 5, 2000, 0);
// if first dialogue
if ((this->picto.actor.textId != 0x1644) && (curFrame >= this->animEndFrame) &&
(this->animIndex == ENKAKASI_ANIM_SLOWROLL)) {
EnKakasi_ChangeAnim(this, ENKAKASI_ANIM_SPIN_REACH_OFFER);
this->unkCounter1A4 = 0;
}
// if dialogue: oh sorry come back again
if ((this->picto.actor.textId == 0x1651) || (this->picto.actor.textId == 0x1659)) {
if ((curFrame >= this->animEndFrame) && (this->animIndex != ENKAKASI_ANIM_SPIN_REACH_OFFER)) {
if (++this->unkCounter1A4 >= 2) {
this->unkCounter1A4 = 0;
EnKakasi_ChangeAnim(this, ENKAKASI_ANIM_SPIN_REACH_OFFER);
}
}
}
if ((this->unkState1A8 == 2) && (this->unkState196 == 2)) {
func_800B7298(play, &this->picto.actor, PLAYER_CSMODE_73);
this->unkState1A8 = 0;
}
if ((this->talkState == Message_GetState(&play->msgCtx)) && Message_ShouldAdvance(play)) {
Message_CloseTextbox(play);
if (this->talkState == TEXT_STATE_5) {
// bad song input
if ((this->unkState196 == 2) && (this->picto.actor.textId == 0x1647)) {
func_800B7298(play, &this->picto.actor, PLAYER_CSMODE_END);
}
// after timeskip
if (this->picto.actor.textId == 0x1653) {
u32 saveContextDay2 = gSaveContext.save.day;
if (this->animIndex != ENKAKASI_ANIM_SIDEWAYS_SHAKING) {
EnKakasi_ChangeAnim(this, ENKAKASI_ANIM_SIDEWAYS_SHAKING);
}
if ((saveContextDay2 == 3) && gSaveContext.save.isNight) {
// text: dangerous outside
this->picto.actor.textId = 0x164F;
} else if (gSaveContext.save.isNight) {
// text: would you like to skip time?
this->picto.actor.textId = 0x164E;
} else {
// text: would you like to skip time? 2
this->picto.actor.textId = 0x1645;
}
Message_ContinueTextbox(play, this->picto.actor.textId);
return;
} else if ((this->picto.actor.textId == 0x165D) || (this->picto.actor.textId == 0x165F) ||
(this->picto.actor.textId == 0x1660) || (this->picto.actor.textId == 0x1652)) {
func_800B7298(play, &this->picto.actor, PLAYER_CSMODE_4);
if (CutsceneManager_GetCurrentCsId() == CS_ID_GLOBAL_TALK) {
CutsceneManager_Stop(CS_ID_GLOBAL_TALK);
CutsceneManager_Queue(this->csIdList[0]);
this->actionFunc = EnKakasi_DancingRemark;
} else {
if (!CutsceneManager_IsNext(this->csIdList[0])) {
CutsceneManager_Queue(this->csIdList[0]);
this->actionFunc = EnKakasi_DancingRemark;
} else {
CutsceneManager_StartWithPlayerCs(this->csIdList[0], &this->picto.actor);
this->subCamId = CutsceneManager_GetCurrentSubCamId(this->picto.actor.csId);
this->actionFunc = EnKakasi_DancingRemark;
}
}
return;
} else if ((this->picto.actor.textId == 0x1645) || (this->picto.actor.textId == 0x164E)) {
this->picto.actor.textId = 0x1650; // "Shall we dance? No Yes"
if (this->animIndex != ENKAKASI_ANIM_SIDEWAYS_SHAKING) {
EnKakasi_ChangeAnim(this, ENKAKASI_ANIM_SIDEWAYS_SHAKING);
}
this->talkState = TEXT_STATE_CHOICE;
} else if (this->picto.actor.textId == 0x1644) {
if (this->animIndex != ENKAKASI_ANIM_SIDEWAYS_SHAKING) {
EnKakasi_ChangeAnim(this, ENKAKASI_ANIM_SIDEWAYS_SHAKING);
}
if (gSaveContext.save.isNight) {
this->picto.actor.textId = 0x164E;
} else {
this->picto.actor.textId = 0x1645;
}
} else if (this->picto.actor.textId == 0x164F) {
if (this->animIndex != ENKAKASI_ANIM_SIDEWAYS_SHAKING) {
EnKakasi_ChangeAnim(this, ENKAKASI_ANIM_SIDEWAYS_SHAKING);
}
this->picto.actor.textId = 0x165A;
} else if (this->picto.actor.textId == 0x1651) {
if (this->animIndex != ENKAKASI_ANIM_SIDEWAYS_SHAKING) {
EnKakasi_ChangeAnim(this, ENKAKASI_ANIM_SIDEWAYS_SHAKING);
}
this->picto.actor.textId = 0x1654;
} else if (this->picto.actor.textId == 0x1654) {
this->picto.actor.textId = 0x1655;
} else if (this->picto.actor.textId == 0x1655) {
this->picto.actor.textId = 0x1656;
this->talkState = TEXT_STATE_CHOICE;
} else if (this->picto.actor.textId == 0x1658) {
this->picto.actor.textId = 0x1659;
} else if (this->picto.actor.textId == 0x165A) {
this->picto.actor.textId = 0x165B;
} else if (this->picto.actor.textId == 0x165B) {
this->picto.actor.textId = 0x165C;
this->talkState = TEXT_STATE_CHOICE;
} else if (this->picto.actor.textId == 0x165E) {
this->picto.actor.textId = 0x165F;
} else {
EnKakasi_SetupIdleStanding(this);
return;
}
} else {
this->talkState = TEXT_STATE_5;
if (play->msgCtx.choiceIndex == 1) {
Audio_PlaySfx_MessageDecide();
if (this->picto.actor.textId == 0x1656) {
this->picto.actor.textId = 0x1658;
} else if (this->picto.actor.textId == 0x165C) {
this->picto.actor.textId = 0x165E;
} else if ((day == 3) && gSaveContext.save.isNight) {
this->picto.actor.textId = 0x164F;
} else {
this->picto.actor.textId = 0x1652;
}
EnKakasi_ChangeAnim(this, ENKAKASI_ANIM_HOPPING_REGULAR);
} else {
Audio_PlaySfx_MessageCancel();
if (this->picto.actor.textId == 0x1656) { // would you like to learn a song? yes/no
this->picto.actor.textId = 0x1657;
} else if (this->picto.actor.textId == 0x165C) { // would you like to learn a song? yes/no
this->picto.actor.textId = 0x165D;
} else {
this->picto.actor.textId = 0x1651;
}
this->unkCounter1A4 = 0;
if (this->animIndex != ENKAKASI_ANIM_ARMS_CROSSED_ROCKING) {
EnKakasi_ChangeAnim(this, ENKAKASI_ANIM_ARMS_CROSSED_ROCKING);
}
}
}
Message_ContinueTextbox(play, this->picto.actor.textId);
}
}
void EnKakasi_SetupSongTeach(EnKakasi* this, PlayState* play) {
this->picto.actor.textId = 0x1646;
Message_StartTextbox(play, this->picto.actor.textId, &this->picto.actor);
this->subCamId = SUB_CAM_ID_DONE;
this->subCamFov = 0.0f;
this->subCamFovNext = 60.0f;
EnKakasi_ChangeAnim(this, ENKAKASI_ANIM_TWIRL);
this->unkState196 = 2;
this->actionFunc = EnKakasi_OcarinaRemark;
}
/*
* you took out ocarina hes talking about how he wants to hear you play him a song
* before actually teaching
*/
void EnKakasi_OcarinaRemark(EnKakasi* this, PlayState* play) {
if ((Message_GetState(&play->msgCtx) == TEXT_STATE_5) && Message_ShouldAdvance(play)) {
func_80152434(play, 0x35);
this->unkState1A8 = 0;
if (CutsceneManager_GetCurrentCsId() == CS_ID_GLOBAL_TALK) {
CutsceneManager_Stop(CS_ID_GLOBAL_TALK);
CutsceneManager_Queue(this->csIdList[0]);
this->actionFunc = EnKakasi_TeachingSong;
} else if (!CutsceneManager_IsNext(this->csIdList[0])) {
CutsceneManager_Queue(this->csIdList[0]);
this->actionFunc = EnKakasi_TeachingSong;
} else {
this->unkState1A8 = 1;
CutsceneManager_StartWithPlayerCs(this->csIdList[0], &this->picto.actor);
this->subCamId = CutsceneManager_GetCurrentSubCamId(this->picto.actor.csId);
Math_Vec3f_Copy(&this->unk22C, &this->picto.actor.home.pos);
this->actionFunc = EnKakasi_TeachingSong;
}
}
}
void EnKakasi_TeachingSong(EnKakasi* this, PlayState* play) {
Vec3f tempVec;
EnKakasi_CheckPlayerPosition(this, play);
Math_SmoothStepToS(&this->picto.actor.shape.rot.y, this->picto.actor.home.rot.y, 1, 3000, 0);
if (this->unkState1A8 == 0) {
if (CutsceneManager_GetCurrentCsId() == CS_ID_GLOBAL_TALK) {
CutsceneManager_Stop(CS_ID_GLOBAL_TALK);
CutsceneManager_Queue(this->csIdList[0]);
return;
}
if (!CutsceneManager_IsNext(this->csIdList[0])) {
CutsceneManager_Queue(this->csIdList[0]);
return;
}
CutsceneManager_StartWithPlayerCs(this->csIdList[0], &this->picto.actor);
this->subCamId = CutsceneManager_GetCurrentSubCamId(this->picto.actor.csId);
Math_Vec3f_Copy(&this->unk22C, &this->picto.actor.home.pos);
this->unkState1A8 = 1;
this->unkState1A8 = 1;
}
if (this->unkState1A8 == 1) {
this->unk22C.y = this->picto.actor.home.pos.y + 50.0f;
this->subCamEyeNext.x = D_80971DCC[this->unk190].x;
this->subCamEyeNext.y = D_80971DCC[this->unk190].y;
this->subCamEyeNext.z = D_80971DCC[this->unk190].z;
Math_Vec3f_Copy(&tempVec, &this->subCamEyeNext);
OLib_Vec3fAdd(&this->picto.actor.home, &tempVec, &this->subCamEyeNext, OLIB_ADD_OFFSET);
Math_Vec3f_Copy(&this->subCamAtNext, &this->unk22C);
Math_Vec3f_Copy(&this->subCamEye, &this->subCamEyeNext);
Math_Vec3f_Copy(&this->subCamAt, &this->subCamAtNext);
func_8096FAAC(this, play);
func_8096FBB8(this, play);
if (play->msgCtx.ocarinaMode == 4) { // song failed
this->unk190 = 0;
this->unkCounter1A4 = 0;
CutsceneManager_Stop(this->csIdList[0]);
Actor_PlaySfx(&this->picto.actor, NA_SE_EN_YASE_DEAD);
this->unkState196 = 2;
this->subCamId = SUB_CAM_ID_DONE;
this->picto.actor.textId = 0x1647;
this->unkState1A8 = 2;
this->talkState = TEXT_STATE_5;
EnKakasi_ChangeAnim(this, ENKAKASI_ANIM_ARMS_CROSSED_ROCKING);
this->actionFunc = EnKakasi_RegularDialogue;
} else if (play->msgCtx.ocarinaMode == 3) { // song success
this->postTeachTimer = 30;
this->skelAnime.playSpeed = 2.0f;
EnKakasi_ChangeAnim(this, ENKAKASI_ANIM_HOPPING_REGULAR);
this->actionFunc = EnKakasi_PostSongLearnTwirl;
}
}
}
void EnKakasi_PostSongLearnTwirl(EnKakasi* this, PlayState* play) {
f32 curFrame = this->skelAnime.curFrame;
if ((this->postTeachTimer == 0) && (this->animIndex != ENKAKASI_ANIM_TWIRL)) {
EnKakasi_ChangeAnim(this, ENKAKASI_ANIM_TWIRL);
this->skelAnime.playSpeed = 2.0f;
}
if ((this->postTeachTimer == 0) && (this->animIndex == ENKAKASI_ANIM_TWIRL) && (curFrame >= this->animEndFrame)) {
EnKakasi_SetupPostSongLearnDialogue(this, play);
}
}
void EnKakasi_SetupPostSongLearnDialogue(EnKakasi* this, PlayState* play) {
CutsceneManager_Stop(this->csIdList[0]);
play->msgCtx.ocarinaMode = 4;
this->unk190 = 0;
this->unkCounter1A4 = 0;
EnKakasi_ChangeAnim(this, ENKAKASI_ANIM_HOPPING_REGULAR);
this->subCamId = SUB_CAM_ID_DONE;
this->talkState = TEXT_STATE_5;
this->unkState1A8 = 1;
this->actionFunc = EnKakasi_PostSongLearnDialogue;
this->subCamFov = 0.0f;
this->subCamFovNext = 60.0f;
}
void EnKakasi_PostSongLearnDialogue(EnKakasi* this, PlayState* play) {
Player* player = GET_PLAYER(play);
f32 curFrame = this->skelAnime.curFrame;
Vec3f vec3fCopy;
Math_SmoothStepToS(&this->picto.actor.shape.rot.y, this->picto.actor.home.rot.y, 1, 3000, 0);
Math_SmoothStepToS(&player->actor.shape.rot.y, this->picto.actor.yawTowardsPlayer + 0x8000, 5, 1000, 0);
if (this->unk190 == 0) {
Message_CloseTextbox(play);
func_800B7298(play, &this->picto.actor, PLAYER_CSMODE_86);
this->picto.actor.textId = 0x1648;
Message_StartTextbox(play, (this->picto.actor.textId), &this->picto.actor);
this->unkState1A8 = 0;
this->unk190 = 1;
}
if ((this->picto.actor.textId == 0x1648) && (this->animIndex == ENKAKASI_ANIM_HOPPING_REGULAR) &&
(curFrame >= this->animEndFrame)) {
this->unkCounter1A4++;
if (this->unkCounter1A4 >= 2) {
EnKakasi_ChangeAnim(this, ENKAKASI_ANIM_ARMS_CROSSED_ROCKING);
}
}
if ((this->picto.actor.textId == 0x164B) && (this->animIndex == ENKAKASI_ANIM_ARMS_CROSSED_ROCKING) &&
(curFrame >= this->animEndFrame)) {
this->unkCounter1A4++;
if (this->unkCounter1A4 >= 2) {
EnKakasi_ChangeAnim(this, ENKAKASI_ANIM_SPIN_REACH_OFFER);
}
}
if (this->unkState1A8 == 0) {
if (CutsceneManager_GetCurrentCsId() == CS_ID_GLOBAL_TALK) {
CutsceneManager_Stop(CS_ID_GLOBAL_TALK);
CutsceneManager_Queue(this->csIdList[0]);
return;
}
if (!CutsceneManager_IsNext(this->csIdList[0])) {
CutsceneManager_Queue(this->csIdList[0]);
return;
}
Math_Vec3f_Copy(&this->unk22C, &this->picto.actor.home.pos);
CutsceneManager_StartWithPlayerCs(this->csIdList[0], &this->picto.actor);
this->subCamId = CutsceneManager_GetCurrentSubCamId(this->picto.actor.csId);
func_800B7298(play, &this->picto.actor, PLAYER_CSMODE_86);
this->unkState1A8 = 1;
}
if (this->subCamId != SUB_CAM_ID_DONE) {
this->unk22C.y = this->picto.actor.home.pos.y + 50.0f;
EnKakasi_CheckPlayerPosition(this, play);
this->subCamEyeNext.x = D_80971FA0[this->unk190].x;
this->subCamEyeNext.y = D_80971FA0[this->unk190].y;
this->subCamEyeNext.z = D_80971FA0[this->unk190].z;
Math_Vec3f_Copy(&vec3fCopy, &this->subCamEyeNext);
OLib_Vec3fAdd(&this->picto.actor.home, &vec3fCopy, &this->subCamEyeNext, OLIB_ADD_OFFSET);
this->subCamAtNext.x = D_80971FE8[this->unk190].x + this->unk22C.x;
this->subCamAtNext.y = D_80971FE8[this->unk190].y + this->unk22C.y;
this->subCamAtNext.z = D_80971FE8[this->unk190].z + this->unk22C.z;
Math_Vec3f_Copy(&this->subCamEye, &this->subCamEyeNext);
Math_Vec3f_Copy(&this->subCamAt, &this->subCamAtNext);
}
func_8096FAAC(this, play);
if ((this->unkState1A8 != 0) && (Message_GetState(&play->msgCtx) == this->talkState) &&
Message_ShouldAdvance(play)) {
Message_CloseTextbox(play);
if (this->talkState == TEXT_STATE_5) {
this->unk190++;
if (this->unk190 > 5) {
this->unk190 = 5;
}
if (this->picto.actor.textId == 0x1648) {
func_800B7298(play, &this->picto.actor, PLAYER_CSMODE_WAIT);
this->picto.actor.textId = 0x1649;
if (this->animIndex != ENKAKASI_ANIM_ARMS_CROSSED_ROCKING) {
EnKakasi_ChangeAnim(this, ENKAKASI_ANIM_ARMS_CROSSED_ROCKING);
}
} else if (this->picto.actor.textId == 0x1649) {
this->picto.actor.textId = 0x1660;
this->talkState = TEXT_STATE_CHOICE;
} else if (this->picto.actor.textId == 0x164A) {
this->picto.actor.textId = 0x164B;
} else if (this->picto.actor.textId == 0x164B) {
this->picto.actor.textId = 0x164C;
EnKakasi_ChangeAnim(this, ENKAKASI_ANIM_TWIRL);
} else {
if ((this->picto.actor.textId == 0x164C) || (this->picto.actor.textId == 0x1661)) {
EnKakasi_SetupDigAway(this);
return;
}
}
} else {
this->talkState = TEXT_STATE_5;
if (play->msgCtx.choiceIndex == 1) {
Audio_PlaySfx_MessageDecide();
this->picto.actor.textId = 0x164A;
} else {
Audio_PlaySfx_MessageCancel();
this->picto.actor.textId = 0x1661;
}
}
Message_ContinueTextbox(play, this->picto.actor.textId);
}
}
/*
* talking before dancing the night away, and cutscene setup
*/
void EnKakasi_DancingRemark(EnKakasi* this, PlayState* play) {
u32 currentDay = gSaveContext.save.day;
this->unkState196 = 3;
if (CutsceneManager_GetCurrentCsId() == CS_ID_GLOBAL_TALK) {
CutsceneManager_Stop(CS_ID_GLOBAL_TALK);
CutsceneManager_Queue(this->csIdList[0]);
} else if (!CutsceneManager_IsNext(this->csIdList[0])) {
CutsceneManager_Queue(this->csIdList[0]);
} else {
CutsceneManager_StartWithPlayerCs(this->csIdList[0], &this->picto.actor);
this->subCamId = CutsceneManager_GetCurrentSubCamId(this->picto.actor.csId);
if ((currentDay == 3) && gSaveContext.save.isNight) {
EnKakasi_SetupDigAway(this);
} else {
Audio_PlaySubBgm(NA_BGM_SARIAS_SONG);
EnKakasi_SetupDanceNightAway(this);
}
}
}
void EnKakasi_SetupDanceNightAway(EnKakasi* this) {
this->unk190 = 0;
this->unkCounter1A4 = 0;
this->subCamFov = 0.0f;
this->subCamFovNext = 60.0f;
EnKakasi_ChangeAnim(this, ENKAKASI_ANIM_TWIRL);
Math_Vec3f_Copy(&this->unk22C, &this->picto.actor.home.pos);
Play_EnableMotionBlur(180);
this->actionFunc = EnKakasi_DancingNightAway;
}
void EnKakasi_DancingNightAway(EnKakasi* this, PlayState* play) {
f32 curFrame = this->skelAnime.curFrame;
Vec3f localVec3f;
Player* player;
EnKakasi_CheckPlayerPosition(this, play);
Math_SmoothStepToS(&this->picto.actor.shape.rot.y, this->picto.actor.home.rot.y, 1, 3000, 0);
this->unk22C.y = this->picto.actor.home.pos.y + 50.0f;
this->subCamEyeNext.x = D_80971E38[this->unk190].x;
this->subCamEyeNext.y = D_80971E38[this->unk190].y;
this->subCamEyeNext.z = D_80971E38[this->unk190].z;
Math_Vec3f_Copy(&localVec3f, &this->subCamEyeNext);
OLib_Vec3fAdd(&this->picto.actor.home, &localVec3f, &this->subCamEyeNext, OLIB_ADD_OFFSET);
this->subCamAtNext.x = D_80971EEC[this->unk190].x + this->unk22C.x;
this->subCamAtNext.y = D_80971EEC[this->unk190].y + this->unk22C.y;
this->subCamAtNext.z = D_80971EEC[this->unk190].z + this->unk22C.z;
if ((this->unk190 != 6) && (this->unk190 != 7)) {
Math_Vec3f_Copy(&this->subCamEye, &this->subCamEyeNext);
Math_Vec3f_Copy(&this->subCamAt, &this->subCamAtNext);
}
if ((this->unk190 >= 7) && (this->unk190 != 0xE)) {
this->picto.actor.shape.rot.y += 0x800;
}
func_8096FAAC(this, play);
// switching through manual cutscene states
switch (this->unk190) {
case 0:
// twirling
this->unk204 = 0x28;
this->unk190++;
break;
case 1:
// end of twirl, start shaking back and forth
if ((this->unk204 == 0) && (curFrame >= this->animEndFrame)) {
this->unk204 = 0x14;
this->unk190++;
EnKakasi_ChangeAnim(this, ENKAKASI_ANIM_SIDEWAYS_SHAKING);
}
break;
case 2:
// camera view on the left
if (this->unk204 == 0) {
this->unk204 = 0x14;
this->unk190++;
}
break;
case 3:
// camera view on the right
if (this->unk204 == 0) {
this->unk204 = 0x14;
this->unk190++;
}
break;
case 4:
// camera view close up front
if (this->unk204 == 0) {
this->unk204 = 0x14;
this->unk190++;
}
break;
case 5:
// camera view zoomed out front
if (this->unk204 == 0) {
this->unk204 = 0xF;
this->unk190++;
}
break;
case 6:
// zoom in and sweep down in from case 5
if (this->unk204 == 0) {
this->unk204 = 0xF;
this->unk190++;
}
break;
case 7:
// zoom in close from case 6
if (this->unk204 == 0) {
this->unk204 = 0xA;
this->unk190++;
}
break;
case 8:
case 9:
case 10:
case 11:
case 12:
case 13:
// multiple quick angle cuts viewing from multiple sides
if (this->unk204 == 0) {
this->unk190++;
this->unk204 = 0xA;
if (this->unk190 == 0xE) {
func_800B7298(play, &this->picto.actor, PLAYER_CSMODE_73);
Play_DisableMotionBlur();
this->unk204 = 0x14;
}
}
break;
case 14:
// goes off once for some camera changes,
// otherwise it's the end when camera is back to normal and Player is confused
Math_SmoothStepToS(&this->picto.actor.shape.rot.y, this->picto.actor.yawTowardsPlayer, 5, 1000, 0);
if (this->unk204 == 0) {
player = GET_PLAYER(play);
Play_SetRespawnData(&play->state, RESPAWN_MODE_DOWN, Entrance_CreateFromSpawn(0), player->unk_3CE,
PLAYER_PARAMS(0xFF, PLAYER_INITMODE_B), &player->unk_3C0, player->unk_3CC);
func_80169EFC(&play->state);
if ((gSaveContext.save.time > CLOCK_TIME(18, 0)) || (gSaveContext.save.time < CLOCK_TIME(6, 0))) {
gSaveContext.save.time = CLOCK_TIME(6, 0);
gSaveContext.respawnFlag = -4;
SET_EVENTINF(EVENTINF_TRIGGER_DAYTELOP);
} else {
gSaveContext.save.time = CLOCK_TIME(18, 0);
gSaveContext.respawnFlag = -8;
}
SET_WEEKEVENTREG(WEEKEVENTREG_83_01);
this->unk190 = 0;
this->actionFunc = EnKakasi_DoNothing;
}
break;
default:
break;
}
}
void EnKakasi_DoNothing(EnKakasi* this, PlayState* play) {
}
void EnKakasi_SetupDigAway(EnKakasi* this) {
if (this->animIndex != ENKAKASI_ANIM_SIDEWAYS_SHAKING) {
EnKakasi_ChangeAnim(this, ENKAKASI_ANIM_SIDEWAYS_SHAKING);
}
this->unk190 = 0;
this->unkCounter1A4 = 0;
this->subCamFovNext = 60.0f;
this->subCamFov = 60.0f;
Math_Vec3f_Copy(&this->unk22C, &this->picto.actor.home.pos);
this->unkState196 = 4;
this->actionFunc = EnKakasi_DiggingAway;
}
void EnKakasi_DiggingAway(EnKakasi* this, PlayState* play) {
Vec3f tempunk238;
Vec3f tempWorldPos;
if (this->subCamId != SUB_CAM_ID_DONE) {
this->unk22C.y = this->picto.actor.home.pos.y + 50.0f;
this->subCamEyeNext.x = D_80972030.x;
this->subCamEyeNext.y = D_80972030.y;
this->subCamEyeNext.z = D_80972030.z;
Math_Vec3f_Copy(&tempunk238, &this->subCamEyeNext);
OLib_Vec3fAdd(&this->picto.actor.home, &tempunk238, &this->subCamEyeNext, OLIB_ADD_OFFSET);
this->subCamAtNext.x = ((f32)D_8097203C.x) + this->unk22C.x; // cast req
this->subCamAtNext.y = ((f32)D_8097203C.y) + this->unk22C.y;
this->subCamAtNext.z = ((f32)D_8097203C.z) + this->unk22C.z;
Math_Vec3f_Copy(&this->subCamEye, &this->subCamEyeNext);
Math_Vec3f_Copy(&this->subCamAt, &this->subCamAtNext);
func_8096FAAC(this, play);
}
if (this->unkCounter1A4 < 15) {
this->unkCounter1A4++;
return;
}
this->picto.actor.shape.rot.y += 0x3000;
Math_SmoothStepToS(&this->unk190, 500, 5, 50, 0);
if ((play->gameplayFrames % 4) == 0) {
Math_Vec3f_Copy(&tempWorldPos, &this->picto.actor.world.pos);
tempWorldPos.y = this->picto.actor.floorHeight;
tempWorldPos.x += Rand_CenteredFloat(2.0f);
tempWorldPos.z += Rand_CenteredFloat(2.0f);
if (play->sceneId == SCENE_8ITEMSHOP) {
EffectSsGSplash_Spawn(play, &tempWorldPos, 0, 0, 0, Rand_CenteredFloat(100.0f) + 200.0f);
SoundSource_PlaySfxAtFixedWorldPos(play, &tempWorldPos, 0x32, NA_SE_EV_BOMB_DROP_WATER);
} else {
Actor_SpawnFloorDustRing(play, &this->picto.actor, &this->picto.actor.world.pos,
this->picto.actor.shape.shadowScale - 20.0f, 5, 4.0f, 200, 10, 1);
Actor_PlaySfx(&this->picto.actor, NA_SE_EN_AKINDONUTS_HIDE);
}
}
Math_ApproachF(&this->picto.actor.shape.yOffset, -6000.0f, 0.5f, 200.0f);
if (fabsf(this->picto.actor.shape.yOffset + 6000.0f) < 10.0f) {
SET_WEEKEVENTREG(WEEKEVENTREG_79_08);
func_800B7298(play, &this->picto.actor, PLAYER_CSMODE_END);
CutsceneManager_Stop(this->csIdList[0]);
this->aboveGroundStatus = ENKAKASI_ABOVE_GROUND_TYPE;
this->songSummonDist = 80.0f;
EnKakasi_SetupIdleUnderground(this);
}
}
void EnKakasi_SetupIdleUnderground(EnKakasi* this) {
this->picto.actor.shape.yOffset = -7000.0;
this->picto.actor.draw = NULL;
this->picto.actor.flags |= ACTOR_FLAG_CANT_LOCK_ON;
this->unkState196 = 5;
this->actionFunc = EnKakasi_IdleUnderground;
}
void EnKakasi_IdleUnderground(EnKakasi* this, PlayState* play) {
if (CHECK_WEEKEVENTREG(WEEKEVENTREG_79_08) && (this->picto.actor.xzDistToPlayer < this->songSummonDist) &&
((BREG(1) != 0) || (play->msgCtx.ocarinaMode == 0xD))) {
this->picto.actor.flags &= ~ACTOR_FLAG_CANT_LOCK_ON;
play->msgCtx.ocarinaMode = 4;
this->actionFunc = EnKakasi_SetupRiseOutOfGround;
}
}
void EnKakasi_SetupRiseOutOfGround(EnKakasi* this, PlayState* play) {
s32 csIdIndex;
csIdIndex = 0;
if (this->aboveGroundStatus == ENKAKASI_ABOVE_GROUND_TYPE) {
csIdIndex = 1;
}
if (CutsceneManager_GetCurrentCsId() == CS_ID_GLOBAL_TALK) {
CutsceneManager_Stop(CS_ID_GLOBAL_TALK);
CutsceneManager_Queue(this->csIdList[csIdIndex]);
} else if (!CutsceneManager_IsNext(this->csIdList[csIdIndex])) {
CutsceneManager_Queue(this->csIdList[csIdIndex]);
} else {
CutsceneManager_StartWithPlayerCs(this->csIdList[csIdIndex], &this->picto.actor);
Actor_PlaySfx(&this->picto.actor, NA_SE_EN_AKINDONUTS_HIDE);
this->picto.actor.draw = EnKakasi_Draw;
this->unkState196 = 6;
this->actionFunc = EnKakasi_RisingOutOfGround;
}
}
void EnKakasi_RisingOutOfGround(EnKakasi* this, PlayState* play) {
this->picto.actor.shape.rot.y += 0x3000;
if (this->animIndex != ENKAKASI_ANIM_SIDEWAYS_SHAKING) {
EnKakasi_ChangeAnim(this, ENKAKASI_ANIM_SIDEWAYS_SHAKING);
}
if (this->picto.actor.shape.yOffset < -10.0f) {
if ((play->gameplayFrames % 8) == 0) {
Actor_SpawnFloorDustRing(play, &this->picto.actor, &this->picto.actor.world.pos,
this->picto.actor.shape.shadowScale - 20.0f, 10, 8.0f, 500, 10, 1);
Actor_PlaySfx(&this->picto.actor, NA_SE_EN_AKINDONUTS_HIDE);
}
Math_ApproachF(&this->picto.actor.shape.yOffset, 0.0f, 0.5f, 200.0f);
} else {
EnKakasi_SetupIdleRisen(this);
}
}
void EnKakasi_SetupIdleRisen(EnKakasi* this) {
// text: great to see you again
this->picto.actor.textId = 0x164D;
this->unkState196 = 7;
this->actionFunc = EnKakasi_IdleRisen;
this->picto.actor.shape.yOffset = 0.0f;
}
void EnKakasi_IdleRisen(EnKakasi* this, PlayState* play) {
Math_SmoothStepToS(&this->picto.actor.shape.rot.y, this->picto.actor.yawTowardsPlayer, 5, 1000, 0);
if (Actor_ProcessTalkRequest(&this->picto.actor, &play->state)) {
this->actionFunc = EnKakasi_RisenDialogue;
} else {
Actor_OfferTalk(&this->picto.actor, play, 70.0f);
}
}
void EnKakasi_RisenDialogue(EnKakasi* this, PlayState* play) {
Math_SmoothStepToS(&this->picto.actor.shape.rot.y, this->picto.actor.yawTowardsPlayer, 5, 1000, 0);
if ((Message_GetState(&play->msgCtx) == TEXT_STATE_5) && Message_ShouldAdvance(play)) {
Message_CloseTextbox(play);
EnKakasi_SetupIdleRisen(this);
}
}
void EnKakasi_Update(Actor* thisx, PlayState* play) {
EnKakasi* this = THIS;
s32 pad;
SkelAnime_Update(&this->skelAnime);
if (this->picto.actor.draw != NULL) {
EnKakasi_CheckAnimationSfx(this);
}
this->picto.actor.world.rot.y = this->picto.actor.shape.rot.y;
DECR(this->postTeachTimer);
DECR(this->unk204);
if (this->unkState196 != 5) {
if ((this->unk1BC.x != 0.0f) || (this->unk1BC.z != 0.0f)) {
Math_Vec3f_Copy(&this->picto.actor.focus.pos, &this->unk1BC);
this->picto.actor.focus.pos.y += 10.0f;
if (this->subCamId == SUB_CAM_ID_DONE) {
Math_Vec3s_Copy(&this->picto.actor.focus.rot, &this->picto.actor.world.rot);
} else {
Math_Vec3s_Copy(&this->picto.actor.focus.rot, &this->picto.actor.home.rot);
}
}
} else {
Actor_SetFocus(&this->picto.actor, this->unkHeight);
}
this->actionFunc(this, play);
Actor_MoveWithGravity(&this->picto.actor);
Actor_UpdateBgCheckInfo(play, &this->picto.actor, 50.0f, 50.0f, 100.0f,
UPDBGCHECKINFO_FLAG_4 | UPDBGCHECKINFO_FLAG_8 | UPDBGCHECKINFO_FLAG_10);
if (this->picto.actor.draw != NULL) {
Collider_UpdateCylinder(&this->picto.actor, &this->collider);
CollisionCheck_SetAC(play, &play->colChkCtx, &this->collider.base);
CollisionCheck_SetOC(play, &play->colChkCtx, &this->collider.base);
}
}
void EnKakasi_PostLimbDraw(PlayState* play, s32 limbIndex, Gfx** dList, Vec3s* rot, Actor* thisx) {
EnKakasi* this = THIS;
if (limbIndex == 4) {
Matrix_MultVec3f(&gZeroVec3f, &this->unk1BC);
}
}
void EnKakasi_Draw(Actor* thisx, PlayState* play) {
EnKakasi* this = THIS;
Gfx_SetupDL25_Opa(play->state.gfxCtx);
SkelAnime_DrawFlexOpa(play, this->skelAnime.skeleton, this->skelAnime.jointTable, this->skelAnime.dListCount, NULL,
EnKakasi_PostLimbDraw, &this->picto.actor);
}
|
1ec35f4e2ba46c76af0d8a235d20f60b470270ce
|
e9911598c43e8526da22b2773a73d9b5966f602a
|
/imap/sync_log.c
|
a2336329229b72d6eeb439991fbe2ebc7adeda74
|
[
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause"
] |
permissive
|
cyrusimap/cyrus-imapd
|
07236dfd887ed92c147938cf1ed2591449d7e8fd
|
315441d067ba85814768f840f20bc3bb7f20ea6b
|
refs/heads/master
| 2023-09-05T09:57:10.683822
| 2023-09-05T06:09:43
| 2023-09-05T06:09:43
| 59,071,965
| 508
| 164
|
NOASSERTION
| 2023-09-13T04:34:31
| 2016-05-18T01:33:49
|
C
|
UTF-8
|
C
| false
| false
| 19,352
|
c
|
sync_log.c
|
/* sync_log.c -- Cyrus synchronization logging functions
*
* Copyright (c) 1994-2008 Carnegie Mellon University. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The name "Carnegie Mellon University" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For permission or any legal
* details, please contact
* Carnegie Mellon University
* Center for Technology Transfer and Enterprise Creation
* 4615 Forbes Avenue
* Suite 302
* Pittsburgh, PA 15213
* (412) 268-7393, fax: (412) 268-7395
* innovation@andrew.cmu.edu
*
* 4. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by Computing Services
* at Carnegie Mellon University (http://www.cmu.edu/computing/)."
*
* CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
* THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY 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.
*
* Original version written by David Carter <dpc22@cam.ac.uk>
* Rewritten and integrated into Cyrus by Ken Murchison <ken@oceana.com>
*/
/* YYY Need better quoting for obscure filenames: use literals? */
#include <config.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sysexits.h>
#include <syslog.h>
#include <errno.h>
#include "assert.h"
#include "command.h"
#include "sync_log.h"
#include "global.h"
#include "cyr_lock.h"
#include "mailbox.h"
#include "retry.h"
#include "util.h"
#include "xmalloc.h"
#include "xstrlcpy.h"
#include "xunlink.h"
/* generated headers are not necessarily in current directory */
#include "imap/imap_err.h"
static int sync_log_suppressed = 0;
static strarray_t *channels = NULL;
static strarray_t *unsuppressable = NULL;
static struct buf *rightnow_log = NULL;
static int sync_log_initialized = 0;
static void done_cb(void *rock __attribute__((unused))) {
sync_log_done();
}
static void init_internal() {
if (!sync_log_initialized) {
sync_log_init();
cyrus_modules_add(done_cb, NULL);
}
}
EXPORTED void sync_log_init(void)
{
const char *conf;
int i;
/* sync_log_init() may be called more than once */
if (channels) strarray_free(channels);
conf = config_getstring(IMAPOPT_SYNC_LOG_CHANNELS);
if (!conf) conf = "\"\"";
channels = strarray_split(conf, " ", 0);
/*
* The sysadmin can specify "" in the value of sync_log_channels to
* mean the default channel name - this will be useful for sysadmins
* who want to start using a sync log channel for squatter but who
* have been using the default sync log channel for sync_client.
*/
i = strarray_find(channels, "\"\"", 0);
if (i >= 0)
strarray_set(channels, i, NULL);
strarray_free(unsuppressable);
unsuppressable = NULL;
conf = config_getstring(IMAPOPT_SYNC_LOG_UNSUPPRESSABLE_CHANNELS);
if (conf) {
unsuppressable = strarray_split(conf, " ", 0);
i = strarray_find(unsuppressable, "\"\"", 0);
if (i >= 0)
strarray_set(unsuppressable, i, NULL);
}
conf = config_getstring(IMAPOPT_SYNC_RIGHTNOW_CHANNEL);
if (conf) {
rightnow_log = buf_new();
}
sync_log_initialized = 1;
}
EXPORTED void sync_log_suppress(void)
{
sync_log_suppressed = 1;
}
EXPORTED void sync_log_done(void)
{
sync_log_reset();
if (rightnow_log) {
buf_destroy(rightnow_log);
rightnow_log = NULL;
}
strarray_free(channels);
channels = NULL;
strarray_free(unsuppressable);
unsuppressable = NULL;
sync_log_initialized = 0;
}
static char *sync_log_fname(const char *channel)
{
static char buf[MAX_MAILBOX_PATH];
if (channel)
snprintf(buf, MAX_MAILBOX_PATH,
"%s/sync/%s/log", config_dir, channel);
else
snprintf(buf, MAX_MAILBOX_PATH,
"%s/sync/log", config_dir);
return buf;
}
static int sync_log_enabled(const char *channel)
{
if (!config_getswitch(IMAPOPT_SYNC_LOG))
return 0; /* entire mechanism is disabled */
if (!sync_log_suppressed)
return 1; /* _suppress() wasn't called */
if (unsuppressable && strarray_find(unsuppressable, channel, 0) >= 0)
return 1; /* channel is unsuppressable */
return 0; /* suppressed */
}
static void sync_log_base(const char *channel, const char *string)
{
int fd;
struct stat sbuffile, sbuffd;
int retries = 0;
const char *fname;
fname = sync_log_fname(channel);
while (retries++ < SYNC_LOG_RETRIES) {
fd = open(fname, O_WRONLY|O_APPEND|O_CREAT, 0640);
if (fd < 0 && errno == ENOENT) {
if (!cyrus_mkdir(fname, 0755)) {
fd = open(fname, O_WRONLY|O_APPEND|O_CREAT, 0640);
}
}
if (fd < 0) {
syslog(LOG_ERR, "sync_log(): Unable to write to log file %s: %s",
fname, strerror(errno));
return;
}
if (lock_blocking(fd, fname) == -1) {
syslog(LOG_ERR, "sync_log(): Failed to lock %s for %s: %m",
fname, string);
xclose(fd);
return;
}
/* Check that the file wasn't renamed after it was opened above */
if ((fstat(fd, &sbuffd) == 0) &&
(stat(fname, &sbuffile) == 0) &&
(sbuffd.st_ino == sbuffile.st_ino))
break;
lock_unlock(fd, fname);
xclose(fd);
}
if (retries >= SYNC_LOG_RETRIES) {
xclose(fd);
syslog(LOG_ERR,
"sync_log(): Failed to lock %s for %s after %d attempts",
fname, string, retries);
return;
}
if (retry_write(fd, string, strlen(string)) < 0)
syslog(LOG_ERR, "write() to %s failed: %s",
fname, strerror(errno));
(void)fsync(fd); /* paranoia */
lock_unlock(fd, fname);
xclose(fd);
}
EXPORTED struct buf *sync_log_rightnow_buf()
{
if (!channels) return NULL;
if (!rightnow_log) return NULL;
if (!buf_len(rightnow_log)) return NULL;
return rightnow_log;
}
EXPORTED void sync_log_reset()
{
if (!channels) return;
if (!rightnow_log) return;
if (!buf_len(rightnow_log)) return;
syslog(LOG_NOTICE, "SYNCNOTICE: rightnow log leaked %s", buf_cstring(rightnow_log));
buf_reset(rightnow_log);
}
static const char *sync_quote_name(const char *name)
{
static char buf[MAX_MAILBOX_BUFFER+3]; /* "x2 plus \0 */
char c;
int src;
int dst = 0;
int need_quote = 0;
/* initial quote */
buf[dst++] = '"';
/* degenerate case - no name is the empty string, quote it */
if (!name || !*name) {
need_quote = 1;
goto end;
}
for (src = 0; name[src]; src++) {
c = name[src];
if ((c == '\r') || (c == '\n'))
fatal("Illegal line break in folder name", EX_IOERR);
/* quoteable characters */
if ((c == '\\') || (c == '\"') || (c == '{') || (c == '}')) {
need_quote = 1;
buf[dst++] = '\\';
}
/* non-atom characters */
else if ((c == ' ') || (c == '\t') || (c == '(') || (c == ')')) {
need_quote = 1;
}
buf[dst++] = c;
if (dst > MAX_MAILBOX_BUFFER)
fatal("word too long", EX_IOERR);
}
end:
if (need_quote) {
buf[dst++] = '\"';
buf[dst] = '\0';
return buf;
}
else {
buf[dst] = '\0';
return buf + 1; /* skip initial quote */
}
}
#define BUFSIZE 4096
static char *va_format(const char *fmt, va_list ap)
{
static char buf[BUFSIZE+1];
size_t len;
int ival;
const char *sval;
const char *p;
for (len = 0, p = fmt; *p && len < BUFSIZE; p++) {
if (*p != '%') {
buf[len++] = *p;
continue;
}
switch (*++p) {
case 'd':
ival = va_arg(ap, int);
len += snprintf(buf+len, BUFSIZE-len, "%d", ival);
break;
case 's':
sval = va_arg(ap, const char *);
sval = sync_quote_name(sval);
strlcpy(buf+len, sval, BUFSIZE-len);
len += strlen(sval);
break;
default:
buf[len++] = *p;
break;
}
}
if (buf[len-1] != '\n') buf[len++] = '\n';
buf[len] = '\0';
return buf;
}
EXPORTED void sync_log(const char *fmt, ...)
{
va_list ap;
const char *val;
int i;
init_internal();
if (!channels) return;
va_start(ap, fmt);
val = va_format(fmt, ap);
va_end(ap);
if (rightnow_log)
buf_appendcstr(rightnow_log, val);
for (i = 0 ; i < channels->count ; i++) {
const char *channel = channels->data[i];
if (sync_log_enabled(channel))
sync_log_base(channel, val);
}
}
EXPORTED void sync_log_channel(const char *channel, const char *fmt, ...)
{
va_list ap;
const char *val;
init_internal();
va_start(ap, fmt);
val = va_format(fmt, ap);
va_end(ap);
sync_log_base(channel, val);
}
/*
* Read-side sync log code
*/
struct sync_log_reader
{
/*
* This object works in four modes:
*
* - initialised with a sync log channel
* - standard mode used by sync_client
* - slr->log_file != NULL
* - slr->work_file is the name of a rename()d
* file that needs to be unlink()ed.
* - slr->content_buf is empty
*
* - initialised with a saved file name
* - used by the sync_client -f option
* - slr->log_file = NULL
* - slr->work_file is the file given us by the user
* which it's important that we do not unlink()
* - slr->content_buf is empty
*
* - initialised with a file descriptor
* - slr->log_file = NULL
* - slr->work_file = NULL
* - slr->fd is a file descriptor, probably stdin,
* and possibly a pipe
* - slr->content_buf is empty
* - we cannot unlink() anything even if we wanted to.
*
* - initialised with the content of a file
* - slr->log_file = NULL
* - slr->work_file = NULL
* - slr->content_buf has a length
* - we cannot unlink() anything even if we wanted to.
*/
char *log_file;
char *work_file;
int fd;
int fd_is_ours;
struct protstream *input;
struct buf type;
struct buf arg1;
struct buf arg2;
struct buf contentbuf;
};
static sync_log_reader_t *sync_log_reader_alloc(void)
{
sync_log_reader_t *slr = xzmalloc(sizeof(sync_log_reader_t));
slr->fd = -1;
return slr;
}
/*
* Create a sync log reader object which will read from the given sync log
* channel 'channel'. The channel may be NULL for the default channel.
* Returns a new object which must be freed with sync_log_reader_free().
* Does not return NULL.
*/
EXPORTED sync_log_reader_t *sync_log_reader_create_with_channel(const char *channel)
{
sync_log_reader_t *slr = sync_log_reader_alloc();
struct buf buf = BUF_INITIALIZER;
slr->log_file = xstrdup(sync_log_fname(channel));
/* Create a work log filename. We will process this
* first if it exists */
buf_printf(&buf, "%s-run", slr->log_file);
slr->work_file = buf_release(&buf);
return slr;
}
/*
* Create a sync log reader object which will read from the given file
* 'filename'. Returns a new object which must be freed with
* sync_log_reader_free(). Does not return NULL.
*/
EXPORTED sync_log_reader_t *sync_log_reader_create_with_filename(const char *filename)
{
sync_log_reader_t *slr = sync_log_reader_alloc();
slr->work_file = xstrdup(filename);
/* slr->log_file remain NULL, which matters later */
return slr;
}
EXPORTED sync_log_reader_t *sync_log_reader_create_with_content(const char *content)
{
sync_log_reader_t *slr = sync_log_reader_alloc();
buf_init_ro_cstr(&slr->contentbuf, content);
return slr;
}
/*
* Create a sync log reader object which will read from the given file
* descriptor 'fd'. The file descriptor must be open for reading and
* is not closed. Returns a new object which must be freed with
* sync_log_reader_free(). Does not return NULL.
*/
EXPORTED sync_log_reader_t *sync_log_reader_create_with_fd(int fd)
{
sync_log_reader_t *slr = sync_log_reader_alloc();
slr->fd = fd;
slr->fd_is_ours = 0;
/* slr->log_file remain NULL, which matters later */
return slr;
}
/*
* Free a sync log reader object.
*/
EXPORTED void sync_log_reader_free(sync_log_reader_t *slr)
{
if (!slr) return;
if (slr->input) prot_free(slr->input);
if (slr->fd_is_ours && slr->fd >= 0) close(slr->fd);
free(slr->log_file);
free(slr->work_file);
buf_free(&slr->type);
buf_free(&slr->arg1);
buf_free(&slr->arg2);
buf_free(&slr->contentbuf);
free(slr);
}
/*
* Begin reading a sync log file. If the reader is reading from a
* channel, rename the current log file so it will not be appended to by
* the write side code, and open the file. Otherwise, just open the file
* (note this is still necessary even when the reader is reading from a
* file descriptor).
*
* When sync_log_reader_begin() returns success, you should loop calling
* sync_log_reader_getitem() and handling the items, until it returns
* EOF, and then call sync_log_reader_end().
*
* Returns zero on success, IMAP_AGAIN if reading from a channel and
* there is no current log file, or an IMAP error code on failure.
*/
EXPORTED int sync_log_reader_begin(sync_log_reader_t *slr)
{
struct stat sbuf;
int r;
if (slr->input) {
r = sync_log_reader_end(slr);
if (r) return r;
}
if (buf_len(&slr->contentbuf)) {
slr->input = prot_readmap(buf_base(&slr->contentbuf), buf_len(&slr->contentbuf));
return 0;
}
if (stat(slr->work_file, &sbuf) == 0) {
/* Existing work log file - process this first */
syslog(LOG_NOTICE,
"Reprocessing sync log file %s", slr->work_file);
}
else if (!slr->log_file) {
syslog(LOG_ERR, "No sync log filename");
return IMAP_IOERROR;
}
else {
/* Check for sync_log file */
if (stat(slr->log_file, &sbuf) < 0) {
if (errno == ENOENT)
return IMAP_AGAIN; /* no problem, try again later */
syslog(LOG_ERR, "Failed to stat %s: %m",
slr->log_file);
return IMAP_IOERROR;
}
/* Move sync_log to our work file */
if (rename(slr->log_file, slr->work_file) < 0) {
syslog(LOG_ERR, "Rename %s -> %s failed: %m",
slr->log_file, slr->work_file);
return IMAP_IOERROR;
}
}
if (slr->fd < 0) {
int fd = open(slr->work_file, O_RDWR, 0);
if (fd < 0) {
syslog(LOG_ERR, "Failed to open %s: %m", slr->work_file);
return IMAP_IOERROR;
}
if (lock_blocking(fd, slr->work_file) < 0) {
syslog(LOG_ERR, "Failed to lock %s: %m", slr->work_file);
close(fd);
return IMAP_IOERROR;
}
slr->fd = fd;
slr->fd_is_ours = 1;
/* we can unlock immediately, since we have serialised
* any process which held the lock over the rename. All
* future attempts to lock this inode will stat and notice
* the rename, so they won't write any more */
lock_unlock(slr->fd, slr->work_file);
}
slr->input = prot_new(slr->fd, /*write*/0);
return 0;
}
EXPORTED const char *sync_log_reader_get_file_name(const sync_log_reader_t *slr)
{
return slr->work_file;
}
/*
* Finish reading a sync log file. Closes the file (and, if the reader
* is reading from a channel, unlinks the work file and prepares for the
* next file). Returns 0 on success or an IMAP error code on failure.
*/
EXPORTED int sync_log_reader_end(sync_log_reader_t *slr)
{
if (!slr->input)
return 0;
if (slr->input) {
prot_free(slr->input);
slr->input = NULL;
}
if (slr->fd_is_ours && slr->fd >= 0) {
lock_unlock(slr->fd, slr->work_file);
close(slr->fd);
slr->fd = -1;
}
if (slr->log_file) {
/* We were initialised with a sync log channel, whose
* log file we rename()d to the work file. Now that
* we've done with the work file we can unlink it.
* Further checks at this point are just paranoia. */
if (slr->work_file && xunlink(slr->work_file) < 0) {
syslog(LOG_ERR, "Unlink %s failed: %m", slr->work_file);
return IMAP_IOERROR;
}
}
return 0;
}
/*
* Read a single log item from a sync log file. The item will be
* returned as three constant strings. The first string is the type of
* the item (e.g. "MAILBOX") and is always capitalised. The second and
* third strings are arguments.
*
* Returns 0 on success, EOF when the end of the file is reached, or an
* IMAP error code on failure.
*/
EXPORTED int sync_log_reader_getitem(sync_log_reader_t *slr,
const char *args[3])
{
int c;
const char *arg1s = NULL;
const char *arg2s = NULL;
if (!slr->input)
return EOF;
for (;;) {
if ((c = getword(slr->input, &slr->type)) == EOF)
return EOF;
/* Ignore blank lines */
if (c == '\r') c = prot_getc(slr->input);
if (c == '\n')
continue;
if (c != ' ') {
syslog(LOG_ERR, "Invalid input");
eatline(slr->input, c);
continue;
}
if ((c = getastring(slr->input, 0, &slr->arg1)) == EOF) return EOF;
arg1s = slr->arg1.s;
arg2s = NULL;
if (c == ' ') {
if ((c = getastring(slr->input, 0, &slr->arg2)) == EOF) return EOF;
arg2s = slr->arg2.s;
}
if (c == '\r') c = prot_getc(slr->input);
if (c != '\n') {
syslog(LOG_ERR, "Garbage at end of input line");
eatline(slr->input, c);
continue;
}
break;
}
ucase(slr->type.s);
args[0] = slr->type.s;
args[1] = arg1s;
args[2] = arg2s;
return 0;
}
|
3899d217557622f4491c6d34e07ba94394d13190
|
f367e4b66a1ee42e85830b31df88f63723c36a47
|
/lib/cmetrics/tests/atomic_operations.c
|
6734a59cfceb67473b1f908c8bf2e7d1c54caf78
|
[
"Apache-2.0"
] |
permissive
|
fluent/fluent-bit
|
06873e441162b92941024e9a7e9e8fc934150bf7
|
1a41f49dc2f3ae31a780caa9ffd6137b1d703065
|
refs/heads/master
| 2023-09-05T13:44:55.347372
| 2023-09-05T10:14:33
| 2023-09-05T10:14:33
| 29,933,948
| 4,907
| 1,565
|
Apache-2.0
| 2023-09-14T10:17:02
| 2015-01-27T20:41:52
|
C
|
UTF-8
|
C
| false
| false
| 2,989
|
c
|
atomic_operations.c
|
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* CMetrics
* ========
* Copyright 2021-2022 The CMetrics Authors
*
* 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 <cmetrics/cmetrics.h>
#include <cmetrics/cmt_atomic.h>
#if defined (_WIN32) || defined (_WIN64)
#include <windows.h>
#else
#include <pthread.h>
#endif
#include "cmt_tests.h"
#define THREAD_COUNT 100
#define CYCLE_COUNT 10000
#define EXPECTED_VALUE (THREAD_COUNT * CYCLE_COUNT)
uint64_t global_counter;
static inline void add_through_compare_exchange(uint64_t val)
{
uint64_t old;
uint64_t new;
int result;
do {
old = global_counter;
new = old + val;
result = cmt_atomic_compare_exchange(&global_counter, old, new);
}
while(0 == result);
}
void *worker_thread_add_through_compare_exchange(void *ptr)
{
int local_counter;
for (local_counter = 0 ; local_counter < CYCLE_COUNT ; local_counter++) {
add_through_compare_exchange(1);
}
return NULL;
}
#if defined (_WIN32) || defined (_WIN64)
void test_atomic_operations()
{
HANDLE threads[THREAD_COUNT];
DWORD thread_ids[THREAD_COUNT];
int thread_index;
DWORD result;
cmt_initialize();
global_counter = 0;
for(thread_index = 0 ; thread_index < THREAD_COUNT ; thread_index++)
{
threads[thread_index] = CreateThread(NULL, 0,
(LPTHREAD_START_ROUTINE) worker_thread_add_through_compare_exchange,
NULL, 0, &thread_ids[thread_index]);
}
for(thread_index = 0 ; thread_index < THREAD_COUNT ; thread_index++)
{
result = WaitForSingleObject(threads[thread_index], INFINITE);
}
TEST_CHECK(global_counter == EXPECTED_VALUE);
}
#else
void test_atomic_operations()
{
pthread_t threads[THREAD_COUNT];
int thread_index;
cmt_initialize();
global_counter = 0;
for(thread_index = 0 ; thread_index < THREAD_COUNT ; thread_index++)
{
pthread_create(&threads[thread_index], NULL,
worker_thread_add_through_compare_exchange, NULL);
}
for(thread_index = 0 ; thread_index < THREAD_COUNT ; thread_index++)
{
pthread_join(threads[thread_index], NULL);
}
TEST_CHECK(global_counter == EXPECTED_VALUE);
}
#endif
TEST_LIST = {
{"atomic_operations", test_atomic_operations},
{ 0 }
};
|
b5dfcf3a965f189350c0f11e5b6abe5ae88d72a8
|
7df190df28da7e4ff166e55dc8ce780f11236a9f
|
/src/include.v24/include/bcmenet47xx.h
|
3ca978f6fec6fe72ac10576d46695cae4853d55f
|
[] |
no_license
|
mirror/dd-wrt
|
25416946e6132aa54b35809de61834a1825a9a36
|
8f2934a5a2adfbb59b471375aa3a38de5d036531
|
refs/heads/master
| 2023-08-31T14:54:47.496685
| 2023-08-30T17:40:54
| 2023-08-30T17:40:54
| 7,470,282
| 520
| 281
| null | 2023-05-29T20:56:24
| 2013-01-06T17:21:29
| null |
UTF-8
|
C
| false
| false
| 7,638
|
h
|
bcmenet47xx.h
|
/*
* Hardware-specific definitions for
* Broadcom BCM47XX 10/100 Mbps Ethernet cores.
*
* Copyright 2005, Broadcom Corporation
* All Rights Reserved.
*
* This is UNPUBLISHED PROPRIETARY SOURCE CODE of Broadcom Corporation;
* the contents of this file may not be disclosed to third parties, copied
* or duplicated in any form, in whole or in part, without the prior
* written permission of Broadcom Corporation.
* $Id$
*/
#ifndef _bcmenet_47xx_h_
#define _bcmenet_47xx_h_
#include <bcmenetmib.h>
#include <bcmenetrxh.h>
#include <bcmenetphy.h>
#define BCMENET_NFILTERS 64 /* # ethernet address filter entries */
#define BCMENET_MCHASHBASE 0x200 /* multicast hash filter base address */
#define BCMENET_MCHASHSIZE 256 /* multicast hash filter size in bytes */
#define BCMENET_MAX_DMA 4096 /* chip has 12 bits of DMA addressing */
/* power management event wakeup pattern constants */
#define BCMENET_NPMP 4 /* chip supports 4 wakeup patterns */
#define BCMENET_PMPBASE 0x400 /* wakeup pattern base address */
#define BCMENET_PMPSIZE 0x80 /* 128bytes each pattern */
#define BCMENET_PMMBASE 0x600 /* wakeup mask base address */
#define BCMENET_PMMSIZE 0x10 /* 128bits each mask */
/* cpp contortions to concatenate w/arg prescan */
#ifndef PAD
#define _PADLINE(line) pad ## line
#define _XSTR(line) _PADLINE(line)
#define PAD _XSTR(__LINE__)
#endif /* PAD */
/*
* Host Interface Registers
*/
typedef volatile struct _bcmenettregs {
/* Device and Power Control */
uint32 devcontrol;
uint32 PAD[2];
uint32 biststatus;
uint32 wakeuplength;
uint32 PAD[3];
/* Interrupt Control */
uint32 intstatus;
uint32 intmask;
uint32 gptimer;
uint32 PAD[23];
/* Ethernet MAC Address Filtering Control */
uint32 PAD[2];
uint32 enetftaddr;
uint32 enetftdata;
uint32 PAD[2];
/* Ethernet MAC Control */
uint32 emactxmaxburstlen;
uint32 emacrxmaxburstlen;
uint32 emaccontrol;
uint32 emacflowcontrol;
uint32 PAD[20];
/* DMA Lazy Interrupt Control */
uint32 intrecvlazy;
uint32 PAD[63];
/* DMA engine */
dma32regp_t dmaregs;
dma32diag_t dmafifo;
uint32 PAD[116];
/* EMAC Registers */
uint32 rxconfig;
uint32 rxmaxlength;
uint32 txmaxlength;
uint32 PAD;
uint32 mdiocontrol;
uint32 mdiodata;
uint32 emacintmask;
uint32 emacintstatus;
uint32 camdatalo;
uint32 camdatahi;
uint32 camcontrol;
uint32 enetcontrol;
uint32 txcontrol;
uint32 txwatermark;
uint32 mibcontrol;
uint32 PAD[49];
/* EMAC MIB counters */
bcmenetmib_t mib;
uint32 PAD[585];
/* Sonics SiliconBackplane config registers */
sbconfig_t sbconfig;
} bcmenetregs_t;
/* device control */
#define DC_PM ((uint32)1 << 7) /* pattern filtering enable */
#define DC_IP ((uint32)1 << 10) /* internal ephy present (rev >= 1) */
#define DC_ER ((uint32)1 << 15) /* ephy reset */
#define DC_MP ((uint32)1 << 16) /* mii phy mode enable */
#define DC_CO ((uint32)1 << 17) /* mii phy mode: enable clocks */
#define DC_PA_MASK 0x7c0000 /* mii phy mode: mdc/mdio phy address */
#define DC_PA_SHIFT 18
#define DC_FS_MASK 0x03800000 /* fifo size (rev >= 8) */
#define DC_FS_SHIFT 23
#define DC_FS_4K 0 /* 4Kbytes */
#define DC_FS_512 1 /* 512bytes */
/* wakeup length */
#define WL_P0_MASK 0x7f /* pattern 0 */
#define WL_D0 ((uint32)1 << 7)
#define WL_P1_MASK 0x7f00 /* pattern 1 */
#define WL_P1_SHIFT 8
#define WL_D1 ((uint32)1 << 15)
#define WL_P2_MASK 0x7f0000 /* pattern 2 */
#define WL_P2_SHIFT 16
#define WL_D2 ((uint32)1 << 23)
#define WL_P3_MASK 0x7f000000 /* pattern 3 */
#define WL_P3_SHIFT 24
#define WL_D3 ((uint32)1 << 31)
/* intstatus and intmask */
#define I_PME ((uint32)1 << 6) /* power management event */
#define I_TO ((uint32)1 << 7) /* general purpose timeout */
#define I_PC ((uint32)1 << 10) /* descriptor error */
#define I_PD ((uint32)1 << 11) /* data error */
#define I_DE ((uint32)1 << 12) /* descriptor protocol error */
#define I_RU ((uint32)1 << 13) /* receive descriptor underflow */
#define I_RO ((uint32)1 << 14) /* receive fifo overflow */
#define I_XU ((uint32)1 << 15) /* transmit fifo underflow */
#define I_RI ((uint32)1 << 16) /* receive interrupt */
#define I_XI ((uint32)1 << 24) /* transmit interrupt */
#define I_EM ((uint32)1 << 26) /* emac interrupt */
#define I_MW ((uint32)1 << 27) /* mii write */
#define I_MR ((uint32)1 << 28) /* mii read */
/* emaccontrol */
#define EMC_CG ((uint32)1 << 0) /* crc32 generation enable */
#define EMC_EP ((uint32)1 << 2) /* onchip ephy: powerdown (rev >= 1) */
#define EMC_ED ((uint32)1 << 3) /* onchip ephy: energy detected (rev >= 1) */
#define EMC_LC_MASK 0xe0 /* onchip ephy: led control (rev >= 1) */
#define EMC_LC_SHIFT 5
/* emacflowcontrol */
#define EMF_RFH_MASK 0xff /* rx fifo hi water mark */
#define EMF_PG ((uint32)1 << 15) /* enable pause frame generation */
/* interrupt receive lazy */
#define IRL_TO_MASK 0x00ffffff /* timeout */
#define IRL_FC_MASK 0xff000000 /* frame count */
#define IRL_FC_SHIFT 24 /* frame count */
/* emac receive config */
#define ERC_DB ((uint32)1 << 0) /* disable broadcast */
#define ERC_AM ((uint32)1 << 1) /* accept all multicast */
#define ERC_RDT ((uint32)1 << 2) /* receive disable while transmitting */
#define ERC_PE ((uint32)1 << 3) /* promiscuous enable */
#define ERC_LE ((uint32)1 << 4) /* loopback enable */
#define ERC_FE ((uint32)1 << 5) /* enable flow control */
#define ERC_UF ((uint32)1 << 6) /* accept unicast flow control frame */
#define ERC_RF ((uint32)1 << 7) /* reject filter */
#define ERC_CA ((uint32)1 << 8) /* cam absent */
/* emac mdio control */
#define MC_MF_MASK 0x7f /* mdc frequency */
#define MC_PE ((uint32)1 << 7) /* mii preamble enable */
/* emac mdio data */
#define MD_DATA_MASK 0xffff /* r/w data */
#define MD_TA_MASK 0x30000 /* turnaround value */
#define MD_TA_SHIFT 16
#define MD_TA_VALID (2 << MD_TA_SHIFT) /* valid ta */
#define MD_RA_MASK 0x7c0000 /* register address */
#define MD_RA_SHIFT 18
#define MD_PMD_MASK 0xf800000 /* physical media device */
#define MD_PMD_SHIFT 23
#define MD_OP_MASK 0x30000000 /* opcode */
#define MD_OP_SHIFT 28
#define MD_OP_WRITE (1 << MD_OP_SHIFT) /* write op */
#define MD_OP_READ (2 << MD_OP_SHIFT) /* read op */
#define MD_SB_MASK 0xc0000000 /* start bits */
#define MD_SB_SHIFT 30
#define MD_SB_START (0x1 << MD_SB_SHIFT) /* start of frame */
/* emac intstatus and intmask */
#define EI_MII ((uint32)1 << 0) /* mii mdio interrupt */
#define EI_MIB ((uint32)1 << 1) /* mib interrupt */
#define EI_FLOW ((uint32)1 << 2) /* flow control interrupt */
/* emac cam data high */
#define CD_V ((uint32)1 << 16) /* valid bit */
/* emac cam control */
#define CC_CE ((uint32)1 << 0) /* cam enable */
#define CC_MS ((uint32)1 << 1) /* mask select */
#define CC_RD ((uint32)1 << 2) /* read */
#define CC_WR ((uint32)1 << 3) /* write */
#define CC_INDEX_MASK 0x3f0000 /* index */
#define CC_INDEX_SHIFT 16
#define CC_CB ((uint32)1 << 31) /* cam busy */
/* emac ethernet control */
#define EC_EE ((uint32)1 << 0) /* emac enable */
#define EC_ED ((uint32)1 << 1) /* emac disable */
#define EC_ES ((uint32)1 << 2) /* emac soft reset */
#define EC_EP ((uint32)1 << 3) /* external phy select */
/* emac transmit control */
#define EXC_FD ((uint32)1 << 0) /* full duplex */
#define EXC_FM ((uint32)1 << 1) /* flowmode */
#define EXC_SB ((uint32)1 << 2) /* single backoff enable */
#define EXC_SS ((uint32)1 << 3) /* small slottime */
/* emac mib control */
#define EMC_RZ ((uint32)1 << 0) /* autoclear on read */
#endif /* _bcmenet_47xx_h_ */
|
dc4345b0d40977f320dc8e5e22728c6e2327020e
|
35ae6922fbfe50390b37927ee2eaeab2469c3b46
|
/ulib/axlibc/include/dirent.h
|
41897510ba6b5ef4c82e498dd3041e8416b57ea8
|
[
"Apache-2.0",
"AGPL-3.0-only",
"LicenseRef-scancode-mulanpubl-2.0",
"AGPL-3.0-or-later",
"GPL-3.0-only",
"MulanPSL-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-mulanpsl-2.0-en"
] |
permissive
|
rcore-os/arceos
|
5a4fe111ed186941a0c8f420ae4165494d2bcd77
|
94eeaa3c2eb247f15f8403d5aa614f878077f48b
|
refs/heads/main
| 2023-08-30T21:07:40.133762
| 2023-08-27T14:21:04
| 2023-08-27T14:31:00
| 605,446,225
| 255
| 94
|
Apache-2.0
| 2023-09-13T11:39:29
| 2023-02-23T07:02:40
|
Rust
|
UTF-8
|
C
| false
| false
| 863
|
h
|
dirent.h
|
#ifndef _DIRENT_H
#define _DIRENT_H
#include <sys/types.h>
struct __dirstream {
long long tell;
int fd;
int buf_pos;
int buf_end;
int lock[1];
char buf[2048];
};
typedef struct __dirstream DIR;
struct dirent {
ino_t d_ino;
off_t d_off;
unsigned short d_reclen;
unsigned char d_type;
char d_name[256];
};
int closedir(DIR *);
DIR *fdopendir(int);
DIR *opendir(const char *);
struct dirent *readdir(DIR *);
int readdir_r(DIR *__restrict, struct dirent *__restrict, struct dirent **__restrict);
void rewinddir(DIR *);
int dirfd(DIR *);
#define DT_UNKNOWN 0
#define DT_FIFO 1
#define DT_CHR 2
#define DT_DIR 4
#define DT_BLK 6
#define DT_REG 8
#define DT_LNK 10
#define DT_SOCK 12
#define DT_WHT 14
#define IFTODT(x) ((x) >> 12 & 017)
#define DTTOIF(x) ((x) << 12)
#endif //_DIRENT_H
|
ba142e3ccfdb2858b54d991e1a1595bdb9ff95ff
|
03666e5f961946fc1a0ac67781ac1425562ef0d7
|
/src/operators/LCS/QvisLCSWindow.C
|
f708c242210dc7c51510de7fe775f624d8a1eeae
|
[
"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
| 82,224
|
c
|
QvisLCSWindow.C
|
// Copyright (c) Lawrence Livermore National Security, LLC and other VisIt
// Project developers. See the top-level LICENSE file for dates and other
// details. No copyright assignment is required to contribute to VisIt.
#include "QvisLCSWindow.h"
#include <LCSAttributes.h>
#include <QCheckBox>
#include <QComboBox>
#include <QGroupBox>
#include <QLabel>
#include <QLayout>
#include <QLineEdit>
#include <QSlider>
#include <QSpinBox>
#include <QTabWidget>
#include <QButtonGroup>
#include <QRadioButton>
#include <SelectionProperties.h>
static void
TurnOn(QWidget *w0, QWidget *w1=NULL);
static void
TurnOff(QWidget *w0, QWidget *w1=NULL);
// ****************************************************************************
// Method: QvisLCSWindow::QvisLCSWindow
//
// Purpose:
// Constructor
//
// Programmer: Brad Whitlock
// Creation: Mon Oct 21 14:19:00 PST 2002
//
// Modifications:
//
// Dave Pugmire, Thu Mar 15 11:23:18 EDT 2012
// Add named selections as a seed source.
//
// ****************************************************************************
QvisLCSWindow::QvisLCSWindow(const int type,
LCSAttributes *subj,
const QString &caption,
const QString &shortName,
QvisNotepadArea *notepad)
: QvisOperatorWindow(type, subj, caption, shortName, notepad)
{
plotType = type;
atts = subj;
}
// ****************************************************************************
// Method: QvisLCSWindow::~QvisLCSWindow
//
// Purpose:
// Destructor
//
// Programmer: Brad Whitlock
// Creation: Mon Oct 21 14:19:00 PST 2002
//
// Modifications:
//
// ****************************************************************************
QvisLCSWindow::~QvisLCSWindow()
{
}
// ****************************************************************************
// Method: QvisLCSWindow::CreateWindowContents
//
// Purpose:
// Creates the widgets for the window.
//
// Programmer: Brad Whitlock
// Creation: Mon Oct 21 14:19:00 PST 2002
//
// ****************************************************************************
void
QvisLCSWindow::CreateWindowContents()
{
QTabWidget *propertyTabs = new QTabWidget(central);
topLayout->addWidget(propertyTabs);
// ----------------------------------------------------------------------
// Integration tab
// ----------------------------------------------------------------------
QWidget *integrationTab = new QWidget();
propertyTabs->addTab(integrationTab, tr("Integration"));
CreateIntegrationTab(integrationTab);
// ----------------------------------------------------------------------
// LCS tab
// ----------------------------------------------------------------------
QWidget *LCSTab = new QWidget();
propertyTabs->addTab(LCSTab, tr("LCS"));
CreateLCSTab(LCSTab);
// ----------------------------------------------------------------------
// Appearance tab
// ----------------------------------------------------------------------
QWidget *appearanceTab = new QWidget();
propertyTabs->addTab(appearanceTab, tr("Appearance"));
CreateAppearanceTab(appearanceTab);
// ----------------------------------------------------------------------
// Advanced tab
// ----------------------------------------------------------------------
QWidget *advancedTab = new QWidget();
propertyTabs->addTab(advancedTab, tr("Advanced"));
CreateAdvancedTab(advancedTab);
}
// ****************************************************************************
// Method: QvisLCSWindow::CreateIntegrationTab
//
// Purpose:
// Populates the integration tab.
//
// Programmer: Dave Pugmire
// Creation: Tue Dec 29 14:37:53 EST 2009
//
// Modifications:
// Kathleen Biagas, Tue Apr 18 16:34:41 PDT 2023
// Support Qt6: buttonClicked -> idClicked.
//
// ****************************************************************************
void
QvisLCSWindow::CreateIntegrationTab(QWidget *pageIntegration)
{
QGridLayout *mainLayout = new QGridLayout(pageIntegration);
mainLayout->setContentsMargins(5,5,5,5);
mainLayout->setSpacing(10);
// Create the source group box.
QGroupBox *sourceGroup = new QGroupBox(central);
sourceGroup->setTitle(tr("Source"));
mainLayout->addWidget(sourceGroup, 0, 0, 5, 2);
// mainLayout->setStretchFactor(sourceGroup, 100);
QGridLayout *sourceLayout = new QGridLayout(sourceGroup);
sourceLayout->setContentsMargins(5,5,5,5);
sourceLayout->setSpacing(10);
// Create the source type combo box.
sourceLayout->addWidget(new QLabel(tr("Source type"), sourceGroup), 0, 0);
sourceType = new QComboBox(sourceGroup);
sourceType->addItem(tr("Native Mesh"));
sourceType->addItem(tr("Regular Grid"));
connect(sourceType, SIGNAL(activated(int)),
this, SLOT(sourceTypeChanged(int)));
sourceLayout->addWidget(sourceType, 0, 1, 1, 2);
// Create the source geometry subgroup
QGroupBox *geometryGroup = new QGroupBox();
sourceLayout->addWidget(geometryGroup, 1, 0, 4, 3);
QGridLayout *geometryLayout = new QGridLayout(geometryGroup);
geometryLayout->setContentsMargins(5,5,5,5);
geometryLayout->setSpacing(10);
geometryLayout->setRowStretch(5,10);
// Regular grid
QGroupBox *regularGridBox = new QGroupBox();
regularGridBox->setTitle(tr("Regular Grid"));
geometryLayout->addWidget(regularGridBox);
// Resolution
QGridLayout *rgridLayout = new QGridLayout(regularGridBox);
ResolutionLabel = new QLabel(tr("Resolution"));
rgridLayout->addWidget(ResolutionLabel,0,0);
Resolution = new QLineEdit();
connect(Resolution, SIGNAL(returnPressed()),
this, SLOT(ResolutionProcessText()));
rgridLayout->addWidget(Resolution, 0, 1, 1, 2);
// Start extents
rgridLayout->addWidget(new QLabel(tr("Data start extent")), 1, 0);
UseDataSetStart = new QButtonGroup();
QRadioButton* rb = new QRadioButton(tr("Full"));
UseDataSetStart->addButton(rb, 0);
rgridLayout->addWidget(rb, 1,1);
rb = new QRadioButton(tr("Subset"));
UseDataSetStart->addButton(rb, 1);
rgridLayout->addWidget(rb, 1,2);
#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
connect(UseDataSetStart, SIGNAL(buttonClicked(int)), this,
SLOT(UseDataSetStartChanged(int)));
#else
connect(UseDataSetStart, SIGNAL(idClicked(int)), this,
SLOT(UseDataSetStartChanged(int)));
#endif
StartPosition = new QLineEdit();
connect(StartPosition, SIGNAL(returnPressed()),
this, SLOT(StartPositionProcessText()));
rgridLayout->addWidget(StartPosition, 1,3);
// End extents
rgridLayout->addWidget(new QLabel(tr("Data end extent")), 2, 0);
UseDataSetEnd = new QButtonGroup();
rb = new QRadioButton(tr("Full"));
UseDataSetEnd->addButton(rb, 0);
rgridLayout->addWidget(rb, 2,1);
rb = new QRadioButton(tr("Subset"));
UseDataSetEnd->addButton(rb, 1);
rgridLayout->addWidget(rb, 2,2);
#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
connect(UseDataSetEnd, SIGNAL(buttonClicked(int)), this,
SLOT(UseDataSetEndChanged(int)));
#else
connect(UseDataSetEnd, SIGNAL(idClicked(int)), this,
SLOT(UseDataSetEndChanged(int)));
#endif
EndPosition = new QLineEdit();
connect(EndPosition, SIGNAL(returnPressed()),
this, SLOT(EndPositionProcessText()));
rgridLayout->addWidget(EndPosition, 2,3);
// Create the auxiliary grid group box.
QGroupBox *auxiliaryGridGroup = new QGroupBox();
auxiliaryGridGroup->setTitle(tr("Auxiliary Grid"));
sourceLayout->addWidget(auxiliaryGridGroup, 5, 0, 1, 4);
QGridLayout *auxiliaryGridLayout = new QGridLayout(auxiliaryGridGroup);
auxiliaryGridLayout->setContentsMargins(5,5,5,5);
auxiliaryGridLayout->setSpacing(10);
// Auxiliary grid label and combo box
auxiliaryGridLayout->addWidget( new QLabel(tr("Auxiliary Grid")), 0,0);
auxiliaryGrid = new QComboBox();
auxiliaryGrid->addItem(tr("None"));
auxiliaryGrid->addItem(tr("2D"));
auxiliaryGrid->addItem(tr("3D"));
connect(auxiliaryGrid, SIGNAL(activated(int)),
this, SLOT(auxiliaryGridChanged(int)));
auxiliaryGridLayout->addWidget(auxiliaryGrid, 0,1);
// Create the auxiliary grid spacing
auxiliaryGridSpacingLabel = new QLabel(tr("Spacing"));
auxiliaryGridSpacing = new QLineEdit();
connect(auxiliaryGridSpacing, SIGNAL(returnPressed()), this,
SLOT(auxiliaryGridSpacingProcessText()));
auxiliaryGridLayout->addWidget(auxiliaryGridSpacingLabel, 0,2);
auxiliaryGridLayout->addWidget(auxiliaryGridSpacing, 0,3);
// Create the field group box.
QGroupBox *fieldGroup = new QGroupBox();
fieldGroup->setTitle(tr("Field"));
mainLayout->addWidget(fieldGroup, 6, 0, 1, 1);
// mainLayout->setStretchFactor(fieldGroup, 100);
QGridLayout *fieldLayout = new QGridLayout(fieldGroup);
fieldLayout->setContentsMargins(5,5,5,5);
fieldLayout->setSpacing(10);
fieldLayout->addWidget( new QLabel(tr("Field")), 0,0);
fieldType = new QComboBox();
fieldType->addItem(tr("Default"));
fieldType->addItem(tr("Flash"));
fieldType->addItem(tr("M3D-C1 2D"));
fieldType->addItem(tr("M3D-C1 3D"));
fieldType->addItem(tr("Nek5000"));
fieldType->addItem(tr("Nektar++"));
connect(fieldType, SIGNAL(activated(int)),
this, SLOT(fieldTypeChanged(int)));
fieldLayout->addWidget(fieldType, 0,1);
// Create the field constant text field.
fieldConstantLabel = new QLabel(tr("Constant"));
fieldConstant = new QLineEdit();
connect(fieldConstant, SIGNAL(returnPressed()), this,
SLOT(fieldConstantProcessText()));
fieldLayout->addWidget(fieldConstantLabel, 0,2);
fieldLayout->addWidget(fieldConstant, 0,3);
// Create the widgets that specify a velocity source.
velocitySource = new QLineEdit();
connect(velocitySource, SIGNAL(returnPressed()),
this, SLOT(velocitySourceProcessText()));
velocitySourceLabel = new QLabel(tr("Velocity"));
velocitySourceLabel->setBuddy(velocitySource);
fieldLayout->addWidget(velocitySourceLabel, 1, 2);
fieldLayout->addWidget(velocitySource, 1, 3);
// Create the node centering
// forceNodal = new QCheckBox(tr("Force node centering"));
// connect(forceNodal, SIGNAL(toggled(bool)), this, SLOT(forceNodalChanged(bool)));
// fieldLayout->addWidget(forceNodal, 2, 0);
// Create the integration group box.
QGroupBox *integrationGroup = new QGroupBox(central);
integrationGroup->setTitle(tr("Integration"));
mainLayout->addWidget(integrationGroup, 7, 0, 4, 2);
// mainLayout->setStretchFactor(integrationGroup, 100);
QGridLayout *integrationLayout = new QGridLayout(integrationGroup);
integrationLayout->setContentsMargins(5,5,5,5);
integrationLayout->setSpacing(10);
// Create the direction of integration.
integrationLayout->addWidget(new QLabel(tr("Integration direction"),
central), 0, 0);
directionType = new QComboBox(central);
directionType->addItem(tr("Forward"));
directionType->addItem(tr("Backward"));
connect(directionType, SIGNAL(activated(int)),
this, SLOT(directionTypeChanged(int)));
integrationLayout->addWidget(directionType, 0, 1);
// Create the type of integration.
integrationLayout->addWidget( new QLabel(tr("Integrator"), integrationGroup), 1,0);
integrationType = new QComboBox(integrationGroup);
integrationType->addItem(tr("Forward Euler (Single-step)"));
integrationType->addItem(tr("Leapfrog (Single-step)"));
integrationType->addItem(tr("Runge-Kutta-Dormand-Prince (RKDP)"));
integrationType->addItem(tr("Adams-Bashforth (Multi-step)"));
integrationType->addItem(tr("Runge-Kutta 4 (Single-step)"));
integrationType->addItem(tr("M3D-C1 2D Integrator (M3D-C1 2D fields only)"));
connect(integrationType, SIGNAL(activated(int)),
this, SLOT(integrationTypeChanged(int)));
integrationLayout->addWidget(integrationType, 1,1);
// Create the step length text field.
maxStepLengthLabel = new QLabel(tr("Step length"), integrationGroup);
maxStepLength = new QLineEdit(integrationGroup);
connect(maxStepLength, SIGNAL(returnPressed()),
this, SLOT(maxStepLengthProcessText()));
integrationLayout->addWidget(maxStepLengthLabel, 2,0);
integrationLayout->addWidget(maxStepLength, 2,1);
limitMaxTimeStep = new QCheckBox(tr("Limit maximum time step"), integrationGroup);
connect(limitMaxTimeStep, SIGNAL(toggled(bool)), this, SLOT(limitMaxTimeStepChanged(bool)));
integrationLayout->addWidget(limitMaxTimeStep, 3, 0);
// Create the step length text field.
maxTimeStep = new QLineEdit(integrationGroup);
connect(maxTimeStep, SIGNAL(returnPressed()),
this, SLOT(maxTimeStepProcessText()));
integrationLayout->addWidget(maxTimeStep, 3,1);
QGroupBox *toleranceGroup = new QGroupBox(central);
toleranceGroup->setTitle(tr("Tolerances: max error for step < max(abstol, reltol*velocity_i) for each component i"));
integrationLayout->addWidget(toleranceGroup, 4, 0, 2, 3);
QGridLayout *toleranceLayout = new QGridLayout(toleranceGroup);
toleranceLayout->setContentsMargins(5,5,5,5);
toleranceLayout->setSpacing(10);
// Create the relative tolerance text field.
relTolLabel = new QLabel(tr("Relative tolerance"), toleranceGroup);
relTol = new QLineEdit(toleranceGroup);
connect(relTol, SIGNAL(returnPressed()),
this, SLOT(relTolProcessText()));
toleranceLayout->addWidget(relTolLabel, 0, 0);
toleranceLayout->addWidget(relTol, 0, 1);
// Create the absolute tolerance text field.
absTolLabel = new QLabel(tr("Absolute tolerance"), toleranceGroup);
absTol = new QLineEdit(toleranceGroup);
connect(absTol, SIGNAL(returnPressed()), this, SLOT(absTolProcessText()));
toleranceLayout->addWidget(absTolLabel, 1, 0);
toleranceLayout->addWidget(absTol, 1, 1);
absTolSizeType = new QComboBox(toleranceGroup);
absTolSizeType->addItem(tr("Absolute"), 0);
absTolSizeType->addItem(tr("Fraction of Bounding Box"), 1);
connect(absTolSizeType, SIGNAL(activated(int)), this, SLOT(absTolSizeTypeChanged(int)));
toleranceLayout->addWidget(absTolSizeType, 1, 2);
}
// ****************************************************************************
// Method: QvisLCSWindow::LCSTab
//
// Purpose:
// Populates the lcs tab.
//
// Programmer: Dave Pugmire
// Creation: Tue Dec 29 14:37:53 EST 2009
//
// Modifications:
// Kathleen Biagas, Tue Apr 18 16:34:41 PDT 2023
// Support Qt6: buttonClicked -> idClicked.
//
// ****************************************************************************
void
QvisLCSWindow::CreateLCSTab(QWidget *pageLCS)
{
QGridLayout *mainLayout = new QGridLayout(pageLCS);
mainLayout->setContentsMargins(5,5,5,5);
mainLayout->setSpacing(10);
// Create the termination group box.
QGroupBox *terminationGroup = new QGroupBox(central);
terminationGroup->setTitle(tr("Termination"));
mainLayout->addWidget(terminationGroup, 0, 0, 2, 2);
// mainLayout->setStretchFactor(terminationGroup, 100);
QGridLayout *terminationLayout = new QGridLayout(terminationGroup);
terminationLayout->setContentsMargins(5,5,5,5);
terminationLayout->setSpacing(10);
// For FTLE or FLLE base the termintion on the time or distance,
// respectively. While using the max steps as a back up. This is
// opposite of streamlines/pathlines which optionally use the
// termination.
terminationTypeButtonGroup = new QButtonGroup(terminationGroup);
// Create the operation of lcs.
terminationLayout->addWidget(new QLabel(tr("Operation type"),
central), 0, 0);
operationType = new QComboBox(central);
operationType->addItem(tr("Integration time"));
operationType->addItem(tr("Arc length"));
operationType->addItem(tr("Average distance from seed"));
operationType->addItem(tr("Eigen Value"));
operationType->addItem(tr("Eigen Vector"));
operationType->addItem(tr("Lyapunov Exponent"));
connect(operationType, SIGNAL(activated(int)),
this, SLOT(operationTypeChanged(int)));
terminationLayout->addWidget(operationType, 0, 1);
// Create the cauchyGreenTensor of integration.
cauchyGreenTensorLabel = new QLabel(tr("Tensor"), central);
cauchyGreenTensorLabel->setAlignment(Qt::AlignRight | Qt::AlignCenter);
terminationLayout->addWidget(cauchyGreenTensorLabel, 0, 2);
cauchyGreenTensor = new QComboBox(central);
cauchyGreenTensor->addItem(tr("Left Cauchy Green"));
cauchyGreenTensor->addItem(tr("Right Cauchy Green"));
connect(cauchyGreenTensor, SIGNAL(activated(int)),
this, SLOT(cauchyGreenTensorChanged(int)));
terminationLayout->addWidget(cauchyGreenTensor, 0, 3);
// Create the eigenComponent of integration.
eigenComponentLabel = new QLabel(tr("Eigen value"), central);
terminationLayout->addWidget(eigenComponentLabel, 1, 0);
eigenComponent = new QComboBox(central);
eigenComponent->addItem(tr("Smallest"));
eigenComponent->addItem(tr("Intermediate (3D only)"));
eigenComponent->addItem(tr("Largest"));
eigenComponent->addItem(tr("Shear Pos."));
eigenComponent->addItem(tr("Shear Neg."));
eigenComponent->addItem(tr("Shear Pos. linear combination"));
eigenComponent->addItem(tr("Shear Neg. linear combination"));
eigenComponent->setMaxCount(7);
connect(eigenComponent, SIGNAL(activated(int)),
this, SLOT(eigenComponentChanged(int)));
terminationLayout->addWidget(eigenComponent, 1, 1);
// Create the operator of integrator.
operatorType = new QComboBox(central);
operatorType->addItem(tr("Base value"));
operatorType->addItem(tr("Gradient"));
connect(operatorType, SIGNAL(activated(int)),
this, SLOT(operatorTypeChanged(int)));
terminationLayout->addWidget(operatorType, 0, 2);
clampLogValues = new QCheckBox(tr("Clamp exponent values"), central);
connect(clampLogValues, SIGNAL(toggled(bool)), this, SLOT(clampLogValuesChanged(bool)));
terminationLayout->addWidget(clampLogValues, 1, 3);
// Create the eigen weight text field.
// eigenWeightLabel = new QLabel(tr("Weight"), central);
// eigenWeightLabel->setAlignment(Qt::AlignRight | Qt::AlignCenter);
eigenWeightEdit = new QLineEdit(terminationGroup);
connect(eigenWeightEdit, SIGNAL(returnPressed()), this, SLOT(eigenWeightEditProcessText()));
eigenWeightSlider = new QSlider(Qt::Horizontal, central);
eigenWeightSlider->setRange(-100,+100);
eigenWeightSlider->setSingleStep(10);
eigenWeightSlider->setValue(0);
connect(eigenWeightSlider, SIGNAL(valueChanged(int)),
this, SLOT(eigenWeightSliderChanged(int)));
connect(eigenWeightSlider, SIGNAL(sliderPressed()),
this, SLOT(eigenWeightSliderPressed()));
connect(eigenWeightSlider, SIGNAL(sliderReleased()),
this, SLOT(eigenWeightSliderReleased()));
// terminationLayout->addWidget(eigenWeightLabel, 2, 3);
terminationLayout->addWidget(eigenWeightEdit, 1, 2);
terminationLayout->addWidget(eigenWeightSlider, 1, 3);
// Radio button termination type
QRadioButton *rb = new QRadioButton(tr("Limit maximum advection time i.e. FTLE"), terminationGroup);
terminationTypeButtonGroup->addButton(rb, 0);
terminationLayout->addWidget(rb, 2, 0, 1, 2);
rb->setChecked(true);
rb = new QRadioButton(tr("Limit maximum advection distance i.e. FLLE"), terminationGroup);
terminationTypeButtonGroup->addButton(rb, 1);
terminationLayout->addWidget(rb, 3, 0, 1, 2);
rb = new QRadioButton(tr("Limit maximum size i.e. FSLE"), terminationGroup);
terminationTypeButtonGroup->addButton(rb, 2);
terminationLayout->addWidget(rb, 4, 0, 1, 2);
#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
connect(terminationTypeButtonGroup, SIGNAL(buttonClicked(int)), this, SLOT(terminationTypeButtonGroupChanged(int)));
#else
connect(terminationTypeButtonGroup, SIGNAL(idClicked(int)), this, SLOT(terminationTypeButtonGroupChanged(int)));
#endif
// Check box termination type
limitMaxTime = new QCheckBox(tr("Limit maximum advection time"), terminationGroup);
connect(limitMaxTime, SIGNAL(toggled(bool)), this, SLOT(limitMaxTimeChanged(bool)));
terminationLayout->addWidget(limitMaxTime, 2, 0, 1, 2);
limitMaxTime->hide();
limitMaxDistance = new QCheckBox(tr("Limit maximum advection distance"), terminationGroup);
connect(limitMaxDistance, SIGNAL(toggled(bool)), this, SLOT(limitMaxDistanceChanged(bool)));
terminationLayout->addWidget(limitMaxDistance, 3, 0, 1, 2);
limitMaxDistance->hide();
// Termination values
maxTime = new QLineEdit(central);
connect(maxTime, SIGNAL(returnPressed()), this, SLOT(maxTimeProcessText()));
terminationLayout->addWidget(maxTime, 2, 2);
maxDistance = new QLineEdit(central);
connect(maxDistance, SIGNAL(returnPressed()), this, SLOT(maxDistanceProcessText()));
terminationLayout->addWidget(maxDistance, 3, 2);
maxSize = new QLineEdit(central);
connect(maxSize, SIGNAL(returnPressed()), this, SLOT(maxSizeProcessText()));
terminationLayout->addWidget(maxSize, 4, 2);
// Max steps override
QLabel *maxStepsLabel = new QLabel(tr("Maximum number of steps"), terminationGroup);
terminationLayout->addWidget(maxStepsLabel, 5, 0, 1, 2);
maxSteps = new QLineEdit(central);
connect(maxSteps, SIGNAL(returnPressed()),
this, SLOT(maxStepsProcessText()));
terminationLayout->addWidget(maxSteps, 5, 2);
// Seed generation group.
QGroupBox *seedGroup = new QGroupBox(pageLCS);
seedGroup->setTitle(tr("Seed generation"));
mainLayout->addWidget(seedGroup, 6, 0, 4, 2);
QGridLayout *seedGroupLayout = new QGridLayout(seedGroup);
seedGroupLayout->setSpacing(10);
seedGroupLayout->setColumnStretch(1,10);
QLabel *thresholdLimitLabel = new QLabel(tr("Threshold limit"), seedGroup);
thresholdLimitLabel->setAlignment(Qt::AlignRight | Qt::AlignCenter);
seedGroupLayout->addWidget(thresholdLimitLabel, 0, 0);
thresholdLimit = new QLineEdit(seedGroup);
connect(thresholdLimit, SIGNAL(returnPressed()),
this, SLOT(thresholdLimitProcessText()));
seedGroupLayout->addWidget(thresholdLimit, 0, 1);
QLabel *radialLimitLabel = new QLabel(tr("Radial limit"), seedGroup);
radialLimitLabel->setAlignment(Qt::AlignRight | Qt::AlignCenter);
seedGroupLayout->addWidget(radialLimitLabel, 1, 0);
radialLimit = new QLineEdit(seedGroup);
connect(radialLimit, SIGNAL(returnPressed()),
this, SLOT(radialLimitProcessText()));
seedGroupLayout->addWidget(radialLimit, 1, 1);
QLabel *boundaryLimitLabel = new QLabel(tr("Boundary limit"), seedGroup);
boundaryLimitLabel->setAlignment(Qt::AlignRight | Qt::AlignCenter);
seedGroupLayout->addWidget(boundaryLimitLabel, 2, 0);
boundaryLimit = new QLineEdit(seedGroup);
connect(boundaryLimit, SIGNAL(returnPressed()),
this, SLOT(boundaryLimitProcessText()));
seedGroupLayout->addWidget(boundaryLimit, 2, 1);
QLabel *seedLimitLabel = new QLabel(tr("Maximum number of seeds"), seedGroup);
seedLimitLabel->setAlignment(Qt::AlignRight | Qt::AlignCenter);
seedGroupLayout->addWidget( seedLimitLabel, 3, 0);
seedLimit = new QSpinBox(seedGroup);
seedLimit->setKeyboardTracking(false);
seedLimit->setMinimum(1);
seedLimit->setMaximum(100);
connect(seedLimit, SIGNAL(valueChanged(int)),
this, SLOT(seedLimitChanged(int)));
seedGroupLayout->addWidget( seedLimit, 3, 1);
}
// ****************************************************************************
// Method: QvisLCSWindow::CreateAppearanceTab
//
// Purpose:
// Populates the appearance tab.
//
// Programmer: Dave Pugmire
// Creation: Tue Dec 29 14:37:53 EST 2009
//
// Modifications:
// Kathleen Biagas, Wed Jun 8 17:10:30 PDT 2016
// Set keyboard tracking to false for spin boxes so that 'valueChanged'
// signal will only emit when 'enter' is pressed or spinbox loses focus.
//
// Kathleen Biagas, Tue Apr 18 16:34:41 PDT 2023
// Support Qt6: buttonClicked -> idClicked.
//
// ****************************************************************************
void
QvisLCSWindow::CreateAppearanceTab(QWidget *pageAppearance)
{
QGridLayout *mainLayout = new QGridLayout(pageAppearance);
mainLayout->setContentsMargins(5,5,5,5);
mainLayout->setSpacing(10);
// Streamlines/Pathline Group.
QGroupBox *icGrp = new QGroupBox(pageAppearance);
icGrp->setTitle(tr("Streamlines vs Pathlines"));
mainLayout->addWidget(icGrp, 1, 0);
QGridLayout *icGrpLayout = new QGridLayout(icGrp);
icGrpLayout->setSpacing(10);
icGrpLayout->setColumnStretch(1,10);
icButtonGroup = new QButtonGroup(icGrp);
QRadioButton *streamlineButton = new QRadioButton(tr("Streamline\n Compute trajectories in an (instantaneous) snapshot of the vector field.\n Uses and loads vector data from only the current time slice."), icGrp);
QRadioButton *pathlineButton = new QRadioButton(tr("Pathline \n Compute trajectories in the time-varying vector field.\n Uses and loads vector data from all relevant time slices."), icGrp);
streamlineButton->setChecked(true);
icButtonGroup->addButton(streamlineButton, 0);
icButtonGroup->addButton(pathlineButton, 1);
icGrpLayout->addWidget(streamlineButton, 1, 0);
icGrpLayout->addWidget(pathlineButton, 2, 0);
#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
connect(icButtonGroup, SIGNAL(buttonClicked(int)), this, SLOT(icButtonGroupChanged(int)));
#else
connect(icButtonGroup, SIGNAL(idClicked(int)), this, SLOT(icButtonGroupChanged(int)));
#endif
// Pathline Options
QGroupBox *pathlineOptionsGrp = new QGroupBox(icGrp);
pathlineOptionsGrp->setTitle(tr("Pathline Options"));
icGrpLayout->addWidget(pathlineOptionsGrp, 3, 0);
QGridLayout *pathlineOptionsGrpLayout = new QGridLayout(pathlineOptionsGrp);
pathlineOptionsGrpLayout->setSpacing(10);
pathlineOptionsGrpLayout->setColumnStretch(1,10);
pathlineOverrideStartingTimeFlag = new QCheckBox(tr("Override Starting Time"), pathlineOptionsGrp);
connect(pathlineOverrideStartingTimeFlag, SIGNAL(toggled(bool)),
this, SLOT(pathlineOverrideStartingTimeFlagChanged(bool)));
pathlineOptionsGrpLayout->addWidget(pathlineOverrideStartingTimeFlag, 1, 0);
QLabel *pathlineOverrideStartingTimeLabel = new QLabel(tr("Time"), pathlineOptionsGrp);
pathlineOverrideStartingTimeLabel->setAlignment(Qt::AlignRight | Qt::AlignCenter);
pathlineOptionsGrpLayout->addWidget(pathlineOverrideStartingTimeLabel, 1, 1);
pathlineOverrideStartingTime = new QLineEdit(pathlineOptionsGrp);
connect(pathlineOverrideStartingTime, SIGNAL(returnPressed()),
this, SLOT(pathlineOverrideStartingTimeProcessText()));
pathlineOptionsGrpLayout->addWidget(pathlineOverrideStartingTime, 1, 2);
QLabel *pathlinePeriodLabel = new QLabel(tr("Period"), pathlineOptionsGrp);
pathlinePeriodLabel->setAlignment(Qt::AlignRight | Qt::AlignCenter);
pathlineOptionsGrpLayout->addWidget(pathlinePeriodLabel, 1, 3);
pathlinePeriod = new QLineEdit(pathlineOptionsGrp);
connect(pathlinePeriod, SIGNAL(returnPressed()),
this, SLOT(pathlinePeriodProcessText()));
pathlineOptionsGrpLayout->addWidget(pathlinePeriod, 1, 4);
QGroupBox *cmfeOptionsGrp = new QGroupBox(pathlineOptionsGrp);
cmfeOptionsGrp->setTitle(tr("How to perform interpolation over time"));
pathlineOptionsGrpLayout->addWidget(cmfeOptionsGrp, 2, 0, 2, 5);
QGridLayout *cmfeOptionsGrpLayout = new QGridLayout(cmfeOptionsGrp);
cmfeOptionsGrpLayout->setSpacing(10);
cmfeOptionsGrpLayout->setColumnStretch(1,10);
pathlineCMFEButtonGroup = new QButtonGroup(cmfeOptionsGrp);
QRadioButton *connButton = new QRadioButton(tr("Mesh is static over time (fast, but special purpose)"), cmfeOptionsGrp);
QRadioButton *posButton = new QRadioButton(tr("Mesh changes over time (slow, but robust)"), cmfeOptionsGrp);
posButton->setChecked(true);
pathlineCMFEButtonGroup->addButton(connButton, 0);
pathlineCMFEButtonGroup->addButton(posButton, 1);
cmfeOptionsGrpLayout->addWidget(connButton, 2, 0, 1, 5);
cmfeOptionsGrpLayout->addWidget(posButton, 3, 0, 1, 5);
#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
connect(pathlineCMFEButtonGroup, SIGNAL(buttonClicked(int)), this, SLOT(pathlineCMFEButtonGroupChanged(int)));
#else
connect(pathlineCMFEButtonGroup, SIGNAL(idClicked(int)), this, SLOT(pathlineCMFEButtonGroupChanged(int)));
#endif
}
// ****************************************************************************
// Method: QvisLCSWindow::CreateAdvancedTab
//
// Purpose:
// Populates the advanced tab.
//
// Programmer: Dave Pugmire
// Creation: Tue Dec 29 14:37:53 EST 2009
//
// Modifications:
//
// Hank Childs, Wed Sep 29 19:25:06 PDT 2010
// Add option for having VisIt select the best algorithm.
//
// Hank Childs, Oct 8 23:30:27 PDT 2010
// Set up controls for multiple termination criteria.
//
// Hank Childs, Sun Dec 5 05:31:57 PST 2010
// Add additional warning controls.
//
// Kathleen Biagas, Wed Jun 8 17:10:30 PDT 2016
// Set keyboard tracking to false for spin boxes so that 'valueChanged'
// signal will only emit when 'enter' is pressed or spinbox loses focus.
//
// ****************************************************************************
void
QvisLCSWindow::CreateAdvancedTab(QWidget *pageAdvanced)
{
QGridLayout *mainLayout = new QGridLayout(pageAdvanced);
mainLayout->setContentsMargins(5,5,5,5);
mainLayout->setSpacing(5);
QGroupBox *algoGrp = new QGroupBox(pageAdvanced);
algoGrp->setTitle(tr("Parallel integration options"));
mainLayout->addWidget(algoGrp, 0, 0);
// Algorithm group.
QGridLayout *algoGLayout = new QGridLayout(algoGrp);
algoGLayout->setSpacing(10);
algoGLayout->setColumnStretch(1,10);
parallelAlgoLabel = new QLabel(tr("Parallelization"), algoGrp);
parallelAlgo = new QComboBox(algoGrp);
parallelAlgo->addItem(tr("Parallelize over curves"));
parallelAlgo->addItem(tr("Parallelize over domains"));
parallelAlgo->addItem(tr("Parallelize over curves and domains"));
parallelAlgo->addItem(tr("Have VisIt select the best algorithm"));
connect(parallelAlgo, SIGNAL(activated(int)),
this, SLOT(parallelAlgorithmChanged(int)));
algoGLayout->addWidget( parallelAlgoLabel, 1,0);
algoGLayout->addWidget( parallelAlgo, 1,1);
maxSLCountLabel = new QLabel(tr("Communication threshold"), algoGrp);
maxSLCount = new QSpinBox(algoGrp);
maxSLCount->setKeyboardTracking(false);
maxSLCount->setMinimum(1);
maxSLCount->setMaximum(100000);
connect(maxSLCount, SIGNAL(valueChanged(int)),
this, SLOT(maxSLCountChanged(int)));
algoGLayout->addWidget( maxSLCountLabel, 2,0);
algoGLayout->addWidget( maxSLCount,2,1);
maxDomainCacheLabel = new QLabel(tr("Domain cache size"), algoGrp);
maxDomainCache = new QSpinBox(algoGrp);
maxDomainCache->setKeyboardTracking(false);
maxDomainCache->setMinimum(1);
maxDomainCache->setMaximum(100000);
connect(maxDomainCache, SIGNAL(valueChanged(int)),
this, SLOT(maxDomainCacheChanged(int)));
algoGLayout->addWidget( maxDomainCacheLabel, 3,0);
algoGLayout->addWidget( maxDomainCache, 3,1);
workGroupSizeLabel = new QLabel(tr("Work group size"), algoGrp);
workGroupSize = new QSpinBox(algoGrp);
workGroupSize->setKeyboardTracking(false);
workGroupSize->setMinimum(2);
workGroupSize->setMaximum(1000000);
connect(workGroupSize, SIGNAL(valueChanged(int)),
this, SLOT(workGroupSizeChanged(int)));
algoGLayout->addWidget( workGroupSizeLabel, 4,0);
algoGLayout->addWidget( workGroupSize, 4,1);
// Warnings group.
QGroupBox *warningsGrp = new QGroupBox(pageAdvanced);
warningsGrp->setTitle(tr("Warnings"));
mainLayout->addWidget(warningsGrp, 1, 0);
QGridLayout *warningsGLayout = new QGridLayout(warningsGrp);
warningsGLayout->setSpacing(10);
warningsGLayout->setColumnStretch(1,10);
issueWarningForAdvection = new QCheckBox(central);
connect(issueWarningForAdvection, SIGNAL(toggled(bool)),
this, SLOT(issueWarningForAdvectionChanged(bool)));
warningsGLayout->addWidget(issueWarningForAdvection, 0, 0);
QLabel *advectionLabel = new QLabel(tr("Issue warning if the advection limit is not reached."), warningsGrp);
warningsGLayout->addWidget(advectionLabel, 0, 1, 1, 2);
issueWarningForBoundary = new QCheckBox(central);
connect(issueWarningForBoundary, SIGNAL(toggled(bool)),
this, SLOT(issueWarningForBoundaryChanged(bool)));
warningsGLayout->addWidget(issueWarningForBoundary, 1, 0);
QLabel *boundaryLabel = new QLabel(tr("Issue warning if the spatial boundary is reached."), warningsGrp);
warningsGLayout->addWidget(boundaryLabel, 1, 1, 1, 2);
issueWarningForMaxSteps = new QCheckBox(central);
connect(issueWarningForMaxSteps, SIGNAL(toggled(bool)),
this, SLOT(issueWarningForMaxStepsChanged(bool)));
warningsGLayout->addWidget(issueWarningForMaxSteps, 2, 0);
QLabel *maxStepsLabel = new QLabel(tr("Issue warning when the maximum number of steps is reached."), warningsGrp);
warningsGLayout->addWidget(maxStepsLabel, 2, 1, 1, 2);
issueWarningForStepsize = new QCheckBox(central);
connect(issueWarningForStepsize, SIGNAL(toggled(bool)),
this, SLOT(issueWarningForStepsizeChanged(bool)));
warningsGLayout->addWidget(issueWarningForStepsize, 3, 0);
QLabel *stepsizeLabel = new QLabel(tr("Issue warning when a step size underflow is detected."), warningsGrp);
warningsGLayout->addWidget(stepsizeLabel, 3, 1, 1, 2);
issueWarningForStiffness = new QCheckBox(central);
connect(issueWarningForStiffness, SIGNAL(toggled(bool)),
this, SLOT(issueWarningForStiffnessChanged(bool)));
warningsGLayout->addWidget(issueWarningForStiffness, 4, 0);
QLabel *stiffnessLabel = new QLabel(tr("Issue warning when a stiffness condition is detected."), warningsGrp);
warningsGLayout->addWidget(stiffnessLabel, 4, 1, 1, 2);
issueWarningForCriticalPoints = new QCheckBox(central);
connect(issueWarningForCriticalPoints, SIGNAL(toggled(bool)),
this, SLOT(issueWarningForCriticalPointsChanged(bool)));
warningsGLayout->addWidget(issueWarningForCriticalPoints, 5, 0);
QLabel *critPointLabel = new QLabel(tr("Issue warning when a curve doesn't terminate at a critical point."), warningsGrp);
warningsGLayout->addWidget(critPointLabel, 5, 1, 1, 2);
criticalPointThresholdLabel = new QLabel(tr("Speed cutoff for critical points"), warningsGrp);
criticalPointThresholdLabel->setAlignment(Qt::AlignRight | Qt::AlignCenter);
warningsGLayout->addWidget(criticalPointThresholdLabel, 6, 1);
criticalPointThreshold = new QLineEdit(warningsGrp);
criticalPointThreshold->setAlignment(Qt::AlignLeft);
connect(criticalPointThreshold, SIGNAL(returnPressed()),
this, SLOT(criticalPointThresholdProcessText()));
warningsGLayout->addWidget(criticalPointThreshold, 6, 2);
}
// ****************************************************************************
// Method: QvisLCSWindow::UpdateWindow
//
// Purpose:
// Updates the widgets in the window when the subject changes.
//
// Programmer: Brad Whitlock
// Creation: Mon Oct 21 14:19:00 PST 2002
//
// Modifications:
// Kathleen Biagas, Thu Apr 9 07:19:54 MST 2015
// Use helper function DoubleToQString for consistency in formatting across
// all windows.
//
// ****************************************************************************
void
QvisLCSWindow::UpdateWindow(bool doAll)
{
bool bval;
int ival;
for(int i = 0; i < atts->NumAttributes(); ++i)
{
if(!doAll)
{
if(!atts->IsSelected(i))
{
continue;
}
}
switch(i)
{
case LCSAttributes::ID_sourceType:
// Update lots of widget visibility and enabled states.
sourceType->blockSignals(true);
sourceType->setCurrentIndex(atts->GetSourceType());
sourceType->blockSignals(false);
if (atts->GetSourceType() == LCSAttributes::RegularGrid)
{
Resolution->setEnabled(true);
ResolutionLabel->setEnabled(true);
UseDataSetStart->button(0)->setEnabled(true);
UseDataSetStart->button(1)->setEnabled(true);
UseDataSetEnd->button(0)->setEnabled(true);
UseDataSetEnd->button(1)->setEnabled(true);
StartPosition->setEnabled(atts->GetUseDataSetStart() ==
LCSAttributes::Subset);
EndPosition->setEnabled(atts->GetUseDataSetEnd() ==
LCSAttributes::Subset);
}
else
{
Resolution->setEnabled(false);
ResolutionLabel->setEnabled(false);
UseDataSetStart->button(0)->setEnabled(false);
UseDataSetStart->button(1)->setEnabled(false);
UseDataSetEnd->button(0)->setEnabled(false);
UseDataSetEnd->button(1)->setEnabled(false);
StartPosition->setEnabled(false);
EndPosition->setEnabled(false);
}
break;
case LCSAttributes::ID_Resolution:
Resolution->setText(IntsToQString(atts->GetResolution(),3));
break;
case LCSAttributes::ID_UseDataSetStart:
UseDataSetStart->blockSignals(true);
UseDataSetStart->button(atts->GetUseDataSetStart())->setChecked(true);
UseDataSetStart->blockSignals(false);
StartPosition->setEnabled(atts->GetUseDataSetStart() ==
LCSAttributes::Subset);
break;
case LCSAttributes::ID_StartPosition:
StartPosition->setText(DoublesToQString(atts->GetStartPosition(), 3));
break;
case LCSAttributes::ID_UseDataSetEnd:
UseDataSetEnd->blockSignals(true);
UseDataSetEnd->button(atts->GetUseDataSetEnd())->setChecked(true);
UseDataSetEnd->blockSignals(false);
EndPosition->setEnabled(atts->GetUseDataSetEnd() ==
LCSAttributes::Subset);
break;
case LCSAttributes::ID_EndPosition:
EndPosition->setText(DoublesToQString(atts->GetEndPosition(), 3));
break;
case LCSAttributes::ID_maxStepLength:
maxStepLength->setText(DoubleToQString(atts->GetMaxStepLength()));
break;
case LCSAttributes::ID_limitMaximumTimestep:
limitMaxTimeStep->blockSignals(true);
limitMaxTimeStep->setChecked(atts->GetLimitMaximumTimestep());
limitMaxTimeStep->blockSignals(false);
maxTimeStep->blockSignals(true);
if (atts->GetIntegrationType() ==
LCSAttributes::DormandPrince )
{
maxTimeStep->setEnabled(atts->GetLimitMaximumTimestep());
}
else
{
maxTimeStep->setEnabled(false);
}
maxTimeStep->blockSignals(false);
break;
case LCSAttributes::ID_maxTimeStep:
maxTimeStep->setText(DoubleToQString(atts->GetMaxTimeStep()));
break;
case LCSAttributes::ID_maxSteps:
maxSteps->setText(IntToQString(atts->GetMaxSteps()));
break;
case LCSAttributes::ID_terminateByDistance:
limitMaxDistance->blockSignals(true);
limitMaxDistance->setChecked(atts->GetTerminateByDistance());
limitMaxDistance->blockSignals(false);
maxDistance->setEnabled(atts->GetTerminateByDistance());
break;
case LCSAttributes::ID_terminateByTime:
limitMaxTime->blockSignals(true);
limitMaxTime->setChecked(atts->GetTerminateByTime());
limitMaxTime->blockSignals(false);
maxTime->setEnabled(atts->GetTerminateByTime());
break;
case LCSAttributes::ID_operationType:
operationType->blockSignals(true);
operationType->setCurrentIndex(int(atts->GetOperationType()) );
operationType->blockSignals(false);
if( atts->GetOperationType() == LCSAttributes::Lyapunov )
{
terminationTypeButtonGroup->blockSignals(true);
terminationTypeButtonGroup->button(0)->show();
terminationTypeButtonGroup->button(1)->show();
terminationTypeButtonGroup->button(2)->show();
cauchyGreenTensorLabel->show();
cauchyGreenTensor->show();
eigenComponent->removeItem(6);
eigenComponent->removeItem(5);
eigenComponent->removeItem(4);
eigenComponent->removeItem(3);
eigenComponentLabel->show();
eigenComponent->show();
maxSize->show();
limitMaxDistance->hide();
limitMaxTime->hide();
atts->SetTerminateByTime( atts->GetTerminationType() == LCSAttributes::Time);
atts->SetTerminateByDistance( atts->GetTerminationType() == LCSAttributes::Distance);
atts->SetTerminateBySize( atts->GetTerminationType() == LCSAttributes::Size);
// eigenWeightLabel->hide();
eigenWeightEdit->hide();
eigenWeightSlider->hide();
operatorType->hide();
clampLogValues->show();
terminationTypeButtonGroup->blockSignals(false);
}
else
{
terminationTypeButtonGroup->button(0)->hide();
terminationTypeButtonGroup->button(1)->hide();
terminationTypeButtonGroup->button(2)->hide();
if( atts->GetOperationType() == LCSAttributes::EigenVector )
{
if( eigenComponent->itemText(3).isNull() ||
eigenComponent->itemText(3).isEmpty() )
{
eigenComponent->addItem(tr("Shear Pos."));
eigenComponent->addItem(tr("Shear Neg."));
eigenComponent->addItem(tr("Lambda Shear Pos."));
eigenComponent->addItem(tr("Lambda Shear Neg."));
}
bval = (atts->GetEigenComponent() ==
LCSAttributes::PosLambdaShearVector ||
atts->GetEigenComponent() ==
LCSAttributes::NegLambdaShearVector);
if( bval )
{
// eigenWeightLabel->show();
eigenWeightEdit->show();
eigenWeightSlider->show();
}
else
{
// eigenWeightLabel->hide();
eigenWeightEdit->hide();
eigenWeightSlider->hide();
}
// eigenWeightLabel->setEnabled( bval );
eigenWeightEdit->setEnabled( bval );
eigenWeightSlider->setEnabled( bval );
}
else
{
if( !(eigenComponent->itemText(3).isNull()) &&
!(eigenComponent->itemText(3).isEmpty()) )
{
eigenComponent->removeItem(6);
eigenComponent->removeItem(5);
eigenComponent->removeItem(4);
eigenComponent->removeItem(3);
}
// eigenWeightLabel->hide();
eigenWeightEdit->hide();
eigenWeightSlider->hide();
}
if( atts->GetOperationType() == LCSAttributes::EigenValue ||
atts->GetOperationType() == LCSAttributes::EigenVector )
{
cauchyGreenTensorLabel->show();
cauchyGreenTensor->show();
eigenComponentLabel->show();
eigenComponent->show();
operatorType->hide();
}
else
{
cauchyGreenTensorLabel->hide();
cauchyGreenTensor->hide();
eigenComponentLabel->hide();
eigenComponent->hide();
operatorType->show();
}
maxSize->hide();
limitMaxDistance->show();
limitMaxTime->show();
if( atts->GetOperatorType() == LCSAttributes::BaseValue)
clampLogValues->hide();
else
clampLogValues->show();
}
break;
case LCSAttributes::ID_cauchyGreenTensor:
cauchyGreenTensor->blockSignals(true);
cauchyGreenTensor->setCurrentIndex(int(atts->GetCauchyGreenTensor()) );
cauchyGreenTensor->blockSignals(false);
break;
case LCSAttributes::ID_eigenComponent:
eigenComponent->blockSignals(true);
eigenComponent->setCurrentIndex(int(atts->GetEigenComponent()) );
eigenComponent->blockSignals(false);
bval = (atts->GetEigenComponent() ==
LCSAttributes::PosLambdaShearVector ||
atts->GetEigenComponent() ==
LCSAttributes::NegLambdaShearVector);
if( bval )
{
// eigenWeightLabel->show();
eigenWeightEdit->show();
eigenWeightSlider->show();
}
else
{
// eigenWeightLabel->hide();
eigenWeightEdit->hide();
eigenWeightSlider->hide();
}
// eigenWeightLabel->setEnabled( bval );
eigenWeightEdit->setEnabled( bval );
eigenWeightSlider->setEnabled( bval );
break;
case LCSAttributes::ID_operatorType:
operatorType->blockSignals(true);
operatorType->setCurrentIndex(int(atts->GetOperatorType()) );
operatorType->blockSignals(false);
if( atts->GetOperationType() == LCSAttributes::Lyapunov ||
atts->GetOperatorType() == LCSAttributes::Gradient)
clampLogValues->show();
else
clampLogValues->hide();
break;
case LCSAttributes::ID_eigenWeight:
eigenWeightEdit->setText(DoubleToQString(atts->GetEigenWeight()));
ival =
int(qMin(qMax(-100.0,1000.0*(atts->GetEigenWeight()-1.0)),100.0));
eigenWeightSlider->blockSignals(true);
eigenWeightSlider->setValue(ival);
eigenWeightSlider->blockSignals(false);
break;
case LCSAttributes::ID_clampLogValues:
clampLogValues->blockSignals(true);
clampLogValues->setChecked(atts->GetClampLogValues());
clampLogValues->blockSignals(false);
break;
case LCSAttributes::ID_terminationType:
terminationTypeButtonGroup->blockSignals(true);
terminationTypeButtonGroup->button(atts->GetTerminationType())->setChecked(true);
terminationTypeButtonGroup->blockSignals(false);
maxTime->setEnabled(atts->GetTerminationType() == LCSAttributes::Time);
maxDistance->setEnabled(atts->GetTerminationType() == LCSAttributes::Distance);
maxSize->setEnabled(atts->GetTerminationType() == LCSAttributes::Size);
break;
case LCSAttributes::ID_termSize:
maxSize->setText(DoubleToQString(atts->GetTermSize()));
break;
case LCSAttributes::ID_termDistance:
maxDistance->setText(DoubleToQString(atts->GetTermDistance()));
break;
case LCSAttributes::ID_termTime:
maxTime->setText(DoubleToQString(atts->GetTermTime()));
break;
case LCSAttributes::ID_velocitySource:
velocitySource->setText(DoublesToQString(atts->GetVelocitySource(),3));
break;
case LCSAttributes::ID_integrationDirection:
directionType->blockSignals(true);
directionType->setCurrentIndex(int(atts->GetIntegrationDirection()) );
directionType->blockSignals(false);
break;
case LCSAttributes::ID_relTol:
relTol->setText(DoubleToQString(atts->GetRelTol()));
break;
case LCSAttributes::ID_absTolSizeType:
absTolSizeType->blockSignals(true);
absTolSizeType->setCurrentIndex((int) atts->GetAbsTolSizeType());
absTolSizeType->blockSignals(false);
if (atts->GetAbsTolSizeType() == LCSAttributes::FractionOfBBox)
{
absTol->setText(DoubleToQString(atts->GetAbsTolBBox()));
}
if (atts->GetAbsTolSizeType() == LCSAttributes::Absolute)
{
absTol->setText(DoubleToQString(atts->GetAbsTolAbsolute()));
}
break;
case LCSAttributes::ID_absTolBBox:
if (atts->GetAbsTolSizeType() == LCSAttributes::FractionOfBBox)
{
absTol->setText(DoubleToQString(atts->GetAbsTolBBox()));
}
break;
case LCSAttributes::ID_absTolAbsolute:
if (atts->GetAbsTolSizeType() == LCSAttributes::Absolute)
{
absTol->setText(DoubleToQString(atts->GetAbsTolAbsolute()));
}
break;
case LCSAttributes::ID_auxiliaryGrid:
auxiliaryGrid->blockSignals(true);
auxiliaryGrid->setCurrentIndex(atts->GetAuxiliaryGrid());
auxiliaryGrid->blockSignals(false);
auxiliaryGridSpacingLabel->setEnabled(!(atts->GetAuxiliaryGrid() ==
LCSAttributes::None));
auxiliaryGridSpacing->setEnabled(!(atts->GetAuxiliaryGrid() ==
LCSAttributes::None));
break;
case LCSAttributes::ID_auxiliaryGridSpacing:
auxiliaryGridSpacing->setText(DoubleToQString(atts->GetAuxiliaryGridSpacing()));
break;
case LCSAttributes::ID_fieldType:
// Update lots of widget visibility and enabled states.
UpdateFieldAttributes();
fieldType->blockSignals(true);
fieldType->setCurrentIndex(atts->GetFieldType());
fieldType->blockSignals(false);
integrationType->blockSignals(true);
if (atts->GetFieldType() == LCSAttributes::M3DC12DField)
{
atts->SetIntegrationType(LCSAttributes::M3DC12DIntegrator);
integrationType->setCurrentIndex(LCSAttributes::M3DC12DIntegrator);
UpdateIntegrationAttributes();
}
else if (atts->GetIntegrationType() == LCSAttributes::M3DC12DIntegrator)
{
atts->SetIntegrationType(LCSAttributes::DormandPrince);
integrationType->setCurrentIndex(LCSAttributes::DormandPrince);
UpdateIntegrationAttributes();
}
integrationType->blockSignals(false);
break;
case LCSAttributes::ID_fieldConstant:
fieldConstant->setText(DoubleToQString(atts->GetFieldConstant()));
break;
case LCSAttributes::ID_integrationType:
// Update lots of widget visibility and enabled states.
UpdateIntegrationAttributes();
integrationType->blockSignals(true);
integrationType->setCurrentIndex(atts->GetIntegrationType());
integrationType->blockSignals(false);
fieldType->blockSignals(true);
if (atts->GetIntegrationType() == LCSAttributes::M3DC12DIntegrator)
{
atts->SetFieldType(LCSAttributes::M3DC12DField);
fieldType->setCurrentIndex(LCSAttributes::M3DC12DField);
UpdateFieldAttributes();
}
else if (atts->GetFieldType() == LCSAttributes::M3DC12DField)
{
atts->SetFieldType(LCSAttributes::Default);
fieldType->setCurrentIndex(LCSAttributes::Default);
UpdateFieldAttributes();
}
fieldType->blockSignals(false);
break;
case LCSAttributes::ID_thresholdLimit:
thresholdLimit->setText(DoubleToQString(atts->GetThresholdLimit()));
break;
case LCSAttributes::ID_radialLimit:
radialLimit->setText(DoubleToQString(atts->GetRadialLimit()));
break;
case LCSAttributes::ID_boundaryLimit:
boundaryLimit->setText(DoubleToQString(atts->GetBoundaryLimit()));
break;
case LCSAttributes::ID_seedLimit:
seedLimit->blockSignals(true);
seedLimit->setValue(atts->GetSeedLimit());
seedLimit->blockSignals(false);
break;
case LCSAttributes::ID_parallelizationAlgorithmType:
// Update lots of widget visibility and enabled states.
UpdateAlgorithmAttributes();
parallelAlgo->blockSignals(true);
parallelAlgo->setCurrentIndex(atts->GetParallelizationAlgorithmType());
parallelAlgo->blockSignals(false);
break;
case LCSAttributes::ID_maxProcessCount:
maxSLCount->blockSignals(true);
maxSLCount->setValue(atts->GetMaxProcessCount());
maxSLCount->blockSignals(false);
break;
case LCSAttributes::ID_maxDomainCacheSize:
maxDomainCache->blockSignals(true);
maxDomainCache->setValue(atts->GetMaxDomainCacheSize());
maxDomainCache->blockSignals(false);
break;
case LCSAttributes::ID_workGroupSize:
workGroupSize->blockSignals(true);
workGroupSize->setValue(atts->GetWorkGroupSize());
workGroupSize->blockSignals(false);
break;
case LCSAttributes::ID_pathlines:
icButtonGroup->blockSignals(true);
icButtonGroup->button(atts->GetPathlines()?1:0)->setChecked(true);
pathlineOverrideStartingTimeFlag->setEnabled(atts->GetPathlines());
if( pathlineOverrideStartingTimeFlag->isChecked() && ! icButtonGroup->button(1)->isChecked() )
pathlineOverrideStartingTimeFlag->setChecked(false);
pathlineOverrideStartingTime->setEnabled(atts->GetPathlines() && atts->GetPathlinesOverrideStartingTimeFlag());
pathlinePeriod->setEnabled(atts->GetPathlines());
pathlineCMFEButtonGroup->button(0)->setEnabled(atts->GetPathlines());
pathlineCMFEButtonGroup->button(1)->setEnabled(atts->GetPathlines());
icButtonGroup->blockSignals(false);
break;
case LCSAttributes::ID_pathlinesOverrideStartingTimeFlag:
pathlineOverrideStartingTimeFlag->blockSignals(true);
pathlineOverrideStartingTimeFlag->setChecked(atts->GetPathlinesOverrideStartingTimeFlag());
pathlineOverrideStartingTime->setEnabled(atts->GetPathlines() && atts->GetPathlinesOverrideStartingTimeFlag());
pathlineOverrideStartingTimeFlag->blockSignals(false);
break;
case LCSAttributes::ID_pathlinesOverrideStartingTime:
pathlineOverrideStartingTime->setText(DoubleToQString(atts->GetPathlinesOverrideStartingTime()));
break;
case LCSAttributes::ID_pathlinesPeriod:
pathlinePeriod->setText(DoubleToQString(atts->GetPathlinesPeriod()));
break;
case LCSAttributes::ID_pathlinesCMFE:
pathlineCMFEButtonGroup->blockSignals(true);
pathlineCMFEButtonGroup->button(atts->GetPathlinesCMFE())->setChecked(true);
pathlineCMFEButtonGroup->blockSignals(false);
break;
// case LCSAttributes::ID_forceNodeCenteredData:
// forceNodal->blockSignals(true);
// forceNodal->setChecked(atts->GetForceNodeCenteredData());
// forceNodal->blockSignals(false);
// break;
case LCSAttributes::ID_issueAdvectionWarnings:
issueWarningForAdvection->blockSignals(true);
issueWarningForAdvection->setChecked(atts->GetIssueAdvectionWarnings());
issueWarningForAdvection->blockSignals(false);
break;
case LCSAttributes::ID_issueBoundaryWarnings:
issueWarningForBoundary->blockSignals(true);
issueWarningForBoundary->setChecked(atts->GetIssueBoundaryWarnings());
issueWarningForBoundary->blockSignals(false);
break;
case LCSAttributes::ID_issueTerminationWarnings:
issueWarningForMaxSteps->blockSignals(true);
issueWarningForMaxSteps->setChecked(atts->GetIssueTerminationWarnings());
issueWarningForMaxSteps->blockSignals(false);
break;
case LCSAttributes::ID_issueCriticalPointsWarnings:
issueWarningForCriticalPoints->blockSignals(true);
issueWarningForCriticalPoints->setChecked(atts->GetIssueCriticalPointsWarnings());
criticalPointThreshold->setEnabled(atts->GetIssueCriticalPointsWarnings());
criticalPointThresholdLabel->setEnabled(atts->GetIssueCriticalPointsWarnings());
issueWarningForCriticalPoints->blockSignals(false);
break;
case LCSAttributes::ID_issueStepsizeWarnings:
issueWarningForStepsize->blockSignals(true);
issueWarningForStepsize->setChecked(atts->GetIssueStepsizeWarnings());
issueWarningForStepsize->blockSignals(false);
break;
case LCSAttributes::ID_issueStiffnessWarnings:
issueWarningForStiffness->blockSignals(true);
issueWarningForStiffness->setChecked(atts->GetIssueStiffnessWarnings());
issueWarningForStiffness->blockSignals(false);
break;
case LCSAttributes::ID_criticalPointThreshold:
criticalPointThreshold->setText(DoubleToQString(atts->GetCriticalPointThreshold()));
break;
}
}
}
// ****************************************************************************
// Method: QvisLCSWindow::UpdateFieldAttributes
//
// Purpose:
// Updates the widgets for the various field types.
//
// Programmer: Dave Pugmire
// Creation: Thu Jul 31 14:41:00 EDT 2008
//
// ****************************************************************************
void
QvisLCSWindow::UpdateFieldAttributes()
{
switch( atts->GetFieldType() )
{
case LCSAttributes::M3DC12DField:
if( atts->GetIntegrationType() ==
LCSAttributes::M3DC12DIntegrator )
TurnOn(fieldConstant, fieldConstantLabel);
else
TurnOff(fieldConstant, fieldConstantLabel);
TurnOff(velocitySource, velocitySourceLabel);
break;
case LCSAttributes::FlashField:
TurnOn(fieldConstant, fieldConstantLabel);
TurnOn(velocitySource, velocitySourceLabel);
break;
default:
TurnOff(fieldConstant, fieldConstantLabel);
TurnOff(velocitySource, velocitySourceLabel);
break;
}
}
// ****************************************************************************
// Method: QvisLCSWindow::UpdateIntegrationAttributes
//
// Purpose:
// Updates the widgets for the various integration types.
//
// Programmer: Dave Pugmire
// Creation: Thu Jul 31 14:41:00 EDT 2008
//
// Modifications:
//
// ****************************************************************************
void
QvisLCSWindow::UpdateIntegrationAttributes()
{
//Turn off everything.
maxStepLength->hide();
maxStepLengthLabel->hide();
limitMaxTimeStep->hide();
maxTimeStep->hide();
relTol->hide();
relTolLabel->hide();
absTol->hide();
absTolLabel->hide();
absTolSizeType->hide();
switch( atts->GetIntegrationType() )
{
case LCSAttributes::Euler:
case LCSAttributes::Leapfrog:
case LCSAttributes::RK4:
maxStepLength->show();
maxStepLengthLabel->show();
break;
case LCSAttributes::DormandPrince:
limitMaxTimeStep->show();
maxTimeStep->show();
relTol->show();
relTolLabel->show();
absTol->show();
absTolLabel->show();
absTolSizeType->show();
break;
case LCSAttributes::AdamsBashforth:
case LCSAttributes::M3DC12DIntegrator:
maxStepLength->show();
maxStepLengthLabel->show();
absTol->show();
absTolLabel->show();
absTolSizeType->show();
break;
default:
break;
}
}
// ****************************************************************************
// Method: QvisLCSWindow::UpdateAlgorithmAttributes
//
// Purpose:
// Updates the widgets for the various integration types.
//
// Programmer: Dave Pugmire
// Creation: Fri Aug 1 16:41:38 EDT 2008
//
//
// Modifications:
//
// ****************************************************************************
void
QvisLCSWindow::UpdateAlgorithmAttributes()
{
bool useLoadOnDemand = (atts->GetParallelizationAlgorithmType() ==
LCSAttributes::LoadOnDemand);
bool useStaticDomains = (atts->GetParallelizationAlgorithmType() ==
LCSAttributes::ParallelStaticDomains);
bool useMasterSlave = (atts->GetParallelizationAlgorithmType() ==
LCSAttributes::MasterSlave);
//Turn off everything.
maxDomainCacheLabel->hide();
maxDomainCache->hide();
maxSLCountLabel->hide();
maxSLCount->hide();
workGroupSizeLabel->hide();
workGroupSize->hide();
if ( useLoadOnDemand )
{
maxDomainCacheLabel->show();
maxDomainCache->show();
}
else if ( useStaticDomains )
{
maxSLCountLabel->show();
maxSLCount->show();
}
else if (useMasterSlave)
{
maxDomainCacheLabel->show();
maxDomainCache->show();
maxSLCountLabel->show();
maxSLCount->show();
workGroupSizeLabel->show();
workGroupSize->show();
}
}
// ****************************************************************************
// Method: QvisLCSWindow::GetCurrentValues
//
// Purpose:
// Gets values from certain widgets and stores them in the subject.
//
// Programmer: Brad Whitlock
// Creation: Mon Oct 21 14:19:00 PST 2002
//
// Modifications:
// Kathleen Biagas, Wed Jun 8 17:10:30 PDT 2016
// Ensure values are retrieved from spin boxes.
//
// ****************************************************************************
void
QvisLCSWindow::GetCurrentValues(int which_widget)
{
bool doAll = (which_widget == -1);
QString msg;
// Do resolution
if(which_widget == LCSAttributes::ID_Resolution || doAll)
{
int val[3];
if(LineEditGetInts(Resolution, val, 3))
atts->SetResolution(val);
else
{
ResettingError(tr("Resolution"),
IntsToQString(atts->GetResolution(), 3));
atts->SetResolution(atts->GetResolution());
}
}
// Do Start Position
if(which_widget == LCSAttributes::ID_StartPosition || doAll)
{
double val[3];
if(LineEditGetDoubles(StartPosition, val, 3))
atts->SetStartPosition(val);
else
{
ResettingError(tr("StartPosition"),
DoublesToQString(atts->GetStartPosition(), 3));
atts->SetStartPosition(atts->GetStartPosition());
}
}
// Do End Position
if(which_widget == LCSAttributes::ID_EndPosition || doAll)
{
double val[3];
if(LineEditGetDoubles(EndPosition, val, 3))
atts->SetEndPosition(val);
else
{
ResettingError(tr("EndPosition"),
DoublesToQString(atts->GetEndPosition(), 3));
atts->SetEndPosition(atts->GetEndPosition());
}
}
// Do auxiliaryGridSpacing
if(which_widget == LCSAttributes::ID_auxiliaryGridSpacing || doAll)
{
double val;
if(LineEditGetDouble(auxiliaryGridSpacing, val))
atts->SetAuxiliaryGridSpacing(val);
else
{
ResettingError(tr("auxiliary grid spacing"),
DoubleToQString(atts->GetAuxiliaryGridSpacing()));
atts->SetAuxiliaryGridSpacing(atts->GetAuxiliaryGridSpacing());
}
}
// Do fieldConstant
if(which_widget == LCSAttributes::ID_fieldConstant || doAll)
{
double val;
if(LineEditGetDouble(fieldConstant, val))
atts->SetFieldConstant(val);
else
{
ResettingError(tr("field constant"),
DoubleToQString(atts->GetFieldConstant()));
atts->SetFieldConstant(atts->GetFieldConstant());
}
}
// Do stepLength
if(which_widget == LCSAttributes::ID_maxStepLength || doAll)
{
double val;
if(LineEditGetDouble(maxStepLength, val))
atts->SetMaxStepLength(val);
else
{
ResettingError(tr("step length"),
DoubleToQString(atts->GetMaxStepLength()));
atts->SetMaxStepLength(atts->GetMaxStepLength());
}
}
// Do max time step
if(which_widget == LCSAttributes::ID_maxTimeStep || doAll)
{
double val;
if(LineEditGetDouble(maxTimeStep, val))
atts->SetMaxTimeStep(val);
else
{
ResettingError(tr("step length"),
DoubleToQString(atts->GetMaxTimeStep()));
atts->SetMaxTimeStep(atts->GetMaxTimeStep());
}
}
// Do termination
if(which_widget == LCSAttributes::ID_eigenWeight || doAll)
{
double val;
if(LineEditGetDouble(eigenWeightEdit, val) && 0.9 <= val && val <= 1.1)
atts->SetEigenWeight(val);
else
{
ResettingError(tr("eigen weight"),
DoubleToQString(atts->GetEigenWeight()));
atts->SetEigenWeight(atts->GetEigenWeight());
}
}
if(which_widget == LCSAttributes::ID_maxSteps || doAll)
{
int val;
if(LineEditGetInt(maxSteps, val))
atts->SetMaxSteps(val);
else
{
ResettingError(tr("max steps"),
IntToQString(atts->GetMaxSteps()));
atts->SetMaxSteps(atts->GetMaxSteps());
}
}
if(which_widget == LCSAttributes::ID_termTime || doAll)
{
double val;
if(LineEditGetDouble(maxTime, val))
atts->SetTermTime(val);
else
{
ResettingError(tr("max time"),
DoubleToQString(atts->GetTermTime()));
atts->SetTermTime(atts->GetTermTime());
}
}
if(which_widget == LCSAttributes::ID_termDistance || doAll)
{
double val;
if(LineEditGetDouble(maxDistance, val))
atts->SetTermDistance(val);
else
{
ResettingError(tr("max distance"),
DoubleToQString(atts->GetTermDistance()));
atts->SetTermDistance(atts->GetTermDistance());
}
}
if(which_widget == LCSAttributes::ID_termSize || doAll)
{
double val;
if(LineEditGetDouble(maxSize, val))
atts->SetTermSize(val);
else
{
ResettingError(tr("max size"),
DoubleToQString(atts->GetTermSize()));
atts->SetTermSize(atts->GetTermSize());
}
}
if(which_widget == LCSAttributes::ID_pathlinesOverrideStartingTime || doAll)
{
double val;
if(LineEditGetDouble(pathlineOverrideStartingTime, val))
atts->SetPathlinesOverrideStartingTime(val);
else
{
ResettingError(tr("Pathlines Override Starting Time"),
DoubleToQString(atts->GetPathlinesOverrideStartingTime()));
atts->SetPathlinesOverrideStartingTime(atts->GetPathlinesOverrideStartingTime());
}
}
if(which_widget == LCSAttributes::ID_pathlinesPeriod || doAll)
{
double val;
if(LineEditGetDouble(pathlinePeriod, val))
atts->SetPathlinesPeriod(val);
else
{
ResettingError(tr("Pathlines Period"),
DoubleToQString(atts->GetPathlinesPeriod()));
atts->SetPathlinesPeriod(atts->GetPathlinesPeriod());
}
}
// Do relTol
if(which_widget == LCSAttributes::ID_relTol || doAll)
{
double val;
if(LineEditGetDouble(relTol, val))
atts->SetRelTol(val);
else
{
ResettingError(tr("relative tolerance"),
DoubleToQString(atts->GetRelTol()));
atts->SetRelTol(atts->GetRelTol());
}
}
// Do absTol
if ((which_widget == LCSAttributes::ID_absTolBBox || doAll)
&& atts->GetAbsTolSizeType() == LCSAttributes::FractionOfBBox)
{
double val;
if(LineEditGetDouble(absTol, val))
atts->SetAbsTolBBox(val);
else
{
ResettingError(tr("absolute tolerance"),
DoubleToQString(atts->GetAbsTolBBox()));
atts->SetAbsTolBBox(atts->GetAbsTolBBox());
}
}
if ((which_widget == LCSAttributes::ID_absTolAbsolute || doAll)
&& atts->GetAbsTolSizeType() == LCSAttributes::Absolute)
{
double val;
if(LineEditGetDouble(absTol, val))
atts->SetAbsTolAbsolute(val);
else
{
ResettingError(tr("absolute tolerance"),
DoubleToQString(atts->GetAbsTolAbsolute()));
atts->SetAbsTolAbsolute(atts->GetAbsTolAbsolute());
}
}
// Do velocitySource
if(which_widget == LCSAttributes::ID_velocitySource || doAll)
{
double val[3];
if(LineEditGetDoubles(velocitySource, val, 3))
atts->SetVelocitySource(val);
else
{
ResettingError(tr("velocity source"),
DoublesToQString(atts->GetVelocitySource(), 3));
atts->SetVelocitySource(atts->GetVelocitySource());
}
}
if(which_widget == LCSAttributes::ID_thresholdLimit || doAll)
{
double val;
if(LineEditGetDouble(thresholdLimit, val))
atts->SetThresholdLimit(val);
else
{
ResettingError(tr("Threshold Limit"),
DoubleToQString(atts->GetThresholdLimit()));
atts->SetThresholdLimit(atts->GetThresholdLimit());
}
}
if(which_widget == LCSAttributes::ID_radialLimit || doAll)
{
double val;
if(LineEditGetDouble(radialLimit, val))
atts->SetRadialLimit(val);
else
{
ResettingError(tr("Radial Limit"),
DoubleToQString(atts->GetRadialLimit()));
atts->SetRadialLimit(atts->GetRadialLimit());
}
}
if(which_widget == LCSAttributes::ID_boundaryLimit || doAll)
{
double val;
if(LineEditGetDouble(boundaryLimit, val))
atts->SetBoundaryLimit(val);
else
{
ResettingError(tr("Boundary Limit"),
DoubleToQString(atts->GetBoundaryLimit()));
atts->SetBoundaryLimit(atts->GetBoundaryLimit());
}
}
// seedLimit
if (which_widget == LCSAttributes::ID_seedLimit || doAll)
{
// This can only be an integer, so no error checking is needed.
int val = seedLimit->value();
if (val >= 0)
atts->SetSeedLimit(val);
}
// maxProcessCount
if (which_widget == LCSAttributes::ID_maxProcessCount || doAll)
{
// This can only be an integer, so no error checking is needed.
int val = maxSLCount->value();
if (val >= 1)
atts->SetMaxProcessCount(val);
}
// workGroupSize
if (which_widget == LCSAttributes::ID_workGroupSize || doAll)
{
// This can only be an integer, so no error checking is needed.
int val = workGroupSize->value();
if (val >= 2)
atts->SetWorkGroupSize(val);
}
// criticalPointThreshold
if(which_widget == LCSAttributes::ID_criticalPointThreshold || doAll)
{
double val;
if(LineEditGetDouble(criticalPointThreshold, val))
atts->SetCriticalPointThreshold(val);
else
{
ResettingError(tr("Speed cutoff for critical points"),
DoubleToQString(atts->GetCriticalPointThreshold()));
atts->SetCriticalPointThreshold(atts->GetCriticalPointThreshold());
}
}
// maxDomainCache
if (which_widget == LCSAttributes::ID_maxDomainCacheSize || doAll)
{
if (maxDomainCache->value() != atts->GetMaxDomainCacheSize())
atts->SetMaxDomainCacheSize(maxDomainCache->value());
}
}
void
QvisLCSWindow::sourceTypeChanged(int val)
{
if(val != atts->GetSourceType())
{
atts->SetSourceType(LCSAttributes::SourceType(val));
Apply();
}
}
void
QvisLCSWindow::ResolutionProcessText()
{
GetCurrentValues(LCSAttributes::ID_Resolution);
Apply();
}
void
QvisLCSWindow::UseDataSetStartChanged(int val)
{
atts->SetUseDataSetStart(LCSAttributes::Extents(val));
Apply();
}
void
QvisLCSWindow::StartPositionProcessText()
{
GetCurrentValues(LCSAttributes::ID_StartPosition);
Apply();
}
void
QvisLCSWindow::UseDataSetEndChanged(int val)
{
atts->SetUseDataSetEnd(LCSAttributes::Extents(val));
Apply();
}
void
QvisLCSWindow::EndPositionProcessText()
{
GetCurrentValues(LCSAttributes::ID_EndPosition);
Apply();
}
void
QvisLCSWindow::directionTypeChanged(int val)
{
if(val != atts->GetIntegrationDirection())
{
atts->SetIntegrationDirection(LCSAttributes::IntegrationDirection(val));
Apply();
}
}
void
QvisLCSWindow::fieldTypeChanged(int val)
{
if(val != atts->GetFieldType())
{
atts->SetFieldType(LCSAttributes::FieldType(val));
Apply();
}
}
void
QvisLCSWindow::fieldConstantProcessText()
{
GetCurrentValues(LCSAttributes::ID_fieldConstant);
Apply();
}
void
QvisLCSWindow::auxiliaryGridChanged(int val)
{
if(val != atts->GetAuxiliaryGrid())
{
atts->SetAuxiliaryGrid(LCSAttributes::AuxiliaryGrid(val));
Apply();
}
}
void
QvisLCSWindow::auxiliaryGridSpacingProcessText()
{
GetCurrentValues(LCSAttributes::ID_auxiliaryGridSpacing);
Apply();
}
void
QvisLCSWindow::integrationTypeChanged(int val)
{
if(val != atts->GetIntegrationType())
{
atts->SetIntegrationType(LCSAttributes::IntegrationType(val));
Apply();
}
}
void
QvisLCSWindow::parallelAlgorithmChanged(int val)
{
if(val != atts->GetParallelizationAlgorithmType())
{
atts->SetParallelizationAlgorithmType(LCSAttributes::ParallelizationAlgorithmType(val));
Apply();
}
}
void
QvisLCSWindow::maxStepLengthProcessText()
{
GetCurrentValues(LCSAttributes::ID_maxStepLength);
Apply();
}
void
QvisLCSWindow::maxTimeStepProcessText()
{
GetCurrentValues(LCSAttributes::ID_maxTimeStep);
Apply();
}
void
QvisLCSWindow::maxStepsProcessText()
{
GetCurrentValues(LCSAttributes::ID_maxSteps);
Apply();
}
void
QvisLCSWindow::limitMaxTimeChanged(bool val)
{
if(val != atts->GetTerminateByTime())
{
atts->SetTerminateByTime(val);
Apply();
}
}
void
QvisLCSWindow::limitMaxDistanceChanged(bool val)
{
if(val != atts->GetTerminateByDistance())
{
atts->SetTerminateByDistance(val);
Apply();
}
}
void
QvisLCSWindow::operationTypeChanged(int val)
{
if(val != atts->GetOperationType())
{
atts->SetOperationType(LCSAttributes::OperationType(val));
Apply();
}
}
void
QvisLCSWindow::cauchyGreenTensorChanged(int val)
{
if(val != atts->GetCauchyGreenTensor())
{
atts->SetCauchyGreenTensor(LCSAttributes::CauchyGreenTensor(val));
Apply();
}
}
void
QvisLCSWindow::eigenComponentChanged(int val)
{
if(val != atts->GetEigenComponent())
{
atts->SetEigenComponent(LCSAttributes::EigenComponent(val));
Apply();
}
}
void
QvisLCSWindow::operatorTypeChanged(int val)
{
if(val != atts->GetOperatorType())
{
atts->SetOperatorType(LCSAttributes::OperatorType(val));
Apply();
}
}
void
QvisLCSWindow::eigenWeightEditProcessText()
{
GetCurrentValues(LCSAttributes::ID_eigenWeight);
Apply();
}
void
QvisLCSWindow::eigenWeightSliderChanged(int val)
{
atts->SetEigenWeight( 1.0 + (double) val/1000.0 );
eigenWeightEdit->setText(DoubleToQString( (double) 1.0 + val/1000.0 ) );
if (!sliderDragging)
Apply();
}
void
QvisLCSWindow::eigenWeightSliderPressed()
{
sliderDragging = true;
}
void
QvisLCSWindow::eigenWeightSliderReleased()
{
sliderDragging = false;
Apply();
}
void
QvisLCSWindow::clampLogValuesChanged(bool val)
{
atts->SetClampLogValues(val);
Apply();
}
void
QvisLCSWindow::terminationTypeButtonGroupChanged(int index)
{
atts->SetTerminationType( (LCSAttributes::TerminationType) index );
atts->SetTerminateByTime( index == 0);
atts->SetTerminateByDistance( index == 1);
atts->SetTerminateBySize( index == 2);
Apply();
}
void
QvisLCSWindow::maxTimeProcessText()
{
GetCurrentValues(LCSAttributes::ID_termTime);
Apply();
}
void
QvisLCSWindow::maxDistanceProcessText()
{
GetCurrentValues(LCSAttributes::ID_termDistance);
Apply();
}
void
QvisLCSWindow::maxSizeProcessText()
{
GetCurrentValues(LCSAttributes::ID_termSize);
Apply();
}
void
QvisLCSWindow::relTolProcessText()
{
GetCurrentValues(LCSAttributes::ID_relTol);
Apply();
}
void
QvisLCSWindow::thresholdLimitProcessText()
{
GetCurrentValues(LCSAttributes::ID_thresholdLimit);
Apply();
}
void
QvisLCSWindow::radialLimitProcessText()
{
GetCurrentValues(LCSAttributes::ID_radialLimit);
Apply();
}
void
QvisLCSWindow::boundaryLimitProcessText()
{
GetCurrentValues(LCSAttributes::ID_boundaryLimit);
Apply();
}
void
QvisLCSWindow::seedLimitChanged(int val)
{
atts->SetSeedLimit(val);
Apply();
}
void
QvisLCSWindow::maxSLCountChanged(int val)
{
atts->SetMaxProcessCount(val);
Apply();
}
void
QvisLCSWindow::maxDomainCacheChanged(int val)
{
atts->SetMaxDomainCacheSize(val);
Apply();
}
void
QvisLCSWindow::workGroupSizeChanged(int val)
{
atts->SetWorkGroupSize(val);
Apply();
}
void
QvisLCSWindow::icButtonGroupChanged(int val)
{
switch( val )
{
case 0: // Streamline
atts->SetPathlines(false);
break;
case 1: // Pathline
atts->SetPathlines(true);
break;
}
Apply();
}
void
QvisLCSWindow::pathlineOverrideStartingTimeFlagChanged(bool val)
{
atts->SetPathlinesOverrideStartingTimeFlag(val);
Apply();
}
void
QvisLCSWindow::pathlineOverrideStartingTimeProcessText()
{
GetCurrentValues(LCSAttributes::ID_pathlinesOverrideStartingTime);
Apply();
}
void
QvisLCSWindow::pathlinePeriodProcessText()
{
GetCurrentValues(LCSAttributes::ID_pathlinesPeriod);
Apply();
}
void
QvisLCSWindow::pathlineCMFEButtonGroupChanged(int val)
{
atts->SetPathlinesCMFE((LCSAttributes::PathlinesCMFE)val);
Apply();
}
void
QvisLCSWindow::absTolProcessText()
{
GetCurrentValues(LCSAttributes::ID_absTolBBox);
GetCurrentValues(LCSAttributes::ID_absTolAbsolute);
Apply();
}
void
QvisLCSWindow::absTolSizeTypeChanged(int val)
{
atts->SetAbsTolSizeType((LCSAttributes::SizeType) val);
Apply();
}
void
QvisLCSWindow::limitMaxTimeStepChanged(bool val)
{
atts->SetLimitMaximumTimestep(val);
Apply();
}
// void
// QvisLCSWindow::forceNodalChanged(bool val)
// {
// atts->SetForceNodeCenteredData(val);
// Apply();
// }
void
QvisLCSWindow::velocitySourceProcessText()
{
GetCurrentValues(LCSAttributes::ID_velocitySource);
Apply();
}
void
QvisLCSWindow::issueWarningForAdvectionChanged(bool val)
{
atts->SetIssueAdvectionWarnings(val);
Apply();
}
void
QvisLCSWindow::issueWarningForBoundaryChanged(bool val)
{
atts->SetIssueBoundaryWarnings(val);
Apply();
}
void
QvisLCSWindow::issueWarningForMaxStepsChanged(bool val)
{
atts->SetIssueTerminationWarnings(val);
Apply();
}
void
QvisLCSWindow::issueWarningForStepsizeChanged(bool val)
{
atts->SetIssueStepsizeWarnings(val);
Apply();
}
void
QvisLCSWindow::issueWarningForStiffnessChanged(bool val)
{
atts->SetIssueStiffnessWarnings(val);
Apply();
}
void
QvisLCSWindow::issueWarningForCriticalPointsChanged(bool val)
{
atts->SetIssueCriticalPointsWarnings(val);
Apply();
}
void
QvisLCSWindow::criticalPointThresholdProcessText(void)
{
GetCurrentValues(LCSAttributes::ID_criticalPointThreshold);
Apply();
}
static void
TurnOn(QWidget *w0, QWidget *w1)
{
if (w0)
{
w0->setEnabled(true);
w0->show();
}
if (w1)
{
w1->setEnabled(true);
w1->show();
}
}
static void
TurnOff(QWidget *w0, QWidget *w1)
{
if (w0)
{
w0->setEnabled(false);
w0->hide();
}
if (w1)
{
w1->setEnabled(false);
w1->hide();
}
}
|
f58a3701b2b31268ef4f12c4304cb3b2998432f8
|
cf60f9591fef521d3092f81785de7942d0ca568e
|
/PubNub/include/PNPresenceWhereNowParser.h
|
ca80c5509e0dda74c06e2cd780db06526121baa2
|
[
"MIT"
] |
permissive
|
pubnub/objective-c
|
a49e2e5c7898eb893b601ae31a098361fb8b4406
|
eef06ae76fd45931ea09900e3b3ce50133870eca
|
refs/heads/master
| 2023-04-07T08:28:47.174178
| 2023-01-05T11:15:57
| 2023-01-05T11:15:57
| 8,490,984
| 137
| 145
|
NOASSERTION
| 2023-03-30T08:47:36
| 2013-03-01T00:10:41
|
Objective-C
|
UTF-8
|
C
| false
| false
| 45
|
h
|
PNPresenceWhereNowParser.h
|
../Network/Parsers/PNPresenceWhereNowParser.h
|
20ebfdaa0b7be8fbb3945a906cb938b7cb6e8782
|
376e1818d427b5e4d32fa6dd6c7b71e9fd88afdb
|
/sysutils/open-vm-tools/patches/patch-lib_hgfsUri_hgfsUriPosix.c
|
a5bc013f5e2478ee90faef502e45d0be93a7c507
|
[] |
no_license
|
NetBSD/pkgsrc
|
a0732c023519650ef821ab89c23ab6ab59e25bdb
|
d042034ec4896cc5b47ed6f2e5b8802d9bc5c556
|
refs/heads/trunk
| 2023-09-01T07:40:12.138283
| 2023-09-01T05:25:19
| 2023-09-01T05:25:19
| 88,439,572
| 321
| 138
| null | 2023-07-12T22:34:14
| 2017-04-16T20:04:15
| null |
UTF-8
|
C
| false
| false
| 462
|
c
|
patch-lib_hgfsUri_hgfsUriPosix.c
|
$NetBSD: patch-lib_hgfsUri_hgfsUriPosix.c,v 1.1 2016/10/09 03:41:56 ryoon Exp $
--- lib/hgfsUri/hgfsUriPosix.c.orig 2016-02-16 20:06:45.000000000 +0000
+++ lib/hgfsUri/hgfsUriPosix.c
@@ -23,7 +23,7 @@
* x-vmware-share:// style URIs
*/
-#if !defined __linux__ && !defined __APPLE__ && !defined __FreeBSD__
+#if !defined __linux__ && !defined __APPLE__ && !defined __FreeBSD__ && !defined __NetBSD__
# error This file should not be compiled
#endif
|
ae59b39d73aad6c4ebc6b571d400972cf26d5134
|
cc13bdb0f445b8acf6bec24946fcfb5e854989b6
|
/Pods/gRPC-Core/third_party/upb/upb/generated_util.h
|
ccdb80b4a200ddb9a8289756e4a247f8592f7082
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
devMEremenko/XcodeBenchmark
|
59eaf0f7d6cdaead6338511431489d9d2bf0bbb5
|
3aaaa6aa4400a20513dd4b6fdb372c48b8c9e772
|
refs/heads/master
| 2023-09-04T08:37:51.014081
| 2023-07-25T23:37:37
| 2023-07-25T23:37:37
| 288,524,849
| 2,335
| 346
|
MIT
| 2023-09-08T16:52:16
| 2020-08-18T17:47:47
|
Swift
|
UTF-8
|
C
| false
| false
| 3,366
|
h
|
generated_util.h
|
/*
** Functions for use by generated code. These are not public and users must
** not call them directly.
*/
#ifndef UPB_GENERATED_UTIL_H_
#define UPB_GENERATED_UTIL_H_
#include <stdint.h>
#if COCOAPODS==1
#include "third_party/upb/upb/msg.h"
#else
#include "upb/msg.h"
#endif
#if COCOAPODS==1
#include "third_party/upb/upb/port_def.inc"
#else
#include "upb/port_def.inc"
#endif
#define PTR_AT(msg, ofs, type) (type*)((const char*)msg + ofs)
UPB_INLINE const void *_upb_array_accessor(const void *msg, size_t ofs,
size_t *size) {
const upb_array *arr = *PTR_AT(msg, ofs, const upb_array*);
if (arr) {
if (size) *size = arr->len;
return arr->data;
} else {
if (size) *size = 0;
return NULL;
}
}
UPB_INLINE void *_upb_array_mutable_accessor(void *msg, size_t ofs,
size_t *size) {
upb_array *arr = *PTR_AT(msg, ofs, upb_array*);
if (arr) {
if (size) *size = arr->len;
return arr->data;
} else {
if (size) *size = 0;
return NULL;
}
}
/* TODO(haberman): this is a mess. It will improve when upb_array no longer
* carries reflective state (type, elem_size). */
UPB_INLINE void *_upb_array_resize_accessor(void *msg, size_t ofs, size_t size,
size_t elem_size,
upb_fieldtype_t type,
upb_arena *arena) {
upb_array *arr = *PTR_AT(msg, ofs, upb_array*);
if (!arr) {
arr = upb_array_new(arena);
if (!arr) return NULL;
*PTR_AT(msg, ofs, upb_array*) = arr;
}
if (size > arr->size) {
size_t new_size = UPB_MAX(arr->size, 4);
size_t old_bytes = arr->size * elem_size;
size_t new_bytes;
while (new_size < size) new_size *= 2;
new_bytes = new_size * elem_size;
arr->data = upb_arena_realloc(arena, arr->data, old_bytes, new_bytes);
if (!arr->data) {
return NULL;
}
arr->size = new_size;
}
arr->len = size;
return arr->data;
}
UPB_INLINE bool _upb_array_append_accessor(void *msg, size_t ofs,
size_t elem_size,
upb_fieldtype_t type,
const void *value,
upb_arena *arena) {
upb_array *arr = *PTR_AT(msg, ofs, upb_array*);
size_t i = arr ? arr->len : 0;
void *data =
_upb_array_resize_accessor(msg, ofs, i + 1, elem_size, type, arena);
if (!data) return false;
memcpy(PTR_AT(data, i * elem_size, char), value, elem_size);
return true;
}
UPB_INLINE bool _upb_has_field(const void *msg, size_t idx) {
return (*PTR_AT(msg, idx / 8, const char) & (1 << (idx % 8))) != 0;
}
UPB_INLINE bool _upb_sethas(const void *msg, size_t idx) {
return (*PTR_AT(msg, idx / 8, char)) |= (char)(1 << (idx % 8));
}
UPB_INLINE bool _upb_clearhas(const void *msg, size_t idx) {
return (*PTR_AT(msg, idx / 8, char)) &= (char)(~(1 << (idx % 8)));
}
UPB_INLINE bool _upb_has_oneof_field(const void *msg, size_t case_ofs, int32_t num) {
return *PTR_AT(msg, case_ofs, int32_t) == num;
}
#undef PTR_AT
#if COCOAPODS==1
#include "third_party/upb/upb/port_undef.inc"
#else
#include "upb/port_undef.inc"
#endif
#endif /* UPB_GENERATED_UTIL_H_ */
|
f2b79dcf05af7f3d22b1a55d555974980fbee6b2
|
331640994b1b6f66c1639278571ddbdc6c8c0751
|
/src/nxt_file.c
|
6f1a93e48360f766d5b7d98c7c7e7fc7a8a2ebed
|
[
"Apache-2.0"
] |
permissive
|
nginx/unit
|
eabcd067eaa60f4bdcf0cfaffe7d9932add2c66a
|
9b22b6957bc87b3df002d0bc691fdae6a20abdac
|
refs/heads/master
| 2023-09-04T02:02:13.581700
| 2023-08-30T16:07:24
| 2023-08-30T16:07:24
| 102,627,638
| 4,649
| 452
|
Apache-2.0
| 2023-09-12T01:28:22
| 2017-09-06T15:45:30
|
C
|
UTF-8
|
C
| false
| false
| 15,173
|
c
|
nxt_file.c
|
/*
* Copyright (C) Igor Sysoev
* Copyright (C) NGINX, Inc.
*/
#include <nxt_main.h>
nxt_int_t
nxt_file_open(nxt_task_t *task, nxt_file_t *file, nxt_uint_t mode,
nxt_uint_t create, nxt_file_access_t access)
{
#ifdef __CYGWIN__
mode |= O_BINARY;
#endif
/* O_NONBLOCK is to prevent blocking on FIFOs, special devices, etc. */
mode |= (O_NONBLOCK | create);
file->fd = open((char *) file->name, mode, access);
file->error = (file->fd == -1) ? nxt_errno : 0;
#if (NXT_DEBUG)
nxt_thread_time_update(task->thread);
#endif
nxt_debug(task, "open(\"%FN\", 0x%uXi, 0x%uXi): %FD err:%d",
file->name, mode, access, file->fd, file->error);
if (file->fd != -1) {
return NXT_OK;
}
if (file->log_level != 0) {
nxt_log(task, file->log_level, "open(\"%FN\") failed %E",
file->name, file->error);
}
return NXT_ERROR;
}
#if (NXT_HAVE_OPENAT2)
nxt_int_t
nxt_file_openat2(nxt_task_t *task, nxt_file_t *file, nxt_uint_t mode,
nxt_uint_t create, nxt_file_access_t access, nxt_fd_t dfd,
nxt_uint_t resolve)
{
struct open_how how;
nxt_memzero(&how, sizeof(how));
/* O_NONBLOCK is to prevent blocking on FIFOs, special devices, etc. */
mode |= (O_NONBLOCK | create);
how.flags = mode;
how.mode = access;
how.resolve = resolve;
file->fd = syscall(SYS_openat2, dfd, file->name, &how, sizeof(how));
file->error = (file->fd == -1) ? nxt_errno : 0;
#if (NXT_DEBUG)
nxt_thread_time_update(task->thread);
#endif
nxt_debug(task, "openat2(%FD, \"%FN\"): %FD err:%d", dfd, file->name,
file->fd, file->error);
if (file->fd != -1) {
return NXT_OK;
}
if (file->log_level != 0) {
nxt_log(task, file->log_level, "openat2(%FD, \"%FN\") failed %E", dfd,
file->name, file->error);
}
return NXT_ERROR;
}
#endif
void
nxt_file_close(nxt_task_t *task, nxt_file_t *file)
{
nxt_debug(task, "close(%FD)", file->fd);
if (close(file->fd) != 0) {
nxt_alert(task, "close(%FD, \"%FN\") failed %E",
file->fd, file->name, nxt_errno);
}
}
ssize_t
nxt_file_write(nxt_file_t *file, const u_char *buf, size_t size,
nxt_off_t offset)
{
ssize_t n;
nxt_thread_debug(thr);
n = pwrite(file->fd, buf, size, offset);
file->error = (n < 0) ? nxt_errno : 0;
nxt_thread_time_debug_update(thr);
nxt_log_debug(thr->log, "pwrite(%FD, %p, %uz, %O): %z",
file->fd, buf, size, offset, n);
if (nxt_fast_path(n >= 0)) {
return n;
}
nxt_thread_log_alert("pwrite(%FD, \"%FN\", %p, %uz, %O) failed %E",
file->fd, file->name, buf, size,
offset, file->error);
return NXT_ERROR;
}
ssize_t
nxt_file_read(nxt_file_t *file, u_char *buf, size_t size, nxt_off_t offset)
{
ssize_t n;
nxt_thread_debug(thr);
n = pread(file->fd, buf, size, offset);
file->error = (n <= 0) ? nxt_errno : 0;
nxt_thread_time_debug_update(thr);
nxt_log_debug(thr->log, "pread(%FD, %p, %uz, %O): %z",
file->fd, buf, size, offset, n);
if (nxt_fast_path(n >= 0)) {
return n;
}
nxt_thread_log_alert("pread(%FD, \"%FN\", %p, %uz, %O) failed %E",
file->fd, file->name, buf, size,
offset, file->error);
return NXT_ERROR;
}
#if (NXT_HAVE_READAHEAD)
/* FreeBSD 8.0 fcntl(F_READAHEAD, size) enables read ahead up to the size. */
void
nxt_file_read_ahead(nxt_file_t *file, nxt_off_t offset, size_t size)
{
int ret;
u_char buf;
ret = fcntl(file->fd, F_READAHEAD, (int) size);
nxt_thread_log_debug("fcntl(%FD, F_READAHEAD, %uz): %d",
file->fd, size, ret);
if (nxt_fast_path(ret != -1)) {
(void) nxt_file_read(file, &buf, 1, offset);
return;
}
nxt_thread_log_alert("fcntl(%FD, \"%FN\", F_READAHEAD, %uz) failed %E",
file->fd, file->name, size, nxt_errno);
}
#elif (NXT_HAVE_POSIX_FADVISE)
/*
* POSIX_FADV_SEQUENTIAL
* Linux doubles the default readahead window size of a backing device
* which is usually 128K.
*
* FreeBSD does nothing.
*
* POSIX_FADV_WILLNEED
* Linux preloads synchronously up to 2M of specified file region in
* the kernel page cache. Linux-specific readahead(2) syscall does
* the same. Both operations are blocking despite posix_fadvise(2)
* claims the opposite.
*
* FreeBSD does nothing.
*/
void
nxt_file_read_ahead(nxt_file_t *file, nxt_off_t offset, size_t size)
{
nxt_err_t err;
err = posix_fadvise(file->fd, offset, size, POSIX_FADV_WILLNEED);
nxt_thread_log_debug("posix_fadvise(%FD, \"%FN\", %O, %uz, %d): %d",
file->fd, file->name, offset, size,
POSIX_FADV_WILLNEED, err);
if (nxt_fast_path(err == 0)) {
return;
}
nxt_thread_log_alert("posix_fadvise(%FD, \"%FN\", %O, %uz, %d) failed %E",
file->fd, file->name, offset, size,
POSIX_FADV_WILLNEED, err);
}
#elif (NXT_HAVE_RDAHEAD)
/* MacOSX fcntl(F_RDAHEAD). */
void
nxt_file_read_ahead(nxt_file_t *file, nxt_off_t offset, size_t size)
{
int ret;
u_char buf;
ret = fcntl(file->fd, F_RDAHEAD, 1);
nxt_thread_log_debug("fcntl(%FD, F_RDAHEAD, 1): %d", file->fd, ret);
if (nxt_fast_path(ret != -1)) {
(void) nxt_file_read(file, &buf, 1, offset);
return;
}
nxt_thread_log_alert("fcntl(%FD, \"%FN\", F_RDAHEAD, 1) failed %E",
file->fd, file->name, nxt_errno);
}
#else
void
nxt_file_read_ahead(nxt_file_t *file, nxt_off_t offset, size_t size)
{
u_char buf;
(void) nxt_file_read(file, &buf, 1, offset);
}
#endif
nxt_int_t
nxt_file_info(nxt_file_t *file, nxt_file_info_t *fi)
{
int n;
if (file->fd == NXT_FILE_INVALID) {
n = stat((char *) file->name, fi);
file->error = (n != 0) ? nxt_errno : 0;
nxt_thread_log_debug("stat(\"%FN)\": %d", file->name, n);
if (n == 0) {
return NXT_OK;
}
if (file->log_level != 0) {
nxt_thread_log_error(file->log_level, "stat(\"%FN\") failed %E",
file->name, file->error);
}
return NXT_ERROR;
} else {
n = fstat(file->fd, fi);
file->error = (n != 0) ? nxt_errno : 0;
nxt_thread_log_debug("fstat(%FD): %d", file->fd, n);
if (n == 0) {
return NXT_OK;
}
/* Use NXT_LOG_ALERT because fstat() error on open file is strange. */
nxt_thread_log_alert("fstat(%FD, \"%FN\") failed %E",
file->fd, file->name, file->error);
return NXT_ERROR;
}
}
nxt_int_t
nxt_file_delete(nxt_file_name_t *name)
{
nxt_thread_log_debug("unlink(\"%FN\")", name);
if (nxt_fast_path(unlink((char *) name) == 0)) {
return NXT_OK;
}
nxt_thread_log_alert("unlink(\"%FN\") failed %E", name, nxt_errno);
return NXT_ERROR;
}
nxt_int_t
nxt_file_set_access(nxt_file_name_t *name, nxt_file_access_t access)
{
if (nxt_fast_path(chmod((char *) name, access) == 0)) {
return NXT_OK;
}
nxt_thread_log_alert("chmod(\"%FN\") failed %E", name, nxt_errno);
return NXT_ERROR;
}
nxt_int_t
nxt_file_rename(nxt_file_name_t *old_name, nxt_file_name_t *new_name)
{
int ret;
nxt_thread_log_debug("rename(\"%FN\", \"%FN\")", old_name, new_name);
ret = rename((char *) old_name, (char *) new_name);
if (nxt_fast_path(ret == 0)) {
return NXT_OK;
}
nxt_thread_log_alert("rename(\"%FN\", \"%FN\") failed %E",
old_name, new_name, nxt_errno);
return NXT_ERROR;
}
/*
* ioctl(FIONBIO) sets a non-blocking mode using one syscall,
* thereas fcntl(F_SETFL, O_NONBLOCK) needs to learn the current state
* using fcntl(F_GETFL).
*
* ioctl() and fcntl() are syscalls at least in Linux 2.2, FreeBSD 2.x,
* and Solaris 7.
*
* Linux 2.4 uses BKL for ioctl() and fcntl(F_SETFL).
* Linux 2.6 does not use BKL.
*/
#if (NXT_HAVE_FIONBIO)
nxt_int_t
nxt_fd_nonblocking(nxt_task_t *task, nxt_fd_t fd)
{
int nb;
nb = 1;
if (nxt_fast_path(ioctl(fd, FIONBIO, &nb) != -1)) {
return NXT_OK;
}
nxt_alert(task, "ioctl(%d, FIONBIO) failed %E", fd, nxt_errno);
return NXT_ERROR;
}
nxt_int_t
nxt_fd_blocking(nxt_task_t *task, nxt_fd_t fd)
{
int nb;
nb = 0;
if (nxt_fast_path(ioctl(fd, FIONBIO, &nb) != -1)) {
return NXT_OK;
}
nxt_alert(task, "ioctl(%d, !FIONBIO) failed %E", fd, nxt_errno);
return NXT_ERROR;
}
#else /* !(NXT_HAVE_FIONBIO) */
nxt_int_t
nxt_fd_nonblocking(nxt_task_t *task, nxt_fd_t fd)
{
int flags;
flags = fcntl(fd, F_GETFL);
if (nxt_slow_path(flags == -1)) {
nxt_alert(task, "fcntl(%d, F_GETFL) failed %E", fd, nxt_errno);
return NXT_ERROR;
}
flags |= O_NONBLOCK;
if (nxt_slow_path(fcntl(fd, F_SETFL, flags) == -1)) {
nxt_alert(task, "fcntl(%d, F_SETFL, O_NONBLOCK) failed %E",
fd, nxt_errno);
return NXT_ERROR;
}
return NXT_OK;
}
nxt_int_t
nxt_fd_blocking(nxt_task_t *task, nxt_fd_t fd)
{
int flags;
flags = fcntl(fd, F_GETFL);
if (nxt_slow_path(flags == -1)) {
nxt_alert(task, "fcntl(%d, F_GETFL) failed %E", fd, nxt_errno);
return NXT_ERROR;
}
flags &= O_NONBLOCK;
if (nxt_slow_path(fcntl(fd, F_SETFL, flags) == -1)) {
nxt_alert(task, "fcntl(%d, F_SETFL, !O_NONBLOCK) failed %E",
fd, nxt_errno);
return NXT_ERROR;
}
return NXT_OK;
}
#endif /* NXT_HAVE_FIONBIO */
ssize_t
nxt_fd_write(nxt_fd_t fd, u_char *buf, size_t size)
{
ssize_t n;
nxt_err_t err;
n = write(fd, buf, size);
err = (n == -1) ? nxt_errno : 0;
nxt_thread_log_debug("write(%FD, %p, %uz): %z", fd, buf, size, n);
if (nxt_slow_path(n <= 0)) {
nxt_thread_log_alert("write(%FD) failed %E", fd, err);
}
return n;
}
ssize_t
nxt_fd_read(nxt_fd_t fd, u_char *buf, size_t size)
{
ssize_t n;
nxt_err_t err;
n = read(fd, buf, size);
err = (n == -1) ? nxt_errno : 0;
nxt_thread_log_debug("read(%FD, %p, %uz): %z", fd, buf, size, n);
if (nxt_slow_path(n <= 0)) {
if (err == NXT_EAGAIN) {
return 0;
}
nxt_thread_log_alert("read(%FD) failed %E", fd, err);
}
return n;
}
void
nxt_fd_close(nxt_fd_t fd)
{
nxt_thread_log_debug("close(%FD)", fd);
if (nxt_slow_path(close(fd) != 0)) {
nxt_thread_log_alert("close(%FD) failed %E", fd, nxt_errno);
}
}
FILE *
nxt_file_fopen(nxt_task_t *task, const char *pathname, const char *mode)
{
int err;
FILE *fp;
#if (NXT_DEBUG)
nxt_thread_time_update(task->thread);
#endif
fp = fopen(pathname, mode);
err = (fp == NULL) ? nxt_errno : 0;
nxt_debug(task, "fopen(\"%s\", \"%s\"): fp:%p err:%d", pathname, mode, fp,
err);
if (nxt_fast_path(fp != NULL)) {
return fp;
}
nxt_alert(task, "fopen(\"%s\") failed %E", pathname, err);
return NULL;
}
void
nxt_file_fclose(nxt_task_t *task, FILE *fp)
{
nxt_debug(task, "fclose(%p)", fp);
if (nxt_slow_path(fclose(fp) == -1)) {
nxt_alert(task, "fclose() failed %E", nxt_errno);
}
}
/*
* nxt_file_redirect() redirects the file to the fd descriptor.
* Then the fd descriptor is closed.
*/
nxt_int_t
nxt_file_redirect(nxt_file_t *file, nxt_fd_t fd)
{
nxt_thread_log_debug("dup2(%FD, %FD, \"%FN\")", fd, file->fd, file->name);
if (dup2(fd, file->fd) == -1) {
nxt_thread_log_alert("dup2(%FD, %FD, \"%FN\") failed %E",
fd, file->fd, file->name, nxt_errno);
return NXT_ERROR;
}
if (close(fd) != 0) {
nxt_thread_log_alert("close(%FD, \"%FN\") failed %E",
fd, file->name, nxt_errno);
return NXT_ERROR;
}
return NXT_OK;
}
/* nxt_file_stdout() redirects the stdout descriptor to the file. */
nxt_int_t
nxt_file_stdout(nxt_file_t *file)
{
nxt_thread_log_debug("dup2(%FD, %FD, \"%FN\")",
file->fd, STDOUT_FILENO, file->name);
if (dup2(file->fd, STDOUT_FILENO) != -1) {
return NXT_OK;
}
nxt_thread_log_alert("dup2(%FD, %FD, \"%FN\") failed %E",
file->fd, STDOUT_FILENO, file->name, nxt_errno);
return NXT_ERROR;
}
/* nxt_file_stderr() redirects the stderr descriptor to the file. */
nxt_int_t
nxt_file_stderr(nxt_file_t *file)
{
nxt_thread_log_debug("dup2(%FD, %FD, \"%FN\")",
file->fd, STDERR_FILENO, file->name);
if (dup2(file->fd, STDERR_FILENO) != -1) {
return NXT_OK;
}
nxt_thread_log_alert("dup2(%FD, %FD, \"%FN\") failed %E",
file->fd, STDERR_FILENO, file->name, nxt_errno);
return NXT_ERROR;
}
nxt_int_t
nxt_stderr_start(void)
{
int flags, fd;
flags = fcntl(nxt_stderr, F_GETFL);
if (flags != -1) {
/*
* If the stderr output of a multithreaded application is
* redirected to a file:
* Linux, Solaris and MacOSX do not write atomically to the output;
* MacOSX besides adds zeroes to the output.
* O_APPEND fixes this.
*/
(void) fcntl(nxt_stderr, F_SETFL, flags | O_APPEND);
} else {
/*
* The stderr descriptor is closed before application start.
* Reserve the stderr descriptor for future use. Errors are
* ignored because anyway they could be written nowhere.
*/
fd = open("/dev/null", O_WRONLY | O_APPEND);
if (fd != -1) {
(void) dup2(fd, nxt_stderr);
if (fd != nxt_stderr) {
(void) close(fd);
}
}
}
return flags;
}
nxt_int_t
nxt_pipe_create(nxt_task_t *task, nxt_fd_t *pp, nxt_bool_t nbread,
nxt_bool_t nbwrite)
{
if (pipe(pp) != 0) {
nxt_alert(task, "pipe() failed %E", nxt_errno);
return NXT_ERROR;
}
nxt_debug(task, "pipe(): %FD:%FD", pp[0], pp[1]);
if (nbread) {
if (nxt_fd_nonblocking(task, pp[0]) != NXT_OK) {
return NXT_ERROR;
}
}
if (nbwrite) {
if (nxt_fd_nonblocking(task, pp[1]) != NXT_OK) {
return NXT_ERROR;
}
}
return NXT_OK;
}
void
nxt_pipe_close(nxt_task_t *task, nxt_fd_t *pp)
{
nxt_debug(task, "pipe close(%FD:%FD)", pp[0], pp[1]);
if (close(pp[0]) != 0) {
nxt_alert(task, "pipe close(%FD) failed %E", pp[0], nxt_errno);
}
if (close(pp[1]) != 0) {
nxt_alert(task, "pipe close(%FD) failed %E", pp[1], nxt_errno);
}
}
size_t
nxt_dir_current(char *buf, size_t len)
{
if (nxt_fast_path(getcwd(buf, len) != NULL)) {
return nxt_strlen(buf);
}
nxt_thread_log_alert("getcwd(%uz) failed %E", len, nxt_errno);
return 0;
}
|
2e72ad141948b4e0c42011a00d37b1aafe90d83a
|
5ff4b6986e6799bc0e143e060bafc14369030d8b
|
/toolchain/riscv-isa-sim/riscv/insns/fsgnjx_h.h
|
9310269545fd2e4087f459750d17922572770049
|
[
"LicenseRef-scancode-bsd-3-clause-jtag",
"GPL-3.0-or-later",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"GPL-1.0-or-later",
"LLVM-exception",
"Apache-2.0",
"BSD-3-Clause"
] |
permissive
|
pulp-platform/mempool
|
7583204b2436cfc12ed95599463e51ad4df51557
|
c98fb3ada4f255623eaf9b09861f397a60c3d96b
|
refs/heads/main
| 2023-08-08T09:07:56.696580
| 2023-07-27T17:24:38
| 2023-07-27T17:24:38
| 223,218,149
| 178
| 28
|
Apache-2.0
| 2023-07-27T17:24:39
| 2019-11-21T16:34:37
|
C
|
UTF-8
|
C
| false
| false
| 85
|
h
|
fsgnjx_h.h
|
require_extension(EXT_ZFH);
require_fp;
WRITE_FRD(fsgnj16(FRS1, FRS2, false, true));
|
82f1d4bd500c1d882b436e48663c72f24aef112f
|
88ae8695987ada722184307301e221e1ba3cc2fa
|
/third_party/libaom/source/libaom/aom/aom_image.h
|
d5f0c087e6b22d7a848305a93bcd54d33805140b
|
[
"BSD-3-Clause",
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"BSD-2-Clause"
] |
permissive
|
iridium-browser/iridium-browser
|
71d9c5ff76e014e6900b825f67389ab0ccd01329
|
5ee297f53dc7f8e70183031cff62f37b0f19d25f
|
refs/heads/master
| 2023-08-03T16:44:16.844552
| 2023-07-20T15:17:00
| 2023-07-23T16:09:30
| 220,016,632
| 341
| 40
|
BSD-3-Clause
| 2021-08-13T13:54:45
| 2019-11-06T14:32:31
| null |
UTF-8
|
C
| false
| false
| 19,240
|
h
|
aom_image.h
|
/*
* Copyright (c) 2016, Alliance for Open Media. All rights reserved
*
* This source code is subject to the terms of the BSD 2 Clause License and
* the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
* was not distributed with this source code in the LICENSE file, you can
* obtain it at www.aomedia.org/license/software. If the Alliance for Open
* Media Patent License 1.0 was not distributed with this source code in the
* PATENTS file, you can obtain it at www.aomedia.org/license/patent.
*/
/*!\file
* \brief Describes the aom image descriptor and associated operations
*
*/
#ifndef AOM_AOM_AOM_IMAGE_H_
#define AOM_AOM_AOM_IMAGE_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "aom/aom_integer.h"
/*!\brief Current ABI version number
*
* \internal
* If this file is altered in any way that changes the ABI, this value
* must be bumped. Examples include, but are not limited to, changing
* types, removing or reassigning enums, adding/removing/rearranging
* fields to structures
*/
#define AOM_IMAGE_ABI_VERSION (9) /**<\hideinitializer*/
#define AOM_IMG_FMT_PLANAR 0x100 /**< Image is a planar format. */
#define AOM_IMG_FMT_UV_FLIP 0x200 /**< V plane precedes U in memory. */
/** 0x400 used to signal alpha channel, skipping for backwards compatibility. */
#define AOM_IMG_FMT_HIGHBITDEPTH 0x800 /**< Image uses 16bit framebuffer. */
/*!\brief List of supported image formats */
typedef enum aom_img_fmt {
AOM_IMG_FMT_NONE,
AOM_IMG_FMT_YV12 =
AOM_IMG_FMT_PLANAR | AOM_IMG_FMT_UV_FLIP | 1, /**< planar YVU */
AOM_IMG_FMT_I420 = AOM_IMG_FMT_PLANAR | 2,
AOM_IMG_FMT_AOMYV12 = AOM_IMG_FMT_PLANAR | AOM_IMG_FMT_UV_FLIP |
3, /** < planar 4:2:0 format with aom color space */
AOM_IMG_FMT_AOMI420 = AOM_IMG_FMT_PLANAR | 4,
AOM_IMG_FMT_I422 = AOM_IMG_FMT_PLANAR | 5,
AOM_IMG_FMT_I444 = AOM_IMG_FMT_PLANAR | 6,
/*!\brief Allows detection of the presence of AOM_IMG_FMT_NV12 at compile time.
*/
#define AOM_HAVE_IMG_FMT_NV12 1
AOM_IMG_FMT_NV12 =
AOM_IMG_FMT_PLANAR | 7, /**< 4:2:0 with U and V interleaved */
AOM_IMG_FMT_I42016 = AOM_IMG_FMT_I420 | AOM_IMG_FMT_HIGHBITDEPTH,
AOM_IMG_FMT_YV1216 = AOM_IMG_FMT_YV12 | AOM_IMG_FMT_HIGHBITDEPTH,
AOM_IMG_FMT_I42216 = AOM_IMG_FMT_I422 | AOM_IMG_FMT_HIGHBITDEPTH,
AOM_IMG_FMT_I44416 = AOM_IMG_FMT_I444 | AOM_IMG_FMT_HIGHBITDEPTH,
} aom_img_fmt_t; /**< alias for enum aom_img_fmt */
/*!\brief List of supported color primaries */
typedef enum aom_color_primaries {
AOM_CICP_CP_RESERVED_0 = 0, /**< For future use */
AOM_CICP_CP_BT_709 = 1, /**< BT.709 */
AOM_CICP_CP_UNSPECIFIED = 2, /**< Unspecified */
AOM_CICP_CP_RESERVED_3 = 3, /**< For future use */
AOM_CICP_CP_BT_470_M = 4, /**< BT.470 System M (historical) */
AOM_CICP_CP_BT_470_B_G = 5, /**< BT.470 System B, G (historical) */
AOM_CICP_CP_BT_601 = 6, /**< BT.601 */
AOM_CICP_CP_SMPTE_240 = 7, /**< SMPTE 240 */
AOM_CICP_CP_GENERIC_FILM =
8, /**< Generic film (color filters using illuminant C) */
AOM_CICP_CP_BT_2020 = 9, /**< BT.2020, BT.2100 */
AOM_CICP_CP_XYZ = 10, /**< SMPTE 428 (CIE 1921 XYZ) */
AOM_CICP_CP_SMPTE_431 = 11, /**< SMPTE RP 431-2 */
AOM_CICP_CP_SMPTE_432 = 12, /**< SMPTE EG 432-1 */
AOM_CICP_CP_RESERVED_13 = 13, /**< For future use (values 13 - 21) */
AOM_CICP_CP_EBU_3213 = 22, /**< EBU Tech. 3213-E */
AOM_CICP_CP_RESERVED_23 = 23 /**< For future use (values 23 - 255) */
} aom_color_primaries_t; /**< alias for enum aom_color_primaries */
/*!\brief List of supported transfer functions */
typedef enum aom_transfer_characteristics {
AOM_CICP_TC_RESERVED_0 = 0, /**< For future use */
AOM_CICP_TC_BT_709 = 1, /**< BT.709 */
AOM_CICP_TC_UNSPECIFIED = 2, /**< Unspecified */
AOM_CICP_TC_RESERVED_3 = 3, /**< For future use */
AOM_CICP_TC_BT_470_M = 4, /**< BT.470 System M (historical) */
AOM_CICP_TC_BT_470_B_G = 5, /**< BT.470 System B, G (historical) */
AOM_CICP_TC_BT_601 = 6, /**< BT.601 */
AOM_CICP_TC_SMPTE_240 = 7, /**< SMPTE 240 M */
AOM_CICP_TC_LINEAR = 8, /**< Linear */
AOM_CICP_TC_LOG_100 = 9, /**< Logarithmic (100 : 1 range) */
AOM_CICP_TC_LOG_100_SQRT10 =
10, /**< Logarithmic (100 * Sqrt(10) : 1 range) */
AOM_CICP_TC_IEC_61966 = 11, /**< IEC 61966-2-4 */
AOM_CICP_TC_BT_1361 = 12, /**< BT.1361 */
AOM_CICP_TC_SRGB = 13, /**< sRGB or sYCC*/
AOM_CICP_TC_BT_2020_10_BIT = 14, /**< BT.2020 10-bit systems */
AOM_CICP_TC_BT_2020_12_BIT = 15, /**< BT.2020 12-bit systems */
AOM_CICP_TC_SMPTE_2084 = 16, /**< SMPTE ST 2084, ITU BT.2100 PQ */
AOM_CICP_TC_SMPTE_428 = 17, /**< SMPTE ST 428 */
AOM_CICP_TC_HLG = 18, /**< BT.2100 HLG, ARIB STD-B67 */
AOM_CICP_TC_RESERVED_19 = 19 /**< For future use (values 19-255) */
} aom_transfer_characteristics_t; /**< alias for enum aom_transfer_function */
/*!\brief List of supported matrix coefficients */
typedef enum aom_matrix_coefficients {
AOM_CICP_MC_IDENTITY = 0, /**< Identity matrix */
AOM_CICP_MC_BT_709 = 1, /**< BT.709 */
AOM_CICP_MC_UNSPECIFIED = 2, /**< Unspecified */
AOM_CICP_MC_RESERVED_3 = 3, /**< For future use */
AOM_CICP_MC_FCC = 4, /**< US FCC 73.628 */
AOM_CICP_MC_BT_470_B_G = 5, /**< BT.470 System B, G (historical) */
AOM_CICP_MC_BT_601 = 6, /**< BT.601 */
AOM_CICP_MC_SMPTE_240 = 7, /**< SMPTE 240 M */
AOM_CICP_MC_SMPTE_YCGCO = 8, /**< YCgCo */
AOM_CICP_MC_BT_2020_NCL =
9, /**< BT.2020 non-constant luminance, BT.2100 YCbCr */
AOM_CICP_MC_BT_2020_CL = 10, /**< BT.2020 constant luminance */
AOM_CICP_MC_SMPTE_2085 = 11, /**< SMPTE ST 2085 YDzDx */
AOM_CICP_MC_CHROMAT_NCL =
12, /**< Chromaticity-derived non-constant luminance */
AOM_CICP_MC_CHROMAT_CL = 13, /**< Chromaticity-derived constant luminance */
AOM_CICP_MC_ICTCP = 14, /**< BT.2100 ICtCp */
AOM_CICP_MC_RESERVED_15 = 15 /**< For future use (values 15-255) */
} aom_matrix_coefficients_t;
/*!\brief List of supported color range */
typedef enum aom_color_range {
AOM_CR_STUDIO_RANGE = 0, /**<- Y [16..235], UV [16..240] (bit depth 8) */
/**<- Y [64..940], UV [64..960] (bit depth 10) */
/**<- Y [256..3760], UV [256..3840] (bit depth 12) */
AOM_CR_FULL_RANGE = 1 /**<- YUV/RGB [0..255] (bit depth 8) */
/**<- YUV/RGB [0..1023] (bit depth 10) */
/**<- YUV/RGB [0..4095] (bit depth 12) */
} aom_color_range_t; /**< alias for enum aom_color_range */
/*!\brief List of chroma sample positions */
typedef enum aom_chroma_sample_position {
AOM_CSP_UNKNOWN = 0, /**< Unknown */
AOM_CSP_VERTICAL = 1, /**< Horizontally co-located with luma(0, 0)*/
/**< sample, between two vertical samples */
AOM_CSP_COLOCATED = 2, /**< Co-located with luma(0, 0) sample */
AOM_CSP_RESERVED = 3 /**< Reserved value */
} aom_chroma_sample_position_t; /**< alias for enum aom_transfer_function */
/*!\brief List of insert flags for Metadata
*
* These flags control how the library treats metadata during encode.
*
* While encoding, when metadata is added to an aom_image via
* aom_img_add_metadata(), the flag passed along with the metadata will
* determine where the metadata OBU will be placed in the encoded OBU stream.
* Metadata will be emitted into the output stream within the next temporal unit
* if it satisfies the specified insertion flag.
*
* During decoding, when the library encounters a metadata OBU, it is always
* flagged as AOM_MIF_ANY_FRAME and emitted with the next output aom_image.
*/
typedef enum aom_metadata_insert_flags {
AOM_MIF_NON_KEY_FRAME = 0, /**< Adds metadata if it's not keyframe */
AOM_MIF_KEY_FRAME = 1, /**< Adds metadata only if it's a keyframe */
AOM_MIF_ANY_FRAME = 2 /**< Adds metadata to any type of frame */
} aom_metadata_insert_flags_t;
/*!\brief Array of aom_metadata structs for an image. */
typedef struct aom_metadata_array aom_metadata_array_t;
/*!\brief Metadata payload. */
typedef struct aom_metadata {
uint32_t type; /**< Metadata type */
uint8_t *payload; /**< Metadata payload data */
size_t sz; /**< Metadata payload size */
aom_metadata_insert_flags_t insert_flag; /**< Metadata insertion flag */
} aom_metadata_t;
/**\brief Image Descriptor */
typedef struct aom_image {
aom_img_fmt_t fmt; /**< Image Format */
aom_color_primaries_t cp; /**< CICP Color Primaries */
aom_transfer_characteristics_t tc; /**< CICP Transfer Characteristics */
aom_matrix_coefficients_t mc; /**< CICP Matrix Coefficients */
int monochrome; /**< Whether image is monochrome */
aom_chroma_sample_position_t csp; /**< chroma sample position */
aom_color_range_t range; /**< Color Range */
/* Image storage dimensions */
unsigned int w; /**< Stored image width */
unsigned int h; /**< Stored image height */
unsigned int bit_depth; /**< Stored image bit-depth */
/* Image display dimensions */
unsigned int d_w; /**< Displayed image width */
unsigned int d_h; /**< Displayed image height */
/* Image intended rendering dimensions */
unsigned int r_w; /**< Intended rendering image width */
unsigned int r_h; /**< Intended rendering image height */
/* Chroma subsampling info */
unsigned int x_chroma_shift; /**< subsampling order, X */
unsigned int y_chroma_shift; /**< subsampling order, Y */
/* Image data pointers. */
#define AOM_PLANE_PACKED 0 /**< To be used for all packed formats */
#define AOM_PLANE_Y 0 /**< Y (Luminance) plane */
#define AOM_PLANE_U 1 /**< U (Chroma) plane */
#define AOM_PLANE_V 2 /**< V (Chroma) plane */
/* planes[AOM_PLANE_V] = NULL and stride[AOM_PLANE_V] = 0 when fmt ==
* AOM_IMG_FMT_NV12 */
unsigned char *planes[3]; /**< pointer to the top left pixel for each plane */
int stride[3]; /**< stride between rows for each plane */
size_t sz; /**< data size */
int bps; /**< bits per sample (for packed formats) */
int temporal_id; /**< Temporal layer Id of image */
int spatial_id; /**< Spatial layer Id of image */
/*!\brief The following member may be set by the application to associate
* data with this image.
*/
void *user_priv;
/* The following members should be treated as private. */
unsigned char *img_data; /**< private */
int img_data_owner; /**< private */
int self_allocd; /**< private */
aom_metadata_array_t
*metadata; /**< Metadata payloads associated with the image. */
void *fb_priv; /**< Frame buffer data associated with the image. */
} aom_image_t; /**< alias for struct aom_image */
/*!\brief Open a descriptor, allocating storage for the underlying image
*
* Returns a descriptor for storing an image of the given format. The
* storage for the image is allocated on the heap.
*
* \param[in] img Pointer to storage for descriptor. If this parameter
* is NULL, the storage for the descriptor will be
* allocated on the heap.
* \param[in] fmt Format for the image
* \param[in] d_w Width of the image
* \param[in] d_h Height of the image
* \param[in] align Alignment, in bytes, of the image buffer and
* each row in the image (stride).
*
* \return Returns a pointer to the initialized image descriptor. If the img
* parameter is non-null, the value of the img parameter will be
* returned.
*/
aom_image_t *aom_img_alloc(aom_image_t *img, aom_img_fmt_t fmt,
unsigned int d_w, unsigned int d_h,
unsigned int align);
/*!\brief Open a descriptor, using existing storage for the underlying image
*
* Returns a descriptor for storing an image of the given format. The
* storage for the image has been allocated elsewhere, and a descriptor is
* desired to "wrap" that storage.
*
* \param[in] img Pointer to storage for descriptor. If this parameter
* is NULL, the storage for the descriptor will be
* allocated on the heap.
* \param[in] fmt Format for the image
* \param[in] d_w Width of the image
* \param[in] d_h Height of the image
* \param[in] align Alignment, in bytes, of each row in the image
* (stride).
* \param[in] img_data Storage to use for the image
*
* \return Returns a pointer to the initialized image descriptor. If the img
* parameter is non-null, the value of the img parameter will be
* returned.
*/
aom_image_t *aom_img_wrap(aom_image_t *img, aom_img_fmt_t fmt, unsigned int d_w,
unsigned int d_h, unsigned int align,
unsigned char *img_data);
/*!\brief Open a descriptor, allocating storage for the underlying image with a
* border
*
* Returns a descriptor for storing an image of the given format and its
* borders. The storage for the image is allocated on the heap.
*
* \param[in] img Pointer to storage for descriptor. If this parameter
* is NULL, the storage for the descriptor will be
* allocated on the heap.
* \param[in] fmt Format for the image
* \param[in] d_w Width of the image
* \param[in] d_h Height of the image
* \param[in] align Alignment, in bytes, of the image buffer and
* each row in the image (stride).
* \param[in] size_align Alignment, in pixels, of the image width and height.
* \param[in] border A border that is padded on four sides of the image.
*
* \return Returns a pointer to the initialized image descriptor. If the img
* parameter is non-null, the value of the img parameter will be
* returned.
*/
aom_image_t *aom_img_alloc_with_border(aom_image_t *img, aom_img_fmt_t fmt,
unsigned int d_w, unsigned int d_h,
unsigned int align,
unsigned int size_align,
unsigned int border);
/*!\brief Set the rectangle identifying the displayed portion of the image
*
* Updates the displayed rectangle (aka viewport) on the image surface to
* match the specified coordinates and size. Specifically, sets img->d_w,
* img->d_h, and elements of the img->planes[] array.
*
* \param[in] img Image descriptor
* \param[in] x leftmost column
* \param[in] y topmost row
* \param[in] w width
* \param[in] h height
* \param[in] border A border that is padded on four sides of the image.
*
* \return 0 if the requested rectangle is valid, nonzero (-1) otherwise.
*/
int aom_img_set_rect(aom_image_t *img, unsigned int x, unsigned int y,
unsigned int w, unsigned int h, unsigned int border);
/*!\brief Flip the image vertically (top for bottom)
*
* Adjusts the image descriptor's pointers and strides to make the image
* be referenced upside-down.
*
* \param[in] img Image descriptor
*/
void aom_img_flip(aom_image_t *img);
/*!\brief Close an image descriptor
*
* Frees all allocated storage associated with an image descriptor.
*
* \param[in] img Image descriptor
*/
void aom_img_free(aom_image_t *img);
/*!\brief Get the width of a plane
*
* Get the width of a plane of an image
*
* \param[in] img Image descriptor
* \param[in] plane Plane index
*/
int aom_img_plane_width(const aom_image_t *img, int plane);
/*!\brief Get the height of a plane
*
* Get the height of a plane of an image
*
* \param[in] img Image descriptor
* \param[in] plane Plane index
*/
int aom_img_plane_height(const aom_image_t *img, int plane);
/*!\brief Add metadata to image.
*
* Adds metadata to aom_image_t.
* Function makes a copy of the provided data parameter.
* Metadata insertion point is controlled by insert_flag.
*
* \param[in] img Image descriptor
* \param[in] type Metadata type
* \param[in] data Metadata contents
* \param[in] sz Metadata contents size
* \param[in] insert_flag Metadata insert flag
*
* \return Returns 0 on success. If img or data is NULL, sz is 0, or memory
* allocation fails, it returns -1.
*/
int aom_img_add_metadata(aom_image_t *img, uint32_t type, const uint8_t *data,
size_t sz, aom_metadata_insert_flags_t insert_flag);
/*!\brief Return a metadata payload stored within the image metadata array.
*
* Gets the metadata (aom_metadata_t) at the indicated index in the image
* metadata array.
*
* \param[in] img Pointer to image descriptor to get metadata from
* \param[in] index Metadata index to get from metadata array
*
* \return Returns a const pointer to the selected metadata, if img and/or index
* is invalid, it returns NULL.
*/
const aom_metadata_t *aom_img_get_metadata(const aom_image_t *img,
size_t index);
/*!\brief Return the number of metadata blocks within the image.
*
* Gets the number of metadata blocks contained within the provided image
* metadata array.
*
* \param[in] img Pointer to image descriptor to get metadata number
* from.
*
* \return Returns the size of the metadata array. If img or metadata is NULL,
* it returns 0.
*/
size_t aom_img_num_metadata(const aom_image_t *img);
/*!\brief Remove metadata from image.
*
* Removes all metadata in image metadata list and sets metadata list pointer
* to NULL.
*
* \param[in] img Image descriptor
*/
void aom_img_remove_metadata(aom_image_t *img);
/*!\brief Allocate memory for aom_metadata struct.
*
* Allocates storage for the metadata payload, sets its type and copies the
* payload data into the aom_metadata struct. A metadata payload buffer of size
* sz is allocated and sz bytes are copied from data into the payload buffer.
*
* \param[in] type Metadata type
* \param[in] data Metadata data pointer
* \param[in] sz Metadata size
* \param[in] insert_flag Metadata insert flag
*
* \return Returns the newly allocated aom_metadata struct. If data is NULL,
* sz is 0, or memory allocation fails, it returns NULL.
*/
aom_metadata_t *aom_img_metadata_alloc(uint32_t type, const uint8_t *data,
size_t sz,
aom_metadata_insert_flags_t insert_flag);
/*!\brief Free metadata struct.
*
* Free metadata struct and its buffer.
*
* \param[in] metadata Metadata struct pointer
*/
void aom_img_metadata_free(aom_metadata_t *metadata);
#ifdef __cplusplus
} // extern "C"
#endif
#endif // AOM_AOM_AOM_IMAGE_H_
|
5be05468666cc2d98c9679e3bae256eea8947a2f
|
da1500e0d3040497614d5327d2461a22e934b4d8
|
/net/http/http_status_code_list.h
|
3e62c9b25cd78f41c25ac331edfcbd07cb90972e
|
[
"BSD-3-Clause"
] |
permissive
|
youtube/cobalt
|
34085fc93972ebe05b988b15410e99845efd1968
|
acefdaaadd3ef46f10f63d1acae2259e4024d383
|
refs/heads/main
| 2023-09-01T13:09:47.225174
| 2023-09-01T08:54:54
| 2023-09-01T08:54:54
| 50,049,789
| 169
| 80
|
BSD-3-Clause
| 2023-09-14T21:50:50
| 2016-01-20T18:11:34
| null |
UTF-8
|
C
| false
| false
| 3,130
|
h
|
http_status_code_list.h
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file intentionally does not have header guards, it's included
// inside a macro to generate enum. The following line silences a
// presubmit warning that would otherwise be triggered by this:
// no-include-guard-because-multiply-included
// This file contains the list of HTTP status codes. Taken from IANA HTTP Status
// Code Registry.
// http://www.iana.org/assignments/http-status-codes/http-status-codes.xml
#ifndef HTTP_STATUS
#error "HTTP_STATUS should be defined before including this file"
#endif
// Informational 1xx
HTTP_STATUS(CONTINUE, 100, "Continue")
HTTP_STATUS(SWITCHING_PROTOCOLS, 101, "Switching Protocols")
// Successful 2xx
HTTP_STATUS(OK, 200, "OK")
HTTP_STATUS(CREATED, 201, "Created")
HTTP_STATUS(ACCEPTED, 202, "Accepted")
HTTP_STATUS(NON_AUTHORITATIVE_INFORMATION, 203, "Non-Authoritative Information")
HTTP_STATUS(NO_CONTENT, 204, "No Content")
HTTP_STATUS(RESET_CONTENT, 205, "Reset Content")
HTTP_STATUS(PARTIAL_CONTENT, 206, "Partial Content")
// Redirection 3xx
HTTP_STATUS(MULTIPLE_CHOICES, 300, "Multiple Choices")
HTTP_STATUS(MOVED_PERMANENTLY, 301, "Moved Permanently")
HTTP_STATUS(FOUND, 302, "Found")
HTTP_STATUS(SEE_OTHER, 303, "See Other")
HTTP_STATUS(NOT_MODIFIED, 304, "Not Modified")
HTTP_STATUS(USE_PROXY, 305, "Use Proxy")
// 306 is no longer used.
HTTP_STATUS(TEMPORARY_REDIRECT, 307, "Temporary Redirect")
HTTP_STATUS(PERMANENT_REDIRECT, 308, "Permanent Redirect")
// Client error 4xx
HTTP_STATUS(BAD_REQUEST, 400, "Bad Request")
HTTP_STATUS(UNAUTHORIZED, 401, "Unauthorized")
HTTP_STATUS(PAYMENT_REQUIRED, 402, "Payment Required")
HTTP_STATUS(FORBIDDEN, 403, "Forbidden")
HTTP_STATUS(NOT_FOUND, 404, "Not Found")
HTTP_STATUS(METHOD_NOT_ALLOWED, 405, "Method Not Allowed")
HTTP_STATUS(NOT_ACCEPTABLE, 406, "Not Acceptable")
HTTP_STATUS(PROXY_AUTHENTICATION_REQUIRED, 407, "Proxy Authentication Required")
HTTP_STATUS(REQUEST_TIMEOUT, 408, "Request Timeout")
HTTP_STATUS(CONFLICT, 409, "Conflict")
HTTP_STATUS(GONE, 410, "Gone")
HTTP_STATUS(LENGTH_REQUIRED, 411, "Length Required")
HTTP_STATUS(PRECONDITION_FAILED, 412, "Precondition Failed")
HTTP_STATUS(REQUEST_ENTITY_TOO_LARGE, 413, "Request Entity Too Large")
HTTP_STATUS(REQUEST_URI_TOO_LONG, 414, "Request-URI Too Long")
HTTP_STATUS(UNSUPPORTED_MEDIA_TYPE, 415, "Unsupported Media Type")
HTTP_STATUS(REQUESTED_RANGE_NOT_SATISFIABLE, 416,
"Requested Range Not Satisfiable")
HTTP_STATUS(EXPECTATION_FAILED, 417, "Expectation Failed")
// 418 returned by Cloud Print.
HTTP_STATUS(INVALID_XPRIVET_TOKEN, 418, "Invalid XPrivet Token")
HTTP_STATUS(TOO_EARLY, 425, "Too Early")
// Server error 5xx
HTTP_STATUS(INTERNAL_SERVER_ERROR, 500, "Internal Server Error")
HTTP_STATUS(NOT_IMPLEMENTED, 501, "Not Implemented")
HTTP_STATUS(BAD_GATEWAY, 502, "Bad Gateway")
HTTP_STATUS(SERVICE_UNAVAILABLE, 503, "Service Unavailable")
HTTP_STATUS(GATEWAY_TIMEOUT, 504, "Gateway Timeout")
HTTP_STATUS(VERSION_NOT_SUPPORTED, 505, "HTTP Version Not Supported")
|
9441ca1a299135114ffcf9caf9bcbfba0779e9d0
|
db229415713a206a848429321e19006b212d20d5
|
/test/wasm/simd128/narrow.c
|
7b84293b8c4b38fe7b8d0e0c1862efacbdcf2aa1
|
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] |
permissive
|
simd-everywhere/simde
|
66dd029cbd0b3814b0377c72d953f223d38e7e53
|
4d55fc25bcfddc0e2f0c744448557a070dd310c9
|
refs/heads/master
| 2023-09-04T12:55:25.455223
| 2023-08-18T12:46:56
| 2023-08-18T14:53:06
| 86,497,800
| 1,570
| 173
|
MIT
| 2023-09-07T13:41:28
| 2017-03-28T19:14:32
|
C
|
UTF-8
|
C
| false
| false
| 21,429
|
c
|
narrow.c
|
/* Copyright (c) 2021 Evan Nemerson <evan@nemerson.com>
*
* 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 SIMDE_TEST_WASM_SIMD128_INSN narrow
#include "../../../simde/wasm/simd128.h"
#include "test-simd128.h"
static int
test_simde_wasm_i8x16_narrow_i16x8(SIMDE_MUNIT_TEST_ARGS) {
#if 1
SIMDE_TEST_STRUCT_MODIFIERS struct {
int16_t a[sizeof(simde_v128_t) / sizeof(int16_t)];
int16_t b[sizeof(simde_v128_t) / sizeof(int16_t)];
int8_t r[sizeof(simde_v128_t) / sizeof(int8_t)];
} test_vec[] = {
{ { INT16_C( 116), INT16_C( 133), -INT16_C( 241), -INT16_C( 223), INT16_C( 235), -INT16_C( 224), INT16_C( 239), -INT16_C( 52) },
{ INT16_C( 128), -INT16_C( 85), -INT16_C( 176), -INT16_C( 85), -INT16_C( 219), INT16_C( 95), INT16_C( 75), -INT16_C( 195) },
{ INT8_C( 116), INT8_MAX, INT8_MIN, INT8_MIN, INT8_MAX, INT8_MIN, INT8_MAX, -INT8_C( 52),
INT8_MAX, -INT8_C( 85), INT8_MIN, -INT8_C( 85), INT8_MIN, INT8_C( 95), INT8_C( 75), INT8_MIN } },
{ { INT16_C( 193), INT16_C( 211), INT16_C( 124), -INT16_C( 67), INT16_C( 114), -INT16_C( 198), -INT16_C( 137), -INT16_C( 95) },
{ INT16_C( 19), INT16_C( 242), INT16_C( 13), INT16_C( 136), INT16_C( 37), -INT16_C( 218), -INT16_C( 145), -INT16_C( 174) },
{ INT8_MAX, INT8_MAX, INT8_C( 124), -INT8_C( 67), INT8_C( 114), INT8_MIN, INT8_MIN, -INT8_C( 95),
INT8_C( 19), INT8_MAX, INT8_C( 13), INT8_MAX, INT8_C( 37), INT8_MIN, INT8_MIN, INT8_MIN } },
{ { -INT16_C( 6), -INT16_C( 8), -INT16_C( 38), INT16_C( 139), -INT16_C( 116), INT16_C( 127), -INT16_C( 222), -INT16_C( 123) },
{ INT16_C( 124), -INT16_C( 138), -INT16_C( 149), -INT16_C( 43), -INT16_C( 235), INT16_C( 150), -INT16_C( 31), INT16_C( 225) },
{ -INT8_C( 6), -INT8_C( 8), -INT8_C( 38), INT8_MAX, -INT8_C( 116), INT8_MAX, INT8_MIN, -INT8_C( 123),
INT8_C( 124), INT8_MIN, INT8_MIN, -INT8_C( 43), INT8_MIN, INT8_MAX, -INT8_C( 31), INT8_MAX } },
{ { INT16_C( 73), -INT16_C( 51), -INT16_C( 206), INT16_C( 208), -INT16_C( 217), -INT16_C( 46), -INT16_C( 200), INT16_C( 18) },
{ INT16_C( 13), INT16_C( 253), INT16_C( 221), INT16_C( 70), -INT16_C( 65), INT16_C( 247), -INT16_C( 160), -INT16_C( 222) },
{ INT8_C( 73), -INT8_C( 51), INT8_MIN, INT8_MAX, INT8_MIN, -INT8_C( 46), INT8_MIN, INT8_C( 18),
INT8_C( 13), INT8_MAX, INT8_MAX, INT8_C( 70), -INT8_C( 65), INT8_MAX, INT8_MIN, INT8_MIN } },
{ { INT16_C( 18), INT16_C( 27), -INT16_C( 126), -INT16_C( 50), -INT16_C( 51), INT16_C( 111), -INT16_C( 241), INT16_C( 175) },
{ -INT16_C( 240), INT16_C( 91), INT16_C( 245), -INT16_C( 102), -INT16_C( 195), INT16_C( 220), -INT16_C( 38), INT16_C( 6) },
{ INT8_C( 18), INT8_C( 27), -INT8_C( 126), -INT8_C( 50), -INT8_C( 51), INT8_C( 111), INT8_MIN, INT8_MAX,
INT8_MIN, INT8_C( 91), INT8_MAX, -INT8_C( 102), INT8_MIN, INT8_MAX, -INT8_C( 38), INT8_C( 6) } },
{ { -INT16_C( 192), INT16_C( 174), INT16_C( 230), INT16_C( 152), INT16_C( 198), -INT16_C( 102), INT16_C( 8), -INT16_C( 225) },
{ INT16_C( 164), -INT16_C( 246), -INT16_C( 220), -INT16_C( 9), INT16_C( 127), INT16_C( 117), INT16_C( 220), -INT16_C( 168) },
{ INT8_MIN, INT8_MAX, INT8_MAX, INT8_MAX, INT8_MAX, -INT8_C( 102), INT8_C( 8), INT8_MIN,
INT8_MAX, INT8_MIN, INT8_MIN, -INT8_C( 9), INT8_MAX, INT8_C( 117), INT8_MAX, INT8_MIN } },
{ { -INT16_C( 108), INT16_C( 71), -INT16_C( 57), INT16_C( 250), INT16_C( 25), -INT16_C( 146), INT16_C( 113), INT16_C( 49) },
{ INT16_C( 132), -INT16_C( 107), INT16_C( 94), INT16_C( 68), -INT16_C( 25), -INT16_C( 78), -INT16_C( 10), INT16_C( 204) },
{ -INT8_C( 108), INT8_C( 71), -INT8_C( 57), INT8_MAX, INT8_C( 25), INT8_MIN, INT8_C( 113), INT8_C( 49),
INT8_MAX, -INT8_C( 107), INT8_C( 94), INT8_C( 68), -INT8_C( 25), -INT8_C( 78), -INT8_C( 10), INT8_MAX } },
{ { -INT16_C( 5), INT16_C( 153), -INT16_C( 239), -INT16_C( 172), -INT16_C( 100), INT16_C( 143), -INT16_C( 131), -INT16_C( 172) },
{ -INT16_C( 40), -INT16_C( 232), INT16_C( 203), -INT16_C( 116), -INT16_C( 57), -INT16_C( 103), INT16_C( 51), -INT16_C( 203) },
{ -INT8_C( 5), INT8_MAX, INT8_MIN, INT8_MIN, -INT8_C( 100), INT8_MAX, INT8_MIN, INT8_MIN,
-INT8_C( 40), INT8_MIN, INT8_MAX, -INT8_C( 116), -INT8_C( 57), -INT8_C( 103), INT8_C( 51), INT8_MIN } }
};
for (size_t i = 0 ; i < (sizeof(test_vec) / sizeof(test_vec[0])) ; i++) {
simde_v128_t a = simde_wasm_v128_load(test_vec[i].a);
simde_v128_t b = simde_wasm_v128_load(test_vec[i].b);
simde_v128_t r = simde_wasm_i8x16_narrow_i16x8(a, b);
simde_test_wasm_i8x16_assert_equal(r, simde_wasm_v128_load(test_vec[i].r));
}
return 0;
#else
fputc('\n', stdout);
for (int i = 0 ; i < 8 ; i++) {
simde_v128_t
a = simde_test_wasm_i16x8_random(),
b = simde_test_wasm_i16x8_random(),
r;
a = simde_wasm_i16x8_shr(a, 7);
b = simde_wasm_i16x8_shr(b, 7);
r = simde_wasm_i8x16_narrow_i16x8(a, b);
simde_test_wasm_i16x8_write(3, a, SIMDE_TEST_VEC_POS_FIRST);
simde_test_wasm_i16x8_write(3, b, SIMDE_TEST_VEC_POS_MIDDLE);
simde_test_wasm_i8x16_write(3, r, SIMDE_TEST_VEC_POS_LAST);
}
return 1;
#endif
}
static int
test_simde_wasm_i16x8_narrow_i32x4(SIMDE_MUNIT_TEST_ARGS) {
#if 1
SIMDE_TEST_STRUCT_MODIFIERS struct {
int32_t a[sizeof(simde_v128_t) / sizeof(int32_t)];
int32_t b[sizeof(simde_v128_t) / sizeof(int32_t)];
int16_t r[sizeof(simde_v128_t) / sizeof(int16_t)];
} test_vec[] = {
{ { -INT32_C( 45502), -INT32_C( 35793), INT32_C( 59913), -INT32_C( 50624) },
{ -INT32_C( 13889), -INT32_C( 41254), INT32_C( 29817), INT32_C( 35350) },
{ INT16_MIN, INT16_MIN, INT16_MAX, INT16_MIN, -INT16_C( 13889), INT16_MIN, INT16_C( 29817), INT16_MAX } },
{ { -INT32_C( 477), INT32_C( 30424), -INT32_C( 34428), -INT32_C( 36373) },
{ INT32_C( 26474), -INT32_C( 57504), -INT32_C( 59574), -INT32_C( 59903) },
{ -INT16_C( 477), INT16_C( 30424), INT16_MIN, INT16_MIN, INT16_C( 26474), INT16_MIN, INT16_MIN, INT16_MIN } },
{ { -INT32_C( 51519), -INT32_C( 22179), INT32_C( 63923), -INT32_C( 64543) },
{ INT32_C( 50166), INT32_C( 29946), -INT32_C( 58420), -INT32_C( 29140) },
{ INT16_MIN, -INT16_C( 22179), INT16_MAX, INT16_MIN, INT16_MAX, INT16_C( 29946), INT16_MIN, -INT16_C( 29140) } },
{ { INT32_C( 27529), INT32_C( 25233), -INT32_C( 20166), INT32_C( 6470) },
{ -INT32_C( 51153), INT32_C( 41405), INT32_C( 7844), INT32_C( 12736) },
{ INT16_C( 27529), INT16_C( 25233), -INT16_C( 20166), INT16_C( 6470), INT16_MIN, INT16_MAX, INT16_C( 7844), INT16_C( 12736) } },
{ { INT32_C( 65271), INT32_C( 57830), INT32_C( 9276), INT32_C( 36250) },
{ -INT32_C( 53007), INT32_C( 55036), INT32_C( 843), INT32_C( 58187) },
{ INT16_MAX, INT16_MAX, INT16_C( 9276), INT16_MAX, INT16_MIN, INT16_MAX, INT16_C( 843), INT16_MAX } },
{ { INT32_C( 16213), INT32_C( 11140), INT32_C( 56774), -INT32_C( 26224) },
{ INT32_C( 39768), -INT32_C( 22281), INT32_C( 8963), INT32_C( 21272) },
{ INT16_C( 16213), INT16_C( 11140), INT16_MAX, -INT16_C( 26224), INT16_MAX, -INT16_C( 22281), INT16_C( 8963), INT16_C( 21272) } },
{ { INT32_C( 23143), INT32_C( 60768), -INT32_C( 57776), INT32_C( 25315) },
{ INT32_C( 27137), -INT32_C( 43172), -INT32_C( 25395), INT32_C( 3207) },
{ INT16_C( 23143), INT16_MAX, INT16_MIN, INT16_C( 25315), INT16_C( 27137), INT16_MIN, -INT16_C( 25395), INT16_C( 3207) } },
{ { INT32_C( 27685), -INT32_C( 42675), INT32_C( 45345), -INT32_C( 22230) },
{ INT32_C( 7473), -INT32_C( 52503), INT32_C( 35935), -INT32_C( 23455) },
{ INT16_C( 27685), INT16_MIN, INT16_MAX, -INT16_C( 22230), INT16_C( 7473), INT16_MIN, INT16_MAX, -INT16_C( 23455) } }
};
for (size_t i = 0 ; i < (sizeof(test_vec) / sizeof(test_vec[0])) ; i++) {
simde_v128_t a = simde_wasm_v128_load(test_vec[i].a);
simde_v128_t b = simde_wasm_v128_load(test_vec[i].b);
simde_v128_t r = simde_wasm_i16x8_narrow_i32x4(a, b);
simde_test_wasm_i16x8_assert_equal(r, simde_wasm_v128_load(test_vec[i].r));
}
return 0;
#else
fputc('\n', stdout);
for (int i = 0 ; i < 8 ; i++) {
simde_v128_t
a = simde_test_wasm_i32x4_random(),
b = simde_test_wasm_i32x4_random(),
r;
a = simde_wasm_i32x4_shr(a, 15);
b = simde_wasm_i32x4_shr(b, 15);
r = simde_wasm_i16x8_narrow_i32x4(a, b);
simde_test_wasm_i32x4_write(3, a, SIMDE_TEST_VEC_POS_FIRST);
simde_test_wasm_i32x4_write(3, b, SIMDE_TEST_VEC_POS_MIDDLE);
simde_test_wasm_i16x8_write(3, r, SIMDE_TEST_VEC_POS_LAST);
}
return 1;
#endif
}
static int
test_simde_wasm_u8x16_narrow_i16x8(SIMDE_MUNIT_TEST_ARGS) {
#if 1
SIMDE_TEST_STRUCT_MODIFIERS struct {
int16_t a[sizeof(simde_v128_t) / sizeof(int16_t)];
int16_t b[sizeof(simde_v128_t) / sizeof(int16_t)];
uint8_t r[sizeof(simde_v128_t) / sizeof(int8_t)];
} test_vec[] = {
{ { INT16_C( 311), -INT16_C( 392), -INT16_C( 33), -INT16_C( 332), -INT16_C( 404), -INT16_C( 44), -INT16_C( 7), INT16_C( 71) },
{ -INT16_C( 386), INT16_C( 397), INT16_C( 506), -INT16_C( 408), -INT16_C( 181), -INT16_C( 118), INT16_C( 47), -INT16_C( 273) },
{ UINT8_MAX, UINT8_C( 0), UINT8_C( 0), UINT8_C( 0), UINT8_C( 0), UINT8_C( 0), UINT8_C( 0), UINT8_C( 71),
UINT8_C( 0), UINT8_MAX, UINT8_MAX, UINT8_C( 0), UINT8_C( 0), UINT8_C( 0), UINT8_C( 47), UINT8_C( 0) } },
{ { INT16_C( 132), -INT16_C( 316), INT16_C( 399), INT16_C( 217), -INT16_C( 498), -INT16_C( 238), -INT16_C( 486), INT16_C( 171) },
{ INT16_C( 187), -INT16_C( 33), -INT16_C( 440), -INT16_C( 234), INT16_C( 403), INT16_C( 92), INT16_C( 217), -INT16_C( 245) },
{ UINT8_C(132), UINT8_C( 0), UINT8_MAX, UINT8_C(217), UINT8_C( 0), UINT8_C( 0), UINT8_C( 0), UINT8_C(171),
UINT8_C(187), UINT8_C( 0), UINT8_C( 0), UINT8_C( 0), UINT8_MAX, UINT8_C( 92), UINT8_C(217), UINT8_C( 0) } },
{ { INT16_C( 340), INT16_C( 74), -INT16_C( 266), INT16_C( 308), -INT16_C( 180), INT16_C( 94), INT16_C( 291), INT16_C( 267) },
{ INT16_C( 35), -INT16_C( 178), -INT16_C( 26), INT16_C( 45), -INT16_C( 249), INT16_C( 242), INT16_C( 374), -INT16_C( 99) },
{ UINT8_MAX, UINT8_C( 74), UINT8_C( 0), UINT8_MAX, UINT8_C( 0), UINT8_C( 94), UINT8_MAX, UINT8_MAX,
UINT8_C( 35), UINT8_C( 0), UINT8_C( 0), UINT8_C( 45), UINT8_C( 0), UINT8_C(242), UINT8_MAX, UINT8_C( 0) } },
{ { INT16_C( 156), -INT16_C( 158), -INT16_C( 368), -INT16_C( 406), INT16_C( 281), -INT16_C( 210), -INT16_C( 360), -INT16_C( 3) },
{ -INT16_C( 21), INT16_C( 219), INT16_C( 75), INT16_C( 340), INT16_C( 367), INT16_C( 27), -INT16_C( 506), INT16_C( 454) },
{ UINT8_C(156), UINT8_C( 0), UINT8_C( 0), UINT8_C( 0), UINT8_MAX, UINT8_C( 0), UINT8_C( 0), UINT8_C( 0),
UINT8_C( 0), UINT8_C(219), UINT8_C( 75), UINT8_MAX, UINT8_MAX, UINT8_C( 27), UINT8_C( 0), UINT8_MAX } },
{ { INT16_C( 50), -INT16_C( 507), -INT16_C( 512), INT16_C( 435), INT16_C( 226), INT16_C( 396), INT16_C( 120), -INT16_C( 245) },
{ INT16_C( 436), -INT16_C( 370), -INT16_C( 228), INT16_C( 195), -INT16_C( 148), INT16_C( 418), -INT16_C( 330), INT16_C( 39) },
{ UINT8_C( 50), UINT8_C( 0), UINT8_C( 0), UINT8_MAX, UINT8_C(226), UINT8_MAX, UINT8_C(120), UINT8_C( 0),
UINT8_MAX, UINT8_C( 0), UINT8_C( 0), UINT8_C(195), UINT8_C( 0), UINT8_MAX, UINT8_C( 0), UINT8_C( 39) } },
{ { -INT16_C( 135), INT16_C( 63), INT16_C( 384), INT16_C( 79), INT16_C( 198), -INT16_C( 455), -INT16_C( 477), INT16_C( 370) },
{ INT16_C( 357), -INT16_C( 235), INT16_C( 137), -INT16_C( 121), INT16_C( 427), -INT16_C( 202), -INT16_C( 57), INT16_C( 200) },
{ UINT8_C( 0), UINT8_C( 63), UINT8_MAX, UINT8_C( 79), UINT8_C(198), UINT8_C( 0), UINT8_C( 0), UINT8_MAX,
UINT8_MAX, UINT8_C( 0), UINT8_C(137), UINT8_C( 0), UINT8_MAX, UINT8_C( 0), UINT8_C( 0), UINT8_C(200) } },
{ { -INT16_C( 475), -INT16_C( 325), INT16_C( 327), -INT16_C( 325), -INT16_C( 66), INT16_C( 164), -INT16_C( 208), INT16_C( 251) },
{ -INT16_C( 359), -INT16_C( 192), INT16_C( 430), -INT16_C( 38), INT16_C( 511), -INT16_C( 112), -INT16_C( 125), INT16_C( 231) },
{ UINT8_C( 0), UINT8_C( 0), UINT8_MAX, UINT8_C( 0), UINT8_C( 0), UINT8_C(164), UINT8_C( 0), UINT8_C(251),
UINT8_C( 0), UINT8_C( 0), UINT8_MAX, UINT8_C( 0), UINT8_MAX, UINT8_C( 0), UINT8_C( 0), UINT8_C(231) } },
{ { INT16_C( 201), -INT16_C( 170), INT16_C( 245), INT16_C( 507), -INT16_C( 54), -INT16_C( 256), INT16_C( 136), INT16_C( 181) },
{ INT16_C( 128), INT16_C( 421), -INT16_C( 241), INT16_C( 368), INT16_C( 151), -INT16_C( 152), -INT16_C( 490), -INT16_C( 346) },
{ UINT8_C(201), UINT8_C( 0), UINT8_C(245), UINT8_MAX, UINT8_C( 0), UINT8_C( 0), UINT8_C(136), UINT8_C(181),
UINT8_C(128), UINT8_MAX, UINT8_C( 0), UINT8_MAX, UINT8_C(151), UINT8_C( 0), UINT8_C( 0), UINT8_C( 0) } }
};
for (size_t i = 0 ; i < (sizeof(test_vec) / sizeof(test_vec[0])) ; i++) {
simde_v128_t a = simde_wasm_v128_load(test_vec[i].a);
simde_v128_t b = simde_wasm_v128_load(test_vec[i].b);
simde_v128_t r = simde_wasm_u8x16_narrow_i16x8(a, b);
simde_test_wasm_u8x16_assert_equal(r, simde_wasm_v128_load(test_vec[i].r));
}
return 0;
#else
fputc('\n', stdout);
for (int i = 0 ; i < 8 ; i++) {
simde_v128_t
a = simde_test_wasm_i16x8_random(),
b = simde_test_wasm_i16x8_random(),
r;
a = simde_wasm_i16x8_shr(a, 6);
b = simde_wasm_i16x8_shr(b, 6);
r = simde_wasm_u8x16_narrow_i16x8(a, b);
simde_test_wasm_i16x8_write(3, a, SIMDE_TEST_VEC_POS_FIRST);
simde_test_wasm_i16x8_write(3, b, SIMDE_TEST_VEC_POS_MIDDLE);
simde_test_wasm_u8x16_write(3, r, SIMDE_TEST_VEC_POS_LAST);
}
return 1;
#endif
}
static int
test_simde_wasm_u16x8_narrow_i32x4(SIMDE_MUNIT_TEST_ARGS) {
#if 1
SIMDE_TEST_STRUCT_MODIFIERS struct {
int32_t a[sizeof(simde_v128_t) / sizeof(int32_t)];
int32_t b[sizeof(simde_v128_t) / sizeof(int32_t)];
uint16_t r[sizeof(simde_v128_t) / sizeof(int16_t)];
} test_vec[] = {
{ { -INT32_C( 18757), -INT32_C( 67527), -INT32_C( 108538), INT32_C( 121671) },
{ INT32_C( 3463), -INT32_C( 19911), INT32_C( 38807), INT32_C( 61775) },
{ UINT16_C( 0), UINT16_C( 0), UINT16_C( 0), UINT16_MAX, UINT16_C( 3463), UINT16_C( 0), UINT16_C(38807), UINT16_C(61775) } },
{ { INT32_C( 113334), -INT32_C( 15674), INT32_C( 35649), -INT32_C( 98091) },
{ -INT32_C( 58412), -INT32_C( 124646), -INT32_C( 63794), INT32_C( 85211) },
{ UINT16_MAX, UINT16_C( 0), UINT16_C(35649), UINT16_C( 0), UINT16_C( 0), UINT16_C( 0), UINT16_C( 0), UINT16_MAX } },
{ { -INT32_C( 123522), -INT32_C( 77501), INT32_C( 24629), -INT32_C( 98808) },
{ -INT32_C( 15033), -INT32_C( 98185), -INT32_C( 8036), -INT32_C( 28632) },
{ UINT16_C( 0), UINT16_C( 0), UINT16_C(24629), UINT16_C( 0), UINT16_C( 0), UINT16_C( 0), UINT16_C( 0), UINT16_C( 0) } },
{ { INT32_C( 65892), INT32_C( 25331), -INT32_C( 26070), -INT32_C( 120912) },
{ -INT32_C( 70654), INT32_C( 88287), -INT32_C( 98231), -INT32_C( 18033) },
{ UINT16_MAX, UINT16_C(25331), UINT16_C( 0), UINT16_C( 0), UINT16_C( 0), UINT16_MAX, UINT16_C( 0), UINT16_C( 0) } },
{ { INT32_C( 25658), INT32_C( 113784), -INT32_C( 68341), -INT32_C( 58573) },
{ -INT32_C( 71945), INT32_C( 3981), -INT32_C( 30509), INT32_C( 114913) },
{ UINT16_C(25658), UINT16_MAX, UINT16_C( 0), UINT16_C( 0), UINT16_C( 0), UINT16_C( 3981), UINT16_C( 0), UINT16_MAX } },
{ { INT32_C( 52573), -INT32_C( 99853), INT32_C( 14110), -INT32_C( 61428) },
{ -INT32_C( 64749), INT32_C( 82798), INT32_C( 124351), -INT32_C( 44001) },
{ UINT16_C(52573), UINT16_C( 0), UINT16_C(14110), UINT16_C( 0), UINT16_C( 0), UINT16_MAX, UINT16_MAX, UINT16_C( 0) } },
{ { -INT32_C( 14822), -INT32_C( 8506), -INT32_C( 113448), INT32_C( 44883) },
{ INT32_C( 73344), -INT32_C( 57352), INT32_C( 127436), -INT32_C( 17972) },
{ UINT16_C( 0), UINT16_C( 0), UINT16_C( 0), UINT16_C(44883), UINT16_MAX, UINT16_C( 0), UINT16_MAX, UINT16_C( 0) } },
{ { INT32_C( 24525), -INT32_C( 127031), -INT32_C( 56704), -INT32_C( 115436) },
{ INT32_C( 76270), -INT32_C( 21925), -INT32_C( 104518), INT32_C( 98690) },
{ UINT16_C(24525), UINT16_C( 0), UINT16_C( 0), UINT16_C( 0), UINT16_MAX, UINT16_C( 0), UINT16_C( 0), UINT16_MAX } }
};
for (size_t i = 0 ; i < (sizeof(test_vec) / sizeof(test_vec[0])) ; i++) {
simde_v128_t a = simde_wasm_v128_load(test_vec[i].a);
simde_v128_t b = simde_wasm_v128_load(test_vec[i].b);
simde_v128_t r = simde_wasm_u16x8_narrow_i32x4(a, b);
simde_test_wasm_u16x8_assert_equal(r, simde_wasm_v128_load(test_vec[i].r));
}
return 0;
#else
fputc('\n', stdout);
for (int i = 0 ; i < 8 ; i++) {
simde_v128_t
a = simde_test_wasm_i32x4_random(),
b = simde_test_wasm_i32x4_random(),
r;
a = simde_wasm_i32x4_shr(a, 14);
b = simde_wasm_i32x4_shr(b, 14);
r = simde_wasm_u16x8_narrow_i32x4(a, b);
simde_test_wasm_i32x4_write(3, a, SIMDE_TEST_VEC_POS_FIRST);
simde_test_wasm_i32x4_write(3, b, SIMDE_TEST_VEC_POS_MIDDLE);
simde_test_wasm_u16x8_write(3, r, SIMDE_TEST_VEC_POS_LAST);
}
return 1;
#endif
}
SIMDE_TEST_FUNC_LIST_BEGIN
SIMDE_TEST_FUNC_LIST_ENTRY(wasm_i8x16_narrow_i16x8)
SIMDE_TEST_FUNC_LIST_ENTRY(wasm_i16x8_narrow_i32x4)
SIMDE_TEST_FUNC_LIST_ENTRY(wasm_u8x16_narrow_i16x8)
SIMDE_TEST_FUNC_LIST_ENTRY(wasm_u16x8_narrow_i32x4)
SIMDE_TEST_FUNC_LIST_END
#include "test-simd128-footer.h"
|
e868b461c9bb2a229a7a7d8521d845e437357a26
|
50e95229b9a1161ac294137120aaba94c9eb06bc
|
/sources/ippcp/pcpeccpstdca_160r2.c
|
164eca82ac3a89f12382dab070dca7522562c4ba
|
[
"Apache-2.0",
"Intel"
] |
permissive
|
intel/ipp-crypto
|
f0f05b87203705e82603db67bed5f8def13a5ee8
|
36e76e2388f3dd10cc440e213dfcf6ef59a0dfb8
|
refs/heads/develop
| 2023-09-04T08:15:06.851373
| 2023-07-27T12:47:12
| 2023-07-27T12:47:12
| 140,034,345
| 304
| 81
|
Apache-2.0
| 2023-08-30T17:18:36
| 2018-07-06T22:16:28
|
C
|
UTF-8
|
C
| false
| false
| 1,824
|
c
|
pcpeccpstdca_160r2.c
|
/*******************************************************************************
* Copyright (C) 2020 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions
* and limitations under the License.
*
*******************************************************************************/
/*
//
// Purpose:
// Cryptography Primitive.
// ECC over Prime Finite Field (recommended ECC parameters)
//
// Contents:
// secp160r2
//
*/
#include "owndefs.h"
#include "owncp.h"
#include "pcpgfpstuff.h"
#if defined( _IPP_DATA )
/*
// Recommended Parameters secp160r2
*/
const BNU_CHUNK_T secp160r2_p[] = { // 2^160 -2^32 -2^14 -2^12 -2^9 -2^8 -2^7 -2^2 -1
LL(0xFFFFAC73, 0xFFFFFFFE), LL(0xFFFFFFFF, 0xFFFFFFFF), L_(0xFFFFFFFF)};
const BNU_CHUNK_T secp160r2_a[] = {
LL(0xFFFFAC70, 0xFFFFFFFE), LL(0xFFFFFFFF, 0xFFFFFFFF), L_(0xFFFFFFFF)};
const BNU_CHUNK_T secp160r2_b[] = {
LL(0xF50388BA, 0x04664D5A), LL(0xAB572749, 0xFB59EB8B), L_(0xB4E134D3)};
const BNU_CHUNK_T secp160r2_gx[] = {
LL(0x3144CE6D, 0x30F7199D), LL(0x1F4FF11B, 0x293A117E), L_(0x52DCB034)};
const BNU_CHUNK_T secp160r2_gy[] = {
LL(0xA7D43F2E, 0xF9982CFE), LL(0xE071FA0D, 0xE331F296), L_(0xFEAFFEF2)};
const BNU_CHUNK_T secp160r2_r[] = {
LL(0xF3A1A16B, 0xE786A818), LL(0x0000351E, 0x00000000), LL(0x00000000, 0x1)};
BNU_CHUNK_T secp160r2_h = 1;
#endif /* _IPP_DATA */
|
6b6214511a615a7ad1c44824f968e74dbd4ee40a
|
ff477a586b946c575441b6189123ab86c175e5ae
|
/htslib/htslib/kstring.h
|
53a19806d162f327595994c96a807aee087f8674
|
[
"MIT",
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
pysam-developers/pysam
|
5552e4903106fc253869a405f4a2c068c6bd65c5
|
0663ca85739877e5dd05c0eb2512a8bcaa515b39
|
refs/heads/master
| 2023-08-16T19:10:17.566296
| 2023-08-15T10:06:59
| 2023-08-15T12:28:29
| 16,557,526
| 678
| 332
|
MIT
| 2023-09-14T10:40:22
| 2014-02-05T20:38:10
|
C
|
UTF-8
|
C
| false
| false
| 11,462
|
h
|
kstring.h
|
/* The MIT License
Copyright (C) 2011 by Attractive Chaos <attractor@live.co.uk>
Copyright (C) 2013-2014, 2016, 2018-2020, 2022 Genome Research 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 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 KSTRING_H
#define KSTRING_H
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <limits.h>
#include <errno.h>
#include <sys/types.h>
#include "hts_defs.h"
#include "kroundup.h"
#if defined __GNUC__ && (__GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ > 4))
#ifdef __MINGW_PRINTF_FORMAT
#define KS_ATTR_PRINTF(fmt, arg) __attribute__((__format__ (__MINGW_PRINTF_FORMAT, fmt, arg)))
#else
#define KS_ATTR_PRINTF(fmt, arg) __attribute__((__format__ (__printf__, fmt, arg)))
#endif // __MINGW_PRINTF_FORMAT
#else
#define KS_ATTR_PRINTF(fmt, arg)
#endif
#ifndef HAVE___BUILTIN_CLZ
#if defined __GNUC__ && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
#define HAVE___BUILTIN_CLZ 1
#endif
#endif
// Ensure ssize_t exists within this header. All #includes must precede this,
// and ssize_t must be undefined again at the end of this header.
#if defined _MSC_VER && defined _INTPTR_T_DEFINED && !defined _SSIZE_T_DEFINED && !defined ssize_t
#define HTSLIB_SSIZE_T
#define ssize_t intptr_t
#endif
/* kstring_t is a simple non-opaque type whose fields are likely to be
* used directly by user code (but see also ks_str() and ks_len() below).
* A kstring_t object is initialised by either of
* kstring_t str = KS_INITIALIZE;
* kstring_t str; ...; ks_initialize(&str);
* and either ownership of the underlying buffer should be given away before
* the object disappears (see ks_release() below) or the kstring_t should be
* destroyed with ks_free(&str) or free(str.s) */
#ifndef KSTRING_T
#define KSTRING_T kstring_t
typedef struct kstring_t {
size_t l, m;
char *s;
} kstring_t;
#endif
typedef struct ks_tokaux_t {
uint64_t tab[4];
int sep, finished;
const char *p; // end of the current token
} ks_tokaux_t;
#ifdef __cplusplus
extern "C" {
#endif
HTSLIB_EXPORT
int kvsprintf(kstring_t *s, const char *fmt, va_list ap) KS_ATTR_PRINTF(2,0);
HTSLIB_EXPORT
int ksprintf(kstring_t *s, const char *fmt, ...) KS_ATTR_PRINTF(2,3);
HTSLIB_EXPORT
int kputd(double d, kstring_t *s); // custom %g only handler
HTSLIB_EXPORT
int ksplit_core(char *s, int delimiter, int *_max, int **_offsets);
HTSLIB_EXPORT
char *kstrstr(const char *str, const char *pat, int **_prep);
HTSLIB_EXPORT
char *kstrnstr(const char *str, const char *pat, int n, int **_prep);
HTSLIB_EXPORT
void *kmemmem(const void *_str, int n, const void *_pat, int m, int **_prep);
/* kstrtok() is similar to strtok_r() except that str is not
* modified and both str and sep can be NULL. For efficiency, it is
* actually recommended to set both to NULL in the subsequent calls
* if sep is not changed. */
HTSLIB_EXPORT
char *kstrtok(const char *str, const char *sep, ks_tokaux_t *aux);
/* kgetline() uses the supplied fgets()-like function to read a "\n"-
* or "\r\n"-terminated line from fp. The line read is appended to the
* kstring without its terminator and 0 is returned; EOF is returned at
* EOF or on error (determined by querying fp, as per fgets()). */
typedef char *kgets_func(char *, int, void *);
HTSLIB_EXPORT
int kgetline(kstring_t *s, kgets_func *fgets_fn, void *fp);
/* kgetline2() uses the supplied hgetln()-like function to read a "\n"-
* or "\r\n"-terminated line from fp. The line read is appended to the
* ksring without its terminator and 0 is returned; EOF is returned at
* EOF or on error (determined by querying fp, as per fgets()). */
typedef ssize_t kgets_func2(char *, size_t, void *);
HTSLIB_EXPORT
int kgetline2(kstring_t *s, kgets_func2 *fgets_fn, void *fp);
#ifdef __cplusplus
}
#endif
/// kstring initializer for structure assignment
#define KS_INITIALIZE { 0, 0, NULL }
/// kstring initializer for pointers
/**
@note Not to be used if the buffer has been allocated. Use ks_release()
or ks_clear() instead.
*/
static inline void ks_initialize(kstring_t *s)
{
s->l = s->m = 0;
s->s = NULL;
}
/// Resize a kstring to a given capacity
static inline int ks_resize(kstring_t *s, size_t size)
{
if (s->m < size) {
char *tmp;
size = (size > (SIZE_MAX>>2)) ? size : size + (size >> 1);
tmp = (char*)realloc(s->s, size);
if (!tmp)
return -1;
s->s = tmp;
s->m = size;
}
return 0;
}
/// Increase kstring capacity by a given number of bytes
static inline int ks_expand(kstring_t *s, size_t expansion)
{
size_t new_size = s->l + expansion;
if (new_size < s->l) // Overflow check
return -1;
return ks_resize(s, new_size);
}
/// Returns the kstring buffer
static inline char *ks_str(kstring_t *s)
{
return s->s;
}
/// Returns the kstring buffer, or an empty string if l == 0
/**
* Unlike ks_str(), this function will never return NULL. If the kstring is
* empty it will return a read-only empty string. As the returned value
* may be read-only, the caller should not attempt to modify it.
*/
static inline const char *ks_c_str(kstring_t *s)
{
return s->l && s->s ? s->s : "";
}
static inline size_t ks_len(kstring_t *s)
{
return s->l;
}
/// Reset kstring length to zero
/**
@return The kstring itself
Example use: kputsn(string, len, ks_clear(s))
*/
static inline kstring_t *ks_clear(kstring_t *s)
{
s->l = 0;
return s;
}
// Give ownership of the underlying buffer away to something else (making
// that something else responsible for freeing it), leaving the kstring_t
// empty and ready to be used again, or ready to go out of scope without
// needing free(str.s) to prevent a memory leak.
static inline char *ks_release(kstring_t *s)
{
char *ss = s->s;
s->l = s->m = 0;
s->s = NULL;
return ss;
}
/// Safely free the underlying buffer in a kstring.
static inline void ks_free(kstring_t *s)
{
if (s) {
free(s->s);
ks_initialize(s);
}
}
static inline int kputsn(const char *p, size_t l, kstring_t *s)
{
size_t new_sz = s->l + l + 2;
if (new_sz <= s->l || ks_resize(s, new_sz) < 0)
return EOF;
memcpy(s->s + s->l, p, l);
s->l += l;
s->s[s->l] = 0;
return l;
}
static inline int kputs(const char *p, kstring_t *s)
{
if (!p) { errno = EFAULT; return -1; }
return kputsn(p, strlen(p), s);
}
static inline int kputc(int c, kstring_t *s)
{
if (ks_resize(s, s->l + 2) < 0)
return EOF;
s->s[s->l++] = c;
s->s[s->l] = 0;
return (unsigned char)c;
}
static inline int kputc_(int c, kstring_t *s)
{
if (ks_resize(s, s->l + 1) < 0)
return EOF;
s->s[s->l++] = c;
return 1;
}
static inline int kputsn_(const void *p, size_t l, kstring_t *s)
{
size_t new_sz = s->l + l;
if (new_sz < s->l || ks_resize(s, new_sz ? new_sz : 1) < 0)
return EOF;
memcpy(s->s + s->l, p, l);
s->l += l;
return l;
}
static inline int kputuw(unsigned x, kstring_t *s)
{
#if HAVE___BUILTIN_CLZ && UINT_MAX == 4294967295U
static const unsigned int kputuw_num_digits[32] = {
10, 10, 10, 9, 9, 9, 8, 8,
8, 7, 7, 7, 7, 6, 6, 6,
5, 5, 5, 4, 4, 4, 4, 3,
3, 3, 2, 2, 2, 1, 1, 1
};
static const unsigned int kputuw_thresholds[32] = {
0, 0, 1000000000U, 0, 0, 100000000U, 0, 0,
10000000, 0, 0, 0, 1000000, 0, 0, 100000,
0, 0, 10000, 0, 0, 0, 1000, 0,
0, 100, 0, 0, 10, 0, 0, 0
};
#else
uint64_t m;
#endif
static const char kputuw_dig2r[] =
"00010203040506070809"
"10111213141516171819"
"20212223242526272829"
"30313233343536373839"
"40414243444546474849"
"50515253545556575859"
"60616263646566676869"
"70717273747576777879"
"80818283848586878889"
"90919293949596979899";
unsigned int l, j;
char *cp;
// Trivial case - also prevents __builtin_clz(0), which is undefined
if (x < 10) {
if (ks_resize(s, s->l + 2) < 0)
return EOF;
s->s[s->l++] = '0'+x;
s->s[s->l] = 0;
return 0;
}
// Find out how many digits are to be printed.
#if HAVE___BUILTIN_CLZ && UINT_MAX == 4294967295U
/*
* Table method - should be quick if clz can be done in hardware.
* Find the most significant bit of the value to print and look
* up in a table to find out how many decimal digits are needed.
* This number needs to be adjusted by 1 for cases where the decimal
* length could vary for a given number of bits (for example,
* a four bit number could be between 8 and 15).
*/
l = __builtin_clz(x);
l = kputuw_num_digits[l] - (x < kputuw_thresholds[l]);
#else
// Fallback for when clz is not available
m = 1;
l = 0;
do {
l++;
m *= 10;
} while (x >= m);
#endif
if (ks_resize(s, s->l + l + 2) < 0)
return EOF;
// Add digits two at a time
j = l;
cp = s->s + s->l;
while (x >= 10) {
const char *d = &kputuw_dig2r[2*(x%100)];
x /= 100;
memcpy(&cp[j-=2], d, 2);
}
// Last one (if necessary). We know that x < 10 by now.
if (j == 1)
cp[0] = x + '0';
s->l += l;
s->s[s->l] = 0;
return 0;
}
static inline int kputw(int c, kstring_t *s)
{
unsigned int x = c;
if (c < 0) {
x = -x;
if (ks_resize(s, s->l + 3) < 0)
return EOF;
s->s[s->l++] = '-';
}
return kputuw(x, s);
}
static inline int kputll(long long c, kstring_t *s)
{
char buf[32];
int i, l = 0;
unsigned long long x = c;
if (c < 0) x = -x;
do { buf[l++] = x%10 + '0'; x /= 10; } while (x > 0);
if (c < 0) buf[l++] = '-';
if (ks_resize(s, s->l + l + 2) < 0)
return EOF;
for (i = l - 1; i >= 0; --i) s->s[s->l++] = buf[i];
s->s[s->l] = 0;
return 0;
}
static inline int kputl(long c, kstring_t *s) {
return kputll(c, s);
}
/*
* Returns 's' split by delimiter, with *n being the number of components;
* NULL on failure.
*/
static inline int *ksplit(kstring_t *s, int delimiter, int *n)
{
int max = 0, *offsets = 0;
*n = ksplit_core(s->s, delimiter, &max, &offsets);
return offsets;
}
#ifdef HTSLIB_SSIZE_T
#undef HTSLIB_SSIZE_T
#undef ssize_t
#endif
#endif
|
4b2825aa30b8a481e11642d0f3cc04f4b36d60d5
|
bee7edf8fc24b69a31f73e2cef82352b9921d992
|
/src/ngx_http_sysguard_node.h
|
b49961a9c839f7a386d560016adaf961cbe1bd39
|
[
"BSD-2-Clause",
"BSD-3-Clause"
] |
permissive
|
vozlt/nginx-module-sysguard
|
20d98fec9c8a5a9eea24ae6a4585702cac201e8c
|
864c491ccfec7a3a5549f0f3d962fca7dee7f620
|
refs/heads/master
| 2023-08-29T22:25:47.124273
| 2022-09-06T13:55:51
| 2022-09-06T13:55:51
| 82,876,313
| 611
| 37
|
BSD-2-Clause
| 2022-09-06T13:55:52
| 2017-02-23T02:42:37
|
C
|
UTF-8
|
C
| false
| false
| 1,524
|
h
|
ngx_http_sysguard_node.h
|
/*
* Copyright (C) 2010-2015 Alibaba Group Holding Limited
* Copyright (C) YoungJoo Kim (vozlt)
*/
#ifndef _NGX_SYSGUARD_NODE_H_INCLUDED_
#define _NGX_SYSGUARD_NODE_H_INCLUDED_
#define NGX_HTTP_SYSGUARD_AVERAGE_AMM 0
#define NGX_HTTP_SYSGUARD_AVERAGE_WMA 1
typedef struct {
ngx_msec_t time;
ngx_msec_int_t msec;
} ngx_http_sysguard_node_time_t;
typedef struct {
ngx_http_sysguard_node_time_t *times;
ngx_int_t front;
ngx_int_t rear;
ngx_int_t len;
} ngx_http_sysguard_node_time_ring_t;
void ngx_http_sysguard_node_time_ring_zero(
ngx_http_sysguard_node_time_ring_t *q);
void ngx_http_sysguard_node_time_ring_init(
ngx_http_sysguard_node_time_ring_t *q,
size_t len);
void ngx_http_sysguard_node_time_ring_insert(
ngx_http_sysguard_node_time_ring_t *q,
ngx_msec_int_t x);
ngx_int_t ngx_http_sysguard_node_time_ring_push(
ngx_http_sysguard_node_time_ring_t *q,
ngx_msec_int_t x);
ngx_int_t ngx_http_sysguard_node_time_ring_pop(
ngx_http_sysguard_node_time_ring_t *q,
ngx_http_sysguard_node_time_t *x);
ngx_msec_t ngx_http_sysguard_node_time_ring_average_amm(
ngx_http_request_t *r,
ngx_http_sysguard_node_time_ring_t *q);
ngx_msec_t ngx_http_sysguard_node_time_ring_average_wma(
ngx_http_request_t *r,
ngx_http_sysguard_node_time_ring_t *q);
#endif /* _NGX_SYSGUARD_NODE_H_INCLUDED_ */
/* vi:set ft=c ts=4 sw=4 et fdm=marker: */
|
2cfee691fc21f23cf2ece9cb0f472758951c4bd8
|
cfe35a116b31a929d2f57277047cb7689dce104c
|
/dart/external/convhull_3d/safe_convhull_3d.h
|
6ffd70349df7795a600eb641acd4b2210325150b
|
[
"BSD-2-Clause"
] |
permissive
|
dartsim/dart
|
b43fefc5ea0a5be46e88f939e7bb56ac49030205
|
78a6d822754525bd5fd645f30d269c357b499628
|
refs/heads/main
| 2023-08-31T01:19:00.075197
| 2023-08-22T19:51:58
| 2023-08-22T19:51:58
| 2,418,592
| 869
| 324
|
BSD-2-Clause
| 2023-09-05T23:08:14
| 2011-09-19T21:53:51
|
C++
|
UTF-8
|
C
| false
| false
| 2,184
|
h
|
safe_convhull_3d.h
|
/*
* Copyright (c) 2011-2023, The DART development contributors
* All rights reserved.
*
* The list of contributors can be found at:
* https://github.com/dartsim/dart/blob/master/LICENSE
*
* This file is provided under the following "BSD-style" License:
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL 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.
*/
#pragma once
// Check if we are using GCC or Clang
#ifdef __GNUC__
#pragma GCC system_header
#define CONVHULL_3D_ENABLE
#include <dart/external/convhull_3d/convhull_3d.h>
// Check if we are using MSVC
#elif defined(_MSC_VER)
#pragma warning(push, 0)
#define CONVHULL_3D_ENABLE
#include <dart/external/convhull_3d/convhull_3d.h>
#pragma warning(pop)
// For other compilers, you might just include it normally or
// add specific pragmas for those compilers
#else
#define CONVHULL_3D_ENABLE
#include <dart/external/convhull_3d/convhull_3d.h>
#endif
|
328b84b163d57984c6cbacb7ce57c41b7f19285a
|
1cf86f3b8a75e4b9e2256a49dd7f904d1bc3667c
|
/src/cpp/stdguard.h
|
1461e9149d48a8d69927e91715480db9d737c688
|
[
"Zlib"
] |
permissive
|
hugoam/two
|
bfaa6f0184e7e45e4f2fbc0e2d6257ed51dfe54d
|
d4b386f48c572da03ac5c89e702cf08f388d434d
|
refs/heads/master
| 2023-04-27T11:10:21.640620
| 2023-04-18T21:04:38
| 2023-04-18T21:04:38
| 116,430,022
| 717
| 63
|
Zlib
| 2019-05-11T16:04:24
| 2018-01-05T21:48:50
|
C++
|
UTF-8
|
C
| false
| false
| 472
|
h
|
stdguard.h
|
#include <cpp/preimport.h>
#ifdef _MSC_VER
#else
#define __EXCEPTION__
#define _GLIBCXX_CMATH
#define _GLIBCXX_NUMERIC_LIMITS
#define _GLIBCXX_STRING
#define _GLIBCXX_VECTOR
#define _GLIBCXX_MAP
#define _GLIBCXX_TUPLE
#define _GLIBCXX_MEMORY
#define _GLIBCXX_CHRONO
#define _GLIBCXX_TYPE_TRAITS
#define _EXT_TYPE_TRAITS
#define _CPP_TYPE_TRAITS_H
#define _GLIBCXX_SYSTEM_ERROR
#define _GLIBCXX_FUNCTIONAL
#define _MOVE_H
#define _MATH_H
#define _INITIALIZER_LIST
#endif
|
d15c46e8e6a92baa1771bd40171caa57b95dfd73
|
e5f4f37d941ceb8145d65f92028cc54658b1ac01
|
/Data/Samples/TextureSample/Shaders/SampleConstantBuffer.h
|
9dbaee2d25fd0bef8bbc4450f7a2d26d8f5e2b1f
|
[
"MIT"
] |
permissive
|
ezEngine/ezEngine
|
19983d2733a5409fb2665c6c3a0a575dadcefb50
|
c46e3b4b2cd46798e4abb4938fbca281c054b039
|
refs/heads/dev
| 2023-09-06T02:17:28.152665
| 2023-09-05T18:25:43
| 2023-09-05T18:25:43
| 18,179,848
| 1,050
| 165
|
MIT
| 2023-09-14T21:44:39
| 2014-03-27T15:02:16
|
C++
|
UTF-8
|
C
| false
| false
| 179
|
h
|
SampleConstantBuffer.h
|
#pragma once
// This file is included both in shader code and in C++ code
CONSTANT_BUFFER(ezTextureSampleConstants, 2)
{
MAT4(ModelMatrix);
MAT4(ViewProjectionMatrix);
};
|
145d1853a0828886c79a0d533e38bbccf7a2030a
|
70ffcb065027032a399f44b9ec91e7b61d73583d
|
/common/test/run-codex32.c
|
ab75f129af8f2f5a2db1cd23a808cf6a899ee2d3
|
[
"MIT"
] |
permissive
|
ElementsProject/lightning
|
4e260841b2ebad8c772a5ff91ef1ebbc3fe1ad71
|
990096f904e26386527a4eddd8d3262464bacabd
|
refs/heads/master
| 2023-09-01T07:11:34.794039
| 2023-08-31T09:55:14
| 2023-08-31T22:02:14
| 37,350,472
| 2,812
| 961
|
NOASSERTION
| 2023-09-14T19:33:22
| 2015-06-13T00:04:22
|
C
|
UTF-8
|
C
| false
| false
| 29,862
|
c
|
run-codex32.c
|
#include "config.h"
#include "../bech32_util.c"
#include "../bech32.c"
#include "../codex32.c"
#include "../json_parse.c"
#include "../json_parse_simple.c"
#include <ccan/array_size/array_size.h>
#include <common/codex32.h>
#include <ccan/tal/grab_file/grab_file.h>
#include <ccan/tal/path/path.h>
#include <common/setup.h>
/* AUTOGENERATED MOCKS START */
/* Generated stub for amount_asset_is_main */
bool amount_asset_is_main(struct amount_asset *asset UNNEEDED)
{ fprintf(stderr, "amount_asset_is_main called!\n"); abort(); }
/* Generated stub for amount_asset_to_sat */
struct amount_sat amount_asset_to_sat(struct amount_asset *asset UNNEEDED)
{ fprintf(stderr, "amount_asset_to_sat called!\n"); abort(); }
/* Generated stub for amount_sat */
struct amount_sat amount_sat(u64 satoshis UNNEEDED)
{ fprintf(stderr, "amount_sat called!\n"); abort(); }
/* Generated stub for amount_sat_add */
bool amount_sat_add(struct amount_sat *val UNNEEDED,
struct amount_sat a UNNEEDED,
struct amount_sat b UNNEEDED)
{ fprintf(stderr, "amount_sat_add called!\n"); abort(); }
/* Generated stub for amount_sat_div */
struct amount_sat amount_sat_div(struct amount_sat sat UNNEEDED, u64 div UNNEEDED)
{ fprintf(stderr, "amount_sat_div called!\n"); abort(); }
/* Generated stub for amount_sat_eq */
bool amount_sat_eq(struct amount_sat a UNNEEDED, struct amount_sat b UNNEEDED)
{ fprintf(stderr, "amount_sat_eq called!\n"); abort(); }
/* Generated stub for amount_sat_greater_eq */
bool amount_sat_greater_eq(struct amount_sat a UNNEEDED, struct amount_sat b UNNEEDED)
{ fprintf(stderr, "amount_sat_greater_eq called!\n"); abort(); }
/* Generated stub for amount_sat_mul */
bool amount_sat_mul(struct amount_sat *res UNNEEDED, struct amount_sat sat UNNEEDED, u64 mul UNNEEDED)
{ fprintf(stderr, "amount_sat_mul called!\n"); abort(); }
/* Generated stub for amount_sat_sub */
bool amount_sat_sub(struct amount_sat *val UNNEEDED,
struct amount_sat a UNNEEDED,
struct amount_sat b UNNEEDED)
{ fprintf(stderr, "amount_sat_sub called!\n"); abort(); }
/* Generated stub for amount_sat_to_asset */
struct amount_asset amount_sat_to_asset(struct amount_sat *sat UNNEEDED, const u8 *asset UNNEEDED)
{ fprintf(stderr, "amount_sat_to_asset called!\n"); abort(); }
/* Generated stub for amount_tx_fee */
struct amount_sat amount_tx_fee(u32 fee_per_kw UNNEEDED, size_t weight UNNEEDED)
{ fprintf(stderr, "amount_tx_fee called!\n"); abort(); }
/* Generated stub for fromwire */
const u8 *fromwire(const u8 **cursor UNNEEDED, size_t *max UNNEEDED, void *copy UNNEEDED, size_t n UNNEEDED)
{ fprintf(stderr, "fromwire called!\n"); abort(); }
/* Generated stub for fromwire_bool */
bool fromwire_bool(const u8 **cursor UNNEEDED, size_t *max UNNEEDED)
{ fprintf(stderr, "fromwire_bool called!\n"); abort(); }
/* Generated stub for fromwire_fail */
void *fromwire_fail(const u8 **cursor UNNEEDED, size_t *max UNNEEDED)
{ fprintf(stderr, "fromwire_fail called!\n"); abort(); }
/* Generated stub for fromwire_secp256k1_ecdsa_signature */
void fromwire_secp256k1_ecdsa_signature(const u8 **cursor UNNEEDED, size_t *max UNNEEDED,
secp256k1_ecdsa_signature *signature UNNEEDED)
{ fprintf(stderr, "fromwire_secp256k1_ecdsa_signature called!\n"); abort(); }
/* Generated stub for fromwire_sha256 */
void fromwire_sha256(const u8 **cursor UNNEEDED, size_t *max UNNEEDED, struct sha256 *sha256 UNNEEDED)
{ fprintf(stderr, "fromwire_sha256 called!\n"); abort(); }
/* Generated stub for fromwire_tal_arrn */
u8 *fromwire_tal_arrn(const tal_t *ctx UNNEEDED,
const u8 **cursor UNNEEDED, size_t *max UNNEEDED, size_t num UNNEEDED)
{ fprintf(stderr, "fromwire_tal_arrn called!\n"); abort(); }
/* Generated stub for fromwire_u32 */
u32 fromwire_u32(const u8 **cursor UNNEEDED, size_t *max UNNEEDED)
{ fprintf(stderr, "fromwire_u32 called!\n"); abort(); }
/* Generated stub for fromwire_u64 */
u64 fromwire_u64(const u8 **cursor UNNEEDED, size_t *max UNNEEDED)
{ fprintf(stderr, "fromwire_u64 called!\n"); abort(); }
/* Generated stub for fromwire_u8 */
u8 fromwire_u8(const u8 **cursor UNNEEDED, size_t *max UNNEEDED)
{ fprintf(stderr, "fromwire_u8 called!\n"); abort(); }
/* Generated stub for fromwire_u8_array */
void fromwire_u8_array(const u8 **cursor UNNEEDED, size_t *max UNNEEDED, u8 *arr UNNEEDED, size_t num UNNEEDED)
{ fprintf(stderr, "fromwire_u8_array called!\n"); abort(); }
/* Generated stub for mvt_tag_str */
const char *mvt_tag_str(enum mvt_tag tag UNNEEDED)
{ fprintf(stderr, "mvt_tag_str called!\n"); abort(); }
/* Generated stub for node_id_from_hexstr */
bool node_id_from_hexstr(const char *str UNNEEDED, size_t slen UNNEEDED, struct node_id *id UNNEEDED)
{ fprintf(stderr, "node_id_from_hexstr called!\n"); abort(); }
/* Generated stub for parse_amount_msat */
bool parse_amount_msat(struct amount_msat *msat UNNEEDED, const char *s UNNEEDED, size_t slen UNNEEDED)
{ fprintf(stderr, "parse_amount_msat called!\n"); abort(); }
/* Generated stub for parse_amount_sat */
bool parse_amount_sat(struct amount_sat *sat UNNEEDED, const char *s UNNEEDED, size_t slen UNNEEDED)
{ fprintf(stderr, "parse_amount_sat called!\n"); abort(); }
/* Generated stub for towire */
void towire(u8 **pptr UNNEEDED, const void *data UNNEEDED, size_t len UNNEEDED)
{ fprintf(stderr, "towire called!\n"); abort(); }
/* Generated stub for towire_bool */
void towire_bool(u8 **pptr UNNEEDED, bool v UNNEEDED)
{ fprintf(stderr, "towire_bool called!\n"); abort(); }
/* Generated stub for towire_secp256k1_ecdsa_signature */
void towire_secp256k1_ecdsa_signature(u8 **pptr UNNEEDED,
const secp256k1_ecdsa_signature *signature UNNEEDED)
{ fprintf(stderr, "towire_secp256k1_ecdsa_signature called!\n"); abort(); }
/* Generated stub for towire_sha256 */
void towire_sha256(u8 **pptr UNNEEDED, const struct sha256 *sha256 UNNEEDED)
{ fprintf(stderr, "towire_sha256 called!\n"); abort(); }
/* Generated stub for towire_u32 */
void towire_u32(u8 **pptr UNNEEDED, u32 v UNNEEDED)
{ fprintf(stderr, "towire_u32 called!\n"); abort(); }
/* Generated stub for towire_u64 */
void towire_u64(u8 **pptr UNNEEDED, u64 v UNNEEDED)
{ fprintf(stderr, "towire_u64 called!\n"); abort(); }
/* Generated stub for towire_u8 */
void towire_u8(u8 **pptr UNNEEDED, u8 v UNNEEDED)
{ fprintf(stderr, "towire_u8 called!\n"); abort(); }
/* Generated stub for towire_u8_array */
void towire_u8_array(u8 **pptr UNNEEDED, const u8 *arr UNNEEDED, size_t num UNNEEDED)
{ fprintf(stderr, "towire_u8_array called!\n"); abort(); }
/* AUTOGENERATED MOCKS END */
/* Print the "cl" variant of the vector */
static void print_cl_vec(const char *desc, const struct codex32 *parts)
{
const char *err;
char *bip93;
err = codex32_secret_encode(tmpctx, "cl", parts->id, parts->threshold,
parts->payload, tal_bytelen(parts->payload),
&bip93);
assert(!err);
printf("%s: %s\n", desc, bip93);
}
int main(int argc, char *argv[])
{
common_setup(argv[0]);
char *fail, *c;
struct codex32 *parts;
/* Test vector for codex32_secret_encode*/
u8 seed_b[32] = {
0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88,
0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x00,
0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88,
0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x00,
};
assert(codex32_secret_encode(tmpctx, "ms", "leet", 0, seed_b, ARRAY_SIZE(seed_b), &c) == NULL);
assert(streq(c,
"ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqqtum9pgv99ycma"));
/*
* Test vector 1
*
* This example shows the codex32 format, when used without splitting the secret into any shares. The payload contains 26 bech32 characters, which corresponds to 130 bits. We truncate the last two bits in order to obtain a 128-bit master seed.
*
* codex32 secret (bech32): ms10testsxxxxxxxxxxxxxxxxxxxxxxxxxx4nzvca9cmczlw
*
* Master secret (hex): 318c6318c6318c6318c6318c6318c631
*
* * human-readable part: ms
* * separator: 1
* * k value: 0 (no secret splitting)
* * identifier: test
* * share index: s (the secret)
* * payload: xxxxxxxxxxxxxxxxxxxxxxxxxx
* * checksum: 4nzvca9cmczlw
* * master node xprv: xprv9s21ZrQH143K3taPNekMd9oV5K6szJ8ND7vVh6fxicRUMDcChr3bFFzuxY8qP3xFFBL6DWc2uEYCfBFZ2nFWbAqKPhtCLRjgv78EZJDEfpL
*/
parts = codex32_decode(tmpctx, NULL, "ms10testsxxxxxxxxxxxxxxxxxxxxxxxxxx4nzvca9cmczlw", &fail);
if (parts) {
assert(streq(parts->hrp, "ms"));
assert(parts->threshold == 0);
assert(strcmp(parts->id,"test") == 0);
assert(parts->share_idx == 's');
assert(streq(tal_hexstr(tmpctx, parts->payload, tal_bytelen(parts->payload)),
"318c6318c6318c6318c6318c6318c631"));
print_cl_vec("Test vector 1", parts);
} else {
abort();
}
tal_free(parts);
/*
* Test vector 2
* This example shows generating a new master seed using "random" codex32 shares, as well as deriving an additional codex32 share, using k=2 and an identifier of NAME. Although codex32 strings are canonically all lowercase, it's also valid to use all uppercase.
*
* Share with index A: MS12NAMEA320ZYXWVUTSRQPNMLKJHGFEDCAXRPP870HKKQRM
*
* Share with index C: MS12NAMECACDEFGHJKLMNPQRSTUVWXYZ023FTR2GDZMPY6PN
*
* * Derived share with index D: MS12NAMEDLL4F8JLH4E5VDVULDLFXU2JHDNLSM97XVENRXEG
* * Secret share with index S: MS12NAMES6XQGUZTTXKEQNJSJZV4JV3NZ5K3KWGSPHUH6EVW
* * Master secret (hex): d1808e096b35b209ca12132b264662a5
* * master node xprv: xprv9s21ZrQH143K2NkobdHxXeyFDqE44nJYvzLFtsriatJNWMNKznGoGgW5UMTL4fyWtajnMYb5gEc2CgaKhmsKeskoi9eTimpRv2N11THhPTU
*/
parts = codex32_decode(tmpctx, "ms", "MS12NAMES6XQGUZTTXKEQNJSJZV4JV3NZ5K3KWGSPHUH6EVW", &fail);
if(parts) {
assert(streq(tal_hexstr(tmpctx, parts->payload, tal_bytelen(parts->payload)), "d1808e096b35b209ca12132b264662a5"));
print_cl_vec("Test vector 2", parts);
} else {
abort();
}
tal_free(parts);
/*
* Test vector 3
* This example shows splitting an existing 128-bit master seed into "random" codex32 shares, using k=3 and an identifier of cash. We appended two zero bits in order to obtain 26 bech32 characters (130 bits of data) from the 128-bit master seed.
*
* Master secret (hex): ffeeddccbbaa99887766554433221100
*
* * Secret share with index s: ms13cashsllhdmn9m42vcsamx24zrxgs3qqjzqud4m0d6nln
*
* * Share with index a: ms13casha320zyxwvutsrqpnmlkjhgfedca2a8d0zehn8a0t
*
* * Share with index c: ms13cashcacdefghjklmnpqrstuvwxyz023949xq35my48dr
*
* * Derived share with index d: ms13cashd0wsedstcdcts64cd7wvy4m90lm28w4ffupqs7rm
* * Derived share with index e: ms13casheekgpemxzshcrmqhaydlp6yhms3ws7320xyxsar9
* * Derived share with index f: ms13cashf8jh6sdrkpyrsp5ut94pj8ktehhw2hfvyrj48704
* master node xprv: xprv9s21ZrQH143K266qUcrDyYJrSG7KA3A7sE5UHndYRkFzsPQ6xwUhEGK1rNuyyA57Vkc1Ma6a8boVqcKqGNximmAe9L65WsYNcNitKRPnABd
* Any three of the five shares among acdef can be used to recover the secret.
* Note that the choice to append two zero bits was arbitrary, and any of the following four secret shares would have been valid choices. However, each choice would have resulted in a different set of derived shares.
*
* * ms13cashsllhdmn9m42vcsamx24zrxgs3qqjzqud4m0d6nln
* * ms13cashsllhdmn9m42vcsamx24zrxgs3qpte35dvzkjpt0r
* * ms13cashsllhdmn9m42vcsamx24zrxgs3qzfatvdwq5692k6
* * ms13cashsllhdmn9m42vcsamx24zrxgs3qrsx6ydhed97jx2
*/
char *addr_vec3[] = {
"ms13cashsllhdmn9m42vcsamx24zrxgs3qqjzqud4m0d6nln",
"ms13cashsllhdmn9m42vcsamx24zrxgs3qpte35dvzkjpt0r",
"ms13cashsllhdmn9m42vcsamx24zrxgs3qzfatvdwq5692k6",
"ms13cashsllhdmn9m42vcsamx24zrxgs3qrsx6ydhed97jx2",
};
for (size_t i = 0; i < ARRAY_SIZE(addr_vec3); i++) {
parts = codex32_decode(tmpctx, NULL, addr_vec3[i], &fail);
if(parts) {
assert(streq(tal_hexstr(tmpctx, parts->payload, tal_bytelen(parts->payload)),
"ffeeddccbbaa99887766554433221100"));
print_cl_vec("Test vector 3", parts);
} else {
abort();
}
tal_free(parts);
}
/*
* Test vector 4
* 256-bit secret (hex): ffeeddccbbaa99887766554433221100ffeeddccbbaa99887766554433221100
* * codex32 secret: ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqqtum9pgv99ycma
* * master node xprv: xprv9s21ZrQH143K3s41UCWxXTsU4TRrhkpD1t21QJETan3hjo8DP5LFdFcB5eaFtV8x6Y9aZotQyP8KByUjgLTbXCUjfu2iosTbMv98g8EQoqr
*
* Note that the choice to append four zero bits was arbitrary, and any of the following sixteen codex32 secrets would have been valid:
*
* * ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqqtum9pgv99ycma
* * ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqpj82dp34u6lqtd
* * ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqzsrs4pnh7jmpj5
* * ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqrfcpap2w8dqezy
* * ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqy5tdvphn6znrf0
* * ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyq9dsuypw2ragmel
* * ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqx05xupvgp4v6qx
* * ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyq8k0h5p43c2hzsk
* * ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqgum7hplmjtr8ks
* * ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqf9q0lpxzt5clxq
* * ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyq28y48pyqfuu7le
* * ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqt7ly0paesr8x0f
* * ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqvrvg7pqydv5uyz
* * ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqd6hekpea5n0y5j
* * ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqwcnrwpmlkmt9dt
* * ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyq0pgjxpzx0ysaam
*/
char *addr_vec4[] = {
"ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqqtum9pgv99ycma",
"ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqpj82dp34u6lqtd",
"ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqzsrs4pnh7jmpj5",
"ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqrfcpap2w8dqezy",
"ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqy5tdvphn6znrf0",
"ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyq9dsuypw2ragmel",
"ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqx05xupvgp4v6qx",
"ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyq8k0h5p43c2hzsk",
"ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqgum7hplmjtr8ks",
"ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqf9q0lpxzt5clxq",
"ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyq28y48pyqfuu7le",
"ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqt7ly0paesr8x0f",
"ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqvrvg7pqydv5uyz",
"ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqd6hekpea5n0y5j",
"ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqwcnrwpmlkmt9dt",
"ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyq0pgjxpzx0ysaam",
};
for (size_t i = 0; i < ARRAY_SIZE(addr_vec4); i++) {
parts = codex32_decode(tmpctx, NULL, addr_vec4[i], &fail);
if (parts) {
assert(streq(tal_hexstr(tmpctx, parts->payload, tal_bytelen(parts->payload)),
"ffeeddccbbaa99887766554433221100ffeeddccbbaa99887766554433221100"));
print_cl_vec("Test vector 4", parts);
} else {
abort();
}
tal_free(parts);
}
/*
* Test vector 5
* This example shows generating a new 512-bit master seed using "random" codex32 characters and appending a checksum. The payload contains 103 bech32 characters, which corresponds to 515 bits. The last three bits are discarded when converting to a 512-bit master seed.
*
* This is an example of a Long codex32 String.
*
* * Secret share with index S: MS100C8VSM32ZXFGUHPCHTLUPZRY9X8GF2TVDW0S3JN54KHCE6MUA7LQPZYGSFJD6AN074RXVCEMLH8WU3TK925ACDEFGHJKLMNPQRSTUVWXY06FHPV80UNDVARHRAK
* * Master secret (hex): dc5423251cb87175ff8110c8531d0952d8d73e1194e95b5f19d6f9df7c01111104c9baecdfea8cccc677fb9ddc8aec5553b86e528bcadfdcc201c17c638c47e9
* * master node xprv: xprv9s21ZrQH143K4UYT4rP3TZVKKbmRVmfRqTx9mG2xCy2JYipZbkLV8rwvBXsUbEv9KQiUD7oED1Wyi9evZzUn2rqK9skRgPkNaAzyw3YrpJN
*
*/
parts = codex32_decode(tmpctx, NULL, "MS100C8VSM32ZXFGUHPCHTLUPZRY9X8GF2TVDW0S3JN54KHCE6MUA7LQPZYGSFJD6AN074RXVCEMLH8WU3TK925ACDEFGHJKLMNPQRSTUVWXY06FHPV80UNDVARHRAK", &fail);
if (parts) {
assert(streq(tal_hexstr(tmpctx, parts->payload, tal_bytelen(parts->payload)),
"dc5423251cb87175ff8110c8531d0952d8d73e1194e95b5f19d6f9df7c01111104c9baecdfea8cccc677fb9ddc8aec5553b86e528bcadfdcc201c17c638c47e9"));
print_cl_vec("Test vector 5", parts);
} else {
abort();
}
tal_free(parts);
/* ---- Invalid codex test vectors ----
* These examples have incorrect checksums.
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxve740yyge2ghq
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxve740yyge2ghp
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxlk3yepcstwr
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxx6pgnv7jnpcsp
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxx0cpvr7n4geq
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxm5252y7d3lr
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxrd9sukzl05ej
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxc55srw5jrm0
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxgc7rwhtudwc
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxx4gy22afwghvs
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxe8yfm0
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxvm597d
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxme084q0vpht7pe0
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxme084q0vpht7pew
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxqyadsp3nywm8a
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxzvg7ar4hgaejk
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxcznau0advgxqe
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxch3jrc6j5040j
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx52gxl6ppv40mcv
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx7g4g2nhhle8fk
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx63m45uj8ss4x8
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxy4r708q7kg65x
*
*/
char *addr_invalid[] = {
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxve740yyge2ghq",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxve740yyge2ghp",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxlk3yepcstwr",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxx6pgnv7jnpcsp",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxx0cpvr7n4geq",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxm5252y7d3lr",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxrd9sukzl05ej",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxc55srw5jrm0",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxgc7rwhtudwc",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxx4gy22afwghvs",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxe8yfm0",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxvm597d",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxme084q0vpht7pe0",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxme084q0vpht7pew",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxqyadsp3nywm8a",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxzvg7ar4hgaejk",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxcznau0advgxqe",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxch3jrc6j5040j",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx52gxl6ppv40mcv",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx7g4g2nhhle8fk",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx63m45uj8ss4x8",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxy4r708q7kg65x",
};
for (size_t i = 0; i < ARRAY_SIZE(addr_invalid); i++) {
parts = codex32_decode(tmpctx, NULL, addr_invalid[i], &fail);
if (parts) {
abort();
} else {
assert(streq(fail, "Invalid checksum!"));
}
tal_free(parts);
}
/* These examples use the wrong checksum for their given data sizes.
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxurfvwmdcmymdufv
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxcsyppjkd8lz4hx3
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxu6hwvl5p0l9xf3c
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwqey9rfs6smenxa
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxv70wkzrjr4ntqet
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx3hmlrmpa4zl0v
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxrfggf88znkaup
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxpt7l4aycv9qzj
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxus27z9xtyxyw3
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxcwm4re8fs78vn
*
*/
char *addr_invalid1[] = {
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxurfvwmdcmymdufv",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxcsyppjkd8lz4hx3",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxu6hwvl5p0l9xf3c",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwqey9rfs6smenxa",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxv70wkzrjr4ntqet",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx3hmlrmpa4zl0v",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxrfggf88znkaup",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxpt7l4aycv9qzj",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxus27z9xtyxyw3",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxcwm4re8fs78vn",
};
for (size_t i = 0; i < ARRAY_SIZE(addr_invalid1); i++) {
parts = codex32_decode(tmpctx, NULL, addr_invalid1[i], &fail);
if (parts) {
printf("payload == %zu\n", tal_bytelen(parts->payload));
abort();
} else {
assert(streq(fail, "Invalid checksum!") ||
streq(fail, "Invalid length!") ||
streq(fail, "Invalid payload!"));
}
tal_free(parts);
}
/*
* These examples have improper lengths. They are either too short, too long, or would decode to byte sequence with an incomplete group greater than 4 bits.
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxw0a4c70rfefn4
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxk4pavy5n46nea
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxx9lrwar5zwng4w
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxr335l5tv88js3
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxvu7q9nz8p7dj68v
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxpq6k542scdxndq3
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxkmfw6jm270mz6ej
* * ms12fauxxxxxxxxxxxxxxxxxxxxxxxxxxzhddxw99w7xws
* * ms12fauxxxxxxxxxxxxxxxxxxxxxxxxxxxx42cux6um92rz
* * ms12fauxxxxxxxxxxxxxxxxxxxxxxxxxxxxxarja5kqukdhy9
* * ms12fauxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxky0ua3ha84qk8
* * ms12fauxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx9eheesxadh2n2n9
* * ms12fauxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx9llwmgesfulcj2z
* * ms12fauxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx02ev7caq6n9fgkf
*/
char *addr_invalid2[] = {
// "ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxw0a4c70rfefn4", FALSE POSITIVE
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxk4pavy5n46nea",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxx9lrwar5zwng4w",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxr335l5tv88js3",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxvu7q9nz8p7dj68v",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxpq6k542scdxndq3",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxkmfw6jm270mz6ej",
// "ms12fauxxxxxxxxxxxxxxxxxxxxxxxxxxzhddxw99w7xws", FALSE POSITIVE
"ms12fauxxxxxxxxxxxxxxxxxxxxxxxxxxxx42cux6um92rz",
"ms12fauxxxxxxxxxxxxxxxxxxxxxxxxxxxxxarja5kqukdhy9",
"ms12fauxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxky0ua3ha84qk8",
"ms12fauxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx9eheesxadh2n2n9",
"ms12fauxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx9llwmgesfulcj2z",
"ms12fauxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx02ev7caq6n9fgkf",
};
for (size_t i = 0; i < ARRAY_SIZE(addr_invalid2); i++) {
parts = codex32_decode(tmpctx, NULL, addr_invalid2[i], &fail);
if (parts) {
printf("payload %zu\n", tal_bytelen(parts->payload));
abort();
} else {
assert(streq(fail, "Invalid payload!") ||
streq(fail, "Invalid length!"));
}
tal_free(parts);
}
/*
* This example uses a "0" threshold with a non-"s" index
* * ms10fauxxxxxxxxxxxxxxxxxxxxxxxxxxxx0z26tfn0ulw3p
*/
parts = codex32_decode(tmpctx, NULL, "ms10fauxxxxxxxxxxxxxxxxxxxxxxxxxxxx0z26tfn0ulw3p", &fail);
if (parts) {
abort();
} else {
assert(streq(fail, "Expected share index s for threshold 0!"));
}
tal_free(parts);
/*
* This example has a threshold that is not a digit.
* * ms1fauxxxxxxxxxxxxxxxxxxxxxxxxxxxxxda3kr3s0s2swg
*/
parts = codex32_decode(tmpctx, NULL, "ms1fauxxxxxxxxxxxxxxxxxxxxxxxxxxxxxda3kr3s0s2swg", &fail);
if (parts) {
abort();
} else {
assert(streq(fail, "Invalid threshold!"));
}
tal_free(parts);
/*
* These examples do not begin with the required "ms" or "MS" prefix and/or are missing the "1" separator.
* * 0fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxuqxkk05lyf3x2
* * 10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxuqxkk05lyf3x2
* * ms0fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxuqxkk05lyf3x2
* * m10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxuqxkk05lyf3x2
* * s10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxuqxkk05lyf3x2
* * 0fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxhkd4f70m8lgws
* * 10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxhkd4f70m8lgws
* * m10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxx8t28z74x8hs4l
* * s10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxh9d0fhnvfyx3x
*/
char *addr_invalid3[] = {
"0fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxuqxkk05lyf3x2",
"10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxuqxkk05lyf3x2",
"ms0fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxuqxkk05lyf3x2",
"m10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxuqxkk05lyf3x2",
"s10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxuqxkk05lyf3x2",
"0fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxhkd4f70m8lgws",
"10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxhkd4f70m8lgws",
"m10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxx8t28z74x8hs4l",
"s10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxh9d0fhnvfyx3x",
};
for (size_t i = 0; i < ARRAY_SIZE(addr_invalid3); i++) {
parts = codex32_decode(tmpctx, "ms", addr_invalid3[i], &fail);
if (parts) {
abort();
} else {
assert(strstr(fail, "Invalid hrp ") ||
streq(fail, "Separator doesn't exist!"));
}
tal_free(parts);
}
/*
* These examples all incorrectly mix upper and lower case characters.
* * Ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxuqxkk05lyf3x2
* * mS10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxuqxkk05lyf3x2
* * MS10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxuqxkk05lyf3x2
* * ms10FAUXsxxxxxxxxxxxxxxxxxxxxxxxxxxuqxkk05lyf3x2
* * ms10fauxSxxxxxxxxxxxxxxxxxxxxxxxxxxuqxkk05lyf3x2
* * ms10fauxsXXXXXXXXXXXXXXXXXXXXXXXXXXuqxkk05lyf3x2
* * ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxUQXKK05LYF3X2
*/
char *addr_invalid4[] = {
"Ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxuqxkk05lyf3x2",
"mS10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxuqxkk05lyf3x2",
"MS10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxuqxkk05lyf3x2",
"ms10FAUXsxxxxxxxxxxxxxxxxxxxxxxxxxxuqxkk05lyf3x2",
"ms10fauxSxxxxxxxxxxxxxxxxxxxxxxxxxxuqxkk05lyf3x2",
"ms10fauxsXXXXXXXXXXXXXXXXXXXXXXXXXXuqxkk05lyf3x2",
"ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxUQXKK05LYF3X2",
};
for (size_t i = 0; i < ARRAY_SIZE(addr_invalid4); i++) {
parts = codex32_decode(tmpctx, NULL, addr_invalid4[i], &fail);
if (parts) {
abort();
} else {
assert(streq(fail, "Not a valid bech32 string!"));
}
tal_free(parts);
}
common_shutdown();
return 0;
}
|
c9a964bbc7ddd5844790bcd18743549a72fc0c1c
|
8380b5eb12e24692e97480bfa8939a199d067bce
|
/Carberp/Source/Modules.h
|
3c91aa7205873410677a9f0a2838e814c83fbe01
|
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
RamadhanAmizudin/malware
|
788ee745b5bb23b980005c2af08f6cb8763981c2
|
62d0035db6bc9aa279b7c60250d439825ae65e41
|
refs/heads/master
| 2023-02-05T13:37:18.909646
| 2023-01-26T08:43:18
| 2023-01-26T08:43:18
| 53,407,812
| 873
| 291
| null | 2023-01-26T08:43:19
| 2016-03-08T11:44:21
|
C++
|
WINDOWS-1251
|
C
| false
| false
| 336
|
h
|
Modules.h
|
/*--------------------------------------------------------------------------*/
//
// Заголовочный файл объединяющий в себе включаемы/отключаемые возможности
// бота.
//
/*--------------------------------------------------------------------------*/
|
fea68224b8ab8ea0c28175c051a928e0565982aa
|
450916eee7580beb928ed8f387db4f0a8c1aa508
|
/src/amuse/community/athena/src/athena/src/output_pdf.c
|
1f0e48c94894909d081bb7f4f58dc20a627e6c13
|
[
"GPL-1.0-or-later",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
amusecode/amuse
|
42095545893f5a86ea79c2a52ce54d3ce8eb204f
|
b57c1e2fda1457d5025307be105c2aa59b19b574
|
refs/heads/main
| 2023-08-31T04:50:48.880044
| 2023-08-30T12:00:20
| 2023-08-30T12:00:20
| 18,516,331
| 158
| 118
|
Apache-2.0
| 2023-08-30T12:00:22
| 2014-04-07T12:35:07
|
AMPL
|
UTF-8
|
C
| false
| false
| 11,218
|
c
|
output_pdf.c
|
#include "copyright.h"
/*============================================================================*/
/*! \file output_pdf.c
* \brief Outputs Probability Distribution Functions of selected variables
* in formatted tabular form.
*
* PURPOSE: Outputs Probability Distribution Functions of selected variables
* in formatted tabular form. Fully MPI enabled, which requires passing
* lots of global sums and means (only the parent process produces output).
* With SMR, dumps are made for all levels and domains, unless nlevel and
* ndomain are specified in <output> block.
*
* CONTAINS PUBLIC FUNCTIONS:
* - output_pdf() - output PDFs
*============================================================================*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include "defs.h"
#include "athena.h"
#include "prototypes.h"
static int size_dat=0; /* Number of elements in the data[] array */
static double *data=NULL; /* Computed data array: data[size_dat] */
static int size_pdf=0; /* Number of elements in the pdf[] array */
static int *pdf=NULL; /* (non-normalized) PDF */
#ifdef MPI_PARALLEL
static int *cd_pdf=NULL; /* (non-normalized) complete Domain PDF */
#endif /* MPI_PARALLEL */
static char def_fmt[]="%21.15e"; /* A default tabular dump data format */
/*----------------------------------------------------------------------------*/
/*! \fn void output_pdf(MeshS *pM, OutputS *pOut)
* \brief Outputs PDFs. */
void output_pdf(MeshS *pM, OutputS *pOut)
{
GridS *pG;
FILE *pfile;
char fmt[80];
char fid[80]; /* File "id" for the statistics table */
char *fname,*plev=NULL,*pdom=NULL,*pdir=NULL;
char levstr[8],domstr[8],dirstr[8];
int nl,nd,i,j,k,is,ie,js,je,ks,ke;
int n, data_cnt;
double dmin, dmax, delta, dpdf, dat, scl;
double mean=0.0, var=0.0; /* mean and variance of the distribution */
double adev=0.0, sdev=0.0; /* average & standard deviation */
double skew=0.0, kurt=0.0; /* skewness and kurtosis of the distribution */
double r, s, ep=0.0; /* Temp. variables for calculating the variance, etc. */
#ifdef MPI_PARALLEL
DomainS *pD;
int ierr, cd_data_cnt, myID_Comm_Domain;
#endif /* MPI_PARALLEL */
/* Loop over all Domains in Mesh, and output Grid data */
for (nl=0; nl<(pM->NLevels); nl++){
for (nd=0; nd<(pM->DomainsPerLevel[nl]); nd++){
if (pM->Domain[nl][nd].Grid != NULL){
/* write files if domain and level match input, or are not specified (-1) */
if ((pOut->nlevel == -1 || pOut->nlevel == nl) &&
(pOut->ndomain == -1 || pOut->ndomain == nd)){
pG = pM->Domain[nl][nd].Grid;
#ifdef MPI_PARALLEL
pD = (DomainS*)&(pM->Domain[nl][nd]);
ierr = MPI_Comm_rank(pD->Comm_Domain, &myID_Comm_Domain);
cd_data_cnt = (pD->Nx[0])*(pD->Nx[1])*(pD->Nx[2]);
#endif
is = pG->is, ie = pG->ie;
js = pG->js, je = pG->je;
ks = pG->ks, ke = pG->ke;
data_cnt = (ie - is + 1)*(je - js + 1)*(ke - ks + 1);
/* Are the requisite arrays allocated? */
if(data == NULL){
size_dat = data_cnt;
data = (double *)calloc(size_dat,sizeof(double));
if(data == NULL)
ath_error("[output_pdf]: Failed to allocate data array\n");
/* This choice for size_pdf represents a balance between
* resolution in the PDF and "shot noise" in the data binning. */
#ifdef MPI_PARALLEL
size_pdf = (int)sqrt((double)cd_data_cnt);
#else /* MPI_PARALLEL */
size_pdf = (int)sqrt((double)size_dat);
#endif /* MPI_PARALLEL */
pdf = (int *)calloc(size_pdf,sizeof(int));
if(pdf == NULL)
ath_error("[output_pdf]: Failed to allocate pdf array\n");
#ifdef MPI_PARALLEL
if(myID_Comm_Domain == 0){ /* I'm the parent */
cd_pdf = (int *)calloc(size_pdf,sizeof(int));
if(cd_pdf == NULL)
ath_error("[output_pdf]: Failed to allocate cd_pdf array\n");
}
#endif /* MPI_PARALLEL */
}
/* Initialize dmin, dmax */
dmin = dmax = (*pOut->expr)(pG,is,js,ks);
/* Fill the data array */
n=0;
for(k = ks; k<=ke; k++){
for(j = js; j<=je; j++){
for(i = is; i<=ie; i++){
data[n] = (double)(*pOut->expr)(pG,i,j,k);
dmin = data[n] < dmin ? data[n] : dmin;
dmax = data[n] > dmax ? data[n] : dmax;
mean += data[n];
n++;
}
}
}
#ifdef MPI_PARALLEL
dat = dmin;
ierr = MPI_Allreduce(&dat,&dmin,1,MPI_DOUBLE,MPI_MIN,pD->Comm_Domain);
dat = dmax;
ierr = MPI_Allreduce(&dat,&dmax,1,MPI_DOUBLE,MPI_MAX,pD->Comm_Domain);
dat = mean;
ierr = MPI_Allreduce(&dat,&mean,1,MPI_DOUBLE,MPI_SUM,pD->Comm_Domain);
mean /= (double)cd_data_cnt; /* Complete the calc. of the mean */
#else /* MPI_PARALLEL */
mean /= (double)data_cnt; /* Complete the calc. of the mean */
#endif /* MPI_PARALLEL */
if(data_cnt > 1){
/* Calculate the variance, etc. with the corrected 2-pass formula */
for(n=0; n<data_cnt; n++){
s = data[n] - mean;
adev += fabs(s);
ep += s;
var += (r = s*s);
skew += (r *= s);
kurt += (r *= s);
}
#ifdef MPI_PARALLEL
dat = ep;
ierr = MPI_Allreduce(&dat,&ep,1,MPI_DOUBLE,MPI_SUM,pD->Comm_Domain);
dat = var;
ierr = MPI_Allreduce(&dat,&var,1,MPI_DOUBLE,MPI_SUM,pD->Comm_Domain);
dat = skew;
ierr = MPI_Allreduce(&dat,&skew,1,MPI_DOUBLE,MPI_SUM,pD->Comm_Domain);
dat = kurt;
ierr = MPI_Allreduce(&dat,&kurt,1,MPI_DOUBLE,MPI_SUM,pD->Comm_Domain);
adev /= (double)cd_data_cnt;
var = (var - ep*ep/(double)cd_data_cnt)/(double)(cd_data_cnt-1);
sdev = sqrt(var);
if(sdev > 0.0){
skew /= var*sdev*cd_data_cnt;
kurt = kurt/(var*var*cd_data_cnt) - 3.0;
}
#else /* MPI_PARALLEL */
adev /= (double)data_cnt;
var = (var - ep*ep/(double)data_cnt)/(double)(data_cnt-1);
sdev = sqrt(var);
if(sdev > 0.0){
skew /= var*sdev*data_cnt;
kurt = kurt/(var*var*data_cnt) - 3.0;
}
#endif /* MPI_PARALLEL */
}
/* Store the global maximum and minimum of the quantity */
pOut->gmin = dmin < pOut->gmin ? dmin : pOut->gmin;
pOut->gmax = dmax > pOut->gmax ? dmax : pOut->gmax;
/* Compute the pdf directly using sampling. Define size_pdf bins, each of equal
* size, and fill them with the number of cells whose data value falls in the
* range spanned by the bin. */
if(dmax - dmin > 0.0){
/* Initialize pdf[] to zero */
for(n=0; n<size_pdf; n++) pdf[n] = 0;
/* Calculate the number of cells whose data falls in each bin */
scl = (double)size_pdf/(dmax - dmin);
for(n=0; n<data_cnt; n++){
i = (int)(scl*(data[n] - dmin));
i = i < size_pdf ? i : size_pdf - 1;
pdf[i]++;
}
}
#ifdef MPI_PARALLEL
/* Sum up the pdf in the array cd_pdf */
ierr=MPI_Reduce(pdf,cd_pdf,size_pdf,MPI_INT,MPI_SUM,0,pD->Comm_Domain);
#endif /* MPI_PARALLEL */
#ifdef MPI_PARALLEL
/* For parallel calculations, only the parent writes the output. */
if(myID_Comm_Domain != 0) return;
#endif /* MPI_PARALLEL */
/* Create filename and open file. pdf files are always written in lev#
* directories of root (rank=0) process. */
#ifdef MPI_PARALLEL
if (nl>0) {
plev = &levstr[0];
sprintf(plev,"lev%d",nl);
pdir = &dirstr[0];
sprintf(pdir,"../lev%d",nl);
}
#else
if (nl>0) {
plev = &levstr[0];
sprintf(plev,"lev%d",nl);
pdir = &dirstr[0];
sprintf(pdir,"lev%d",nl);
}
#endif
if (nd>0) {
pdom = &domstr[0];
sprintf(pdom,"dom%d",nd);
}
fname = ath_fname(pdir,pM->outfilename,plev,pdom,num_digit,
pOut->num,pOut->id,"prb");
if(fname == NULL){
ath_perr(-1,"[output_pdf]: Unable to create filename\n");
}
pfile = fopen(fname,"w");
if(pfile == NULL){
ath_perr(-1,"[output_pdf]: Unable to open pdf file\n");
}
/* Write out some extra information in a header */
fprintf(pfile,"# Time = %21.15e\n",pG->time);
fprintf(pfile,"# expr = \"%s\"\n",pOut->out);
fprintf(pfile,"# Nbin = %d\n",((dmax - dmin) > 0.0 ? size_pdf : 1));
fprintf(pfile,"# dmin = %21.15e\n",dmin);
fprintf(pfile,"# dmax = %21.15e\n",dmax);
fprintf(pfile,"# mean = %21.15e\n",mean);
fprintf(pfile,"# variance = %21.15e\n",var);
fprintf(pfile,"# std. dev. = %21.15e\n",sdev);
fprintf(pfile,"# avg. dev. = %21.15e\n",adev);
fprintf(pfile,"# skewness = %21.15e\n",skew);
fprintf(pfile,"# kurtosis = %21.15e\n#\n",kurt);
/* Add a white space to the format */
if(pOut->dat_fmt == NULL)
sprintf(fmt,"%s %s\n",def_fmt, def_fmt);
else
sprintf(fmt,"%s %s\n",pOut->dat_fmt,pOut->dat_fmt);
/* write out the normalized Proabability Distribution Function */
if(dmax - dmin > 0.0){
delta = (dmax - dmin)/(double)(size_pdf);
#ifdef MPI_PARALLEL
scl = (double)size_pdf/(double)(cd_data_cnt*(dmax - dmin));
#else
scl = (double)size_pdf/(double)(data_cnt*(dmax - dmin));
#endif /* MPI_PARALLEL */
for(n=0; n<size_pdf; n++){
/* Calculate the normalized Prob. Dist. Fun. */
dat = dmin + (n + 0.5)*delta;
#ifdef MPI_PARALLEL
dpdf = (double)(cd_pdf[n])*scl;
#else
dpdf = (double)(pdf[n])*scl;
#endif /* MPI_PARALLEL */
fprintf(pfile, fmt, dat, dpdf);
}
}
else
fprintf(pfile,fmt,dmax,1.0);
fclose(pfile);
/* Also write a history type file on the statistics */
sprintf(fid,"prb_stat.%s",pOut->id);
fname = ath_fname(pdir,pM->outfilename,plev,pdom,0,0,fid,"tab");
if(fname == NULL){
ath_perr(-1,"[output_pdf]: Unable to create stats filename\n");
}
pfile = fopen(fname,"a");
if(pfile == NULL){
ath_perr(-1,"[output_pdf]: Unable to open stats file\n");
}
if(pOut->num == 0){
fprintf(pfile,"# expr = \"%s\"\n#\n",pOut->out);
fprintf(pfile,"# time dmin dmax mean variance \"std. dev.\" ");
fprintf(pfile,"\"avg. dev.\" skewness kurtosis\n#\n");
}
/* Add a white space to the format */
if(pOut->dat_fmt == NULL) sprintf(fmt," %s",def_fmt);
else sprintf(fmt," %s",pOut->dat_fmt);
fprintf(pfile,"%21.15e",pG->time);
/* write out the table of statistics */
fprintf(pfile,fmt,dmin);
fprintf(pfile,fmt,dmax);
fprintf(pfile,fmt,mean);
fprintf(pfile,fmt,var);
fprintf(pfile,fmt,sdev);
fprintf(pfile,fmt,adev);
fprintf(pfile,fmt,skew);
fprintf(pfile,fmt,kurt);
fprintf(pfile,"\n");
fclose(pfile);
}}
}
}
return;
}
|
2eb11512045396f75ed051e00af603b117c770b0
|
0744dcc5394cebf57ebcba343747af6871b67017
|
/apps/examples/wifi_manager/wm_test/wm_test_log.h
|
8b64f36916736c983bdd9b4204766de086977d59
|
[
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] |
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
| 1,585
|
h
|
wm_test_log.h
|
/****************************************************************************
*
* Copyright 2021 Samsung Electronics All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License\n");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*
****************************************************************************/
#pragma once
#ifndef __LINUX__
#define WT_LOG(tag, fmt, args...) \
printf(tag "[T%d] " fmt "\t%s:%d\n", getpid(), ##args, __FUNCTION__, __LINE__)
#define WT_LOGE(tag, fmt, args...) \
printf(tag "[ERR][T%d] " fmt "\t%s:%d\n", getpid(), ##args, __FUNCTION__, __LINE__)
#define WT_LOGP(tag, fmt, args...) \
printf(fmt, ##args)
#else
#define WT_LOG(tag, fmt, args...) \
printf(tag "[INFO] " fmt "\t%s:%d\n", ##args, __FUNCTION__, __LINE__)
#define WT_LOGE(tag, fmt, args...) \
printf(tag "[ERR] " fmt "\t%s:%d\n", ##args, __FUNCTION__, __LINE__)
#define WT_LOGP(tag, fmt, args...) \
printf(fmt, ##args)
#endif
#define WT_ENTER \
do { \
WT_LOG(TAG, "-->"); \
} while (0)
#define WT_LEAVE \
do { \
WT_LOG(TAG, "<--"); \
} while (0)
|
74e5431929e1fd67c6ab8802fbf616df4d496835
|
7f6c235b0598353549959c18f69eefd20b766907
|
/libsrc/threading/preempt/get_task.c
|
31ed756621b70afc03fa7e1fd97e39b3ab4a9cb4
|
[
"ClArtistic"
] |
permissive
|
z88dk/z88dk
|
46dfd4905f36d99333173cadd0a660839befc9f0
|
8b07f37cc43c5d9ffe69b563c80763491d8faff7
|
refs/heads/master
| 2023-09-04T19:29:49.254958
| 2023-09-03T20:51:24
| 2023-09-03T20:51:24
| 54,035,569
| 820
| 263
|
NOASSERTION
| 2023-09-05T11:09:04
| 2016-03-16T13:48:16
|
Assembly
|
UTF-8
|
C
| false
| false
| 595
|
c
|
get_task.c
|
/*
* z88dk z80 multi-task library
*
* $Id: get_task.c,v 1.3 2016-04-25 17:33:05 dom Exp $
*/
#include <threading/preempt.h>
#asm
SECTION code_clib
PUBLIC get_task
; Entry: a = task number
; Exit ix = Task table for specified task
; a = task number
;
; Uses: b,d,e
.get_task
ld ix,_threadbase + threads - THREAD_SIZE
ld de,THREAD_SIZE
ld b,a
inc b
.get_task_loop
add ix,de
djnz get_task_loop
ret
#endasm
|
e5f6a1a2093f0cb5186d724db9ca39013c2ec2df
|
f1ee65fbe1ffc43c2aac45e41515f1987eb534a4
|
/src/third_party/nasm/nasmlib/nctype.c
|
f30f37e055f867e9193a6e4def62a6312ec1bd14
|
[
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] |
permissive
|
klzgrad/naiveproxy
|
6e0d206b6f065b9311d1e12b363109f2d35cc058
|
8ef1cecadfd4e2b5d57e7ea2fa42d05717e51c2e
|
refs/heads/master
| 2023-08-20T22:42:12.511091
| 2023-06-04T03:54:34
| 2023-08-16T23:30:19
| 119,178,893
| 5,710
| 976
|
BSD-3-Clause
| 2023-08-05T10:59:59
| 2018-01-27T16:02:33
|
C++
|
UTF-8
|
C
| false
| false
| 3,576
|
c
|
nctype.c
|
/* ----------------------------------------------------------------------- *
*
* Copyright 1996-2018 The NASM Authors - All Rights Reserved
* See the file AUTHORS included with the NASM distribution for
* the specific copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ----------------------------------------------------------------------- */
#include "nctype.h"
#include <ctype.h>
/*
* Table of tolower() results. This avoids function calls
* on some platforms.
*/
unsigned char nasm_tolower_tab[256];
static void tolower_tab_init(void)
{
int i;
for (i = 0; i < 256; i++)
nasm_tolower_tab[i] = tolower(i);
}
/*
* Table of character type flags; some are simply <ctype.h>,
* some are NASM-specific.
*/
uint16_t nasm_ctype_tab[256];
#if !defined(HAVE_ISCNTRL) && !defined(iscntrl)
# define iscntrl(x) ((x) < 32)
#endif
#if !defined(HAVE_ISASCII) && !defined(isascii)
# define isascii(x) ((x) < 128)
#endif
static void ctype_tab_init(void)
{
int i;
for (i = 0; i < 256; i++) {
enum nasm_ctype ct = 0;
if (iscntrl(i))
ct |= NCT_CTRL;
if (isascii(i))
ct |= NCT_ASCII;
if (isspace(i) && i != '\n')
ct |= NCT_SPACE;
if (isalpha(i)) {
ct |= (nasm_tolower(i) == i) ? NCT_LOWER : NCT_UPPER;
ct |= NCT_ID|NCT_IDSTART;
}
if (isdigit(i))
ct |= NCT_DIGIT|NCT_ID;
if (isxdigit(i))
ct |= NCT_HEX;
/* Non-ASCII character, but no ctype returned (e.g. Unicode) */
if (!ct && !ispunct(i))
ct |= NCT_ID|NCT_IDSTART;
nasm_ctype_tab[i] = ct;
}
nasm_ctype_tab['-'] |= NCT_MINUS;
nasm_ctype_tab['$'] |= NCT_DOLLAR|NCT_ID;
nasm_ctype_tab['_'] |= NCT_UNDER|NCT_ID|NCT_IDSTART;
nasm_ctype_tab['.'] |= NCT_ID|NCT_IDSTART;
nasm_ctype_tab['@'] |= NCT_ID|NCT_IDSTART;
nasm_ctype_tab['?'] |= NCT_ID|NCT_IDSTART;
nasm_ctype_tab['#'] |= NCT_ID;
nasm_ctype_tab['~'] |= NCT_ID;
nasm_ctype_tab['\''] |= NCT_QUOTE;
nasm_ctype_tab['\"'] |= NCT_QUOTE;
nasm_ctype_tab['`'] |= NCT_QUOTE;
}
void nasm_ctype_init(void)
{
tolower_tab_init();
ctype_tab_init();
}
|
2111e204eaabbdd648518c74bb02b3867189acaa
|
0fa1152e1e434ce9fe9e2db95f43f25675bf7d27
|
/src/drivers/transponder/sagetech_mxs/sg_sdk/toIcao.c
|
cc683e19cfc984617c22115764cfecdea174fed7
|
[
"BSD-3-Clause",
"Apache-2.0"
] |
permissive
|
PX4/PX4-Autopilot
|
4cc90dccc9285ca4db7f595ac5a7547df02ca92e
|
3d61ab84c42ff8623bd48ff0ba74f9cf26bb402b
|
refs/heads/main
| 2023-08-30T23:58:35.398450
| 2022-03-26T01:29:03
| 2023-08-30T15:40:01
| 5,298,790
| 3,146
| 3,798
|
BSD-3-Clause
| 2023-09-14T17:22:04
| 2012-08-04T21:19:36
|
C++
|
UTF-8
|
C
| false
| false
| 380
|
c
|
toIcao.c
|
/**
* @copyright Copyright (c) 2021 Sagetech, Inc. All rights reserved.
*
* @file toIcao.c
* @author Jacob.Garrison
*
* @date Mar 9, 2021
*
*/
#include "sgUtil.h"
/*
* Documented in the header file.
*/
uint32_t toIcao(const uint8_t bytes[])
{
uint32_t icao = (0 << 24) | ((uint32_t)bytes[0] << 16) | ((uint32_t)bytes[1] << 8) | ((uint32_t)bytes[2]);
return icao;
}
|
f7587c4964ef95ed6fb3e71c37d44ed85e68fc9a
|
1ecae23f22fd25334e9803f83c5f5f319a606cfe
|
/uc-crux-llvm/test/programs/oob_read_stack.c
|
6b4de7b5dae7178e6df92de6530cae32899ffce9
|
[
"BSD-3-Clause"
] |
permissive
|
GaloisInc/crucible
|
8ea77b3f45e36ee6ad38a5dff827793fd38456a4
|
c19fc2c53851cdd162ae1ccca14032467e3c2fd1
|
refs/heads/master
| 2023-08-29T01:28:48.974504
| 2023-08-22T23:31:42
| 2023-08-22T23:31:42
| 72,476,365
| 563
| 45
| null | 2023-08-31T22:07:29
| 2016-10-31T20:43:08
|
Rust
|
UTF-8
|
C
| false
| false
| 160
|
c
|
oob_read_stack.c
|
int dereferences_argument_16(int *ptr) __attribute__((noinline)) { return ptr[16]; }
int oob_read_stack() {
int x[8];
return dereferences_argument_16(x);
}
|
81a95c188501c77d5067177f6839375978e12010
|
e1d9c54e9925e30e388a255b53a93cccad0b94cb
|
/kubernetes/model/v1_container_state_running.h
|
90638d5426ecc36c9665e1d758c539d6daa61b72
|
[
"curl",
"Apache-2.0"
] |
permissive
|
kubernetes-client/c
|
dd4fd8095485c083e0f40f2b48159b1609a6141b
|
5ac5ff25e9809a92a48111b1f77574b6d040b711
|
refs/heads/master
| 2023-08-13T10:51:03.702497
| 2023-08-07T19:18:32
| 2023-08-07T19:18:32
| 247,958,425
| 127
| 47
|
Apache-2.0
| 2023-09-07T20:07:00
| 2020-03-17T11:59:05
|
C
|
UTF-8
|
C
| false
| false
| 975
|
h
|
v1_container_state_running.h
|
/*
* v1_container_state_running.h
*
* ContainerStateRunning is a running state of a container.
*/
#ifndef _v1_container_state_running_H_
#define _v1_container_state_running_H_
#include <string.h>
#include "../external/cJSON.h"
#include "../include/list.h"
#include "../include/keyValuePair.h"
#include "../include/binary.h"
typedef struct v1_container_state_running_t v1_container_state_running_t;
typedef struct v1_container_state_running_t {
char *started_at; //date time
} v1_container_state_running_t;
v1_container_state_running_t *v1_container_state_running_create(
char *started_at
);
void v1_container_state_running_free(v1_container_state_running_t *v1_container_state_running);
v1_container_state_running_t *v1_container_state_running_parseFromJSON(cJSON *v1_container_state_runningJSON);
cJSON *v1_container_state_running_convertToJSON(v1_container_state_running_t *v1_container_state_running);
#endif /* _v1_container_state_running_H_ */
|
13196658e65c63e33763159affc46d1c9cc51b04
|
e814383d36a10839104efaa4df277996ab220fa3
|
/opal/mca/base/mca_base_pvar.h
|
f0bdb1b747cb15bcfc2b8610e15d4921630f4e6c
|
[
"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
| 21,865
|
h
|
mca_base_pvar.h
|
/* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil -*- */
/*
* Copyright (c) 2013-2015 Los Alamos National Security, LLC. All rights
* reserved.
* Copyright (c) 2018 The University of Tennessee and The University
* of Tennessee Research Foundation. All rights
* reserved.
*
* Additional copyrights may follow
*
* $HEADER$
*/
#if !defined(OPAL_MPIT_PVAR_H)
# define OPAL_MPIT_PVAR_H
# include "opal/mca/base/mca_base_var.h"
/*
* These flags are used when registering a new pvar.
*/
typedef enum {
/** This variable should be marked as invalid when the containing
group is deregistered (IWG = "invalidate with group"). This
flag is set automatically when you register a variable with
mca_base_component_pvvar_register(), but can also be set
manually when you register a variable with
mca_base_pvar_register(). Analogous to the
MCA_BASE_VAR_FLAG_DWG flag. */
MCA_BASE_PVAR_FLAG_IWG = 0x040,
/** This variable can not be written. Will be ignored for counter,
timer, and aggregate variables. These variable handles will be
updated relative to the value reported by the get_value()
function provided at registration time. */
MCA_BASE_PVAR_FLAG_READONLY = 0x080,
/** This variable runs continuously after being bound to a handle. */
MCA_BASE_PVAR_FLAG_CONTINUOUS = 0x100,
/** This variable can be updated atomically. This flag is ignored
by mca_base_pvar_register() at this time. */
MCA_BASE_PVAR_FLAG_ATOMIC = 0x200,
/** This variable has been marked as invalid. This flag is ignored
by mca_base_pvar_register(). */
MCA_BASE_PVAR_FLAG_INVALID = 0x400,
} mca_base_pvar_flag_t;
/*
* These flags are passed to the mca_base_notify_fn_t function.
*/
typedef enum {
/** A handle has been created an bound to this variable. The
return value must be the number of values associated with
the bound object or an OPAL error. For example, if the variable
is the number of messages sent to each peer in a communicator then the
return value should be the size of the bound communicator. */
MCA_BASE_PVAR_HANDLE_BIND,
/** A handle associated with this variable has been started. It is
recommended that any computation that might affect performance
only be performed when a bound handle has been started. */
MCA_BASE_PVAR_HANDLE_START,
/** A handle associated with this variable has been stopped */
MCA_BASE_PVAR_HANDLE_STOP,
/** A handle associated with this variable has been freed */
MCA_BASE_PVAR_HANDLE_UNBIND
} mca_base_pvar_event_t;
/*
* The class type is passed when registering a new pvar.
*/
enum {
/** Variable represents a state */
MCA_BASE_PVAR_CLASS_STATE,
/** Variable represents a the utilization level of a resource */
MCA_BASE_PVAR_CLASS_LEVEL,
/** Variable represents the fixed size of a resource */
MCA_BASE_PVAR_CLASS_SIZE,
/** Variable represents the utilization level of a resource.
Valid type: double */
MCA_BASE_PVAR_CLASS_PERCENTAGE,
/** Variable describes the high-watermark of the utilization
of a resource */
MCA_BASE_PVAR_CLASS_HIGHWATERMARK,
/** Variable describes the low-watermark of the utilization
of a resource */
MCA_BASE_PVAR_CLASS_LOWWATERMARK,
/** Variable counts the number of occurrences of a specific event */
MCA_BASE_PVAR_CLASS_COUNTER,
/** Variable represents a sum of arguments processed during a
specific event */
MCA_BASE_PVAR_CLASS_AGGREGATE,
/** Variable represents the aggregated time that is spent
executing an specific event */
MCA_BASE_PVAR_CLASS_TIMER,
/** Variable doesn't fit any other class */
MCA_BASE_PVAR_CLASS_GENERIC
};
# define MCA_BASE_PVAR_CLASS_ANY -1
/*
* Reserved bindings; passed when registering a new pvar. OPAL will
* ignore any other binding type.
*/
enum {
MCA_BASE_VAR_BIND_NO_OBJECT,
MCA_BASE_VAR_BIND_MPI_COMM,
MCA_BASE_VAR_BIND_MPI_DATATYPE,
MCA_BASE_VAR_BIND_MPI_ERRHANDLER,
MCA_BASE_VAR_BIND_MPI_FILE,
MCA_BASE_VAR_BIND_MPI_GROUP,
MCA_BASE_VAR_BIND_MPI_OP,
MCA_BASE_VAR_BIND_MPI_REQUEST,
MCA_BASE_VAR_BIND_MPI_WIN,
MCA_BASE_VAR_BIND_MPI_MESSAGE,
MCA_BASE_VAR_BIND_MPI_INFO,
MCA_BASE_VAR_BIND_FIRST_AVAILABLE,
};
struct mca_base_pvar_t;
/**
* Function to retrieve the current value of a variable.
*
* @param[in] pvar Performance variable to get the value of.
* @param[out] value Current value of the variable.
* @param[in] obj Bound object
*
* This function will be called to get the current value of a variable. The value
* pointer will be large enough to hold the datatype and count specified when this
* variable was created and bound.
*/
typedef int (*mca_base_get_value_fn_t)(const struct mca_base_pvar_t *pvar, void *value, void *obj);
/**
* Function to set the current value of a variable.
*
* @param[in] pvar Performance variable to set the value of.
* @param[in] value Value to write.
* @param[in] obj Bound object.
*
* This function will be called to set the current value of a variable. The value
* pointer will be large enough to hold the datatype and count specified when this
* variable was created and bound. Read-only variables are not expected to provide
* this function.
*/
typedef int (*mca_base_set_value_fn_t)(struct mca_base_pvar_t *pvar, const void *value, void *obj);
/**
* Function to notify of a pvar handle event.
*
* @param[in] pvar Performance variable the handle is associated with
* @param[in] event Event that has occurred. See mca_base_pvar_event_t.
* @param[in] obj Bound object
* @param[out] count Value count for this object (on MCA_BASE_PVAR_HANDLE_BIND)
*
* Depending on the event this functions is expected to:
* On MCA_BASE_PVAR_HANDLE_BIND: depending on the bound object returns the number of values
* needed for get_value().
* On MCA_BASE_PVAR_HANDLE_START: enable the performance variable.
* On MCA_BASE_PVAR_HANDLE_STOP: XXX -- TODO -- finish me
*/
typedef int (*mca_base_notify_fn_t)(struct mca_base_pvar_t *pvar, mca_base_pvar_event_t event,
void *obj, int *count);
/**
* Structure representing an OPAL performance variable.
*/
typedef struct mca_base_pvar_t {
/** Make this an opal object */
opal_object_t super;
/** Variable index */
int pvar_index;
/** Full name of the variable: form is framework_component_name */
char *name;
/** Description of this performance variable */
char *description;
/** MCA variable group this variable is associated with */
int group_index;
/** Verbosity level of this variable */
mca_base_var_info_lvl_t verbosity;
/** Variable class. See mpi.h.in MPIT pvar classes */
int var_class;
/** MPI datatype of the information stored in the performance variable */
mca_base_var_type_t type;
/** Enumerator for integer values */
mca_base_var_enum_t *enumerator;
/** Type of object to which this variable must be bound or MCA_BASE_VAR_BIND_NULL */
int bind;
/** Flags for this variable */
mca_base_pvar_flag_t flags;
/** Get the current value of this variable */
mca_base_get_value_fn_t get_value;
/** Set the current value of this variable. Only valid for read-write variables. */
mca_base_set_value_fn_t set_value;
/** Notify the creator of this variable of a change */
mca_base_notify_fn_t notify;
/** Context of this variable */
void *ctx;
/** List of bound pvar handles. NOTE: The items in this list are
offsetof(mca_base_pvar_handle_t, list2) into a pvar handle. */
opal_list_t bound_handles;
} mca_base_pvar_t;
OBJ_CLASS_DECLARATION(mca_base_pvar_t);
/**
* Performance variable session
*/
typedef struct mca_base_pvar_session_t {
/** Make this an opal object */
opal_object_t super;
/** List of all handles in the session */
opal_list_t handles;
} mca_base_pvar_session_t;
OBJ_CLASS_DECLARATION(mca_base_pvar_session_t);
/**
* Performance variable handle
*
* Handles are used to bind performance variables to objects, read, write, and
* reset values.
*/
typedef struct mca_base_pvar_handle_t {
/** List item in pvar session */
opal_list_item_t super;
/** XXX -- use me -- add this list item to the associated variable */
opal_list_item_t list2;
/** session this handle is associated with */
mca_base_pvar_session_t *session;
/** performance variable this handle is associated with */
mca_base_pvar_t *pvar;
/** MPI object handle */
void *obj_handle;
/** Number of values for this handle */
int count;
/** Last value read from the variable */
void *last_value;
/** Current sum for counters and timers */
void *current_value;
/** Temporary buffer for counters. Used to calculate deltas between
the last value and the current value. */
void *tmp_value;
/** Has this handle been started (or is continuous) */
bool started;
} mca_base_pvar_handle_t;
OBJ_CLASS_DECLARATION(mca_base_pvar_handle_t);
/****************************************************************************
* The following functions are public functions, and are intended to
* be used by components and frameworks to expose their performance
* variables.
****************************************************************************/
/**
* Register a performance variable
*
* @param[in] framework Name of registering framework
* @param[in] component Name of registering component
* @param[in] name Name of performance variable
* @param[in] description Description of the performance variable. Verbose
* is good!
* @param[in] verbosity Opal info verbosity of this variable. Equivalent to
* MPI_T verbosity.
* @param[in] var_class Class of performance variable. See mpi.h.in MPI_T_PVAR_CLASS_*
* @param[in] type Type of this performance variable
* @param[in] enumerator Enumerator for this variable. Will be
* OBJ_RETAIN'd (created by, for example,
* mca_base_var_enum_create()).
* @param[in] bind Object type this variable should be bound to. See mpi.h.in
* MPI_T_BIND_*
* @param[in] flags Flags for this variable. See mca_base_pvar_flag_t for acceptable
* flags.
* @param[in] get_value Function for reading the value of this variable. If this function
* is NULL a default function that reads 1 value from ctx will be used.
* See mca_base_get_value_fn_t.
* @param[in] set_value Function for writing the value of this variable. This pointer is
* ignored if the \flags includes \MCA_BASE_PVAR_FLAG_READONLY. If this
* function is NULL a default function that writes 1 value from ctx will
* be used. See mca_base_set_value_fn_t.
* @param[in] notify Function for notifying about variable handle events. If this function
* is NULL then a default function that ignores all events will be used.
* See mca_base_notify_fn_t.
* @param[in] ctx Context for this variable. Will be stored in the resulting variable
* for future use.
*
* @returns index On success returns the index of this variable.
* @returns OPAL_ERROR On error.
*
* Note: if used incorrectly this function may fail an assert(); see
* MPI 3.0 14.3 to see acceptable values for datatype given the class.
*/
OPAL_DECLSPEC int
mca_base_pvar_register(const char *project, const char *framework, const char *component,
const char *name, const char *description, mca_base_var_info_lvl_t verbosity,
int var_class, mca_base_var_type_t type, mca_base_var_enum_t *enumerator,
int bind, mca_base_pvar_flag_t flags, mca_base_get_value_fn_t get_value,
mca_base_set_value_fn_t set_value, mca_base_notify_fn_t notify, void *ctx);
/**
* Convenience function for registering a performance variable
* associated with a component.
*
* While quite similar to mca_base_pvar_register(), there is one key
* difference: pvars registered with this function will automatically
* be unregistered / made unavailable when that component is closed by
* its framework.
*/
OPAL_DECLSPEC int mca_base_component_pvar_register(
const mca_base_component_t *component, const char *name, const char *description,
mca_base_var_info_lvl_t verbosity, int var_class, mca_base_var_type_t type,
mca_base_var_enum_t *enumerator, int bind, mca_base_pvar_flag_t flags,
mca_base_get_value_fn_t get_value, mca_base_set_value_fn_t set_value,
mca_base_notify_fn_t notify, void *ctx);
/**
* Find the index for an MCA performance variable based on its names.
*
* @param project Name of the project
* @param type Name of the type containing the variable.
* @param component Name of the component containing the variable.
* @param param Name of the variable.
*
* @retval OPAL_ERROR If the variable was not found.
* @retval index If the variable was found.
*
* It is not always convenient to widely propagate a variable's index
* value, or it may be necessary to look up the variable from a
* different component. This function can be used to look up the index
* of any registered variable. The returned index can be used with
* mca_base_pvar_get(), mca_base_pvar_handle_alloc(), and
* mca_base_pvar_dump().
*/
OPAL_DECLSPEC int mca_base_pvar_find(const char *project, const char *framework,
const char *component, const char *name);
/**
* Find the index for a performance variable based on its full name
*
* @param full_name [in] Full name of the variable
* @param index [out] Index of the variable
*
* See mca_base_pvar_find().
*/
OPAL_DECLSPEC int mca_base_pvar_find_by_name(const char *full_name, int var_class, int *index);
/****************************************************************************
* The following functions are the back-end to the MPI_T API functions
* and/or the internals of the performance variable system itself.
****************************************************************************/
/**
* Return the number or registered performance variables.
*
* @param[out] count Number of registered performance variables.
*
* This function can be called before mca_base_pvar_init() and after
* mca_base_pvar_finalize().
*/
OPAL_DECLSPEC int mca_base_pvar_get_count(int *count);
/**
* Update the handles associated with the specified performance variable and MPI object
*
* @param[in] index Index of the performance variable
* @param[in] value New value of the variable.
* @param[in] obj Object updated handles should be bound to.
*
* This function will obtain and hold the mpit big lock until all handles are updated. It
* is recommended this function not be called from within any critical code path. Calling
* this function should only be necessary to update watermarks.
*/
OPAL_DECLSPEC int mca_base_pvar_update_all_handles(int index, const void *obj);
/**
* Get the variable at an index
*
* @param[in] index Index of variable to get.
* @param[out] pvar Performance variable from index on success.
*
* @returns OPAL_SUCCESS on success
* @returns OPAL_ERR_VALUE_OUT_OF_BOUNDS on if index is out of range
*/
OPAL_DECLSPEC int mca_base_pvar_get(int index, const mca_base_pvar_t **pvar);
/**
* Dump strings describing the performance variable at an index
*
* @param[in] index Variable index
* @param[out] out Array of strings representing this variable
* @param[in] output_type Type of output desired
*
* This function returns an array of strings describing the variable. All strings
* and the array must be freed by the caller. The \output_type may be either
* MCA_BASE_VAR_DUMP_READABLE or MCA_BASE_VAR_DUMP_PARSABLE.
*/
OPAL_DECLSPEC int mca_base_pvar_dump(int index, char ***out, mca_base_var_dump_type_t output_type);
/**
* Mark a performance variable as invalid
*
* @param[in] index Variable index
*
* A performance variable that has been marked as invalid will not be available. To
* restore a performance variable it has to be re-registered using mca_base_pvar_register().
*/
int mca_base_pvar_mark_invalid(int index);
/**
* Convenience functions for performance variables
*/
static inline bool mca_base_pvar_is_sum(const mca_base_pvar_t *pvar)
{
return (MCA_BASE_PVAR_CLASS_COUNTER == pvar->var_class
|| MCA_BASE_PVAR_CLASS_TIMER == pvar->var_class
|| MCA_BASE_PVAR_CLASS_AGGREGATE == pvar->var_class);
}
static inline bool mca_base_pvar_is_watermark(const mca_base_pvar_t *pvar)
{
return (MCA_BASE_PVAR_CLASS_HIGHWATERMARK == pvar->var_class
|| MCA_BASE_PVAR_CLASS_LOWWATERMARK == pvar->var_class);
}
static inline bool mca_base_pvar_is_readonly(const mca_base_pvar_t *pvar)
{
return !!(pvar->flags & MCA_BASE_PVAR_FLAG_READONLY);
}
static inline bool mca_base_pvar_is_continuous(const mca_base_pvar_t *pvar)
{
return !!(pvar->flags & MCA_BASE_PVAR_FLAG_CONTINUOUS);
}
static inline bool mca_base_pvar_is_atomic(const mca_base_pvar_t *pvar)
{
return !!(pvar->flags & MCA_BASE_PVAR_FLAG_ATOMIC);
}
static inline bool mca_base_pvar_is_invalid(const mca_base_pvar_t *pvar)
{
return !!(pvar->flags & MCA_BASE_PVAR_FLAG_INVALID);
}
/* Handle functions */
/**
* Bind a new handle and object to a performance variable
*
* @param[in] session Valid pvar session
* @param[in] index Variable index
* @param[in] obj_handle Object handle
* @param[out] handle New handle
* @param[out] count Number of values associated with this object
*
* This function allocates a new performance variable handle and binds it
* to \obj_handle (if the variable binding is 0 the object is ignored). On
* success a new handle is returned in \handle and the number of values i
* returned in \count. Calls to read/write must provide buffers that will
* hold \count values of the type of the performance variable specified by
* \index.
*/
OPAL_DECLSPEC int mca_base_pvar_handle_alloc(mca_base_pvar_session_t *session, int index,
void *obj_handle, mca_base_pvar_handle_t **handle,
int *count);
/**
* Free an allocated performance variable handle
*
* @param[in] handle Handle to free
*
* After calling this function the performance variable will no longer be valid.
*/
OPAL_DECLSPEC int mca_base_pvar_handle_free(mca_base_pvar_handle_t *handle);
/**
* Update a performance variable handle.
*
* @param[in] handle Handle to update
*
* The new value of the handle will depend on the class of performance variable.
* For counters and timers the new value will be the current handle value plus the
* difference between the last and the current variable value. For high/low watermarks
* the new value will be the greater/lesser of the current handle value and the
* current variable value. This call does not update other types of handles.
*/
OPAL_DECLSPEC int mca_base_pvar_handle_update(mca_base_pvar_handle_t *handle);
/**
* Read the current value of a handle
*
* @param[in] handle Handle to read from
* @param[out] value Buffer to store the current value in
*
* Read the current value of the handle or variable (depending on the variable class)
* and return it in the buffer specified by value. The buffer must be large enough to
* hold the correct number and type of this handle's value (see mca_base_pvar_handle_update()).
*/
OPAL_DECLSPEC int mca_base_pvar_handle_read_value(mca_base_pvar_handle_t *handle, void *value);
/**
* Write a value to a read-write handle
*
* @param[in] handle Handle to update
* @param[in] value Value to write
*
* If the underlying variable is read-only this function will fail with OPAL_ERR_PERM.
*/
OPAL_DECLSPEC int mca_base_pvar_handle_write_value(mca_base_pvar_handle_t *handle,
const void *value);
/**
* Convenience function for sending notification of a handle change
*
* @param[in] handle Handle event occurred on
* @param[in] event Event that occurred
* @param[out] count Value count returned when binding a handle
*/
OPAL_DECLSPEC int mca_base_pvar_notify(mca_base_pvar_handle_t *handle, mca_base_pvar_event_t event,
int *count);
/**
* Start a performance variable handle
*
* @param[in] handle Handle to start
*
* @returns OPAL_SUCCESS on success
* @returns OPAL_ERR_NOT_SUPPORTED if the handle could not be started
*/
OPAL_DECLSPEC int mca_base_pvar_handle_start(mca_base_pvar_handle_t *handle);
/**
* Stop a performance variable handle
*
* @param[in] handle Handle to stop (must be started)
*
* @return OPAL_SUCCESS on success
* @returns OPAL_ERR_NOT_SUPPORTED if the handle could not be started
*/
OPAL_DECLSPEC int mca_base_pvar_handle_stop(mca_base_pvar_handle_t *handle);
/**
* Reset a performance variable handle
*
* @param[in] handle Handle to reset
*
* Reset the handle to a value equivalent to when the handle was first allocated.
*/
OPAL_DECLSPEC int mca_base_pvar_handle_reset(mca_base_pvar_handle_t *handle);
static inline bool mca_base_pvar_handle_is_running(mca_base_pvar_handle_t *handle)
{
return handle->started || !!(handle->pvar->flags & MCA_BASE_PVAR_FLAG_CONTINUOUS);
}
#endif
|
ca1933cc7778cc0ef3313dc95b878611a3fdf166
|
cce217852fee0a222fdca9f8f6ee8897c540c663
|
/patch/shiftboth.h
|
7a9b8c23f6cd821e45daee79434f876e2e0ae40f
|
[
"MIT"
] |
permissive
|
bakkeby/dwm-flexipatch
|
d3e920f13701714d33a5ea75a12bb52df68f54aa
|
7849eaa08b71d359c939b946598716539b4ba1d7
|
refs/heads/master
| 2023-08-31T22:09:22.250888
| 2023-08-24T16:18:03
| 2023-08-24T16:18:03
| 206,426,925
| 1,094
| 366
|
MIT
| 2023-08-24T16:18:04
| 2019-09-04T22:35:38
|
C
|
UTF-8
|
C
| false
| false
| 39
|
h
|
shiftboth.h
|
static void shiftboth(const Arg *arg);
|
9322b403354d817c36c53194e7e7d8884b1e26f3
|
01cd23a38c901356c1d03869faf9a528bdeba720
|
/framework/PVRUtils/OpenGLES/UIRendererShaders_ES.h
|
5ced08405c610458c91e049231c8aa2665a37d60
|
[
"MIT"
] |
permissive
|
powervr-graphics/Native_SDK
|
f29fd2848b43abb290e09632391282d90b40a046
|
91b58cc2d1d2b1405b997ad7bc46f9224d0ec1ce
|
refs/heads/master
| 2023-07-07T01:20:21.987328
| 2023-04-28T15:57:49
| 2023-04-28T15:57:49
| 25,927,337
| 651
| 238
|
MIT
| 2022-02-28T09:05:46
| 2014-10-29T15:28:11
|
C++
|
UTF-8
|
C
| false
| false
| 2,070
|
h
|
UIRendererShaders_ES.h
|
/*!
\brief The shaders for UIRenderer as c-style strings, glsl200es and glsl300es versions.
\file PVRUtils/OpenGLES/UIRendererShaders_ES.h
\author PowerVR by Imagination, Developer Technology Team
\copyright Copyright (c) Imagination Technologies Limited.
*/
/// <summary>Source for the OpenGL ES 2 vertex shader for the UIRenderer</summary>
static const char _print3DShader_glsles200_vsh[] = "attribute highp vec4 myVertex;\n"
"attribute mediump vec2 myUV;\n"
"uniform mat4 myMVPMatrix;\n"
"uniform mat4 myUVMatrix;\n"
"varying mediump vec2 texCoord;\n"
"\n"
"void main()\n"
"{\n"
"\tgl_Position = myMVPMatrix * myVertex;\n"
"\ttexCoord = (myUVMatrix * vec4(myUV.st,1.0,1.0)).xy;\n"
"}\n";
static const int _print3DShader_glsles200_vsh_size = sizeof(_print3DShader_glsles200_vsh) / sizeof(_print3DShader_glsles200_vsh[0]);
/// <summary>Source for the OpenGL ES 2 fragment shader of the UIRenderer</summary>
static const char _print3DShader_glsles200_fsh[] = "uniform sampler2D fontTexture;\n"
"uniform highp vec4 varColor;\n"
"uniform bool alphaMode;\n"
"varying mediump vec2 texCoord;\n"
"void main()\n"
"{\n"
"\tmediump vec4 vTex = texture2D(fontTexture, texCoord);\n"
"\tif (alphaMode)\n"
"\t{\n"
"\t\tgl_FragColor = vec4(varColor.rgb, varColor.a * vTex.a);\n"
"\t}\n"
"\telse\n"
"\t{\n"
"\t\tgl_FragColor = vec4(varColor * vTex);\n"
"\t}\n"
"\t#ifndef FRAMEBUFFER_SRGB\n"
"\t\tgl_FragColor.rgb = pow(gl_FragColor.rgb, vec3(0.4545454545));// Gamma correction (0.4545454545 = 1.0/ 2.2)\n"
"\t#endif\n"
"}\n";
static const int _print3DShader_glsles200_fsh_size = sizeof(_print3DShader_glsles200_fsh) / sizeof(_print3DShader_glsles200_fsh[0]);
|
6e02972b415b07b1e6e9c660cf212d07249a8b1a
|
9ceacf33fd96913cac7ef15492c126d96cae6911
|
/sys/ufs/ufs/ufs_quota_stub.c
|
ed7f8fefda0e7c64422716dff57e3d51b6d86dbc
|
[] |
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,237
|
c
|
ufs_quota_stub.c
|
/* $OpenBSD: ufs_quota_stub.c,v 1.8 2015/03/14 03:38:53 jsg Exp $ */
#include <sys/param.h>
#include <sys/kernel.h>
#include <sys/systm.h>
#include <sys/namei.h>
#include <sys/malloc.h>
#include <sys/vnode.h>
#include <sys/mount.h>
#include <ufs/ufs/quota.h>
#include <ufs/ufs/inode.h>
#include <ufs/ufs/ufsmount.h>
#include <ufs/ufs/ufs_extern.h>
#ifndef QUOTA
int
getinoquota(struct inode *ip) {
return (0);
}
int
ufs_quota_alloc_blocks2(struct inode *ip, daddr_t change,
struct ucred *cred, enum ufs_quota_flags flags) {
return (0);
}
int
ufs_quota_free_blocks2(struct inode *ip, daddr_t change,
struct ucred *cred, enum ufs_quota_flags flags) {
return (0);
}
int
ufs_quota_alloc_inode2(struct inode *ip, struct ucred *cred,
enum ufs_quota_flags flags) {
return (0);
}
int
ufs_quota_free_inode2(struct inode *ip, struct ucred *cred,
enum ufs_quota_flags flags) {
return (0);
}
int
quotaoff(struct proc *p, struct mount *mp, int flags) {
return (0);
}
int
qsync(struct mount *mp) {
return (0);
}
int
ufs_quotactl(struct mount *mp, int a, uid_t u, caddr_t addr, struct proc *p) {
return (EOPNOTSUPP);
}
void
ufs_quota_init(void) {
}
int
ufs_quota_delete(struct inode *ip) {
return (0);
}
#endif
|
6b0c41421d97f62b520ae8351c7ab82a0067b62b
|
765f7b8c2caf2d50da8f431f1332207456ba33ee
|
/kernel/net/ipv4.c
|
6870af1594e745c2dfd8906845c966faa3159800
|
[
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-commercial-license",
"AGPL-3.0-or-later",
"GPL-1.0-or-later",
"NCSA",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
klange/toaruos
|
a840f8d46993dc7a8850f82b6d04ba0c2af276a9
|
4a31a09ba27904b42ee35e8fb1a3c7f87669a2ef
|
refs/heads/master
| 2023-09-01T02:00:53.151334
| 2023-08-28T00:59:18
| 2023-08-28T00:59:18
| 1,259,258
| 5,557
| 613
|
NCSA
| 2023-02-04T08:24:11
| 2011-01-16T00:59:27
|
C
|
UTF-8
|
C
| false
| false
| 31,811
|
c
|
ipv4.c
|
/**
* @file kernel/net/ipv4.c
* @brief IPv4, TCP, UDP protocol implementation.
*
* @copyright
* This file is part of ToaruOS and is released under the terms
* of the NCSA / University of Illinois License - see LICENSE.md
* Copyright (C) 2021 K. Lange
*/
#include <errno.h>
#include <kernel/types.h>
#include <kernel/string.h>
#include <kernel/printf.h>
#include <kernel/syscall.h>
#include <kernel/hashmap.h>
#include <kernel/vfs.h>
#include <kernel/time.h>
#include <kernel/misc.h>
#include <kernel/assert.h>
#include <kernel/net/netif.h>
#include <kernel/net/eth.h>
#include <kernel/net/ipv4.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#ifndef MISAKA_DEBUG_NET
#define printf(...) if (_debug) printf(__VA_ARGS__)
//#define printf(...)
#endif
#define DEFAULT_TCP_WINDOW_SIZE 65535
static int _debug __attribute__((unused)) = 0;
static void ip_ntoa(const uint32_t src_addr, char * out) {
snprintf(out, 16, "%d.%d.%d.%d",
(src_addr & 0xFF000000) >> 24,
(src_addr & 0xFF0000) >> 16,
(src_addr & 0xFF00) >> 8,
(src_addr & 0xFF));
}
static uint16_t icmp_checksum(struct ipv4_packet * packet) {
uint32_t sum = 0;
uint16_t * s = (uint16_t *)packet->payload;
for (int i = 0; i < (ntohs(packet->length) - 20) / 2; ++i) {
sum += ntohs(s[i]);
}
if (sum > 0xFFFF) {
sum = (sum >> 16) + (sum & 0xFFFF);
}
return ~(sum & 0xFFFF) & 0xFFFF;
}
uint16_t calculate_ipv4_checksum(struct ipv4_packet * p) {
uint32_t sum = 0;
uint16_t * s = (uint16_t *)p;
/* TODO: Checksums for options? */
for (int i = 0; i < 10; ++i) {
sum += ntohs(s[i]);
if (sum > 0xFFFF) {
sum = (sum >> 16) + (sum & 0xFFFF);
}
}
return ~(sum & 0xFFFF) & 0xFFFF;
}
uint16_t calculate_tcp_checksum(struct tcp_check_header * p, struct tcp_header * h, void * d, size_t payload_size) {
uint32_t sum = 0;
uint16_t * s = (uint16_t *)p;
/* TODO: Checksums for options? */
for (int i = 0; i < 6; ++i) {
sum += ntohs(s[i]);
if (sum > 0xFFFF) {
sum = (sum >> 16) + (sum & 0xFFFF);
}
}
s = (uint16_t *)h;
for (int i = 0; i < 10; ++i) {
sum += ntohs(s[i]);
if (sum > 0xFFFF) {
sum = (sum >> 16) + (sum & 0xFFFF);
}
}
uint16_t d_words = payload_size / 2;
s = (uint16_t *)d;
for (unsigned int i = 0; i < d_words; ++i) {
sum += ntohs(s[i]);
if (sum > 0xFFFF) {
sum = (sum >> 16) + (sum & 0xFFFF);
}
}
if (d_words * 2 != payload_size) {
uint8_t * t = (uint8_t *)d;
uint8_t tmp[2];
tmp[0] = t[d_words * sizeof(uint16_t)];
tmp[1] = 0;
uint16_t * f = (uint16_t *)tmp;
sum += ntohs(f[0]);
if (sum > 0xFFFF) {
sum = (sum >> 16) + (sum & 0xFFFF);
}
}
return ~(sum & 0xFFFF) & 0xFFFF;
}
int net_ipv4_send(struct ipv4_packet * response, fs_node_t * nic) {
/* TODO: This should be routing, with a _hint_ about the interface, not the actual nic to send from! */
struct EthernetDevice * enic = nic->device;
/* where are we going? */
uint32_t ipdest = response->destination;
/* Get the ethernet address of the destination */
struct ArpCacheEntry * resp;
/* Is this local or should we send it to the gateway? */
if (!enic->ipv4_subnet || ((ipdest & enic->ipv4_subnet) != (enic->ipv4_addr & enic->ipv4_subnet))) {
ipdest = enic->ipv4_gateway;
resp = net_arp_cache_get(ipdest);
} else {
resp = net_arp_cache_get(ipdest);
if (!resp) {
net_arp_ask(ipdest, nic);
unsigned long s, ss;
relative_time(0, 1000, &s, &ss);
sleep_until((process_t *)this_core->current_process, s, ss);
switch_task(0);
resp = net_arp_cache_get(ipdest);
}
}
/* Pass the packet to the next stage */
net_eth_send(enic, ntohs(response->length), response, ETHERNET_TYPE_IPV4, resp ? resp->hwaddr : ETHERNET_BROADCAST_MAC);
return 0;
}
static sock_t * icmp_handler = NULL;
static void icmp_handle(struct ipv4_packet * packet, const char * src, const char * dest, fs_node_t * nic) {
struct icmp_header * header = (void*)&packet->payload;
/* Is this a PING request? */
if (header->type == 8 && header->code == 0) {
printf("net: ping with %d bytes of payload\n", ntohs(packet->length));
if (ntohs(packet->length) & 1) {
packet->length = htons(ntohs(packet->length) + 1);
}
struct ipv4_packet * response = malloc(ntohs(packet->length));
memcpy(response, packet, ntohs(packet->length));
response->length = packet->length;
response->destination = packet->source;
response->source = ((struct EthernetDevice*)nic->device)->ipv4_addr;
response->ttl = 64;
response->protocol = 1;
response->ident = packet->ident;
response->flags_fragment = htons(0x4000);
response->version_ihl = 0x45;
response->dscp_ecn = 0;
response->checksum = 0;
response->checksum = htons(calculate_ipv4_checksum(response));
struct icmp_header * ping_reply = (void*)&response->payload;
ping_reply->csum = 0;
ping_reply->type = 0;
ping_reply->csum = htons(icmp_checksum(response));
/* send ipv4... */
net_ipv4_send(response,nic);
free(response);
} else if (header->type == 0 && header->code == 0) {
printf("net: ping reply\n");
/* Did we have a client waiting for this? */
if (icmp_handler) {
net_sock_add(icmp_handler, packet, ntohs(packet->length));
}
} else {
printf("net: ipv4: %s: %s -> %s ICMP %d (code = %d)\n", nic->name, src, dest, header->type, header->code);
}
}
static void sock_icmp_close(sock_t * sock) {
icmp_handler = NULL;
}
static long sock_icmp_recv(sock_t * sock, struct msghdr * msg, int flags) {
if (msg->msg_iovlen > 1) {
return -ENOTSUP;
}
if (msg->msg_iovlen == 0) return 0;
if (!sock->rx_queue->length && sock->nonblocking) return -EAGAIN;
char * packet = net_sock_get(sock);
if (!packet) return -EINTR;
size_t packet_size = *(size_t*)packet - sizeof(struct ipv4_packet);
struct ipv4_packet * src = (struct ipv4_packet*)(packet + sizeof(size_t));
if (packet_size > msg->msg_iov[0].iov_len) {
dprintf("ICMP recv too big for vector\n");
packet_size = msg->msg_iov[0].iov_len;
}
if (msg->msg_namelen == sizeof(struct sockaddr_in)) {
if (msg->msg_name) {
((struct sockaddr_in*)msg->msg_name)->sin_family = AF_INET;
((struct sockaddr_in*)msg->msg_name)->sin_port = 0;
((struct sockaddr_in*)msg->msg_name)->sin_addr.s_addr = src->source;
((struct sockaddr_in*)msg->msg_name)->sin_zero[0] = src->ttl;
}
}
memcpy(msg->msg_iov[0].iov_base, src->payload, packet_size);
free(packet);
return packet_size;
}
static long sock_icmp_send(sock_t * sock, const struct msghdr *msg, int flags) {
if (msg->msg_iovlen > 1) {
return -ENOTSUP;
}
if (msg->msg_iovlen == 0) return 0;
if (msg->msg_namelen != sizeof(struct sockaddr_in)) {
return -EINVAL;
}
struct sockaddr_in * name = msg->msg_name;
fs_node_t * nic = net_if_route(name->sin_addr.s_addr);
if (!nic) return -ENONET;
size_t total_length = sizeof(struct ipv4_packet) + msg->msg_iov[0].iov_len;
struct ipv4_packet * response = malloc(total_length);
response->length = htons(total_length);
response->destination = name->sin_addr.s_addr;
response->source = ((struct EthernetDevice*)nic->device)->ipv4_addr;
response->ttl = 64;
response->protocol = 1;
response->ident = 0;
response->flags_fragment = htons(0x4000);
response->version_ihl = 0x45;
response->dscp_ecn = 0;
response->checksum = 0;
response->checksum = htons(calculate_ipv4_checksum(response));
memcpy(response->payload, msg->msg_iov[0].iov_base, msg->msg_iov[0].iov_len);
net_ipv4_send(response,nic);
free(response);
return 0;
}
static int icmp_socket(void) {
printf("icmp socket...\n");
if (icmp_handler) return -EINVAL;
sock_t * sock = net_sock_create();
sock->sock_recv = sock_icmp_recv;
sock->sock_send = sock_icmp_send;
sock->sock_close = sock_icmp_close;
icmp_handler = sock;
return process_append_fd((process_t *)this_core->current_process, (fs_node_t *)sock);
}
static hashmap_t * udp_sockets = NULL;
static hashmap_t * tcp_sockets = NULL;
void ipv4_install(void) {
udp_sockets = hashmap_create_int(10);
tcp_sockets = hashmap_create_int(10);
}
#define TCP_FLAGS_FIN (1 << 0)
#define TCP_FLAGS_SYN (1 << 1)
#define TCP_FLAGS_RST (1 << 2)
#define TCP_FLAGS_PSH (1 << 3)
#define TCP_FLAGS_ACK (1 << 4)
#define TCP_FLAGS_URG (1 << 5)
#define TCP_FLAGS_ECE (1 << 6)
#define TCP_FLAGS_CWR (1 << 7)
#define TCP_FLAGS_NS (1 << 8)
#define DATA_OFFSET_5 (0x5 << 12)
static int tcp_ack(fs_node_t * nic, sock_t * sock, struct ipv4_packet * packet, int isSynAck, size_t payload_len) {
struct tcp_header * tcp = (struct tcp_header*)&packet->payload;
int retval = 1;
int window_size = DEFAULT_TCP_WINDOW_SIZE;
int send_thrice = 0;
#if 0
/* XXX: This means the header is bigger than we expect... */
if ((ntohs(tcp->flags) & 0xF000) != 0x5000) {
int _debug __attribute__((unused)) = 1;
printf("tcp: uh, weird flags? %#4x\n", ntohs(tcp->flags));
}
#endif
if (sock->priv32[1] != 0 && !isSynAck &&
sock->priv32[1] != ntohl(tcp->seq_number)) {
#if 0
int _debug __attribute__((unused)) = 1;
printf("tcp: suspicious of their seq number?\n");
printf("tcp: their seq = %u our ack = %u\n",
ntohl(tcp->seq_number), sock->priv32[1]);
#endif
//window_size = 300;
retval = 0;
send_thrice = 1;
} else {
sock->priv32[0] = isSynAck ? 1 : sock->priv32[0];
sock->priv32[1] = (ntohl(tcp->seq_number) + payload_len) & 0xFFFFFFFF;
sock->priv[1] = 2;
}
sock->priv[2]++;
#if 0
printf("tcp: their ack = %u our seq = %u\n",
ntohl(tcp->ack_number), sock->priv32[0]);
printf("tcp: their seq = %u our ack = %u\n",
ntohl(tcp->seq_number), sock->priv32[1]);
#endif
size_t total_length = sizeof(struct ipv4_packet) + sizeof(struct tcp_header);
struct ipv4_packet * response = malloc(total_length);
response->length = htons(total_length);
response->destination = packet->source;
response->source = ((struct EthernetDevice*)nic->device)->ipv4_addr;
response->ttl = 64;
response->protocol = IPV4_PROT_TCP;
response->ident = htons(sock->priv[2]);
response->flags_fragment = htons(0x0);
response->version_ihl = 0x45;
response->dscp_ecn = 0;
response->checksum = 0;
response->checksum = htons(calculate_ipv4_checksum(response));
int flags = TCP_FLAGS_ACK;
if (ntohs(tcp->flags) & TCP_FLAGS_FIN) {
/* Other side is closed now */
sock->priv32[1]++;
sock->priv[1] = 3;
}
/* Stick TCP header into payload */
struct tcp_header * tcp_header = (struct tcp_header*)&response->payload;
tcp_header->source_port = htons(sock->priv[0]);
tcp_header->destination_port = tcp->source_port;
tcp_header->seq_number = htonl(sock->priv32[0]);
tcp_header->ack_number = htonl(sock->priv32[1]);
tcp_header->flags = htons(flags | 0x5000);
tcp_header->window_size = htons(window_size);
tcp_header->checksum = 0;
tcp_header->urgent = 0;
/* Calculate checksum */
struct tcp_check_header check_hd = {
.source = response->source,
.destination = response->destination,
.zeros = 0,
.protocol = IPV4_PROT_TCP,
.tcp_len = htons(sizeof(struct tcp_header)),
};
tcp_header->checksum = htons(calculate_tcp_checksum(&check_hd, tcp_header, NULL, 0));
net_ipv4_send(response,nic);
if (send_thrice) {
net_ipv4_send(response,nic);
net_ipv4_send(response,nic);
}
free(response);
return retval;
}
void net_ipv4_handle(struct ipv4_packet * packet, fs_node_t * nic, size_t size) {
if (size < sizeof(struct ipv4_packet)) {
dprintf("ipv4: Incoming packet is too small.\n");
}
char dest[16];
char src[16];
ip_ntoa(ntohl(packet->destination), dest);
ip_ntoa(ntohl(packet->source), src);
switch (packet->protocol) {
case 1:
icmp_handle(packet, src, dest, nic);
break;
case IPV4_PROT_UDP: {
uint16_t dest_port = ntohs(((uint16_t*)&packet->payload)[1]);
printf("net: ipv4: %s: %s -> %s udp %d to %d\n", nic->name, src, dest, ntohs(((uint16_t*)&packet->payload)[0]), dest_port);
if (hashmap_has(udp_sockets, (void*)(uintptr_t)dest_port)) {
printf("net: udp: received and have a waiting endpoint!\n");
sock_t * sock = hashmap_get(udp_sockets, (void*)(uintptr_t)dest_port);
net_sock_add(sock, packet, ntohs(packet->length));
}
break;
}
case IPV4_PROT_TCP: {
uint16_t dest_port = ntohs(((uint16_t*)&packet->payload)[1]);
printf("net: ipv4: %s: %s -> %s tcp %d to %d\n", nic->name, src, dest, ntohs(((uint16_t*)&packet->payload)[0]), dest_port);
sock_t * sock = hashmap_get(tcp_sockets, (void*)(uintptr_t)dest_port);
if (sock) {
printf("net: tcp: received and have a waiting endpoint!\n");
/* What kind of packet is this? Is it something we were expecting? */
struct tcp_header * tcp = (struct tcp_header*)&packet->payload;
if (sock->priv[1] == 1) {
/* Awaiting SYN ACK, is this one? */
if ((ntohs(tcp->flags) & (TCP_FLAGS_SYN | TCP_FLAGS_ACK)) == (TCP_FLAGS_SYN | TCP_FLAGS_ACK)) {
printf("tcp: synack\n");
if (tcp_ack(nic, sock, packet, 1, 1)) {
net_sock_add(sock, packet, ntohs(packet->length));
}
} else if ((ntohs(tcp->flags) & (TCP_FLAGS_RST))) {
sock->priv[1] = 0;
net_sock_alert(sock);
}
} else if (sock->priv[1] == 2) {
size_t packet_len = ntohs(packet->length) - sizeof(struct ipv4_packet);
size_t hlen = ((ntohs(tcp->flags) & 0xF000) >> 12) * 4;
size_t payload_len = packet_len - hlen;
if (payload_len) {
printf("tcp: acking because payload_len = %zu (hlen=%zu, packet_len=%zu)\n", payload_len, hlen, packet_len);
if (tcp_ack(nic, sock, packet, 0, payload_len)) {
net_sock_add(sock, packet, ntohs(packet->length));
}
} else if (ntohs(tcp->flags) & TCP_FLAGS_FIN) {
tcp_ack(nic, sock, packet, 0, 0);
}
}
}
break;
}
}
}
static spin_lock_t udp_port_lock = {0};
static int next_port = 12345;
static int udp_get_port(sock_t * sock) {
spin_lock(udp_port_lock);
int out = next_port++;
hashmap_set(udp_sockets, (void*)(uintptr_t)out, sock);
sock->priv[0] = out;
spin_unlock(udp_port_lock);
return out;
}
static long sock_udp_send(sock_t * sock, const struct msghdr *msg, int flags) {
printf("udp: send called\n");
if (msg->msg_iovlen > 1) {
printf("net: todo: can't send multiple iovs\n");
return -ENOTSUP;
}
if (msg->msg_iovlen == 0) return 0;
if (msg->msg_namelen != sizeof(struct sockaddr_in)) {
printf("udp: invalid destination address size %ld\n", msg->msg_namelen);
return -EINVAL;
}
if (sock->priv[0] == 0) {
udp_get_port(sock);
printf("udp: assigning port %d to socket\n", sock->priv[0]);
}
struct sockaddr_in * name = msg->msg_name;
char dest[16];
ip_ntoa(ntohl(name->sin_addr.s_addr), dest);
printf("udp: want to send to %s\n", dest);
/* Routing: We need a device to send this on... */
fs_node_t * nic = net_if_route(name->sin_addr.s_addr);
if (!nic) return 0;
size_t total_length = sizeof(struct ipv4_packet) + msg->msg_iov[0].iov_len + sizeof(struct udp_packet);
struct ipv4_packet * response = malloc(total_length);
response->length = htons(total_length);
response->destination = name->sin_addr.s_addr;
response->source = ((struct EthernetDevice*)nic->device)->ipv4_addr;
response->ttl = 64;
response->protocol = IPV4_PROT_UDP;
response->ident = 0;
response->flags_fragment = htons(0x4000);
response->version_ihl = 0x45;
response->dscp_ecn = 0;
response->checksum = 0;
response->checksum = htons(calculate_ipv4_checksum(response));
/* Stick UDP header into payload */
struct udp_packet * udp_packet = (struct udp_packet*)&response->payload;
udp_packet->source_port = htons(sock->priv[0]);
udp_packet->destination_port = name->sin_port;
udp_packet->length = htons(sizeof(struct udp_packet) + msg->msg_iov[0].iov_len);
udp_packet->checksum = 0;
memcpy(response->payload + sizeof(struct udp_packet), msg->msg_iov[0].iov_base, msg->msg_iov[0].iov_len);
net_ipv4_send(response,nic);
free(response);
return msg->msg_iov[0].iov_len;
}
static long sock_udp_recv(sock_t * sock, struct msghdr * msg, int flags) {
printf("udp: recv called\n");
if (!sock->priv[0]) {
printf("udp: recv() but socket has no port\n");
return -EINVAL;
}
if (msg->msg_iovlen > 1) {
printf("net: todo: can't recv multiple iovs\n");
return -ENOTSUP;
}
if (msg->msg_iovlen == 0) return 0;
if (!sock->rx_queue->length && sock->nonblocking) return -EAGAIN;
char * packet = net_sock_get(sock);
if (!packet) return -EINTR;
struct ipv4_packet * data = (struct ipv4_packet*)(packet + sizeof(size_t));
struct udp_packet * udp_packet = (struct udp_packet*)&data->payload;
printf("udp: got response, size is %u - sizeof(ipv4) - sizeof(udp) = %lu\n",
ntohs(data->length), ntohs(data->length) - sizeof(struct ipv4_packet) - sizeof(struct udp_packet));
memcpy(msg->msg_iov[0].iov_base, udp_packet->payload, ntohs(data->length) - sizeof(struct ipv4_packet) - sizeof(struct udp_packet));
if (msg->msg_namelen == sizeof(struct sockaddr_in)) {
if (msg->msg_name) {
((struct sockaddr_in*)msg->msg_name)->sin_family = AF_INET;
((struct sockaddr_in*)msg->msg_name)->sin_port = udp_packet->source_port;
((struct sockaddr_in*)msg->msg_name)->sin_addr.s_addr = data->source;
}
}
printf("udp: data copied to iov 0, return length?\n");
long resp = ntohs(data->length) - sizeof(struct ipv4_packet) - sizeof(struct udp_packet);
free(packet);
return resp;
}
static void sock_udp_close(sock_t * sock) {
if (sock->priv[0]) {
printf("udp: removing port %d from bound map\n", sock->priv[0]);
spin_lock(udp_port_lock);
hashmap_remove(udp_sockets, (void*)(uintptr_t)sock->priv[0]);
spin_unlock(udp_port_lock);
}
}
static long sock_udp_bind(sock_t * sock, const struct sockaddr *addr, socklen_t addrlen) {
if (sock->priv[0]) return -EINVAL; /* Already bound */
/* Get port */
const struct sockaddr_in * addr_in = (const struct sockaddr_in *)addr;
int port = ntohs(addr_in->sin_port);
spin_lock(udp_port_lock);
if (hashmap_has(udp_sockets, (void*)(uintptr_t)port)) {
spin_unlock(udp_port_lock);
return -EADDRINUSE;
}
hashmap_set(udp_sockets, (void*)(uintptr_t)port, sock);
sock->priv[0] = port;
spin_unlock(udp_port_lock);
/* Totally ignore the NIC stuff */
return 0;
}
static int udp_socket(void) {
printf("udp socket...\n");
sock_t * sock = net_sock_create();
sock->sock_recv = sock_udp_recv;
sock->sock_send = sock_udp_send;
sock->sock_close = sock_udp_close;
sock->sock_bind = sock_udp_bind;
return process_append_fd((process_t *)this_core->current_process, (fs_node_t *)sock);
}
static spin_lock_t tcp_port_lock = {0};
static void sock_tcp_close(sock_t * sock) {
if (sock->priv[0]) {
printf("tcp: removing port %d from bound map\n", sock->priv[0]);
spin_lock(tcp_port_lock);
hashmap_remove(tcp_sockets, (void*)(uintptr_t)sock->priv[0]);
spin_unlock(tcp_port_lock);
size_t total_length = sizeof(struct ipv4_packet) + sizeof(struct tcp_header);
fs_node_t * nic = net_if_route(((struct sockaddr_in*)&sock->dest)->sin_addr.s_addr);
if (!nic) return;
struct ipv4_packet * response = malloc(total_length);
response->length = htons(total_length);
response->destination = ((struct sockaddr_in*)&sock->dest)->sin_addr.s_addr;
response->source = ((struct EthernetDevice*)nic->device)->ipv4_addr;
response->ttl = 64;
response->protocol = IPV4_PROT_TCP;
sock->priv[2]++;
response->ident = htons(sock->priv[2]);
response->flags_fragment = htons(0x0);
response->version_ihl = 0x45;
response->dscp_ecn = 0;
response->checksum = 0;
response->checksum = htons(calculate_ipv4_checksum(response));
/* Stick TCP header into payload */
struct tcp_header * tcp_header = (struct tcp_header*)&response->payload;
tcp_header->source_port = htons(sock->priv[0]);
tcp_header->destination_port = ((struct sockaddr_in*)&sock->dest)->sin_port;
tcp_header->seq_number = htonl(sock->priv32[0]);
tcp_header->ack_number = htonl(sock->priv32[1]);
tcp_header->flags = htons(TCP_FLAGS_FIN | TCP_FLAGS_ACK | 0x5000);
tcp_header->window_size = htons(DEFAULT_TCP_WINDOW_SIZE);
tcp_header->checksum = 0;
tcp_header->urgent = 0;
/* Calculate checksum */
struct tcp_check_header check_hd = {
.source = response->source,
.destination = response->destination,
.zeros = 0,
.protocol = IPV4_PROT_TCP,
.tcp_len = htons(sizeof(struct tcp_header)),
};
tcp_header->checksum = htons(calculate_tcp_checksum(&check_hd, tcp_header, tcp_header->payload, 0));
net_ipv4_send(response,nic);
free(response);
}
}
static int next_tcp_port = 49152;
static int tcp_get_port(sock_t * sock) {
spin_lock(tcp_port_lock);
int out = next_tcp_port++;
hashmap_set(tcp_sockets, (void*)(uintptr_t)out, sock);
sock->priv[0] = out;
spin_unlock(tcp_port_lock);
return out;
}
static long sock_tcp_recv(sock_t * sock, struct msghdr * msg, int flags) {
if (!sock->priv[0]) {
printf("tcp: recv() but socket has no port\n");
return -EINVAL;
}
if (msg->msg_iovlen > 1) {
printf("net: todo: can't recv multiple iovs\n");
return -ENOTSUP;
}
if (msg->msg_iovlen == 0) return 0;
if (sock->unread) {
if (sock->unread > msg->msg_iov[0].iov_len) {
unsigned long out = msg->msg_iov[0].iov_len;
sock->unread -= out;
memcpy(msg->msg_iov[0].iov_base, sock->buf, out);
char * x = malloc(sock->unread);
memcpy(x, sock->buf + out, sock->unread);
free(sock->buf);
sock->buf = x;
return out;
} else {
unsigned long out = sock->unread;
sock->unread = 0;
memcpy(msg->msg_iov[0].iov_base, sock->buf, out);
free(sock->buf);
sock->buf = NULL;
return out;
}
}
if (!sock->rx_queue->length && sock->priv[1] == 3) {
return 0; /* EOF */
}
if (!sock->rx_queue->length && sock->nonblocking) return -EAGAIN;
while (!sock->rx_queue->length) {
int r = process_wait_nodes((process_t *)this_core->current_process, (fs_node_t*[]){(fs_node_t*)sock,NULL}, 200);
if (r == -EINTR) return -ERESTARTSYS;
if (!sock->rx_queue->length) {
if (sock->priv[1] == 3) {
/* Socket was closed while waiting */
return 0;
}
}
}
char * packet = net_sock_get(sock);
if (!packet) return -EINTR;
struct ipv4_packet * data = (struct ipv4_packet*)(packet + sizeof(size_t));
size_t packet_size = *(size_t*)packet;
unsigned long resp = ntohs(data->length);
if (resp != packet_size) {
dprintf("packet size does not match: %zu %zu\n", resp, packet_size);
resp = packet_size;
}
if (resp < sizeof(struct ipv4_packet) + sizeof(struct tcp_header)) {
dprintf("Invalid receive data?\n");
assert(0);
}
resp -= sizeof(struct ipv4_packet) + sizeof(struct tcp_header);
if (resp > (unsigned long)msg->msg_iov[0].iov_len) {
memcpy(msg->msg_iov[0].iov_base, data->payload + sizeof(struct tcp_header),msg->msg_iov[0].iov_len);
resp -= msg->msg_iov[0].iov_len;
if (resp == 0xFFFFffffFFFFffff) printf("what\n");
sock->unread = resp;
sock->buf = malloc(resp);
memcpy(sock->buf, data->payload + sizeof(struct tcp_header) + msg->msg_iov[0].iov_len, resp);
free(packet);
return msg->msg_iov[0].iov_len;
}
memcpy(msg->msg_iov[0].iov_base, data->payload + sizeof(struct tcp_header), resp);
free(packet);
return resp;
}
extern uint32_t rand(void);
static long sock_tcp_connect(sock_t * sock, const struct sockaddr *addr, socklen_t addrlen) {
const struct sockaddr_in * dest = (const struct sockaddr_in *)addr;
char deststr[16];
ip_ntoa(ntohl(dest->sin_addr.s_addr), deststr);
printf("tcp: connect requested to %s port %d\n", deststr, ntohs(dest->sin_port));
if (sock->priv[1] != 0) {
printf("tcp: socket is already connected?\n");
return -EINVAL;
}
/* Get a port */
tcp_get_port(sock);
printf("tcp: connecting from ephemeral port %d\n", (int)sock->priv[0]);
/* Mark as awaiting connection, send initial SYN */
sock->priv[1] = 1;
memcpy(&sock->dest, addr, addrlen);
fs_node_t * nic = net_if_route(dest->sin_addr.s_addr);
if (!nic) return -ENONET;
size_t total_length = sizeof(struct ipv4_packet) + sizeof(struct tcp_header);
struct ipv4_packet * response = malloc(total_length);
response->length = htons(total_length);
response->destination = dest->sin_addr.s_addr;
response->source = ((struct EthernetDevice*)nic->device)->ipv4_addr;
response->ttl = 64;
response->protocol = IPV4_PROT_TCP;
sock->priv[2] = rand();
response->ident = htons(sock->priv[2]);
response->flags_fragment = htons(0x0);
response->version_ihl = 0x45;
response->dscp_ecn = 0;
response->checksum = 0;
response->checksum = htons(calculate_ipv4_checksum(response));
/* Stick TCP header into payload */
struct tcp_header * tcp_header = (struct tcp_header*)&response->payload;
tcp_header->source_port = htons(sock->priv[0]);
tcp_header->destination_port = dest->sin_port;
tcp_header->seq_number = 0;
tcp_header->ack_number = 0;
tcp_header->flags = htons((1 << 1) | 0x5000);
tcp_header->window_size = htons(DEFAULT_TCP_WINDOW_SIZE);
tcp_header->checksum = 0;
tcp_header->urgent = 0;
/* Calculate checksum */
struct tcp_check_header check_hd = {
.source = response->source,
.destination = response->destination,
.zeros = 0,
.protocol = IPV4_PROT_TCP,
.tcp_len = htons(sizeof(struct tcp_header)),
};
tcp_header->checksum = htons(calculate_tcp_checksum(&check_hd, tcp_header, NULL, 0));
net_ipv4_send(response,nic);
//int _debug __attribute__((unused)) = 1;
printf("tcp: waiting for connect to finish; queue = %ld\n", sock->rx_queue->length);
unsigned long s, ss;
unsigned long ns, nss;
relative_time(1,0,&s,&ss);
int attempts = 0;
while (!sock->rx_queue->length) {
int result = process_wait_nodes((process_t *)this_core->current_process, (fs_node_t*[]){(fs_node_t*)sock,NULL}, 200);
relative_time(0,0,&ns,&nss);
if (sock->priv[1] == 0) {
free(response);
return -ECONNREFUSED;
}
if (result != 0 && (ns > s || (ns == s && nss > ss))) {
if (attempts++ == 3) {
printf("tcp: connect timed out\n");
free(response);
return -ETIMEDOUT;
}
printf("tcp: retrying...\n");
net_ipv4_send(response,nic);
relative_time(1,0,&s,&ss);
}
}
free(response);
printf("tcp: queue should have data now (len = %lu), trying to read\n", sock->rx_queue->length);
/* wait for signal that we connected or timed out */
char * packet = net_sock_get(sock);
if (!packet) return -EINTR;
//struct ipv4_packet * data = packet + sizeof(size_t);
printf("tcp: connect complete\n");
free(packet);
return 0;
}
ssize_t sock_tcp_read(fs_node_t *node, off_t offset, size_t size, uint8_t *buffer) {
printf("tcp: read into buffer of %zu bytes\n", size);
struct iovec _iovec = {
buffer, size
};
struct msghdr _header = {
.msg_name = NULL,
.msg_namelen = 0,
.msg_iov = &_iovec,
.msg_iovlen = 1,
.msg_control = NULL,
.msg_controllen = 0,
.msg_flags = 0,
};
return sock_tcp_recv((sock_t*)node, &_header, 0);
}
static void delay_yield(size_t subticks) {
unsigned long s, ss;
relative_time(0, subticks, &s, &ss);
sleep_until((process_t *)this_core->current_process, s, ss);
switch_task(0);
}
static long sock_tcp_send(sock_t * sock, const struct msghdr *msg, int flags) {
printf("tcp: send called\n");
if (msg->msg_iovlen > 1) {
printf("net: todo: can't send multiple iovs\n");
return -ENOTSUP;
}
if (msg->msg_iovlen == 0) return 0;
size_t size_into = 0;
size_t size_remaining = msg->msg_iov[0].iov_len;
size_t last = arch_perf_timer();
while (size_remaining) {
size_t size_to_send = size_remaining > 1024 ? 1024 : size_remaining;
size_t total_length = sizeof(struct ipv4_packet) + sizeof(struct tcp_header) + size_to_send;
fs_node_t * nic = net_if_route(((struct sockaddr_in*)&sock->dest)->sin_addr.s_addr);
if (!nic) return -ENONET;
struct ipv4_packet * response = malloc(total_length);
response->length = htons(total_length);
response->destination = ((struct sockaddr_in*)&sock->dest)->sin_addr.s_addr;
response->source = ((struct EthernetDevice*)nic->device)->ipv4_addr;
response->ttl = 64;
response->protocol = IPV4_PROT_TCP;
sock->priv[2]++;
response->ident = htons(sock->priv[2]);
response->flags_fragment = htons(0x0);
response->version_ihl = 0x45;
response->dscp_ecn = 0;
response->checksum = 0;
response->checksum = htons(calculate_ipv4_checksum(response));
/* Stick TCP header into payload */
struct tcp_header * tcp_header = (struct tcp_header*)&response->payload;
tcp_header->source_port = htons(sock->priv[0]);
tcp_header->destination_port = ((struct sockaddr_in*)&sock->dest)->sin_port;
tcp_header->seq_number = htonl(sock->priv32[0]);
tcp_header->ack_number = htonl(sock->priv32[1]);
tcp_header->flags = htons(TCP_FLAGS_PSH | TCP_FLAGS_ACK | 0x5000);
tcp_header->window_size = htons(DEFAULT_TCP_WINDOW_SIZE);
tcp_header->checksum = 0;
tcp_header->urgent = 0;
sock->priv32[0] += size_to_send;
/* Calculate checksum */
struct tcp_check_header check_hd = {
.source = response->source,
.destination = response->destination,
.zeros = 0,
.protocol = IPV4_PROT_TCP,
.tcp_len = htons(sizeof(struct tcp_header) + size_to_send),
};
memcpy(tcp_header->payload, (char*)msg->msg_iov[0].iov_base + size_into, size_to_send);
tcp_header->checksum = htons(calculate_tcp_checksum(&check_hd, tcp_header, tcp_header->payload, size_to_send));
net_ipv4_send(response,nic);
free(response);
size_remaining -= size_to_send;
size_into += size_to_send;
if (size_remaining) {
/* Keep us away from the BSP... */
if (processor_count > 1) {
if (this_core->cpu_id == 0) {
delay_yield(0);
}
} else {
if (arch_perf_timer() - last > 10000UL * arch_cpu_mhz()) {
delay_yield(0);
last = arch_perf_timer();
}
}
}
}
return size_into;
}
ssize_t sock_tcp_write(fs_node_t *node, off_t offset, size_t size, uint8_t *buffer) {
printf("tcp: write of %zu bytes\n", size);
struct iovec _iovec = {
(void*)buffer, size
};
struct msghdr _header = {
.msg_name = NULL,
.msg_namelen = 0,
.msg_iov = &_iovec,
.msg_iovlen = 1,
.msg_control = NULL,
.msg_controllen = 0,
.msg_flags = 0,
};
return sock_tcp_send((sock_t*)node, &_header, 0);
}
long sock_tcp_getsockname(sock_t * sock, struct sockaddr *addr, socklen_t * addrlen) {
in_addr_t ip4_addr = 0;
fs_node_t * nic = net_if_route(((struct sockaddr_in*)&sock->dest)->sin_addr.s_addr);
if (nic) {
ip4_addr = ((struct EthernetDevice*)nic->device)->ipv4_addr;
}
struct sockaddr_in out = {
AF_INET, htons(sock->priv[0]), { ip4_addr }, {0},
};
memcpy(addr, &out, *addrlen < sizeof(struct sockaddr_in) ? *addrlen : sizeof(struct sockaddr_in));
if (*addrlen < sizeof(struct sockaddr_in)) *addrlen = sizeof(struct sockaddr_in);
return 0;
}
long sock_tcp_getpeername(sock_t * sock, struct sockaddr *addr, socklen_t * addrlen) {
in_addr_t ip4_addr = ((struct sockaddr_in*)&sock->dest)->sin_addr.s_addr;
struct sockaddr_in out = {
AF_INET, ((struct sockaddr_in*)&sock->dest)->sin_port, { ip4_addr }, {0},
};
memcpy(addr, &out, *addrlen < sizeof(struct sockaddr_in) ? *addrlen : sizeof(struct sockaddr_in));
if (*addrlen < sizeof(struct sockaddr_in)) *addrlen = sizeof(struct sockaddr_in);
return 0;
}
static int tcp_socket(void) {
printf("tcp socket...\n");
sock_t * sock = net_sock_create();
sock->sock_recv = sock_tcp_recv;
sock->sock_send = sock_tcp_send;
sock->sock_close = sock_tcp_close;
sock->sock_connect = sock_tcp_connect;
sock->sock_getsockname = sock_tcp_getsockname;
sock->sock_getpeername = sock_tcp_getpeername;
sock->_fnode.read = sock_tcp_read;
sock->_fnode.write = sock_tcp_write;
int fd = process_append_fd((process_t *)this_core->current_process, (fs_node_t *)sock);
FD_MODE(fd) = 03;
return fd;
}
long net_ipv4_socket(int type, int protocol) {
/* Ignore protocol, make socket for 'type' only... */
switch (type) {
case SOCK_DGRAM:
if (!protocol || protocol == IPPROTO_UDP)
return udp_socket();
if (protocol == IPPROTO_ICMP)
return icmp_socket();
return -EINVAL;
case SOCK_STREAM:
return tcp_socket();
default:
return -EINVAL;
}
}
|
c17b585d82ad691e32b0ae98d0b922b58fa55e1d
|
76f7459a09acb9be2d52407132f5ff8955627da2
|
/frame/base/bli_func.c
|
7cb7aac6d2d8aca41d390b41fe33ae3a231aebcc
|
[
"BSD-3-Clause"
] |
permissive
|
flame/blis
|
448bc0ad139b726188129c5627c304274b41c3c1
|
6dcf7666eff14348e82fbc2750be4b199321e1b9
|
refs/heads/master
| 2023-09-01T14:56:11.920485
| 2023-08-27T19:18:57
| 2023-08-27T19:18:57
| 16,143,904
| 1,696
| 361
|
NOASSERTION
| 2023-08-27T19:18:58
| 2014-01-22T15:58:24
|
C
|
UTF-8
|
C
| false
| false
| 3,188
|
c
|
bli_func.c
|
/*
BLIS
An object-based framework for developing high-performance BLAS-like
libraries.
Copyright (C) 2014, The University of Texas at Austin
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name(s) of the copyright holder(s) 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 "blis.h"
func_t* bli_func_create
(
void_fp ptr_s,
void_fp ptr_d,
void_fp ptr_c,
void_fp ptr_z
)
{
func_t* f;
err_t r_val;
f = ( func_t* )bli_malloc_intl( sizeof( func_t ), &r_val );
bli_func_init
(
f,
ptr_s,
ptr_d,
ptr_c,
ptr_z
);
return f;
}
void bli_func_init
(
func_t* f,
void_fp ptr_s,
void_fp ptr_d,
void_fp ptr_c,
void_fp ptr_z
)
{
bli_func_set_dt( ptr_s, BLIS_FLOAT, f );
bli_func_set_dt( ptr_d, BLIS_DOUBLE, f );
bli_func_set_dt( ptr_c, BLIS_SCOMPLEX, f );
bli_func_set_dt( ptr_z, BLIS_DCOMPLEX, f );
}
void bli_func_init_null
(
func_t* f
)
{
bli_func_set_dt( NULL, BLIS_FLOAT, f );
bli_func_set_dt( NULL, BLIS_DOUBLE, f );
bli_func_set_dt( NULL, BLIS_SCOMPLEX, f );
bli_func_set_dt( NULL, BLIS_DCOMPLEX, f );
}
void bli_func_free( func_t* f )
{
bli_free_intl( f );
}
// -----------------------------------------------------------------------------
bool bli_func_is_null_dt( num_t dt,
const func_t* f )
{
return ( bli_func_get_dt( dt, f ) == NULL );
}
bool bli_func_is_null( const func_t* f )
{
bool r_val = TRUE;
num_t dt;
// Iterate over all floating-point datatypes. If any is non-null,
// return FALSE. Otherwise, if they are all null, return TRUE.
for ( dt = BLIS_DT_LO; dt <= BLIS_DT_HI; ++dt )
{
if ( bli_func_get_dt( dt, f ) != NULL )
{
r_val = FALSE;
break;
}
}
return r_val;
}
|
76a487d0a023e61994cf673537d2609d39e8631e
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/include/linux/netfilter_bridge/ebt_802_3.h
|
e17e8bfb4e8beba6e72ce72ec161528d5468ae32
|
[
"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
| 290
|
h
|
ebt_802_3.h
|
#ifndef __LINUX_BRIDGE_EBT_802_3_H
#define __LINUX_BRIDGE_EBT_802_3_H
#include <linux/skbuff.h>
#include <uapi/linux/netfilter_bridge/ebt_802_3.h>
static inline struct ebt_802_3_hdr *ebt_802_3_hdr(const struct sk_buff *skb)
{
return (struct ebt_802_3_hdr *)skb_mac_header(skb);
}
#endif
|
f958f9d21ee1125e3738c2c9786bc8eca9eab76f
|
84c498e7a634f1c54c0caaf18ede3f20f8852dc8
|
/NeXAS/pac_pack/pac_pack.c
|
f096656db56694b632cc920abd9ff7ff2cf52728
|
[] |
no_license
|
Yggdrasill-Moe/Niflheim
|
4697e8d5cea5da7e5732f925b190c9d47ef94071
|
51048e7af2ae2c69db772ff59ac26390ab0ea73b
|
refs/heads/master
| 2023-07-19T18:34:26.398212
| 2023-07-17T01:11:04
| 2023-07-17T01:11:04
| 163,126,766
| 103
| 23
| null | null | null | null |
GB18030
|
C
| false
| false
| 6,318
|
c
|
pac_pack.c
|
/*
用于封包NeXAS引擎的pac文件
made by Darkness-TX
2016.12.01
添加新版NeXAS支持
upload by AyamiKaze
2020.03.18
*/
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <io.h>
#include <direct.h>
#include <Windows.h>
#include <zstd.h>
#include <zlib.h>
#include <locale.h>
#include "Huffman_comp.h"
typedef unsigned char unit8;
typedef unsigned short unit16;
typedef unsigned int unit32;
unit32 FileNum = 0;//总文件数,初始计数为0
struct header
{
unit8 magic[4];//PAC\0
unit32 num;
unit32 mode;//BH中是4
}pac_header;
struct index
{
WCHAR name[64];//文件名
unit32 Offset;//文件偏移
unit32 FileSize;//解压大小
unit32 ComSize;//未解压大小
}Index[7000];
/*
void ReadIndex(char *fname)
{
FILE *src, *dst;
unit32 ComSize = 0, UncomSize = 0, i = 0;
unit8 *cdata, *udata, dstname[200];
src = fopen(fname, "rb");
sprintf(dstname, "%s_INDEX", fname);
fread(pac_header.magic, 4, 1, src);
if (strncmp(pac_header.magic, "PAC\0", 4) != 0)
{
printf("文件头不是PAC\0!\n");
fclose(src);
system("pause");
exit(0);
}
else
{
fread(&pac_header.num, 4, 1, src);
fread(&pac_header.mode, 4, 1, src);
printf("%s filenum:%d mode:%d\n\n", fname, pac_header.num, pac_header.mode);
if (pac_header.mode != 4)
{
printf("不是模式4!\n");
system("pause");
exit(0);
}
else
{
fseek(src, -4, SEEK_END);
fread(&ComSize, 4, 1, src);
fseek(src, -4 - ComSize, SEEK_END);
cdata = malloc(ComSize);
fread(cdata, ComSize, 1, src);
for (i = 0; i < ComSize; i++)
cdata[i] = ~cdata[i];
UncomSize = 76 * pac_header.num;
udata = malloc(UncomSize);
huffman_uncompress(udata, &UncomSize, cdata, ComSize);
dst = fopen(dstname, "wb");
fwrite(udata, UncomSize, 1, dst);
free(cdata);
fclose(dst);
fclose(src);
for (i = 0; i < pac_header.num; i++)
memcpy(&Index[i], &udata[i * 76], 76);
free(udata);
}
}
}
void packFileNoIndex(char *fname)
{
FILE *src, *dst;
unit8 *cdata, *udata, dirname[200];
unit32 compsize, i;
WCHAR srcname[200];
sprintf(dirname, "%s_new", fname);
dst = fopen(dirname, "wb");
sprintf(dirname, "%s_unpack", fname);
_chdir(dirname);
fwrite(pac_header.magic, 1, 4, dst);
fwrite(&pac_header.num, 1, 4, dst);
fwrite(&pac_header.mode, 1, 4, dst);
for (i = 0; i < pac_header.num; i++)
{
MultiByteToWideChar(932, 0, Index[i].name, -1, srcname, 64);
src = _wfopen(srcname, L"rb");
Index[i].ComSize = Index[i].FileSize * 4;
cdata = malloc(Index[i].ComSize);
udata = malloc(Index[i].FileSize);
fread(udata, 1, Index[i].FileSize, src);
compress2(cdata, &Index[i].ComSize, udata, Index[i].FileSize, Z_DEFAULT_COMPRESSION);
Index[i].Offset = ftell(dst);
fwrite(cdata, Index[i].ComSize, 1, dst);
fclose(src);
free(cdata);
free(udata);
FileNum += 1;
wprintf(L"%ls offset:0x%X filesize:0x%X comsize:0x%X\n", srcname, Index[i].Offset, Index[i].FileSize, Index[i].ComSize);
}
udata = malloc(pac_header.num * 76);
compsize = pac_header.num * 76 * 4;
cdata = malloc(compsize);
for (i = 0; i < pac_header.num; i++)
memcpy(&udata[i * 76], &Index[i], 76);
//huffman_compress(cdata, &compsize, udata, compsize / 4);
//fwrite(cdata, 1, compsize, dst);
//fwrite(&compsize, 1, 4, dst);
//free(udata);
//free(cdata);
//fclose(dst);
//printf("IndexSize:0x%X\n", compsize);
}
*/
unit32 process_dir(char *dname)
{
long Handle;
unit32 i = 0;
struct _wfinddata64i32_t FileInfo;
_chdir(dname);//跳转路径
if ((Handle = _wfindfirst(L"*.*", &FileInfo)) == -1L)
{
printf("没有找到匹配的项目\n");
system("pause");
return -1;
}
do
{
if (FileInfo.name[0] == '.') //过滤本级目录和父目录
continue;
swprintf(Index[FileNum].name, 260, FileInfo.name);
Index[FileNum].FileSize = FileInfo.size;
Index[FileNum].ComSize = Index[FileNum].FileSize * 4;
FileNum++;
} while (_wfindnext(Handle, &FileInfo) == 0);
return FileNum;
}
void PackFile(char *fname)
{
FILE *src, *dst;
unit32 i, compsize;
unit8 *udata, *cdata, dstname[200];
wchar_t bname[5];
sprintf(pac_header.magic, "PAC\0");
pac_header.num = FileNum;
pac_header.mode = 4;
pac_header.mode &= 0xFF;
sprintf(dstname, "%s.pac", fname);
_chdir("..");
dst = fopen(dstname, "wb");
fwrite(&pac_header, 1, sizeof(pac_header), dst);
_chdir(fname);
for (i = 0; i < pac_header.num; i++)
{
src = _wfopen(Index[i].name, L"rb");
wcscpy(bname, wcschr(Index[i].name, L'.') + 1);
udata = malloc(Index[i].FileSize);
cdata = malloc(Index[i].ComSize);
Index[i].Offset = ftell(dst);
fread(udata, 1, Index[i].FileSize, src);
//mode >= 4时,已知fnt、png文件不进行压缩,如果压缩了会无法读取
if (wcscmp(bname, L"fnt") == 0 || wcscmp(bname, L"png") == 0)
{
fwrite(udata, 1, Index[i].FileSize, dst);
Index[i].ComSize = Index[i].FileSize;
}
else
{
compress2(cdata, &Index[i].ComSize, udata, Index[i].FileSize, Z_DEFAULT_COMPRESSION);
fwrite(cdata, 1, Index[i].ComSize, dst);
}
free(cdata);
free(udata);
fclose(src);
wprintf(L"%ls offset:0x%X filesize:0x%X comsize:0x%X\n", Index[i].name, Index[i].Offset, Index[i].FileSize, Index[i].ComSize);
}
udata = malloc(76 * pac_header.num);
compsize = 76 * pac_header.num * 4;
cdata = malloc(compsize);
memset(udata, 0, 76 * pac_header.num);
for (i = 0; i < pac_header.num; i++)
{
WideCharToMultiByte(932, 0, Index[i].name, 64, dstname, 64, NULL, FALSE);
memcpy(&udata[i * 76], dstname, 64);
memcpy(&udata[i * 76 + 64], &Index[i].Offset, 4);
memcpy(&udata[i * 76 + 68], &Index[i].FileSize, 4);
memcpy(&udata[i * 76 + 72], &Index[i].ComSize, 4);
}
huffman_compress(cdata, &compsize, udata, 76 * pac_header.num);
for (i = 0; i < compsize; i++)
cdata[i] = ~cdata[i];
fwrite(cdata, 1, compsize, dst);
fwrite(&compsize, 1, 4, dst);
free(cdata);
free(udata);
fclose(dst);
}
int main(int argc, char *argv[])
{
setlocale(LC_ALL, "chs");
printf("project:Niflheim-NeXAS\n用于封包BH的pac文件。\n将文件夹拖到程序上。\nby Darkness-TX 2016.12.02\n\n添加新版NeXAS封包支持\nby AyamiKaze 2020.03.18\n\n");
//ReadIndex(argv[1]);
//packFileNoIndex(argv[1]);
process_dir(argv[1]);
PackFile(argv[1]);
printf("已完成,总文件数%d\n", FileNum);
system("pause");
return 0;
}
|
1b76ab1be5abe4ae28dd32283aa0f45cc31a4cb7
|
ff477a586b946c575441b6189123ab86c175e5ae
|
/bcftools/vcfgtcheck.c
|
f646e1f6d17e98ac5913159532956ab514aff1e7
|
[
"MIT",
"LicenseRef-scancode-proprietary-license",
"GPL-3.0-only",
"GPL-1.0-or-later",
"BSD-1-Clause"
] |
permissive
|
pysam-developers/pysam
|
5552e4903106fc253869a405f4a2c068c6bd65c5
|
0663ca85739877e5dd05c0eb2512a8bcaa515b39
|
refs/heads/master
| 2023-08-16T19:10:17.566296
| 2023-08-15T10:06:59
| 2023-08-15T12:28:29
| 16,557,526
| 678
| 332
|
MIT
| 2023-09-14T10:40:22
| 2014-02-05T20:38:10
|
C
|
UTF-8
|
C
| false
| false
| 53,516
|
c
|
vcfgtcheck.c
|
/* vcfgtcheck.c -- Check sample identity.
Copyright (C) 2013-2021 Genome Research Ltd.
Author: Petr Danecek <pd3@sanger.ac.uk>
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 <stdio.h>
#include <stdarg.h>
#include <unistd.h>
#include <getopt.h>
#include <assert.h>
#include <ctype.h>
#include <string.h>
#include <strings.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <math.h>
#include <htslib/vcf.h>
#include <htslib/synced_bcf_reader.h>
#include <htslib/vcfutils.h>
#include <htslib/kbitset.h>
#include <htslib/hts_os.h>
#include <inttypes.h>
#include <sys/time.h>
#include "bcftools.h"
#include "extsort.h"
//#include "hclust.h"
typedef struct
{
int iqry, igt;
}
pair_t;
typedef struct
{
bcf_srs_t *files; // first reader is the query VCF - single sample normally or multi-sample for cross-check
bcf_hdr_t *gt_hdr, *qry_hdr; // VCF with genotypes to compare against and the query VCF
char *cwd, **argv, *gt_samples, *qry_samples, *regions, *targets, *qry_fname, *gt_fname, *pair_samples;
int argc, gt_samples_is_file, qry_samples_is_file, regions_is_file, targets_is_file, pair_samples_is_file;
int regions_overlap, targets_overlap;
int qry_use_GT,gt_use_GT, nqry_smpl,ngt_smpl, *qry_smpl,*gt_smpl;
double *pdiff, *qry_prob, *gt_prob;
uint32_t *ndiff,*ncnt,ncmp, npairs;
int32_t *qry_arr,*gt_arr, nqry_arr,ngt_arr;
uint8_t *qry_dsg, *gt_dsg;
pair_t *pairs;
double *hwe_prob, dsg2prob[8][3], pl2prob[256];
double min_inter_err, max_intra_err;
int all_sites, hom_only, ntop, cross_check, calc_hwe_prob, sort_by_hwe, dry_run, use_PLs;
FILE *fp;
unsigned int nskip_no_match, nskip_not_ba, nskip_mono, nskip_no_data, nskip_dip_GT, nskip_dip_PL;
// for --distinctive-sites
double distinctive_sites;
kbitset_t *kbs_diff;
size_t diff_sites_size;
extsort_t *es;
char *es_tmp_prefix, *es_max_mem;
}
args_t;
static void set_cwd(args_t *args)
{
int i;
char *buf;
size_t nbuf = 500;
args->cwd = (char*) malloc(sizeof(char)*nbuf);
for (i=0; i<5; i++)
{
if ( (buf = getcwd(args->cwd, nbuf)) ) break;
nbuf *= 2;
args->cwd = (char*) realloc(args->cwd, sizeof(char)*nbuf);
}
assert(buf);
}
static void print_header(args_t *args, FILE *fp)
{
fprintf(fp, "# This file was produced by bcftools (%s+htslib-%s), the command line was:\n", bcftools_version(), hts_version());
fprintf(fp, "# \t bcftools %s ", args->argv[0]);
int i;
for (i=1; i<args->argc; i++)
fprintf(fp, " %s",args->argv[i]);
fprintf(fp, "\n# and the working directory was:\n");
fprintf(fp, "# \t %s\n#\n", args->cwd);
}
static int cmp_int(const void *_a, const void *_b)
{
int a = *((int*)_a);
int b = *((int*)_b);
if ( a < b ) return -1;
if ( a > b ) return 1;
return 0;
}
static int cmp_pair(const void *_a, const void *_b)
{
pair_t *a = (pair_t*)_a;
pair_t *b = (pair_t*)_b;
if ( a->iqry < b->iqry ) return -1;
if ( a->iqry > b->iqry ) return 1;
if ( a->igt < b->igt ) return -1;
if ( a->igt > b->igt ) return 1;
return 0;
}
typedef struct
{
uint32_t ndiff,rid,pos,rand; // rand is to shuffle sites with the same ndiff from across all chromosoms
unsigned long kbs_dat[1];
}
diff_sites_t;
#if DBG
static void diff_sites_debug_print(args_t *args, diff_sites_t *ds)
{
int i;
memcpy(args->kbs_diff->b,ds->kbs_dat,args->kbs_diff->n*sizeof(unsigned long));
fprintf(stderr,"%s:%d\t%d\t",bcf_hdr_id2name(args->qry_hdr,ds->rid),ds->pos+1,ds->ndiff);
for (i=0; i<args->npairs; i++) fprintf(stderr,"%d",kbs_exists(args->kbs_diff,i)?1:0);
fprintf(stderr,"\n");
}
#endif
static int diff_sites_cmp(const void *aptr, const void *bptr)
{
diff_sites_t *a = *((diff_sites_t**)aptr);
diff_sites_t *b = *((diff_sites_t**)bptr);
if ( a->ndiff < b->ndiff ) return 1; // descending order
if ( a->ndiff > b->ndiff ) return -1;
if ( a->rand < b->rand ) return -1;
if ( a->rand > b->rand ) return 1;
return 0;
}
static void diff_sites_init(args_t *args)
{
int nsites = args->distinctive_sites<=1 ? args->npairs*args->distinctive_sites : args->distinctive_sites;
if ( nsites<=0 ) error("The value for --distinctive-sites was set too low: %d\n",nsites);
if ( nsites > args->npairs )
{
fprintf(stderr,"Warning: The value for --distinctive-sites is bigger than is the number of pairs, all discordant sites be printed.\n");
nsites = args->npairs;
args->distinctive_sites = args->npairs + 1;
}
else
args->distinctive_sites = nsites;
args->kbs_diff = kbs_init(args->npairs);
size_t n = (args->npairs + KBS_ELTBITS-1) / KBS_ELTBITS;
assert( n==args->kbs_diff->n );
args->diff_sites_size = sizeof(diff_sites_t) + (n-1)*sizeof(unsigned long);
args->es = extsort_alloc();
extsort_set_opt(args->es,size_t,DAT_SIZE,args->diff_sites_size);
extsort_set_opt(args->es,const char*,TMP_PREFIX,args->es_tmp_prefix);
extsort_set_opt(args->es,const char*,MAX_MEM,args->es_max_mem);
extsort_set_opt(args->es,extsort_cmp_f,FUNC_CMP,diff_sites_cmp);
extsort_init(args->es);
}
static void diff_sites_destroy(args_t *args)
{
kbs_destroy(args->kbs_diff);
extsort_destroy(args->es);
}
static inline void diff_sites_reset(args_t *args)
{
kbs_clear(args->kbs_diff);
}
static inline void diff_sites_push(args_t *args, int ndiff, int rid, int pos)
{
diff_sites_t *dat = (diff_sites_t*) malloc(args->diff_sites_size);
memset(dat,0,sizeof(*dat)); // for debugging: prevent warnings about uninitialized memory coming from struct padding (not needed after rand added)
dat->ndiff = ndiff;
dat->rid = rid;
dat->pos = pos;
dat->rand = hts_lrand48();
memcpy(dat->kbs_dat,args->kbs_diff->b,args->kbs_diff->n*sizeof(unsigned long));
extsort_push(args->es,dat);
}
static inline int diff_sites_shift(args_t *args, int *ndiff, int *rid, int *pos)
{
diff_sites_t *dat = (diff_sites_t*) extsort_shift(args->es);
if ( !dat ) return 0;
*ndiff = dat->ndiff;
*rid = dat->rid;
*pos = dat->pos;
memcpy(args->kbs_diff->b,dat->kbs_dat,args->kbs_diff->n*sizeof(unsigned long));
return 1;
}
static void init_samples(char *list, int list_is_file, int **smpl, int *nsmpl, bcf_hdr_t *hdr, char *vcf_fname)
{
int i;
if ( !strcmp(list,"-") )
{
*nsmpl = bcf_hdr_nsamples(hdr);
*smpl = (int*) malloc(sizeof(**smpl)*(*nsmpl));
for (i=0; i<*nsmpl; i++) (*smpl)[i] = i;
return;
}
char **tmp = hts_readlist(list, list_is_file, nsmpl);
if ( !tmp || !*nsmpl ) error("Failed to parse %s\n", list);
*smpl = (int*) malloc(sizeof(**smpl)*(*nsmpl));
for (i=0; i<*nsmpl; i++)
{
int idx = bcf_hdr_id2int(hdr, BCF_DT_SAMPLE, tmp[i]);
if ( idx<0 ) error("No such sample in %s: [%s]\n",vcf_fname,tmp[i]);
(*smpl)[i] = idx;
free(tmp[i]);
}
free(tmp);
qsort(*smpl,*nsmpl,sizeof(**smpl),cmp_int);
// check for duplicates
for (i=1; i<*nsmpl; i++)
if ( (*smpl)[i-1]==(*smpl)[i] )
error("Error: the sample \"%s\" is listed twice in %s\n", hdr->samples[(*smpl)[i]],list);
}
static void init_data(args_t *args)
{
hts_srand48(0);
args->files = bcf_sr_init();
if ( args->regions )
{
bcf_sr_set_opt(args->files,BCF_SR_REGIONS_OVERLAP,args->regions_overlap);
if ( bcf_sr_set_regions(args->files, args->regions, args->regions_is_file)<0 ) error("Failed to read the regions: %s\n", args->regions);
}
if ( args->targets )
{
bcf_sr_set_opt(args->files,BCF_SR_TARGETS_OVERLAP,args->targets_overlap);
if ( bcf_sr_set_targets(args->files, args->targets, args->targets_is_file, 0)<0 ) error("Failed to read the targets: %s\n", args->targets);
}
if ( args->gt_fname ) bcf_sr_set_opt(args->files, BCF_SR_REQUIRE_IDX);
if ( !bcf_sr_add_reader(args->files,args->qry_fname) ) error("Failed to open %s: %s\n", args->qry_fname,bcf_sr_strerror(args->files->errnum));
if ( args->gt_fname && !bcf_sr_add_reader(args->files, args->gt_fname) )
error("Failed to read from %s: %s\n", !strcmp("-",args->gt_fname)?"standard input":args->gt_fname,bcf_sr_strerror(args->files->errnum));
args->qry_hdr = bcf_sr_get_header(args->files,0);
if ( !bcf_hdr_nsamples(args->qry_hdr) ) error("No samples in %s?\n", args->qry_fname);
if ( args->gt_fname )
{
args->gt_hdr = bcf_sr_get_header(args->files,1);
if ( !bcf_hdr_nsamples(args->gt_hdr) ) error("No samples in %s?\n", args->gt_fname);
}
// Determine whether GT or PL will be used
if ( args->qry_use_GT==-1 ) // not set by -u, qry uses PL by default
{
if ( bcf_hdr_id2int(args->qry_hdr,BCF_DT_ID,"PL")>=0 )
args->qry_use_GT = 0;
else if ( bcf_hdr_id2int(args->qry_hdr,BCF_DT_ID,"GT")>=0 )
args->qry_use_GT = 1;
else
error("[E::%s] Neither PL nor GT tag is present in the header of %s\n", __func__, args->qry_fname);
}
else if ( args->qry_use_GT==1 )
{
if ( bcf_hdr_id2int(args->qry_hdr,BCF_DT_ID,"GT")<0 )
error("[E::%s] The GT tag is not present in the header of %s\n", __func__, args->qry_fname);
}
else if ( bcf_hdr_id2int(args->qry_hdr,BCF_DT_ID,"PL")<0 )
error("[E::%s] The PL tag is not present in the header of %s\n", __func__, args->qry_fname);
if ( args->gt_hdr )
{
if ( args->gt_use_GT==-1 ) // not set by -u, gt uses GT by default
{
if ( bcf_hdr_id2int(args->gt_hdr,BCF_DT_ID,"GT")>=0 )
args->gt_use_GT = 1;
else if ( bcf_hdr_id2int(args->gt_hdr,BCF_DT_ID,"PL")>=0 )
args->gt_use_GT = 0;
else
error("[E::%s] Neither PL nor GT tag is present in the header of %s\n", __func__, args->gt_fname);
}
else if ( args->gt_use_GT==1 )
{
if ( bcf_hdr_id2int(args->gt_hdr,BCF_DT_ID,"GT")<0 )
error("[E::%s] The GT tag is not present in the header of %s\n", __func__, args->gt_fname);
}
else if ( bcf_hdr_id2int(args->gt_hdr,BCF_DT_ID,"PL")<0 )
error("[E::%s] The PL tag is not present in the header of %s\n", __func__, args->gt_fname);
}
else
args->gt_use_GT = args->qry_use_GT;
// Prepare samples
int i,j;
args->nqry_smpl = bcf_hdr_nsamples(args->qry_hdr);
if ( args->qry_samples )
{
init_samples(args->qry_samples, args->qry_samples_is_file, &args->qry_smpl, &args->nqry_smpl, args->qry_hdr, args->qry_fname);
}
if ( args->gt_samples )
{
init_samples(args->gt_samples, args->gt_samples_is_file, &args->gt_smpl, &args->ngt_smpl,
args->gt_hdr ? args->gt_hdr : args->qry_hdr,
args->gt_fname ? args->gt_fname : args->qry_fname);
}
else if ( args->pair_samples )
{
int npairs;
char **tmp = hts_readlist(args->pair_samples, args->pair_samples_is_file, &npairs);
if ( !tmp || !npairs ) error("Failed to parse %s\n", args->pair_samples);
if ( !args->pair_samples_is_file && npairs%2 ) error("Expected even number of comma-delimited samples with -p\n");
args->npairs = args->pair_samples_is_file ? npairs : npairs/2;
args->pairs = (pair_t*) calloc(args->npairs,sizeof(*args->pairs));
if ( !args->pair_samples_is_file )
{
for (i=0; i<args->npairs; i++)
{
args->pairs[i].iqry = bcf_hdr_id2int(args->qry_hdr, BCF_DT_SAMPLE, tmp[2*i]);
args->pairs[i].igt = bcf_hdr_id2int(args->gt_hdr?args->gt_hdr:args->qry_hdr, BCF_DT_SAMPLE, tmp[2*i+1]);
if ( args->pairs[i].iqry < 0 ) error("No such sample in %s: [%s]\n",args->qry_fname,tmp[2*i]);
if ( args->pairs[i].igt < 0 ) error("No such sample in %s: [%s]\n",args->gt_fname?args->gt_fname:args->qry_fname,tmp[2*i+1]);
free(tmp[2*i]);
free(tmp[2*i+1]);
}
}
else
{
for (i=0; i<args->npairs; i++)
{
char *ptr = tmp[i];
while ( *ptr && !isspace(*ptr) ) ptr++;
if ( !*ptr ) error("Could not parse %s: %s\n",args->pair_samples,tmp[i]);
*ptr = 0;
args->pairs[i].iqry = bcf_hdr_id2int(args->qry_hdr, BCF_DT_SAMPLE, tmp[i]);
if ( args->pairs[i].iqry < 0 ) error("No such sample in %s: [%s]\n",args->qry_fname,tmp[i]);
ptr++;
while ( *ptr && isspace(*ptr) ) ptr++;
args->pairs[i].igt = bcf_hdr_id2int(args->gt_hdr?args->gt_hdr:args->qry_hdr, BCF_DT_SAMPLE, ptr);
if ( args->pairs[i].igt < 0 ) error("No such sample in %s: [%s]\n",args->gt_fname?args->gt_fname:args->qry_fname,ptr);
free(tmp[i]);
}
}
free(tmp);
qsort(args->pairs,args->npairs,sizeof(*args->pairs),cmp_pair);
}
else if ( args->gt_hdr )
args->ngt_smpl = bcf_hdr_nsamples(args->gt_hdr);
if ( !args->ngt_smpl )
{
args->ngt_smpl = args->nqry_smpl;
args->gt_smpl = args->qry_smpl;
args->cross_check = 1;
}
// The data arrays
if ( !args->npairs ) args->npairs = args->cross_check ? args->nqry_smpl*(args->nqry_smpl+1)/2 : args->ngt_smpl*args->nqry_smpl;
if ( !args->pair_samples )
{
args->qry_dsg = (uint8_t*) malloc(args->nqry_smpl);
args->gt_dsg = args->cross_check ? args->qry_dsg : (uint8_t*) malloc(args->ngt_smpl);
}
if ( args->use_PLs )
{
args->pdiff = (double*) calloc(args->npairs,sizeof(*args->pdiff)); // log probability of pair samples being the same
args->qry_prob = (double*) malloc(3*args->nqry_smpl*sizeof(*args->qry_prob));
args->gt_prob = args->cross_check ? args->qry_prob : (double*) malloc(3*args->ngt_smpl*sizeof(*args->gt_prob));
// dsg2prob: the first index is bitmask of 8 possible dsg combinations (only 1<<0,1<<2,1<<3 are set, accessing
// anything else indicated an error, this is just to reuse gt_to_dsg()); the second index are the corresponding
// probabilities of 0/0, 0/1, and 1/1 genotypes
for (i=0; i<8; i++)
for (j=0; j<3; j++)
args->dsg2prob[i][j] = HUGE_VAL;
args->dsg2prob[1][0] = -log(1-pow(10,-0.1*args->use_PLs));
args->dsg2prob[1][1] = -log(0.5*pow(10,-0.1*args->use_PLs));
args->dsg2prob[1][2] = -log(0.5*pow(10,-0.1*args->use_PLs));
args->dsg2prob[2][0] = -log(0.5*pow(10,-0.1*args->use_PLs));
args->dsg2prob[2][1] = -log(1-pow(10,-0.1*args->use_PLs));
args->dsg2prob[2][2] = -log(0.5*pow(10,-0.1*args->use_PLs));
args->dsg2prob[4][0] = -log(0.5*pow(10,-0.1*args->use_PLs));
args->dsg2prob[4][1] = -log(0.5*pow(10,-0.1*args->use_PLs));
args->dsg2prob[4][2] = -log(1-pow(10,-0.1*args->use_PLs));
// lookup table to avoid exponentiation
for (i=0; i<256; i++) args->pl2prob[i] = pow(10,-0.1*i);
}
else
args->ndiff = (uint32_t*) calloc(args->npairs,sizeof(*args->ndiff)); // number of differing genotypes for each pair of samples
args->ncnt = (uint32_t*) calloc(args->npairs,sizeof(*args->ncnt)); // number of comparisons performed (non-missing data)
if ( !args->ncnt ) error("Error: failed to allocate %.1f Mb\n", args->npairs*sizeof(*args->ncnt)/1e6);
if ( args->calc_hwe_prob )
{
// prob of the observed sequence of matches given site AFs and HWE
args->hwe_prob = (double*) calloc(args->npairs,sizeof(*args->hwe_prob));
if ( !args->hwe_prob ) error("Error: failed to allocate %.1f Mb. Run with --no-HWE-prob to save some memory.\n", args->npairs*sizeof(*args->hwe_prob)/1e6);
}
if ( args->distinctive_sites ) diff_sites_init(args);
args->fp = stdout;
print_header(args, args->fp);
}
static void destroy_data(args_t *args)
{
if ( args->gt_dsg!=args->qry_dsg ) free(args->gt_dsg);
free(args->qry_dsg);
if ( args->gt_prob!=args->qry_prob ) free(args->gt_prob);
free(args->qry_prob);
free(args->es_max_mem);
fclose(args->fp);
if ( args->distinctive_sites ) diff_sites_destroy(args);
free(args->hwe_prob);
free(args->cwd);
free(args->qry_arr);
if ( args->gt_hdr ) free(args->gt_arr);
free(args->pdiff);
free(args->ndiff);
free(args->ncnt);
free(args->qry_smpl);
if ( args->gt_smpl!=args->qry_smpl ) free(args->gt_smpl);
free(args->pairs);
bcf_sr_destroy(args->files);
}
static inline uint8_t gt_to_dsg(int32_t *ptr)
{
if ( bcf_gt_is_missing(ptr[0]) || bcf_gt_is_missing(ptr[1]) || ptr[1]==bcf_int32_vector_end ) return 0;
uint8_t dsg = (bcf_gt_allele(ptr[0])?1:0) + (bcf_gt_allele(ptr[1])?1:0);
return 1<<dsg;
}
static inline uint8_t pl_to_dsg(int32_t *ptr)
{
if ( ptr[0]==bcf_int32_missing || ptr[1]==bcf_int32_missing || ptr[2]==bcf_int32_missing ) return 0;
if ( ptr[1]==bcf_int32_vector_end || ptr[2]==bcf_int32_vector_end ) return 0;
int min_pl = ptr[0]<ptr[1] ? (ptr[0]<ptr[2]?ptr[0]:ptr[2]) : (ptr[1]<ptr[2]?ptr[1]:ptr[2]);
uint8_t dsg = 0;
if ( ptr[0]==min_pl ) dsg |= 1;
if ( ptr[1]==min_pl ) dsg |= 2;
if ( ptr[2]==min_pl ) dsg |= 4;
return dsg;
}
static inline uint8_t gt_to_prob(args_t *args, int32_t *ptr, double *prob)
{
uint8_t dsg = gt_to_dsg(ptr);
if ( dsg )
{
prob[0] = args->dsg2prob[dsg][0];
prob[1] = args->dsg2prob[dsg][1];
prob[2] = args->dsg2prob[dsg][2];
}
return dsg;
}
static inline uint8_t pl_to_prob(args_t *args, int32_t *ptr, double *prob)
{
uint8_t dsg = pl_to_dsg(ptr);
if ( dsg )
{
prob[0] = (ptr[0]>=0 && ptr[0]<255) ? args->pl2prob[ptr[0]] : args->pl2prob[255];
prob[1] = (ptr[1]>=0 && ptr[1]<255) ? args->pl2prob[ptr[1]] : args->pl2prob[255];
prob[2] = (ptr[2]>=0 && ptr[2]<255) ? args->pl2prob[ptr[2]] : args->pl2prob[255];
double sum = prob[0] + prob[1] + prob[2];
prob[0] /= sum;
prob[1] /= sum;
prob[2] /= sum;
prob[0] = -log(prob[0]);
prob[1] = -log(prob[1]);
prob[2] = -log(prob[2]);
}
return dsg;
}
static int set_data(args_t *args, bcf_hdr_t *hdr, bcf1_t *rec, int32_t **arr, int32_t *narr, int *narr1, int *use_GT)
{
static int warn_dip_GT = 1;
static int warn_dip_PL = 1;
int i;
for (i=0; i<2; i++)
{
if ( *use_GT )
{
int ret = bcf_get_genotypes(hdr,rec,arr,narr);
if ( ret < 0 )
{
if ( !i ) { *use_GT = 0; continue; }
args->nskip_no_data++;
return -1;
}
if ( ret != 2*bcf_hdr_nsamples(hdr) )
{
if ( warn_dip_GT )
{
fprintf(stderr,"INFO: skipping %s:%"PRIhts_pos", only diploid FORMAT/GT fields supported. (This is printed only once.)\n", bcf_seqname(hdr,rec),rec->pos+1);
warn_dip_GT = 0;
}
args->nskip_dip_GT++;
return -1;
}
*narr1 = 2;
return 0;
}
int ret = bcf_get_format_int32(hdr,rec,"PL",arr,narr);
if ( ret < 0 )
{
if ( !i ) { *use_GT = 1; continue; }
args->nskip_no_data++;
return -1;
}
if ( ret != 3*bcf_hdr_nsamples(hdr) )
{
if ( warn_dip_PL )
{
fprintf(stderr,"INFO: skipping %s:%"PRIhts_pos", only diploid FORMAT/PL fields supported. (This is printed only once.)\n", bcf_seqname(hdr,rec),rec->pos+1);
warn_dip_PL = 0;
}
args->nskip_dip_PL++;
return -1;
}
*narr1 = 3;
return 0;
}
return -1; // should never reach
}
static void process_line(args_t *args)
{
int i,j,k, nqry1, ngt1, ret;
bcf1_t *gt_rec = NULL, *qry_rec = bcf_sr_get_line(args->files,0); // the query file
int qry_use_GT = args->qry_use_GT;
int gt_use_GT = args->gt_use_GT;
ret = set_data(args, args->qry_hdr, qry_rec, &args->qry_arr, &args->nqry_arr, &nqry1, &qry_use_GT);
if ( ret<0 ) return;
if ( args->gt_hdr )
{
gt_rec = bcf_sr_get_line(args->files,1);
ret = set_data(args, args->gt_hdr, gt_rec, &args->gt_arr, &args->ngt_arr, &ngt1, >_use_GT);
if ( ret<0 ) return;
}
else
{
ngt1 = nqry1;
args->gt_arr = args->qry_arr;
}
args->ncmp++;
double af,hwe_dsg[8];
if ( args->calc_hwe_prob )
{
int ac[2];
if ( args->gt_hdr )
{
if ( bcf_calc_ac(args->gt_hdr, gt_rec, ac, BCF_UN_INFO|BCF_UN_FMT)!=1 ) error("todo: bcf_calc_ac() failed\n");
}
else if ( bcf_calc_ac(args->qry_hdr, qry_rec, ac, BCF_UN_INFO|BCF_UN_FMT)!=1 ) error("todo: bcf_calc_ac() failed\n");
// hwe indexes correspond to the bitmask of eight dsg combinations to account for PL uncertainty
// for in the extreme case we can have uninformative PL=0,0,0. So the values are the minima of e.g.
// hwe[1,2,4] .. dsg=0,1,2
// hwe[3] .. dsg=0 or 1
// hwe[6] .. dsg=1 or 2
double hwe[3];
const double min_af = 1e-5; // cap the AF in case we get unrealistic values
af = (double)ac[1]/(ac[0]+ac[1]);
hwe[0] = af>min_af ? -log(af*af) : -log(min_af*min_af);
hwe[1] = af>min_af && af<1-min_af ? -log(2*af*(1-af)) : -log(2*min_af*(1-min_af));
hwe[2] = af<(1-min_af) ? -log((1-af)*(1-af)) : -log(min_af*min_af);
hwe_dsg[0] = 0;
for (i=1; i<8; i++)
{
hwe_dsg[i] = HUGE_VAL;
for (k=0; k<3; k++)
{
if ( ((1<<k)&i) && hwe_dsg[i] > hwe[k] ) hwe_dsg[i] = hwe[k];
}
}
}
// The sample pairs were given explicitly via -p/-P options
if ( args->pairs )
{
if ( !args->use_PLs )
{
int ndiff = 0;
if ( args->kbs_diff ) diff_sites_reset(args);
for (i=0; i<args->npairs; i++)
{
int32_t *ptr;
uint8_t qry_dsg, gt_dsg;
ptr = args->gt_arr + args->pairs[i].igt*ngt1;
gt_dsg = gt_use_GT ? gt_to_dsg(ptr) : pl_to_dsg(ptr);
if ( !gt_dsg ) continue; // missing value
if ( args->hom_only && !(gt_dsg&5) ) continue; // not a hom
ptr = args->qry_arr + args->pairs[i].iqry*nqry1;
qry_dsg = qry_use_GT ? gt_to_dsg(ptr) : pl_to_dsg(ptr);
if ( !qry_dsg ) continue; // missing value
int match = qry_dsg & gt_dsg;
if ( !match )
{
args->ndiff[i]++;
if ( args->kbs_diff ) { ndiff++; kbs_insert(args->kbs_diff, i); }
}
else if ( args->calc_hwe_prob ) args->hwe_prob[i] += hwe_dsg[match];
args->ncnt[i]++;
}
if ( ndiff ) diff_sites_push(args, ndiff, qry_rec->rid, qry_rec->pos);
}
else // use_PLs set
{
for (i=0; i<args->npairs; i++)
{
int32_t *ptr;
double qry_prob[3], gt_prob[3];
uint8_t qry_dsg, gt_dsg;
ptr = args->gt_arr + args->pairs[i].igt*ngt1;
gt_dsg = gt_use_GT ? gt_to_prob(args,ptr,gt_prob) : pl_to_prob(args,ptr,gt_prob);
if ( !gt_dsg ) continue; // missing value
if ( args->hom_only && !(gt_dsg&5) ) continue; // not a hom
ptr = args->qry_arr + args->pairs[i].iqry*nqry1;
qry_dsg = qry_use_GT ? gt_to_prob(args,ptr,qry_prob) : pl_to_prob(args,ptr,qry_prob);
if ( !qry_dsg ) continue; // missing value
double min = qry_prob[0] + gt_prob[0];
qry_prob[1] += gt_prob[1];
if ( min > qry_prob[1] ) min = qry_prob[1];
qry_prob[2] += gt_prob[2];
if ( min > qry_prob[2] ) min = qry_prob[2];
args->pdiff[i] += min;
if ( args->calc_hwe_prob )
{
int match = qry_dsg & gt_dsg;
args->hwe_prob[i] += hwe_dsg[match];
}
args->ncnt[i]++;
}
}
return;
}
int idx=0;
if ( !args->use_PLs )
{
for (i=0; i<args->nqry_smpl; i++)
{
int iqry = args->qry_smpl ? args->qry_smpl[i] : i;
int32_t *ptr = args->qry_arr + nqry1*iqry;
args->qry_dsg[i] = qry_use_GT ? gt_to_dsg(ptr) : pl_to_dsg(ptr);
}
if ( !args->cross_check ) // in this case gt_dsg points to qry_dsg
{
for (i=0; i<args->ngt_smpl; i++)
{
int igt = args->gt_smpl ? args->gt_smpl[i] : i;
int32_t *ptr = args->gt_arr + ngt1*igt;
args->gt_dsg[i] = gt_use_GT ? gt_to_dsg(ptr) : pl_to_dsg(ptr);
if ( args->hom_only && !(args->gt_dsg[i]&5) ) args->gt_dsg[i] = 0; // not a hom, set to a missing value
}
}
for (i=0; i<args->nqry_smpl; i++)
{
int ngt = args->cross_check ? i : args->ngt_smpl; // two files or a sub-diagonal cross-check mode?
if ( !args->qry_dsg[i] ) { idx += ngt; continue; } // missing value
for (j=0; j<ngt; j++)
{
if ( !args->gt_dsg[j] ) { idx++; continue; } // missing value
int match = args->qry_dsg[i] & args->gt_dsg[j];
if ( !match ) args->ndiff[idx]++;
else if ( args->calc_hwe_prob ) args->hwe_prob[idx] += hwe_dsg[match];
args->ncnt[idx]++;
idx++;
}
}
}
else // use_PLs set
{
for (i=0; i<args->nqry_smpl; i++)
{
int iqry = args->qry_smpl ? args->qry_smpl[i] : i;
int32_t *ptr = args->qry_arr + nqry1*iqry;
args->qry_dsg[i] = qry_use_GT ? gt_to_prob(args,ptr,args->qry_prob+i*3) : pl_to_prob(args,ptr,args->qry_prob+i*3);
}
if ( !args->cross_check ) // in this case gt_dsg points to qry_dsg
{
for (i=0; i<args->ngt_smpl; i++)
{
int igt = args->gt_smpl ? args->gt_smpl[i] : i;
int32_t *ptr = args->gt_arr + ngt1*igt;
args->gt_dsg[i] = gt_use_GT ? gt_to_prob(args,ptr,args->gt_prob+i*3) : pl_to_prob(args,ptr,args->gt_prob+i*3);
if ( args->hom_only && !(args->gt_dsg[i]&5) ) args->gt_dsg[i] = 0; // not a hom, set to a missing value
}
}
for (i=0; i<args->nqry_smpl; i++)
{
int ngt = args->cross_check ? i : args->ngt_smpl; // two files or a sub-diagonal cross-check mode?
if ( !args->qry_dsg[i] ) { idx += ngt; continue; } // missing value
for (j=0; j<ngt; j++)
{
if ( !args->gt_dsg[j] ) { idx++; continue; } // missing value
double min = args->qry_prob[i*3] + args->gt_prob[j*3];
if ( min > args->qry_prob[i*3+1] + args->gt_prob[j*3+1] ) min = args->qry_prob[i*3+1] + args->gt_prob[j*3+1];
if ( min > args->qry_prob[i*3+2] + args->gt_prob[j*3+2] ) min = args->qry_prob[i*3+2] + args->gt_prob[j*3+2];
args->pdiff[idx] += min;
if ( args->calc_hwe_prob )
{
int match = args->qry_dsg[i] & args->gt_dsg[j];
args->hwe_prob[idx] += hwe_dsg[match];
}
args->ncnt[idx]++;
idx++;
}
}
}
}
typedef struct
{
int ism, idx;
double val;
}
idbl_t;
static int cmp_idbl(const void *_a, const void *_b)
{
idbl_t *a = (idbl_t*)_a;
idbl_t *b = (idbl_t*)_b;
if ( a->val < b->val ) return -1;
if ( a->val > b->val ) return 1;
return 0;
}
static void report_distinctive_sites(args_t *args)
{
extsort_sort(args->es);
fprintf(args->fp,"# DS, distinctive sites:\n");
fprintf(args->fp,"# - chromosome\n");
fprintf(args->fp,"# - position\n");
fprintf(args->fp,"# - cumulative number of pairs distinguished by this block\n");
fprintf(args->fp,"# - block id\n");
fprintf(args->fp,"#DS\t[2]Chromosome\t[3]Position\t[4]Cumulative number of distinct pairs\t[5]Block id\n");
kbitset_t *kbs_blk = kbs_init(args->npairs);
kbitset_iter_t itr;
int i,ndiff,rid,pos,ndiff_tot = 0, iblock = 0;
int ndiff_min = args->distinctive_sites <= args->npairs ? args->distinctive_sites : args->npairs;
while ( diff_sites_shift(args,&ndiff,&rid,&pos) )
{
int ndiff_new = 0, ndiff_dbg = 0;
kbs_start(&itr);
while ( (i=kbs_next(args->kbs_diff, &itr))>=0 )
{
ndiff_dbg++;
if ( kbs_exists(kbs_blk,i) ) continue; // already set
kbs_insert(kbs_blk,i);
ndiff_new++;
}
if ( ndiff_dbg!=ndiff ) error("Corrupted data, fixme: %d vs %d\n",ndiff_dbg,ndiff);
if ( !ndiff_new ) continue; // no new pair distinguished by this site
ndiff_tot += ndiff_new;
fprintf(args->fp,"DS\t%s\t%d\t%d\t%d\n",bcf_hdr_id2name(args->qry_hdr,rid),pos+1,ndiff_tot,iblock);
if ( ndiff_tot < ndiff_min ) continue; // fewer than the requested number of pairs can be distinguished at this point
iblock++;
ndiff_tot = 0;
kbs_clear(kbs_blk);
}
kbs_destroy(kbs_blk);
}
static void report(args_t *args)
{
fprintf(args->fp,"INFO\tsites-compared\t%u\n",args->ncmp);
fprintf(args->fp,"INFO\tsites-skipped-no-match\t%u\n",args->nskip_no_match);
fprintf(args->fp,"INFO\tsites-skipped-multiallelic\t%u\n",args->nskip_not_ba);
fprintf(args->fp,"INFO\tsites-skipped-monoallelic\t%u\n",args->nskip_mono);
fprintf(args->fp,"INFO\tsites-skipped-no-data\t%u\n",args->nskip_no_data);
fprintf(args->fp,"INFO\tsites-skipped-GT-not-diploid\t%u\n",args->nskip_dip_GT);
fprintf(args->fp,"INFO\tsites-skipped-PL-not-diploid\t%u\n",args->nskip_dip_PL);
fprintf(args->fp,"# DC, discordance:\n");
fprintf(args->fp,"# - query sample\n");
fprintf(args->fp,"# - genotyped sample\n");
fprintf(args->fp,"# - discordance (number of mismatches; smaller is better)\n");
fprintf(args->fp,"# - negative log of HWE probability at matching sites (rare genotypes mataches are more informative, bigger is better)\n");
fprintf(args->fp,"# - number of sites compared (bigger is better)\n");
fprintf(args->fp,"#DC\t[2]Query Sample\t[3]Genotyped Sample\t[4]Discordance\t[5]-log P(HWE)\t[6]Number of sites compared\n");
int trim = args->ntop;
if ( !args->pairs )
{
if ( !args->ngt_smpl && args->nqry_smpl <= args->ntop ) trim = 0;
if ( args->ngt_smpl && args->ngt_smpl <= args->ntop ) trim = 0;
}
if ( args->pairs )
{
int i;
for (i=0; i<args->npairs; i++)
{
int iqry = args->pairs[i].iqry;
int igt = args->pairs[i].igt;
if ( args->ndiff )
{
fprintf(args->fp,"DC\t%s\t%s\t%u\t%e\t%u\n",
args->qry_hdr->samples[iqry],
args->gt_hdr?args->gt_hdr->samples[igt]:args->qry_hdr->samples[igt],
args->ndiff[i],
args->calc_hwe_prob ? args->hwe_prob[i] : 0,
args->ncnt[i]);
}
else
{
fprintf(args->fp,"DC\t%s\t%s\t%e\t%e\t%u\n",
args->qry_hdr->samples[iqry],
args->gt_hdr?args->gt_hdr->samples[igt]:args->qry_hdr->samples[igt],
args->pdiff[i],
args->calc_hwe_prob ? args->hwe_prob[i] : 0,
args->ncnt[i]);
}
}
}
else if ( !trim )
{
int i,j,idx=0;
for (i=0; i<args->nqry_smpl; i++)
{
int iqry = args->qry_smpl ? args->qry_smpl[i] : i;
int ngt = args->cross_check ? i : args->ngt_smpl;
for (j=0; j<ngt; j++)
{
int igt = args->gt_smpl ? args->gt_smpl[j] : j;
if ( args->ndiff )
{
fprintf(args->fp,"DC\t%s\t%s\t%u\t%e\t%u\n",
args->qry_hdr->samples[iqry],
args->gt_hdr?args->gt_hdr->samples[igt]:args->qry_hdr->samples[igt],
args->ndiff[idx],
args->calc_hwe_prob ? args->hwe_prob[idx] : 0,
args->ncnt[idx]);
}
else
{
fprintf(args->fp,"DC\t%s\t%s\t%e\t%e\t%u\n",
args->qry_hdr->samples[iqry],
args->gt_hdr?args->gt_hdr->samples[igt]:args->qry_hdr->samples[igt],
args->pdiff[idx],
args->calc_hwe_prob ? args->hwe_prob[idx] : 0,
args->ncnt[idx]);
}
idx++;
}
}
}
else if ( !args->cross_check )
{
idbl_t *arr = (idbl_t*)malloc(sizeof(*arr)*args->ngt_smpl);
int i,j;
for (i=0; i<args->nqry_smpl; i++)
{
int idx = i*args->ngt_smpl;
for (j=0; j<args->ngt_smpl; j++)
{
if ( args->sort_by_hwe )
arr[j].val = -args->hwe_prob[idx];
else if ( args->ndiff )
arr[j].val = args->ncnt[idx] ? (double)args->ndiff[idx]/args->ncnt[idx] : 0;
else
arr[j].val = args->ncnt[idx] ? args->pdiff[idx]/args->ncnt[idx] : 0;
arr[j].ism = j;
arr[j].idx = idx;
idx++;
}
qsort(arr, args->ngt_smpl, sizeof(*arr), cmp_idbl);
int iqry = args->qry_smpl ? args->qry_smpl[i] : i;
for (j=0; j<args->ntop; j++)
{
int idx = arr[j].idx;
int igt = args->gt_smpl ? args->gt_smpl[arr[j].ism] : arr[j].ism;
if ( args->ndiff )
{
fprintf(args->fp,"DC\t%s\t%s\t%u\t%e\t%u\n",
args->qry_hdr->samples[iqry],
args->gt_hdr?args->gt_hdr->samples[igt]:args->qry_hdr->samples[igt],
args->ndiff[idx],
args->calc_hwe_prob ? args->hwe_prob[idx] : 0,
args->ncnt[idx]);
}
else
{
fprintf(args->fp,"DC\t%s\t%s\t%e\t%e\t%u\n",
args->qry_hdr->samples[iqry],
args->gt_hdr?args->gt_hdr->samples[igt]:args->qry_hdr->samples[igt],
args->pdiff[idx],
args->calc_hwe_prob ? args->hwe_prob[idx] : 0,
args->ncnt[idx]);
}
}
}
free(arr);
}
else
{
int narr = args->nqry_smpl-1;
idbl_t *arr = (idbl_t*)malloc(sizeof(*arr)*narr);
int i,j,k,idx;
for (i=0; i<args->nqry_smpl; i++)
{
k = 0, idx = i*(i-1)/2;
for (j=0; j<i; j++)
{
if ( args->sort_by_hwe )
arr[k].val = -args->hwe_prob[idx];
else if ( args->ndiff )
arr[k].val = args->ncnt[idx] ? (double)args->ndiff[idx]/args->ncnt[idx] : 0;
else
arr[k].val = args->ncnt[idx] ? args->pdiff[idx]/args->ncnt[idx] : 0;
arr[k].ism = j;
arr[k].idx = idx;
idx++;
k++;
}
for (; j<narr; j++)
{
idx = j*(j+1)/2 + i;
if ( args->sort_by_hwe )
arr[k].val = -args->hwe_prob[idx];
else if ( args->ndiff )
arr[k].val = args->ncnt[idx] ? (double)args->ndiff[idx]/args->ncnt[idx] : 0;
else
arr[k].val = args->ncnt[idx] ? args->pdiff[idx]/args->ncnt[idx] : 0;
arr[k].ism = j + 1;
arr[k].idx = idx;
k++;
}
qsort(arr, narr, sizeof(*arr), cmp_idbl);
int iqry = args->qry_smpl ? args->qry_smpl[i] : i;
for (j=0; j<args->ntop; j++)
{
if ( i <= arr[j].ism ) continue;
int idx = arr[j].idx;
int igt = args->qry_smpl ? args->qry_smpl[arr[j].ism] : arr[j].ism;
if ( args->ndiff )
{
fprintf(args->fp,"DC\t%s\t%s\t%u\t%e\t%u\n",
args->qry_hdr->samples[iqry],
args->qry_hdr->samples[igt],
args->ndiff[idx],
args->calc_hwe_prob ? args->hwe_prob[idx] : 0,
args->ncnt[idx]);
}
else
{
fprintf(args->fp,"DC\t%s\t%s\t%e\t%e\t%u\n",
args->qry_hdr->samples[iqry],
args->qry_hdr->samples[igt],
args->pdiff[idx],
args->calc_hwe_prob ? args->hwe_prob[idx] : 0,
args->ncnt[idx]);
}
}
}
free(arr);
}
}
static int is_input_okay(args_t *args, int nmatch)
{
int i;
const char *msg;
bcf_hdr_t *hdr;
bcf1_t *rec;
if ( args->gt_hdr && nmatch!=2 )
{
if ( args->nskip_no_match++ ) return 0;
for (i=0; i<2; i++)
{
rec = bcf_sr_get_line(args->files,i);
if ( rec ) break;
}
hdr = bcf_sr_get_header(args->files,i);
fprintf(stderr,"INFO: skipping %s:%"PRIhts_pos", no record with matching POS+ALT. (This is printed only once.)\n",
bcf_seqname(hdr,rec),rec->pos+1);
return 0;
}
for (i=0; i<2; i++)
{
hdr = bcf_sr_get_header(args->files,i);
rec = bcf_sr_get_line(args->files,i);
if ( rec->n_allele>2 )
{
if ( args->nskip_not_ba++ ) return 0;
msg = "not a biallelic site, run `bcftools norm -m -` first";
goto not_okay;
}
if ( bcf_get_variant_types(rec)==VCF_REF )
{
if ( args->nskip_mono++ ) return 0;
msg = "monoallelic site";
goto not_okay;
}
if ( !args->gt_hdr ) break;
}
return 1;
not_okay:
fprintf(stderr,"INFO: skipping %s:%"PRIhts_pos", %s. (This is printed only once.)\n",
bcf_seqname(hdr,rec),rec->pos+1,msg);
return 0;
}
static void usage(void)
{
fprintf(stderr, "\n");
fprintf(stderr, "About: Check sample identity. With no -g BCF given, multi-sample cross-check is performed.\n");
fprintf(stderr, "Usage: bcftools gtcheck [options] [-g <genotypes.vcf.gz>] <query.vcf.gz>\n");
fprintf(stderr, "\n");
fprintf(stderr, "Options:\n");
//fprintf(stderr, " -a, --all-sites Output comparison for all sites\n");
//fprintf(stderr, " -c, --cluster MIN,MAX Min inter- and max intra-sample error [0.23,-0.3]\n");
fprintf(stderr, " --distinctive-sites Find sites that can distinguish between at least NUM sample pairs.\n");
fprintf(stderr, " NUM[,MEM[,TMP]] If the number is smaller or equal to 1, it is interpreted as the fraction of pairs.\n");
fprintf(stderr, " The optional MEM string sets the maximum memory used for in-memory sorting [500M]\n");
#ifdef _WIN32
fprintf(stderr, " and TMP is a prefix of temporary files used by external sorting [/bcftools.XXXXXX]\n");
#else
fprintf(stderr, " and TMP is a prefix of temporary files used by external sorting [/tmp/bcftools.XXXXXX]\n");
#endif
fprintf(stderr, " --dry-run Stop after first record to estimate required time\n");
fprintf(stderr, " -e, --error-probability INT Phred-scaled probability of genotyping error, 0 for faster but less accurate results [40]\n");
fprintf(stderr, " -g, --genotypes FILE Genotypes to compare against\n");
fprintf(stderr, " -H, --homs-only Homozygous genotypes only, useful with low coverage data (requires -g)\n");
fprintf(stderr, " --n-matches INT Print only top INT matches for each sample (sorted by average score), 0 for unlimited.\n");
fprintf(stderr, " Use negative value to sort by HWE probability rather than by discordance [0]\n");
fprintf(stderr, " --no-HWE-prob Disable calculation of HWE probability\n");
fprintf(stderr, " -p, --pairs LIST Comma-separated sample pairs to compare (qry,gt[,qry,gt..] with -g or qry,qry[,qry,qry..] w/o)\n");
fprintf(stderr, " -P, --pairs-file FILE File with tab-delimited sample pairs to compare (qry,gt with -g or qry,qry w/o)\n");
fprintf(stderr, " -r, --regions REGION Restrict to comma-separated list of regions\n");
fprintf(stderr, " -R, --regions-file FILE Restrict to regions listed in a file\n");
fprintf(stderr, " --regions-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [1]\n");
fprintf(stderr, " -s, --samples [qry|gt]:LIST List of query or -g samples, \"-\" to select all samples (by default all samples are compared)\n");
fprintf(stderr, " -S, --samples-file [qry|gt]:FILE File with the query or -g samples to compare\n");
fprintf(stderr, " -t, --targets REGION Similar to -r but streams rather than index-jumps\n");
fprintf(stderr, " -T, --targets-file FILE Similar to -R but streams rather than index-jumps\n");
fprintf(stderr, " --targets-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [0]\n");
fprintf(stderr, " -u, --use TAG1[,TAG2] Which tag to use in the query file (TAG1) and the -g file (TAG2) [PL,GT]\n");
fprintf(stderr, "Examples:\n");
fprintf(stderr, " # Check discordance of all samples from B against all sample in A\n");
fprintf(stderr, " bcftools gtcheck -g A.bcf B.bcf\n");
fprintf(stderr, "\n");
fprintf(stderr, " # Limit comparisons to the fiven list of samples\n");
fprintf(stderr, " bcftools gtcheck -s gt:a1,a2,a3 -s qry:b1,b2 -g A.bcf B.bcf\n");
fprintf(stderr, "\n");
fprintf(stderr, " # Compare only two pairs a1,b1 and a1,b2\n");
fprintf(stderr, " bcftools gtcheck -p a1,b1,a1,b2 -g A.bcf B.bcf\n");
fprintf(stderr, "\n");
exit(1);
}
int main_vcfgtcheck(int argc, char *argv[])
{
int c;
args_t *args = (args_t*) calloc(1,sizeof(args_t));
args->argc = argc; args->argv = argv; set_cwd(args);
args->qry_use_GT = -1;
args->gt_use_GT = -1;
args->calc_hwe_prob = 1;
args->use_PLs = 40;
args->regions_overlap = 1;
args->targets_overlap = 0;
// external sort for --distinctive-sites
#ifdef _WIN32
args->es_tmp_prefix = NULL;
#else
args->es_tmp_prefix = "/tmp/bcftools-gtcheck";
#endif
args->es_max_mem = strdup("500M");
// In simulated sample swaps the minimum error was 0.3 and maximum intra-sample error was 0.23
// - min_inter: pairs with smaller err value will be considered identical
// - max_intra: pairs with err value bigger than abs(max_intra_err) will be considered
// different. If negative, the cutoff may be heuristically lowered
args->min_inter_err = 0.23;
args->max_intra_err = -0.3;
static struct option loptions[] =
{
{"error-probability",1,0,'e'},
{"use",1,0,'u'},
{"cluster",1,0,'c'},
{"GTs-only",1,0,'G'},
{"all-sites",0,0,'a'},
{"homs-only",0,0,'H'},
{"help",0,0,'h'},
{"genotypes",1,0,'g'},
{"plot",1,0,'p'},
{"samples",1,0,'s'},
{"samples-file",1,0,'S'},
{"n-matches",1,0,2},
{"no-HWE-prob",0,0,3},
{"target-sample",1,0,4},
{"dry-run",0,0,5},
{"distinctive-sites",1,0,6},
{"regions",1,0,'r'},
{"regions-file",1,0,'R'},
{"regions-overlap",required_argument,NULL,7},
{"targets",1,0,'t'},
{"targets-file",1,0,'T'},
{"targets-overlap",required_argument,NULL,8},
{"pairs",1,0,'p'},
{"pairs-file",1,0,'P'},
{0,0,0,0}
};
char *tmp;
while ((c = getopt_long(argc, argv, "hg:p:s:S:p:P:Hr:R:at:T:G:c:u:e:",loptions,NULL)) >= 0) {
switch (c) {
case 'e':
args->use_PLs = strtol(optarg,&tmp,10);
if ( !tmp || *tmp ) error("Could not parse: --error-probability %s\n", optarg);
break;
case 'u':
{
int i,nlist;
char **list = hts_readlist(optarg, 0, &nlist);
if ( !list || nlist<=0 || nlist>2 ) error("Failed to parse --use %s\n", optarg);
if ( !strcasecmp("GT",list[0]) ) args->qry_use_GT = 1;
else if ( !strcasecmp("PL",list[0]) ) args->qry_use_GT = 0;
else error("Failed to parse --use %s; only GT and PL are supported\n", optarg);
if ( nlist==2 )
{
if ( !strcasecmp("GT",list[1]) ) args->gt_use_GT = 1;
else if ( !strcasecmp("PL",list[1]) ) args->gt_use_GT = 0;
else error("Failed to parse --use %s; only GT and PL are supported\n", optarg);
}
else args->gt_use_GT = args->qry_use_GT;
for (i=0; i<nlist; i++) free(list[i]);
free(list);
}
break;
case 2 :
args->ntop = strtol(optarg,&tmp,10);
if ( !tmp || *tmp ) error("Could not parse: --n-matches %s\n", optarg);
if ( args->ntop < 0 )
{
args->sort_by_hwe = 1;
args->ntop *= -1;
}
break;
case 3 : args->calc_hwe_prob = 0; break;
case 4 : error("The option -S, --target-sample has been deprecated\n"); break;
case 5 : args->dry_run = 1; break;
case 6 :
args->distinctive_sites = strtod(optarg,&tmp);
if ( *tmp )
{
if ( *tmp!=',' ) error("Could not parse: --distinctive-sites %s\n", optarg);
tmp++;
free(args->es_max_mem);
args->es_max_mem = strdup(tmp);
while ( *tmp && *tmp!=',' ) tmp++;
if ( *tmp ) { *tmp = 0; args->es_tmp_prefix = tmp+1; }
}
args->use_PLs = 0;
break;
case 'c':
error("The -c option is to be implemented, please open an issue on github\n");
args->min_inter_err = strtod(optarg,&tmp);
if ( *tmp )
{
if ( *tmp!=',') error("Could not parse: -c %s\n", optarg);
args->max_intra_err = strtod(tmp+1,&tmp);
if ( *tmp ) error("Could not parse: -c %s\n", optarg);
}
break;
case 'G': error("The option -G, --GTs-only has been deprecated\n"); break;
case 'a': args->all_sites = 1; error("The -a option is to be implemented, please open an issue on github\n"); break;
case 'H': args->hom_only = 1; break;
case 'g': args->gt_fname = optarg; break;
// case 'p': args->plot = optarg; break;
case 's':
if ( !strncasecmp("gt:",optarg,3) ) args->gt_samples = optarg+3;
else if ( !strncasecmp("qry:",optarg,4) ) args->qry_samples = optarg+4;
else error("Which one? Query samples (qry:%s) or genotype samples (gt:%s)?\n",optarg,optarg);
break;
case 'S':
if ( !strncasecmp("gt:",optarg,3) ) args->gt_samples = optarg+3, args->gt_samples_is_file = 1;
else if ( !strncasecmp("qry:",optarg,4) ) args->qry_samples = optarg+4, args->qry_samples_is_file = 1;
else error("Which one? Query samples (qry:%s) or genotype samples (gt:%s)?\n",optarg,optarg);
break;
case 'p': args->pair_samples = optarg; break;
case 'P': args->pair_samples = optarg; args->pair_samples_is_file = 1; break;
case 'r': args->regions = optarg; break;
case 'R': args->regions = optarg; args->regions_is_file = 1; break;
case 't': args->targets = optarg; break;
case 'T': args->targets = optarg; args->targets_is_file = 1; break;
case 7 :
args->regions_overlap = parse_overlap_option(optarg);
if ( args->regions_overlap < 0 ) error("Could not parse: --regions-overlap %s\n",optarg);
break;
case 8 :
args->targets_overlap = parse_overlap_option(optarg);
if ( args->targets_overlap < 0 ) error("Could not parse: --targets-overlap %s\n",optarg);
break;
case 'h':
case '?': usage(); break;
default: error("Unknown argument: %s\n", optarg);
}
}
if ( optind==argc )
{
if ( !isatty(fileno((FILE *)stdin)) ) args->qry_fname = "-"; // reading from stdin
else usage(); // no files given
}
else args->qry_fname = argv[optind];
if ( argc>optind+1 ) error("Error: too many files given, run with -h for help\n"); // too many files given
if ( args->pair_samples )
{
if ( args->gt_samples || args->qry_samples ) error("The -p/-P option cannot be combined with -s/-S\n");
if ( args->ntop ) error("The --n-matches option cannot be combined with -p/-P\n");
}
if ( args->distinctive_sites && !args->pair_samples ) error("The experimental option --distinctive-sites requires -p/-P\n");
if ( args->hom_only && !args->gt_fname ) error("The option --homs-only requires --genotypes\n");
if ( args->distinctive_sites && args->use_PLs ) error("The option --distinctive-sites cannot be combined with --error-probability\n");
init_data(args);
int ret;
while ( (ret=bcf_sr_next_line(args->files)) )
{
if ( !is_input_okay(args,ret) ) continue;
// time one record to give the user an estimate with very big files
struct timeval t0, t1;
if ( !args->ncmp ) gettimeofday(&t0, NULL);
process_line(args);
if ( args->ncmp==1 )
{
gettimeofday(&t1, NULL);
double delta = (t1.tv_sec - t0.tv_sec) * 1e6 + (t1.tv_usec - t0.tv_usec);
fprintf(stderr,"INFO:\tTime required to process one record .. %f seconds\n",delta/1e6);
fprintf(args->fp,"INFO\tTime required to process one record .. %f seconds\n",delta/1e6);
if ( args->dry_run ) break;
}
}
if ( !args->dry_run )
{
report(args);
if ( args->distinctive_sites ) report_distinctive_sites(args);
}
destroy_data(args);
free(args);
return 0;
}
|
14a5bc9ec98f3d7bf5544ac5b829e950d9156e44
|
88ae8695987ada722184307301e221e1ba3cc2fa
|
/third_party/wayland-protocols/gtk/modules/printbackends/gtkcloudprintaccount.h
|
7cb2333ac2111cc5d5fbce42b6518da9bdae27eb
|
[
"BSD-3-Clause",
"MIT",
"LGPL-2.0-or-later",
"LGPL-2.0-only",
"LGPL-2.1-only",
"Apache-2.0",
"GPL-1.0-or-later"
] |
permissive
|
iridium-browser/iridium-browser
|
71d9c5ff76e014e6900b825f67389ab0ccd01329
|
5ee297f53dc7f8e70183031cff62f37b0f19d25f
|
refs/heads/master
| 2023-08-03T16:44:16.844552
| 2023-07-20T15:17:00
| 2023-07-23T16:09:30
| 220,016,632
| 341
| 40
|
BSD-3-Clause
| 2021-08-13T13:54:45
| 2019-11-06T14:32:31
| null |
UTF-8
|
C
| false
| false
| 2,864
|
h
|
gtkcloudprintaccount.h
|
/* gtkcloudprintaccount.h: Google Cloud Print account class
* 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_CLOUDPRINT_ACCOUNT_H__
#define __GTK_CLOUDPRINT_ACCOUNT_H__
#include <glib-object.h>
#include <json-glib/json-glib.h>
#include "gtkprintbackendcloudprint.h"
G_BEGIN_DECLS
#define GTK_TYPE_CLOUDPRINT_ACCOUNT (gtk_cloudprint_account_get_type ())
#define GTK_CLOUDPRINT_ACCOUNT(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), GTK_TYPE_CLOUDPRINT_ACCOUNT, GtkCloudprintAccount))
#define GTK_IS_CLOUDPRINT_ACCOUNT(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), GTK_TYPE_CLOUDPRINT_ACCOUNT))
typedef struct _GtkPrinterCloudprint GtkPrinterCloudprint;
typedef struct _GtkCloudprintAccount GtkCloudprintAccount;
void gtk_cloudprint_account_register_type (GTypeModule *module);
GtkCloudprintAccount *gtk_cloudprint_account_new (const char *id,
const char *path,
const char *presentation_identity);
GType gtk_cloudprint_account_get_type (void) G_GNUC_CONST;
void gtk_cloudprint_account_search (GtkCloudprintAccount *account,
GDBusConnection *connection,
GCancellable *cancellable,
GAsyncReadyCallback callback,
gpointer user_data);
JsonNode *gtk_cloudprint_account_search_finish (GtkCloudprintAccount *account,
GAsyncResult *result,
GError **error);
void gtk_cloudprint_account_printer (GtkCloudprintAccount *account,
const char *printerid,
GCancellable *cancellable,
GAsyncReadyCallback callback,
gpointer user_data);
JsonObject *gtk_cloudprint_account_printer_finish (GtkCloudprintAccount *account,
GAsyncResult *result,
GError **error);
void gtk_cloudprint_account_submit (GtkCloudprintAccount *account,
GtkPrinterCloudprint *printer,
GMappedFile *file,
const char *title,
GCancellable *cancellable,
GAsyncReadyCallback callback,
gpointer user_data);
JsonObject *gtk_cloudprint_account_submit_finish (GtkCloudprintAccount *account,
GAsyncResult *result,
GError **error);
const char *gtk_cloudprint_account_get_presentation_identity (GtkCloudprintAccount *account);
G_END_DECLS
#endif /* __GTK_CLOUDPRINT_ACCOUNT_H__ */
|
380025768ac6f07c4b19a3f1bf951601afb77993
|
847ebadf2b0e7c01ad33ce92b42528a1a5c4846c
|
/datapath-windows/ovsext/PacketParser.c
|
e89ff0641459acdfd827dc6c92bc75148f13a808
|
[
"BSD-3-Clause",
"ISC",
"Apache-2.0",
"SISSL",
"GPL-2.0-only",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] |
permissive
|
openvswitch/ovs
|
6f782527cf5fde4ccfd25e68d359b91ff41acf8a
|
bc79a7bf033fa4cda8ccfc5481db3cfccd72650c
|
refs/heads/master
| 2023-09-04T06:31:47.899017
| 2023-08-03T16:19:12
| 2023-09-01T20:15:05
| 18,383,364
| 3,366
| 2,259
|
Apache-2.0
| 2023-08-17T13:17:13
| 2014-04-02T22:15:28
|
C
|
UTF-8
|
C
| false
| false
| 10,337
|
c
|
PacketParser.c
|
/*
* Copyright (c) 2014 VMware, 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 "PacketParser.h"
//XXX consider moving to NdisGetDataBuffer.
const VOID *
OvsGetPacketBytes(const NET_BUFFER_LIST *nbl,
UINT32 len,
UINT32 srcOffset,
VOID *storage)
{
NDIS_STATUS status = NDIS_STATUS_SUCCESS;
PNET_BUFFER netBuffer = NET_BUFFER_LIST_FIRST_NB(nbl);
PMDL currentMdl;
BOOLEAN firstMDL = TRUE;
ULONG destOffset = 0;
VOID *dest = storage;
const UINT32 copyLen = len;
ULONG packetLen;
packetLen = NET_BUFFER_DATA_LENGTH(netBuffer);
// Start copy from current MDL
currentMdl = NET_BUFFER_CURRENT_MDL(netBuffer);
// Data on current MDL may be offset from start of MDL
while (destOffset < copyLen && currentMdl) {
PUCHAR srcMemory = OvsGetMdlWithLowPriority(currentMdl);
ULONG length = MmGetMdlByteCount(currentMdl);
if (!srcMemory) {
status = NDIS_STATUS_RESOURCES;
break;
}
if (firstMDL) {
ULONG mdlOffset = NET_BUFFER_CURRENT_MDL_OFFSET(netBuffer);
srcMemory += mdlOffset;
length -= mdlOffset;
firstMDL = FALSE;
}
length = MIN(length, packetLen);
packetLen -= length;
ASSERT((INT)packetLen >= 0);
if (srcOffset >= length) {
currentMdl = NDIS_MDL_LINKAGE(currentMdl);
srcOffset -= length;
continue;
} else {
srcMemory += srcOffset;
length -= srcOffset;
srcOffset = 0;
}
length = min(length, copyLen-destOffset);
NdisMoveMemory((PUCHAR)dest+destOffset, srcMemory, length);
destOffset += length;
currentMdl = NDIS_MDL_LINKAGE(currentMdl);
}
if (destOffset == copyLen) {
ASSERT(status == NDIS_STATUS_SUCCESS);
return storage;
}
return NULL;
}
NDIS_STATUS
OvsParseIPv6(const NET_BUFFER_LIST *packet,
Ipv6Key *ipv6Key,
POVS_PACKET_HDR_INFO layers)
{
UINT16 ofs = layers->l3Offset;
IPv6Hdr ipv6HdrStorage;
const IPv6Hdr *nh;
UINT32 nextHdr;
nh = OvsGetPacketBytes(packet, sizeof *nh, ofs, &ipv6HdrStorage);
if (!nh) {
return NDIS_STATUS_FAILURE;
}
nextHdr = nh->nexthdr;
RtlCopyMemory(&ipv6Key->ipv6Src, nh->saddr.s6_addr, 16);
RtlCopyMemory(&ipv6Key->ipv6Dst, nh->daddr.s6_addr, 16);
ipv6Key->nwTos = ((nh->flow_lbl[0] & 0xF0) >> 4) | (nh->priority << 4);
ipv6Key->ipv6Label =
((nh->flow_lbl[0] & 0x0F) << 16) | (nh->flow_lbl[1] << 8) | nh->flow_lbl[2];
ipv6Key->nwTtl = nh->hop_limit;
ipv6Key->nwProto = SOCKET_IPPROTO_NONE;
ipv6Key->nwFrag = OVS_FRAG_TYPE_NONE;
// Parse extended headers and compute L4 offset
ofs += sizeof(IPv6Hdr);
for (;;) {
if ((nextHdr != SOCKET_IPPROTO_HOPOPTS)
&& (nextHdr != SOCKET_IPPROTO_ROUTING)
&& (nextHdr != SOCKET_IPPROTO_DSTOPTS)
&& (nextHdr != SOCKET_IPPROTO_AH)
&& (nextHdr != SOCKET_IPPROTO_FRAGMENT)) {
/*
* It's either a terminal header (e.g., TCP, UDP) or one we
* don't understand. In either case, we're done with the
* packet, so use it to fill in 'nw_proto'.
*/
break;
}
if (nextHdr == SOCKET_IPPROTO_HOPOPTS
|| nextHdr == SOCKET_IPPROTO_ROUTING
|| nextHdr == SOCKET_IPPROTO_DSTOPTS
|| nextHdr == SOCKET_IPPROTO_AH) {
IPv6ExtHdr extHdrStorage;
const IPv6ExtHdr *extHdr;
UINT8 len;
extHdr = OvsGetPacketBytes(packet, sizeof *extHdr, ofs, &extHdrStorage);
if (!extHdr) {
return NDIS_STATUS_FAILURE;
}
len = extHdr->hdrExtLen;
ofs += nextHdr == SOCKET_IPPROTO_AH ? (len + 2) * 4 : (len + 1) * 8;
nextHdr = extHdr->nextHeader;
if (OvsPacketLenNBL(packet) < ofs) {
return NDIS_STATUS_FAILURE;
}
} else if (nextHdr == SOCKET_IPPROTO_FRAGMENT) {
IPv6FragHdr fragHdrStorage;
const IPv6FragHdr *fragHdr;
fragHdr = OvsGetPacketBytes(packet, sizeof *fragHdr, ofs,
&fragHdrStorage);
if (!fragHdr) {
return NDIS_STATUS_FAILURE;
}
nextHdr = fragHdr->nextHeader;
ofs += sizeof *fragHdr;
/* We only process the first fragment. */
if (fragHdr->offlg != htons(0)) {
if ((ntohs(fragHdr->offlg) & IP6F_OFF_HOST_ORDER_MASK) == htons(0)) {
ipv6Key->nwFrag = OVS_FRAG_TYPE_FIRST;
} else {
ipv6Key->nwFrag = OVS_FRAG_TYPE_LATER;
nextHdr = SOCKET_IPPROTO_FRAGMENT;
break;
}
} else {
ipv6Key->nwFrag = OVS_FRAG_TYPE_NONE;
}
}
}
ipv6Key->nwProto = (UINT8)nextHdr;
layers->l4Offset = ofs;
return NDIS_STATUS_SUCCESS;
}
VOID
OvsParseTcp(const NET_BUFFER_LIST *packet,
L4Key *flow,
POVS_PACKET_HDR_INFO layers)
{
TCPHdr tcpStorage;
const TCPHdr *tcp = OvsGetTcp(packet, layers->l4Offset, &tcpStorage);
if (tcp) {
if (flow) {
flow->tpSrc = tcp->source;
flow->tpDst = tcp->dest;
}
if (layers) {
layers->isTcp = 1;
layers->l7Offset = layers->l4Offset + 4 * tcp->doff;
}
}
}
VOID
OvsParseSctp(const NET_BUFFER_LIST *packet,
L4Key *flow,
POVS_PACKET_HDR_INFO layers)
{
SCTPHdr sctpStorage;
const SCTPHdr *sctp = OvsGetSctp(packet, layers->l4Offset, &sctpStorage);
if (sctp) {
if (flow) {
flow->tpSrc = sctp->source;
flow->tpDst = sctp->dest;
}
if (layers) {
layers->isSctp = 1;
layers->l7Offset = layers->l4Offset + sizeof *sctp;
}
}
}
VOID
OvsParseUdp(const NET_BUFFER_LIST *packet,
L4Key *flow,
POVS_PACKET_HDR_INFO layers)
{
UDPHdr udpStorage;
const UDPHdr *udp = OvsGetUdp(packet, layers->l4Offset, &udpStorage);
if (udp) {
if (flow) {
flow->tpSrc = udp->source;
flow->tpDst = udp->dest;
}
if (layers) {
layers->isUdp = 1;
if (udp->check == 0) {
layers->udpCsumZero = 1;
}
layers->l7Offset = layers->l4Offset + sizeof *udp;
}
}
}
NDIS_STATUS
OvsParseIcmpV6(const NET_BUFFER_LIST *packet,
Ipv6Key *ipv6Key,
Icmp6Key *icmp6Key,
POVS_PACKET_HDR_INFO layers)
{
UINT16 ofs = layers->l4Offset;
ICMPHdr icmpStorage;
const ICMPHdr *icmp;
memset(&icmp6Key->ndTarget, 0, sizeof(icmp6Key->ndTarget));
memset(icmp6Key->arpSha, 0, sizeof(icmp6Key->arpSha));
memset(icmp6Key->arpTha, 0, sizeof(icmp6Key->arpTha));
icmp = OvsGetIcmp(packet, ofs, &icmpStorage);
if (!icmp) {
return NDIS_STATUS_FAILURE;
}
ofs += sizeof *icmp;
/*
* The ICMPv6 type and code fields use the 16-bit transport port
* fields, so we need to store them in 16-bit network byte order.
*/
if (ipv6Key) {
ipv6Key->l4.tpSrc = htons(icmp->type);
ipv6Key->l4.tpDst = htons(icmp->code);
}
if (icmp->code == 0 &&
(icmp->type == ND_NEIGHBOR_SOLICIT ||
icmp->type == ND_NEIGHBOR_ADVERT)) {
struct in6_addr ndTargetStorage;
const struct in6_addr *ndTarget;
ndTarget = OvsGetPacketBytes(packet, sizeof *ndTarget, ofs,
&ndTargetStorage);
if (!ndTarget) {
return NDIS_STATUS_FAILURE;
}
icmp6Key->ndTarget = *ndTarget;
while ((UINT32)(ofs + 8) <= OvsPacketLenNBL(packet)) {
/*
* The minimum size of an option is 8 bytes, which also is
* the size of Ethernet link-layer options.
*/
IPv6NdOptHdr ndOptStorage;
const IPv6NdOptHdr *ndOpt;
UINT16 optLen;
ndOpt = OvsGetPacketBytes(packet, sizeof *ndOpt, ofs, &ndOptStorage);
if (!ndOpt) {
return NDIS_STATUS_FAILURE;
}
optLen = ndOpt->len * 8;
if (!optLen || (UINT32)(ofs + optLen) > OvsPacketLenNBL(packet)) {
goto invalid;
}
/*
* Store the link layer address if the appropriate option is
* provided. It is considered an error if the same link
* layer option is specified twice.
*/
if (ndOpt->type == ND_OPT_SOURCE_LINKADDR && optLen == 8) {
if (Eth_IsNullAddr(icmp6Key->arpSha)) {
memcpy(icmp6Key->arpSha, ndOpt + 1, ETH_ADDR_LENGTH);
} else {
goto invalid;
}
} else if (ndOpt->type == ND_OPT_TARGET_LINKADDR && optLen == 8) {
if (Eth_IsNullAddr(icmp6Key->arpTha)) {
memcpy(icmp6Key->arpTha, ndOpt + 1, ETH_ADDR_LENGTH);
} else {
goto invalid;
}
}
ofs += optLen;
}
}
layers->l7Offset = ofs;
layers->isIcmp = 1;
return NDIS_STATUS_SUCCESS;
invalid:
RtlZeroMemory(&icmp6Key->ndTarget, sizeof(icmp6Key->ndTarget));
RtlZeroMemory(icmp6Key->arpSha, sizeof(icmp6Key->arpSha));
RtlZeroMemory(icmp6Key->arpTha, sizeof(icmp6Key->arpTha));
return NDIS_STATUS_FAILURE;
}
|
cf752d21a398def62c87b25d567e747127721d06
|
03666e5f961946fc1a0ac67781ac1425562ef0d7
|
/src/tools/data/DataManualExamples/Simulations/zerocopy.c
|
4b7a3a47f9c2f45aac244ed661b8ddf959d9c955
|
[
"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
| 34,292
|
c
|
zerocopy.c
|
// Copyright (c) Lawrence Livermore National Security, LLC and other VisIt
// Project developers. See the top-level LICENSE file for dates and other
// details. No copyright assignment is required to contribute to VisIt.
#include <VisItControlInterface_V2.h>
#include <VisItDataInterface_V2.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#ifdef PARALLEL
#include <mpi.h>
#endif
#include "extract.h"
#include "SimulationExample.h"
#define SPHERICAL_COORDINATES
#define FREE(PTR) if((PTR)!=NULL){ free(PTR); PTR = NULL; }
#define VISIT_COMMAND_PROCESS 0
#define VISIT_COMMAND_SUCCESS 1
#define VISIT_COMMAND_FAILURE 2
/* Communication Function prototypes */
int SimBroadcastInt(int *value, int sender, void *cbdata);
int SimBroadcastString(char *str, int len, int sender, void *cbdata);
void SimSlaveProcessCallback(void *);
/* Data Adaptor Function prototypes */
visit_handle SimGetMetaData(void *);
visit_handle SimGetMesh(int, const char *, void *);
visit_handle SimGetVariable(int, const char *, void *);
visit_handle SimGetDomainList(const char *, void *);
/******************************************************************************
* Simulation data and functions
******************************************************************************/
/* ArrayOfStructures */
typedef struct
{
double x,y,z;
float temperature;
double vx,vy,vz;
int I,J,K;
} Node;
typedef struct
{
Node *nodes;
int nnodes;
} ArrayOfStructures;
void ArrayOfStructures_ctor(ArrayOfStructures *obj, int nnodes)
{
obj->nnodes = nnodes;
obj->nodes = (Node *)malloc(nnodes * sizeof(Node));
}
void ArrayOfStructures_dtor(ArrayOfStructures *obj)
{
FREE(obj->nodes);
obj->nnodes = 0;
}
/* StructureOfArrays */
typedef struct
{
double *x, *y, *z;
double *xyz; /* for baseline case with contiguous coords. */
float *temperature;
double *vx,*vy,*vz;
int *I,*J,*K;
int nnodes;
} StructureOfArrays;
void StructureOfArrays_ctor(StructureOfArrays *obj, int nnodes)
{
obj->nnodes = nnodes;
obj->x = (double *)malloc(nnodes * sizeof(double));
obj->y = (double *)malloc(nnodes * sizeof(double));
obj->z = (double *)malloc(nnodes * sizeof(double));
obj->xyz = (double *)malloc(3 * nnodes * sizeof(double));
obj->temperature = (float *)malloc(nnodes * sizeof(float));
obj->vx = (double *)malloc(nnodes * sizeof(double));
obj->vy = (double *)malloc(nnodes * sizeof(double));
obj->vz = (double *)malloc(nnodes * sizeof(double));
obj->I = (int *)malloc(nnodes * sizeof(int));
obj->J = (int *)malloc(nnodes * sizeof(int));
obj->K = (int *)malloc(nnodes * sizeof(int));
}
void StructureOfArrays_dtor(StructureOfArrays *obj)
{
FREE(obj->x);
FREE(obj->y);
FREE(obj->z);
FREE(obj->xyz);
FREE(obj->temperature);
FREE(obj->vx);
FREE(obj->vy);
FREE(obj->vz);
FREE(obj->I);
FREE(obj->J);
FREE(obj->K);
obj->nnodes = 0;
}
/******************************************************************************
* Simulation data and functions
******************************************************************************/
#define SIM_STOPPED 0
#define SIM_RUNNING 1
typedef struct
{
#ifdef PARALLEL
MPI_Comm par_comm;
#endif
int par_rank;
int par_size;
int cycle;
double time;
int runMode;
int done;
int dims[3];
float extents[6];
int echo;
ArrayOfStructures aos;
StructureOfArrays soa;
} simulation_data;
void
simulation_data_ctor(simulation_data *sim, int nx, int ny, int nz)
{
sim->par_rank = 0;
sim->par_size = 1;
sim->cycle = 0;
sim->time = 0.;
sim->runMode = SIM_STOPPED;
sim->done = 0;
sim->dims[0] = nx;
sim->dims[1] = ny;
sim->dims[2] = nz;
#ifdef SPHERICAL_COORDINATES
sim->extents[0] = 0.0001f;
sim->extents[1] = 1.f;
sim->extents[2] = 0.f;
sim->extents[3] = M_PI;
sim->extents[4] = 0.f;
sim->extents[5] = M_PI;
#else
sim->extents[0] = 0.f;
sim->extents[1] = 4.f;
sim->extents[2] = 0.f;
sim->extents[3] = 4.f;
sim->extents[4] = 0.f;
sim->extents[5] = 4.f;
#endif
sim->echo = 0;
ArrayOfStructures_ctor(&sim->aos, sim->dims[0]*sim->dims[1]*sim->dims[2]);
StructureOfArrays_ctor(&sim->soa, sim->dims[0]*sim->dims[1]*sim->dims[2]);
}
void
simulation_data_dtor(simulation_data *sim)
{
ArrayOfStructures_dtor(&sim->aos);
StructureOfArrays_dtor(&sim->soa);
}
void
simulation_data_update(simulation_data *sim)
{
double x,y,z,sx,sy,sz,r,tx,ty,tz,offset,scale;
int index, i,j,k;
#ifdef SPHERICAL_COORDINATES
double theta,phi;
#endif
if(sim->par_rank == 0)
{
printf("Simulating time step: cycle=%d, time=%lg\n", sim->cycle, sim->time);
fflush(stdout);
}
/* Update values. */
offset = (sim->extents[1] - sim->extents[0]) * sim->par_rank;
index = 0;
for(k = 0; k < sim->dims[2]; ++k)
{
tz = ((double)k) / ((double)(sim->dims[2] - 1));
z = (1.f-tz)*sim->extents[4] + tz*sim->extents[5];
for(j = 0; j < sim->dims[1]; ++j)
{
ty = ((double)j) / ((double)(sim->dims[1] - 1));
y = (1.f-ty)*sim->extents[2] + ty*sim->extents[3];
for(i = 0; i < sim->dims[0]; ++i)
{
tx = ((double)i) / ((double)(sim->dims[0] - 1));
x = (1.f-tx)*sim->extents[0] + tx*sim->extents[1];
#ifdef SPHERICAL_COORDINATES
r = x + offset;
theta = z + sim->time;
phi = y;
sx = r * cos(theta) * sin(phi);
sy = r * sin(theta) * sin(phi);
sz = r * cos(phi);
#else
sx = x + offset;
sy = y;
sz = z;
#endif
r = sqrt(sx*sx + sy*sy + sz*sz);
scale = (r == 0.) ? 1. : (1. / r);
/* Save AOS version */
sim->aos.nodes[index].x = sx;
sim->aos.nodes[index].y = sy;
sim->aos.nodes[index].z = sz;
sim->aos.nodes[index].temperature = r;
sim->aos.nodes[index].vx = sx * scale;
sim->aos.nodes[index].vy = sy * scale;
sim->aos.nodes[index].vz = sz * scale;
sim->aos.nodes[index].I = i;
sim->aos.nodes[index].J = j;
sim->aos.nodes[index].K = k;
/* Save SOA version */
sim->soa.x[index] = sx;
sim->soa.y[index] = sy;
sim->soa.z[index] = sz;
sim->soa.xyz[index*3+0] = sx;
sim->soa.xyz[index*3+1] = sy;
sim->soa.xyz[index*3+2] = sz;
sim->soa.temperature[index] = r;
sim->soa.vx[index] = sx * scale;
sim->soa.vy[index] = sy * scale;
sim->soa.vz[index] = sz * scale;
sim->soa.I[index] = i;
sim->soa.J[index] = j;
sim->soa.K[index] = k;
++index;
}
}
}
}
void
simulation_advance(simulation_data *sim)
{
++sim->cycle;
sim->time += (M_PI / 10.);
}
/* Callback function for control commands, which are the buttons in the
* GUI's Simulation window. This type of command is handled automatically
* provided that you have registered a command callback such as this.
*/
void SimControlCommandCallback(const char *cmd, const char *args, void *cbdata)
{
simulation_data *sim = (simulation_data *)cbdata;
if(strcmp(cmd, "quit") == 0)
sim->done = 1;
else if(strcmp(cmd, "halt") == 0)
sim->runMode = SIM_STOPPED;
else if(strcmp(cmd, "step") == 0)
{
simulation_data_update(sim);
simulation_advance(sim);
VisItTimeStepChanged();
VisItUpdatePlots();
}
else if(strcmp(cmd, "run") == 0)
sim->runMode = SIM_RUNNING;
if(sim->echo && sim->par_rank == 0)
{
fprintf(stderr, "Command '%s' completed.\n", cmd);
fflush(stderr);
}
}
void
SetupCallbacks(simulation_data *sim)
{
VisItSetCommandCallback(SimControlCommandCallback, (void*)sim);
VisItSetSlaveProcessCallback2(SimSlaveProcessCallback, (void*)sim);
VisItSetGetMetaData(SimGetMetaData, (void*)sim);
VisItSetGetMesh(SimGetMesh, (void*)sim);
VisItSetGetVariable(SimGetVariable, (void*)sim);
VisItSetGetDomainList(SimGetDomainList, (void*)sim);
}
/******************************************************************************
*
* Function: mainloop_batch
*
* Purpose: The batch version of the main loop. It iterates and makes extracts.
*
* Programmer: Brad Whitlock
* Date: Tue Feb 3 13:10:23 PST 2015
*
* Modifications:
*
*****************************************************************************/
void mainloop_batch(simulation_data *sim)
{
char filebase[100];
const char *extractvars[] = {"q", "xc", "radius", NULL};
double origin[] = {5., 5., 5.}, normal[] = {0., 0.707, 0.707};
double isos[] = {0.2, 0.5, 0.8};
double v0[] = {1.,1.,1.}, v1[] = {5., 1.5, 7.}, v2[] = {8., 2., 5.};
/* Explicitly load VisIt runtime functions and install callbacks. */
VisItInitializeRuntime();
SetupCallbacks(sim);
while(!sim->done)
{
/* Update the simulation data for this iteration.*/
simulation_data_update(sim);
/* Tell VisIt that some metadata changed.*/
VisItTimeStepChanged();
/* Make some extracts. */
sprintf(filebase, "slice3v_%04d", sim->cycle);
extract_slice_3v(filebase, v0, v1, v2, extractvars);
sprintf(filebase, "sliceON_%04d", sim->cycle);
extract_slice_origin_normal(filebase, origin, normal, extractvars);
sprintf(filebase, "sliceX_%04d", sim->cycle);
extract_slice(filebase, 0, 0.5, extractvars);
sprintf(filebase, "sliceY_%04d", sim->cycle);
extract_slice(filebase, 1, 2.5, extractvars);
sprintf(filebase, "sliceZ_%04d", sim->cycle);
extract_slice(filebase, 2, 5., extractvars);
sprintf(filebase, "iso_%04d", sim->cycle);
extract_iso(filebase, "q", isos, 3, extractvars);
simulation_advance(sim);
}
}
/* Called to handle case 3 from VisItDetectInput where we have console
* input that needs to be processed in order to accomplish an action.
*/
void
mainloop_interactive_console_command(simulation_data *sim)
{
/* Read A Command */
char cmd[1000];
if (sim->par_rank == 0)
{
if(VisItReadConsole(1000, cmd) == VISIT_ERROR)
{
sprintf(cmd, "quit");
printf("quit\n");
}
}
#ifdef PARALLEL
/* Broadcast the command to all processors. */
MPI_Bcast(cmd, 1000, MPI_CHAR, 0, sim->par_comm);
#endif
SimControlCommandCallback(cmd, NULL, sim);
}
/******************************************************************************
*
* Function: mainloop_interactive
*
* Purpose: Handles the program's main event loop and dispatches events to
* other functions for processing.
*
* Programmer: Brad Whitlock
* Date: Thu Nov 2 17:26:08 PST 2006
*
* Modifications:
*
*****************************************************************************/
int SimProcessVisItCommand(simulation_data *sim);
void mainloop_interactive(simulation_data *sim)
{
int blocking, visitstate = 0, err = 0;
/* If we're not running by default then simulate once there's something
* once VisIt connects.
*/
if(sim->runMode == SIM_STOPPED)
simulation_data_update(sim);
if (sim->par_rank == 0)
{
fprintf(stderr, "command> ");
fflush(stderr);
}
do
{
blocking = (sim->runMode == SIM_RUNNING) ? 0 : 1;
/* Get input from VisIt or timeout so the simulation can run. */
if(sim->par_rank == 0)
{
visitstate = VisItDetectInput(blocking, fileno(stdin));
}
#ifdef PARALLEL
/* Broadcast the return value of VisItDetectInput to all procs. */
MPI_Bcast(&visitstate, 1, MPI_INT, 0, sim->par_comm);
#endif
/* Do different things depending on the output from VisItDetectInput. */
switch(visitstate)
{
case 0:
/* There was no input from VisIt, return control to sim. */
simulation_data_update(sim);
simulation_advance(sim);
VisItTimeStepChanged();
VisItUpdatePlots();
break;
case 1:
/* VisIt is trying to connect to sim. */
if(VisItAttemptToCompleteConnection() == VISIT_OKAY)
{
fprintf(stderr, "VisIt connected\n");
/* Install callbacks */
SetupCallbacks(sim);
}
else
{
/* Print the error message */
char *err = VisItGetLastError();
fprintf(stderr, "VisIt did not connect: %s\n", err);
free(err);
}
break;
case 2:
/* VisIt wants to tell the engine something. */
if(!SimProcessVisItCommand(sim))
{
/* Disconnect on an error or closed connection. */
VisItDisconnect();
/* Start running again if VisIt closes. */
/*sim->runMode = SIM_RUNNING;*/
}
break;
case 3:
/* VisItDetectInput detected console input - do something with it.
* NOTE: you can't get here unless you pass a file descriptor to
* VisItDetectInput instead of -1.
*/
mainloop_interactive_console_command(sim);
if (sim->par_rank == 0)
{
fprintf(stderr, "command> ");
fflush(stderr);
}
break;
default:
fprintf(stderr, "Can't recover from error %d!\n", visitstate);
err = 1;
break;
}
} while(!sim->done && err == 0);
}
/******************************************************************************
*
* Purpose: This is the main function for the program.
*
* Programmer: Brad Whitlock
* Date: Tue Feb 3 14:53:45 PST 2015
*
* Input Arguments:
* argc : The number of command line arguments.
* argv : The command line arguments.
*
* Modifications:
*
*****************************************************************************/
int main(int argc, char **argv)
{
int i,nx = 50, ny = 50,nz = 50, batch = 0, echo = 0;
char *env = NULL;
simulation_data sim;
#ifdef PARALLEL
/* Initialize MPI */
MPI_Init(&argc, &argv);
#endif
/* Check for command line arguments. */
for(i = 1; i < argc; ++i)
{
if((i+1) < argc)
{
if(strcmp(argv[i], "-nx") == 0)
{
sscanf(argv[i+1], "%d", &nx);
i++;
}
else if(strcmp(argv[i], "-ny") == 0)
{
sscanf(argv[i+1], "%d", &ny);
i++;
}
else if(strcmp(argv[i], "-nz") == 0)
{
sscanf(argv[i+1], "%d", &nz);
i++;
}
else if(strcmp(argv[i], "-dir") == 0)
{
/* Specify the path to VisIt installation. */
VisItSetDirectory(argv[i+1]);
i++;
}
}
else if(strcmp(argv[i], "-batch") == 0)
{
batch = 1;
}
else if(strcmp(argv[i], "-echo") == 0)
{
echo = 1;
}
}
/* Initialize environment variables. */
SimulationArguments(argc, argv);
simulation_data_ctor(&sim, nx, ny, nz);
sim.echo = echo;
#ifdef PARALLEL
/* Create a new communicator. */
if (MPI_Comm_dup(MPI_COMM_WORLD, &sim.par_comm) != MPI_SUCCESS)
sim.par_comm = MPI_COMM_WORLD;
MPI_Comm_rank (sim.par_comm, &sim.par_rank);
MPI_Comm_size (sim.par_comm, &sim.par_size);
/* Install callback functions for global communication. */
VisItSetBroadcastIntFunction2(SimBroadcastInt, (void*)&sim);
VisItSetBroadcastStringFunction2(SimBroadcastString, (void*)&sim);
/* Tell libsim whether the simulation is parallel. */
VisItSetParallel(sim.par_size > 1);
VisItSetParallelRank(sim.par_rank);
/* Tell libsim which communicator to use. You must pass the address of
* an MPI_Comm object.
*/
VisItSetMPICommunicator((void *)&sim.par_comm);
#endif
/* Only read the environment on rank 0. This could happen before MPI_Init if
* we are using an MPI that does not like to let us spawn processes but we
* would not know our processor rank.
*/
if(sim.par_rank == 0)
env = VisItGetEnvironment();
/* Pass the environment to all other processors collectively. */
VisItSetupEnvironment2(env);
if(env != NULL)
free(env);
/* Call the main loop. */
if(batch)
mainloop_batch(&sim);
else
{
if(sim.par_rank == 0)
{
/* Write out .sim file that VisIt uses to connect. */
VisItInitializeSocketAndDumpSimFile(
#ifdef PARALLEL
"zerocopy_par",
#else
"zerocopy",
#endif
"Demonstrates VariableData setArrayData functions for zero copy",
"/path/to/where/sim/was/started",
NULL, NULL, SimulationFilename());
}
mainloop_interactive(&sim);
}
if(VisItIsConnected())
VisItDisconnect();
simulation_data_dtor(&sim);
#ifdef PARALLEL
MPI_Finalize();
#endif
return 0;
}
/*******************************************************************************
********************************************************************************
***** ADAPTOR FUNCTIONS
********************************************************************************
*******************************************************************************/
/* COMMUNICATION ADAPTOR FUNCTIONS. */
#ifdef PARALLEL
int SimBroadcastInt(int *value, int sender, void *cbdata)
{
simulation_data *sim = (simulation_data *)cbdata;
return MPI_Bcast(value, 1, MPI_INT, sender, sim->par_comm);
}
int SimBroadcastString(char *str, int len, int sender, void *cbdata)
{
simulation_data *sim = (simulation_data *)cbdata;
return MPI_Bcast(str, len, MPI_CHAR, sender, sim->par_comm);
}
#endif
void SimSlaveProcessCallback(void *cbdata)
{
#ifdef PARALLEL
simulation_data *sim = (simulation_data *)cbdata;
int command = VISIT_COMMAND_PROCESS;
MPI_Bcast(&command, 1, MPI_INT, 0, sim->par_comm);
#endif
}
/* Helper function for SimProcessVisItCommand */
static void BroadcastSlaveCommand(int *command, simulation_data *sim)
{
#ifdef PARALLEL
MPI_Bcast(command, 1, MPI_INT, 0, sim->par_comm);
#endif
}
/* Process commands from viewer on all processors. */
int SimProcessVisItCommand(simulation_data *sim)
{
int command = VISIT_COMMAND_PROCESS;
if (sim->par_rank==0)
{
int success = VisItProcessEngineCommand();
if (success == VISIT_OKAY)
{
command = VISIT_COMMAND_SUCCESS;
BroadcastSlaveCommand(&command, sim);
return 1;
}
else
{
command = VISIT_COMMAND_FAILURE;
BroadcastSlaveCommand(&command, sim);
return 0;
}
}
else
{
/* Note: only through the SlaveProcessCallback callback
* above can the rank 0 process send a VISIT_COMMAND_PROCESS
* instruction to the non-rank 0 processes. */
while (1)
{
BroadcastSlaveCommand(&command, sim);
switch (command)
{
case VISIT_COMMAND_PROCESS:
VisItProcessEngineCommand();
break;
case VISIT_COMMAND_SUCCESS:
return 1;
case VISIT_COMMAND_FAILURE:
return 0;
}
}
}
}
/* DATA ADAPTOR FUNCTIONS */
/* soa_s means "structure of arrays with coordinates made of single variabledata object."
soa_m means "structure of arrays with coordinates made of multiple variabledata objects."
*/
const char *cmd_names[] = {"halt", "step", "run"};
const char *meshes[] = {"soa_s", "soa_m", "soa_i", "aos_s", "aos_m", "aos_c"};
const char *scalars[] = {"temperature", "vx", "vy", "vz", "I", "J", "K"};
const char *vectors[] = {"velocity"};
/******************************************************************************
*
* Purpose: This callback function returns simulation metadata.
*
* Programmer: Brad Whitlock
* Date: Fri Jul 17 15:54:51 PDT 2015
*
* Modifications:
*
*****************************************************************************/
visit_handle
SimGetMetaData(void *cbdata)
{
visit_handle md = VISIT_INVALID_HANDLE;
simulation_data *sim = (simulation_data *)cbdata;
/* Create metadata. */
if(VisIt_SimulationMetaData_alloc(&md) == VISIT_OKAY)
{
int i,j;
visit_handle mmd = VISIT_INVALID_HANDLE;
visit_handle vmd = VISIT_INVALID_HANDLE;
/* Set the simulation state. */
VisIt_SimulationMetaData_setMode(md, VISIT_SIMMODE_RUNNING);
VisIt_SimulationMetaData_setCycleTime(md, sim->cycle, sim->time);
for(i = 0; i < sizeof(meshes)/sizeof(const char*); ++i)
{
/* Add mesh metadata. */
if(VisIt_MeshMetaData_alloc(&mmd) == VISIT_OKAY)
{
/* Set the mesh's properties.*/
VisIt_MeshMetaData_setName(mmd, meshes[i]);
VisIt_MeshMetaData_setMeshType(mmd, VISIT_MESHTYPE_CURVILINEAR);
VisIt_MeshMetaData_setTopologicalDimension(mmd, 3);
VisIt_MeshMetaData_setSpatialDimension(mmd, 3);
VisIt_MeshMetaData_setNumDomains(mmd, sim->par_size);
VisIt_MeshMetaData_setDomainTitle(mmd, "Domains");
VisIt_MeshMetaData_setDomainPieceName(mmd, "domain");
VisIt_MeshMetaData_setNumGroups(mmd, 0);
VisIt_MeshMetaData_setXUnits(mmd, "cm");
VisIt_MeshMetaData_setYUnits(mmd, "cm");
VisIt_MeshMetaData_setZUnits(mmd, "cm");
VisIt_MeshMetaData_setXLabel(mmd, "Width");
VisIt_MeshMetaData_setYLabel(mmd, "Height");
VisIt_MeshMetaData_setZLabel(mmd, "Depth");
VisIt_SimulationMetaData_addMesh(md, mmd);
}
/* Add scalars. */
for(j = 0; j < sizeof(scalars)/sizeof(const char*); ++j)
{
if(VisIt_VariableMetaData_alloc(&vmd) == VISIT_OKAY)
{
char varname[100];
sprintf(varname, "%s/%s", meshes[i], scalars[j]);
VisIt_VariableMetaData_setName(vmd, varname);
VisIt_VariableMetaData_setMeshName(vmd, meshes[i]);
VisIt_VariableMetaData_setType(vmd, VISIT_VARTYPE_SCALAR);
VisIt_VariableMetaData_setCentering(vmd, VISIT_VARCENTERING_NODE);
VisIt_SimulationMetaData_addVariable(md, vmd);
}
}
/* Add vectors. */
for(j = 0; j < sizeof(vectors)/sizeof(const char*); ++j)
{
if(VisIt_VariableMetaData_alloc(&vmd) == VISIT_OKAY)
{
char varname[100];
sprintf(varname, "%s/%s", meshes[i], vectors[j]);
VisIt_VariableMetaData_setName(vmd, varname);
VisIt_VariableMetaData_setMeshName(vmd, meshes[i]);
VisIt_VariableMetaData_setType(vmd, VISIT_VARTYPE_VECTOR);
VisIt_VariableMetaData_setCentering(vmd, VISIT_VARCENTERING_NODE);
VisIt_SimulationMetaData_addVariable(md, vmd);
}
}
}
/* Add some commands. */
for(i = 0; i < sizeof(cmd_names)/sizeof(const char *); ++i)
{
visit_handle cmd = VISIT_INVALID_HANDLE;
if(VisIt_CommandMetaData_alloc(&cmd) == VISIT_OKAY)
{
VisIt_CommandMetaData_setName(cmd, cmd_names[i]);
VisIt_SimulationMetaData_addGenericCommand(md, cmd);
}
}
}
return md;
}
/******************************************************************************
*
* Purpose: This callback function returns meshes.
*
* Programmer: Brad Whitlock
* Date: Fri Jul 17 15:54:51 PDT 2015
*
* Modifications:
*
*****************************************************************************/
int serror(int simerr)
{
if(simerr == VISIT_ERROR)
printf("error: %s\n", VisItGetLastError());
return simerr;
}
visit_handle
SimGetMesh(int domain, const char *name, void *cbdata)
{
visit_handle h = VISIT_INVALID_HANDLE;
simulation_data *sim = (simulation_data *)cbdata;
if(VisIt_CurvilinearMesh_alloc(&h) != VISIT_ERROR)
{
visit_handle hx, hy, hz, hxyz;
if(strcmp(name, "soa_s") == 0)
{
/* Set coordinates using a single variable data made from SOA data. */
serror(VisIt_VariableData_alloc(&hxyz));
serror(VisIt_VariableData_setArrayDataD(hxyz, 0, VISIT_OWNER_SIM, sim->soa.nnodes, 0, sizeof(double), sim->soa.x));
serror(VisIt_VariableData_setArrayDataD(hxyz, 1, VISIT_OWNER_SIM, sim->soa.nnodes, 0, sizeof(double), sim->soa.y));
serror(VisIt_VariableData_setArrayDataD(hxyz, 2, VISIT_OWNER_SIM, sim->soa.nnodes, 0, sizeof(double), sim->soa.z));
serror(VisIt_CurvilinearMesh_setCoords3(h, sim->dims, hxyz));
}
else if(strcmp(name, "soa_m") == 0)
{
/* Set coordinates using 3 variable datas made from SOA data. */
serror(VisIt_VariableData_alloc(&hx));
serror(VisIt_VariableData_alloc(&hy));
serror(VisIt_VariableData_alloc(&hz));
serror(VisIt_VariableData_setDataD(hx, VISIT_OWNER_SIM, 1, sim->soa.nnodes, sim->soa.x));
serror(VisIt_VariableData_setDataD(hy, VISIT_OWNER_SIM, 1, sim->soa.nnodes, sim->soa.y));
serror(VisIt_VariableData_setDataD(hz, VISIT_OWNER_SIM, 1, sim->soa.nnodes, sim->soa.z));
serror(VisIt_CurvilinearMesh_setCoordsXYZ(h, sim->dims, hx, hy, hz));
}
else if(strcmp(name, "soa_i") == 0)
{
/* Set coordinates using a single variable data made from SOA interleaved data. */
serror(VisIt_VariableData_alloc(&hxyz));
serror(VisIt_VariableData_setDataD(hxyz, VISIT_OWNER_SIM, 3, sim->soa.nnodes, sim->soa.xyz));
serror(VisIt_CurvilinearMesh_setCoords3(h, sim->dims, hxyz));
}
else if(strcmp(name, "aos_s") == 0)
{
/* Set coordinates using a single variable data made from AOS data. */
serror(VisIt_VariableData_alloc(&hxyz));
serror(VisIt_VariableData_setArrayDataD(hxyz, 0, VISIT_OWNER_SIM, sim->aos.nnodes, 0, sizeof(Node), &(sim->aos.nodes[0].x)));
serror(VisIt_VariableData_setArrayDataD(hxyz, 1, VISIT_OWNER_SIM, sim->aos.nnodes, 0, sizeof(Node), &(sim->aos.nodes[0].y)));
serror(VisIt_VariableData_setArrayDataD(hxyz, 2, VISIT_OWNER_SIM, sim->aos.nnodes, 0, sizeof(Node), &(sim->aos.nodes[0].z)));
serror(VisIt_CurvilinearMesh_setCoords3(h, sim->dims, hxyz));
}
else if(strcmp(name, "aos_m") == 0)
{
/* Set coordinates using 3 variable datas made from AOS data. */
serror(VisIt_VariableData_alloc(&hx));
serror(VisIt_VariableData_alloc(&hy));
serror(VisIt_VariableData_alloc(&hz));
serror(VisIt_VariableData_setArrayDataD(hx, 0, VISIT_OWNER_SIM, sim->aos.nnodes, 0, sizeof(Node), &(sim->aos.nodes[0].x)));
serror(VisIt_VariableData_setArrayDataD(hy, 0, VISIT_OWNER_SIM, sim->aos.nnodes, 0, sizeof(Node), &(sim->aos.nodes[0].y)));
serror(VisIt_VariableData_setArrayDataD(hz, 0, VISIT_OWNER_SIM, sim->aos.nnodes, 0, sizeof(Node), &(sim->aos.nodes[0].z)));
serror(VisIt_CurvilinearMesh_setCoordsXYZ(h, sim->dims, hx, hy, hz));
}
else if(strcmp(name, "aos_c") == 0)
{
/* Set coordinates using 3 variable datas made from AOS data. Let's COPY data */
serror(VisIt_VariableData_alloc(&hx));
serror(VisIt_VariableData_alloc(&hy));
serror(VisIt_VariableData_alloc(&hz));
serror(VisIt_VariableData_setArrayDataD(hx, 0, VISIT_OWNER_COPY, sim->aos.nnodes, 0, sizeof(Node), &(sim->aos.nodes[0].x)));
serror(VisIt_VariableData_setArrayDataD(hy, 0, VISIT_OWNER_COPY, sim->aos.nnodes, 0, sizeof(Node), &(sim->aos.nodes[0].y)));
serror(VisIt_VariableData_setArrayDataD(hz, 0, VISIT_OWNER_COPY, sim->aos.nnodes, 0, sizeof(Node), &(sim->aos.nodes[0].z)));
serror(VisIt_CurvilinearMesh_setCoordsXYZ(h, sim->dims, hx, hy, hz));
}
}
return h;
}
/******************************************************************************
*
* Purpose: This callback function returns scalars.
*
* Programmer: Brad Whitlock
* Date: Fri Jul 17 15:54:51 PDT 2015
*
* Modifications:
*
*****************************************************************************/
visit_handle
SimGetVariable(int domain, const char *name, void *cbdata)
{
visit_handle h = VISIT_INVALID_HANDLE;
simulation_data *sim = (simulation_data *)cbdata;
if(strncmp(name, "aos", 3) == 0)
{
int nnodes, owner;
owner = (strcmp(name, "aos_c") == 0) ? VISIT_OWNER_COPY : VISIT_OWNER_SIM;
nnodes = sim->aos.nnodes;
/* Use setDataArray functions to set up strided array access. */
VisIt_VariableData_alloc(&h);
if(strcmp(name+6, "temperature") == 0)
serror(VisIt_VariableData_setArrayDataF(h, 0, owner, nnodes, 0, sizeof(Node), &(sim->aos.nodes[0].temperature)));
else if(strcmp(name+6, "vx") == 0)
serror(VisIt_VariableData_setArrayDataD(h, 0, owner, nnodes, 0, sizeof(Node), &(sim->aos.nodes[0].vx)));
else if(strcmp(name+6, "vy") == 0)
serror(VisIt_VariableData_setArrayDataD(h, 0, owner, nnodes, 0, sizeof(Node), &(sim->aos.nodes[0].vy)));
else if(strcmp(name+6, "vz") == 0)
serror(VisIt_VariableData_setArrayDataD(h, 0, owner, nnodes, 0, sizeof(Node), &(sim->aos.nodes[0].vz)));
else if(strcmp(name+6, "I") == 0)
serror(VisIt_VariableData_setArrayDataI(h, 0, owner, nnodes, 0, sizeof(Node), &(sim->aos.nodes[0].I)));
else if(strcmp(name+6, "J") == 0)
serror(VisIt_VariableData_setArrayDataI(h, 0, owner, nnodes, 0, sizeof(Node), &(sim->aos.nodes[0].J)));
else if(strcmp(name+6, "K") == 0)
serror(VisIt_VariableData_setArrayDataI(h, 0, owner, nnodes, 0, sizeof(Node), &(sim->aos.nodes[0].K)));
else if(strcmp(name+6, "velocity") == 0)
{
/* Combine separate strided array access into a vector. */
serror(VisIt_VariableData_setArrayDataD(h, 0, owner, nnodes, 0, sizeof(Node), &(sim->aos.nodes[0].vx)));
serror(VisIt_VariableData_setArrayDataD(h, 1, owner, nnodes, 0, sizeof(Node), &(sim->aos.nodes[0].vy)));
serror(VisIt_VariableData_setArrayDataD(h, 2, owner, nnodes, 0, sizeof(Node), &(sim->aos.nodes[0].vz)));
}
}
else if(strncmp(name, "soa", 3) == 0)
{
int nnodes = sim->soa.nnodes;
/* Use setData functions to set up contiguous array access. */
VisIt_VariableData_alloc(&h);
if(strcmp(name+6, "temperature") == 0)
serror(VisIt_VariableData_setDataF(h, VISIT_OWNER_SIM, 1, nnodes, sim->soa.temperature));
else if(strcmp(name+6, "vx") == 0)
serror(VisIt_VariableData_setDataD(h, VISIT_OWNER_SIM, 1, nnodes, sim->soa.vx));
else if(strcmp(name+6, "vy") == 0)
serror(VisIt_VariableData_setDataD(h, VISIT_OWNER_SIM, 1, nnodes, sim->soa.vy));
else if(strcmp(name+6, "vz") == 0)
serror(VisIt_VariableData_setDataD(h, VISIT_OWNER_SIM, 1, nnodes, sim->soa.vz));
else if(strcmp(name+6, "I") == 0)
serror(VisIt_VariableData_setDataI(h, VISIT_OWNER_SIM, 1, nnodes, sim->soa.I));
else if(strcmp(name+6, "J") == 0)
serror(VisIt_VariableData_setDataI(h, VISIT_OWNER_SIM, 1, nnodes, sim->soa.J));
else if(strcmp(name+6, "K") == 0)
serror(VisIt_VariableData_setDataI(h, VISIT_OWNER_SIM, 1, nnodes, sim->soa.K));
else if(strcmp(name+6, "velocity") == 0)
{
/* Combine separate contiguous arrays into a vector. */
serror(VisIt_VariableData_setArrayDataD(h, 0, VISIT_OWNER_SIM, nnodes, 0, sizeof(double), sim->soa.vx));
serror(VisIt_VariableData_setArrayDataD(h, 1, VISIT_OWNER_SIM, nnodes, 0, sizeof(double), sim->soa.vy));
serror(VisIt_VariableData_setArrayDataD(h, 2, VISIT_OWNER_SIM, nnodes, 0, sizeof(double), sim->soa.vz));
}
}
return h;
}
/******************************************************************************
*
* Purpose: This callback function returns a domain list (the list of domains
* owned by this processor).
*
* Programmer: Brad Whitlock
* Date: Fri Jul 17 15:54:51 PDT 2015
*
* Modifications:
*
*****************************************************************************/
visit_handle
SimGetDomainList(const char *name, void *cbdata)
{
visit_handle h = VISIT_INVALID_HANDLE;
if(VisIt_DomainList_alloc(&h) != VISIT_ERROR)
{
visit_handle hdl;
int *iptr = NULL;
simulation_data *sim = (simulation_data *)cbdata;
iptr = (int *)malloc(sizeof(int));
*iptr = sim->par_rank;
VisIt_VariableData_alloc(&hdl);
VisIt_VariableData_setDataI(hdl, VISIT_OWNER_VISIT, 1, 1, iptr);
VisIt_DomainList_setDomains(h, sim->par_size, hdl);
}
return h;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.