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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8b54e3c0145426931f48f27cdbd6b8fd73552c3f
|
010279e2ba272d09e9d2c4e903722e5faba2cf7a
|
/contrib/python/scipy/py3/scipy/optimize/_highs/src/ipm/basiclu/src/lu_build_factors.c
|
6dfef468799ec9b31c77c76aac38fd7b708f4c1b
|
[
"MIT",
"Apache-2.0",
"Python-2.0",
"LicenseRef-scancode-unknown-license-reference",
"Qhull",
"BSD-3-Clause",
"BSL-1.0",
"BSD-2-Clause"
] |
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
| 12,855
|
c
|
lu_build_factors.c
|
/*
* lu_build_factors.c
*
* Copyright (C) 2016-2018 ERGO-Code
*
* Build rowwise and columnwise form of L and U
*
*/
#include "lu_internal.h"
#include "lu_list.h"
#include "lu_file.h"
/*
BASICLU maintains the factorization in the form
B = L * R^1 * R^2 * ... * R^{nforrest} * U,
where L[p,p] is unit lower triangular and U[pivotrow,pivotcol] is upper
triangular. After refactorization nforrest = 0 and p and pivotrow hold the
same permutation. pivotrow and pivotcol are modified by updates, p is not.
The permutations are stored as follows:
---------------------------------------
p[0..m-1] is a vector.
pivotrow[0..pivotlen-1],
pivotcol[0..pivotlen-1]
are vectors of length m <= pivotlen < 2*m which may contain duplicate
indices. For each index its last occurance is its position in the pivot
sequence, see lu_garbage_perm().
pmap[0..m-1],
qmap[0..m-1]
are vectors such that i = pmap[j] and j = qmap[i] when element (i,j) of
U is pivot element.
The matrix L is stored as follows:
----------------------------------
Lindex[0..Lnz+m-1],
Lvalue[0..Lnz+m-1]
hold L columnwise without the unit diagonal. Each column is terminated
by index -1. Row indices are row indices of B.
Lbegin[i] points to the first element in column i.
Lbegin_p[k] points to the first element in column p[k].
Lindex[Lnz+m..2*(Lnz+m)-1],
Lvalue[Lnz+m..2*(Lnz+m)-1]
hold L rowwise without the unit diagonal. Each row is terminated
by index -1. Column indices are such that column i holds the elimination
factors from the pivot step in which row i was pivot row.
Ltbegin[i] points to the first element in row i.
Ltbegin_p[k] points to the first element in row p[k].
The matrices R^k are stored as follows:
---------------------------------------
Lindex[Rbegin[k]..Rbegin[k+1]-1],
Lvalue[Rbegin[k]..Rbegin[k+1]-1]
hold the nontrivial column of R^k without the unit diagonal.
Row indices are row indices of B. Rbegin[0] is one past the last
element of the L storage.
eta_row[k]
holds the row index of the diagonal element of the nontrivial column
of R^k. These are row indices of B.
The matrix U is stored as follows:
----------------------------------
Uindex[1..Unz+m],
Uvalue[1..Unz+m]
hold U columnwise without the pivot elements. Each column is terminated
by index -1. Row indices are row indices of B. Updates will introduce
gaps into the data structure.
Uindex[0] stores index -1. All empty columns (ie. column in U with no
off-diagonal elements) are stored in Uindex[0]. For each empty column
the length of the data structure decreases by 1.
Ubegin[i] points to the first element in column qmap[i].
Windex[..],
Wvalue[..]
hold U rowwise without the pivot elements. Column indices are column
indices of B. The rows are stored in a dynamic file structure with gaps
between them and out of order.
Wbegin[j] points to the first element in row pmap[j].
Wend[j] points to one past the last element in row pmap[j].
Wflink, Wblink double linked list of rows in memory order.
col_pivot[0..m-1],
row_pivot[0..m-1]
hold the pivot elements by column and by row index.
*/
/*
* lu_build_factors() - build data structures for L, R, U and permutations
*
* Return:
*
* BASICLU_REALLOCATE require more memory in L, U, and/or W
* BASICLU_OK
*/
lu_int lu_build_factors(struct lu *this)
{
const lu_int m = this->m;
const lu_int rank = this->rank;
const lu_int Lmem = this->Lmem;
const lu_int Umem = this->Umem;
const lu_int Wmem = this->Wmem;
const lu_int pad = this->pad;
const double stretch = this->stretch;
lu_int *pinv = this->pinv;
lu_int *qinv = this->qinv;
lu_int *pmap = this->pmap; /* shares memory with pinv */
lu_int *qmap = this->qmap; /* shares memory with qinv */
lu_int *pivotcol = this->pivotcol;
lu_int *pivotrow = this->pivotrow;
lu_int *Lbegin = this->Lbegin;
lu_int *Lbegin_p = this->Lbegin_p;
lu_int *Ltbegin = this->Ltbegin;
lu_int *Ltbegin_p = this->Ltbegin_p;
lu_int *Ubegin = this->Ubegin;
lu_int *Rbegin = this->Rbegin;
lu_int *Wbegin = this->Wbegin;
lu_int *Wend = this->Wend;
lu_int *Wflink = this->Wflink;
lu_int *Wblink = this->Wblink;
double *col_pivot = this->col_pivot;
double *row_pivot = this->row_pivot;
lu_int *Lindex = this->Lindex;
double *Lvalue = this->Lvalue;
lu_int *Uindex = this->Uindex;
double *Uvalue = this->Uvalue;
lu_int *Windex = this->Windex;
double *Wvalue = this->Wvalue;
lu_int *iwork1 = this->iwork1;
lu_int i, j, ipivot, jpivot, k, lrank, nz, Lnz, Unz, need, get, put, pos;
double pivot, min_pivot, max_pivot;
lu_int status = BASICLU_OK;
/*
* So far L is stored columnwise in Lindex, Lvalue and U stored rowwise
* in Uindex, Uvalue. The factorization has computed rank columns of L
* and rank rows of U. If rank < m, then the columns which have not been
* pivotal will be removed from U.
*/
Lnz = Lbegin_p[rank];
Lnz -= rank; /* because each column is terminated by -1 */
Unz = Ubegin[rank]; /* might be decreased when rank < m */
/*
* Calculate memory and reallocate. The rowwise and columnwise storage of
* L both need space for Lnz nonzeros + m terminators. The same for the
* columnwise storage of U except that Uindex[0] = -1 is reserved to
* accomodate pointers to empty columns. In the rowwise storage of U each
* row with nz nonzeros is padded by stretch*nz + pad elements.
*/
need = 2*(Lnz+m);
if (Lmem < need)
{
this->addmemL = need-Lmem;
status = BASICLU_REALLOCATE;
}
need = Unz+m+1;
if (Umem < need)
{
this->addmemU = need-Umem;
status = BASICLU_REALLOCATE;
}
need = Unz + stretch*Unz + m*pad;
if (Wmem < need)
{
this->addmemW = need-Wmem;
status = BASICLU_REALLOCATE;
}
if (status != BASICLU_OK)
return status;
/* ------------------ */
/* Build permutations */
/* ------------------ */
/*
* Append columns/rows which have not been pivotal to the end of the
* pivot sequence. Build pivotrow, pivotcol as inverse of pinv, qinv.
*/
#ifndef NDEBUG
for (k = 0; k < m; k++)
pivotrow[k] = -1;
for (k = 0; k < m; k++)
pivotcol[k] = -1;
#endif
lrank = rank;
for (i = 0; i < m; i++)
{
if (pinv[i] < 0)
pinv[i] = lrank++;
pivotrow[pinv[i]] = i;
}
assert(lrank == m);
lrank = rank;
for (j = 0; j < m; j++)
{
if (qinv[j] < 0)
qinv[j] = lrank++;
pivotcol[qinv[j]] = j;
}
assert(lrank == m);
#ifndef NDEBUG
for (k = 0; k < m; k++)
assert(pivotrow[k] >= 0);
for (k = 0; k < m; k++)
assert(pivotcol[k] >= 0);
#endif
/* Dependent columns get unit pivot elements. */
for (k = rank; k < m; k++)
col_pivot[pivotcol[k]] = 1.0;
/* ----------------------- */
/* Lower triangular factor */
/* ----------------------- */
/*
* L columnwise. If rank < m, then complete with unit columns (no
* off-diagonals, so nothing to store here).
*/
put = Lbegin_p[rank];
for (k = rank; k < m; k++)
{
Lindex[put++] = -1;
Lbegin_p[k+1] = put;
}
assert(Lbegin_p[m] == Lnz+m);
for (i = 0; i < m; i++)
Lbegin[i] = Lbegin_p[pinv[i]];
/*
* L rowwise.
*/
memset(iwork1, 0, m*sizeof(lu_int)); /* row counts */
for (get = 0; get < Lnz+m; get++)
{
if ((i = Lindex[get]) >= 0)
iwork1[i]++;
}
put = Lnz+m; /* L rowwise starts here */
for (k = 0; k < m; k++)
{
i = pivotrow[k];
Ltbegin_p[k] = put;
Ltbegin[i] = put;
put += iwork1[i];
Lindex[put++] = -1; /* terminate row */
iwork1[i]= Ltbegin_p[k];
}
assert(put == 2*(Lnz+m));
for (k = 0; k < m; k++) /* fill rows */
{
ipivot = pivotrow[k];
for (get = Lbegin_p[k]; (i = Lindex[get]) >= 0; get++)
{
put = iwork1[i]++; /* put into row i */
Lindex[put] = ipivot;
Lvalue[put] = Lvalue[get];
}
}
#ifndef NDEBUG
for (i = 0; i < m; i++)
assert(Lindex[iwork1[i]] == -1);
#endif
Rbegin[0] = 2*(Lnz+m); /* beginning of update etas */
/* ----------------------- */
/* Upper triangular factor */
/* ----------------------- */
/*
* U rowwise.
*/
lu_file_empty(m, Wbegin, Wend, Wflink, Wblink, Wmem);
memset(iwork1, 0, m*sizeof(lu_int)); /* column counts */
put = 0;
/*
* Use separate loops for full rank and rank deficient factorizations. In
* the first case no elements are removed from U, so skip the test.
*/
if (rank == m)
{
for (k = 0; k < m; k++)
{
jpivot = pivotcol[k];
Wbegin[jpivot] = put;
nz = 0;
for (pos = Ubegin[k]; pos < Ubegin[k+1]; pos++)
{
j = Uindex[pos];
Windex[put] = j;
Wvalue[put++] = Uvalue[pos];
iwork1[j]++;
nz++;
}
Wend[jpivot] = put;
put += stretch*nz + pad;
lu_list_move(jpivot, 0, Wflink, Wblink, m, NULL);
}
}
else
{
Unz = 0; /* actual number of nonzeros */
for (k = 0; k < rank; k++)
{
jpivot = pivotcol[k];
Wbegin[jpivot] = put;
nz = 0;
for (pos = Ubegin[k]; pos < Ubegin[k+1]; pos++)
{
j = Uindex[pos];
if (qinv[j] < rank)
{
Windex[put] = j;
Wvalue[put++] = Uvalue[pos];
iwork1[j]++;
nz++;
}
}
Wend[jpivot] = put;
put += stretch*nz + pad;
lu_list_move(jpivot, 0, Wflink, Wblink, m, NULL);
Unz += nz;
}
for (k = rank; k < m; k++)
{
jpivot = pivotcol[k];
Wbegin[jpivot] = put;
Wend[jpivot] = put;
put += pad;
lu_list_move(jpivot, 0, Wflink, Wblink, m, NULL);
}
}
assert(put <= Wend[m]);
Wbegin[m] = put; /* beginning of free space */
/*
* U columnwise.
*/
Uindex[0] = -1;
put = 1;
for (k = 0; k < m; k++) /* set column pointers */
{
j = pivotcol[k];
i = pivotrow[k];
nz = iwork1[j];
if (nz == 0)
{
Ubegin[i] = 0; /* empty columns all in position 0 */
}
else
{
Ubegin[i] = put;
put += nz;
Uindex[put++] = -1; /* terminate column */
}
iwork1[j] = Ubegin[i];
}
Ubegin[m] = put;
for (k = 0; k < m; k++) /* fill columns */
{
jpivot = pivotcol[k];
i = pivotrow[k];
for (pos = Wbegin[jpivot]; pos < Wend[jpivot]; pos++)
{
j = Windex[pos];
put = iwork1[j]++;
assert(put >= 1);
Uindex[put] = i;
Uvalue[put] = Wvalue[pos];
}
}
#ifndef NDEBUG
for (j = 0; j < m; j++)
assert(Uindex[iwork1[j]] == -1);
#endif
/* -------------------- */
/* Build pivot sequence */
/* -------------------- */
/* Build row-column mappings, overwriting pinv, qinv. */
for (k = 0; k < m; k++)
{
i = pivotrow[k];
j = pivotcol[k];
pmap[j] = i;
qmap[i] = j;
}
/* Build pivots by row index. */
max_pivot = 0.0;
min_pivot = INFINITY;
for (i = 0; i < m; i++)
{
row_pivot[i] = col_pivot[qmap[i]];
pivot = fabs(row_pivot[i]);
max_pivot = fmax(pivot, max_pivot);
min_pivot = fmin(pivot, min_pivot);
}
memcpy(this->p, pivotrow, m*sizeof(lu_int));
this->min_pivot = min_pivot;
this->max_pivot = max_pivot;
this->pivotlen = m;
this->Lnz = Lnz;
this->Unz = Unz;
this->Rnz = 0;
return status;
}
|
d8c540ad602385353667ef0ea7920b76cfe36f01
|
9ceacf33fd96913cac7ef15492c126d96cae6911
|
/sys/arch/amd64/include/pte.h
|
c2bd8793c7df9d0108d4712fa87a38fc96179495
|
[] |
no_license
|
openbsd/src
|
ab97ef834fd2d5a7f6729814665e9782b586c130
|
9e79f3a0ebd11a25b4bff61e900cb6de9e7795e9
|
refs/heads/master
| 2023-09-02T18:54:56.624627
| 2023-09-02T15:16:12
| 2023-09-02T15:16:12
| 66,966,208
| 3,394
| 1,235
| null | 2023-08-08T02:42:25
| 2016-08-30T18:18:25
|
C
|
UTF-8
|
C
| false
| false
| 6,338
|
h
|
pte.h
|
/* $OpenBSD: pte.h,v 1.17 2023/01/20 16:01:04 deraadt Exp $ */
/* $NetBSD: pte.h,v 1.1 2003/04/26 18:39:47 fvdl Exp $ */
/*
* Copyright (c) 2001 Wasabi Systems, Inc.
* All rights reserved.
*
* Written by Frank van der Linden for Wasabi Systems, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed for the NetBSD Project by
* Wasabi Systems, Inc.
* 4. The name of Wasabi Systems, Inc. may not be used to endorse
* or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL WASABI SYSTEMS, INC
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _MACHINE_PTE_H_
#define _MACHINE_PTE_H_
/*
* amd64 MMU hardware structure:
*
* the (first generation) amd64 MMU is a 4-level MMU which maps 2^48 bytes
* of virtual memory. The pagesize we use is 4K (4096 [0x1000] bytes),
* although 2M and 4M can be used as well. The indexes in the levels
* are 9 bits wide (512 64bit entries per level), dividing the bits
* 9-9-9-9-12.
*
* The top level table, called PML4, contains 512 64bit entries pointing
* to 3rd level table. The 3rd level table is called the 'page directory
* pointers directory' and has 512 entries pointing to page directories.
* The 2nd level is the page directory, containing 512 pointers to
* page table pages. Lastly, level 1 consists of pages containing 512
* PTEs.
*
* Simply put, levels 4-1 all consist of pages containing 512
* entries pointing to the next level. Level 0 is the actual PTEs
* themselves.
*
* For a description on the other bits, which are i386 compatible,
* see the i386 pte.h
*/
#if !defined(_LOCORE)
/*
* here we define the data types for PDEs and PTEs
*/
typedef u_int64_t pd_entry_t; /* PDE */
typedef u_int64_t pt_entry_t; /* PTE */
#endif
/*
* now we define various for playing with virtual addresses
*/
#define L1_SHIFT 12
#define L2_SHIFT 21
#define L3_SHIFT 30
#define L4_SHIFT 39
#define NBPD_L1 (1ULL << L1_SHIFT) /* # bytes mapped by L1 ent (4K) */
#define NBPD_L2 (1ULL << L2_SHIFT) /* # bytes mapped by L2 ent (2MB) */
#define NBPD_L3 (1ULL << L3_SHIFT) /* # bytes mapped by L3 ent (1G) */
#define NBPD_L4 (1ULL << L4_SHIFT) /* # bytes mapped by L4 ent (512G) */
#define L4_MASK 0x0000ff8000000000UL
#define L3_MASK 0x0000007fc0000000UL
#define L2_MASK 0x000000003fe00000UL
#define L1_MASK 0x00000000001ff000UL
#define L4_FRAME L4_MASK
#define L3_FRAME (L4_FRAME|L3_MASK)
#define L2_FRAME (L3_FRAME|L2_MASK)
#define L1_FRAME (L2_FRAME|L1_MASK)
#define PAGE_MASK_L2 (NBPD_L2 - 1)
#define x86_round_pdr(x) \
((((unsigned long)(x)) + (NBPD_L2 - 1)) & ~(NBPD_L2 - 1))
/*
* PDE/PTE bits. These are no different from their i386 counterparts.
*/
#define PG_V 0x0000000000000001UL /* valid */
#define PG_RO 0x0000000000000000UL /* read-only */
#define PG_RW 0x0000000000000002UL /* read-write */
#define PG_u 0x0000000000000004UL /* user accessible */
#define PG_PROT 0x0000000000000006UL
#define PG_WT 0x0000000000000008UL /* write through */
#define PG_N 0x0000000000000010UL /* non-cacheable */
#define PG_U 0x0000000000000020UL /* used */
#define PG_M 0x0000000000000040UL /* modified */
#define PG_PAT 0x0000000000000080UL /* PAT bit. (on pte) */
#define PG_PS 0x0000000000000080UL /* 2MB page size (on pde) */
#define PG_G 0x0000000000000100UL /* not flushed */
#define PG_AVAIL1 0x0000000000000200UL
#define PG_AVAIL2 0x0000000000000400UL
#define PG_AVAIL3 0x0000000000000800UL
#define PG_PATLG 0x0000000000001000UL /* PAT on large pages */
#define PG_PKMASK 0x7800000000000000UL /* Protection Key Mask */
#define PG_XO 0x0800000000000000UL /* key1 used for execute-only */
#define PG_NX 0x8000000000000000UL /* non-executable */
#define PG_FRAME 0x000ffffffffff000UL
#define PG_LGFRAME 0x000fffffffe00000UL /* large (2M) page frame mask */
#define PGK_VALUE 0xfffffffc /* key0 is normal */
/* EPT PTE bits */
#define EPT_R (1ULL << 0)
#define EPT_W (1ULL << 1)
#define EPT_X (1ULL << 2)
#define EPT_WB (6ULL << 3)
#define EPT_PS (1ULL << 7)
/* Cacheability bits when we are using PAT */
#define PG_WB (0) /* The default */
#define PG_WC (PG_WT) /* WT and CD is WC */
#define PG_UCMINUS (PG_N) /* UC but mtrr can override */
#define PG_UC (PG_WT | PG_N) /* hard UC */
/*
* short forms of protection codes
*/
#define PG_KR 0x0000000000000000UL /* kernel read-only */
#define PG_KW 0x0000000000000002UL /* kernel read-write */
/*
* page protection exception bits
*/
#define PGEX_P 0x01 /* protection violation (vs. no mapping) */
#define PGEX_W 0x02 /* exception during a write cycle */
#define PGEX_U 0x04 /* exception while in user mode (upl) */
#define PGEX_I 0x10 /* instruction fetch blocked by NX */
#define PGEX_PK 0x20 /* protection-key violation */
#ifdef _KERNEL
extern pt_entry_t pg_xo; /* XO pte bits using PKU key1 */
extern pt_entry_t pg_nx; /* NX pte bit */
extern pt_entry_t pg_g_kern; /* PG_G if glbl mappings can be used in kern */
#endif /* _KERNEL */
#endif /* _MACHINE_PTE_H_ */
|
473d1f56653cc3a4fa02b1fcb14129dc98ca2a7b
|
4bc40d60c146300030512b11e375cb8abbf2f5b3
|
/FemtoRV/FIRMWARE/EXAMPLES/malloc_test.c
|
b7c5737aa35321264479c844a3bb16aa151d0fd8
|
[
"BSD-3-Clause"
] |
permissive
|
BrunoLevy/learn-fpga
|
fd18ea8a67cfc46d29fac9ad417ae7990b135118
|
fd954b06f6dc57ee042d0c82e9418e83c4b261b4
|
refs/heads/master
| 2023-08-23T06:15:43.195975
| 2023-08-04T06:41:22
| 2023-08-04T06:41:22
| 267,350,664
| 2,036
| 191
|
BSD-3-Clause
| 2023-06-23T13:41:44
| 2020-05-27T15:04:05
|
C++
|
UTF-8
|
C
| false
| false
| 294
|
c
|
malloc_test.c
|
#include <stdlib.h>
extern int femtosoc_tty_init();
int main() {
femtosoc_tty_init();
void* p1 = malloc(10);
void* p2 = malloc(100);
printf("p1=0x%x\n",p1);
printf("p2=0x%x\n",p2);
free(p2);
free(p1);
void* p3 = malloc(50);
printf("p1=0x%x\n",p3);
exit(0);
}
|
f42f2cedd4973bbe3e80db478302e0e2c3cf2d46
|
f9e0bec9ebe796b499669219fdc93596c9ac84bc
|
/test/initializer-nested-array-address.c
|
fb8bbd5466d4d7137dbf3ccedcaf82be80c6d067
|
[
"Unlicense",
"ISC",
"LicenseRef-scancode-public-domain",
"MIT"
] |
permissive
|
michaelforney/cproc
|
9dac8bbb4c51edcd5e27a282963126c34052dc29
|
0985a7893a4b5de63a67ebab445892d9fffe275b
|
refs/heads/master
| 2023-09-03T12:51:45.642163
| 2022-12-14T22:29:59
| 2023-05-02T18:53:44
| 182,349,746
| 582
| 50
|
NOASSERTION
| 2022-10-30T21:23:20
| 2019-04-20T02:24:28
|
C
|
UTF-8
|
C
| false
| false
| 32
|
c
|
initializer-nested-array-address.c
|
int x[2][3];
int *y = &x[1][2];
|
7ad508647b2215707aef3f625fe3222c1c399fcb
|
229a28fc18c13bfe1ba7fc81c38b03651ed8e93b
|
/sw/vendor/riscv-isa-sim/riscv/insns/sra.h
|
403b9b733a5e3cce36c7885e906a80f4dace1309
|
[
"LicenseRef-scancode-bsd-3-clause-jtag",
"GPL-3.0-or-later",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
pulp-platform/snitch
|
d3967742434fa21e8af71afa6be35ea5420166ca
|
d026f47843f0ea6c269244c4e6851e0e09141ec3
|
refs/heads/master
| 2023-08-24T08:42:36.230951
| 2023-06-19T09:34:05
| 2023-06-19T09:34:05
| 289,236,605
| 194
| 44
|
Apache-2.0
| 2023-07-11T12:46:26
| 2020-08-21T09:57:34
|
SystemVerilog
|
UTF-8
|
C
| false
| false
| 57
|
h
|
sra.h
|
WRITE_RD(sext_xlen(sext_xlen(RS1) >> (RS2 & (xlen-1))));
|
4f1931498ef526e0ec885c6d23734b796eb29676
|
e8b38b8dfa348ff006eb197a7906ca8e491a23dc
|
/pyccel/stdlib/numpy/numpy_c.h
|
4133e9dbe9bc256f57fc0437cf841858b5a787e9
|
[
"MIT"
] |
permissive
|
pyccel/pyccel
|
d79a81dbdff1172839a6a1227abfcc1f97e6c97b
|
1896b761ba662c90b14c195bbb6eb5cddc57cbfc
|
refs/heads/devel
| 2023-08-30T12:15:25.244401
| 2023-08-28T09:31:32
| 2023-08-28T09:31:32
| 100,463,736
| 307
| 39
|
MIT
| 2023-09-14T19:29:26
| 2017-08-16T07:59:14
|
Python
|
UTF-8
|
C
| false
| false
| 650
|
h
|
numpy_c.h
|
/* --------------------------------------------------------------------------------------- */
/* This file is part of Pyccel which is released under MIT License. See the LICENSE file */
/* or go to https://github.com/pyccel/pyccel/blob/master/LICENSE for full license details. */
/* --------------------------------------------------------------------------------------- */
#ifndef NUMPY_H
# define NUMPY_H
# include <complex.h>
# include <stdbool.h>
# include <stdint.h>
# include <math.h>
#define SIGN(x) (x ? (x < 0 ? -1 : 1) : 0)
long long int isign(long long int x);
double fsign(double x);
double complex csign(double complex x);
#endif
|
f2f188db81d49374e945b1f330409e7dfb21a1ec
|
2087572dce8ad93695b27b5c61f0236c7d91ffde
|
/AppLockerBypass/IgnoreAppLocker.c
|
3229050286d4640727b809838d0b1330b15702cf
|
[
"Unlicense"
] |
permissive
|
gtworek/PSBits
|
5560ca6f7704b8585c582b920de195fc186c055a
|
d169c36881c93f43e617193f642caa534b50e6e0
|
refs/heads/master
| 2023-08-17T22:26:39.701215
| 2023-08-10T10:30:50
| 2023-08-10T10:30:50
| 194,408,180
| 2,573
| 464
|
Unlicense
| 2023-09-06T21:22:28
| 2019-06-29T13:22:36
|
PowerShell
|
UTF-8
|
C
| false
| false
| 11,886
|
c
|
IgnoreAppLocker.c
|
#include <tchar.h>
#include <Windows.h>
#include <Psapi.h>
#include <TlHelp32.h>
#include <strsafe.h>
#define DLLEXPORT __declspec(dllexport)
BOOL bActionDone = FALSE;
DWORD dwActiveConsoleSessionId;
DWORD getSpoolerPID(void)
{
TCHAR strMsg[1024] = { 0 };
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (TRUE == Process32First(snapshot, &entry))
{
while (TRUE == Process32Next(snapshot, &entry))
{
if (0 == _tcscmp(entry.szExeFile, _T("spoolsv.exe")))
{
_stprintf_s(strMsg, _countof(strMsg), _T("Spooler PID found: %d"), entry.th32ProcessID);
OutputDebugString(strMsg);
CloseHandle(snapshot);
return entry.th32ProcessID;
}
}
}
CloseHandle(snapshot);
return 0;
}
DWORD getWinlogonPID(void)
{
TCHAR strMsg[1024] = { 0 };
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (TRUE == Process32First(snapshot, &entry))
{
while (TRUE == Process32Next(snapshot, &entry))
{
if (0 == _tcscmp(entry.szExeFile, _T("winlogon.exe")))
{
_stprintf_s(strMsg, _countof(strMsg), _T("Winlogon PID found: %d"), entry.th32ProcessID);
OutputDebugString(strMsg);
CloseHandle(snapshot);
return entry.th32ProcessID;
}
}
}
CloseHandle(snapshot);
return 0;
}
BOOL SetPrivilege(HANDLE hToken, LPCTSTR lpszPrivilege)
{
TOKEN_PRIVILEGES tp;
LUID luid;
BOOL bStatus;
bStatus = LookupPrivilegeValue(NULL, lpszPrivilege, &luid);
if (!bStatus)
{
_tprintf(_T("ERROR: LookupPrivilegeValue() returned %lu\r\n"), GetLastError());
return FALSE;
}
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
bStatus = AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES)NULL, (PDWORD)NULL);
if (!bStatus)
{
_tprintf(_T("ERROR: AdjustTokenPrivileges() returned %lu\r\n"), GetLastError());
return FALSE;
}
if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)
{
_tprintf(_T("ERROR: The token does not have the specified privilege.\r\n"));
return FALSE;
}
return TRUE;
}
DWORD elevateAsWinlogon(void)
{
TCHAR strMsg[1024] = { 0 };
_stprintf_s(strMsg, _countof(strMsg), _T("Entering %hs"), __FUNCTION__);
OutputDebugString(strMsg);
BOOL bStatus;
DWORD dwLastError;
HANDLE currentTokenHandle = NULL;
bStatus = OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, ¤tTokenHandle);
if (!bStatus)
{
_stprintf_s(strMsg, _countof(strMsg), _T("ERROR: OpenProcessToken() returned %lu"), GetLastError());
OutputDebugString(strMsg);
return GetLastError();
}
bStatus = SetPrivilege(currentTokenHandle, SE_DEBUG_NAME);
if (!bStatus)
{
_stprintf_s(strMsg, _countof(strMsg), _T("ERROR: SetPrivilege(SE_DEBUG_NAME) returned %lu"), GetLastError());
OutputDebugString(strMsg);
dwLastError = GetLastError();
CloseHandle(currentTokenHandle);
return dwLastError;
}
bStatus = SetPrivilege(currentTokenHandle, SE_IMPERSONATE_NAME);
if (!bStatus)
{
_stprintf_s(strMsg, _countof(strMsg), _T("ERROR: SetPrivilege(SE_IMPERSONATE_NAME) returned %lu"), GetLastError());
OutputDebugString(strMsg);
dwLastError = GetLastError();
CloseHandle(currentTokenHandle);
return dwLastError;
}
CloseHandle(currentTokenHandle);
HANDLE tokenHandle = NULL;
HANDLE duplicateTokenHandle = NULL;
DWORD pidToImpersonate;
pidToImpersonate = getWinlogonPID();
if (0 == pidToImpersonate)
{
_stprintf_s(strMsg, _countof(strMsg), _T("ERROR: Useful PID was not found."));
OutputDebugString(strMsg);
return ERROR_ERRORS_ENCOUNTERED;
}
HANDLE processHandle;
processHandle = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pidToImpersonate);
if (NULL == processHandle)
{
_stprintf_s(strMsg, _countof(strMsg), _T("ERROR: OpenProcess() returned %lu"), GetLastError());
OutputDebugString(strMsg);
return GetLastError();
}
bStatus = OpenProcessToken(processHandle, TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_ASSIGN_PRIMARY, &tokenHandle);
if (!bStatus)
{
_stprintf_s(strMsg, _countof(strMsg), _T("ERROR: OpenProcessToken returned %lu"), GetLastError());
OutputDebugString(strMsg);
dwLastError = GetLastError();
CloseHandle(processHandle);
return dwLastError;
}
CloseHandle(processHandle);
SECURITY_IMPERSONATION_LEVEL seimp = SecurityImpersonation;
TOKEN_TYPE tk = TokenPrimary;
bStatus = DuplicateTokenEx(tokenHandle, MAXIMUM_ALLOWED, NULL, seimp, tk, &duplicateTokenHandle);
if (!bStatus)
{
_stprintf_s(strMsg, _countof(strMsg), _T("ERROR: DuplicateTokenEx returned %lu"), GetLastError());
OutputDebugString(strMsg);
dwLastError = GetLastError();
CloseHandle(tokenHandle);
return dwLastError;
}
bStatus = SetPrivilege(duplicateTokenHandle, SE_ASSIGNPRIMARYTOKEN_NAME);
if (!bStatus)
{
_stprintf_s(strMsg, _countof(strMsg), _T("ERROR: SetPrivilege(SE_ASSIGNPRIMARYTOKEN_NAME) returned %lu"), GetLastError());
OutputDebugString(strMsg);
dwLastError = GetLastError();
CloseHandle(duplicateTokenHandle);
CloseHandle(tokenHandle);
return dwLastError;
}
bStatus = ImpersonateLoggedOnUser(duplicateTokenHandle);
if (!bStatus)
{
_stprintf_s(strMsg, _countof(strMsg), _T("ERROR: ImpersonateLoggedOnUser() returned %lu"), GetLastError());
OutputDebugString(strMsg);
dwLastError = GetLastError();
CloseHandle(duplicateTokenHandle);
CloseHandle(tokenHandle);
return dwLastError;
}
CloseHandle(duplicateTokenHandle);
CloseHandle(tokenHandle);
_stprintf_s(strMsg, _countof(strMsg), _T("Elevation successful."));
OutputDebugString(strMsg);
return ERROR_SUCCESS;
}
DWORD elevateAndRunAsSpooler(LPWSTR lpApplicationName)
{
TCHAR strMsg[1024] = { 0 };
_stprintf_s(strMsg, _countof(strMsg), _T("Entering %hs"), __FUNCTION__);
OutputDebugString(strMsg);
BOOL bStatus;
DWORD dwLastError;
HANDLE currentTokenHandle = NULL;
bStatus = OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, ¤tTokenHandle);
if (!bStatus)
{
_stprintf_s(strMsg, _countof(strMsg), _T("ERROR: OpenProcessToken() returned %lu"), GetLastError());
OutputDebugString(strMsg);
return GetLastError();
}
bStatus = SetPrivilege(currentTokenHandle, SE_DEBUG_NAME);
if (!bStatus)
{
_stprintf_s(strMsg, _countof(strMsg), _T("ERROR: SetPrivilege(SE_DEBUG_NAME) returned %lu"), GetLastError());
OutputDebugString(strMsg);
dwLastError = GetLastError();
CloseHandle(currentTokenHandle);
return dwLastError;
}
bStatus = SetPrivilege(currentTokenHandle, SE_IMPERSONATE_NAME);
if (!bStatus)
{
_stprintf_s(strMsg, _countof(strMsg), _T("ERROR: SetPrivilege(SE_IMPERSONATE_NAME) returned %lu"), GetLastError());
OutputDebugString(strMsg);
dwLastError = GetLastError();
CloseHandle(currentTokenHandle);
return dwLastError;
}
CloseHandle(currentTokenHandle);
HANDLE tokenHandle = NULL;
HANDLE duplicateTokenHandle = NULL;
DWORD pidToImpersonate;
pidToImpersonate = getSpoolerPID();
if (0 == pidToImpersonate)
{
_stprintf_s(strMsg, _countof(strMsg), _T("ERROR: Useful PID was not found."));
OutputDebugString(strMsg);
return ERROR_ERRORS_ENCOUNTERED;
}
HANDLE processHandle;
processHandle = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pidToImpersonate);
if (NULL == processHandle)
{
_stprintf_s(strMsg, _countof(strMsg), _T("ERROR: OpenProcess() returned %lu"), GetLastError());
OutputDebugString(strMsg);
return GetLastError();
}
bStatus = OpenProcessToken(processHandle, TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_ASSIGN_PRIMARY, &tokenHandle);
if (!bStatus)
{
_stprintf_s(strMsg, _countof(strMsg), _T("ERROR: OpenProcessToken returned %lu"), GetLastError());
OutputDebugString(strMsg);
dwLastError = GetLastError();
CloseHandle(processHandle);
return dwLastError;
}
CloseHandle(processHandle);
SECURITY_IMPERSONATION_LEVEL seimp = SecurityImpersonation;
TOKEN_TYPE tk = TokenPrimary;
bStatus = DuplicateTokenEx(tokenHandle, MAXIMUM_ALLOWED, NULL, seimp, tk, &duplicateTokenHandle);
if (!bStatus)
{
_stprintf_s(strMsg, _countof(strMsg), _T("ERROR: DuplicateTokenEx returned %lu"), GetLastError());
OutputDebugString(strMsg);
dwLastError = GetLastError();
CloseHandle(tokenHandle);
return dwLastError;
}
bStatus = SetPrivilege(duplicateTokenHandle, SE_ASSIGNPRIMARYTOKEN_NAME);
if (!bStatus)
{
_stprintf_s(strMsg, _countof(strMsg), _T("ERROR: SetPrivilege(SE_ASSIGNPRIMARYTOKEN_NAME) returned %lu"), GetLastError());
OutputDebugString(strMsg);
dwLastError = GetLastError();
CloseHandle(duplicateTokenHandle);
CloseHandle(tokenHandle);
return dwLastError;
}
bStatus = SetPrivilege(duplicateTokenHandle, SE_TCB_NAME);
if (!bStatus)
{
_stprintf_s(strMsg, _countof(strMsg), _T("ERROR: SetPrivilege(SE_TCB_NAME) returned %lu"), GetLastError());
OutputDebugString(strMsg);
dwLastError = GetLastError();
CloseHandle(duplicateTokenHandle);
CloseHandle(tokenHandle);
return dwLastError;
}
bStatus = ImpersonateLoggedOnUser(duplicateTokenHandle);
if (!bStatus)
{
_stprintf_s(strMsg, _countof(strMsg), _T("ERROR: ImpersonateLoggedOnUser() returned %lu"), GetLastError());
OutputDebugString(strMsg);
dwLastError = GetLastError();
CloseHandle(duplicateTokenHandle);
CloseHandle(tokenHandle);
return dwLastError;
}
DWORD dwSessionId;
bStatus = ProcessIdToSessionId(GetCurrentProcessId(), &dwSessionId);
if (!bStatus)
{
_stprintf_s(strMsg, _countof(strMsg), _T("ERROR: ProcessIdToSessionId() returned %lu"), GetLastError());
OutputDebugString(strMsg);
dwLastError = GetLastError();
CloseHandle(duplicateTokenHandle);
CloseHandle(tokenHandle);
return dwLastError;
}
bStatus = SetTokenInformation(duplicateTokenHandle, TokenSessionId, &dwSessionId, sizeof(dwSessionId));
if (!bStatus)
{
_stprintf_s(strMsg, _countof(strMsg), _T("ERROR: SetTokenInformation(TokenSessionId) returned %lu"), GetLastError());
OutputDebugString(strMsg);
dwLastError = GetLastError();
CloseHandle(duplicateTokenHandle);
CloseHandle(tokenHandle);
return dwLastError;
}
_stprintf_s(strMsg, _countof(strMsg), _T("Elevation successful. Launching child process."));
OutputDebugString(strMsg);
PROCESS_INFORMATION pi = { 0 };
STARTUPINFO si = { 0 };
si.cb = sizeof(si);
si.lpDesktop = _T("Winsta0\\Default");
si.wShowWindow = TRUE;
bStatus = CreateProcessAsUserW(duplicateTokenHandle, lpApplicationName, NULL, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
if (!bStatus)
{
_stprintf_s(strMsg, _countof(strMsg), _T("ERROR: CreateProcessAsUser() returned %lu"), GetLastError());
OutputDebugString(strMsg);
return (int)GetLastError();
}
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
CloseHandle(duplicateTokenHandle);
CloseHandle(tokenHandle);
return ERROR_SUCCESS;
}
DLLEXPORT
VOID doIt(void)
{
if (!bActionDone)
{
bActionDone = TRUE;
dwActiveConsoleSessionId = WTSGetActiveConsoleSessionId();
LPWSTR* wszArgList;
int numArgs;
wszArgList = CommandLineToArgvW(GetCommandLineW(), &numArgs);
if (NULL != wszArgList)
{
elevateAsWinlogon();
elevateAndRunAsSpooler(wszArgList[numArgs - 1]);
LocalFree(wszArgList);
}
}
}
#pragma warning( disable : 4104) // ignore warning about private functions - https://docs.microsoft.com/en-us/cpp/error-messages/tool-errors/linker-tools-warning-lnk4104
DLLEXPORT
STDAPI
DllRegisterServer(void)
{
doIt();
return S_OK;
}
DLLEXPORT
STDAPI
DllUnregisterServer(void)
{
doIt();
return S_OK;
}
DLLEXPORT
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
doIt();
return TRUE;
}
|
01b36fe405874a5a861ebc91de50b792828ffaf1
|
d169de4c5c6b281984df35536430dcc931a957a9
|
/source/service/pbuf/vsf_pbuf_pool.c
|
59252c87b06b4af0156a40c2730f183ee6d141b5
|
[
"LGPL-2.1-only",
"Apache-2.0"
] |
permissive
|
vsfteam/vsf
|
2ba968ba2ef53b036668019c6c6746149a63c38a
|
522a52ff2ee4ed149b52789a5bd366f80c08c458
|
refs/heads/master
| 2023-08-27T07:32:08.339123
| 2023-08-26T17:46:07
| 2023-08-26T17:46:07
| 181,911,464
| 273
| 83
|
Apache-2.0
| 2023-08-29T03:08:36
| 2019-04-17T14:43:42
|
C
|
UTF-8
|
C
| false
| false
| 6,496
|
c
|
vsf_pbuf_pool.c
|
/*****************************************************************************
* Copyright(C)2009-2022 by VSF Team *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a 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. *
* *
****************************************************************************/
/*============================ INCLUDES ======================================*/
#include "service/vsf_service_cfg.h"
#if VSF_USE_PBUF == ENABLED
#include "./vsf_pbuf_pool.h"
/*============================ MACROS ========================================*/
/*============================ MACROFIED FUNCTIONS ===========================*/
/*============================ TYPES =========================================*/
/*============================ LOCAL VARIABLES ===============================*/
/*============================ PROTOTYPES ====================================*/
static vsf_pbuf_t * __vsf_stream_src_pbuf_free(void *obj_ptr, vsf_pbuf_t *block_ptr);
/*============================ GLOBAL VARIABLES ==============================*/
const i_pbuf_methods_t VSF_PBUF_ADAPTER_METHODS_STREAM_SRC = {
.Free = &__vsf_stream_src_pbuf_free,
};
/*============================ IMPLEMENTATION ================================*/
static vsf_pbuf_t * __vsf_stream_src_pbuf_free(void *obj_ptr, vsf_pbuf_t *block_ptr)
{
VSF_SERVICE_ASSERT(NULL != obj_ptr);
vsf_pbuf_pool_free( (vsf_pbuf_pool_t *)obj_ptr, block_ptr);
return NULL;
};
void vsf_pbuf_pool_init(vsf_pbuf_pool_t *this_ptr,
uint32_t u32_item_size,
uint_fast16_t u16_align,
vsf_pool_cfg_t *pcfg)
{
vsf_pool_init((vsf_pool_t *)this_ptr, u32_item_size, u16_align, pcfg);
}
bool vsf_pbuf_pool_add_buffer( vsf_pbuf_pool_t *this_ptr,
void *buffer_ptr,
uint_fast32_t u32_size,
uint_fast16_t u16_item_size)
{
if ( (NULL == buffer_ptr)
|| (0 == u32_size)
|| (u16_item_size <sizeof(vsf_pbuf_t))) {
return false;
}
return vsf_pool_add_buffer_ex( (vsf_pool_t *)this_ptr, (uintptr_t)buffer_ptr,
u32_size,
u16_item_size,
vsf_pbuf_pool_item_init_event_handler );
}
vsf_pbuf_t *vsf_pbuf_pool_alloc(vsf_pbuf_pool_t *this_ptr)
{
vsf_pbuf_t *pbuf = (vsf_pbuf_t *)vsf_pool_alloc((vsf_pool_t *)this_ptr);
if (NULL != pbuf) {
vsf_pbuf_size_reset(pbuf);
}
return pbuf;
}
void vsf_pbuf_pool_free(vsf_pbuf_pool_t *this_ptr, vsf_pbuf_t *item_ptr)
{
vsf_pool_free((vsf_pool_t *)this_ptr, (uintptr_t)item_ptr);
}
SECTION(".text." "vsf_pbuf" "_get_pool_item_count")
uint_fast32_t vsf_pbuf_get_pool_item_count(vsf_pbuf_pool_t *this_ptr)
{
return vsf_pool_get_count((vsf_pool_t *)this_ptr);
}
SECTION(".text." "vsf_pbuf" "_pool_get_region")
vsf_protect_region_t *vsf_pbuf_pool_get_region(vsf_pbuf_pool_t *this_ptr)
{
return vsf_pool_get_region((vsf_pool_t *)this_ptr);
}
SECTION(".text." "vsf_pbuf" "_pool_get_target")
uintptr_t vsf_pbuf_pool_get_target(vsf_pbuf_pool_t *this_ptr)
{
return vsf_pool_get_tag((vsf_pool_t *)this_ptr);
}
#endif
|
5efbc3835f1e797a127d87b319e218c81422ba96
|
c6759b857e55991fea3ef0b465dbcee53fa38714
|
/rtos/pmsis/tests/api/quick/periph/aes_dual_core/integration_tests/hyper_ram_aes/test_aes_dual_core_hyper.c
|
665156399a28c4548f9ac77d817c687c841c2d09
|
[
"Apache-2.0"
] |
permissive
|
GreenWaves-Technologies/gap_sdk
|
1b343bba97b7a5ce62a24162bd72eef5cc67e269
|
3fea306d52ee33f923f2423c5a75d9eb1c07e904
|
refs/heads/master
| 2023-09-01T14:38:34.270427
| 2023-08-10T09:04:44
| 2023-08-10T09:04:44
| 133,324,605
| 145
| 96
|
Apache-2.0
| 2023-08-27T19:03:52
| 2018-05-14T07:50:29
|
C
|
UTF-8
|
C
| false
| false
| 2,861
|
c
|
test_aes_dual_core_hyper.c
|
/*
* Copyright (C) 2020 GreenWaves Technologies
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD license. See the LICENSE file for details.
*
*/
#include "pmsis.h"
#include "stdio.h"
#include <bsp/bsp.h>
#include <bsp/ram/hyperram.h>
#define BUFF_SIZE 2048
static uint8_t aes_key_ecb_128[16] = {
0x00, 0x01, 0x02, 0x03,
0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0A, 0x0B,
0x0C, 0x0D, 0x0E, 0x0F,
};
static char *buff[2];
static char *rcv_buff[2];
static uint32_t hyper_buff[2];
static struct pi_device hyper;
int test_entry()
{
printf("Entering main controller (mode: hyperram)\n");
struct pi_hyperram_conf conf;
pi_hyperram_conf_init(&conf);
conf.ram.aes_conf.enabled = 1;
conf.ram.aes_conf.mode = PI_AES_MODE_ECB;
conf.ram.aes_conf.key_len = PI_AES_KEY_128;
conf.ram.aes_conf.key = (uint32_t*) aes_key_ecb_128;
conf.ram.aes_conf.iv = NULL;
for (int i=0; i<2; i++)
{
buff[i] = pmsis_l2_malloc(BUFF_SIZE);
if (buff[i] == NULL)
{
return 1;
}
rcv_buff[i] = pmsis_l2_malloc(BUFF_SIZE);
if (rcv_buff[i] == NULL)
{
return 2;
}
}
pi_open_from_conf(&hyper, &conf);
if (pi_ram_open(&hyper))
{
return 3;
}
if (pi_ram_alloc(&hyper, &hyper_buff[0], BUFF_SIZE))
{
return 4;
}
if (pi_ram_alloc(&hyper, &hyper_buff[1], BUFF_SIZE))
{
return 5;
}
for (int i=0; i<BUFF_SIZE; i++)
{
buff[0][i] = i & 0x7f;
buff[1][i] = i | 0x80;
}
printf("Writing data (on-the-fly encryption)\n");
pi_ram_write(&hyper, hyper_buff[0], buff[0], BUFF_SIZE);
pi_ram_write(&hyper, hyper_buff[1], buff[1], BUFF_SIZE);
printf("Reading data (on-the-fly decryption)\n");
pi_ram_read(&hyper, hyper_buff[0], rcv_buff[0], BUFF_SIZE);
pi_ram_read(&hyper, hyper_buff[1], rcv_buff[1], BUFF_SIZE);
printf("Verifying data\n");
for (int j=0; j<2; j++)
{
for (int i=0; i<BUFF_SIZE; i++)
{
unsigned char expected;
if (j == 0)
{
expected = i & 0x7f;
}
else
{
expected = i | 0x80;
}
if (expected != rcv_buff[j][i])
{
printf("Error, buffer: %d, index: %d, expected: 0x%x, read: 0x%x\n", j, i, expected, rcv_buff[j][i]);
return 6;
}
}
}
pi_ram_free(&hyper, hyper_buff[0], BUFF_SIZE);
pi_ram_free(&hyper, hyper_buff[1], BUFF_SIZE);
pi_ram_close(&hyper);
printf("TEST SUCCESS\n");
return 0;
}
void test_kickoff(void *arg)
{
int ret = test_entry();
pmsis_exit(ret);
}
int main()
{
return pmsis_kickoff((void *)test_kickoff);
}
|
f8c8ed2c9c0d88540674f812d67afb1405a11290
|
ac2f43c8e0d9649a7f063c59b3dffdfed9fd7ed7
|
/common/recipes-core/asd_1.4.3/files/daemon/jtag_handler.c
|
f2d66a38713aad833936f874da8d17ee911af29d
|
[
"BSD-3-Clause"
] |
permissive
|
facebook/openbmc
|
bef10604ced226288600f55248b7f1be9945aea4
|
32777c66a8410d767eae15baabf71c61a0bef13c
|
refs/heads/helium
| 2023-08-17T03:13:54.729494
| 2023-08-16T23:24:18
| 2023-08-16T23:24:18
| 31,917,712
| 684
| 331
| null | 2023-07-25T21:19:08
| 2015-03-09T19:18:35
|
C
|
UTF-8
|
C
| false
| false
| 16,312
|
c
|
jtag_handler.c
|
/*
Copyright (c) 2019, Intel Corporation
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "jtag_handler.h"
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include "logging.h"
#include "mem_helper.h"
static const ASD_LogStream stream = ASD_LogStream_JTAG;
static const ASD_LogOption option = ASD_LogOption_None;
static const char* JtagStatesString[] = {
"TLR", "RTI", "SelDR", "CapDR", "ShfDR", "Ex1DR", "PauDR", "Ex2DR",
"UpdDR", "SelIR", "CapIR", "ShfIR", "Ex1IR", "PauIR", "Ex2IR", "UpdIR"};
#ifdef JTAG_LEGACY_DRIVER
STATUS JTAG_clock_cycle(int handle, unsigned char tms, unsigned char tdi);
#endif
STATUS perform_shift(JTAG_Handler* state, unsigned int number_of_bits,
unsigned int input_bytes, unsigned char* input,
unsigned int output_bytes, unsigned char* output,
enum jtag_states current_tap_state,
enum jtag_states end_tap_state);
void initialize_jtag_chains(JTAG_Handler* state)
{
for (int i = 0; i < MAX_SCAN_CHAINS; i++)
{
state->chains[i].shift_padding.drPre = 0;
state->chains[i].shift_padding.drPost = 0;
state->chains[i].shift_padding.irPre = 0;
state->chains[i].shift_padding.irPost = 0;
state->chains[i].tap_state = jtag_tlr;
state->chains[i].scan_state = JTAGScanState_Done;
}
}
JTAG_Handler* JTAGHandler()
{
JTAG_Handler* state = (JTAG_Handler*)malloc(sizeof(JTAG_Handler));
if (state == NULL)
{
return NULL;
}
state->active_chain = &state->chains[SCAN_CHAIN_0];
initialize_jtag_chains(state);
state->sw_mode = true;
memset(state->padDataOne, ~0, sizeof(state->padDataOne));
memset(state->padDataZero, 0, sizeof(state->padDataZero));
state->JTAG_driver_handle = -1;
for (unsigned int i = 0; i < MAX_WAIT_CYCLES; i++)
{
state->bitbang_data[i].tms = 0;
state->bitbang_data[i].tdi = 0;
}
return state;
}
STATUS init_passthrough_path(void *state, uint8_t fru,
STATUS (*send_back_to_client)(void* state, unsigned char* buffer, size_t length)) {
return ST_ERR;
}
#ifdef JTAG_LEGACY_DRIVER
STATUS JTAG_clock_cycle(int handle, unsigned char tms, unsigned char tdi)
{
struct tck_bitbang bitbang = {0};
bitbang.tms = tms;
bitbang.tdi = tdi;
if (ioctl(handle, AST_JTAG_BITBANG, &bitbang) < 0)
{
ASD_log(ASD_LogLevel_Error, stream, option,
"ioctl AST_JTAG_BITBANG failed");
return ST_ERR;
}
return ST_OK;
}
#endif
STATUS JTAG_initialize(JTAG_Handler* state, bool sw_mode)
{
#ifndef JTAG_LEGACY_DRIVER
struct jtag_mode jtag_mode;
#endif
if (state == NULL)
return ST_ERR;
state->sw_mode = (state->force_jtag_hw) ? false : sw_mode;
ASD_log(ASD_LogLevel_Info, stream, option, "JTAG mode set to '%s'.",
state->sw_mode ? "software" : "hardware");
#ifdef JTAG_LEGACY_DRIVER
state->JTAG_driver_handle = open("/dev/jtag", O_RDWR);
#else
state->JTAG_driver_handle = open("/dev/jtag0", O_RDWR);
#endif
if (state->JTAG_driver_handle == -1)
{
ASD_log(ASD_LogLevel_Error, stream, option,
"Can't open /dev/jtag, please install driver");
return ST_ERR;
}
#ifndef JTAG_LEGACY_DRIVER
jtag_mode.feature = JTAG_XFER_MODE;
jtag_mode.mode = sw_mode ? JTAG_XFER_SW_MODE : JTAG_XFER_HW_MODE;
if (ioctl(state->JTAG_driver_handle, JTAG_SIOCMODE, &jtag_mode))
{
ASD_log(ASD_LogLevel_Error, stream, option,
"Failed JTAG_SIOCMODE to set xfer mode");
close(state->JTAG_driver_handle);
state->JTAG_driver_handle = -1;
return ST_ERR;
}
#endif
if (JTAG_set_tap_state(state, jtag_tlr) != ST_OK)
{
ASD_log(ASD_LogLevel_Error, stream, option,
"Failed to reset tap state.");
close(state->JTAG_driver_handle);
state->JTAG_driver_handle = -1;
return ST_ERR;
}
initialize_jtag_chains(state);
return ST_OK;
}
STATUS JTAG_deinitialize(JTAG_Handler* state)
{
if (state == NULL)
return ST_ERR;
close(state->JTAG_driver_handle);
state->JTAG_driver_handle = -1;
return ST_OK;
}
STATUS JTAG_set_padding(JTAG_Handler* state, const JTAGPaddingTypes padding,
const unsigned int value)
{
if (state == NULL)
return ST_ERR;
if ((padding == JTAGPaddingTypes_DRPre ||
padding == JTAGPaddingTypes_DRPost) &&
value > DRMAXPADSIZE)
{
return ST_ERR;
}
if ((padding == JTAGPaddingTypes_IRPre ||
padding == JTAGPaddingTypes_IRPost) &&
value > IRMAXPADSIZE)
{
return ST_ERR;
}
if (padding == JTAGPaddingTypes_DRPre)
{
state->active_chain->shift_padding.drPre = value;
}
else if (padding == JTAGPaddingTypes_DRPost)
{
state->active_chain->shift_padding.drPost = value;
}
else if (padding == JTAGPaddingTypes_IRPre)
{
state->active_chain->shift_padding.irPre = value;
}
else if (padding == JTAGPaddingTypes_IRPost)
{
state->active_chain->shift_padding.irPost = value;
}
else
{
ASD_log(ASD_LogLevel_Error, stream, option, "Unknown padding value: %d",
value);
return ST_ERR;
}
return ST_OK;
}
//
// Reset the Tap and wait in idle state
//
STATUS JTAG_tap_reset(JTAG_Handler* state)
{
if (state == NULL)
return ST_ERR;
return JTAG_set_tap_state(state, jtag_tlr);
}
//
// Request the TAP to go to the target state
//
STATUS JTAG_set_tap_state(JTAG_Handler* state, enum jtag_states tap_state)
{
if (state == NULL)
return ST_ERR;
#ifdef JTAG_LEGACY_DRIVER
struct tap_state_param params;
params.mode = state->sw_mode ? SW_MODE : HW_MODE;
params.from_state = state->active_chain->tap_state;
params.to_state = tap_state;
#else
struct jtag_tap_state tap_state_t;
tap_state_t.endstate = tap_state;
tap_state_t.reset =
(tap_state == jtag_tlr) ? JTAG_FORCE_RESET : JTAG_NO_RESET;
tap_state_t.tck = 1;
#endif
#ifdef JTAG_LEGACY_DRIVER
if (ioctl(state->JTAG_driver_handle, AST_JTAG_SET_TAPSTATE, ¶ms)
#else
if (ioctl(state->JTAG_driver_handle, JTAG_SIOCSTATE, &tap_state_t)
#endif
< 0)
{
ASD_log(ASD_LogLevel_Error, stream, option,
"ioctl AST_JTAG_SET_TAPSTATE failed");
return ST_ERR;
}
state->active_chain->tap_state = tap_state;
if ((tap_state == jtag_rti) || (tap_state == jtag_pau_dr))
if (JTAG_wait_cycles(state, 5) != ST_OK)
return ST_ERR;
ASD_log(ASD_LogLevel_Info, stream, option, "Goto state: %s (%d)",
tap_state >=
(sizeof(JtagStatesString) / sizeof(JtagStatesString[0]))
? "Unknown"
: JtagStatesString[tap_state],
tap_state);
return ST_OK;
}
//
// Retrieve the current the TAP state
//
STATUS JTAG_get_tap_state(JTAG_Handler* state, enum jtag_states* tap_state)
{
if (state == NULL || tap_state == NULL)
return ST_ERR;
*tap_state = state->active_chain->tap_state;
return ST_OK;
}
//
// Optionally write and read the requested number of
// bits and go to the requested target state
//
STATUS JTAG_shift(JTAG_Handler* state, unsigned int number_of_bits,
unsigned int input_bytes, unsigned char* input,
unsigned int output_bytes, unsigned char* output,
enum jtag_states end_tap_state)
{
if (state == NULL)
return ST_ERR;
unsigned int preFix = 0;
unsigned int postFix = 0;
unsigned char* padData = NULL;
enum jtag_states current_state;
JTAG_get_tap_state(state, ¤t_state);
if (current_state == jtag_shf_ir)
{
preFix = state->active_chain->shift_padding.irPre;
postFix = state->active_chain->shift_padding.irPost;
padData = state->padDataOne;
}
else if (current_state == jtag_shf_dr)
{
preFix = state->active_chain->shift_padding.drPre;
postFix = state->active_chain->shift_padding.drPost;
padData = state->padDataZero;
}
else
{
ASD_log(ASD_LogLevel_Error, stream, option,
"Shift called but the tap is not in a ShiftIR/DR tap state");
return ST_ERR;
}
if (state->active_chain->scan_state == JTAGScanState_Done)
{
state->active_chain->scan_state = JTAGScanState_Run;
if (preFix)
{
if (perform_shift(state, preFix, IRMAXPADSIZE / 8, padData, 0, NULL,
current_state, current_state) != ST_OK)
return ST_ERR;
}
}
if ((postFix) && (current_state != end_tap_state))
{
state->active_chain->scan_state = JTAGScanState_Done;
if (perform_shift(state, number_of_bits, input_bytes, input,
output_bytes, output, current_state,
current_state) != ST_OK)
return ST_ERR;
if (perform_shift(state, postFix, IRMAXPADSIZE / 8, padData, 0, NULL,
current_state, end_tap_state) != ST_OK)
return ST_ERR;
}
else
{
if (perform_shift(state, number_of_bits, input_bytes, input,
output_bytes, output, current_state,
end_tap_state) != ST_OK)
return ST_ERR;
if (current_state != end_tap_state)
{
state->active_chain->scan_state = JTAGScanState_Done;
}
}
return ST_OK;
}
//
// Optionally write and read the requested number of
// bits and go to the requested target state
//
STATUS perform_shift(JTAG_Handler* state, unsigned int number_of_bits,
unsigned int input_bytes, unsigned char* input,
unsigned int output_bytes, unsigned char* output,
enum jtag_states current_tap_state,
enum jtag_states end_tap_state)
{
#ifdef JTAG_LEGACY_DRIVER
struct scan_xfer scan_xfer;
scan_xfer.mode = state->sw_mode ? SW_MODE : HW_MODE;
scan_xfer.tap_state = current_tap_state;
scan_xfer.length = number_of_bits;
scan_xfer.tdi_bytes = input_bytes;
scan_xfer.tdi = input;
scan_xfer.tdo_bytes = output_bytes;
scan_xfer.tdo = output;
scan_xfer.end_tap_state = end_tap_state;
if (ioctl(state->JTAG_driver_handle, AST_JTAG_READWRITESCAN, &scan_xfer) <
0)
{
ASD_log(ASD_LogLevel_Error, stream, option,
"ioctl AST_JTAG_READWRITESCAN failed.");
return ST_ERR;
}
#else
struct jtag_xfer xfer;
unsigned char tdio[MAX_DATA_SIZE];
xfer.endstate = end_tap_state;
xfer.type =
(current_tap_state == jtag_shf_ir) ? JTAG_SIR_XFER : JTAG_SDR_XFER;
xfer.length = number_of_bits;
xfer.direction = JTAG_READ_WRITE_XFER;
if (output != NULL)
{
if (memcpy_safe(output, output_bytes, input,
DIV_ROUND_UP(number_of_bits, BITS_PER_BYTE)))
{
ASD_log(ASD_LogLevel_Error, stream, option,
"memcpy_safe: input to output copy buffer failed.");
}
xfer.tdio = (__u64)(uintptr_t)output;
}
else
{
if (memcpy_safe(tdio, DIV_ROUND_UP(number_of_bits, BITS_PER_BYTE),
input, DIV_ROUND_UP(number_of_bits, BITS_PER_BYTE)))
{
ASD_log(ASD_LogLevel_Error, stream, option,
"memcpy_safe: input to tdio buffer copy failed.");
}
xfer.tdio = (__u64)(uintptr_t)tdio;
}
if (ioctl(state->JTAG_driver_handle, JTAG_IOCXFER, &xfer) < 0)
{
ASD_log(ASD_LogLevel_Error, stream, option,
"ioctl JTAG_IOCXFER failed");
return ST_ERR;
}
#endif
state->active_chain->tap_state = end_tap_state;
#ifdef ENABLE_DEBUG_LOGGING
if (input != NULL)
ASD_log_shift(ASD_LogLevel_Debug, stream, option, number_of_bits,
input_bytes, input,
(current_tap_state == jtag_shf_dr) ? "Shift DR TDI"
: "Shift IR TDI");
if (output != NULL)
ASD_log_shift(ASD_LogLevel_Debug, stream, option, number_of_bits,
output_bytes, output,
(current_tap_state == jtag_shf_dr) ? "Shift DR TDO"
: "Shift IR TDO");
#endif
return ST_OK;
}
//
// Wait for the requested cycles.
//
// Note: It is the responsibility of the caller to make sure that
// this call is made from RTI, PauDR, PauIR states only. Otherwise
// will have side effects !!!
//
STATUS JTAG_wait_cycles(JTAG_Handler* state, unsigned int number_of_cycles)
{
#ifdef JTAG_LEGACY_DRIVER
if (state == NULL)
return ST_ERR;
if (state->sw_mode)
{
for (unsigned int i = 0; i < number_of_cycles; i++)
{
if (JTAG_clock_cycle(state->JTAG_driver_handle, 0, 0) != ST_OK)
return ST_ERR;
}
}
#else
if (state == NULL)
return ST_ERR;
if (number_of_cycles > MAX_WAIT_CYCLES)
return ST_ERR;
if (state->sw_mode)
{
for (unsigned int i = 0; i < number_of_cycles; i++)
{
if (ioctl(state->JTAG_driver_handle, JTAG_IOCBITBANG, &state->bitbang_data[i]) < 0)
{
ASD_log(ASD_LogLevel_Error, stream, option,
"ioctl JTAG_IOCBITBANG failed");
return ST_ERR;
}
}
}
#endif
return ST_OK;
}
STATUS JTAG_set_jtag_tck(JTAG_Handler* state, unsigned int tck)
{
if (state == NULL)
return ST_ERR;
#ifdef JTAG_LEGACY_DRIVER
struct set_tck_param params;
params.mode = state->sw_mode ? SW_MODE : HW_MODE;
params.tck = tck;
if (ioctl(state->JTAG_driver_handle, AST_JTAG_SET_TCK, ¶ms) < 0)
{
ASD_log(ASD_LogLevel_Error, stream, option,
"ioctl AST_JTAG_SET_TCK failed");
return ST_ERR;
}
#else
unsigned int frq = APB_FREQ / tck;
if (ioctl(state->JTAG_driver_handle, JTAG_SIOCFREQ, &frq) < 0)
{
ASD_log(ASD_LogLevel_Error, stream, option,
"ioctl JTAG_SIOCFREQ failed");
return ST_ERR;
}
#endif
return ST_OK;
}
STATUS JTAG_set_active_chain(JTAG_Handler* state, scanChain chain)
{
if (state == NULL)
return ST_ERR;
if (chain < 0 || chain >= MAX_SCAN_CHAINS)
{
ASD_log(ASD_LogLevel_Error, stream, option, "Invalid scan chain.");
return ST_ERR;
}
state->active_chain = &state->chains[chain];
return ST_OK;
}
|
f316c4f1a19d1a3334a1b9797ddab8e41089d507
|
03b2c80dbc41e904b167d504666e27d798da5447
|
/develop/windows/windows_values.c
|
45e924ee59b1b7ee555c39908d5f4388544d6d2d
|
[
"Unlicense"
] |
permissive
|
nptcl/npt
|
7c1570b497cdce0b8971cb445fbc04cb500232d3
|
aa714a2370ac9fa5348c2fc96159b40b9de3de07
|
refs/heads/master
| 2023-03-20T09:13:54.669118
| 2022-07-02T11:17:44
| 2022-07-02T11:17:44
| 171,985,905
| 160
| 12
|
Unlicense
| 2023-03-11T01:36:37
| 2019-02-22T03:11:34
|
C
|
UTF-8
|
C
| false
| false
| 6,152
|
c
|
windows_values.c
|
#include "bignum.h"
#include "condition.h"
#include "cons.h"
#include "execute_values.h"
#include "integer.h"
#include "strtype.h"
#include "terme_escape.h"
#include "typedef.h"
#include "windows_arch.h"
#include "windows_values.h"
#include "windows_window.h"
static int windows_values_single_(addr cons, addr *ret)
{
addr check;
Return_getcons(cons, ret, &check);
if (check != Nil)
return fmte_("Too many arguments, ~S.", cons, NULL);
return 0;
}
static int windows_values_show_(Execute ptr, addr args)
{
int check;
/* nil */
if (args == Nil)
goto mode_default;
/* :default */
Return(windows_values_single_(args, &args));
Return(string_designator_equalp_char_(args, "default", &check));
if (check)
goto mode_default;
/* :show */
Return(string_designator_equalp_char_(args, "show", &check));
if (check)
goto mode_show;
/* :hide */
Return(string_designator_equalp_char_(args, "hide", &check));
if (check)
goto mode_hide;
/* error */
return fmte_("Invalid show mode, ~S.", args, NULL);
mode_default:
if (windows_window_show_default())
return fmte_("show-window default error.", NULL);
setresult_control(ptr, T);
return 0;
mode_show:
if (windows_window_show_show())
return fmte_("show-window show error.", NULL);
setresult_control(ptr, T);
return 0;
mode_hide:
if (windows_window_show_hide())
return fmte_("show-window hide error.", NULL);
setresult_control(ptr, T);
return 0;
}
static int windows_values_size_(Execute ptr, addr args)
{
int s;
unsigned x0, y0, x, y;
addr v1, v2;
/* empty */
getwidth_windows(&x0, &y0);
x = x0;
y = y0;
if (args == Nil)
goto finish;
Return_getcons(args, &v1, &args);
Return(windows_values_single_(args, &v2));
if (v1 == Nil && v2 == Nil)
return 0;
if (v1 != Nil) {
Return(getint_unsigned_(v1, &s));
x = (unsigned)s;
}
if (v2 != Nil) {
Return(getint_unsigned_(v2, &s));
y = (unsigned)s;
}
if (x == x0 && y == y0)
goto finish;
if (windows_window_size_update(x, y))
return fmte_("windows_window_size_update error", NULL);
finish:
fixnum_heap(&v1, (fixnum)x);
fixnum_heap(&v2, (fixnum)y);
setvalues_control(ptr, v1, v2, NULL);
return 0;
}
static int windows_values_font_(Execute ptr, addr args)
{
/* (terme 'windows 'font name &optional size) */
int value;
addr list, name, size;
Return_getcons(args, &name, &args);
if (args == Nil) {
size = Nil;
value = -1;
}
else {
Return_getcons(args, &size, &list);
if (list != Nil)
return fmte_("Invalid arguments, ~S.", list, NULL);
Return(getint_unsigned_(size, &value));
}
Return(windows_window_setfont_(name, value));
setresult_control(ptr, Nil);
return 0;
}
static int windows_values_color_integer_(addr x, int forep)
{
int v;
Return(getint_signed_(x, &v));
if (v < 0 || 0xFF < v)
return fmte_("Value ~S must be a integer between 0 and 0xFF.", x, NULL);
return windows_window_color_integer_((unsigned)v, forep);
}
static int windows_values_color_rgb_(addr x, addr y, addr z, int forep)
{
int r, g, b;
Return(getint_signed_(x, &r));
if (r < 0 || 0xFF < r)
return fmte_("Value ~S must be a integer between 0 and 0xFF.", x, NULL);
Return(getint_signed_(y, &g));
if (g < 0 || 0xFF < g)
return fmte_("Value ~S must be a integer between 0 and 0xFF.", y, NULL);
Return(getint_signed_(z, &b));
if (b < 0 || 0xFF < b)
return fmte_("Value ~S must be a integer between 0 and 0xFF.", b, NULL);
return windows_window_color_rgb_(
(unsigned)r,
(unsigned)g,
(unsigned)b,
forep);
}
static int windows_values_color_symbol_(Execute ptr, addr x, int forep)
{
int value, bright;
/* color */
Return(terme_color_symbol_(ptr, x, &value, &bright));
if (0 <= value) {
if (bright)
value += 8;
return windows_window_color_integer_(value, forep);
}
/* not */
Return(terme_color_not_symbol_(ptr, x, &value, &bright));
if (0 <= value) {
if (! bright)
value += 8;
return windows_window_color_integer_(value, forep);
}
/* dark */
Return(terme_color_dark_(x, &value));
if (0 <= value)
return windows_window_color_integer_(value, forep);
/* bright */
Return(terme_color_bright_(x, &value));
if (0 <= value)
return windows_window_color_integer_(value + 8, forep);
/* error */
return fmte_("Invalid argument, ~S.", x, NULL);
}
static int windows_values_color_(Execute ptr, addr args, int forep)
{
/* (terme 'windows 'color1 x &optional y z) */
addr x, y, z;
x = y = z = Nil;
Return_getcons(args, &x, &args);
if (args != Nil) {
Return_getcons(args, &y, &args);
if (args != Nil) {
Return_getcons(args, &z, &args);
if (args != Nil)
return fmte_("Invalid arguments, ~S.", args, NULL);
}
}
/* integer */
if (y == Nil && z == Nil) {
if (integerp(x))
return windows_values_color_integer_(x, forep);
else
return windows_values_color_symbol_(ptr, x, forep);
}
if (integerp(x) && integerp(y) && integerp(z))
return windows_values_color_rgb_(x, y, z, forep);
return fmte_("Invalid arguments, ~S, ~S, ~S.", x, y, z, NULL);
}
static int windows_values_color1_(Execute ptr, addr args)
{
return windows_values_color_(ptr, args, 1);
}
static int windows_values_color2_(Execute ptr, addr args)
{
return windows_values_color_(ptr, args, 0);
}
int windows_values_(Execute ptr, addr var, addr args, int *ret)
{
int check;
/* windows */
Return(string_designator_equalp_char_(var, "windows", &check));
if (! check)
return Result(ret, 0);
Return_getcons(args, &var, &args);
*ret = 1;
/* :show */
Return(string_designator_equalp_char_(var, "show", &check));
if (check)
return windows_values_show_(ptr, args);
/* :size */
Return(string_designator_equalp_char_(var, "size", &check));
if (check)
return windows_values_size_(ptr, args);
/* :font */
Return(string_designator_equalp_char_(var, "font", &check));
if (check)
return windows_values_font_(ptr, args);
/* :color1 */
Return(string_designator_equalp_char_(var, "color1", &check));
if (check)
return windows_values_color1_(ptr, args);
/* :color2 */
Return(string_designator_equalp_char_(var, "color2", &check));
if (check)
return windows_values_color2_(ptr, args);
/* error */
return Result(ret, 0);
}
|
ab74dea1c46a7023c6f9e2b4934fbeed44baec31
|
149130c794a9fa7112139b2204a2852be261374c
|
/threads.c
|
d3996c550a76f9c95f42470272e414d41cd51896
|
[
"ISC"
] |
permissive
|
tycho/cpuid
|
3a3b802a349f4c18822280929872806fe52bee12
|
d4beadba5a55c641ac46cc1f61ce450687bb721d
|
refs/heads/master
| 2023-06-07T10:23:39.350891
| 2023-05-23T20:21:18
| 2023-05-23T20:39:29
| 2,156,897
| 150
| 49
|
ISC
| 2021-10-19T19:32:45
| 2011-08-04T20:31:16
|
C
|
UTF-8
|
C
| false
| false
| 6,989
|
c
|
threads.c
|
/*
* CPUID
*
* A simple and small tool to dump/decode CPUID information.
*
* Copyright (c) 2010-2021, Steven Noonan <steven@uplinklabs.net>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "prefix.h"
#include <stdio.h>
#define MAX_CPUS 1024
#ifdef TARGET_OS_LINUX
#include <pthread.h>
#include <sched.h>
#include <string.h>
#define CPUSET_T cpu_set_t
#define CPUSET_MASK_T __cpu_mask
#elif defined(TARGET_OS_FREEBSD)
#include <pthread.h>
#include <pthread_np.h>
#include <sys/param.h>
#include <sys/cpuset.h>
#define CPUSET_T cpuset_t
#define CPUSET_MASK_T long
#undef MAX_CPUS
#define MAX_CPUS CPU_MAXSIZE
#elif defined(TARGET_OS_NETBSD)
#include <pthread.h>
#include <sched.h>
#elif defined(TARGET_OS_SOLARIS)
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/processor.h>
#include <sys/procset.h>
#elif defined(TARGET_OS_MACOSX)
#include <sys/sysctl.h>
/*#define USE_CHUD*/
#ifdef USE_CHUD
extern int chudProcessorCount(void);
extern int utilBindThreadToCPU(int n);
extern int utilUnbindThreadFromCPU(void);
#endif
#endif
#include "state.h"
#include "util.h"
#ifdef TARGET_OS_WINDOWS
#if _WIN32_WINNT < 0x0601
typedef WORD(WINAPI *fnGetActiveProcessorGroupCount)(void);
typedef DWORD(WINAPI *fnGetActiveProcessorCount)(WORD);
typedef BOOL(WINAPI *fnSetThreadGroupAffinity)(HANDLE, const GROUP_AFFINITY *, PGROUP_AFFINITY);
static fnGetActiveProcessorGroupCount GetActiveProcessorGroupCount;
static fnGetActiveProcessorCount GetActiveProcessorCount;
static fnSetThreadGroupAffinity SetThreadGroupAffinity;
#endif
#endif
void thread_init_native(void)
{
#ifdef TARGET_OS_WINDOWS
#if _WIN32_WINNT < 0x0601
HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-function-type"
#endif
GetActiveProcessorGroupCount = (fnGetActiveProcessorGroupCount)GetProcAddress(hKernel32, "GetActiveProcessorGroupCount");
GetActiveProcessorCount = (fnGetActiveProcessorCount)GetProcAddress(hKernel32, "GetActiveProcessorCount");
SetThreadGroupAffinity = (fnSetThreadGroupAffinity)GetProcAddress(hKernel32, "SetThreadGroupAffinity");
#if defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
#endif
#endif
}
uint32_t thread_count_native(struct cpuid_state_t *state)
{
#if defined(TARGET_OS_MACOSX)
uint32_t count;
size_t size = sizeof(count);
if (sysctlbyname("hw.ncpu", &count, &size, NULL, 0))
return 1;
return count;
#elif defined(TARGET_OS_SOLARIS)
long count;
if ((count = sysconf(_SC_NPROCESSORS_ONLN)) == -1)
return 1;
(void)state;
return (uint32_t)count;
#else
static unsigned int i = 0;
if (i) return i;
if (thread_bind_native(state, 0) != 0) {
fprintf(stderr, "ERROR: thread_bind() doesn't appear to be working correctly.\n");
abort();
}
while (thread_bind_native(state, ++i) == 0);
return i;
#endif
}
void thread_init_stub(void)
{
}
uint32_t thread_count_stub(struct cpuid_state_t *state)
{
assert(state);
return state->cpu_logical_count;
}
int thread_bind_native(__unused_variable struct cpuid_state_t *state, uint32_t id)
{
#ifdef TARGET_OS_WINDOWS
BOOL ret = FALSE;
HANDLE hThread = GetCurrentThread();
#if _WIN32_WINNT < 0x0601
if (is_windows7_or_greater()) {
#endif
DWORD threadsInGroup = 0;
WORD groupId, groupCount;
GROUP_AFFINITY affinity;
ZeroMemory(&affinity, sizeof(GROUP_AFFINITY));
groupCount = GetActiveProcessorGroupCount();
for (groupId = 0; groupId < groupCount; groupId++) {
threadsInGroup = GetActiveProcessorCount(groupId);
if (id < threadsInGroup)
break;
id -= threadsInGroup;
}
if (groupId < groupCount && id < threadsInGroup) {
affinity.Group = groupId;
affinity.Mask = 1ULL << id;
ret = SetThreadGroupAffinity(hThread, &affinity, NULL);
}
#if _WIN32_WINNT < 0x0601
} else {
DWORD mask;
if (id > 32)
return 1;
mask = (1 << id);
ret = SetThreadAffinityMask(hThread, mask);
}
#endif
if (state && ret != FALSE)
state->cpu_bound_index = id;
return (ret != FALSE) ? 0 : 1;
#elif defined(TARGET_OS_LINUX) || defined(TARGET_OS_FREEBSD)
int ret;
#ifdef CPU_SET_S
size_t setsize = CPU_ALLOC_SIZE(MAX_CPUS);
CPUSET_T *set = CPU_ALLOC(MAX_CPUS);
pthread_t pth;
pth = pthread_self();
CPU_ZERO_S(setsize, set);
CPU_SET_S(id, setsize, set);
ret = pthread_setaffinity_np(pth, setsize, set);
CPU_FREE(set);
#else
size_t bits_per_set = sizeof(CPUSET_T) * 8;
size_t bits_per_subset = sizeof(CPUSET_MASK_T) * 8;
size_t setsize = sizeof(CPUSET_T) * (MAX_CPUS / bits_per_set);
size_t set_id, subset_id;
unsigned long long mask;
CPUSET_T *set = malloc(setsize);
pthread_t pth;
pth = pthread_self();
for (set_id = 0; set_id < (MAX_CPUS / bits_per_set); set_id++)
CPU_ZERO(&set[set_id]);
set_id = id / bits_per_set;
id %= bits_per_set;
subset_id = id / bits_per_subset;
id %= bits_per_subset;
mask = 1ULL << (unsigned long long)id;
((unsigned long *)set[set_id].__bits)[subset_id] |= mask;
ret = pthread_setaffinity_np(pth, setsize, set);
free(set);
#endif
if (state && ret == 0)
state->cpu_bound_index = id;
return (ret == 0) ? 0 : 1;
#elif defined (TARGET_OS_NETBSD)
cpuset_t *set;
int ret;
set = cpuset_create();
if (set == NULL)
return 1;
cpuset_zero(set);
ret = cpuset_set(id, set);
if (ret == -1)
return 1;
ret = pthread_setaffinity_np(pthread_self(), cpuset_size(set), set);
cpuset_destroy(set);
if (state && ret == 0)
state->cpu_bound_index = id;
return ret == 0 ? 0 : 1;
#elif defined(TARGET_OS_SOLARIS)
/*
* This requires permissions, so can easily fail.
*/
if (processor_bind(P_LWPID, P_MYID, id, NULL) != 0) {
fprintf(stderr, "warning: failed to bind to CPU%u: %s\n",
id, strerror(errno));
return 1;
}
if (state)
state->cpu_bound_index = id;
return 0;
#elif defined(TARGET_OS_MACOSX)
int ret = 1;
#ifdef USE_CHUD
ret = (utilBindThreadToCPU(id) == 0) ? 0 : 1;
#endif
if (state && ret == 0)
state->cpu_bound_index = id;
return ret == 0 ? 0 : 1;
#else
#error "thread_bind_native() not defined for this platform"
#endif
}
int thread_bind_stub(struct cpuid_state_t *state, uint32_t id)
{
assert(state);
assert(id < state->cpu_logical_count);
state->cpu_bound_index = id;
return 0;
}
/* vim: set ts=4 sts=4 sw=4 noet: */
|
59f27424861083e5bb5c8b5a8447a47d78002485
|
85ccd32aa73eecf274a937f1fc3b6f4d484b77da
|
/manual tests/5 rpm/main.c
|
8b1d193ee978c757b321ca7ab0a1d348fef29083
|
[
"Apache-2.0"
] |
permissive
|
mesonbuild/meson
|
48321cf4235dfcc0194fed90ff43a57367592bf7
|
cf5adf0c646474f0259d123fad60ca5ed38ec891
|
refs/heads/master
| 2023-09-01T05:58:50.807952
| 2023-03-17T20:27:37
| 2023-08-31T11:52:41
| 19,784,232
| 5,122
| 1,848
|
Apache-2.0
| 2023-09-14T15:47:23
| 2014-05-14T15:08:16
|
Python
|
UTF-8
|
C
| false
| false
| 111
|
c
|
main.c
|
#include<lib.h>
#include<stdio.h>
int main(void)
{
char *t = meson_print();
printf("%s", t);
return 0;
}
|
07972e57d2513d53fefa72770211c01c2b98f23f
|
aa3befea459382dc5c01c925653d54f435b3fb0f
|
/arch/arm/src/stm32/stm32_fdcan_sock.c
|
6f7c4f586bb961f71b4f5e0f63c14f8b6a09e6ae
|
[
"MIT-open-group",
"BSD-3-Clause",
"HPND-sell-variant",
"BSD-4-Clause-UC",
"LicenseRef-scancode-warranty-disclaimer",
"MIT-0",
"LicenseRef-scancode-bsd-atmel",
"LicenseRef-scancode-gary-s-brown",
"LicenseRef-scancode-proprietary-license",
"SunPro",
"MIT",
"LicenseRef-scancode-public-domain-disclaimer",
"LicenseRef-scancode-other-permissive",
"HPND",
"ISC",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"GPL-1.0-or-later",
"CC-BY-2.0",
"CC-BY-4.0"
] |
permissive
|
apache/nuttx
|
14519a7bff4a87935d94fb8fb2b19edb501c7cec
|
606b6d9310fb25c7d92c6f95bf61737e3c79fa0f
|
refs/heads/master
| 2023-08-25T06:55:45.822534
| 2023-08-23T16:03:31
| 2023-08-24T21:25:47
| 228,103,273
| 407
| 241
|
Apache-2.0
| 2023-09-14T18:26:05
| 2019-12-14T23:27:55
|
C
|
UTF-8
|
C
| false
| false
| 95,004
|
c
|
stm32_fdcan_sock.c
|
/****************************************************************************
* arch/arm/src/stm32/stm32_fdcan_sock.c
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*s
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <inttypes.h>
#include <stdio.h>
#include <sys/types.h>
#include <stdint.h>
#include <stdbool.h>
#include <assert.h>
#include <errno.h>
#include <debug.h>
#include <arch/board/board.h>
#include <nuttx/irq.h>
#include <nuttx/arch.h>
#include <nuttx/wqueue.h>
#include <nuttx/can.h>
#include <nuttx/net/netdev.h>
#include <nuttx/net/can.h>
#include <netpacket/can.h>
#include "arm_internal.h"
#include "stm32_fdcan.h"
#include "hardware/stm32_pinmap.h"
#include "stm32_gpio.h"
#include "stm32_rcc.h"
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/* Pool configuration *******************************************************/
#define POOL_SIZE (1)
/* Work queue support is required. */
#if !defined(CONFIG_SCHED_WORKQUEUE)
# error Work queue support is required
#endif
/* The low priority work queue is preferred. If it is not enabled, LPWORK
* will be the same as HPWORK.
*
* NOTE: However, the network should NEVER run on the high priority work
* queue! That queue is intended only to service short back end interrupt
* processing that never suspends. Suspending the high priority work queue
* may bring the system to its knees!
*/
#define CANWORK LPWORK
/* Clock source *************************************************************/
#define FDCANCLK_PDIV (0)
#if FDCANCLK_PDIV == 0
# define STM32_FDCANCLK_FREQUENCY (STM32_FDCAN_FREQUENCY / (1))
#else
# define STM32_FDCANCLK_FREQUENCY (STM32_FDCAN_FREQUENCY / (2 * FDCANCLK_PDIV))
#endif
/* General Configuration ****************************************************/
#if defined(CONFIG_STM32_STM32G4XXX)
/* FDCAN Message RAM */
# define FDCAN_MSGRAM_WORDS (212)
# define STM32_CANRAM1_BASE (STM32_CANRAM_BASE + 0x0000)
# define STM32_CANRAM2_BASE (STM32_CANRAM_BASE + 1*(FDCAN_MSGRAM_WORDS * 4) + 4)
# define STM32_CANRAM3_BASE (STM32_CANRAM_BASE + 2*(FDCAN_MSGRAM_WORDS * 4) + 4)
# ifdef CONFIG_STM32_FDCAN1
# define FDCAN1_STDFILTER_SIZE (28)
# define FDCAN1_EXTFILTER_SIZE (8)
# define FDCAN1_RXFIFO0_SIZE (3)
# define FDCAN1_RXFIFO1_SIZE (3)
# define FDCAN1_TXEVENTFIFO_SIZE (3)
# define FDCAN1_TXFIFIOQ_SIZE (3)
# define FDCAN1_STDFILTER_WORDS (28)
# define FDCAN1_EXTFILTER_WORDS (16)
# define FDCAN1_RXFIFO0_WORDS (54)
# define FDCAN1_RXFIFO1_WORDS (54)
# define FDCAN1_TXEVENTFIFO_WORDS (6)
# define FDCAN1_TXFIFIOQ_WORDS (54)
# endif
# ifdef CONFIG_STM32_FDCAN2
# define FDCAN2_STDFILTER_SIZE (28)
# define FDCAN2_EXTFILTER_SIZE (8)
# define FDCAN2_RXFIFO0_SIZE (3)
# define FDCAN2_RXFIFO1_SIZE (3)
# define FDCAN2_TXEVENTFIFO_SIZE (3)
# define FDCAN2_TXFIFIOQ_SIZE (3)
# define FDCAN2_STDFILTER_WORDS (28)
# define FDCAN2_EXTFILTER_WORDS (16)
# define FDCAN2_RXFIFO0_WORDS (54)
# define FDCAN2_RXFIFO1_WORDS (54)
# define FDCAN2_TXEVENTFIFO_WORDS (6)
# define FDCAN2_TXFIFIOQ_WORDS (54)
# endif
# ifdef CONFIG_STM32_FDCAN3
# define FDCAN3_STDFILTER_SIZE (28)
# define FDCAN3_EXTFILTER_SIZE (8)
# define FDCAN3_RXFIFO0_SIZE (3)
# define FDCAN3_RXFIFO1_SIZE (3)
# define FDCAN3_TXEVENTFIFO_SIZE (3)
# define FDCAN3_TXFIFIOQ_SIZE (3)
# define FDCAN3_STDFILTER_WORDS (28)
# define FDCAN3_EXTFILTER_WORDS (16)
# define FDCAN3_RXFIFO0_WORDS (54)
# define FDCAN3_RXFIFO1_WORDS (54)
# define FDCAN3_TXEVENTFIFO_WORDS (6)
# define FDCAN3_TXFIFIOQ_WORDS (54)
# endif
#else
# error
#endif
/* FDCAN1 Configuration *****************************************************/
#ifdef CONFIG_STM32_FDCAN1
/* Bit timing */
# define FDCAN1_NTSEG1 (CONFIG_STM32_FDCAN1_NTSEG1 - 1)
# define FDCAN1_NTSEG2 (CONFIG_STM32_FDCAN1_NTSEG2 - 1)
# define FDCAN1_NBRP ((STM32_FDCANCLK_FREQUENCY / \
((FDCAN1_NTSEG1 + FDCAN1_NTSEG2 + 3) * \
CONFIG_STM32_FDCAN1_BITRATE)) - 1)
# define FDCAN1_NSJW (CONFIG_STM32_FDCAN1_NSJW - 1)
# if FDCAN1_NTSEG1 > FDCAN_NBTP_NTSEG1_MAX
# error Invalid FDCAN1 NTSEG1
# endif
# if FDCAN1_NTSEG2 > FDCAN_NBTP_NTSEG2_MAX
# error Invalid FDCAN1 NTSEG2
# endif
# if FDCAN1_NSJW > FDCAN_NBTP_NSJW_MAX
# error Invalid FDCAN1 NSJW
# endif
# if FDCAN1_NBRP > FDCAN_NBTP_NBRP_MAX
# error Invalid FDCAN1 NBRP
# endif
# ifdef CONFIG_STM32_FDCAN1_FD_BRS
# define FDCAN1_DTSEG1 (CONFIG_STM32_FDCAN1_DTSEG1 - 1)
# define FDCAN1_DTSEG2 (CONFIG_STM32_FDCAN1_DTSEG2 - 1)
# define FDCAN1_DBRP ((STM32_FDCANCLK_FREQUENCY / \
((FDCAN1_DTSEG1 + FDCAN1_DTSEG2 + 3) * \
CONFIG_STM32_FDCAN1_DBITRATE)) - 1)
# define FDCAN1_DSJW (CONFIG_STM32_FDCAN1_DSJW - 1)
# else
# define FDCAN1_DTSEG1 1
# define FDCAN1_DTSEG2 1
# define FDCAN1_DBRP 1
# define FDCAN1_DSJW 1
# endif /* CONFIG_STM32_FDCAN1_FD_BRS */
# if FDCAN1_DTSEG1 > FDCAN_DBTP_DTSEG1_MAX
# error Invalid FDCAN1 DTSEG1
# endif
# if FDCAN1_DTSEG2 > FDCAN_DBTP_DTSEG2_MAX
# error Invalid FDCAN1 DTSEG2
# endif
# if FDCAN1_DBRP > FDCAN_DBTP_DBRP_MAX
# error Invalid FDCAN1 DBRP
# endif
# if FDCAN1_DSJW > FDCAN_DBTP_DSJW_MAX
# error Invalid FDCAN1 DSJW
# endif
/* FDCAN1 Message RAM Configuration *****************************************/
/* FDCAN1 Message RAM Layout */
# define FDCAN1_STDFILTER_INDEX 0
# define FDCAN1_EXTFILTERS_INDEX (FDCAN1_STDFILTER_INDEX + FDCAN1_STDFILTER_WORDS)
# define FDCAN1_RXFIFO0_INDEX (FDCAN1_EXTFILTERS_INDEX + FDCAN1_EXTFILTER_WORDS)
# define FDCAN1_RXFIFO1_INDEX (FDCAN1_RXFIFO0_INDEX + FDCAN1_RXFIFO0_WORDS)
# define FDCAN1_TXEVENTFIFO_INDEX (FDCAN1_RXFIFO1_INDEX + FDCAN1_RXFIFO1_WORDS)
# define FDCAN1_TXFIFOQ_INDEX (FDCAN1_TXEVENTFIFO_INDEX + FDCAN1_TXEVENTFIFO_WORDS)
# define FDCAN1_MSGRAM_WORDS (FDCAN1_TXFIFOQ_INDEX + FDCAN1_TXFIFIOQ_WORDS)
#endif /* CONFIG_STM32_FDCAN1 */
/* FDCAN2 Configuration *****************************************************/
#ifdef CONFIG_STM32_FDCAN2
/* Bit timing */
# define FDCAN2_NTSEG1 (CONFIG_STM32_FDCAN2_NTSEG1 - 1)
# define FDCAN2_NTSEG2 (CONFIG_STM32_FDCAN2_NTSEG2 - 1)
# define FDCAN2_NBRP (((STM32_FDCANCLK_FREQUENCY / \
((FDCAN2_NTSEG1 + FDCAN2_NTSEG2 + 3) * \
CONFIG_STM32_FDCAN2_BITRATE)) - 1))
# define FDCAN2_NSJW (CONFIG_STM32_FDCAN2_NSJW - 1)
# if FDCAN2_NTSEG1 > FDCAN_NBTP_NTSEG1_MAX
# error Invalid FDCAN2 NTSEG1
# endif
# if FDCAN2_NTSEG2 > FDCAN_NBTP_NTSEG2_MAX
# error Invalid FDCAN2 NTSEG2
# endif
# if FDCAN2_NSJW > FDCAN_NBTP_NSJW_MAX
# error Invalid FDCAN2 NSJW
# endif
# if FDCAN2_NBRP > FDCAN_NBTP_NBRP_MAX
# error Invalid FDCAN1 NBRP
# endif
# ifdef CONFIG_STM32_FDCAN2_FD_BRS
# define FDCAN2_DTSEG1 (CONFIG_STM32_FDCAN2_DTSEG1 - 1)
# define FDCAN2_DTSEG2 (CONFIG_STM32_FDCAN2_DTSEG2 - 1)
# define FDCAN2_DBRP (((STM32_FDCANCLK_FREQUENCY / \
((FDCAN2_DTSEG1 + FDCAN2_DTSEG2 + 3) * \
CONFIG_STM32_FDCAN2_DBITRATE)) - 1))
# define FDCAN2_DSJW (CONFIG_STM32_FDCAN2_DSJW - 1)
# else
# define FDCAN2_DTSEG1 1
# define FDCAN2_DTSEG2 1
# define FDCAN2_DBRP 1
# define FDCAN2_DSJW 1
# endif /* CONFIG_STM32_FDCAN2_FD_BRS */
# if FDCAN2_DTSEG1 > FDCAN_DBTP_DTSEG1_MAX
# error Invalid FDCAN2 DTSEG1
# endif
# if FDCAN2_DTSEG2 > FDCAN_DBTP_DTSEG2_MAX
# error Invalid FDCAN2 DTSEG2
# endif
# if FDCAN2_DBRP > FDCAN_DBTP_DBRP_MAX
# error Invalid FDCAN2 DBRP
# endif
# if FDCAN2_DSJW > FDCAN_DBTP_DSJW_MAX
# error Invalid FDCAN2 DSJW
# endif
/* FDCAN2 Message RAM Configuration *****************************************/
/* FDCAN2 Message RAM Layout */
# define FDCAN2_STDFILTER_INDEX 0
# define FDCAN2_EXTFILTERS_INDEX (FDCAN2_STDFILTER_INDEX + FDCAN2_STDFILTER_WORDS)
# define FDCAN2_RXFIFO0_INDEX (FDCAN2_EXTFILTERS_INDEX + FDCAN2_EXTFILTER_WORDS)
# define FDCAN2_RXFIFO1_INDEX (FDCAN2_RXFIFO0_INDEX + FDCAN2_RXFIFO0_WORDS)
# define FDCAN2_TXEVENTFIFO_INDEX (FDCAN2_RXFIFO1_INDEX + FDCAN2_RXFIFO1_WORDS)
# define FDCAN2_TXFIFOQ_INDEX (FDCAN2_TXEVENTFIFO_INDEX + FDCAN2_TXEVENTFIFO_WORDS)
# define FDCAN2_MSGRAM_WORDS (FDCAN2_TXFIFOQ_INDEX + FDCAN2_TXFIFIOQ_WORDS)
#endif /* CONFIG_STM32_FDCAN2 */
/* FDCAN3 Configuration *****************************************************/
#ifdef CONFIG_STM32_FDCAN3
/* Bit timing */
# define FDCAN3_NTSEG1 (CONFIG_STM32_FDCAN3_NTSEG1 - 1)
# define FDCAN3_NTSEG2 (CONFIG_STM32_FDCAN3_NTSEG2 - 1)
# define FDCAN3_NBRP (((STM32_FDCANCLK_FREQUENCY / \
((FDCAN3_NTSEG1 + FDCAN3_NTSEG2 + 3) * \
CONFIG_STM32_FDCAN3_BITRATE)) - 1))
# define FDCAN3_NSJW (CONFIG_STM32_FDCAN3_NSJW - 1)
# if FDCAN3_NTSEG1 > FDCAN_NBTP_NTSEG1_MAX
# error Invalid FDCAN3 NTSEG1
# endif
# if FDCAN3_NTSEG2 > FDCAN_NBTP_NTSEG2_MAX
# error Invalid FDCAN3 NTSEG2
# endif
# if FDCAN3_NSJW > FDCAN_NBTP_NSJW_MAX
# error Invalid FDCAN3 NSJW
# endif
# if FDCAN3_NBRP > FDCAN_NBTP_NBRP_MAX
# error Invalid FDCAN1 NBRP
# endif
# ifdef CONFIG_STM32_FDCAN3_FD_BRS
# define FDCAN3_DTSEG1 (CONFIG_STM32_FDCAN3_DTSEG1 - 1)
# define FDCAN3_DTSEG2 (CONFIG_STM32_FDCAN3_DTSEG2 - 1)
# define FDCAN3_DBRP (((STM32_FDCANCLK_FREQUENCY / \
((FDCAN3_DTSEG1 + FDCAN3_DTSEG2 + 3) * \
CONFIG_STM32_FDCAN3_DBITRATE)) - 1))
# define FDCAN3_DSJW (CONFIG_STM32_FDCAN3_DSJW - 1)
# else
# define FDCAN3_DTSEG1 1
# define FDCAN3_DTSEG2 1
# define FDCAN3_DBRP 1
# define FDCAN3_DSJW 1
# endif /* CONFIG_STM32_FDCAN3_FD_BRS */
# if FDCAN3_DTSEG1 > FDCAN_DBTP_DTSEG1_MAX
# error Invalid FDCAN3 DTSEG1
# endif
# if FDCAN3_DTSEG2 > FDCAN_DBTP_DTSEG2_MAX
# error Invalid FDCAN3 DTSEG2
# endif
# if FDCAN3_DBRP > FDCAN_DBTP_DBRP_MAX
# error Invalid FDCAN3 DBRP
# endif
# if FDCAN3_DSJW > FDCAN_DBTP_DSJW_MAX
# error Invalid FDCAN3 DSJW
# endif
/* FDCAN3 Message RAM Configuration *****************************************/
/* FDCAN3 Message RAM Layout */
# define FDCAN3_STDFILTER_INDEX 0
# define FDCAN3_EXTFILTERS_INDEX (FDCAN3_STDFILTER_INDEX + FDCAN3_STDFILTER_WORDS)
# define FDCAN3_RXFIFO0_INDEX (FDCAN3_EXTFILTERS_INDEX + FDCAN3_EXTFILTER_WORDS)
# define FDCAN3_RXFIFO1_INDEX (FDCAN3_RXFIFO0_INDEX + FDCAN3_RXFIFO0_WORDS)
# define FDCAN3_TXEVENTFIFO_INDEX (FDCAN3_RXFIFO1_INDEX + FDCAN3_RXFIFO1_WORDS)
# define FDCAN3_TXFIFOQ_INDEX (FDCAN3_TXEVENTFIFO_INDEX + FDCAN3_TXEVENTFIFO_WORDS)
# define FDCAN3_MSGRAM_WORDS (FDCAN3_TXFIFOQ_INDEX + FDCAN3_TXFIFIOQ_WORDS)
#endif /* CONFIG_STM32_FDCAN3 */
/* Loopback mode */
#undef STM32_FDCAN_LOOPBACK
#if defined(CONFIG_STM32_FDCAN1_LOOPBACK) || \
defined(CONFIG_STM32_FDCAN2_LOOPBACK) || \
defined(CONFIG_STM32_FDCAN3_LOOPBACK)
# define STM32_FDCAN_LOOPBACK 1
#endif
/* Interrupts ***************************************************************/
/* Common interrupts
*
* FDCAN_INT_TSW - Timestamp Wraparound
* FDCAN_INT_MRAF - Message RAM Access Failure
* FDCAN_INT_TOO - Timeout Occurred
* FDCAN_INT_ELO - Error Logging Overflow
* FDCAN_INT_EP - Error Passive
* FDCAN_INT_EW - Warning Status
* FDCAN_INT_BO - Bus_Off Status
* FDCAN_INT_WDI - Watchdog Interrupt
* FDCAN_INT_PEA - Protocol Error in Arbritration Phase
* FDCAN_INT_PED - Protocol Error in Data Phase
*/
#define FDCAN_CMNERR_INTS (FDCAN_INT_MRAF | FDCAN_INT_TOO | FDCAN_INT_EP | \
FDCAN_INT_BO | FDCAN_INT_WDI | FDCAN_INT_PEA | \
FDCAN_INT_PED)
/* RXFIFO mode interrupts
*
* FDCAN_INT_RF0N - Receive FIFO 0 New Message
* FDCAN_INT_RF0F - Receive FIFO 0 Full
* FDCAN_INT_RF0L - Receive FIFO 0 Message Lost
* FDCAN_INT_RF1N - Receive FIFO 1 New Message
* FDCAN_INT_RF1F - Receive FIFO 1 Full
* FDCAN_INT_RF1L - Receive FIFO 1 Message Lost
* FDCAN_INT_HPM - High Priority Message Received
*
*/
#define FDCAN_RXFIFO0_INTS (FDCAN_INT_RF0N | FDCAN_INT_RF0L)
#define FDCAN_RXFIFO1_INTS (FDCAN_INT_RF1N | FDCAN_INT_RF1L)
#define FDCAN_RXERR_INTS (FDCAN_INT_RF0L | FDCAN_INT_RF1L)
/* TX FIFOQ mode interrupts
*
* FDCAN_INT_TFE - Tx FIFO Empty
*
* TX Event FIFO interrupts
*
* FDCAN_INT_TEFN - Tx Event FIFO New Entry
* FDCAN_INT_TEFF - Tx Event FIFO Full
* FDCAN_INT_TEFL - Tx Event FIFO Element Lost
*
* Mode-independent TX-related interrupts
*
* FDCAN_INT_TC - Transmission Completed
* FDCAN_INT_TCF - Transmission Cancellation Finished
*/
#define FDCAN_TXCOMMON_INTS (FDCAN_INT_TC | FDCAN_INT_TCF)
#define FDCAN_TXFIFOQ_INTS (FDCAN_INT_TFE | FDCAN_TXCOMMON_INTS)
#define FDCAN_TXEVFIFO_INTS (FDCAN_INT_TEFN | FDCAN_INT_TEFF | \
FDCAN_INT_TEFL)
#define FDCAN_TXERR_INTS (FDCAN_INT_TEFL | FDCAN_INT_PEA | FDCAN_INT_PED)
/* Common-, TX- and RX-Error-Mask */
#define FDCAN_ANYERR_INTS (FDCAN_CMNERR_INTS | FDCAN_RXERR_INTS | FDCAN_TXERR_INTS)
/* Convenience macro for clearing all interrupts */
#define FDCAN_INT_ALL 0x3fcfffff
/* Debug ********************************************************************/
/* Debug configurations that may be enabled just for testing FDCAN */
#ifndef CONFIG_DEBUG_NET_INFO
# undef CONFIG_STM32_FDCAN_REGDEBUG
#endif
/****************************************************************************
* Private Types
****************************************************************************/
/* CAN frame format */
enum stm32_frameformat_e
{
FDCAN_ISO11898_1_FORMAT = 0, /* Frame format according to ISO11898-1 */
FDCAN_NONISO_BOSCH_V1_FORMAT = 1 /* Frame format according to Bosch CAN FD V1.0 */
};
/* CAN mode of operation */
enum stm32_canmode_e
{
FDCAN_CLASSIC_MODE = 0, /* Classic CAN operation */
#ifdef CONFIG_NET_CAN_CANFD
FDCAN_FD_MODE = 1, /* CAN FD operation */
FDCAN_FD_BRS_MODE = 2 /* CAN FD operation with bit rate switching */
#endif
};
/* CAN driver state */
enum can_state_s
{
FDCAN_STATE_UNINIT = 0, /* Not yet initialized */
FDCAN_STATE_RESET, /* Initialized, reset state */
FDCAN_STATE_SETUP, /* fdcan_setup() has been called */
FDCAN_STATE_DISABLED /* Disabled by a fdcan_shutdown() */
};
/* This structure describes the FDCAN message RAM layout */
struct stm32_msgram_s
{
volatile uint32_t *stdfilters; /* Standard filters */
volatile uint32_t *extfilters; /* Extended filters */
volatile uint32_t *rxfifo0; /* RX FIFO0 */
volatile uint32_t *rxfifo1; /* RX FIFO1 */
volatile uint32_t *txeventfifo; /* TX event FIFO */
volatile uint32_t *txfifoq; /* TX FIFO queue */
};
/* This structure provides the constant configuration of a FDCAN peripheral */
struct stm32_config_s
{
uint32_t rxpinset; /* RX pin configuration */
uint32_t txpinset; /* TX pin configuration */
uintptr_t base; /* Base address of the FDCAN registers */
uint32_t baud; /* Configured baud */
uint32_t nbtp; /* Nominal bit timing/prescaler register setting */
uint32_t dbtp; /* Data bit timing/prescaler register setting */
uint8_t port; /* FDCAN port number (1 or 2) */
uint8_t irq0; /* FDCAN peripheral IRQ number for interrupt line 0 */
uint8_t irq1; /* FDCAN peripheral IRQ number for interrupt line 1 */
uint8_t mode; /* See enum stm32_canmode_e */
uint8_t format; /* See enum stm32_frameformat_e */
uint8_t nstdfilters; /* Number of standard filters */
uint8_t nextfilters; /* Number of extended filters */
uint8_t nrxfifo0; /* Number of RX FIFO0 elements */
uint8_t nrxfifo1; /* Number of RX FIFO1 elements */
uint8_t ntxeventfifo; /* Number of TXevent FIFO elements */
uint8_t ntxfifoq; /* Number of TX FIFO queue elements */
uint8_t rxfifo0esize; /* RX FIFO0 element size (words) */
uint8_t rxfifo1esize; /* RX FIFO1 element size (words) */
uint8_t txeventesize; /* TXevent element size (words) */
uint8_t txbufferesize; /* TX buffer element size (words) */
#ifdef STM32_FDCAN_LOOPBACK
bool loopback; /* True: Loopback mode */
#endif
/* FDCAN message RAM layout */
struct stm32_msgram_s msgram;
};
/* This structure provides the current state of a FDCAN peripheral */
struct stm32_fdcan_s
{
/* The constant configuration */
const struct stm32_config_s *config;
uint8_t state; /* See enum can_state_s */
#ifdef CONFIG_NET_CAN_EXTID
uint8_t nextalloc; /* Number of allocated extended filters */
#endif
uint8_t nstdalloc; /* Number of allocated standard filters */
uint32_t nbtp; /* Current nominal bit timing */
uint32_t dbtp; /* Current data bit timing */
#ifdef CONFIG_NET_CAN_EXTID
uint32_t extfilters[2]; /* Extended filter bit allocator. 2*32=64 */
#endif
uint32_t stdfilters[4]; /* Standard filter bit allocator. 4*32=128 */
#ifdef CONFIG_STM32_FDCAN_REGDEBUG
uintptr_t regaddr; /* Last register address read */
uint32_t regval; /* Last value read from the register */
unsigned int count; /* Number of times that the value was read */
#endif
bool bifup; /* true:ifup false:ifdown */
struct net_driver_s dev; /* Interface understood by the network */
struct work_s irqwork; /* For deferring interrupt work to the wq */
struct work_s pollwork; /* For deferring poll work to the work wq */
/* A pointers to the list of TX/RX descriptors */
struct can_frame *txdesc;
struct can_frame *rxdesc;
/* TX/RX pool */
#ifdef CONFIG_NET_CAN_CANFD
uint8_t tx_pool[sizeof(struct canfd_frame)*POOL_SIZE];
uint8_t rx_pool[sizeof(struct canfd_frame)*POOL_SIZE];
#else
uint8_t tx_pool[sizeof(struct can_frame)*POOL_SIZE];
uint8_t rx_pool[sizeof(struct can_frame)*POOL_SIZE];
#endif
};
/****************************************************************************
* Private Function Prototypes
****************************************************************************/
/* FDCAN Register access */
static uint32_t fdcan_getreg(struct stm32_fdcan_s *priv, int offset);
static void fdcan_putreg(struct stm32_fdcan_s *priv, int offset,
uint32_t regval);
#ifdef CONFIG_STM32_FDCAN_REGDEBUG
static void fdcan_dumpregs(struct stm32_fdcan_s *priv,
const char *msg);
static void fdcan_dumprxregs(struct stm32_fdcan_s *priv,
const char *msg);
static void fdcan_dumptxregs(struct stm32_fdcan_s *priv,
const char *msg);
static void fdcan_dumpramlayout(struct stm32_fdcan_s *priv);
#else
# define fdcan_dumpregs(priv,msg)
# define fdcan_dumprxregs(priv,msg)
# define fdcan_dumptxregs(priv,msg)
# define fdcan_dumpramlayout(priv)
#endif
/* CAN interrupt enable functions */
static void fdcan_rx0int(struct stm32_fdcan_s *priv, bool enable);
static void fdcan_rx1int(struct stm32_fdcan_s *priv, bool enable);
static void fdcan_txint(struct stm32_fdcan_s *priv, bool enable);
#ifdef CONFIG_NET_CAN_ERRORS
static void fdcan_errint(struct stm32_fdcan_s *priv, bool enable);
#endif
/* Common TX logic */
static int fdcan_send(struct stm32_fdcan_s *priv);
static bool fdcan_txready(struct stm32_fdcan_s *priv);
static int fdcan_txpoll(struct net_driver_s *dev);
/* CAN RX interrupt handling */
static void fdcan_rx0interrupt_work(void *arg);
static void fdcan_rx1interrupt_work(void *arg);
/* CAN TX interrupt handling */
static void fdcan_txdone_work(void *arg);
static void fdcan_txdone(struct stm32_fdcan_s *priv);
#ifdef CONFIG_NET_CAN_ERRORS
/* CAN errors interrupt handling */
static void fdcan_error_work(void *arg);
#endif
/* FDCAN interrupt handling */
#ifdef CONFIG_NET_CAN_ERRORS
static void fdcan_error(struct stm32_fdcan_s *priv, uint32_t status);
#endif
static void fdcan_receive(struct stm32_fdcan_s *priv,
volatile uint32_t *rxbuffer,
unsigned long nwords);
static int fdcan_interrupt(int irq, void *context, void *arg);
/* Initialization */
static void fdcan_reset(struct stm32_fdcan_s *priv);
static int fdcan_setup(struct stm32_fdcan_s *priv);
static void fdcan_shutdown(struct stm32_fdcan_s *priv);
/* FDCAN helpers */
#if 0 /* not used for now */
static int
fdcan_start_busoff_recovery_sequence(struct stm32_fdcan_s *priv);
#endif
/* Hardware initialization */
static int fdcan_hw_initialize(struct stm32_fdcan_s *priv);
/* NuttX callback functions */
static int fdcan_ifup(struct net_driver_s *dev);
static int fdcan_ifdown(struct net_driver_s *dev);
static void fdcan_txavail_work(void *arg);
static int fdcan_txavail(struct net_driver_s *dev);
#ifdef CONFIG_NETDEV_IOCTL
static int fdcan_netdev_ioctl(struct net_driver_s *dev, int cmd,
unsigned long arg);
#endif
/****************************************************************************
* Private Data
****************************************************************************/
#ifdef CONFIG_STM32_FDCAN1
/* Message RAM allocation */
/* Constant configuration */
static const struct stm32_config_s g_fdcan1const =
{
.rxpinset = GPIO_FDCAN1_RX,
.txpinset = GPIO_FDCAN1_TX,
.base = STM32_FDCAN1_BASE,
.baud = CONFIG_STM32_FDCAN1_BITRATE,
.nbtp = FDCAN_NBTP_NBRP(FDCAN1_NBRP) |
FDCAN_NBTP_NTSEG1(FDCAN1_NTSEG1) |
FDCAN_NBTP_NTSEG2(FDCAN1_NTSEG2) |
FDCAN_NBTP_NSJW(FDCAN1_NSJW),
.dbtp = FDCAN_DBTP_DBRP(FDCAN1_DBRP) |
FDCAN_DBTP_DTSEG1(FDCAN1_DTSEG1) |
FDCAN_DBTP_DTSEG2(FDCAN1_DTSEG2) |
FDCAN_DBTP_DSJW(FDCAN1_DSJW),
.port = 1,
.irq0 = STM32_IRQ_FDCAN1_0,
.irq1 = STM32_IRQ_FDCAN1_1,
#if defined(CONFIG_STM32_FDCAN1_CLASSIC)
.mode = FDCAN_CLASSIC_MODE,
#elif defined(CONFIG_STM32_FDCAN1_FD)
.mode = FDCAN_FD_MODE,
#else
.mode = FDCAN_FD_BRS_MODE,
#endif
#if defined(CONFIG_STM32_FDCAN1_NONISO_FORMAT)
.format = FDCAN_NONISO_BOSCH_V1_FORMAT,
#else
.format = FDCAN_ISO11898_1_FORMAT,
#endif
.nstdfilters = FDCAN1_STDFILTER_SIZE,
.nextfilters = FDCAN1_EXTFILTER_SIZE,
.nrxfifo0 = FDCAN1_RXFIFO0_SIZE,
.nrxfifo1 = FDCAN1_RXFIFO1_SIZE,
.ntxeventfifo = FDCAN1_TXEVENTFIFO_SIZE,
.ntxfifoq = FDCAN1_TXFIFIOQ_SIZE,
.rxfifo0esize = (FDCAN1_RXFIFO0_WORDS / FDCAN1_RXFIFO0_SIZE),
.rxfifo1esize = (FDCAN1_RXFIFO1_WORDS / FDCAN1_RXFIFO1_SIZE),
.txeventesize = (FDCAN1_TXEVENTFIFO_WORDS / FDCAN1_TXEVENTFIFO_SIZE),
.txbufferesize = (FDCAN1_TXFIFIOQ_WORDS / FDCAN1_TXFIFIOQ_SIZE),
#ifdef CONFIG_STM32_FDCAN1_LOOPBACK
.loopback = true,
#endif
/* FDCAN1 Message RAM */
.msgram =
{
(uint32_t *)(STM32_CANRAM1_BASE + (FDCAN1_STDFILTER_INDEX << 2)),
(uint32_t *)(STM32_CANRAM1_BASE + (FDCAN1_EXTFILTERS_INDEX << 2)),
(uint32_t *)(STM32_CANRAM1_BASE + (FDCAN1_RXFIFO0_INDEX << 2)),
(uint32_t *)(STM32_CANRAM1_BASE + (FDCAN1_RXFIFO1_INDEX << 2)),
(uint32_t *)(STM32_CANRAM1_BASE + (FDCAN1_TXEVENTFIFO_INDEX << 2)),
(uint32_t *)(STM32_CANRAM1_BASE + (FDCAN1_TXFIFOQ_INDEX << 2))
}
};
/* FDCAN1 variable driver state */
static struct stm32_fdcan_s g_fdcan1priv;
#endif /* CONFIG_STM32_FDCAN1 */
#ifdef CONFIG_STM32_FDCAN2
/* FDCAN2 message RAM allocation */
/* FDCAN2 constant configuration */
static const struct stm32_config_s g_fdcan2const =
{
.rxpinset = GPIO_FDCAN2_RX,
.txpinset = GPIO_FDCAN2_TX,
.base = STM32_FDCAN2_BASE,
.baud = CONFIG_STM32_FDCAN2_BITRATE,
.nbtp = FDCAN_NBTP_NBRP(FDCAN2_NBRP) |
FDCAN_NBTP_NTSEG1(FDCAN2_NTSEG1) |
FDCAN_NBTP_NTSEG2(FDCAN2_NTSEG2) |
FDCAN_NBTP_NSJW(FDCAN2_NSJW),
.dbtp = FDCAN_DBTP_DBRP(FDCAN2_DBRP) |
FDCAN_DBTP_DTSEG1(FDCAN2_DTSEG1) |
FDCAN_DBTP_DTSEG2(FDCAN2_DTSEG2) |
FDCAN_DBTP_DSJW(FDCAN2_DSJW),
.port = 2,
.irq0 = STM32_IRQ_FDCAN2_0,
.irq1 = STM32_IRQ_FDCAN2_1,
#if defined(CONFIG_STM32_FDCAN2_CLASSIC)
.mode = FDCAN_CLASSIC_MODE,
#elif defined(CONFIG_STM32_FDCAN2_FD)
.mode = FDCAN_FD_MODE,
#else
.mode = FDCAN_FD_BRS_MODE,
#endif
#if defined(CONFIG_STM32_FDCAN2_NONISO_FORMAT)
.format = FDCAN_NONISO_BOSCH_V1_FORMAT,
#else
.format = FDCAN_ISO11898_1_FORMAT,
#endif
.nstdfilters = FDCAN2_STDFILTER_SIZE,
.nextfilters = FDCAN2_EXTFILTER_SIZE,
.nrxfifo0 = FDCAN2_RXFIFO0_SIZE,
.nrxfifo1 = FDCAN2_RXFIFO1_SIZE,
.ntxeventfifo = FDCAN2_TXEVENTFIFO_SIZE,
.ntxfifoq = FDCAN2_TXFIFIOQ_SIZE,
.rxfifo0esize = (FDCAN2_RXFIFO0_WORDS / FDCAN2_RXFIFO0_SIZE),
.rxfifo1esize = (FDCAN2_RXFIFO1_WORDS / FDCAN2_RXFIFO1_SIZE),
.txeventesize = (FDCAN2_TXEVENTFIFO_WORDS / FDCAN2_TXEVENTFIFO_SIZE),
.txbufferesize = (FDCAN2_TXFIFIOQ_WORDS / FDCAN2_TXFIFIOQ_SIZE),
#ifdef CONFIG_STM32_FDCAN2_LOOPBACK
.loopback = true,
#endif
/* FDCAN2 Message RAM */
.msgram =
{
(uint32_t *)(STM32_CANRAM2_BASE + (FDCAN2_STDFILTER_INDEX << 2)),
(uint32_t *)(STM32_CANRAM2_BASE + (FDCAN2_EXTFILTERS_INDEX << 2)),
(uint32_t *)(STM32_CANRAM2_BASE + (FDCAN2_RXFIFO0_INDEX << 2)),
(uint32_t *)(STM32_CANRAM2_BASE + (FDCAN2_RXFIFO1_INDEX << 2)),
(uint32_t *)(STM32_CANRAM2_BASE + (FDCAN2_TXEVENTFIFO_INDEX << 2)),
(uint32_t *)(STM32_CANRAM2_BASE + (FDCAN2_TXFIFOQ_INDEX << 2))
}
};
/* FDCAN2 variable driver state */
static struct stm32_fdcan_s g_fdcan2priv;
#endif /* CONFIG_STM32_FDCAN2 */
#ifdef CONFIG_STM32_FDCAN3
/* FDCAN3 message RAM allocation */
/* FDCAN3 constant configuration */
static const struct stm32_config_s g_fdcan3const =
{
.rxpinset = GPIO_FDCAN3_RX,
.txpinset = GPIO_FDCAN3_TX,
.base = STM32_FDCAN3_BASE,
.baud = CONFIG_STM32_FDCAN3_BITRATE,
.nbtp = FDCAN_NBTP_NBRP(FDCAN3_NBRP) |
FDCAN_NBTP_NTSEG1(FDCAN3_NTSEG1) |
FDCAN_NBTP_NTSEG2(FDCAN3_NTSEG2) |
FDCAN_NBTP_NSJW(FDCAN3_NSJW),
.dbtp = FDCAN_DBTP_DBRP(FDCAN3_DBRP) |
FDCAN_DBTP_DTSEG1(FDCAN3_DTSEG1) |
FDCAN_DBTP_DTSEG2(FDCAN3_DTSEG2) |
FDCAN_DBTP_DSJW(FDCAN3_DSJW),
.port = 3,
.irq0 = STM32_IRQ_FDCAN3_0,
.irq1 = STM32_IRQ_FDCAN3_1,
#if defined(CONFIG_STM32_FDCAN3_CLASSIC)
.mode = FDCAN_CLASSIC_MODE,
#elif defined(CONFIG_STM32_FDCAN3_FD)
.mode = FDCAN_FD_MODE,
#else
.mode = FDCAN_FD_BRS_MODE,
#endif
#if defined(CONFIG_STM32_FDCAN3_NONISO_FORMAT)
.format = FDCAN_NONISO_BOSCH_V1_FORMAT,
#else
.format = FDCAN_ISO11898_1_FORMAT,
#endif
.nstdfilters = FDCAN3_STDFILTER_SIZE,
.nextfilters = FDCAN3_EXTFILTER_SIZE,
.nrxfifo0 = FDCAN3_RXFIFO0_SIZE,
.nrxfifo1 = FDCAN3_RXFIFO1_SIZE,
.ntxeventfifo = FDCAN3_TXEVENTFIFO_SIZE,
.ntxfifoq = FDCAN3_TXFIFIOQ_SIZE,
.rxfifo0esize = (FDCAN3_RXFIFO0_WORDS / FDCAN3_RXFIFO0_SIZE),
.rxfifo1esize = (FDCAN3_RXFIFO1_WORDS / FDCAN3_RXFIFO1_SIZE),
.txeventesize = (FDCAN3_TXEVENTFIFO_WORDS / FDCAN3_TXEVENTFIFO_SIZE),
.txbufferesize = (FDCAN3_TXFIFIOQ_WORDS / FDCAN3_TXFIFIOQ_SIZE),
#ifdef CONFIG_STM32_FDCAN3_LOOPBACK
.loopback = true,
#endif
/* FDCAN3 Message RAM */
.msgram =
{
(uint32_t *)(STM32_CANRAM3_BASE + (FDCAN3_STDFILTER_INDEX << 2)),
(uint32_t *)(STM32_CANRAM3_BASE + (FDCAN3_EXTFILTERS_INDEX << 2)),
(uint32_t *)(STM32_CANRAM3_BASE + (FDCAN3_RXFIFO0_INDEX << 2)),
(uint32_t *)(STM32_CANRAM3_BASE + (FDCAN3_RXFIFO1_INDEX << 2)),
(uint32_t *)(STM32_CANRAM3_BASE + (FDCAN3_TXEVENTFIFO_INDEX << 2)),
(uint32_t *)(STM32_CANRAM3_BASE + (FDCAN3_TXFIFOQ_INDEX << 2))
}
};
/* FDCAN3 variable driver state */
static struct stm32_fdcan_s g_fdcan3priv;
#endif /* CONFIG_STM32_FDCAN3 */
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Name: fdcan_getreg
*
* Description:
* Read the value of a FDCAN register.
*
* Input Parameters:
* priv - A reference to the FDCAN peripheral state
* offset - The offset to the register to read
*
* Returned Value:
*
****************************************************************************/
#ifdef CONFIG_STM32_FDCAN_REGDEBUG
static uint32_t fdcan_getreg(struct stm32_fdcan_s *priv, int offset)
{
const struct stm32_config_s *config = priv->config;
uintptr_t regaddr = 0;
uint32_t regval = 0;
/* Read the value from the register */
regaddr = config->base + offset;
regval = getreg32(regaddr);
/* Is this the same value that we read from the same register last time?
* Are we polling the register? If so, suppress some of the output.
*/
if (regaddr == priv->regaddr && regval == priv->regval)
{
if (priv->count == 0xffffffff || ++priv->count > 3)
{
if (priv->count == 4)
{
ninfo("...\n");
}
return regval;
}
}
/* No this is a new address or value */
else
{
/* Did we print "..." for the previous value? */
if (priv->count > 3)
{
/* Yes.. then show how many times the value repeated */
ninfo("[repeats %d more times]\n", priv->count - 3);
}
/* Save the new address, value, and count */
priv->regaddr = regaddr;
priv->regval = regval;
priv->count = 1;
}
/* Show the register value read */
ninfo("%08" PRIx32 "->%08" PRIx32 "\n", regaddr, regval);
return regval;
}
#else
static uint32_t fdcan_getreg(struct stm32_fdcan_s *priv, int offset)
{
const struct stm32_config_s *config = priv->config;
return getreg32(config->base + offset);
}
#endif
/****************************************************************************
* Name: fdcan_putreg
*
* Description:
* Set the value of a FDCAN register.
*
* Input Parameters:
* priv - A reference to the FDCAN peripheral state
* offset - The offset to the register to write
* regval - The value to write to the register
*
* Returned Value:
* None
*
****************************************************************************/
#ifdef CONFIG_STM32_FDCAN_REGDEBUG
static void fdcan_putreg(struct stm32_fdcan_s *priv, int offset,
uint32_t regval)
{
const struct stm32_config_s *config = priv->config;
uintptr_t regaddr = config->base + offset;
/* Show the register value being written */
ninfo("%08" PRIx32 "->%08" PRIx32 "\n", regaddr, regval);
/* Write the value */
putreg32(regval, regaddr);
}
#else
static void fdcan_putreg(struct stm32_fdcan_s *priv, int offset,
uint32_t regval)
{
const struct stm32_config_s *config = priv->config;
putreg32(regval, config->base + offset);
}
#endif
/****************************************************************************
* Name: fdcan_dumpctrlregs
*
* Description:
* Dump the contents of all CAN control registers
*
* Input Parameters:
* priv - A reference to the CAN block status
*
* Returned Value:
* None
*
****************************************************************************/
#ifdef CONFIG_STM32_FDCAN_REGDEBUG
static void fdcan_dumpregs(struct stm32_fdcan_s *priv,
const char *msg)
{
const struct stm32_config_s *config = priv->config;
ninfo("CAN%d Control and Status Registers: %s\n", config->port, msg);
ninfo(" Base: %08" PRIx32 "\n", config->base);
/* CAN control and status registers */
ninfo(" CCCR: %08" PRIx32 " TEST: %08" PRIx32 "\n",
getreg32(config->base + STM32_FDCAN_CCCR_OFFSET),
getreg32(config->base + STM32_FDCAN_TEST_OFFSET));
ninfo(" NBTP: %08" PRIx32 " DBTP: %08" PRIx32 "\n",
getreg32(config->base + STM32_FDCAN_NBTP_OFFSET),
getreg32(config->base + STM32_FDCAN_DBTP_OFFSET));
ninfo(" IE: %08" PRIx32 " TIE: %08" PRIx32 "\n",
getreg32(config->base + STM32_FDCAN_IE_OFFSET),
getreg32(config->base + STM32_FDCAN_TXBTIE_OFFSET));
ninfo(" ILE: %08" PRIx32 " ILS: %08" PRIx32 "\n",
getreg32(config->base + STM32_FDCAN_ILE_OFFSET),
getreg32(config->base + STM32_FDCAN_ILS_OFFSET));
ninfo(" TXBC: %08" PRIx32 "\n",
getreg32(config->base + STM32_FDCAN_TXBC_OFFSET));
}
#endif
/****************************************************************************
* Name: fdcan_dumprxregs
*
* Description:
* Dump the contents of all Rx status registers
*
* Input Parameters:
* priv - A reference to the CAN block status
*
* Returned Value:
* None
*
****************************************************************************/
#ifdef CONFIG_STM32_FDCAN_REGDEBUG
static void fdcan_dumprxregs(struct stm32_fdcan_s *priv,
const char *msg)
{
const struct stm32_config_s *config = priv->config;
ninfo("CAN%d Rx Registers: %s\n", config->port, msg);
ninfo(" Base: %08" PRIx32 "\n", config->base);
ninfo(" PSR: %08" PRIx32 " ECR: %08" PRIx32
" HPMS: %08" PRIx32 "\n",
getreg32(config->base + STM32_FDCAN_PSR_OFFSET),
getreg32(config->base + STM32_FDCAN_ECR_OFFSET),
getreg32(config->base + STM32_FDCAN_HPMS_OFFSET));
ninfo(" RXF0S: %08" PRIx32 " RXF0A: %08" PRIx32 "\n",
getreg32(config->base + STM32_FDCAN_RXF0S_OFFSET),
getreg32(config->base + STM32_FDCAN_RXF0A_OFFSET));
ninfo(" RXF1S: %08" PRIx32 " RXF1A: %08" PRIx32 "\n",
getreg32(config->base + STM32_FDCAN_RXF1S_OFFSET),
getreg32(config->base + STM32_FDCAN_RXF1A_OFFSET));
ninfo(" IR: %08" PRIx32 " IE: %08" PRIx32 "\n",
getreg32(config->base + STM32_FDCAN_IR_OFFSET),
getreg32(config->base + STM32_FDCAN_IE_OFFSET));
}
#endif
/****************************************************************************
* Name: fdcan_dumptxregs
*
* Description:
* Dump the contents of all Tx buffer registers
*
* Input Parameters:
* priv - A reference to the CAN block status
*
* Returned Value:
* None
*
****************************************************************************/
#ifdef CONFIG_STM32_FDCAN_REGDEBUG
static void fdcan_dumptxregs(struct stm32_fdcan_s *priv,
const char *msg)
{
const struct stm32_config_s *config = priv->config;
ninfo("CAN%d Tx Registers: %s\n", config->port, msg);
ninfo(" Base: %08" PRIx32 "\n", config->base);
ninfo(" PSR: %08" PRIx32 " ECR: %08" PRIx32 "\n",
getreg32(config->base + STM32_FDCAN_PSR_OFFSET),
getreg32(config->base + STM32_FDCAN_ECR_OFFSET));
ninfo(" TXQFS: %08" PRIx32 " TXBAR: %08" PRIx32
" TXBRP: %08" PRIx32 "\n",
getreg32(config->base + STM32_FDCAN_TXFQS_OFFSET),
getreg32(config->base + STM32_FDCAN_TXBAR_OFFSET),
getreg32(config->base + STM32_FDCAN_TXBRP_OFFSET));
ninfo(" TXBTO: %08" PRIx32 " TXBCR: %08" PRIx32 "\n",
getreg32(config->base + STM32_FDCAN_TXBTO_OFFSET),
getreg32(config->base + STM32_FDCAN_TXBCR_OFFSET));
ninfo(" TXEFS: %08" PRIx32 " TXEFA: %08" PRIx32 "\n",
getreg32(config->base + STM32_FDCAN_TXEFS_OFFSET),
getreg32(config->base + STM32_FDCAN_TXEFA_OFFSET));
ninfo(" IR: %08" PRIx32 " IE: %08" PRIx32
" TIE: %08" PRIx32 "\n",
getreg32(config->base + STM32_FDCAN_IR_OFFSET),
getreg32(config->base + STM32_FDCAN_IE_OFFSET),
getreg32(config->base + STM32_FDCAN_TXBTIE_OFFSET));
}
#endif
/****************************************************************************
* Name: fdcan_dumpramlayout
*
* Description:
* Print the layout of the message RAM
*
* Input Parameters:
* priv - A reference to the CAN block status
*
* Returned Value:
* None
*
****************************************************************************/
#ifdef CONFIG_STM32_FDCAN_REGDEBUG
static void fdcan_dumpramlayout(struct stm32_fdcan_s *priv)
{
const struct stm32_config_s *config = priv->config;
ninfo(" ******* FDCAN%d Message RAM layout *******\n", config->port);
ninfo(" Start # Elmnt Elmnt size (words)\n");
if (config->nstdfilters > 0)
{
ninfo("STD filters %p %4d %2d\n",
config->msgram.stdfilters,
config->nstdfilters,
1);
}
if (config->nextfilters > 0)
{
ninfo("EXT filters %p %4d %2d\n",
config->msgram.extfilters,
config->nextfilters,
2);
}
if (config->nrxfifo0 > 0)
{
ninfo("RX FIFO 0 %p %4d %2d\n",
config->msgram.rxfifo0,
config->nrxfifo0,
config->rxfifo0esize);
}
if (config->nrxfifo1 > 0)
{
ninfo("RX FIFO 1 %p %4d %2d\n",
config->msgram.rxfifo1,
config->nrxfifo1,
config->rxfifo1esize);
}
if (config->ntxeventfifo > 0)
{
ninfo("TX EVENT %p %4d %2d\n",
config->msgram.txeventfifo,
config->ntxeventfifo,
config->txeventesize);
}
if (config->ntxfifoq > 0)
{
ninfo("TX FIFO %p %4d %2d\n",
config->msgram.txfifoq,
config->ntxfifoq,
config->txbufferesize);
}
}
#endif
/****************************************************************************
* Name: fdcan_start_busoff_recovery_sequence
*
* Description:
* This function initiates the BUS-OFF recovery sequence.
* CAN Specification Rev. 2.0 or ISO11898-1:2015.
* According the STM32G4 datasheet section 44.3.2 Software initialziation.
*
* Input Parameters:
* priv - An instance of the FDCAN driver state structure.
*
* Returned Value:
* Zero (OK) is returned on success. Otherwise a negated errno value is
* returned to indicate the nature of the error.
*
****************************************************************************/
#if 0 /* not used for now */
static int
fdcan_start_busoff_recovery_sequence(struct stm32_fdcan_s *priv)
{
uint32_t regval = 0;
DEBUGASSERT(priv);
/* Only start BUS-OFF recovery if we are in BUS-OFF state */
regval = fdcan_getreg(priv, STM32_FDCAN_PSR_OFFSET);
if ((regval & FDCAN_PSR_BO) == 0)
{
return -EPERM;
}
/* Disable initialization mode to issue the recovery sequence */
regval = fdcan_getreg(priv, STM32_FDCAN_CCCR_OFFSET);
regval &= ~FDCAN_CCCR_INIT;
fdcan_putreg(priv, STM32_FDCAN_CCCR_OFFSET, regval);
return OK;
}
#endif
/****************************************************************************
* Name: fdcan_reset
*
* Description:
* Reset the FDCAN device. Called early to initialize the hardware. This
* function is called, before fdcan_setup() and on error conditions.
*
* Input Parameters:
* dev - An instance of the "upper half" can driver state structure.
*
* Returned Value:
* None
*
****************************************************************************/
static void fdcan_reset(struct stm32_fdcan_s *priv)
{
const struct stm32_config_s *config = NULL;
uint32_t regval = 0;
irqstate_t flags;
DEBUGASSERT(priv);
config = priv->config;
DEBUGASSERT(config);
ninfo("FDCAN%d\n", config->port);
UNUSED(config);
/* Disable all interrupts */
fdcan_putreg(priv, STM32_FDCAN_IE_OFFSET, 0);
fdcan_putreg(priv, STM32_FDCAN_TXBTIE_OFFSET, 0);
/* Make sure that all buffers are released.
*
* REVISIT: What if a thread is waiting for a buffer? The following
* will not wake up any waiting threads.
*/
/* Disable the FDCAN controller.
* REVISIT: Should fdcan_shutdown() be called here?
*/
/* Reset the FD CAN.
* REVISIT: Since there is only a single reset for both FDCAN
* controllers, do we really want to use the RCC reset here?
* This will nuke operation of the second controller if another
* device is registered.
*/
flags = enter_critical_section();
regval = getreg32(STM32_RCC_APB1RSTR1);
regval |= RCC_APB1RSTR1_FDCANRST;
putreg32(regval, STM32_RCC_APB1RSTR1);
regval &= ~RCC_APB1RSTR1_FDCANRST;
putreg32(regval, STM32_RCC_APB1RSTR1);
leave_critical_section(flags);
priv->state = FDCAN_STATE_RESET;
}
/****************************************************************************
* Name: fdcan_setup
*
* Description:
* Configure the FDCAN. This method is called the first time that the FDCAN
* device is opened. This will occur when the port is first opened.
* This setup includes configuring and attaching FDCAN interrupts.
* All FDCAN interrupts are disabled upon return.
*
* Input Parameters:
* dev - An instance of the "upper half" can driver state structure.
*
* Returned Value:
* Zero on success; a negated errno on failure
*
****************************************************************************/
static int fdcan_setup(struct stm32_fdcan_s *priv)
{
const struct stm32_config_s *config = NULL;
int ret = 0;
DEBUGASSERT(priv);
config = priv->config;
DEBUGASSERT(config);
ninfo("FDCAN%d\n", config->port);
/* FDCAN hardware initialization */
ret = fdcan_hw_initialize(priv);
if (ret < 0)
{
nerr("ERROR: FDCAN%d H/W initialization failed: %d\n",
config->port, ret);
return ret;
}
fdcan_dumpregs(priv, "After hardware initialization");
/* Attach the FDCAN interrupt handlers */
ret = irq_attach(config->irq0, fdcan_interrupt, priv);
if (ret < 0)
{
nerr("ERROR: Failed to attach FDCAN%d line 0 IRQ (%d)",
config->port, config->irq0);
return ret;
}
ret = irq_attach(config->irq1, fdcan_interrupt, priv);
if (ret < 0)
{
nerr("ERROR: Failed to attach FDCAN%d line 1 IRQ (%d)",
config->port, config->irq1);
return ret;
}
priv->state = FDCAN_STATE_SETUP;
/* Enable the interrupts at the NVIC (they are still disabled at the FDCAN
* peripheral).
*/
up_enable_irq(config->irq0);
up_enable_irq(config->irq1);
return OK;
}
/****************************************************************************
* Name: fdcan_shutdown
*
* Description:
* Disable the FDCAN. This method is called when the FDCAN device
* is closed. This method reverses the operation the setup method.
*
* Input Parameters:
* dev - An instance of the "upper half" can driver state structure.
*
* Returned Value:
* None
*
****************************************************************************/
static void fdcan_shutdown(struct stm32_fdcan_s *priv)
{
const struct stm32_config_s *config = NULL;
uint32_t regval = 0;
DEBUGASSERT(priv);
config = priv->config;
DEBUGASSERT(config);
ninfo("FDCAN%d\n", config->port);
/* Disable FDCAN interrupts at the NVIC */
up_disable_irq(config->irq0);
up_disable_irq(config->irq1);
/* Disable all interrupts from the FDCAN peripheral */
fdcan_putreg(priv, STM32_FDCAN_IE_OFFSET, 0);
fdcan_putreg(priv, STM32_FDCAN_TXBTIE_OFFSET, 0);
/* Detach the FDCAN interrupt handler */
irq_detach(config->irq0);
irq_detach(config->irq1);
/* Disable device by setting the Clock Stop Request bit */
regval = fdcan_getreg(priv, STM32_FDCAN_CCCR_OFFSET);
regval |= FDCAN_CCCR_CSR;
fdcan_putreg(priv, STM32_FDCAN_CCCR_OFFSET, regval);
/* Wait for Init and Clock Stop Acknowledge bits to verify
* device is in the powered down state
*/
while ((fdcan_getreg(priv, STM32_FDCAN_CCCR_OFFSET) & FDCAN_CCCR_INIT)
== 0);
while ((fdcan_getreg(priv, STM32_FDCAN_CCCR_OFFSET) & FDCAN_CCCR_CSA)
== 0);
priv->state = FDCAN_STATE_DISABLED;
}
/****************************************************************************
* Name: fdcan_rx0int
*
* Description:
* Call to enable or disable RX0 interrupts.
*
* Input Parameters:
* priv - reference to the private CAN driver state structure
*
* Returned Value:
* None
*
****************************************************************************/
static void fdcan_rx0int(struct stm32_fdcan_s *priv, bool enable)
{
const struct stm32_config_s *config = NULL;
uint32_t regval = 0;
DEBUGASSERT(priv);
config = priv->config;
DEBUGASSERT(config);
ninfo("CAN%" PRIu8 "RX0 enable: %d\n", config->port, enable);
/* Enable/disable the FIFO 0 message pending interrupt */
regval = fdcan_getreg(priv, STM32_FDCAN_IE_OFFSET);
if (enable)
{
regval |= FDCAN_RXFIFO0_INTS;
}
else
{
regval &= ~FDCAN_RXFIFO0_INTS;
}
fdcan_putreg(priv, STM32_FDCAN_IE_OFFSET, regval);
}
/****************************************************************************
* Name: fdcan_rx1int
*
* Description:
* Call to enable or disable RX1 interrupts.
*
* Input Parameters:
* priv - reference to the private CAN driver state structure
*
* Returned Value:
* None
*
****************************************************************************/
static void fdcan_rx1int(struct stm32_fdcan_s *priv, bool enable)
{
const struct stm32_config_s *config = NULL;
uint32_t regval = 0;
DEBUGASSERT(priv);
config = priv->config;
DEBUGASSERT(config);
ninfo("CAN%" PRIu8 "RX1 enable: %d\n", config->port, enable);
/* Enable/disable the FIFO 1 message pending interrupt */
regval = fdcan_getreg(priv, STM32_FDCAN_IE_OFFSET);
if (enable)
{
regval |= FDCAN_RXFIFO1_INTS;
}
else
{
regval &= ~FDCAN_RXFIFO1_INTS;
}
fdcan_putreg(priv, STM32_FDCAN_IE_OFFSET, regval);
}
/****************************************************************************
* Name: fdcan_txint
*
* Description:
* Call to enable or disable TX interrupts.
*
* Input Parameters:
* dev - An instance of the "upper half" can driver state structure.
*
* Returned Value:
* None
*
****************************************************************************/
static void fdcan_txint(struct stm32_fdcan_s *priv, bool enable)
{
const struct stm32_config_s *config = NULL;
uint32_t regval = 0;
DEBUGASSERT(priv);
config = priv->config;
DEBUGASSERT(config);
ninfo("CAN%" PRIu8 "TX enable: %d\n", config->port, enable);
/* Enable/disable the receive interrupts */
regval = fdcan_getreg(priv, STM32_FDCAN_IE_OFFSET);
if (enable)
{
regval |= FDCAN_TXFIFOQ_INTS;
}
else
{
regval &= ~FDCAN_TXFIFOQ_INTS;
}
fdcan_putreg(priv, STM32_FDCAN_IE_OFFSET, regval);
}
#ifdef CONFIG_NET_CAN_ERRORS
/****************************************************************************
* Name: fdcan_txint
*
* Description:
* Call to enable or disable CAN SCE interrupts.
*
* Input Parameters:
* priv - reference to the private CAN driver state structure
*
* Returned Value:
* None
*
****************************************************************************/
static void fdcan_errint(struct stm32_fdcan_s *priv, bool enable)
{
const struct stm32_config_s *config = NULL;
uint32_t regval = 0;
DEBUGASSERT(priv);
config = priv->config;
DEBUGASSERT(config);
ninfo("CAN%" PRIu8 "ERR enable: %d\n", config->port, enable);
/* Enable/disable the transmit mailbox interrupt */
regval = fdcan_getreg(priv, STM32_FDCAN_IE_OFFSET);
if (enable)
{
regval |= FDCAN_ANYERR_INTS;
}
else
{
regval &= ~FDCAN_ANYERR_INTS;
}
fdcan_putreg(priv, STM32_FDCAN_IE_OFFSET, regval);
}
#endif
/****************************************************************************
* Name: fdcan_send
*
* Description:
* Send one can message.
*
* One CAN-message consists of a maximum of 10 bytes. A message is
* composed of at least the first 2 bytes (when there are no data bytes).
*
* Byte 0: Bits 0-7: Bits 3-10 of the 11-bit CAN identifier
* Byte 1: Bits 5-7: Bits 0-2 of the 11-bit CAN identifier
* Bit 4: Remote Transmission Request (RTR)
* Bits 0-3: Data Length Code (DLC)
* Bytes 2-10: CAN data
*
* Input Parameters:
* dev - An instance of the "upper half" can driver state structure.
*
* Returned Value:
* Zero on success; a negated errno on failure
*
****************************************************************************/
static int fdcan_send(struct stm32_fdcan_s *priv)
{
const struct stm32_config_s *config = NULL;
volatile uint32_t *txbuffer = NULL;
const uint8_t *src = NULL;
uint32_t *dest = NULL;
uint32_t regval = 0;
unsigned int ndx = 0;
unsigned int nbytes = 0;
uint32_t wordbuffer = 0;
unsigned int i = 0;
DEBUGASSERT(priv);
config = priv->config;
DEBUGASSERT(config);
fdcan_dumptxregs(priv, "Before send");
/* That that FIFO elements were configured */
DEBUGASSERT(config->ntxfifoq > 0);
/* Get our reserved Tx FIFO/queue put index */
regval = fdcan_getreg(priv, STM32_FDCAN_TXFQS_OFFSET);
DEBUGASSERT((regval & FDCAN_TXFQS_TFQF) == 0);
ndx = (regval & FDCAN_TXFQS_TFQPI_MASK) >> FDCAN_TXFQS_TFQPI_SHIFT;
/* And the TX buffer corresponding to this index */
txbuffer = (config->msgram.txfifoq + ndx * config->txbufferesize);
/* Format the TX FIFOQ entry
*
* Format word T0:
* Transfer message ID (ID) - Value from message structure
* Remote Transmission Request (RTR) - Value from message structure
* Extended Identifier (XTD) - Depends on configuration.
* Error state indicator (ESI) - ESI bit in CAN FD
*
* Format word T1:
* Data Length Code (DLC) - Value from message structure
* Bit Rate Switch (BRS) - Bit rate switching for CAN FD
* FD format (FDF) - Frame transmited in CAN FD format
* Event FIFO Control (EFC) - Do not store events.
* Message Marker (MM) - Always zero
*/
txbuffer[0] = 0;
txbuffer[1] = 0;
/* CAN 2.0 or CAN FD */
if (priv->dev.d_len == sizeof(struct can_frame))
{
struct can_frame *frame = NULL;
frame = (struct can_frame *)priv->dev.d_buf;
ninfo("CAN%" PRIu8 " 2.0 ID: %" PRIu32 " DLC: %" PRIu8 "\n",
config->port, (uint32_t)frame->can_id, frame->can_dlc);
/* Extended or standard ID */
#ifdef CONFIG_NET_CAN_EXTID
if ((frame->can_id & CAN_EFF_FLAG) != 0)
{
DEBUGASSERT(frame->can_id < (1 << 29));
txbuffer[0] |= BUFFER_R0_EXTID(frame->can_id) | BUFFER_R0_XTD;
}
else
#endif
{
DEBUGASSERT(frame->can_id < (1 << 11));
txbuffer[0] |= BUFFER_R0_STDID(frame->can_id);
}
/* Set DLC */
txbuffer[1] |= BUFFER_R1_DLC(frame->can_dlc);
/* Set flags */
if ((frame->can_id & CAN_RTR_FLAG) != 0)
{
txbuffer[0] |= BUFFER_R0_RTR;
}
/* Reset CAN FD bits */
txbuffer[0] &= ~BUFFER_R0_ESI;
txbuffer[1] &= ~BUFFER_R1_FDF;
txbuffer[1] &= ~BUFFER_R1_BRS;
/* Followed by the amount of data corresponding to the DLC (T2..) */
src = frame->data;
nbytes = frame->can_dlc;
}
#ifdef CONFIG_NET_CAN_CANFD
else /* CAN FD frame */
{
struct canfd_frame *frame = (struct canfd_frame *)priv->dev.d_buf;
frame = (struct canfd_frame *)priv->dev.d_buf;
ninfo("CAN%" PRIu8 " FD ID: %" PRIu32 " len: %" PRIu8 "\n",
config->port, (uint32_t)frame->can_id, frame->len);
/* Extended or standard ID */
#ifdef CONFIG_NET_CAN_EXTID
if ((frame->can_id & CAN_EFF_FLAG) != 0)
{
DEBUGASSERT(frame->can_id < (1 << 29));
txbuffer[0] |= BUFFER_R0_EXTID(frame->can_id) | BUFFER_R0_XTD;
}
else
#endif
{
DEBUGASSERT(frame->can_id < (1 << 11));
txbuffer[0] |= BUFFER_R0_STDID(frame->can_id);
}
/* CANFD frame */
txbuffer[1] |= BUFFER_R1_FDF;
/* Set DLC */
txbuffer[1] |= BUFFER_R1_DLC(len_to_can_dlc[frame->len]);
/* Set flags */
if ((frame->can_id & CAN_RTR_FLAG) != 0)
{
txbuffer[0] |= BUFFER_R0_RTR;
}
if ((frame->flags & CANFD_BRS) != 0)
{
txbuffer[1] |= BUFFER_R1_BRS;
}
if ((frame->flags & CANFD_ESI) != 0)
{
txbuffer[0] |= BUFFER_R0_ESI;
}
/* Followed by the amount of data corresponding to the DLC (T2..) */
src = frame->data;
nbytes = frame->len;
}
#endif
dest = (uint32_t *)&txbuffer[2];
/* Writes must be word length */
for (i = 0; i < nbytes; i += 4)
{
/* Little endian is assumed */
wordbuffer = src[0] |
(src[1] << 8) |
(src[2] << 16) |
(src[3] << 24);
src += 4;
*dest++ = wordbuffer;
}
/* Enable transmit interrupts from the TX FIFOQ buffer by setting TC
* interrupt bit in IR (also requires that the TC interrupt is enabled)
*/
fdcan_putreg(priv, STM32_FDCAN_TXBTIE_OFFSET, (1 << ndx));
/* And request to send the packet */
fdcan_putreg(priv, STM32_FDCAN_TXBAR_OFFSET, (1 << ndx));
return OK;
}
/****************************************************************************
* Name: fdcan_txready
*
* Description:
* Return true if the FDCAN hardware can accept another TX message.
*
* Input Parameters:
* dev - An instance of the "upper half" can driver state structure.
*
* Returned Value:
* True if the FDCAN hardware is ready to accept another TX message.
*
****************************************************************************/
static bool fdcan_txready(struct stm32_fdcan_s *priv)
{
uint32_t regval = 0;
bool notfull = false;
/* Return the state of the TX FIFOQ. Return TRUE if the TX FIFO/Queue is
* not full.
*/
regval = fdcan_getreg(priv, STM32_FDCAN_TXFQS_OFFSET);
notfull = ((regval & FDCAN_TXFQS_TFQF) == 0);
return notfull;
}
/****************************************************************************
* Name: fdcan_rx0interrupt_work
*
* Description:
* CAN RX FIFO 0 worker
*
****************************************************************************/
static void fdcan_rx0interrupt_work(void *arg)
{
struct stm32_fdcan_s *priv = (struct stm32_fdcan_s *)arg;
const struct stm32_config_s *config = NULL;
uint32_t regval = 0;
unsigned int nelem = 0;
unsigned int ndx = 0;
DEBUGASSERT(priv);
config = priv->config;
DEBUGASSERT(config);
/* Clear the RX FIFO0 new message interrupt */
fdcan_putreg(priv, STM32_FDCAN_IR_OFFSET, FDCAN_INT_RF0N);
regval = fdcan_getreg(priv, STM32_FDCAN_RXF0S_OFFSET);
nelem = (regval & FDCAN_RXFS_FFL_MASK) >> FDCAN_RXFS_FFL_SHIFT;
if (nelem > 0)
{
/* Handle the newly received message in FIFO0 */
ndx = (regval & FDCAN_RXFS_FGI_MASK) >> FDCAN_RXFS_FGI_SHIFT;
if ((regval & FDCAN_RXFS_RFL) != 0)
{
nerr("ERROR: Message lost: %08" PRIx32 "\n", regval);
}
else
{
fdcan_receive(priv,
config->msgram.rxfifo0 +
(ndx * priv->config->rxfifo0esize),
priv->config->rxfifo0esize);
#ifdef CONFIG_NET_CAN_ERRORS
/* Turning back on all configured RX error interrupts */
regval = fdcan_getreg(priv, STM32_FDCAN_IE_OFFSET);
regval |= FDCAN_RXERR_INTS;
fdcan_putreg(priv, STM32_FDCAN_IE_OFFSET, regval);
#endif
}
/* Acknowledge reading the FIFO entry */
fdcan_putreg(priv, STM32_FDCAN_RXF0A_OFFSET, ndx);
}
/* Re-enable CAN RX interrupts */
fdcan_rx0int(priv, true);
}
/****************************************************************************
* Name: fdcan_rx1interrupt_work
*
* Description:
* CAN RX FIFO 1 worker
*
****************************************************************************/
static void fdcan_rx1interrupt_work(void *arg)
{
struct stm32_fdcan_s *priv = (struct stm32_fdcan_s *)arg;
const struct stm32_config_s *config = NULL;
uint32_t regval = 0;
unsigned int nelem = 0;
unsigned int ndx = 0;
DEBUGASSERT(priv);
config = priv->config;
DEBUGASSERT(config);
/* Clear the RX FIFO1 new message interrupt */
fdcan_putreg(priv, STM32_FDCAN_IR_OFFSET, FDCAN_INT_RF1N);
/* Check if there is anything in RX FIFO1 */
regval = fdcan_getreg(priv, STM32_FDCAN_RXF1S_OFFSET);
nelem = (regval & FDCAN_RXFS_FFL_MASK) >> FDCAN_RXFS_FFL_SHIFT;
if (nelem == 0)
{
/* Clear the RX FIFO1 interrupt (and all other FIFO1-related
* interrupts)
*/
/* Handle the newly received message in FIFO1 */
ndx = (regval & FDCAN_RXFS_FGI_MASK) >> FDCAN_RXFS_FGI_SHIFT;
if ((regval & FDCAN_RXFS_RFL) != 0)
{
nerr("ERROR: Message lost: %08" PRIx32 "\n", regval);
}
else
{
fdcan_receive(priv,
config->msgram.rxfifo1 +
(ndx * priv->config->rxfifo1esize),
priv->config->rxfifo1esize);
#ifdef CONFIG_NET_CAN_ERRORS
/* Turning back on all configured RX error interrupts */
regval = fdcan_getreg(priv, STM32_FDCAN_IE_OFFSET);
regval |= FDCAN_RXERR_INTS;
fdcan_putreg(priv, STM32_FDCAN_IE_OFFSET, regval);
#endif
}
/* Acknowledge reading the FIFO entry */
fdcan_putreg(priv, STM32_FDCAN_RXF1A_OFFSET, ndx);
}
/* Re-enable CAN RX interrupts */
fdcan_rx1int(priv, true);
}
/****************************************************************************
* Name: fdcan_txdone_work
****************************************************************************/
static void fdcan_txdone_work(void *arg)
{
struct stm32_fdcan_s *priv = (struct stm32_fdcan_s *)arg;
fdcan_txdone(priv);
/* There should be space for a new TX in any event. Poll the network for
* new XMIT data
*/
net_lock();
devif_poll(&priv->dev, fdcan_txpoll);
net_unlock();
}
/****************************************************************************
* Name: fdcan_txdone
****************************************************************************/
static void fdcan_txdone(struct stm32_fdcan_s *priv)
{
const struct stm32_config_s *config = NULL;
unsigned int ndx = 0;
uint32_t regval = 0;
DEBUGASSERT(priv);
config = priv->config;
DEBUGASSERT(config);
/* Clear the pending TX completion interrupt (and all
* other TX-related interrupts)
*/
fdcan_putreg(priv, STM32_FDCAN_IR_OFFSET, FDCAN_TXFIFOQ_INTS);
/* Check all TX buffers */
regval = fdcan_getreg(priv, STM32_FDCAN_TXBTO_OFFSET);
for (ndx = 0; ndx < config->ntxfifoq; ndx++)
{
if ((regval & (1 << ndx)) != 0)
{
/* Tell the upper half that the transfer is finished. */
NETDEV_TXDONE(&priv->dev);
}
}
#ifdef CONFIG_NET_CAN_ERRORS
/* Turning back on PEA and PED error interrupts */
regval = fdcan_getreg(priv, STM32_FDCAN_IE_OFFSET);
regval |= (FDCAN_INT_PEA | FDCAN_INT_PED);
fdcan_putreg(priv, STM32_FDCAN_IE_OFFSET, regval);
#endif
/* Re-enable TX interrupts */
fdcan_txint(priv, true);
}
#ifdef CONFIG_NET_CAN_ERRORS
/****************************************************************************
* Name: fdcan_error_work
****************************************************************************/
static void fdcan_error_work(void *arg)
{
struct stm32_fdcan_s *priv = (struct stm32_fdcan_s *)arg;
uint32_t pending = 0;
uint32_t ir = 0;
uint32_t ie = 0;
uint32_t psr = 0;
/* Get the set of pending interrupts. */
ir = fdcan_getreg(priv, STM32_FDCAN_IR_OFFSET);
ie = fdcan_getreg(priv, STM32_FDCAN_IE_OFFSET);
pending = (ir & ie);
/* Check for common errors */
if ((pending & FDCAN_CMNERR_INTS) != 0)
{
/* When a protocol error ocurrs, the problem is recorded in
* the LEC/DLEC fields of the PSR register. In lieu of
* seprate interrupt flags for each error, the hardware
* groups procotol errors under a single interrupt each for
* arbitration and data phases.
*
* These errors have a tendency to flood the system with
* interrupts, so they are disabled here until we get a
* successful transfer/receive on the hardware
*/
psr = fdcan_getreg(priv, STM32_FDCAN_PSR_OFFSET);
if ((psr & FDCAN_PSR_LEC_MASK) != 0)
{
ie &= ~(FDCAN_INT_PEA | FDCAN_INT_PED);
fdcan_putreg(priv, STM32_FDCAN_IE_OFFSET, ie);
}
/* Clear the error indications */
fdcan_putreg(priv, STM32_FDCAN_IR_OFFSET, FDCAN_CMNERR_INTS);
}
/* Check for transmission errors */
if ((pending & FDCAN_TXERR_INTS) != 0)
{
/* An Acknowledge-Error will occur if for example the device
* is not connected to the bus.
*
* The CAN-Standard states that the Chip has to retry the
* message forever, which will produce an ACKE every time.
* To prevent this Interrupt-Flooding and the high CPU-Load
* we disable the ACKE here as long we didn't transfer at
* least one message successfully (see FDCAN_INT_TC below).
*/
/* Clear the error indications */
fdcan_putreg(priv, STM32_FDCAN_IR_OFFSET, FDCAN_TXERR_INTS);
}
/* Check for reception errors */
if ((pending & FDCAN_RXERR_INTS) != 0)
{
/* To prevent Interrupt-Flooding the current active
* RX error interrupts are disabled. After successfully
* receiving at least one CAN packet all RX error interrupts
* are turned back on.
*
* The Interrupt-Flooding can for example occur if the
* configured CAN speed does not match the speed of the other
* CAN nodes in the network.
*/
ie &= ~(pending & FDCAN_RXERR_INTS);
fdcan_putreg(priv, STM32_FDCAN_IE_OFFSET, ie);
/* Clear the error indications */
fdcan_putreg(priv, STM32_FDCAN_IR_OFFSET, FDCAN_RXERR_INTS);
}
/* Report errors */
net_lock();
fdcan_error(priv, pending & FDCAN_ANYERR_INTS);
net_unlock();
/* Re-enable ERROR interrupts */
fdcan_errint(priv, true);
}
/****************************************************************************
* Name: fdcan_error
*
* Description:
* Report a CAN error
*
* Input Parameters:
* dev - CAN-common state data
* status - Interrupt status with error bits set
*
* Returned Value:
* None
*
****************************************************************************/
static void fdcan_error(struct stm32_fdcan_s *priv, uint32_t status)
{
struct can_frame *frame = (struct can_frame *)priv->rxdesc;
uint32_t psr = 0;
uint16_t errbits = 0;
uint8_t data[CAN_ERR_DLC];
DEBUGASSERT(priv != NULL);
/* Encode error bits */
errbits = 0;
memset(data, 0, sizeof(data));
/* Always fill in "static" error conditions, but set the signaling bit
* only if the condition has changed (see IRQ-Flags below)
* They have to be filled in every time CAN_ERROR_CONTROLLER is set.
*/
psr = fdcan_getreg(priv, STM32_FDCAN_PSR_OFFSET);
if ((psr & FDCAN_PSR_EP) != 0)
{
data[1] |= (CAN_ERR_CRTL_RX_PASSIVE | CAN_ERR_CRTL_TX_PASSIVE);
}
if ((psr & FDCAN_PSR_EW) != 0)
{
data[1] |= (CAN_ERR_CRTL_RX_WARNING | CAN_ERR_CRTL_TX_WARNING);
}
if ((status & (FDCAN_INT_EP | FDCAN_INT_EW)) != 0)
{
/* "Error Passive" or "Error Warning" status changed */
errbits |= CAN_ERR_CRTL;
}
if ((status & FDCAN_INT_PEA) != 0)
{
/* Protocol Error in Arbitration Phase */
if ((psr & FDCAN_PSR_LEC_MASK) != 0)
{
/* Error code present */
if ((psr & FDCAN_PSR_LEC(FDCAN_PSR_EC_STUFF_ERROR)) != 0)
{
/* Stuff Error */
errbits |= CAN_ERR_PROT;
data[2] |= CAN_ERR_PROT_STUFF;
}
if ((psr & FDCAN_PSR_LEC(FDCAN_PSR_EC_FORM_ERROR)) != 0)
{
/* Format Error */
errbits |= CAN_ERR_PROT;
data[2] |= CAN_ERR_PROT_FORM;
}
if ((psr & FDCAN_PSR_LEC(FDCAN_PSR_EC_ACK_ERROR)) != 0)
{
/* Acknowledge Error */
errbits |= CAN_ERR_ACK;
}
if ((psr & FDCAN_PSR_LEC(FDCAN_PSR_EC_BIT0_ERROR)) != 0)
{
/* Bit0 Error */
errbits |= CAN_ERR_PROT;
data[2] |= CAN_ERR_PROT_BIT0;
}
if ((psr & FDCAN_PSR_LEC(FDCAN_PSR_EC_BIT1_ERROR)) != 0)
{
/* Bit1 Error */
errbits |= CAN_ERR_PROT;
data[2] |= CAN_ERR_PROT_BIT1;
}
if ((psr & FDCAN_PSR_LEC(FDCAN_PSR_EC_CRC_ERROR)) != 0)
{
/* Receive CRC Error */
errbits |= CAN_ERR_PROT;
data[3] |= (CAN_ERR_PROT_LOC_CRC_SEQ |
CAN_ERR_PROT_LOC_CRC_DEL);
}
if ((psr & FDCAN_PSR_LEC(FDCAN_PSR_EC_NO_CHANGE)) != 0)
{
/* No Change in Error */
errbits |= CAN_ERR_PROT;
data[2] |= CAN_ERR_PROT_UNSPEC;
}
}
}
if ((status & FDCAN_INT_PED) != 0)
{
/* Protocol Error in Data Phase */
if ((psr & FDCAN_PSR_DLEC_MASK) != 0)
{
/* Error code present */
if ((psr & FDCAN_PSR_DLEC(FDCAN_PSR_EC_STUFF_ERROR)) != 0)
{
/* Stuff Error */
errbits |= CAN_ERR_PROT;
data[2] |= CAN_ERR_PROT_STUFF;
}
if ((psr & FDCAN_PSR_DLEC(FDCAN_PSR_EC_FORM_ERROR)) != 0)
{
/* Format Error */
errbits |= CAN_ERR_PROT;
data[2] |= CAN_ERR_PROT_FORM;
}
if ((psr & FDCAN_PSR_DLEC(FDCAN_PSR_EC_ACK_ERROR)) != 0)
{
/* Acknowledge Error */
errbits |= CAN_ERR_ACK;
}
if ((psr & FDCAN_PSR_DLEC(FDCAN_PSR_EC_BIT0_ERROR)) != 0)
{
/* Bit0 Error */
errbits |= CAN_ERR_PROT;
data[2] |= CAN_ERR_PROT_BIT0;
}
if ((psr & FDCAN_PSR_DLEC(FDCAN_PSR_EC_BIT1_ERROR)) != 0)
{
/* Bit1 Error */
errbits |= CAN_ERR_PROT;
data[2] |= CAN_ERR_PROT_BIT1;
}
if ((psr & FDCAN_PSR_DLEC(FDCAN_PSR_EC_CRC_ERROR)) != 0)
{
/* Receive CRC Error */
errbits |= CAN_ERR_PROT;
data[3] |= (CAN_ERR_PROT_LOC_CRC_SEQ |
CAN_ERR_PROT_LOC_CRC_DEL);
}
if ((psr & FDCAN_PSR_DLEC(FDCAN_PSR_EC_NO_CHANGE)) != 0)
{
/* No Change in Error */
errbits |= CAN_ERR_PROT;
data[2] |= CAN_ERR_PROT_UNSPEC;
}
}
}
if ((status & FDCAN_INT_BO) != 0)
{
/* Bus_Off Status changed */
if ((psr & FDCAN_PSR_BO) != 0)
{
errbits |= CAN_ERR_BUSOFF;
}
else
{
errbits |= CAN_ERR_RESTARTED;
}
}
if ((status & (FDCAN_INT_RF0L | FDCAN_INT_RF1L)) != 0)
{
/* Receive FIFO 0/1 Message Lost
* Receive FIFO 1 Message Lost
*/
errbits |= CAN_ERR_CRTL;
data[1] |= CAN_ERR_CRTL_RX_OVERFLOW;
}
if ((status & FDCAN_INT_TEFL) != 0)
{
/* Tx Event FIFO Element Lost */
errbits |= CAN_ERR_CRTL;
data[1] |= CAN_ERR_CRTL_TX_OVERFLOW;
}
if ((status & FDCAN_INT_TOO) != 0)
{
/* Timeout Occurred */
errbits |= CAN_ERR_TX_TIMEOUT;
}
if ((status & (FDCAN_INT_MRAF | FDCAN_INT_ELO)) != 0)
{
/* Message RAM Access Failure
* Error Logging Overflow
*/
errbits |= CAN_ERR_CRTL;
data[1] |= CAN_ERR_CRTL_UNSPEC;
}
if (errbits != 0)
{
nerr("ERROR: errbits = %08" PRIx16 "\n", errbits);
/* Copy frame */
frame->can_id = errbits;
frame->can_dlc = CAN_ERR_DLC;
memcpy(frame->data, data, CAN_ERR_DLC);
/* Copy the buffer pointer to priv->dev.. Set amount of data
* in priv->dev.d_len
*/
priv->dev.d_len = sizeof(struct can_frame);
priv->dev.d_buf = (uint8_t *)frame;
/* Send to socket interface */
NETDEV_ERRORS(&priv->dev);
can_input(&priv->dev);
/* Point the packet buffer back to the next Tx buffer that will be
* used during the next write. If the write queue is full, then
* this will point at an active buffer, which must not be written
* to. This is OK because devif_poll won't be called unless the
* queue is not full.
*/
priv->dev.d_buf = (uint8_t *)priv->txdesc;
}
}
#endif /* CONFIG_NET_CAN_ERRORS */
/****************************************************************************
* Name: fdcan_receive
*
* Description:
* Receive an FDCAN messages
*
* Input Parameters:
* dev - CAN-common state data
* rxbuffer - The RX buffer containing the received messages
* nwords - The length of the RX buffer (element size in words).
*
* Returned Value:
* None
*
****************************************************************************/
static void fdcan_receive(struct stm32_fdcan_s *priv,
volatile uint32_t *rxbuffer,
unsigned long nwords)
{
fdcan_dumprxregs(dev->cd_priv, "Before receive");
/* CAN 2.0 or CAN FD */
#ifdef CONFIG_NET_CAN_CANFD
if ((rxbuffer[1] & BUFFER_R1_FDF) != 0)
{
struct canfd_frame *frame = (struct canfd_frame *)priv->rxdesc;
/* Format the CAN FD header */
/* Extract the RTR bit */
if ((rxbuffer[0] & BUFFER_R0_RTR) != 0)
{
frame->can_id |= CAN_RTR_FLAG;
}
#ifdef CONFIG_NET_CAN_EXTID
if ((rxbuffer[0] & BUFFER_R0_XTD) != 0)
{
/* Save the extended ID of the newly received message */
frame->can_id = ((rxbuffer[0] & BUFFER_R0_EXTID_MASK) >>
BUFFER_R0_EXTID_SHIFT);
frame->can_id |= CAN_EFF_FLAG;
}
else
{
frame->can_id = ((rxbuffer[0] & BUFFER_R0_STDID_MASK) >>
BUFFER_R0_STDID_SHIFT);
frame->can_id &= ~CAN_EFF_FLAG;
}
#else
if ((rxbuffer[0] & BUFFER_R0_XTD) != 0)
{
/* Drop any messages with extended IDs */
return;
}
/* Save the standard ID of the newly received message */
frame->can_id = ((rxbuffer[0] & BUFFER_R0_STDID_MASK) >>
BUFFER_R0_STDID_SHIFT);
#endif
/* Word R1 contains the DLC and timestamp */
frame->len = can_dlc_to_len[((rxbuffer[1] & BUFFER_R1_DLC_MASK) >>
BUFFER_R1_DLC_SHIFT)];
/* Get CANFD flags */
frame->flags = 0;
if ((rxbuffer[0] & BUFFER_R0_ESI) != 0)
{
frame->flags |= CANFD_ESI;
}
if ((rxbuffer[1] & BUFFER_R1_BRS) != 0)
{
frame->flags |= CANFD_BRS;
}
/* Save the message data */
memcpy(frame->data, (void *)&rxbuffer[2], frame->len);
/* Copy the buffer pointer to priv->dev.. Set amount of data
* in priv->dev.d_len
*/
priv->dev.d_len = sizeof(struct canfd_frame);
priv->dev.d_buf = (uint8_t *)frame;
}
else
#endif
{
struct can_frame *frame = (struct can_frame *)priv->rxdesc;
/* Format the CAN header */
/* Extract the RTR bit */
if ((rxbuffer[0] & BUFFER_R0_RTR) != 0)
{
frame->can_id |= CAN_RTR_FLAG;
}
#ifdef CONFIG_NET_CAN_EXTID
if ((rxbuffer[0] & BUFFER_R0_XTD) != 0)
{
/* Save the extended ID of the newly received message */
frame->can_id = ((rxbuffer[0] & BUFFER_R0_EXTID_MASK) >>
BUFFER_R0_EXTID_SHIFT);
frame->can_id |= CAN_EFF_FLAG;
}
else
{
frame->can_id = ((rxbuffer[0] & BUFFER_R0_STDID_MASK) >>
BUFFER_R0_STDID_SHIFT);
frame->can_id &= ~CAN_EFF_FLAG;
}
#else
if ((rxbuffer[0] & BUFFER_R0_XTD) != 0)
{
/* Drop any messages with extended IDs */
return;
}
/* Save the standard ID of the newly received message */
frame->can_id = ((rxbuffer[0] & BUFFER_R0_STDID_MASK) >>
BUFFER_R0_STDID_SHIFT);
#endif
/* Word R1 contains the DLC and timestamp */
frame->can_dlc = ((rxbuffer[1] & BUFFER_R1_DLC_MASK) >>
BUFFER_R1_DLC_SHIFT);
/* Save the message data */
memcpy(frame->data, (void *)&rxbuffer[2], frame->can_dlc);
/* Copy the buffer pointer to priv->dev.. Set amount of data
* in priv->dev.d_len
*/
priv->dev.d_len = sizeof(struct can_frame);
priv->dev.d_buf = (uint8_t *)frame;
}
/* Send to socket interface */
NETDEV_RXPACKETS(&priv->dev);
can_input(&priv->dev);
/* Point the packet buffer back to the next Tx buffer that will be
* used during the next write. If the write queue is full, then
* this will point at an active buffer, which must not be written
* to. This is OK because devif_poll won't be called unless the
* queue is not full.
*/
priv->dev.d_buf = (uint8_t *)priv->txdesc;
}
/****************************************************************************
* Name: fdcan_interrupt
*
* Description:
* Common FDCAN interrupt handler
*
* irq - The IRQ number of the interrupt.
* context - The register state save array at the time of the interrupt.
*
* Returned Value:
* Zero on success; a negated errno on failure
*
****************************************************************************/
static int fdcan_interrupt(int irq, void *context, void *arg)
{
struct stm32_fdcan_s *priv = (struct stm32_fdcan_s *)arg;
uint32_t pending = 0;
DEBUGASSERT(priv != NULL);
/* Get the set of pending interrupts. */
pending = fdcan_getreg(priv, STM32_FDCAN_IR_OFFSET);
#ifdef CONFIG_NET_CAN_ERRORS
/* Check for any errors */
if ((pending & FDCAN_ANYERR_INTS) != 0)
{
/* Disable further CAN ERROR interrupts and schedule to perform the
* interrupt processing on the worker thread
*/
fdcan_errint(priv, false);
work_queue(CANWORK, &priv->irqwork, fdcan_error_work, priv, 0);
}
#endif
/* Check for successful completion of a transmission */
if ((pending & FDCAN_INT_TC) != 0)
{
/* Disable further TX CAN interrupts. here can be no race
* condition here.
*/
fdcan_txint(priv, false);
work_queue(CANWORK, &priv->irqwork, fdcan_txdone_work, priv, 0);
}
else if ((pending & FDCAN_TXFIFOQ_INTS) != 0)
{
/* Clear unhandled TX events */
fdcan_putreg(priv, STM32_FDCAN_IR_OFFSET, FDCAN_TXFIFOQ_INTS);
}
if (pending & FDCAN_INT_RF1N)
{
/* Disable further CAN RX interrupts and schedule to perform the
* interrupt processing on the worker thread
*/
fdcan_rx1int(priv, false);
work_queue(CANWORK, &priv->irqwork,
fdcan_rx1interrupt_work, priv, 0);
}
/* Clear the RX FIFO0 new message interrupt */
if (pending & FDCAN_INT_RF0N)
{
/* Disable further CAN RX interrupts and schedule to perform the
* interrupt processing on the worker thread
*/
fdcan_rx0int(priv, false);
work_queue(CANWORK, &priv->irqwork,
fdcan_rx0interrupt_work, priv, 0);
}
return OK;
}
/****************************************************************************
* Name: fdcan_hw_initialize
*
* Description:
* FDCAN hardware initialization
*
* Input Parameters:
* priv - A pointer to the private data structure for this FDCAN peripheral
*
* Returned Value:
* Zero on success; a negated errno value on failure.
*
****************************************************************************/
static int fdcan_hw_initialize(struct stm32_fdcan_s *priv)
{
const struct stm32_config_s *config = NULL;
volatile uint32_t *msgram = NULL;
uint32_t regval = 0;
uint32_t cntr = 0;
DEBUGASSERT(priv);
config = priv->config;
DEBUGASSERT(config);
ninfo("FDCAN%d\n", config->port);
/* Clean message RAM */
msgram = config->msgram.stdfilters;
cntr = (FDCAN_MSGRAM_WORDS + 1);
while (cntr > 0)
{
*msgram++ = 0;
cntr--;
}
/* Configure FDCAN pins */
stm32_configgpio(config->rxpinset);
stm32_configgpio(config->txpinset);
/* Renable device if previosuly disabled in fdcan_shutdown() */
if (priv->state == FDCAN_STATE_DISABLED)
{
/* Reset Clock Stop Request bit */
regval = fdcan_getreg(priv, STM32_FDCAN_CCCR_OFFSET);
regval &= ~FDCAN_CCCR_CSR;
fdcan_putreg(priv, STM32_FDCAN_CCCR_OFFSET, regval);
/* Wait for Clock Stop Acknowledge bit reset to indicate
* device is operational
*/
while ((fdcan_getreg(priv, STM32_FDCAN_CCCR_OFFSET) & FDCAN_CCCR_CSA)
!= 0);
}
/* Enable the Initialization state */
regval = fdcan_getreg(priv, STM32_FDCAN_CCCR_OFFSET);
regval |= FDCAN_CCCR_INIT;
fdcan_putreg(priv, STM32_FDCAN_CCCR_OFFSET, regval);
/* Wait for initialization mode to take effect */
while ((fdcan_getreg(priv, STM32_FDCAN_CCCR_OFFSET) & FDCAN_CCCR_INIT)
== 0);
/* Enable writing to configuration registers */
regval = fdcan_getreg(priv, STM32_FDCAN_CCCR_OFFSET);
regval |= FDCAN_CCCR_CCE;
fdcan_putreg(priv, STM32_FDCAN_CCCR_OFFSET, regval);
/* Global Filter Configuration:
*
* ANFS=0: Store all non matching standard frame in RX FIFO0
* ANFE=0: Store all non matching extended frame in RX FIFO0
*/
regval = FDCAN_RXGFC_ANFE_RX_FIFO0 | FDCAN_RXGFC_ANFS_RX_FIFO0;
fdcan_putreg(priv, STM32_FDCAN_RXGFC_OFFSET, regval);
/* Extended ID Filter AND mask */
fdcan_putreg(priv, STM32_FDCAN_XIDAM_OFFSET, 0x1fffffff);
/* Disable all interrupts */
fdcan_putreg(priv, STM32_FDCAN_IE_OFFSET, 0);
fdcan_putreg(priv, STM32_FDCAN_TXBTIE_OFFSET, 0);
/* All interrupts directed to Line 0. But disable both interrupt lines 0
* and 1 for now.
*
* REVISIT: Only interrupt line 0 is used by this driver.
*/
fdcan_putreg(priv, STM32_FDCAN_ILS_OFFSET, 0);
fdcan_putreg(priv, STM32_FDCAN_ILE_OFFSET, 0);
/* Clear all pending interrupts. */
fdcan_putreg(priv, STM32_FDCAN_IR_OFFSET, FDCAN_INT_ALL);
/* Configure FDCAN bit timing */
fdcan_putreg(priv, STM32_FDCAN_NBTP_OFFSET, priv->nbtp);
fdcan_putreg(priv, STM32_FDCAN_DBTP_OFFSET, priv->dbtp);
/* Configure message RAM starting addresses and sizes. */
regval = FDCAN_RXGFC_LSS(config->nstdfilters);
regval |= FDCAN_RXGFC_LSE(config->nextfilters);
fdcan_putreg(priv, STM32_FDCAN_RXGFC_OFFSET, regval);
/* Dump RAM layout */
fdcan_dumpramlayout(priv);
/* Configure Message Filters */
/* Disable all standard filters */
msgram = config->msgram.stdfilters;
cntr = config->nstdfilters;
while (cntr > 0)
{
*msgram++ = STDFILTER_S0_SFEC_DISABLE;
cntr--;
}
/* Disable all extended filters */
msgram = config->msgram.extfilters;
cntr = config->nextfilters;
while (cntr > 0)
{
*msgram = EXTFILTER_F0_EFEC_DISABLE;
msgram = msgram + 2;
cntr--;
}
/* Input clock divider configuration */
regval = FDCANCLK_PDIV;
fdcan_putreg(priv, STM32_FDCAN_CKDIV_OFFSET, regval);
/* CC control register */
regval = fdcan_getreg(priv, STM32_FDCAN_CCCR_OFFSET);
regval &= ~(FDCAN_CCCR_NISO | FDCAN_CCCR_FDOE | FDCAN_CCCR_BRSE);
/* Select ISO11898-1 or Non ISO Bosch CAN FD Specification V1.0 */
switch (config->format)
{
case FDCAN_ISO11898_1_FORMAT:
{
break;
}
case FDCAN_NONISO_BOSCH_V1_FORMAT:
{
regval |= FDCAN_CCCR_NISO;
break;
}
default:
{
return -EINVAL;
}
}
/* Select Classic CAN mode or FD mode with or without fast bit rate
* switching
*/
switch (config->mode)
{
case FDCAN_CLASSIC_MODE:
{
break;
}
#ifdef CONFIG_NET_CAN_CANFD
case FDCAN_FD_MODE:
{
regval |= FDCAN_CCCR_FDOE;
break;
}
case FDCAN_FD_BRS_MODE:
{
regval |= (FDCAN_CCCR_FDOE | FDCAN_CCCR_BRSE);
break;
}
#endif
default:
{
return -EINVAL;
}
}
/* Set the initial CAN mode */
fdcan_putreg(priv, STM32_FDCAN_CCCR_OFFSET, regval);
/* Enable FIFO/Queue mode */
regval = fdcan_getreg(priv, STM32_FDCAN_TXBC_OFFSET);
#ifdef CONFIG_STM32_FDCAN_QUEUE_MODE
regval |= FDCAN_TXBC_TFQM;
#else
regval &= ~FDCAN_TXBC_TFQM;
#endif
fdcan_putreg(priv, STM32_FDCAN_TXBC_OFFSET, regval);
#ifdef STM32_FDCAN_LOOPBACK
/* Is loopback mode selected for this peripheral? */
if (config->loopback)
{
/* FDCAN_CCCR_TEST - Test mode enable
* FDCAN_CCCR_MON - Bus monitoring mode (for internal loopback)
* FDCAN_TEST_LBCK - Loopback mode
*/
regval = fdcan_getreg(priv, STM32_FDCAN_CCCR_OFFSET);
regval |= (FDCAN_CCCR_TEST | FDCAN_CCCR_MON);
fdcan_putreg(priv, STM32_FDCAN_CCCR_OFFSET, regval);
regval = fdcan_getreg(priv, STM32_FDCAN_TEST_OFFSET);
regval |= FDCAN_TEST_LBCK;
fdcan_putreg(priv, STM32_FDCAN_TEST_OFFSET, regval);
}
#endif
/* Configure interrupt lines */
/* Direct all interrupts to Line 0.
*
* Bits in the ILS register correspond to each FDCAN interrupt; A bit
* set to '1' is directed to interrupt line 1; a bit cleared to '0'
* is directed interrupt line 0.
*
* REVISIT: Nothing is done here. Only interrupt line 0 is used by
* this driver and ILS was already cleared above.
*/
/* Enable only interrupt line 0. */
fdcan_putreg(priv, STM32_FDCAN_ILE_OFFSET, FDCAN_ILE_EINT0);
/* Disable initialization mode to enable normal operation */
regval = fdcan_getreg(priv, STM32_FDCAN_CCCR_OFFSET);
regval &= ~FDCAN_CCCR_INIT;
fdcan_putreg(priv, STM32_FDCAN_CCCR_OFFSET, regval);
return OK;
}
/****************************************************************************
* Function: fdcan_ifup
*
* Description:
* NuttX Callback: Bring up the Ethernet interface when an IP address is
* provided
*
* Input Parameters:
* dev - Reference to the NuttX driver state structure
*
* Returned Value:
* None
*
* Assumptions:
*
****************************************************************************/
static int fdcan_ifup(struct net_driver_s *dev)
{
struct stm32_fdcan_s *priv =
(struct stm32_fdcan_s *)dev->d_private;
const struct stm32_config_s *config = NULL;
DEBUGASSERT(priv);
config = priv->config;
DEBUGASSERT(config);
/* Setup CAN */
fdcan_setup(priv);
/* Enable interrupts */
fdcan_rx0int(priv, true);
fdcan_rx1int(priv, true);
fdcan_txint(priv, true);
#ifdef CONFIG_NET_CAN_ERRORS
fdcan_errint(priv, true);
#endif
/* Enable the interrupts at the NVIC */
up_enable_irq(config->irq0);
up_enable_irq(config->irq1);
priv->bifup = true;
priv->txdesc = (struct can_frame *)priv->tx_pool;
priv->rxdesc = (struct can_frame *)priv->rx_pool;
priv->dev.d_buf = (uint8_t *)priv->txdesc;
return OK;
}
/****************************************************************************
* Function: fdcan_ifdown
*
* Description:
* NuttX Callback: Stop the interface.
*
* Input Parameters:
* dev - Reference to the NuttX driver state structure
*
* Returned Value:
* None
*
* Assumptions:
*
****************************************************************************/
static int fdcan_ifdown(struct net_driver_s *dev)
{
struct stm32_fdcan_s *priv =
(struct stm32_fdcan_s *)dev->d_private;
/* Disable CAN interrupts */
fdcan_shutdown(priv);
/* Reset CAN */
fdcan_reset(priv);
return OK;
}
/****************************************************************************
* Function: fdcan_txpoll
*
* Description:
* The transmitter is available, check if the network has any outgoing
* packets ready to send. This is a callback from devif_poll().
* devif_poll() may be called:
*
* 1. When the preceding TX packet send is complete,
* 2. When the preceding TX packet send timesout and the interface is reset
* 3. During normal TX polling
*
* Input Parameters:
* dev - Reference to the NuttX driver state structure
*
* Returned Value:
* OK on success; a negated errno on failure
*
* Assumptions:
* May or may not be called from an interrupt handler. In either case,
* global interrupts are disabled, either explicitly or indirectly through
* interrupt handling logic.
*
****************************************************************************/
static int fdcan_txpoll(struct net_driver_s *dev)
{
struct stm32_fdcan_s *priv =
(struct stm32_fdcan_s *)dev->d_private;
/* If the polling resulted in data that should be sent out on the network,
* the field d_len is set to a value > 0.
*/
if (priv->dev.d_len > 0)
{
fdcan_txdone(priv);
/* Send the packet */
fdcan_send(priv);
/* Check if there is room in the device to hold another packet. If
* not, return a non-zero value to terminate the poll.
*/
if (fdcan_txready(priv) == false)
{
return -EBUSY;
}
}
/* If zero is returned, the polling will continue until all connections
* have been examined.
*/
return 0;
}
/****************************************************************************
* Function: fdcan_txavail_work
*
* Description:
* Perform an out-of-cycle poll on the worker thread.
*
* Input Parameters:
* arg - Reference to the NuttX driver state structure (cast to void*)
*
* Returned Value:
* None
*
* Assumptions:
* Called on the higher priority worker thread.
*
****************************************************************************/
static void fdcan_txavail_work(void *arg)
{
struct stm32_fdcan_s *priv = (struct stm32_fdcan_s *)arg;
/* Ignore the notification if the interface is not yet up */
net_lock();
if (priv->bifup)
{
/* Check if there is room in the hardware to hold another outgoing
* packet.
*/
if (fdcan_txready(priv))
{
/* No, there is space for another transfer. Poll the network for
* new XMIT data.
*/
devif_poll(&priv->dev, fdcan_txpoll);
}
}
net_unlock();
}
/****************************************************************************
* Function: fdcan_txavail
*
* Description:
* Driver callback invoked when new TX data is available. This is a
* stimulus perform an out-of-cycle poll and, thereby, reduce the TX
* latency.
*
* Input Parameters:
* dev - Reference to the NuttX driver state structure
*
* Returned Value:
* None
*
* Assumptions:
* Called in normal user mode
*
****************************************************************************/
static int fdcan_txavail(struct net_driver_s *dev)
{
struct stm32_fdcan_s *priv =
(struct stm32_fdcan_s *)dev->d_private;
/* Is our single work structure available? It may not be if there are
* pending interrupt actions and we will have to ignore the Tx
* availability action.
*/
if (work_available(&priv->pollwork))
{
/* Schedule to serialize the poll on the worker thread. */
fdcan_txavail_work(priv);
}
return OK;
}
/****************************************************************************
* Function: fdcan_ioctl
*
* Description:
* PHY ioctl command handler
*
* Input Parameters:
* dev - Reference to the NuttX driver state structure
* cmd - ioctl command
* arg - Argument accompanying the command
*
* Returned Value:
* Zero (OK) on success; a negated errno value on failure.
*
* Assumptions:
*
****************************************************************************/
#ifdef CONFIG_NETDEV_IOCTL
static int fdcan_netdev_ioctl(struct net_driver_s *dev, int cmd,
unsigned long arg);
{
struct stm32_fdcan_s *priv =
(struct stm32_fdcan_s *)dev->d_private;
int ret = OK;
DEBUGASSERT(priv);
switch (cmd)
{
/* TODO */
default:
ret = -ENOTTY;
break;
}
return ret;
}
#endif /* CONFIG_NETDEV_IOCTL */
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: stm32_cansockinitialize
*
* Description:
* Initialize the selected FDCAN port as CAN socket interface
*
* Input Parameters:
* Port number (for hardware that has multiple FDCAN interfaces)
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
int stm32_fdcansockinitialize(int port)
{
struct stm32_fdcan_s *priv = NULL;
const struct stm32_config_s *config = NULL;
int ret = OK;
ninfo("FDCAN%d\n", port);
/* Select FDCAN peripheral to be initialized */
#ifdef CONFIG_STM32_FDCAN1
if (port == FDCAN1)
{
/* Select the FDCAN1 device structure */
priv = &g_fdcan1priv;
config = &g_fdcan1const;
}
else
#endif
#ifdef CONFIG_STM32_FDCAN2
if (port == FDCAN2)
{
/* Select the FDCAN2 device structure */
priv = &g_fdcan2priv;
config = &g_fdcan2const;
}
else
#endif
#ifdef CONFIG_STM32_FDCAN3
if (port == FDCAN3)
{
/* Select the FDCAN3 device structure */
priv = &g_fdcan3priv;
config = &g_fdcan3const;
}
else
#endif
{
nerr("ERROR: Unsupported port %d\n", port);
ret = -EINVAL;
goto errout;
}
/* Perform one time data initialization */
memset(priv, 0, sizeof(struct stm32_fdcan_s));
priv->config = config;
/* Set the initial bit timing. This might change subsequently
* due to IOCTL command processing.
*/
priv->nbtp = config->nbtp;
priv->dbtp = config->dbtp;
/* Initialize the driver structure */
priv->dev.d_ifup = fdcan_ifup;
priv->dev.d_ifdown = fdcan_ifdown;
priv->dev.d_txavail = fdcan_txavail;
#ifdef CONFIG_NETDEV_IOCTL
priv->dev.d_ioctl = fdcan_netdev_ioctl;
#endif
priv->dev.d_private = priv;
/* Put the interface in the down state. This usually amounts to resetting
* the device and/or calling fdcan_ifdown().
*/
ninfo("callbacks done\n");
fdcan_ifdown(&priv->dev);
/* Register the device with the OS so that socket IOCTLs can be performed */
ret = netdev_register(&priv->dev, NET_LL_CAN);
errout:
return ret;
}
/****************************************************************************
* Name: arm_netinitialize
*
* Description:
* Initialize the CAN device interfaces. If there is more than one device
* interface in the chip, then board-specific logic will have to provide
* this function to determine which, if any, CAN interfaces should be
* initialized.
*
****************************************************************************/
#if !defined(CONFIG_NETDEV_LATEINIT)
void arm_netinitialize(void)
{
#ifdef CONFIG_STM32_CAN1
stm32_fdcansockinitialize(FDCAN1);
#endif
#ifdef CONFIG_STM32_CAN2
stm32_fdcansockinitialize(FDCAN2);
#endif
#ifdef CONFIG_STM32_CAN3
stm32_fdcansockinitialize(FDCAN3);
#endif
}
#endif
|
3f27df0ba7eefd3d5c525c23413210c86394ec7e
|
c9bc99866cfab223c777cfb741083be3e9439d81
|
/product/rdn1e1/include/mcp_rdn1e1_mmap.h
|
74f1a8f3ec689a8b34c5dcccecf1501548f2075d
|
[
"BSD-3-Clause"
] |
permissive
|
ARM-software/SCP-firmware
|
4738ca86ce42d82588ddafc2226a1f353ff2c797
|
f6bcca436768359ffeadd84d65e8ea0c3efc7ef1
|
refs/heads/master
| 2023-09-01T16:13:36.962036
| 2023-08-17T13:00:20
| 2023-08-31T07:43:37
| 134,399,880
| 211
| 165
|
NOASSERTION
| 2023-09-13T14:27:10
| 2018-05-22T10:35:56
|
C
|
UTF-8
|
C
| false
| false
| 1,783
|
h
|
mcp_rdn1e1_mmap.h
|
/*
* Arm SCP/MCP Software
* Copyright (c) 2017-2022, Arm Limited and Contributors. All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef MCP_RDN1E1_MMAP_H
#define MCP_RDN1E1_MMAP_H
#include <stdint.h>
/*
* Top-level base addresses
*/
#define MCP_SOC_EXPANSION1_BASE UINT32_C(0x01000000)
#define MCP_SOC_EXPANSION2_BASE UINT32_C(0x21000000)
#define MCP_SOC_EXPANSION3_BASE UINT32_C(0x40000000)
#define MCP_MHU_SCP_BASE UINT32_C(0x45600000)
#define MCP_SOC_EXPANSION4_BASE UINT32_C(0x48000000)
#define MCP_PERIPH_BASE UINT32_C(0x4C000000)
#define MCP_MEMORY_CONTROLLER UINT32_C(0x4E000000)
#define MCP_POWER_PERIPH_BASE UINT32_C(0x50000000)
#define MCP_SYS0_BASE UINT32_C(0x60000000)
#define MCP_SYS1_BASE UINT32_C(0xA0000000)
#define MCP_PPB_BASE_INTERNAL UINT32_C(0xE0000000)
#define MCP_PPB_BASE_EXTERNAL UINT32_C(0xE0040000)
/*
* Peripherals
*/
#define MCP_REFCLK_CNTCTL_BASE (MCP_PERIPH_BASE)
#define MCP_REFCLK_CNTBASE0_BASE (MCP_PERIPH_BASE + 0x1000)
#define MCP_UART0_BASE (MCP_PERIPH_BASE + 0x2000)
#define MCP_UART1_BASE (MCP_PERIPH_BASE + 0x3000)
#define MCP_WDOG_BASE (MCP_PERIPH_BASE + 0x6000)
#define MCP_MHU_AP_BASE (MCP_PERIPH_BASE + 0x400000)
/*
* Power control peripherals
*/
#define MCP_PIK_BASE (MCP_POWER_PERIPH_BASE)
/*
* System access port 1
*/
#define MCP_REFCLK_CNTCONTROL_BASE (MCP_SYS1_BASE + 0x2A430000)
/*
* Base addresses of MHU devices v2
*/
#define MCP_MHU_MCP_SCP_SND (MCP_MHU_SCP_BASE + 0x00000)
#define MCP_MHU_MCP_SCP_RCV (MCP_MHU_SCP_BASE + 0x10000)
#endif /* MCP_RDN1E1_MMAP_H */
|
ebbd32f091b299b23f2ca69287b0ee795ee0e560
|
7c857119fe1505b1d80d6e62969661c06dc1a2f4
|
/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiHci.c
|
1c9016cdcc13fe25586130f9332ff565d55eada0
|
[
"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
| 21,358
|
c
|
NvmExpressPeiHci.c
|
/** @file
The NvmExpressPei driver is used to manage non-volatile memory subsystem
which follows NVM Express specification at PEI phase.
Copyright (c) 2018 - 2019, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include "NvmExpressPei.h"
/**
Transfer MMIO Data to memory.
@param[in,out] MemBuffer Destination: Memory address.
@param[in] MmioAddr Source: MMIO address.
@param[in] Size Size for read.
@retval EFI_SUCCESS MMIO read sucessfully.
**/
EFI_STATUS
NvmeMmioRead (
IN OUT VOID *MemBuffer,
IN UINTN MmioAddr,
IN UINTN Size
)
{
UINTN Offset;
UINT8 Data;
UINT8 *Ptr;
// priority has adjusted
switch (Size) {
case 4:
*((UINT32 *)MemBuffer) = MmioRead32 (MmioAddr);
break;
case 8:
*((UINT64 *)MemBuffer) = MmioRead64 (MmioAddr);
break;
case 2:
*((UINT16 *)MemBuffer) = MmioRead16 (MmioAddr);
break;
case 1:
*((UINT8 *)MemBuffer) = MmioRead8 (MmioAddr);
break;
default:
Ptr = (UINT8 *)MemBuffer;
for (Offset = 0; Offset < Size; Offset += 1) {
Data = MmioRead8 (MmioAddr + Offset);
Ptr[Offset] = Data;
}
break;
}
return EFI_SUCCESS;
}
/**
Transfer memory data to MMIO.
@param[in,out] MmioAddr Destination: MMIO address.
@param[in] MemBuffer Source: Memory address.
@param[in] Size Size for write.
@retval EFI_SUCCESS MMIO write sucessfully.
**/
EFI_STATUS
NvmeMmioWrite (
IN OUT UINTN MmioAddr,
IN VOID *MemBuffer,
IN UINTN Size
)
{
UINTN Offset;
UINT8 Data;
UINT8 *Ptr;
// priority has adjusted
switch (Size) {
case 4:
MmioWrite32 (MmioAddr, *((UINT32 *)MemBuffer));
break;
case 8:
MmioWrite64 (MmioAddr, *((UINT64 *)MemBuffer));
break;
case 2:
MmioWrite16 (MmioAddr, *((UINT16 *)MemBuffer));
break;
case 1:
MmioWrite8 (MmioAddr, *((UINT8 *)MemBuffer));
break;
default:
Ptr = (UINT8 *)MemBuffer;
for (Offset = 0; Offset < Size; Offset += 1) {
Data = Ptr[Offset];
MmioWrite8 (MmioAddr + Offset, Data);
}
break;
}
return EFI_SUCCESS;
}
/**
Get the page offset for specific NVME based memory.
@param[in] BaseMemIndex The Index of BaseMem (0-based).
@retval - The page count for specific BaseMem Index
**/
UINT32
NvmeBaseMemPageOffset (
IN UINTN BaseMemIndex
)
{
UINT32 Pages;
UINTN Index;
UINT32 PageSizeList[5];
PageSizeList[0] = 1; /* ASQ */
PageSizeList[1] = 1; /* ACQ */
PageSizeList[2] = 1; /* SQs */
PageSizeList[3] = 1; /* CQs */
PageSizeList[4] = NVME_PRP_SIZE; /* PRPs */
if (BaseMemIndex > MAX_BASEMEM_COUNT) {
DEBUG ((DEBUG_ERROR, "%a: The input BaseMem index is invalid.\n", __FUNCTION__));
ASSERT (FALSE);
return 0;
}
Pages = 0;
for (Index = 0; Index < BaseMemIndex; Index++) {
Pages += PageSizeList[Index];
}
return Pages;
}
/**
Wait for NVME controller status to be ready or not.
@param[in] Private The pointer to the PEI_NVME_CONTROLLER_PRIVATE_DATA data structure.
@param[in] WaitReady Flag for waitting status ready or not.
@return EFI_SUCCESS Successfully to wait specific status.
@return others Fail to wait for specific controller status.
**/
EFI_STATUS
NvmeWaitController (
IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private,
IN BOOLEAN WaitReady
)
{
NVME_CSTS Csts;
EFI_STATUS Status;
UINT32 Index;
UINT8 Timeout;
//
// Cap.To specifies max delay time in 500ms increments for Csts.Rdy to set after
// Cc.Enable. Loop produces a 1 millisecond delay per itteration, up to 500 * Cap.To.
//
if (Private->Cap.To == 0) {
Timeout = 1;
} else {
Timeout = Private->Cap.To;
}
Status = EFI_SUCCESS;
for(Index = (Timeout * 500); Index != 0; --Index) {
MicroSecondDelay (1000);
//
// Check if the controller is initialized
//
Status = NVME_GET_CSTS (Private, &Csts);
if (EFI_ERROR(Status)) {
DEBUG ((DEBUG_ERROR, "%a: NVME_GET_CSTS fail, Status - %r\n", __FUNCTION__, Status));
return Status;
}
if ((BOOLEAN) Csts.Rdy == WaitReady) {
break;
}
}
if (Index == 0) {
Status = EFI_TIMEOUT;
}
return Status;
}
/**
Disable the Nvm Express controller.
@param[in] Private The pointer to the PEI_NVME_CONTROLLER_PRIVATE_DATA data structure.
@return EFI_SUCCESS Successfully disable the controller.
@return others Fail to disable the controller.
**/
EFI_STATUS
NvmeDisableController (
IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private
)
{
NVME_CC Cc;
NVME_CSTS Csts;
EFI_STATUS Status;
Status = NVME_GET_CSTS (Private, &Csts);
//
// Read Controller Configuration Register.
//
Status = NVME_GET_CC (Private, &Cc);
if (EFI_ERROR(Status)) {
DEBUG ((DEBUG_ERROR, "%a: NVME_GET_CC fail, Status - %r\n", __FUNCTION__, Status));
goto ErrorExit;
}
if (Cc.En == 1) {
Cc.En = 0;
//
// Disable the controller.
//
Status = NVME_SET_CC (Private, &Cc);
if (EFI_ERROR(Status)) {
DEBUG ((DEBUG_ERROR, "%a: NVME_SET_CC fail, Status - %r\n", __FUNCTION__, Status));
goto ErrorExit;
}
}
Status = NvmeWaitController (Private, FALSE);
if (EFI_ERROR(Status)) {
DEBUG ((DEBUG_ERROR, "%a: NvmeWaitController fail, Status - %r\n", __FUNCTION__, Status));
goto ErrorExit;
}
return EFI_SUCCESS;
ErrorExit:
DEBUG ((DEBUG_ERROR, "%a fail, Status - %r\n", __FUNCTION__, Status));
return Status;
}
/**
Enable the Nvm Express controller.
@param[in] Private The pointer to the PEI_NVME_CONTROLLER_PRIVATE_DATA data structure.
@return EFI_SUCCESS Successfully enable the controller.
@return EFI_DEVICE_ERROR Fail to enable the controller.
@return EFI_TIMEOUT Fail to enable the controller in given time slot.
**/
EFI_STATUS
NvmeEnableController (
IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private
)
{
NVME_CC Cc;
EFI_STATUS Status;
//
// Enable the controller
// CC.AMS, CC.MPS and CC.CSS are all set to 0
//
ZeroMem (&Cc, sizeof (NVME_CC));
Cc.En = 1;
Cc.Iosqes = 6;
Cc.Iocqes = 4;
Status = NVME_SET_CC (Private, &Cc);
if (EFI_ERROR(Status)) {
DEBUG ((DEBUG_ERROR, "%a: NVME_SET_CC fail, Status - %r\n", __FUNCTION__, Status));
goto ErrorExit;
}
Status = NvmeWaitController (Private, TRUE);
if (EFI_ERROR(Status)) {
DEBUG ((DEBUG_ERROR, "%a: NvmeWaitController fail, Status - %r\n", __FUNCTION__, Status));
goto ErrorExit;
}
return EFI_SUCCESS;
ErrorExit:
DEBUG ((DEBUG_ERROR, "%a fail, Status: %r\n", __FUNCTION__, Status));
return Status;
}
/**
Get the Identify Controller data.
@param[in] Private The pointer to the PEI_NVME_CONTROLLER_PRIVATE_DATA data structure.
@param[in] Buffer The Buffer used to store the Identify Controller data.
@return EFI_SUCCESS Successfully get the Identify Controller data.
@return others Fail to get the Identify Controller data.
**/
EFI_STATUS
NvmeIdentifyController (
IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private,
IN VOID *Buffer
)
{
EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket;
EFI_NVM_EXPRESS_COMMAND Command;
EFI_NVM_EXPRESS_COMPLETION Completion;
EFI_STATUS Status;
ZeroMem (&CommandPacket, sizeof(EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET));
ZeroMem (&Command, sizeof(EFI_NVM_EXPRESS_COMMAND));
ZeroMem (&Completion, sizeof(EFI_NVM_EXPRESS_COMPLETION));
Command.Cdw0.Opcode = NVME_ADMIN_IDENTIFY_CMD;
//
// According to Nvm Express 1.1 spec Figure 38, When not used, the field shall be cleared to 0h.
// For the Identify command, the Namespace Identifier is only used for the Namespace Data structure.
//
Command.Nsid = 0;
CommandPacket.NvmeCmd = &Command;
CommandPacket.NvmeCompletion = &Completion;
CommandPacket.TransferBuffer = Buffer;
CommandPacket.TransferLength = sizeof (NVME_ADMIN_CONTROLLER_DATA);
CommandPacket.CommandTimeout = NVME_GENERIC_TIMEOUT;
CommandPacket.QueueType = NVME_ADMIN_QUEUE;
//
// Set bit 0 (Cns bit) to 1 to identify the controller
//
CommandPacket.NvmeCmd->Cdw10 = 1;
CommandPacket.NvmeCmd->Flags = CDW10_VALID;
Status = NvmePassThruExecute (
Private,
NVME_CONTROLLER_NSID,
&CommandPacket
);
return Status;
}
/**
Get specified identify namespace data.
@param[in] Private The pointer to the PEI_NVME_CONTROLLER_PRIVATE_DATA data structure.
@param[in] NamespaceId The specified namespace identifier.
@param[in] Buffer The buffer used to store the identify namespace data.
@return EFI_SUCCESS Successfully get the identify namespace data.
@return EFI_DEVICE_ERROR Fail to get the identify namespace data.
**/
EFI_STATUS
NvmeIdentifyNamespace (
IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private,
IN UINT32 NamespaceId,
IN VOID *Buffer
)
{
EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket;
EFI_NVM_EXPRESS_COMMAND Command;
EFI_NVM_EXPRESS_COMPLETION Completion;
EFI_STATUS Status;
ZeroMem (&CommandPacket, sizeof(EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET));
ZeroMem (&Command, sizeof(EFI_NVM_EXPRESS_COMMAND));
ZeroMem (&Completion, sizeof(EFI_NVM_EXPRESS_COMPLETION));
Command.Cdw0.Opcode = NVME_ADMIN_IDENTIFY_CMD;
Command.Nsid = NamespaceId;
CommandPacket.NvmeCmd = &Command;
CommandPacket.NvmeCompletion = &Completion;
CommandPacket.TransferBuffer = Buffer;
CommandPacket.TransferLength = sizeof (NVME_ADMIN_NAMESPACE_DATA);
CommandPacket.CommandTimeout = NVME_GENERIC_TIMEOUT;
CommandPacket.QueueType = NVME_ADMIN_QUEUE;
//
// Set bit 0 (Cns bit) to 1 to identify a namespace
//
CommandPacket.NvmeCmd->Cdw10 = 0;
CommandPacket.NvmeCmd->Flags = CDW10_VALID;
Status = NvmePassThruExecute (
Private,
NamespaceId,
&CommandPacket
);
return Status;
}
/**
Dump the Identify Controller data.
@param[in] ControllerData The pointer to the NVME_ADMIN_CONTROLLER_DATA data structure.
**/
VOID
NvmeDumpControllerData (
IN NVME_ADMIN_CONTROLLER_DATA *ControllerData
)
{
UINT8 Sn[21];
UINT8 Mn[41];
CopyMem(Sn, ControllerData->Sn, sizeof (ControllerData->Sn));
Sn[20] = 0;
CopyMem(Mn, ControllerData->Mn, sizeof (ControllerData->Mn));
Mn[40] = 0;
DEBUG ((DEBUG_INFO, " == NVME IDENTIFY CONTROLLER DATA ==\n"));
DEBUG ((DEBUG_INFO, " PCI VID : 0x%x\n", ControllerData->Vid));
DEBUG ((DEBUG_INFO, " PCI SSVID : 0x%x\n", ControllerData->Ssvid));
DEBUG ((DEBUG_INFO, " SN : %a\n", Sn));
DEBUG ((DEBUG_INFO, " MN : %a\n", Mn));
DEBUG ((DEBUG_INFO, " FR : 0x%lx\n", *((UINT64*)ControllerData->Fr)));
DEBUG ((DEBUG_INFO, " RAB : 0x%x\n", ControllerData->Rab));
DEBUG ((DEBUG_INFO, " IEEE : 0x%x\n", *(UINT32*)ControllerData->Ieee_oui));
DEBUG ((DEBUG_INFO, " AERL : 0x%x\n", ControllerData->Aerl));
DEBUG ((DEBUG_INFO, " SQES : 0x%x\n", ControllerData->Sqes));
DEBUG ((DEBUG_INFO, " CQES : 0x%x\n", ControllerData->Cqes));
DEBUG ((DEBUG_INFO, " NN : 0x%x\n", ControllerData->Nn));
return;
}
/**
Create IO completion queue.
@param[in] Private The pointer to the PEI_NVME_CONTROLLER_PRIVATE_DATA data structure.
@return EFI_SUCCESS Successfully create io completion queue.
@return others Fail to create io completion queue.
**/
EFI_STATUS
NvmeCreateIoCompletionQueue (
IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private
)
{
EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket;
EFI_NVM_EXPRESS_COMMAND Command;
EFI_NVM_EXPRESS_COMPLETION Completion;
EFI_STATUS Status;
NVME_ADMIN_CRIOCQ CrIoCq;
ZeroMem (&CommandPacket, sizeof(EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET));
ZeroMem (&Command, sizeof(EFI_NVM_EXPRESS_COMMAND));
ZeroMem (&Completion, sizeof(EFI_NVM_EXPRESS_COMPLETION));
ZeroMem (&CrIoCq, sizeof(NVME_ADMIN_CRIOCQ));
CommandPacket.NvmeCmd = &Command;
CommandPacket.NvmeCompletion = &Completion;
Command.Cdw0.Opcode = NVME_ADMIN_CRIOCQ_CMD;
CommandPacket.TransferBuffer = Private->CqBuffer[NVME_IO_QUEUE];
CommandPacket.TransferLength = EFI_PAGE_SIZE;
CommandPacket.CommandTimeout = NVME_GENERIC_TIMEOUT;
CommandPacket.QueueType = NVME_ADMIN_QUEUE;
CrIoCq.Qid = NVME_IO_QUEUE;
CrIoCq.Qsize = NVME_CCQ_SIZE;
CrIoCq.Pc = 1;
CopyMem(&CommandPacket.NvmeCmd->Cdw10, &CrIoCq, sizeof (NVME_ADMIN_CRIOCQ));
CommandPacket.NvmeCmd->Flags = CDW10_VALID | CDW11_VALID;
Status = NvmePassThruExecute (
Private,
NVME_CONTROLLER_NSID,
&CommandPacket
);
return Status;
}
/**
Create IO submission queue.
@param[in] Private The pointer to the PEI_NVME_CONTROLLER_PRIVATE_DATA data structure.
@return EFI_SUCCESS Successfully create io submission queue.
@return others Fail to create io submission queue.
**/
EFI_STATUS
NvmeCreateIoSubmissionQueue (
IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private
)
{
EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket;
EFI_NVM_EXPRESS_COMMAND Command;
EFI_NVM_EXPRESS_COMPLETION Completion;
EFI_STATUS Status;
NVME_ADMIN_CRIOSQ CrIoSq;
ZeroMem (&CommandPacket, sizeof(EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET));
ZeroMem (&Command, sizeof(EFI_NVM_EXPRESS_COMMAND));
ZeroMem (&Completion, sizeof(EFI_NVM_EXPRESS_COMPLETION));
ZeroMem (&CrIoSq, sizeof(NVME_ADMIN_CRIOSQ));
CommandPacket.NvmeCmd = &Command;
CommandPacket.NvmeCompletion = &Completion;
Command.Cdw0.Opcode = NVME_ADMIN_CRIOSQ_CMD;
CommandPacket.TransferBuffer = Private->SqBuffer[NVME_IO_QUEUE];
CommandPacket.TransferLength = EFI_PAGE_SIZE;
CommandPacket.CommandTimeout = NVME_GENERIC_TIMEOUT;
CommandPacket.QueueType = NVME_ADMIN_QUEUE;
CrIoSq.Qid = NVME_IO_QUEUE;
CrIoSq.Qsize = NVME_CSQ_SIZE;
CrIoSq.Pc = 1;
CrIoSq.Cqid = NVME_IO_QUEUE;
CrIoSq.Qprio = 0;
CopyMem(&CommandPacket.NvmeCmd->Cdw10, &CrIoSq, sizeof (NVME_ADMIN_CRIOSQ));
CommandPacket.NvmeCmd->Flags = CDW10_VALID | CDW11_VALID;
Status = NvmePassThruExecute (
Private,
NVME_CONTROLLER_NSID,
&CommandPacket
);
return Status;
}
/**
Initialize the Nvm Express controller.
@param[in] Private The pointer to the PEI_NVME_CONTROLLER_PRIVATE_DATA data structure.
@retval EFI_SUCCESS The NVM Express Controller is initialized successfully.
@retval Others A device error occurred while initializing the controller.
**/
EFI_STATUS
NvmeControllerInit (
IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private
)
{
EFI_STATUS Status;
UINTN Index;
NVME_AQA Aqa;
NVME_ASQ Asq;
NVME_ACQ Acq;
NVME_VER Ver;
//
// Dump the NVME controller implementation version
//
NVME_GET_VER (Private, &Ver);
DEBUG ((DEBUG_INFO, "NVME controller implementation version: %d.%d\n", Ver.Mjr, Ver.Mnr));
//
// Read the controller Capabilities register and verify that the NVM command set is supported
//
NVME_GET_CAP (Private, &Private->Cap);
if (Private->Cap.Css != 0x01) {
DEBUG ((DEBUG_ERROR, "%a: The NVME controller doesn't support NVMe command set.\n", __FUNCTION__));
return EFI_UNSUPPORTED;
}
//
// Currently, the driver only supports 4k page size
//
if ((Private->Cap.Mpsmin + 12) > EFI_PAGE_SHIFT) {
DEBUG ((DEBUG_ERROR, "%a: The driver doesn't support page size other than 4K.\n", __FUNCTION__));
ASSERT (FALSE);
return EFI_UNSUPPORTED;
}
for (Index = 0; Index < NVME_MAX_QUEUES; Index++) {
Private->Pt[Index] = 0;
Private->Cid[Index] = 0;
ZeroMem ((VOID *)(UINTN)(&Private->SqTdbl[Index]), sizeof (NVME_SQTDBL));
ZeroMem ((VOID *)(UINTN)(&Private->CqHdbl[Index]), sizeof (NVME_CQHDBL));
}
ZeroMem (Private->Buffer, EFI_PAGE_SIZE * NVME_MEM_MAX_PAGES);
//
// Disable the NVME controller first
//
Status = NvmeDisableController (Private);
if (EFI_ERROR(Status)) {
DEBUG ((DEBUG_ERROR, "%a: NvmeDisableController fail, Status - %r\n", __FUNCTION__, Status));
return Status;
}
//
// Set the number of entries in admin submission & completion queues
//
Aqa.Asqs = NVME_ASQ_SIZE;
Aqa.Rsvd1 = 0;
Aqa.Acqs = NVME_ACQ_SIZE;
Aqa.Rsvd2 = 0;
//
// Address of admin submission & completion queues
//
Asq = (UINT64)(UINTN)(NVME_ASQ_BASE (Private) & ~0xFFF);
Acq = (UINT64)(UINTN)(NVME_ACQ_BASE (Private) & ~0xFFF);
//
// Address of I/O submission & completion queues
//
Private->SqBuffer[0] = (NVME_SQ *)(UINTN)NVME_ASQ_BASE (Private); // NVME_ADMIN_QUEUE
Private->CqBuffer[0] = (NVME_CQ *)(UINTN)NVME_ACQ_BASE (Private); // NVME_ADMIN_QUEUE
Private->SqBuffer[1] = (NVME_SQ *)(UINTN)NVME_SQ_BASE (Private, 0); // NVME_IO_QUEUE
Private->CqBuffer[1] = (NVME_CQ *)(UINTN)NVME_CQ_BASE (Private, 0); // NVME_IO_QUEUE
DEBUG ((DEBUG_INFO, "Admin Submission Queue Size (Aqa.Asqs) = [%08X]\n", Aqa.Asqs));
DEBUG ((DEBUG_INFO, "Admin Completion Queue Size (Aqa.Acqs) = [%08X]\n", Aqa.Acqs));
DEBUG ((DEBUG_INFO, "Admin Submission Queue (SqBuffer[0]) = [%08X]\n", Private->SqBuffer[0]));
DEBUG ((DEBUG_INFO, "Admin Completion Queue (CqBuffer[0]) = [%08X]\n", Private->CqBuffer[0]));
DEBUG ((DEBUG_INFO, "I/O Submission Queue (SqBuffer[1]) = [%08X]\n", Private->SqBuffer[1]));
DEBUG ((DEBUG_INFO, "I/O Completion Queue (CqBuffer[1]) = [%08X]\n", Private->CqBuffer[1]));
//
// Program admin queue attributes
//
NVME_SET_AQA (Private, &Aqa);
//
// Program admin submission & completion queues address
//
NVME_SET_ASQ (Private, &Asq);
NVME_SET_ACQ (Private, &Acq);
//
// Enable the NVME controller
//
Status = NvmeEnableController (Private);
if (EFI_ERROR(Status)) {
DEBUG ((DEBUG_ERROR, "%a: NvmeEnableController fail, Status - %r\n", __FUNCTION__, Status));
return Status;
}
//
// Get the Identify Controller data
//
if (Private->ControllerData == NULL) {
Private->ControllerData = (NVME_ADMIN_CONTROLLER_DATA *)AllocateZeroPool(sizeof (NVME_ADMIN_CONTROLLER_DATA));
if (Private->ControllerData == NULL) {
return EFI_OUT_OF_RESOURCES;
}
}
Status = NvmeIdentifyController (Private, Private->ControllerData);
if (EFI_ERROR(Status)) {
DEBUG ((DEBUG_ERROR, "%a: NvmeIdentifyController fail, Status - %r\n", __FUNCTION__, Status));
return Status;
}
NvmeDumpControllerData (Private->ControllerData);
//
// Check the namespace number for storing the namespaces information
//
if (Private->ControllerData->Nn > MAX_UINT32 / sizeof (PEI_NVME_NAMESPACE_INFO)) {
DEBUG ((
DEBUG_ERROR,
"%a: Number of Namespaces field in Identify Controller data not supported by the driver.\n",
__FUNCTION__
));
return EFI_UNSUPPORTED;
}
//
// Create one I/O completion queue and one I/O submission queue
//
Status = NvmeCreateIoCompletionQueue (Private);
if (EFI_ERROR(Status)) {
DEBUG ((DEBUG_ERROR, "%a: Create IO completion queue fail, Status - %r\n", __FUNCTION__, Status));
return Status;
}
Status = NvmeCreateIoSubmissionQueue (Private);
if (EFI_ERROR(Status)) {
DEBUG ((DEBUG_ERROR, "%a: Create IO submission queue fail, Status - %r\n", __FUNCTION__, Status));
}
return Status;
}
/**
Free the DMA resources allocated by an NVME controller.
@param[in] Private The pointer to the PEI_NVME_CONTROLLER_PRIVATE_DATA data structure.
**/
VOID
NvmeFreeDmaResource (
IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private
)
{
ASSERT (Private != NULL);
if (Private->BufferMapping != NULL) {
IoMmuFreeBuffer (
NVME_MEM_MAX_PAGES,
Private->Buffer,
Private->BufferMapping
);
}
return;
}
|
4ed8654bac30324ec6bd9118d234140006fcea80
|
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
|
/sys/arch/rs6000/stand/boot/monitor.c
|
3eb9f705c053d5ad54f5b5681c7b14e65dc31fd9
|
[] |
no_license
|
NetBSD/src
|
1a9cbc22ed778be638b37869ed4fb5c8dd616166
|
23ee83f7c0aea0777bd89d8ebd7f0cde9880d13c
|
refs/heads/trunk
| 2023-08-31T13:24:58.105962
| 2023-08-27T15:50:47
| 2023-08-27T15:50:47
| 88,439,547
| 656
| 348
| null | 2023-07-20T20:07:24
| 2017-04-16T20:03:43
| null |
UTF-8
|
C
| false
| false
| 6,911
|
c
|
monitor.c
|
/* $NetBSD: monitor.c,v 1.4 2016/06/11 06:39:25 dholland Exp $ */
/*-
* Copyright (c) 1996, 1997 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Kazuki Sakamoto.
*
* 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.
*/
#ifdef DBMONITOR
#include <lib/libsa/stand.h>
#include <lib/libkern/libkern.h>
#include "boot.h"
#define NULL 0
extern int errno;
extern char *name;
void db_cmd_dump(int, char **);
void db_cmd_get(int, char **);
void db_cmd_mf(int, char **);
void db_cmd_mt(int, char **);
void db_cmd_put(int, char **);
void db_cmd_help(int, char **);
unsigned int mfmsr(void);
void mtmsr(unsigned int);
int db_atob(char *);
struct {
char *name;
void (*fcn)(int, char **);
} db_cmd[] = {
{ "dump", db_cmd_dump },
{ "get", db_cmd_get },
{ "mf", db_cmd_mf },
{ "mt", db_cmd_mt },
{ "put", db_cmd_put },
{ "help", db_cmd_help },
{ NULL, NULL },
};
int
db_monitor(void)
{
int tmp;
int argc, flag;
char *p, *argv[16];
char line[1024];
while(1) {
printf("db> ");
kgets(line, sizeof(line));
flag = 0;
for(p = line, argc = 0; *p != '\0'; p++) {
if (*p != ' ' && *p != '\t') {
if (!flag) {
flag++;
argv[argc++] = p;
}
} else {
if (flag) {
*p = '\0';
flag = 0;
}
}
}
if (argc == 0)
continue;
tmp = 0;
while (db_cmd[tmp].name != NULL) {
if (!strcmp("continue", argv[0]))
return 0;
if (!strcmp(db_cmd[tmp].name, argv[0])) {
(db_cmd[tmp].fcn)(argc, argv);
break;
}
tmp++;
}
if (db_cmd[tmp].name == NULL)
db_cmd_help(argc, argv);
}
return 0;
}
int
db_atob(char *p)
{
int b = 0, width, tmp, exp, x = 0;
if (p[1] == 'x') {
p += 2;
x = 1;
}
width = strlen(p);
while(width--) {
exp = 1;
for (tmp = 1; tmp <= width; tmp++)
exp *= (x ? 16 : 10);
if (*p >= '0' && *p <= '9') {
tmp = *p - '0';
} else {
tmp = *p - 'a' + 10;
}
b += tmp * exp;
p++;
}
return b;
}
void
db_cmd_dump(int argc, char **argv)
{
char *p, *r, *pp;
int mode, add, size, i;
switch (argc) {
case 4:
r = argv[1];
switch (r[1]) {
case 'b':
mode = 1;
break;
case 'h':
mode = 2;
break;
case 'w':
mode = 4;
break;
default:
goto out;
}
p = argv[2];
pp = argv[3];
break;
case 3:
mode = 4;
p = argv[1];
pp = argv[2];
break;
default:
goto out;
}
add = db_atob(p);
size = db_atob(pp);
i = 0;
for (; size > 0;) {
if (!i)
printf("\n0x%x:", add);
switch (mode) {
case 1:
printf(" %x", *(unsigned char *)add);
add += 1;
size -= 1;
if (++i == 16)
i = 0;
break;
case 2:
printf(" %x", *(unsigned short *)add);
add += 2;
size -= 2;
if (++i == 8)
i = 0;
break;
case 4:
printf(" %x", *(unsigned int *)add);
add += 4;
size -= 4;
if (++i == 4)
i = 0;
break;
}
}
printf("\n");
return;
out:
printf("dump [-b][-h][-w] address size\n");
return;
}
void
db_cmd_get(int argc, char **argv)
{
char *p, *r;
int mode, add;
switch (argc) {
case 3:
r = argv[1];
switch (r[1]) {
case 'b':
mode = 1;
break;
case 'h':
mode = 2;
break;
case 'w':
mode = 4;
break;
default:
goto out;
}
p = argv[2];
break;
case 2:
mode = 4;
p = argv[1];
break;
default:
goto out;
}
add = db_atob(p);
printf("0x%x: ", add);
switch (mode) {
case 1:
printf("0x%x", *(char *)add);
break;
case 2:
printf("0x%x", *(short *)add);
break;
case 4:
printf("0x%x", *(int *)add);
break;
}
printf("\n");
return;
out:
printf("get [-b][-h][-w] address\n");
return;
}
void
db_cmd_put(int argc, char **argv)
{
char *p, *r, *pp;
int mode, add, data;
switch (argc) {
case 4:
r = argv[1];
switch (r[1]) {
case 'b':
mode = 1;
break;
case 'h':
mode = 2;
break;
case 'w':
mode = 4;
break;
default:
goto out;
}
p = argv[2];
pp = argv[3];
break;
case 3:
mode = 4;
p = argv[1];
pp = argv[2];
break;
default:
goto out;
}
add = db_atob(p);
data = db_atob(pp);
printf("0x%x: 0x%x", add, data);
switch (mode) {
case 1:
*(char *)add = data;
break;
case 2:
*(short *)add = data;
break;
case 4:
*(int *)add = data;
break;
}
printf("\n");
return;
out:
printf("put [-b][-h][-w] address data\n");
return;
}
#define STR(x) #x
#define FUNC(x) \
unsigned int mf ## x() { \
unsigned int tmp; \
__asm volatile (STR(mf ## x %0) : STR(=r)(tmp)); \
return (tmp); \
} \
void mt ## x(unsigned int data) \
{ \
__asm volatile (STR(mt ## x %0) :: STR(r)(data)); \
} \
#define DEF(x) \
{ #x, mf ## x, mt ## x }
FUNC(msr);
struct {
char *op;
unsigned int (*mf)(void);
void (*mt)(unsigned int);
} mreg [] = {
DEF(msr),
{ NULL, NULL, NULL },
};
void
db_cmd_mf(int argc, char **argv)
{
int i = 0;
if (argc != 2) {
printf("mf register\nregister:");
while (mreg[i].op != NULL)
printf(" %s", mreg[i++].op);
printf("\n");
return;
}
while (mreg[i].op != NULL) {
if (!strcmp(mreg[i].op, argv[1])) {
printf(" 0x%x\n", (mreg[i].mf)());
break;
}
i++;
}
}
void
db_cmd_mt(int argc, char **argv)
{
int i = 0;
if (argc != 3) {
printf("mt register data\nregister:");
while (mreg[i].op != NULL)
printf(" %s", mreg[i++].op);
printf("\n");
return;
}
while (mreg[i].op != NULL) {
if (!strcmp(mreg[i].op, argv[1])) {
(mreg[i].mt)((unsigned int)db_atob(argv[2]));
printf(" 0x%x\n", db_atob(argv[2]));
break;
}
i++;
}
}
void
db_cmd_help(int argc, char **argv)
{
int i = 0;
while (db_cmd[i].name != NULL)
printf("%s, ", db_cmd[i++].name);
printf("continue\n");
}
#endif /* DBMONITOR */
|
3ca69c0df3a1a3efc4ca0aa6b41cd21e7016e8c5
|
72f6d3ad72b2a4a9b6c5f93c5d1b744e2940b884
|
/deps/klib/kson.h
|
a03eb52f58a3ad4663784973203b5f5b8db55fef
|
[
"MIT"
] |
permissive
|
h2o/h2o
|
70012b6527ceb54e9e2819c9c75242b18e381485
|
b165770ce704c782ddee7428ea4a0b23c8bb7894
|
refs/heads/master
| 2023-08-16T13:16:35.018003
| 2023-08-16T03:56:28
| 2023-08-16T03:56:28
| 23,029,617
| 9,377
| 983
|
MIT
| 2023-09-12T04:49:14
| 2014-08-16T23:59:03
|
C
|
UTF-8
|
C
| false
| false
| 1,358
|
h
|
kson.h
|
#ifndef KSON_H
#define KSON_H
#include <string.h>
#define KSON_TYPE_NO_QUOTE 1
#define KSON_TYPE_SGL_QUOTE 2
#define KSON_TYPE_DBL_QUOTE 3
#define KSON_TYPE_BRACKET 4
#define KSON_TYPE_BRACE 5
#define KSON_OK 0
#define KSON_ERR_EXTRA_LEFT 1
#define KSON_ERR_EXTRA_RIGHT 2
#define KSON_ERR_NO_KEY 3
typedef struct kson_node_s {
unsigned long long type:3, n:61;
char *key;
union {
struct kson_node_s **child;
char *str;
} v;
} kson_node_t;
typedef struct {
long n_nodes;
kson_node_t *root;
} kson_t;
#ifdef __cplusplus
extern "C" {
#endif
kson_t *kson_parse(const char *json);
void kson_destroy(kson_t *kson);
const kson_node_t *kson_by_path(const kson_node_t *root, int path_len, ...);
void kson_format(const kson_node_t *root);
#ifdef __cplusplus
}
#endif
#define kson_is_internal(p) ((p)->type == KSON_TYPE_BRACKET || (p)->type == KSON_TYPE_BRACE)
static inline const kson_node_t *kson_by_key(const kson_node_t *p, const char *key)
{
long i;
if (!kson_is_internal(p)) return 0;
for (i = 0; i < (long)p->n; ++i) {
const kson_node_t *q = p->v.child[i];
if (q->key && strcmp(q->key, key) == 0)
return q;
}
return 0;
}
static inline const kson_node_t *kson_by_index(const kson_node_t *p, long i)
{
if (!kson_is_internal(p)) return 0;
return 0 <= i && i < (long)p->n? p->v.child[i] : 0;
}
#endif
|
9cb8e85946a5ea1471981a74881991b684fe16a8
|
771fa3a01480527df835c593bf99c5b8ae702b6a
|
/src/modules/mod_scgi.c
|
feaa61a4b9264b2c5d6b52c414ed9adb39e0ac20
|
[
"CC0-1.0",
"Apache-2.0",
"MIT"
] |
permissive
|
lighttpd/lighttpd2
|
cee558174b0a07174a4488591c16882845d43240
|
23164d557f10d4ccd948b34c5b1323e22ce5088f
|
refs/heads/master
| 2023-09-05T03:39:50.805344
| 2023-07-23T00:03:44
| 2023-07-23T00:03:44
| 1,767,422
| 459
| 135
|
NOASSERTION
| 2023-01-06T20:16:37
| 2011-05-18T18:13:11
|
C
|
UTF-8
|
C
| false
| false
| 8,245
|
c
|
mod_scgi.c
|
/*
* mod_scgi - connect to SCGI backends for generating response content
*
* Author:
* Copyright (c) 2013 Stefan Bühler
*/
#include <lighttpd/base.h>
#include <lighttpd/plugin_core.h>
#include <lighttpd/backends.h>
#include <lighttpd/stream_http_response.h>
LI_API gboolean mod_scgi_init(liModules *mods, liModule *mod);
LI_API gboolean mod_scgi_free(liModules *mods, liModule *mod);
typedef struct scgi_connection scgi_connection;
typedef struct scgi_context scgi_context;
struct scgi_context {
gint refcount;
liBackendPool *pool;
GString *socket_str;
};
struct scgi_connection {
scgi_context *ctx;
liBackendConnection *bcon;
gpointer simple_socket_data;
};
/**********************************************************************************/
static gboolean append_key_value_pair(GByteArray *a, const gchar *key, size_t keylen, const gchar *val, size_t valuelen) {
const guint8 z = 0;
g_byte_array_append(a, (const guint8*) key, keylen);
g_byte_array_append(a, &z, 1);
g_byte_array_append(a, (const guint8*) val, valuelen);
g_byte_array_append(a, &z, 1);
return TRUE;
}
static void cgi_add_cb(gpointer param, const gchar *key, size_t keylen, const gchar *val, size_t valuelen) {
GByteArray *a = (GByteArray*) param;
append_key_value_pair(a, key, keylen, val, valuelen);
}
static void scgi_send_env(liVRequest *vr, liChunkQueue *out) {
GByteArray *buf = g_byte_array_sized_new(0);
liEnvironmentDup *envdup;
GString *tmp = vr->wrk->tmp_str;
GString *env_scgi_value;
g_assert(vr->request.content_length >= 0);
envdup = li_environment_make_dup(&vr->env);
env_scgi_value = li_environment_dup_pop(envdup, CONST_STR_LEN("SCGI"));
li_environment_dup2cgi(vr, envdup, cgi_add_cb, buf);
if (NULL != env_scgi_value) {
append_key_value_pair(buf, CONST_STR_LEN("SCGI"), GSTR_LEN(env_scgi_value));
} else {
append_key_value_pair(buf, CONST_STR_LEN("SCGI"), CONST_STR_LEN("1"));
}
g_string_printf(tmp, "%u:", buf->len);
li_chunkqueue_append_mem(out, GSTR_LEN(tmp));
{
const guint8 c = ',';
g_byte_array_append(buf, &c, 1);
}
li_chunkqueue_append_bytearr(out, buf);
}
/**********************************************************************************/
static void scgi_backend_free(liBackendPool *bpool) {
liBackendConfig *config = (liBackendConfig*) bpool->config;
li_sockaddr_clear(&config->sock_addr);
g_slice_free(liBackendConfig, config);
}
static liBackendCallbacks scgi_backend_cbs = {
/* backend_detach_thread */ NULL,
/* backend_attach_thread */ NULL,
/* backend_new */ NULL,
/* backend_close */ NULL,
scgi_backend_free
};
static scgi_context* scgi_context_new(liServer *srv, GString *dest_socket) {
liSocketAddress saddr;
scgi_context* ctx;
liBackendConfig *config;
saddr = li_sockaddr_from_string(dest_socket, 0);
if (NULL == saddr.addr_up.raw) {
ERROR(srv, "Invalid socket address '%s'", dest_socket->str);
return NULL;
}
config = g_slice_new0(liBackendConfig);
config->callbacks = &scgi_backend_cbs;
config->sock_addr = saddr;
config->max_connections = 0;
config->idle_timeout = 5;
config->connect_timeout = 5;
config->wait_timeout = 5;
config->disable_time = 0;
config->max_requests = 1;
config->watch_for_close = TRUE;
ctx = g_slice_new0(scgi_context);
ctx->refcount = 1;
ctx->pool = li_backend_pool_new(config);
ctx->socket_str = g_string_new_len(GSTR_LEN(dest_socket));
return ctx;
}
static void scgi_context_release(scgi_context *ctx) {
if (!ctx) return;
LI_FORCE_ASSERT(g_atomic_int_get(&ctx->refcount) > 0);
if (g_atomic_int_dec_and_test(&ctx->refcount)) {
li_backend_pool_free(ctx->pool);
g_string_free(ctx->socket_str, TRUE);
g_slice_free(scgi_context, ctx);
}
}
static void scgi_context_acquire(scgi_context *ctx) {
LI_FORCE_ASSERT(g_atomic_int_get(&ctx->refcount) > 0);
g_atomic_int_inc(&ctx->refcount);
}
static void scgi_io_cb(liIOStream *stream, liIOStreamEvent event) {
scgi_connection *con = stream->data;
liWorker *wrk = li_worker_from_iostream(stream);
li_stream_simple_socket_io_cb_with_context(stream, event, &con->simple_socket_data);
switch (event) {
case LI_IOSTREAM_DESTROY:
li_stream_simple_socket_close(stream, FALSE);
li_event_io_set_fd(&con->bcon->watcher, -1);
li_backend_put(wrk, con->ctx->pool, con->bcon, TRUE);
con->bcon = NULL;
scgi_context_release(con->ctx);
g_slice_free(scgi_connection, con);
stream->data = NULL;
return;
default:
break;
}
if ((NULL == stream->stream_in.out || stream->stream_in.out->is_closed) &&
!(NULL == stream->stream_out.out || stream->stream_out.out->is_closed)) {
stream->stream_out.out->is_closed = TRUE;
li_stream_again_later(&stream->stream_out);
}
}
static void scgi_connection_new(liVRequest *vr, liBackendConnection *bcon, scgi_context *ctx) {
scgi_connection* scon = g_slice_new0(scgi_connection);
liIOStream *iostream;
liStream *outplug;
liStream *http_out;
scgi_context_acquire(ctx);
scon->ctx = ctx;
scon->bcon = bcon;
iostream = li_iostream_new(vr->wrk, li_event_io_fd(&bcon->watcher), scgi_io_cb, scon);
/* insert scgi header before actual data */
outplug = li_stream_plug_new(&vr->wrk->loop);
li_stream_connect(outplug, &iostream->stream_out);
scgi_send_env(vr, outplug->out);
li_stream_notify_later(outplug);
http_out = li_stream_http_response_handle(&iostream->stream_in, vr, TRUE, FALSE, FALSE);
li_vrequest_handle_indirect(vr, NULL);
li_vrequest_indirect_connect(vr, outplug, http_out);
li_iostream_release(iostream);
li_stream_release(outplug);
li_stream_release(http_out);
}
/**********************************************************************************/
static liHandlerResult scgi_handle_abort(liVRequest *vr, gpointer param, gpointer context) {
scgi_context *ctx = (scgi_context*) param;
liBackendWait *bwait = context;
if (bwait != NULL) {
li_backend_wait_stop(vr, ctx->pool, &bwait);
}
return LI_HANDLER_GO_ON;
}
static liHandlerResult scgi_handle(liVRequest *vr, gpointer param, gpointer *context) {
liBackendWait *bwait = (liBackendWait*) *context;
liBackendConnection *bcon = NULL;
scgi_context *ctx = (scgi_context*) param;
liBackendResult bres;
if (li_vrequest_is_handled(vr)) return LI_HANDLER_GO_ON;
LI_VREQUEST_WAIT_FOR_REQUEST_BODY(vr);
if (vr->request.content_length < 0) {
VR_ERROR(vr, "%s", "scgi can't handle progressive uploads. enable request body buffering!");
return LI_HANDLER_ERROR;
}
bres = li_backend_get(vr, ctx->pool, &bcon, &bwait);
*context = bwait;
switch (bres) {
case LI_BACKEND_SUCCESS:
LI_FORCE_ASSERT(NULL == bwait);
LI_FORCE_ASSERT(NULL != bcon);
break;
case LI_BACKEND_WAIT:
LI_FORCE_ASSERT(NULL != bwait);
return LI_HANDLER_WAIT_FOR_EVENT;
case LI_BACKEND_TIMEOUT:
li_vrequest_backend_dead(vr);
return LI_HANDLER_GO_ON;
}
scgi_connection_new(vr, bcon, ctx);
return LI_HANDLER_GO_ON;
}
static void scgi_free(liServer *srv, gpointer param) {
scgi_context *ctx = (scgi_context*) param;
UNUSED(srv);
scgi_context_release(ctx);
}
static liAction* scgi_create(liServer *srv, liWorker *wrk, liPlugin* p, liValue *val, gpointer userdata) {
scgi_context *ctx;
UNUSED(wrk); UNUSED(userdata); UNUSED(p);
val = li_value_get_single_argument(val);
if (LI_VALUE_STRING != li_value_type(val)) {
ERROR(srv, "%s", "scgi expects a string as parameter");
return FALSE;
}
ctx = scgi_context_new(srv, val->data.string);
if (NULL == ctx) return NULL;
return li_action_new_function(scgi_handle, scgi_handle_abort, scgi_free, ctx);
}
static const liPluginOption options[] = {
{ NULL, 0, 0, NULL }
};
static const liPluginAction actions[] = {
{ "scgi", scgi_create, NULL },
{ NULL, NULL, NULL }
};
static const liPluginSetup setups[] = {
{ NULL, NULL, NULL }
};
static void plugin_init(liServer *srv, liPlugin *p, gpointer userdata) {
UNUSED(srv); UNUSED(userdata);
p->options = options;
p->actions = actions;
p->setups = setups;
}
gboolean mod_scgi_init(liModules *mods, liModule *mod) {
MODULE_VERSION_CHECK(mods);
mod->config = li_plugin_register(mods->main, "mod_scgi", plugin_init, NULL);
return mod->config != NULL;
}
gboolean mod_scgi_free(liModules *mods, liModule *mod) {
if (mod->config)
li_plugin_free(mods->main, mod->config);
return TRUE;
}
|
623f3acb9bac853dec4322274723b5183f4885bf
|
43bf0bdbd65c8bc8bc99d0ed1d408a79aee2621a
|
/c/src/reactor/timer.c
|
1f552b349b16ce7d05ad6bd9d28ab62ba8488f3f
|
[
"BSD-3-Clause",
"Apache-2.0"
] |
permissive
|
apache/qpid-proton
|
51a6a61352cb206095aec75b27ebaa7fbf211d20
|
6b05c6d64ba04bad96745b1430ca17d436b6fd32
|
refs/heads/main
| 2023-09-01T14:06:34.221772
| 2023-08-09T21:38:18
| 2023-08-09T21:38:18
| 26,309,799
| 236
| 257
|
Apache-2.0
| 2023-08-31T14:37:43
| 2014-11-07T08:00:07
|
C++
|
UTF-8
|
C
| false
| false
| 4,594
|
c
|
timer.c
|
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
#include <proton/reactor.h>
#include "core/object_private.h"
#include <assert.h>
struct pn_task_t {
pn_list_t *pool;
pn_record_t *attachments;
pn_timestamp_t deadline;
bool cancelled;
};
void pn_task_initialize(void *object) {
pn_task_t *task = (pn_task_t *)object;
task->pool = NULL;
task->attachments = pn_record();
task->deadline = 0;
task->cancelled = false;
}
void pn_task_finalize(void *object) {
// if we are the last reference to the pool then don't put ourselves
// into it
pn_task_t *task = (pn_task_t *)object;
if (task->pool && pn_refcount(task->pool) > 1) {
pn_record_clear(task->attachments);
pn_list_add(task->pool, task);
pn_decref(task->pool);
task->pool = NULL;
} else {
pn_decref(task->pool);
pn_decref(task->attachments);
}
}
intptr_t pn_task_compare(void *a, void *b) {
pn_task_t *ta = (pn_task_t *)a;
pn_task_t *tb = (pn_task_t *)b;
return ta->deadline - tb->deadline;
}
#define pn_task_inspect NULL
#define pn_task_hashcode NULL
static const pn_class_t PN_CLASSCLASS(pn_task) = PN_CLASS(pn_task);
pn_task_t *pn_task(void) {
pn_task_t *task = pn_class_new(&PN_CLASSCLASS(pn_task), sizeof(pn_task_t));
return task;
}
pn_record_t *pn_task_attachments(pn_task_t *task) {
assert(task);
return task->attachments;
}
void pn_task_cancel(pn_task_t *task) {
assert(task);
task->cancelled = true;
}
//
// timer
//
struct pn_timer_t {
pn_list_t *pool;
pn_list_t *tasks;
pn_collector_t *collector;
};
static void pn_timer_initialize(void *object) {
pn_timer_t *timer = (pn_timer_t *)object;
timer->pool = pn_list(&PN_CLASSCLASS(pn_task), 0);
timer->tasks = pn_list(&PN_CLASSCLASS(pn_task), 0);
}
static void pn_timer_finalize(void *object) {
pn_timer_t *timer = (pn_timer_t *)object;
pn_decref(timer->pool);
pn_free(timer->tasks);
}
#define pn_timer_inspect NULL
#define pn_timer_compare NULL
#define pn_timer_hashcode NULL
pn_timer_t *pn_timer(pn_collector_t *collector) {
static const pn_class_t clazz = PN_CLASS(pn_timer);
pn_timer_t *timer = pn_class_new(&clazz, sizeof(pn_timer_t));
timer->collector = collector;
return timer;
}
pn_task_t *pn_timer_schedule(pn_timer_t *timer, pn_timestamp_t deadline) {
pn_task_t *task = (pn_task_t *) pn_list_pop(timer->pool);
if (!task) {
task = pn_task();
}
task->pool = timer->pool;
pn_incref(task->pool);
task->deadline = deadline;
task->cancelled = false;
pn_list_minpush(timer->tasks, task);
pn_decref(task);
return task;
}
void pni_timer_flush_cancelled(pn_timer_t *timer) {
while (pn_list_size(timer->tasks)) {
pn_task_t *task = (pn_task_t *) pn_list_get(timer->tasks, 0);
if (task->cancelled) {
pn_task_t *min = (pn_task_t *) pn_list_minpop(timer->tasks);
assert(min == task);
pn_decref(min);
} else {
break;
}
}
}
pn_timestamp_t pn_timer_deadline(pn_timer_t *timer) {
assert(timer);
pni_timer_flush_cancelled(timer);
if (pn_list_size(timer->tasks)) {
pn_task_t *task = (pn_task_t *) pn_list_get(timer->tasks, 0);
return task->deadline;
} else {
return 0;
}
}
void pn_timer_tick(pn_timer_t *timer, pn_timestamp_t now) {
assert(timer);
while (pn_list_size(timer->tasks)) {
pn_task_t *task = (pn_task_t *) pn_list_get(timer->tasks, 0);
if (now >= task->deadline) {
pn_task_t *min = (pn_task_t *) pn_list_minpop(timer->tasks);
assert(min == task);
if (!min->cancelled)
pn_collector_put_object(timer->collector, min, PN_TIMER_TASK);
pn_decref(min);
} else {
break;
}
}
}
int pn_timer_tasks(pn_timer_t *timer) {
assert(timer);
pni_timer_flush_cancelled(timer);
return pn_list_size(timer->tasks);
}
|
8fe2cc0f332bb244d7bfb2b8e3dbdc40c981307b
|
568fa58296378fa129ab3349adf010daa44ed45b
|
/third_party/fwkacllib/inc/runtime/rt_model.h
|
0c01789cd4e1f260862528bbce5d88e0cc3dd35b
|
[
"Apache-2.0",
"BSD-3-Clause",
"NCSA",
"X11-distribute-modifications-variant",
"Zlib",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Unlicense",
"LLVM-exception",
"BSD-2-Clause"
] |
permissive
|
mindspore-ai/akg
|
37f471badc66de6a831f1f45ad84344f34d23ef2
|
99f33858d6972741748cbfc9ab0bf9600428fef7
|
refs/heads/master
| 2023-07-25T23:03:17.672665
| 2023-07-11T07:33:57
| 2023-07-11T07:33:57
| 274,077,856
| 319
| 36
|
Apache-2.0
| 2021-12-30T13:43:08
| 2020-06-22T08:09:05
|
Python
|
UTF-8
|
C
| false
| false
| 14,141
|
h
|
rt_model.h
|
/*
* Copyright (c) Huawei Technologies Co., Ltd. 2020-2021. All rights reserved.
* Description: rt_model.h
* Create: 2020-01-01
*/
#ifndef CCE_RUNTIME_RT_MODEL_H
#define CCE_RUNTIME_RT_MODEL_H
#include "base.h"
#if defined(__cplusplus)
extern "C" {
#endif
typedef enum tagModelTaskType {
RT_MODEL_TASK_KERNEL = 0,
RT_MODEL_TASK_EVENT_RECORD,
RT_MODEL_TASK_EVENT_WAIT,
RT_MODEL_TASK_FUSION_START,
RT_MODEL_TASK_FUSION_END,
RT_MODEL_TASK_KERNEL_EX,
RT_MODEL_TASK_HCCL,
RT_MODEL_TASK_STREAM_SWITCH,
RT_MODEL_TASK_STREAM_ACTIVE,
RT_MODEL_TASK_LABEL_SET,
RT_MODEL_TASK_LABEL_SWITCH,
RT_MODEL_TASK_LABEL_GOTO,
RT_MODEL_TASK_PROFILER_TRACE,
RT_MODEL_TASK_MEMCPY_ASYNC,
RT_MODEL_TASK_NOTIFY_RECORD,
RT_MODEL_TASK_NOTIFY_WAIT,
RT_MODEL_TASK_REDUCE_ASYNC,
RT_MODEL_TASK_RDMA_SEND,
RT_MODEL_TASK_EVENT_RESET,
RT_MODEL_TASK_MODEL_END_GRAPH,
RT_MODEL_TASK_STREAM_SWITCH_N,
RT_MODEL_TASK_RDMA_DB_SEND,
RT_MODEL_TASK_MEMCPY_ADDR_ASYNC,
RT_MODEL_TASK_STREAM_LABEL_SWITCH_BY_INDEX,
RT_MODEL_TASK_STREAM_LABEL_GOTO,
RT_MODEL_TASK_MODEL_EXIT,
RT_MODEL_TASK_ALL_KERNEL,
RT_MODEL_TASK_PROFILER_TRACE_EX,
RT_MODEL_TASK_FFTS_TASK,
RT_MODEL_TASK_FFTS_PLUS_TASK,
RT_MODEL_TASK_DSA_TASK,
RT_MODEL_TASK_CMO,
RT_MODEL_TASK_BARRIER,
RT_MODEL_TASK_NPU_GET_FLOAT_STATUS,
RT_MODEL_TASK_NPU_CLEAR_FLOAT_STATUS,
RT_MODEL_TASK_DVPP,
} rtModelTaskType_t;
typedef enum tagModelStreamType {
RT_MODEL_HEAD_STREAM = 0,
RT_MODEL_WAIT_ACTIVE_STREAM = 1
} rtModelStreamType_t;
typedef enum tagModelQueueFlag {
RT_MODEL_INPUT_QUEUE = 0,
RT_MODEL_OUTPUT_QUEUE = 1
} rtModelQueueFlag_t;
#define EXECUTOR_NONE (0x0U)
#define EXECUTOR_TS (0x01U)
#define EXECUTOR_AICPU (0x02U)
/*
* @ingroup rt_model
* @brief debug flag for kernel exception dump
*/
#define RT_DEBUG_FLAG_AICORE_OVERFLOW (0x1U << 0U)
#define RT_DEBUG_FLAG_ATOMIC_ADD_OVERFLOW (0x1U << 1U)
/**
* @ingroup
* @brief the type defination of aicpu model task command
*/
typedef enum tagTsAicpuModelCmd {
TS_AICPU_MODEL_LOAD = 1,
TS_AICPU_MODEL_EXECUTE,
TS_AICPU_MODEL_DESTROY,
TS_AICPU_MODEL_ABORT,
TS_AICPU_MODEL_RESERVED,
} tsAicpuModelCmd;
typedef struct tagAicpuTaskInfo {
uint32_t taskID;
uint32_t streamID;
uint32_t kernelType;
uint64_t kernelName;
uint64_t kernelSo;
uint64_t paraBase;
uint32_t taskFlag;
} rtAicpuTaskInfo_t;
typedef struct tagModelStreamInfo {
uint32_t streamID;
uint32_t streamFlag;
} rtModelStreamInfo_t;
typedef struct tagModelQueueInfo {
uint32_t queueID;
uint32_t flag;
} rtModelQueueInfo_t;
typedef struct tagAicpuModelInfo {
uint32_t moduleID;
uint32_t tsId;
uint16_t streamInfoNum;
uint16_t aicpuTaskNum;
uint64_t streamInfoPtr;
uint64_t aicpuTaskPtr;
uint16_t queueSize;
uint64_t queueInfoPtr;
} rtAicpuModelInfo_t;
typedef struct tagKernelTaskInfo {
uint16_t blockDim;
uint16_t argsCount;
uint16_t argsSize;
uint16_t reserved;
const char_t *stubFunc;
uint8_t *smDesc;
const uint8_t *args;
uint16_t *argsOffset;
} rtKernelTaskInfo_t;
typedef struct tagAllKernelTaskInfo {
uint16_t blockDim;
uint16_t argsCount;
uint16_t argsSize;
uint16_t reserved;
uint64_t tilingKey;
void *handle;
uint8_t *smDesc;
const uint8_t *args;
uint16_t *argsOffset;
} rtAllKernelTaskInfo_t;
typedef struct tagKernelTaskInfoEx {
uint32_t flags;
uint32_t argsSize;
const void *args;
uint32_t reserved[6];
} rtKernelTaskInfoEx_t;
typedef struct tagEventTaskInfo {
uint32_t eventID;
uint32_t reserved[9];
} rtEventTaskInfo_t;
typedef struct tagStreamSwitchTaskInfo {
int64_t value;
uint64_t pValuePtr;
uint32_t trueStreamID;
uint32_t dataType;
uint32_t reserved[4];
} rtStreamSwitchTaskInfo_t;
typedef struct tagStreamSwitchNTaskInfo {
uint64_t pValuePtr;
uint64_t pTrueStreamPtr;
uint32_t size;
uint32_t elementSize;
uint32_t dataType;
uint32_t reserved[3];
} rtStreamSwitchNTaskInfo_t;
typedef struct tagStreamActiveTaskInfo {
uint32_t activeStreamID;
uint32_t reserved[9];
} rtStreamActiveTaskInfo_t;
typedef struct tagSetTaskInfo {
uint16_t labelId;
uint32_t reserved[9];
} rtLabelSetTaskInfo_t;
typedef struct tagSwitchTaskInfo {
uint32_t value;
uint32_t reserved[9];
} rtLabelSwitchTaskInfo_t;
typedef struct tagLabelGotoTaskInfo {
uint16_t labelId;
uint32_t reserved[9];
} rtLabelGotoTaskInfo_t;
typedef struct tagProfilerTraceTaskInfo {
uint64_t profilerTraceId;
uint32_t notify : 8;
uint32_t reserved_ : 24;
uint32_t flags;
uint32_t reserved[6];
} rtProfilerTrace_t;
typedef struct tagProfilerTraceExTaskInfo {
uint64_t profilerTraceId;
uint64_t modelId;
uint16_t tagId;
uint8_t reserved[22];
} rtProfilerTraceEx_t;
typedef struct tagrtMemcpyAsyncTaskInfo {
const void *dst;
uint64_t destMax;
const void *src;
uint64_t count;
uint32_t kind;
uint32_t reserved;
} rtMemcpyAsyncTaskInfo_t;
typedef struct tagrtNotifyTaskInfo {
uint32_t notifyID;
uint32_t reserved[9];
} rtNotifyTaskInfo_t;
typedef struct tagrtReduceAsyncTaskInfo {
const void *dst;
uint64_t destMax;
const void *src;
uint64_t count;
uint32_t kind;
uint32_t type;
} rtReduceAsyncTaskInfo_t;
typedef struct tagrtRdmaSendTaskInfo {
uint32_t index;
uint32_t wqe_index;
uint32_t reserved[8];
} rtRdmaSendTaskInfo_t;
typedef struct tagrtRdmaDbSendTaskInfo {
uint64_t dbInfo;
uint32_t dbIndex;
uint32_t reserved[7]; // offset 7
} rtRdmaDbSendTaskInfo_t;
typedef struct tagrtModelEndGraphTaskInfo {
uint32_t modelId;
uint32_t executorFlag;
uint32_t reserved[8];
} rtModelEndGraphTaskInfo_t;
typedef struct tagrtModelExitInfo {
uint32_t modelId;
uint32_t streamId;
uint32_t reserved[8];
} rtModelExitTaskInfo_t;
typedef struct tagrtStreamLabelSwitchByIndexTask_t {
uint64_t indexPtr;
uint64_t labelInfoPtr;
uint32_t max;
uint8_t reserved[20];
} rtStreamLabelSwitchByIndexTask_t;
typedef struct tagrtStreamLabelGotoTask_t {
uint16_t labelId;
uint16_t modelId;
uint8_t reserved[36];
} rtStreamLabelGotoTask_t;
typedef struct tagrtNpuGetFloatStatusTask_t {
uint64_t outputAddr;
uint64_t outputSize;
uint32_t checkMode;
uint8_t reserved[20];
} rtNpuGetFloatStatusTask_t;
typedef struct tagrtNpuClearFloatStatusTask_t {
uint32_t checkMode;
uint8_t reserved[36];
} rtNpuClearFloatStatusTask_t;
typedef struct tagTaskInfo {
uint32_t type;
uint32_t streamID;
union {
rtKernelTaskInfoEx_t kernelTaskEx;
rtKernelTaskInfo_t kernelTask;
rtAllKernelTaskInfo_t allKernelTask;
rtEventTaskInfo_t eventTask;
rtStreamSwitchTaskInfo_t streamSwitchTask;
rtStreamActiveTaskInfo_t streamActiveTask;
rtLabelSetTaskInfo_t labelSetTask;
rtLabelSwitchTaskInfo_t labelSwitchTask;
rtLabelGotoTaskInfo_t labelGotoTask;
rtProfilerTrace_t profilertraceTask;
rtProfilerTraceEx_t profilertraceExTask;
rtMemcpyAsyncTaskInfo_t memcpyAsyncTask;
rtNotifyTaskInfo_t notifyTask;
rtReduceAsyncTaskInfo_t reduceAsyncTask;
rtRdmaSendTaskInfo_t rdmaSendTask;
rtRdmaDbSendTaskInfo_t rdmaDbSendTask;
rtModelEndGraphTaskInfo_t modelEndGraphTask;
rtModelExitTaskInfo_t modelExitTask;
rtStreamSwitchNTaskInfo_t streamSwitchNTask;
rtStreamLabelSwitchByIndexTask_t streamLabelSwitchIndexTask;
rtStreamLabelGotoTask_t streamLabelGotoTask;
rtNpuGetFloatStatusTask_t npuGetFloatStatusTask;
rtNpuClearFloatStatusTask_t npuClearFloatStatusTask;
uint32_t reserved[10];
} u;
} rtTaskInfo_t;
typedef struct tagNodeInfo_t {
uint32_t nodeIdx;
uint32_t reserved[1];
} rtNodeInfo;
typedef struct tagHwtsInfo_t {
uint16_t taskId;
uint16_t sqExeHead;
uint16_t streamExeHead;
uint16_t reserved[2];
} rtHwtsInfo;
typedef struct tagLabelDevInfo_t {
uint16_t modelId;
uint16_t streamId;
uint16_t labelId;
union {
rtNodeInfo nodeInfo;
rtHwtsInfo hwtsInfo;
uint16_t reserved[5];
}u;
}rtLabelDevInfo;
typedef rtError_t (*rtTaskGenCallback)(rtModel_t mdl, rtTaskInfo_t *taskInfo);
/**
* @ingroup rt_model
* @brief set callback for generate model
* @param [in] callBack callback function
* @return RT_ERROR_NONE for ok
* @return RT_ERROR_INVALID_VALUE for error input
*/
RTS_API rtError_t rtSetTaskGenCallback(rtTaskGenCallback callback);
/**
* @ingroup rt_model
* @brief create model instance
* @param [out] mdl created model
* @param [in] flag reserved
* @return RT_ERROR_NONE for ok
* @return RT_ERROR_INVALID_VALUE for error input
*/
RTS_API rtError_t rtModelCreate(rtModel_t *mdl, uint32_t flag);
/**
* @ingroup rt_model
* @brief set ge model id to aicpu
* @param [in] model aicpu model
* @param [in] extid ge model id
* @return RT_ERROR_NONE for ok
* @return RT_ERROR_INVALID_VALUE for error input
*/
rtError_t rtModelSetExtId(rtModel_t mdl, uint32_t extId);
/**
* @ingroup rt_model
* @brief destroy model instance
* @param [in] mdl model to destroy
* @return RT_ERROR_NONE for ok
* @return RT_ERROR_INVALID_VALUE for error input
*/
RTS_API rtError_t rtModelDestroy(rtModel_t mdl);
/**
* @ingroup rt_model
* @brief bind model and stream instance
* @param [in] mdl binded model
* @param [in] stm binded stream
* @param [in] flag reserved
* @return RT_ERROR_NONE for ok
* @return RT_ERROR_INVALID_VALUE for error input
*/
RTS_API rtError_t rtModelBindStream(rtModel_t mdl, rtStream_t stm, uint32_t flag);
/**
* @ingroup rt_model
* @brief unbind model and stream instance
* @param [in] mdl unbinded model
* @param [in] stm unbinded stream
* @return RT_ERROR_NONE for ok
* @return RT_ERROR_INVALID_VALUE for error input
*/
RTS_API rtError_t rtModelUnbindStream(rtModel_t mdl, rtStream_t stm);
/**
* @ingroup rt_model
* @brief tell runtime Model has been Loaded
* @param [in] mdl model to execute
* @return RT_ERROR_NONE for ok
*/
RTS_API rtError_t rtModelLoadComplete(rtModel_t mdl);
/**
* @ingroup rt_model
* @brief execute model instance
* @param [in] mdl model to execute
* @return RT_ERROR_NONE for ok
* @return RT_ERROR_INVALID_VALUE for error input
*/
RTS_API rtError_t rtModelExecute(rtModel_t mdl, rtStream_t stm, uint32_t flag);
/**
* @ingroup rt_model
* @brief get model the last persist task id
* @param [in] mdl model to execute
* @param [out] taskId last task id of the model
* @param [out] streamId last steam id of the model
* @return RT_ERROR_NONE for ok
* @return RT_ERROR_INVALID_VALUE for error input
*/
RTS_API rtError_t rtModelGetTaskId(rtModel_t mdl, uint32_t *taskId, uint32_t *streamId);
/**
* @ingroup rt_model
* @brief add a end graph task to stream
* @param [in] mdl model to execute
* @param [in] end graph stream
* @return RT_ERROR_NONE for ok
* @return RT_ERROR_INVALID_VALUE for error input
*/
RTS_API rtError_t rtEndGraph(rtModel_t mdl, rtStream_t stm);
/**
* @ingroup rt_model
* @brief add a end graph task with flag to stream
* @param [in] mdl model to execute
* @param [in] end graph stream
* @param [in] flags AICPU datadump
* @return RT_ERROR_NONE for ok
* @return RT_ERROR_INVALID_VALUE for error input
*/
RTS_API rtError_t rtEndGraphEx(rtModel_t mdl, rtStream_t stm, uint32_t flags);
/**
* @ingroup rt_model
* @brief add a end graph task to stream
* @param [in] mdl model to execute
* @param [in] flags EXECUTOR_TS | EXECUTOR_AICPU
* @return RT_ERROR_NONE for ok
* @return RT_ERROR_INVALID_VALUE for error input
*/
RTS_API rtError_t rtModelExecutorSet(rtModel_t mdl, uint8_t flags);
/**
* @ingroup rt_model
* @brief abort model
* @param [in] mdl model to abort
* @return RT_ERROR_NONE for ok
* @return RT_ERROR_INVALID_VALUE for error input
*/
RTS_API rtError_t rtModelAbort(rtModel_t mdl);
/**
* @ingroup rt_model
* @brief end graph task to model default stream
* @param [in] mdl model to execute
* @param [in] end graph stream
* @return RT_ERROR_NONE for ok
* @return RT_ERROR_INVALID_VALUE for error input
*/
RTS_API rtError_t rtModelExit(rtModel_t mdl, rtStream_t stm);
/**
* @ingroup rt_model
* @brief bind queue
* @param [in] mdl model to bind
* @param [in] queueId queueId to bind
* @param [in] flag
* @return RT_ERROR_NONE for ok
* @return RT_ERROR_INVALID_VALUE for error input
*/
RTS_API rtError_t rtModelBindQueue(rtModel_t mdl, uint32_t queueId, rtModelQueueFlag_t flag);
/**
* @ingroup rt_model
* @brief get model id
* @param [in] mdl
* @param [out] modelId model id
* @return RT_ERROR_NONE for ok
* @return RT_ERROR_INVALID_VALUE for error input
*/
RTS_API rtError_t rtModelGetId(rtModel_t mdl, uint32_t *modelId);
/*
* @ingroup rt_model
* @brief enable debug for dump overflow exception
* @param [in] addr: ddr address of kernel exception dumpped
* @param [in] mdl: model handle
* @param [in] flag: debug flag
* @return RT_ERROR_NONE for ok
* @return RT_ERROR_INVALID_VALUE for error input
*/
RTS_API rtError_t rtDebugRegister(rtModel_t mdl, uint32_t flag, const void *addr,
uint32_t *streamId, uint32_t *taskId);
/*
* @ingroup rt_model
* @brief disable debug for dump overflow exception
* @param [in] mdl: model handle
* @return RT_ERROR_NONE for ok
* @return RT_ERROR_INVALID_VALUE for error input
*/
RTS_API rtError_t rtDebugUnRegister(rtModel_t mdl);
/**
* @ingroup rt_model
* @brief set model group id
* @param [in] mdl model
* @param [in] schGrpId groupId (0,4) 0:default invalid value 1-4 valid value Maximum support 4 groups
* @return RT_ERROR_NONE for ok
* @return RT_ERROR_INVALID_VALUE for error input
*/
RTS_API rtError_t rtModelSetSchGroupId(rtModel_t mdl, const int16_t schGrpId);
#if defined(__cplusplus)
}
#endif
#endif // CCE_RUNTIME_RT_MODEL_H
|
7aaa2cf9832bf47427f01c0046006ed3eef8b674
|
58fe7cb3949dd1930e709696659a0296500b64a6
|
/tests/unit/s2n_npn_extension_test.c
|
b9403d5bdbe117e02f5d4f77cb8de14d6e191a6d
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
aws/s2n-tls
|
3344638a6a69c6f20665cf6847e1bc4b85f2e558
|
62dc7a6d4876e5eee0dea3690d528a4c7080a1d5
|
refs/heads/main
| 2023-08-31T23:26:33.780048
| 2023-08-31T05:17:33
| 2023-08-31T05:17:33
| 21,287,076
| 513
| 213
|
Apache-2.0
| 2023-09-13T23:52:29
| 2014-06-27T19:37:59
|
C
|
UTF-8
|
C
| false
| false
| 13,684
|
c
|
s2n_npn_extension_test.c
|
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <stdint.h>
#include <string.h>
#include "s2n_test.h"
#include "stuffer/s2n_stuffer.h"
#include "testlib/s2n_testlib.h"
#include "tests/s2n_test.h"
#include "tls/extensions/s2n_client_alpn.h"
#include "tls/extensions/s2n_npn.h"
#include "tls/s2n_tls.h"
#include "utils/s2n_safety.h"
#define HTTP11 0x68, 0x74, 0x74, 0x70, 0x2f, 0x31, 0x2e, 0x31
#define SPDY1 0x73, 0x70, 0x64, 0x79, 0x2f, 0x31
#define SPDY2 0x73, 0x70, 0x64, 0x79, 0x2f, 0x32
#define SPDY3 0x73, 0x70, 0x64, 0x79, 0x2f, 0x33
S2N_RESULT s2n_calculate_padding(uint8_t protocol_len, uint8_t *padding_len);
int main(int argc, char **argv)
{
BEGIN_TEST();
const char *protocols[] = { "http/1.1", "spdy/1", "spdy/2" };
const uint8_t protocols_count = s2n_array_len(protocols);
/* Should-send tests on the client side */
{
/* No connection */
EXPECT_FALSE(s2n_client_npn_extension.should_send(NULL));
/* No config */
DEFER_CLEANUP(struct s2n_connection *client_conn = s2n_connection_new(S2N_CLIENT), s2n_connection_ptr_free);
EXPECT_NOT_NULL(client_conn);
EXPECT_FALSE(s2n_client_npn_extension.should_send(client_conn));
/* No application protocols set */
DEFER_CLEANUP(struct s2n_config *config = s2n_config_new(), s2n_config_ptr_free);
EXPECT_NOT_NULL(config);
EXPECT_SUCCESS(s2n_connection_set_config(client_conn, config));
EXPECT_FALSE(s2n_client_npn_extension.should_send(client_conn));
/* Application protocols set but NPN not supported. In this case the ALPN extension will be sent. */
EXPECT_SUCCESS(s2n_config_set_protocol_preferences(config, protocols, protocols_count));
EXPECT_FALSE(s2n_client_npn_extension.should_send(client_conn));
EXPECT_TRUE(s2n_client_alpn_extension.should_send(client_conn));
/* Both ALPN and NPN extensions will be sent */
client_conn->config->npn_supported = true;
EXPECT_TRUE(s2n_client_npn_extension.should_send(client_conn));
EXPECT_TRUE(s2n_client_alpn_extension.should_send(client_conn));
/*
*= https://datatracker.ietf.org/doc/id/draft-agl-tls-nextprotoneg-03#section-3
*= type=test
*# For the same reasons, after a handshake has been performed for a
*# given connection, renegotiations on the same connection MUST NOT
*# include the "next_protocol_negotiation" extension.
*/
client_conn->handshake.renegotiation = true;
EXPECT_FALSE(s2n_client_npn_extension.should_send(client_conn));
EXPECT_TRUE(s2n_client_alpn_extension.should_send(client_conn));
};
/* s2n_client_npn_recv */
{
DEFER_CLEANUP(struct s2n_connection *server_conn = s2n_connection_new(S2N_SERVER), s2n_connection_ptr_free);
EXPECT_NOT_NULL(server_conn);
DEFER_CLEANUP(struct s2n_config *config = s2n_config_new(), s2n_config_ptr_free);
EXPECT_NOT_NULL(config);
EXPECT_SUCCESS(s2n_config_set_protocol_preferences(config, protocols, protocols_count));
EXPECT_SUCCESS(s2n_connection_set_config(server_conn, config));
DEFER_CLEANUP(struct s2n_stuffer extension = { 0 }, s2n_stuffer_free);
EXPECT_SUCCESS(s2n_stuffer_growable_alloc(&extension, 0));
/* NPN not supported */
EXPECT_SUCCESS(s2n_client_npn_extension.recv(server_conn, &extension));
EXPECT_FALSE(server_conn->npn_negotiated);
/* NPN supported */
server_conn->config->npn_supported = true;
EXPECT_SUCCESS(s2n_client_npn_extension.recv(server_conn, &extension));
EXPECT_TRUE(server_conn->npn_negotiated);
/* Server has already negotiated a protocol with the ALPN extension */
uint8_t first_protocol_len = strlen(protocols[0]);
EXPECT_MEMCPY_SUCCESS(server_conn->application_protocol, protocols[0], first_protocol_len + 1);
server_conn->npn_negotiated = false;
EXPECT_SUCCESS(s2n_client_npn_extension.recv(server_conn, &extension));
EXPECT_FALSE(server_conn->npn_negotiated);
};
/* Should-send tests on the server side */
{
DEFER_CLEANUP(struct s2n_connection *server_conn = s2n_connection_new(S2N_SERVER), s2n_connection_ptr_free);
EXPECT_NOT_NULL(server_conn);
DEFER_CLEANUP(struct s2n_config *config = s2n_config_new(), s2n_config_ptr_free);
EXPECT_NOT_NULL(config);
EXPECT_SUCCESS(s2n_config_set_protocol_preferences(config, protocols, protocols_count));
EXPECT_SUCCESS(s2n_connection_set_config(server_conn, config));
/* NPN not negotiated */
EXPECT_FALSE(s2n_server_npn_extension.should_send(server_conn));
/* NPN negotiated */
server_conn->npn_negotiated = true;
EXPECT_TRUE(s2n_server_npn_extension.should_send(server_conn));
};
/* s2n_server_npn_send */
{
DEFER_CLEANUP(struct s2n_connection *server_conn = s2n_connection_new(S2N_SERVER), s2n_connection_ptr_free);
EXPECT_NOT_NULL(server_conn);
DEFER_CLEANUP(struct s2n_config *config = s2n_config_new(), s2n_config_ptr_free);
EXPECT_NOT_NULL(config);
EXPECT_SUCCESS(s2n_config_set_protocol_preferences(config, protocols, protocols_count));
EXPECT_SUCCESS(s2n_connection_set_config(server_conn, config));
DEFER_CLEANUP(struct s2n_stuffer out = { 0 }, s2n_stuffer_free);
EXPECT_SUCCESS(s2n_stuffer_growable_alloc(&out, 0));
EXPECT_SUCCESS(s2n_server_npn_extension.send(server_conn, &out));
uint8_t protocol_len = 0;
uint8_t protocol[UINT8_MAX] = { 0 };
for (size_t i = 0; i < protocols_count; i++) {
EXPECT_SUCCESS(s2n_stuffer_read_uint8(&out, &protocol_len));
EXPECT_EQUAL(protocol_len, strlen(protocols[i]));
EXPECT_SUCCESS(s2n_stuffer_read_bytes(&out, protocol, protocol_len));
EXPECT_BYTEARRAY_EQUAL(protocol, protocols[i], protocol_len);
}
EXPECT_EQUAL(s2n_stuffer_data_available(&out), 0);
};
/* s2n_server_npn_recv */
{
/* Client has no application protocols configured. Not sure how this
* could happen, but added to be thorough. */
{
DEFER_CLEANUP(struct s2n_connection *client_conn = s2n_connection_new(S2N_CLIENT), s2n_connection_ptr_free);
EXPECT_NOT_NULL(client_conn);
DEFER_CLEANUP(struct s2n_stuffer extension = { 0 }, s2n_stuffer_free);
EXPECT_SUCCESS(s2n_stuffer_growable_alloc(&extension, 0));
EXPECT_SUCCESS(s2n_server_npn_extension.recv(client_conn, &extension));
EXPECT_NULL(s2n_get_application_protocol(client_conn));
};
/* NPN recv extension can read NPN send extension */
{
DEFER_CLEANUP(struct s2n_connection *client_conn = s2n_connection_new(S2N_CLIENT), s2n_connection_ptr_free);
EXPECT_NOT_NULL(client_conn);
DEFER_CLEANUP(struct s2n_config *config = s2n_config_new(), s2n_config_ptr_free);
EXPECT_NOT_NULL(config);
EXPECT_SUCCESS(s2n_config_set_protocol_preferences(config, protocols, protocols_count));
EXPECT_SUCCESS(s2n_connection_set_config(client_conn, config));
DEFER_CLEANUP(struct s2n_stuffer extension = { 0 }, s2n_stuffer_free);
EXPECT_SUCCESS(s2n_stuffer_growable_alloc(&extension, 0));
EXPECT_SUCCESS(s2n_server_npn_extension.send(client_conn, &extension));
EXPECT_SUCCESS(s2n_server_npn_extension.recv(client_conn, &extension));
/* Server sent the same list that the client configured so the first protocol in the list is chosen */
EXPECT_NOT_NULL(s2n_get_application_protocol(client_conn));
EXPECT_BYTEARRAY_EQUAL(s2n_get_application_protocol(client_conn), protocols[0], strlen(protocols[0]));
};
/* No match exists */
{
DEFER_CLEANUP(struct s2n_connection *client_conn = s2n_connection_new(S2N_CLIENT), s2n_connection_ptr_free);
EXPECT_NOT_NULL(client_conn);
DEFER_CLEANUP(struct s2n_config *config = s2n_config_new(), s2n_config_ptr_free);
EXPECT_NOT_NULL(config);
EXPECT_SUCCESS(s2n_config_set_protocol_preferences(config, protocols, protocols_count));
EXPECT_SUCCESS(s2n_connection_set_config(client_conn, config));
DEFER_CLEANUP(struct s2n_stuffer extension = { 0 }, s2n_stuffer_free);
EXPECT_SUCCESS(s2n_stuffer_growable_alloc(&extension, 0));
uint8_t protocol[] = { SPDY3 };
EXPECT_SUCCESS(s2n_stuffer_write_uint8(&extension, sizeof(protocol)));
EXPECT_SUCCESS(s2n_stuffer_write_bytes(&extension, protocol, sizeof(protocol)));
/*
*= https://datatracker.ietf.org/doc/id/draft-agl-tls-nextprotoneg-03#section-4
*= type=test
*# In the event that the client doesn't support any of server's protocols, or
*# the server doesn't advertise any, it SHOULD select the first protocol
*# that it supports.
*/
EXPECT_SUCCESS(s2n_server_npn_extension.recv(client_conn, &extension));
EXPECT_NOT_NULL(s2n_get_application_protocol(client_conn));
EXPECT_BYTEARRAY_EQUAL(s2n_get_application_protocol(client_conn), protocols[0], strlen(protocols[0]));
};
/* Server sends empty list */
{
DEFER_CLEANUP(struct s2n_connection *client_conn = s2n_connection_new(S2N_CLIENT), s2n_connection_ptr_free);
EXPECT_NOT_NULL(client_conn);
DEFER_CLEANUP(struct s2n_config *config = s2n_config_new(), s2n_config_ptr_free);
EXPECT_NOT_NULL(config);
EXPECT_SUCCESS(s2n_config_set_protocol_preferences(config, protocols, protocols_count));
EXPECT_SUCCESS(s2n_connection_set_config(client_conn, config));
DEFER_CLEANUP(struct s2n_stuffer extension = { 0 }, s2n_stuffer_free);
EXPECT_SUCCESS(s2n_stuffer_growable_alloc(&extension, 0));
/*
*= https://datatracker.ietf.org/doc/id/draft-agl-tls-nextprotoneg-03#section-4
*= type=test
*# In the event that the client doesn't support any of server's protocols, or
*# the server doesn't advertise any, it SHOULD select the first protocol
*# that it supports.
*/
EXPECT_SUCCESS(s2n_server_npn_extension.recv(client_conn, &extension));
EXPECT_NOT_NULL(s2n_get_application_protocol(client_conn));
EXPECT_BYTEARRAY_EQUAL(s2n_get_application_protocol(client_conn), protocols[0], strlen(protocols[0]));
};
/* Multiple matches exist and server's preferred choice is selected */
{
DEFER_CLEANUP(struct s2n_connection *client_conn = s2n_connection_new(S2N_CLIENT), s2n_connection_ptr_free);
EXPECT_NOT_NULL(client_conn);
DEFER_CLEANUP(struct s2n_config *config = s2n_config_new(), s2n_config_ptr_free);
EXPECT_NOT_NULL(config);
EXPECT_SUCCESS(s2n_config_set_protocol_preferences(config, protocols, protocols_count));
EXPECT_SUCCESS(s2n_connection_set_config(client_conn, config));
DEFER_CLEANUP(struct s2n_stuffer extension = { 0 }, s2n_stuffer_free);
EXPECT_SUCCESS(s2n_stuffer_growable_alloc(&extension, 0));
uint8_t wire_bytes[] = {
/* Size and bytes of first protocol */
0x06,
SPDY1,
/* Size and bytes of second protocol */
0x08,
HTTP11,
/* Size and bytes of second protocol */
0x06,
SPDY2,
};
EXPECT_SUCCESS(s2n_stuffer_write_bytes(&extension, wire_bytes, sizeof(wire_bytes)));
EXPECT_SUCCESS(s2n_server_npn_extension.recv(client_conn, &extension));
EXPECT_NOT_NULL(s2n_get_application_protocol(client_conn));
/* Client's second protocol is selected because the server prefers it over client's first protocol */
EXPECT_BYTEARRAY_EQUAL(s2n_get_application_protocol(client_conn), protocols[1], strlen(protocols[1]));
};
};
/* Check application protocol array can hold the largest uint8_t value.
*
* We frequently copy a uint8_t's worth of data into this array. Adding
* checks to ensure that the array will be large enough causes compilers
* to give warnings that the check will always be true.
* This test will fail if we ever make that array smaller, so we remember
* to go back and add those checks.
*/
{
DEFER_CLEANUP(struct s2n_connection *server_conn = s2n_connection_new(S2N_SERVER), s2n_connection_ptr_free);
EXPECT_NOT_NULL(server_conn);
/* Not <= because the application protocol is a string, which needs to
* be terminated by a null character */
EXPECT_TRUE(UINT8_MAX < sizeof(server_conn->application_protocol));
};
END_TEST();
}
|
82be72f3eba3e9159f82a425045a48bbccda60ab
|
39568e19301a7a112398be542154950af25591de
|
/sw/device/lib/ujson/ujson.c
|
01cc04d82b469deaaa2a36eb4bbbd269fbf2b6f7
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
lowRISC/opentitan
|
493995bc7cf7cb3aee486a5203af3fd62bba3bfc
|
51f6017b8425b14d5a4aa9abace8fe5a25ef08c8
|
refs/heads/master
| 2023-08-31T22:05:09.425796
| 2023-08-14T14:52:15
| 2023-08-31T20:31:13
| 204,516,692
| 2,077
| 634
|
Apache-2.0
| 2023-09-14T21:16:21
| 2019-08-26T16:30:16
|
SystemVerilog
|
UTF-8
|
C
| false
| false
| 10,813
|
c
|
ujson.c
|
// Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
#include "sw/device/lib/ujson/ujson.h"
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include "sw/device/lib/base/math.h"
#include "sw/device/lib/base/status.h"
#include "sw/device/lib/runtime/print.h"
#include "sw/device/lib/ujson/private_status.h"
#include "sw/device/silicon_creator/lib/crc32.h"
static bool is_space(int c) { return c == ' ' || (unsigned)c - '\t' < 5; }
ujson_t ujson_init(void *context, status_t (*getc)(void *),
status_t (*putbuf)(void *, const char *, size_t)) {
ujson_t u = UJSON_INIT(context, getc, putbuf);
return u;
}
void ujson_crc32_reset(ujson_t *uj) { crc32_init(&uj->crc32); }
uint32_t ujson_crc32_finish(ujson_t *uj) { return crc32_finish(&uj->crc32); }
status_t ujson_putbuf(ujson_t *uj, const char *buf, size_t len) {
crc32_add(&uj->crc32, buf, len);
return uj->putbuf(uj->io_context, buf, len);
}
status_t ujson_getc(ujson_t *uj) {
int16_t buffer = uj->buffer;
if (buffer >= 0) {
uj->buffer = -1;
return OK_STATUS(buffer);
} else {
status_t s = uj->getc(uj->io_context);
if (!status_err(s)) {
crc32_add8(&uj->crc32, (uint8_t)s.value);
}
return s;
}
}
status_t ujson_ungetc(ujson_t *uj, char ch) {
if (uj->buffer >= 0) {
return FAILED_PRECONDITION();
}
uj->buffer = ch;
return OK_STATUS();
}
bool ujson_streq(const char *a, const char *b) {
while (*a && *b && *a == *b) {
++a;
++b;
}
return *a == *b;
}
// Consumes whitespace returning first non-whitepsace character found.
static status_t consume_whitespace(ujson_t *uj) {
int ch;
do {
ch = TRY(ujson_getc(uj));
} while (is_space(ch));
return OK_STATUS(ch);
}
static status_t consume_hexdigit(ujson_t *uj) {
int ch = TRY(ujson_getc(uj));
if (ch >= '0' && ch <= '9') {
return OK_STATUS(ch - '0');
} else if (ch >= 'A' && ch <= 'F') {
return OK_STATUS(ch - 'A' + 10);
} else if (ch >= 'a' && ch <= 'f') {
return OK_STATUS(ch - 'a' + 10);
} else {
return OUT_OF_RANGE();
}
}
static status_t consume_hex(ujson_t *uj) {
int a = TRY(consume_hexdigit(uj));
int b = TRY(consume_hexdigit(uj));
int c = TRY(consume_hexdigit(uj));
int d = TRY(consume_hexdigit(uj));
return OK_STATUS((a << 12) | (b << 8) | (c << 4) | d);
}
status_t ujson_consume(ujson_t *uj, char ch) {
if (ch != TRY(consume_whitespace(uj))) {
return NOT_FOUND();
}
return OK_STATUS();
}
status_t ujson_consume_maybe(ujson_t *uj, char ch) {
char got = (char)TRY(consume_whitespace(uj));
if (ch != got) {
ujson_ungetc(uj, got);
return OK_STATUS(0);
}
return OK_STATUS(1);
}
status_t ujson_parse_qs(ujson_t *uj, char *str, size_t len) {
char ch;
int n = 0;
len--; // One char for the nul terminator.
TRY(ujson_consume(uj, '"'));
while (true) {
ch = (char)TRY(ujson_getc(uj));
if (ch == '\"')
break;
if (ch == '\\') {
ch = (char)TRY(ujson_getc(uj));
switch (ch) {
case '"':
case '\\':
case '/':
break;
case 'b':
ch = '\b';
break;
case 'f':
ch = '\f';
break;
case 'n':
ch = '\n';
break;
case 'r':
ch = '\r';
break;
case 't':
ch = '\t';
break;
case 'u':
ch = (char)TRY(consume_hex(uj));
break;
default:
return OUT_OF_RANGE();
}
}
if (len > 0) {
*str++ = ch;
--len;
n++;
}
}
*str = '\0';
return OK_STATUS(n);
}
status_t ujson_parse_integer(ujson_t *uj, void *result, size_t rsz) {
char ch = (char)TRY(consume_whitespace(uj));
bool neg = false;
if (ch == '-') {
neg = true;
ch = (char)TRY(ujson_getc(uj));
}
int64_t value = 0;
if (!(ch >= '0' && ch <= '9')) {
return NOT_FOUND();
}
status_t s;
while (ch >= '0' && ch <= '9') {
value *= 10;
value += ch - '0';
s = ujson_getc(uj);
if (status_err(s))
break;
ch = (char)s.value;
}
if (status_ok(s))
TRY(ujson_ungetc(uj, ch));
if (neg)
value = -value;
memcpy(result, &value, rsz);
return OK_STATUS();
}
status_t ujson_deserialize_bool(ujson_t *uj, bool *value) {
char got = (char)TRY(consume_whitespace(uj));
if (got == 't') {
TRY(ujson_consume(uj, 'r'));
TRY(ujson_consume(uj, 'u'));
TRY(ujson_consume(uj, 'e'));
*value = true;
} else if (got == 'f') {
TRY(ujson_consume(uj, 'a'));
TRY(ujson_consume(uj, 'l'));
TRY(ujson_consume(uj, 's'));
TRY(ujson_consume(uj, 'e'));
*value = false;
} else {
ujson_ungetc(uj, got);
return NOT_FOUND();
}
return OK_STATUS();
}
status_t ujson_deserialize_uint64_t(ujson_t *uj, uint64_t *value) {
return ujson_parse_integer(uj, (void *)value, sizeof(*value));
}
status_t ujson_deserialize_uint32_t(ujson_t *uj, uint32_t *value) {
return ujson_parse_integer(uj, (void *)value, sizeof(*value));
}
status_t ujson_deserialize_uint16_t(ujson_t *uj, uint16_t *value) {
return ujson_parse_integer(uj, (void *)value, sizeof(*value));
}
status_t ujson_deserialize_uint8_t(ujson_t *uj, uint8_t *value) {
return ujson_parse_integer(uj, (void *)value, sizeof(*value));
}
status_t ujson_deserialize_size_t(ujson_t *uj, size_t *value) {
return ujson_parse_integer(uj, (void *)value, sizeof(*value));
}
status_t ujson_deserialize_int64_t(ujson_t *uj, int64_t *value) {
return ujson_parse_integer(uj, (void *)value, sizeof(*value));
}
status_t ujson_deserialize_int32_t(ujson_t *uj, int32_t *value) {
return ujson_parse_integer(uj, (void *)value, sizeof(*value));
}
status_t ujson_deserialize_int16_t(ujson_t *uj, int16_t *value) {
return ujson_parse_integer(uj, (void *)value, sizeof(*value));
}
status_t ujson_deserialize_int8_t(ujson_t *uj, int8_t *value) {
return ujson_parse_integer(uj, (void *)value, sizeof(*value));
}
static const char hex[] = "0123456789abcdef";
status_t ujson_serialize_string(ujson_t *uj, const char *buf) {
uint8_t ch;
TRY(ujson_putbuf(uj, "\"", 1));
while ((ch = (uint8_t)*buf) != '\0') {
if (ch < 0x20 || ch == '"' || ch == '\\' || ch >= 0x7f) {
switch (ch) {
case '"':
TRY(ujson_putbuf(uj, "\\\"", 2));
break;
case '\\':
TRY(ujson_putbuf(uj, "\\\\", 2));
break;
case '\b':
TRY(ujson_putbuf(uj, "\\b", 2));
break;
case '\f':
TRY(ujson_putbuf(uj, "\\f", 2));
break;
case '\n':
TRY(ujson_putbuf(uj, "\\n", 2));
break;
case '\r':
TRY(ujson_putbuf(uj, "\\r", 2));
break;
case '\t':
TRY(ujson_putbuf(uj, "\\t", 2));
break;
default: {
char esc[] = {'\\', 'u', '0', '0', hex[ch >> 4], hex[ch & 0xF]};
TRY(ujson_putbuf(uj, esc, sizeof(esc)));
}
}
} else {
TRY(ujson_putbuf(uj, buf, 1));
}
++buf;
}
TRY(ujson_putbuf(uj, "\"", 1));
return OK_STATUS();
}
static status_t ujson_serialize_integer64(ujson_t *uj, uint64_t value,
bool neg) {
char buf[24];
char *end = buf + sizeof(buf);
size_t len = 0;
*--end = '\0';
// If negative, two's complement for the absolute value.
if (neg)
value = ~value + 1;
do {
// We've banned __udivdi3; do division with the replacement function.
uint64_t remainder;
value = udiv64_slow(value, 10, &remainder);
*--end = '0' + (char)remainder;
++len;
} while (value);
if (neg) {
*--end = '-';
++len;
}
TRY(ujson_putbuf(uj, end, len));
return OK_STATUS();
}
static status_t ujson_serialize_integer32(ujson_t *uj, uint32_t value,
bool neg) {
char buf[24];
char *end = buf + sizeof(buf);
size_t len = 0;
*--end = '\0';
// If negative, two's complement for the absolute value.
if (neg)
value = ~value + 1;
do {
*--end = '0' + value % 10;
value /= 10;
++len;
} while (value);
if (neg) {
*--end = '-';
++len;
}
TRY(ujson_putbuf(uj, end, len));
return OK_STATUS();
}
status_t ujson_serialize_bool(ujson_t *uj, const bool *value) {
if (*value) {
TRY(ujson_putbuf(uj, "true", 4));
} else {
TRY(ujson_putbuf(uj, "false", 5));
}
return OK_STATUS();
}
status_t ujson_serialize_uint64_t(ujson_t *uj, const uint64_t *value) {
return ujson_serialize_integer64(uj, *value, false);
}
status_t ujson_serialize_uint32_t(ujson_t *uj, const uint32_t *value) {
return ujson_serialize_integer32(uj, *value, false);
}
status_t ujson_serialize_uint16_t(ujson_t *uj, const uint16_t *value) {
return ujson_serialize_integer32(uj, *value, false);
}
status_t ujson_serialize_uint8_t(ujson_t *uj, const uint8_t *value) {
return ujson_serialize_integer32(uj, *value, false);
}
status_t ujson_serialize_size_t(ujson_t *uj, const size_t *value) {
if (sizeof(size_t) == sizeof(uint64_t)) {
return ujson_serialize_integer64(uj, *value, false);
} else {
return ujson_serialize_integer32(uj, *value, false);
}
}
status_t ujson_serialize_int64_t(ujson_t *uj, const int64_t *value) {
return ujson_serialize_integer64(uj, (uint64_t)*value, *value < 0);
}
status_t ujson_serialize_int32_t(ujson_t *uj, const int32_t *value) {
return ujson_serialize_integer32(uj, (uint32_t)*value, *value < 0);
}
status_t ujson_serialize_int16_t(ujson_t *uj, const int16_t *value) {
return ujson_serialize_integer32(uj, (uint32_t)*value, *value < 0);
}
status_t ujson_serialize_int8_t(ujson_t *uj, const int8_t *value) {
return ujson_serialize_integer32(uj, (uint32_t)*value, *value < 0);
}
status_t ujson_deserialize_status_t(ujson_t *uj, status_t *value) {
private_status_t code;
uint32_t module_id = 0;
uint32_t arg = 0;
TRY(ujson_consume(uj, '{'));
TRY(ujson_deserialize_private_status_t(uj, &code));
TRY(ujson_consume(uj, ':'));
if (TRY(ujson_consume_maybe(uj, '['))) {
char module[4];
TRY(ujson_parse_qs(uj, module, sizeof(module)));
module_id = MAKE_MODULE_ID(module[0], module[1], module[2]);
TRY(ujson_consume(uj, ','));
TRY(ujson_deserialize_uint32_t(uj, &arg));
TRY(ujson_consume(uj, ']'));
} else {
TRY(ujson_deserialize_uint32_t(uj, &arg));
}
TRY(ujson_consume(uj, '}'));
*value =
status_create((absl_status_t)code, module_id, __FILE__, (int32_t)arg);
return OK_STATUS();
}
status_t ujson_serialize_status_t(ujson_t *uj, const status_t *value) {
buffer_sink_t out = {
.data = uj,
.sink = (size_t(*)(void *, const char *, size_t))ujson_putbuf,
};
base_fprintf(out, "%!r", *value);
return OK_STATUS();
}
|
c2c4a14c8e7b8c005682ad754a3f249fff5f838e
|
0f59e486ea9d7c96b8c3f7f92bf063fc8389f1e8
|
/vtrace/platforms/darwin/excUser.c
|
fe67a43de287c62475ca529b43d680ecf7dc9d48
|
[
"Apache-2.0"
] |
permissive
|
vivisect/vivisect
|
ac259918b6281d9431c32a0b2307c61f9cab0dec
|
b07e161cc28b19fdda0d047eefafed22c5b00f15
|
refs/heads/master
| 2023-08-25T09:02:00.526532
| 2023-07-26T03:07:07
| 2023-07-26T03:07:07
| 26,651,759
| 833
| 181
|
Apache-2.0
| 2023-09-07T03:43:53
| 2014-11-14T18:28:47
|
Python
|
UTF-8
|
C
| false
| false
| 52,461
|
c
|
excUser.c
|
/*
* IDENTIFICATION:
* stub generated Sat Jun 1 13:22:01 2013
* with a MiG generated Sun Oct 24 00:08:18 PDT 2010 by root@hokies.apple.com
* OPTIONS:
*/
#define __MIG_check__Reply__exc_subsystem__ 1
#define __NDR_convert__Reply__exc_subsystem__ 1
#define __NDR_convert__mig_reply_error_subsystem__ 1
#include "exc.h"
#ifndef mig_internal
#define mig_internal static __inline__
#endif /* mig_internal */
#ifndef mig_external
#define mig_external
#endif /* mig_external */
#if !defined(__MigTypeCheck) && defined(TypeCheck)
#define __MigTypeCheck TypeCheck /* Legacy setting */
#endif /* !defined(__MigTypeCheck) */
#if !defined(__MigKernelSpecificCode) && defined(_MIG_KERNEL_SPECIFIC_CODE_)
#define __MigKernelSpecificCode _MIG_KERNEL_SPECIFIC_CODE_ /* Legacy setting */
#endif /* !defined(__MigKernelSpecificCode) */
#ifndef LimitCheck
#define LimitCheck 0
#endif /* LimitCheck */
#ifndef min
#define min(a,b) ( ((a) < (b))? (a): (b) )
#endif /* min */
#if !defined(_WALIGN_)
#define _WALIGN_(x) (((x) + 3) & ~3)
#endif /* !defined(_WALIGN_) */
#if !defined(_WALIGNSZ_)
#define _WALIGNSZ_(x) _WALIGN_(sizeof(x))
#endif /* !defined(_WALIGNSZ_) */
#ifndef UseStaticTemplates
#define UseStaticTemplates 0
#endif /* UseStaticTemplates */
#ifndef __MachMsgErrorWithTimeout
#define __MachMsgErrorWithTimeout(_R_) { \
switch (_R_) { \
case MACH_SEND_INVALID_DATA: \
case MACH_SEND_INVALID_DEST: \
case MACH_SEND_INVALID_HEADER: \
mig_put_reply_port(InP->Head.msgh_reply_port); \
break; \
case MACH_SEND_TIMED_OUT: \
case MACH_RCV_TIMED_OUT: \
default: \
mig_dealloc_reply_port(InP->Head.msgh_reply_port); \
} \
}
#endif /* __MachMsgErrorWithTimeout */
#ifndef __MachMsgErrorWithoutTimeout
#define __MachMsgErrorWithoutTimeout(_R_) { \
switch (_R_) { \
case MACH_SEND_INVALID_DATA: \
case MACH_SEND_INVALID_DEST: \
case MACH_SEND_INVALID_HEADER: \
mig_put_reply_port(InP->Head.msgh_reply_port); \
break; \
default: \
mig_dealloc_reply_port(InP->Head.msgh_reply_port); \
} \
}
#endif /* __MachMsgErrorWithoutTimeout */
#ifndef __DeclareSendRpc
#define __DeclareSendRpc(_NUM_, _NAME_)
#endif /* __DeclareSendRpc */
#ifndef __BeforeSendRpc
#define __BeforeSendRpc(_NUM_, _NAME_)
#endif /* __BeforeSendRpc */
#ifndef __AfterSendRpc
#define __AfterSendRpc(_NUM_, _NAME_)
#endif /* __AfterSendRpc */
#ifndef __DeclareSendSimple
#define __DeclareSendSimple(_NUM_, _NAME_)
#endif /* __DeclareSendSimple */
#ifndef __BeforeSendSimple
#define __BeforeSendSimple(_NUM_, _NAME_)
#endif /* __BeforeSendSimple */
#ifndef __AfterSendSimple
#define __AfterSendSimple(_NUM_, _NAME_)
#endif /* __AfterSendSimple */
#define msgh_request_port msgh_remote_port
#define msgh_reply_port msgh_local_port
#if ( __MigTypeCheck || __NDR_convert__ )
#if __MIG_check__Reply__exc_subsystem__
#if !defined(__MIG_check__Reply__exception_raise_t__defined)
#define __MIG_check__Reply__exception_raise_t__defined
#ifndef __NDR_convert__int_rep__Reply__exception_raise_t__RetCode__defined
#if defined(__NDR_convert__int_rep__exc__kern_return_t__defined)
#define __NDR_convert__int_rep__Reply__exception_raise_t__RetCode__defined
#define __NDR_convert__int_rep__Reply__exception_raise_t__RetCode(a, f) \
__NDR_convert__int_rep__exc__kern_return_t((kern_return_t *)(a), f)
#elif defined(__NDR_convert__int_rep__kern_return_t__defined)
#define __NDR_convert__int_rep__Reply__exception_raise_t__RetCode__defined
#define __NDR_convert__int_rep__Reply__exception_raise_t__RetCode(a, f) \
__NDR_convert__int_rep__kern_return_t((kern_return_t *)(a), f)
#endif /* defined(__NDR_convert__*__defined) */
#endif /* __NDR_convert__int_rep__Reply__exception_raise_t__RetCode__defined */
mig_internal kern_return_t __MIG_check__Reply__exception_raise_t(__Reply__exception_raise_t *Out0P)
{
typedef __Reply__exception_raise_t __Reply;
if (Out0P->Head.msgh_id != 2501) {
if (Out0P->Head.msgh_id == MACH_NOTIFY_SEND_ONCE)
{ return MIG_SERVER_DIED; }
else
{ return MIG_REPLY_MISMATCH; }
}
#if __MigTypeCheck
if ((Out0P->Head.msgh_bits & MACH_MSGH_BITS_COMPLEX) ||
(Out0P->Head.msgh_size != (mach_msg_size_t)sizeof(__Reply)))
{ return MIG_TYPE_ERROR ; }
#endif /* __MigTypeCheck */
#if defined(__NDR_convert__int_rep__Reply__exception_raise_t__RetCode__defined)
if (Out0P->NDR.int_rep != NDR_record.int_rep)
__NDR_convert__int_rep__Reply__exception_raise_t__RetCode(&Out0P->RetCode, Out0P->NDR.int_rep);
#endif /* __NDR_convert__int_rep__Reply__exception_raise_t__RetCode__defined */
{
return Out0P->RetCode;
}
}
#endif /* !defined(__MIG_check__Reply__exception_raise_t__defined) */
#endif /* __MIG_check__Reply__exc_subsystem__ */
#endif /* ( __MigTypeCheck || __NDR_convert__ ) */
/* Routine exception_raise */
mig_external kern_return_t exception_raise
(
mach_port_t exception_port,
mach_port_t thread,
mach_port_t task,
exception_type_t exception,
exception_data_t code,
mach_msg_type_number_t codeCnt
)
{
#ifdef __MigPackStructs
#pragma pack(4)
#endif
typedef struct {
mach_msg_header_t Head;
/* start of the kernel processed data */
mach_msg_body_t msgh_body;
mach_msg_port_descriptor_t thread;
mach_msg_port_descriptor_t task;
/* end of the kernel processed data */
NDR_record_t NDR;
exception_type_t exception;
mach_msg_type_number_t codeCnt;
integer_t code[2];
} Request;
#ifdef __MigPackStructs
#pragma pack()
#endif
#ifdef __MigPackStructs
#pragma pack(4)
#endif
typedef struct {
mach_msg_header_t Head;
NDR_record_t NDR;
kern_return_t RetCode;
mach_msg_trailer_t trailer;
} Reply;
#ifdef __MigPackStructs
#pragma pack()
#endif
#ifdef __MigPackStructs
#pragma pack(4)
#endif
typedef struct {
mach_msg_header_t Head;
NDR_record_t NDR;
kern_return_t RetCode;
} __Reply;
#ifdef __MigPackStructs
#pragma pack()
#endif
/*
* typedef struct {
* mach_msg_header_t Head;
* NDR_record_t NDR;
* kern_return_t RetCode;
* } mig_reply_error_t;
*/
union {
Request In;
Reply Out;
} Mess;
Request *InP = &Mess.In;
Reply *Out0P = &Mess.Out;
mach_msg_return_t msg_result;
unsigned int msgh_size;
#ifdef __MIG_check__Reply__exception_raise_t__defined
kern_return_t check_result;
#endif /* __MIG_check__Reply__exception_raise_t__defined */
__DeclareSendRpc(2401, "exception_raise")
#if UseStaticTemplates
const static mach_msg_port_descriptor_t threadTemplate = {
/* name = */ MACH_PORT_NULL,
/* pad1 = */ 0,
/* pad2 = */ 0,
/* disp = */ 19,
/* type = */ MACH_MSG_PORT_DESCRIPTOR,
};
#endif /* UseStaticTemplates */
#if UseStaticTemplates
const static mach_msg_port_descriptor_t taskTemplate = {
/* name = */ MACH_PORT_NULL,
/* pad1 = */ 0,
/* pad2 = */ 0,
/* disp = */ 19,
/* type = */ MACH_MSG_PORT_DESCRIPTOR,
};
#endif /* UseStaticTemplates */
InP->msgh_body.msgh_descriptor_count = 2;
#if UseStaticTemplates
InP->thread = threadTemplate;
InP->thread.name = thread;
#else /* UseStaticTemplates */
InP->thread.name = thread;
InP->thread.disposition = 19;
InP->thread.type = MACH_MSG_PORT_DESCRIPTOR;
#endif /* UseStaticTemplates */
#if UseStaticTemplates
InP->task = taskTemplate;
InP->task.name = task;
#else /* UseStaticTemplates */
InP->task.name = task;
InP->task.disposition = 19;
InP->task.type = MACH_MSG_PORT_DESCRIPTOR;
#endif /* UseStaticTemplates */
InP->NDR = NDR_record;
InP->exception = exception;
if (codeCnt > 2) {
{ return MIG_ARRAY_TOO_LARGE; }
}
(void)memcpy((char *) InP->code, (const char *) code, 4 * codeCnt);
InP->codeCnt = codeCnt;
msgh_size = (mach_msg_size_t)(sizeof(Request) - 8) + ((4 * codeCnt));
InP->Head.msgh_bits = MACH_MSGH_BITS_COMPLEX|
MACH_MSGH_BITS(19, MACH_MSG_TYPE_MAKE_SEND_ONCE);
/* msgh_size passed as argument */
InP->Head.msgh_request_port = exception_port;
InP->Head.msgh_reply_port = mig_get_reply_port();
InP->Head.msgh_id = 2401;
__BeforeSendRpc(2401, "exception_raise")
msg_result = mach_msg(&InP->Head, MACH_SEND_MSG|MACH_RCV_MSG|MACH_MSG_OPTION_NONE, msgh_size, (mach_msg_size_t)sizeof(Reply), InP->Head.msgh_reply_port, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
__AfterSendRpc(2401, "exception_raise")
if (msg_result != MACH_MSG_SUCCESS) {
__MachMsgErrorWithoutTimeout(msg_result);
{ return msg_result; }
}
#if defined(__MIG_check__Reply__exception_raise_t__defined)
check_result = __MIG_check__Reply__exception_raise_t((__Reply__exception_raise_t *)Out0P);
if (check_result != MACH_MSG_SUCCESS)
{ return check_result; }
#endif /* defined(__MIG_check__Reply__exception_raise_t__defined) */
return KERN_SUCCESS;
}
#if ( __MigTypeCheck || __NDR_convert__ )
#if __MIG_check__Reply__exc_subsystem__
#if !defined(__MIG_check__Reply__exception_raise_state_t__defined)
#define __MIG_check__Reply__exception_raise_state_t__defined
#ifndef __NDR_convert__int_rep__Reply__exception_raise_state_t__RetCode__defined
#if defined(__NDR_convert__int_rep__exc__kern_return_t__defined)
#define __NDR_convert__int_rep__Reply__exception_raise_state_t__RetCode__defined
#define __NDR_convert__int_rep__Reply__exception_raise_state_t__RetCode(a, f) \
__NDR_convert__int_rep__exc__kern_return_t((kern_return_t *)(a), f)
#elif defined(__NDR_convert__int_rep__kern_return_t__defined)
#define __NDR_convert__int_rep__Reply__exception_raise_state_t__RetCode__defined
#define __NDR_convert__int_rep__Reply__exception_raise_state_t__RetCode(a, f) \
__NDR_convert__int_rep__kern_return_t((kern_return_t *)(a), f)
#endif /* defined(__NDR_convert__*__defined) */
#endif /* __NDR_convert__int_rep__Reply__exception_raise_state_t__RetCode__defined */
#ifndef __NDR_convert__int_rep__Reply__exception_raise_state_t__flavor__defined
#if defined(__NDR_convert__int_rep__exc__int__defined)
#define __NDR_convert__int_rep__Reply__exception_raise_state_t__flavor__defined
#define __NDR_convert__int_rep__Reply__exception_raise_state_t__flavor(a, f) \
__NDR_convert__int_rep__exc__int((int *)(a), f)
#elif defined(__NDR_convert__int_rep__int__defined)
#define __NDR_convert__int_rep__Reply__exception_raise_state_t__flavor__defined
#define __NDR_convert__int_rep__Reply__exception_raise_state_t__flavor(a, f) \
__NDR_convert__int_rep__int((int *)(a), f)
#elif defined(__NDR_convert__int_rep__exc__int32_t__defined)
#define __NDR_convert__int_rep__Reply__exception_raise_state_t__flavor__defined
#define __NDR_convert__int_rep__Reply__exception_raise_state_t__flavor(a, f) \
__NDR_convert__int_rep__exc__int32_t((int32_t *)(a), f)
#elif defined(__NDR_convert__int_rep__int32_t__defined)
#define __NDR_convert__int_rep__Reply__exception_raise_state_t__flavor__defined
#define __NDR_convert__int_rep__Reply__exception_raise_state_t__flavor(a, f) \
__NDR_convert__int_rep__int32_t((int32_t *)(a), f)
#endif /* defined(__NDR_convert__*__defined) */
#endif /* __NDR_convert__int_rep__Reply__exception_raise_state_t__flavor__defined */
#ifndef __NDR_convert__int_rep__Reply__exception_raise_state_t__new_state__defined
#if defined(__NDR_convert__int_rep__exc__thread_state_t__defined)
#define __NDR_convert__int_rep__Reply__exception_raise_state_t__new_state__defined
#define __NDR_convert__int_rep__Reply__exception_raise_state_t__new_state(a, f, c) \
__NDR_convert__int_rep__exc__thread_state_t((thread_state_t *)(a), f, c)
#elif defined(__NDR_convert__int_rep__thread_state_t__defined)
#define __NDR_convert__int_rep__Reply__exception_raise_state_t__new_state__defined
#define __NDR_convert__int_rep__Reply__exception_raise_state_t__new_state(a, f, c) \
__NDR_convert__int_rep__thread_state_t((thread_state_t *)(a), f, c)
#elif defined(__NDR_convert__int_rep__exc__natural_t__defined)
#define __NDR_convert__int_rep__Reply__exception_raise_state_t__new_state__defined
#define __NDR_convert__int_rep__Reply__exception_raise_state_t__new_state(a, f, c) \
__NDR_convert__ARRAY((natural_t *)(a), f, c, __NDR_convert__int_rep__exc__natural_t)
#elif defined(__NDR_convert__int_rep__natural_t__defined)
#define __NDR_convert__int_rep__Reply__exception_raise_state_t__new_state__defined
#define __NDR_convert__int_rep__Reply__exception_raise_state_t__new_state(a, f, c) \
__NDR_convert__ARRAY((natural_t *)(a), f, c, __NDR_convert__int_rep__natural_t)
#elif defined(__NDR_convert__int_rep__exc__uint32_t__defined)
#define __NDR_convert__int_rep__Reply__exception_raise_state_t__new_state__defined
#define __NDR_convert__int_rep__Reply__exception_raise_state_t__new_state(a, f, c) \
__NDR_convert__ARRAY((uint32_t *)(a), f, c, __NDR_convert__int_rep__exc__uint32_t)
#elif defined(__NDR_convert__int_rep__uint32_t__defined)
#define __NDR_convert__int_rep__Reply__exception_raise_state_t__new_state__defined
#define __NDR_convert__int_rep__Reply__exception_raise_state_t__new_state(a, f, c) \
__NDR_convert__ARRAY((uint32_t *)(a), f, c, __NDR_convert__int_rep__uint32_t)
#endif /* defined(__NDR_convert__*__defined) */
#endif /* __NDR_convert__int_rep__Reply__exception_raise_state_t__new_state__defined */
#ifndef __NDR_convert__int_rep__Reply__exception_raise_state_t__new_stateCnt__defined
#if defined(__NDR_convert__int_rep__exc__mach_msg_type_number_t__defined)
#define __NDR_convert__int_rep__Reply__exception_raise_state_t__new_stateCnt__defined
#define __NDR_convert__int_rep__Reply__exception_raise_state_t__new_stateCnt(a, f) \
__NDR_convert__int_rep__exc__mach_msg_type_number_t((mach_msg_type_number_t *)(a), f)
#elif defined(__NDR_convert__int_rep__mach_msg_type_number_t__defined)
#define __NDR_convert__int_rep__Reply__exception_raise_state_t__new_stateCnt__defined
#define __NDR_convert__int_rep__Reply__exception_raise_state_t__new_stateCnt(a, f) \
__NDR_convert__int_rep__mach_msg_type_number_t((mach_msg_type_number_t *)(a), f)
#endif /* defined(__NDR_convert__*__defined) */
#endif /* __NDR_convert__int_rep__Reply__exception_raise_state_t__new_stateCnt__defined */
#ifndef __NDR_convert__char_rep__Reply__exception_raise_state_t__flavor__defined
#if defined(__NDR_convert__char_rep__exc__int__defined)
#define __NDR_convert__char_rep__Reply__exception_raise_state_t__flavor__defined
#define __NDR_convert__char_rep__Reply__exception_raise_state_t__flavor(a, f) \
__NDR_convert__char_rep__exc__int((int *)(a), f)
#elif defined(__NDR_convert__char_rep__int__defined)
#define __NDR_convert__char_rep__Reply__exception_raise_state_t__flavor__defined
#define __NDR_convert__char_rep__Reply__exception_raise_state_t__flavor(a, f) \
__NDR_convert__char_rep__int((int *)(a), f)
#elif defined(__NDR_convert__char_rep__exc__int32_t__defined)
#define __NDR_convert__char_rep__Reply__exception_raise_state_t__flavor__defined
#define __NDR_convert__char_rep__Reply__exception_raise_state_t__flavor(a, f) \
__NDR_convert__char_rep__exc__int32_t((int32_t *)(a), f)
#elif defined(__NDR_convert__char_rep__int32_t__defined)
#define __NDR_convert__char_rep__Reply__exception_raise_state_t__flavor__defined
#define __NDR_convert__char_rep__Reply__exception_raise_state_t__flavor(a, f) \
__NDR_convert__char_rep__int32_t((int32_t *)(a), f)
#endif /* defined(__NDR_convert__*__defined) */
#endif /* __NDR_convert__char_rep__Reply__exception_raise_state_t__flavor__defined */
#ifndef __NDR_convert__char_rep__Reply__exception_raise_state_t__new_state__defined
#if defined(__NDR_convert__char_rep__exc__thread_state_t__defined)
#define __NDR_convert__char_rep__Reply__exception_raise_state_t__new_state__defined
#define __NDR_convert__char_rep__Reply__exception_raise_state_t__new_state(a, f, c) \
__NDR_convert__char_rep__exc__thread_state_t((thread_state_t *)(a), f, c)
#elif defined(__NDR_convert__char_rep__thread_state_t__defined)
#define __NDR_convert__char_rep__Reply__exception_raise_state_t__new_state__defined
#define __NDR_convert__char_rep__Reply__exception_raise_state_t__new_state(a, f, c) \
__NDR_convert__char_rep__thread_state_t((thread_state_t *)(a), f, c)
#elif defined(__NDR_convert__char_rep__exc__natural_t__defined)
#define __NDR_convert__char_rep__Reply__exception_raise_state_t__new_state__defined
#define __NDR_convert__char_rep__Reply__exception_raise_state_t__new_state(a, f, c) \
__NDR_convert__ARRAY((natural_t *)(a), f, c, __NDR_convert__char_rep__exc__natural_t)
#elif defined(__NDR_convert__char_rep__natural_t__defined)
#define __NDR_convert__char_rep__Reply__exception_raise_state_t__new_state__defined
#define __NDR_convert__char_rep__Reply__exception_raise_state_t__new_state(a, f, c) \
__NDR_convert__ARRAY((natural_t *)(a), f, c, __NDR_convert__char_rep__natural_t)
#elif defined(__NDR_convert__char_rep__exc__uint32_t__defined)
#define __NDR_convert__char_rep__Reply__exception_raise_state_t__new_state__defined
#define __NDR_convert__char_rep__Reply__exception_raise_state_t__new_state(a, f, c) \
__NDR_convert__ARRAY((uint32_t *)(a), f, c, __NDR_convert__char_rep__exc__uint32_t)
#elif defined(__NDR_convert__char_rep__uint32_t__defined)
#define __NDR_convert__char_rep__Reply__exception_raise_state_t__new_state__defined
#define __NDR_convert__char_rep__Reply__exception_raise_state_t__new_state(a, f, c) \
__NDR_convert__ARRAY((uint32_t *)(a), f, c, __NDR_convert__char_rep__uint32_t)
#endif /* defined(__NDR_convert__*__defined) */
#endif /* __NDR_convert__char_rep__Reply__exception_raise_state_t__new_state__defined */
#ifndef __NDR_convert__float_rep__Reply__exception_raise_state_t__flavor__defined
#if defined(__NDR_convert__float_rep__exc__int__defined)
#define __NDR_convert__float_rep__Reply__exception_raise_state_t__flavor__defined
#define __NDR_convert__float_rep__Reply__exception_raise_state_t__flavor(a, f) \
__NDR_convert__float_rep__exc__int((int *)(a), f)
#elif defined(__NDR_convert__float_rep__int__defined)
#define __NDR_convert__float_rep__Reply__exception_raise_state_t__flavor__defined
#define __NDR_convert__float_rep__Reply__exception_raise_state_t__flavor(a, f) \
__NDR_convert__float_rep__int((int *)(a), f)
#elif defined(__NDR_convert__float_rep__exc__int32_t__defined)
#define __NDR_convert__float_rep__Reply__exception_raise_state_t__flavor__defined
#define __NDR_convert__float_rep__Reply__exception_raise_state_t__flavor(a, f) \
__NDR_convert__float_rep__exc__int32_t((int32_t *)(a), f)
#elif defined(__NDR_convert__float_rep__int32_t__defined)
#define __NDR_convert__float_rep__Reply__exception_raise_state_t__flavor__defined
#define __NDR_convert__float_rep__Reply__exception_raise_state_t__flavor(a, f) \
__NDR_convert__float_rep__int32_t((int32_t *)(a), f)
#endif /* defined(__NDR_convert__*__defined) */
#endif /* __NDR_convert__float_rep__Reply__exception_raise_state_t__flavor__defined */
#ifndef __NDR_convert__float_rep__Reply__exception_raise_state_t__new_state__defined
#if defined(__NDR_convert__float_rep__exc__thread_state_t__defined)
#define __NDR_convert__float_rep__Reply__exception_raise_state_t__new_state__defined
#define __NDR_convert__float_rep__Reply__exception_raise_state_t__new_state(a, f, c) \
__NDR_convert__float_rep__exc__thread_state_t((thread_state_t *)(a), f, c)
#elif defined(__NDR_convert__float_rep__thread_state_t__defined)
#define __NDR_convert__float_rep__Reply__exception_raise_state_t__new_state__defined
#define __NDR_convert__float_rep__Reply__exception_raise_state_t__new_state(a, f, c) \
__NDR_convert__float_rep__thread_state_t((thread_state_t *)(a), f, c)
#elif defined(__NDR_convert__float_rep__exc__natural_t__defined)
#define __NDR_convert__float_rep__Reply__exception_raise_state_t__new_state__defined
#define __NDR_convert__float_rep__Reply__exception_raise_state_t__new_state(a, f, c) \
__NDR_convert__ARRAY((natural_t *)(a), f, c, __NDR_convert__float_rep__exc__natural_t)
#elif defined(__NDR_convert__float_rep__natural_t__defined)
#define __NDR_convert__float_rep__Reply__exception_raise_state_t__new_state__defined
#define __NDR_convert__float_rep__Reply__exception_raise_state_t__new_state(a, f, c) \
__NDR_convert__ARRAY((natural_t *)(a), f, c, __NDR_convert__float_rep__natural_t)
#elif defined(__NDR_convert__float_rep__exc__uint32_t__defined)
#define __NDR_convert__float_rep__Reply__exception_raise_state_t__new_state__defined
#define __NDR_convert__float_rep__Reply__exception_raise_state_t__new_state(a, f, c) \
__NDR_convert__ARRAY((uint32_t *)(a), f, c, __NDR_convert__float_rep__exc__uint32_t)
#elif defined(__NDR_convert__float_rep__uint32_t__defined)
#define __NDR_convert__float_rep__Reply__exception_raise_state_t__new_state__defined
#define __NDR_convert__float_rep__Reply__exception_raise_state_t__new_state(a, f, c) \
__NDR_convert__ARRAY((uint32_t *)(a), f, c, __NDR_convert__float_rep__uint32_t)
#endif /* defined(__NDR_convert__*__defined) */
#endif /* __NDR_convert__float_rep__Reply__exception_raise_state_t__new_state__defined */
mig_internal kern_return_t __MIG_check__Reply__exception_raise_state_t(__Reply__exception_raise_state_t *Out0P)
{
typedef __Reply__exception_raise_state_t __Reply;
#if __MigTypeCheck
unsigned int msgh_size;
#endif /* __MigTypeCheck */
if (Out0P->Head.msgh_id != 2502) {
if (Out0P->Head.msgh_id == MACH_NOTIFY_SEND_ONCE)
{ return MIG_SERVER_DIED; }
else
{ return MIG_REPLY_MISMATCH; }
}
#if __MigTypeCheck
msgh_size = Out0P->Head.msgh_size;
if ((Out0P->Head.msgh_bits & MACH_MSGH_BITS_COMPLEX) ||
((msgh_size > (mach_msg_size_t)sizeof(__Reply) || msgh_size < (mach_msg_size_t)(sizeof(__Reply) - 576)) &&
(msgh_size != (mach_msg_size_t)sizeof(mig_reply_error_t) ||
Out0P->RetCode == KERN_SUCCESS)))
{ return MIG_TYPE_ERROR ; }
#endif /* __MigTypeCheck */
if (Out0P->RetCode != KERN_SUCCESS) {
#ifdef __NDR_convert__mig_reply_error_t__defined
__NDR_convert__mig_reply_error_t((mig_reply_error_t *)Out0P);
#endif /* __NDR_convert__mig_reply_error_t__defined */
return ((mig_reply_error_t *)Out0P)->RetCode;
}
#if defined(__NDR_convert__int_rep__Reply__exception_raise_state_t__new_stateCnt__defined)
if (Out0P->NDR.int_rep != NDR_record.int_rep)
__NDR_convert__int_rep__Reply__exception_raise_state_t__new_stateCnt(&Out0P->new_stateCnt, Out0P->NDR.int_rep);
#endif /* __NDR_convert__int_rep__Reply__exception_raise_state_t__new_stateCnt__defined */
#if __MigTypeCheck
if (msgh_size != (mach_msg_size_t)(sizeof(__Reply) - 576) + ((4 * Out0P->new_stateCnt)))
{ return MIG_TYPE_ERROR ; }
#endif /* __MigTypeCheck */
#if defined(__NDR_convert__int_rep__Reply__exception_raise_state_t__RetCode__defined) || \
defined(__NDR_convert__int_rep__Reply__exception_raise_state_t__flavor__defined) || \
defined(__NDR_convert__int_rep__Reply__exception_raise_state_t__new_state__defined) || \
defined(__NDR_convert__int_rep__Reply__exception_raise_state_t__new_stateCnt__defined)
if (Out0P->NDR.int_rep != NDR_record.int_rep) {
#if defined(__NDR_convert__int_rep__Reply__exception_raise_state_t__RetCode__defined)
__NDR_convert__int_rep__Reply__exception_raise_state_t__RetCode(&Out0P->RetCode, Out0P->NDR.int_rep);
#endif /* __NDR_convert__int_rep__Reply__exception_raise_state_t__RetCode__defined */
#if defined(__NDR_convert__int_rep__Reply__exception_raise_state_t__flavor__defined)
__NDR_convert__int_rep__Reply__exception_raise_state_t__flavor(&Out0P->flavor, Out0P->NDR.int_rep);
#endif /* __NDR_convert__int_rep__Reply__exception_raise_state_t__flavor__defined */
#if defined(__NDR_convert__int_rep__Reply__exception_raise_state_t__new_state__defined)
__NDR_convert__int_rep__Reply__exception_raise_state_t__new_state(&Out0P->new_state, Out0P->NDR.int_rep, Out0P->new_stateCnt);
#endif /* __NDR_convert__int_rep__Reply__exception_raise_state_t__new_state__defined */
}
#endif /* defined(__NDR_convert__int_rep...) */
#if 0 || \
defined(__NDR_convert__char_rep__Reply__exception_raise_state_t__flavor__defined) || \
defined(__NDR_convert__char_rep__Reply__exception_raise_state_t__new_state__defined) || \
0
if (Out0P->NDR.char_rep != NDR_record.char_rep) {
#if defined(__NDR_convert__char_rep__Reply__exception_raise_state_t__flavor__defined)
__NDR_convert__char_rep__Reply__exception_raise_state_t__flavor(&Out0P->flavor, Out0P->NDR.char_rep);
#endif /* __NDR_convert__char_rep__Reply__exception_raise_state_t__flavor__defined */
#if defined(__NDR_convert__char_rep__Reply__exception_raise_state_t__new_state__defined)
__NDR_convert__char_rep__Reply__exception_raise_state_t__new_state(&Out0P->new_state, Out0P->NDR.char_rep, Out0P->new_stateCnt);
#endif /* __NDR_convert__char_rep__Reply__exception_raise_state_t__new_state__defined */
}
#endif /* defined(__NDR_convert__char_rep...) */
#if 0 || \
defined(__NDR_convert__float_rep__Reply__exception_raise_state_t__flavor__defined) || \
defined(__NDR_convert__float_rep__Reply__exception_raise_state_t__new_state__defined) || \
0
if (Out0P->NDR.float_rep != NDR_record.float_rep) {
#if defined(__NDR_convert__float_rep__Reply__exception_raise_state_t__flavor__defined)
__NDR_convert__float_rep__Reply__exception_raise_state_t__flavor(&Out0P->flavor, Out0P->NDR.float_rep);
#endif /* __NDR_convert__float_rep__Reply__exception_raise_state_t__flavor__defined */
#if defined(__NDR_convert__float_rep__Reply__exception_raise_state_t__new_state__defined)
__NDR_convert__float_rep__Reply__exception_raise_state_t__new_state(&Out0P->new_state, Out0P->NDR.float_rep, Out0P->new_stateCnt);
#endif /* __NDR_convert__float_rep__Reply__exception_raise_state_t__new_state__defined */
}
#endif /* defined(__NDR_convert__float_rep...) */
return MACH_MSG_SUCCESS;
}
#endif /* !defined(__MIG_check__Reply__exception_raise_state_t__defined) */
#endif /* __MIG_check__Reply__exc_subsystem__ */
#endif /* ( __MigTypeCheck || __NDR_convert__ ) */
/* Routine exception_raise_state */
mig_external kern_return_t exception_raise_state
(
mach_port_t exception_port,
exception_type_t exception,
const exception_data_t code,
mach_msg_type_number_t codeCnt,
int *flavor,
const thread_state_t old_state,
mach_msg_type_number_t old_stateCnt,
thread_state_t new_state,
mach_msg_type_number_t *new_stateCnt
)
{
#ifdef __MigPackStructs
#pragma pack(4)
#endif
typedef struct {
mach_msg_header_t Head;
NDR_record_t NDR;
exception_type_t exception;
mach_msg_type_number_t codeCnt;
integer_t code[2];
int flavor;
mach_msg_type_number_t old_stateCnt;
natural_t old_state[144];
} Request;
#ifdef __MigPackStructs
#pragma pack()
#endif
#ifdef __MigPackStructs
#pragma pack(4)
#endif
typedef struct {
mach_msg_header_t Head;
NDR_record_t NDR;
kern_return_t RetCode;
int flavor;
mach_msg_type_number_t new_stateCnt;
natural_t new_state[144];
mach_msg_trailer_t trailer;
} Reply;
#ifdef __MigPackStructs
#pragma pack()
#endif
#ifdef __MigPackStructs
#pragma pack(4)
#endif
typedef struct {
mach_msg_header_t Head;
NDR_record_t NDR;
kern_return_t RetCode;
int flavor;
mach_msg_type_number_t new_stateCnt;
natural_t new_state[144];
} __Reply;
#ifdef __MigPackStructs
#pragma pack()
#endif
/*
* typedef struct {
* mach_msg_header_t Head;
* NDR_record_t NDR;
* kern_return_t RetCode;
* } mig_reply_error_t;
*/
union {
Request In;
Reply Out;
} Mess;
Request *InP = &Mess.In;
Reply *Out0P = &Mess.Out;
mach_msg_return_t msg_result;
unsigned int msgh_size;
unsigned int msgh_size_delta;
#ifdef __MIG_check__Reply__exception_raise_state_t__defined
kern_return_t check_result;
#endif /* __MIG_check__Reply__exception_raise_state_t__defined */
__DeclareSendRpc(2402, "exception_raise_state")
InP->NDR = NDR_record;
InP->exception = exception;
if (codeCnt > 2) {
{ return MIG_ARRAY_TOO_LARGE; }
}
(void)memcpy((char *) InP->code, (const char *) code, 4 * codeCnt);
InP->codeCnt = codeCnt;
msgh_size_delta = (4 * codeCnt);
msgh_size = (mach_msg_size_t)(sizeof(Request) - 584) + msgh_size_delta;
InP = (Request *) ((pointer_t) InP + msgh_size_delta - 8);
InP->flavor = *flavor;
if (old_stateCnt > 144) {
{ return MIG_ARRAY_TOO_LARGE; }
}
(void)memcpy((char *) InP->old_state, (const char *) old_state, 4 * old_stateCnt);
InP->old_stateCnt = old_stateCnt;
msgh_size += (4 * old_stateCnt);
InP = &Mess.In;
InP->Head.msgh_bits =
MACH_MSGH_BITS(19, MACH_MSG_TYPE_MAKE_SEND_ONCE);
/* msgh_size passed as argument */
InP->Head.msgh_request_port = exception_port;
InP->Head.msgh_reply_port = mig_get_reply_port();
InP->Head.msgh_id = 2402;
__BeforeSendRpc(2402, "exception_raise_state")
msg_result = mach_msg(&InP->Head, MACH_SEND_MSG|MACH_RCV_MSG|MACH_MSG_OPTION_NONE, msgh_size, (mach_msg_size_t)sizeof(Reply), InP->Head.msgh_reply_port, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
__AfterSendRpc(2402, "exception_raise_state")
if (msg_result != MACH_MSG_SUCCESS) {
__MachMsgErrorWithoutTimeout(msg_result);
{ return msg_result; }
}
#if defined(__MIG_check__Reply__exception_raise_state_t__defined)
check_result = __MIG_check__Reply__exception_raise_state_t((__Reply__exception_raise_state_t *)Out0P);
if (check_result != MACH_MSG_SUCCESS)
{ return check_result; }
#endif /* defined(__MIG_check__Reply__exception_raise_state_t__defined) */
*flavor = Out0P->flavor;
if (Out0P->new_stateCnt > 144) {
(void)memcpy((char *) new_state, (const char *) Out0P->new_state, 4 * 144);
*new_stateCnt = Out0P->new_stateCnt;
{ return MIG_ARRAY_TOO_LARGE; }
}
(void)memcpy((char *) new_state, (const char *) Out0P->new_state, 4 * Out0P->new_stateCnt);
*new_stateCnt = Out0P->new_stateCnt;
return KERN_SUCCESS;
}
#if ( __MigTypeCheck || __NDR_convert__ )
#if __MIG_check__Reply__exc_subsystem__
#if !defined(__MIG_check__Reply__exception_raise_state_identity_t__defined)
#define __MIG_check__Reply__exception_raise_state_identity_t__defined
#ifndef __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__RetCode__defined
#if defined(__NDR_convert__int_rep__exc__kern_return_t__defined)
#define __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__RetCode__defined
#define __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__RetCode(a, f) \
__NDR_convert__int_rep__exc__kern_return_t((kern_return_t *)(a), f)
#elif defined(__NDR_convert__int_rep__kern_return_t__defined)
#define __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__RetCode__defined
#define __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__RetCode(a, f) \
__NDR_convert__int_rep__kern_return_t((kern_return_t *)(a), f)
#endif /* defined(__NDR_convert__*__defined) */
#endif /* __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__RetCode__defined */
#ifndef __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__flavor__defined
#if defined(__NDR_convert__int_rep__exc__int__defined)
#define __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__flavor__defined
#define __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__flavor(a, f) \
__NDR_convert__int_rep__exc__int((int *)(a), f)
#elif defined(__NDR_convert__int_rep__int__defined)
#define __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__flavor__defined
#define __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__flavor(a, f) \
__NDR_convert__int_rep__int((int *)(a), f)
#elif defined(__NDR_convert__int_rep__exc__int32_t__defined)
#define __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__flavor__defined
#define __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__flavor(a, f) \
__NDR_convert__int_rep__exc__int32_t((int32_t *)(a), f)
#elif defined(__NDR_convert__int_rep__int32_t__defined)
#define __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__flavor__defined
#define __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__flavor(a, f) \
__NDR_convert__int_rep__int32_t((int32_t *)(a), f)
#endif /* defined(__NDR_convert__*__defined) */
#endif /* __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__flavor__defined */
#ifndef __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__new_state__defined
#if defined(__NDR_convert__int_rep__exc__thread_state_t__defined)
#define __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__new_state__defined
#define __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__new_state(a, f, c) \
__NDR_convert__int_rep__exc__thread_state_t((thread_state_t *)(a), f, c)
#elif defined(__NDR_convert__int_rep__thread_state_t__defined)
#define __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__new_state__defined
#define __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__new_state(a, f, c) \
__NDR_convert__int_rep__thread_state_t((thread_state_t *)(a), f, c)
#elif defined(__NDR_convert__int_rep__exc__natural_t__defined)
#define __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__new_state__defined
#define __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__new_state(a, f, c) \
__NDR_convert__ARRAY((natural_t *)(a), f, c, __NDR_convert__int_rep__exc__natural_t)
#elif defined(__NDR_convert__int_rep__natural_t__defined)
#define __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__new_state__defined
#define __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__new_state(a, f, c) \
__NDR_convert__ARRAY((natural_t *)(a), f, c, __NDR_convert__int_rep__natural_t)
#elif defined(__NDR_convert__int_rep__exc__uint32_t__defined)
#define __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__new_state__defined
#define __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__new_state(a, f, c) \
__NDR_convert__ARRAY((uint32_t *)(a), f, c, __NDR_convert__int_rep__exc__uint32_t)
#elif defined(__NDR_convert__int_rep__uint32_t__defined)
#define __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__new_state__defined
#define __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__new_state(a, f, c) \
__NDR_convert__ARRAY((uint32_t *)(a), f, c, __NDR_convert__int_rep__uint32_t)
#endif /* defined(__NDR_convert__*__defined) */
#endif /* __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__new_state__defined */
#ifndef __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__new_stateCnt__defined
#if defined(__NDR_convert__int_rep__exc__mach_msg_type_number_t__defined)
#define __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__new_stateCnt__defined
#define __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__new_stateCnt(a, f) \
__NDR_convert__int_rep__exc__mach_msg_type_number_t((mach_msg_type_number_t *)(a), f)
#elif defined(__NDR_convert__int_rep__mach_msg_type_number_t__defined)
#define __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__new_stateCnt__defined
#define __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__new_stateCnt(a, f) \
__NDR_convert__int_rep__mach_msg_type_number_t((mach_msg_type_number_t *)(a), f)
#endif /* defined(__NDR_convert__*__defined) */
#endif /* __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__new_stateCnt__defined */
#ifndef __NDR_convert__char_rep__Reply__exception_raise_state_identity_t__flavor__defined
#if defined(__NDR_convert__char_rep__exc__int__defined)
#define __NDR_convert__char_rep__Reply__exception_raise_state_identity_t__flavor__defined
#define __NDR_convert__char_rep__Reply__exception_raise_state_identity_t__flavor(a, f) \
__NDR_convert__char_rep__exc__int((int *)(a), f)
#elif defined(__NDR_convert__char_rep__int__defined)
#define __NDR_convert__char_rep__Reply__exception_raise_state_identity_t__flavor__defined
#define __NDR_convert__char_rep__Reply__exception_raise_state_identity_t__flavor(a, f) \
__NDR_convert__char_rep__int((int *)(a), f)
#elif defined(__NDR_convert__char_rep__exc__int32_t__defined)
#define __NDR_convert__char_rep__Reply__exception_raise_state_identity_t__flavor__defined
#define __NDR_convert__char_rep__Reply__exception_raise_state_identity_t__flavor(a, f) \
__NDR_convert__char_rep__exc__int32_t((int32_t *)(a), f)
#elif defined(__NDR_convert__char_rep__int32_t__defined)
#define __NDR_convert__char_rep__Reply__exception_raise_state_identity_t__flavor__defined
#define __NDR_convert__char_rep__Reply__exception_raise_state_identity_t__flavor(a, f) \
__NDR_convert__char_rep__int32_t((int32_t *)(a), f)
#endif /* defined(__NDR_convert__*__defined) */
#endif /* __NDR_convert__char_rep__Reply__exception_raise_state_identity_t__flavor__defined */
#ifndef __NDR_convert__char_rep__Reply__exception_raise_state_identity_t__new_state__defined
#if defined(__NDR_convert__char_rep__exc__thread_state_t__defined)
#define __NDR_convert__char_rep__Reply__exception_raise_state_identity_t__new_state__defined
#define __NDR_convert__char_rep__Reply__exception_raise_state_identity_t__new_state(a, f, c) \
__NDR_convert__char_rep__exc__thread_state_t((thread_state_t *)(a), f, c)
#elif defined(__NDR_convert__char_rep__thread_state_t__defined)
#define __NDR_convert__char_rep__Reply__exception_raise_state_identity_t__new_state__defined
#define __NDR_convert__char_rep__Reply__exception_raise_state_identity_t__new_state(a, f, c) \
__NDR_convert__char_rep__thread_state_t((thread_state_t *)(a), f, c)
#elif defined(__NDR_convert__char_rep__exc__natural_t__defined)
#define __NDR_convert__char_rep__Reply__exception_raise_state_identity_t__new_state__defined
#define __NDR_convert__char_rep__Reply__exception_raise_state_identity_t__new_state(a, f, c) \
__NDR_convert__ARRAY((natural_t *)(a), f, c, __NDR_convert__char_rep__exc__natural_t)
#elif defined(__NDR_convert__char_rep__natural_t__defined)
#define __NDR_convert__char_rep__Reply__exception_raise_state_identity_t__new_state__defined
#define __NDR_convert__char_rep__Reply__exception_raise_state_identity_t__new_state(a, f, c) \
__NDR_convert__ARRAY((natural_t *)(a), f, c, __NDR_convert__char_rep__natural_t)
#elif defined(__NDR_convert__char_rep__exc__uint32_t__defined)
#define __NDR_convert__char_rep__Reply__exception_raise_state_identity_t__new_state__defined
#define __NDR_convert__char_rep__Reply__exception_raise_state_identity_t__new_state(a, f, c) \
__NDR_convert__ARRAY((uint32_t *)(a), f, c, __NDR_convert__char_rep__exc__uint32_t)
#elif defined(__NDR_convert__char_rep__uint32_t__defined)
#define __NDR_convert__char_rep__Reply__exception_raise_state_identity_t__new_state__defined
#define __NDR_convert__char_rep__Reply__exception_raise_state_identity_t__new_state(a, f, c) \
__NDR_convert__ARRAY((uint32_t *)(a), f, c, __NDR_convert__char_rep__uint32_t)
#endif /* defined(__NDR_convert__*__defined) */
#endif /* __NDR_convert__char_rep__Reply__exception_raise_state_identity_t__new_state__defined */
#ifndef __NDR_convert__float_rep__Reply__exception_raise_state_identity_t__flavor__defined
#if defined(__NDR_convert__float_rep__exc__int__defined)
#define __NDR_convert__float_rep__Reply__exception_raise_state_identity_t__flavor__defined
#define __NDR_convert__float_rep__Reply__exception_raise_state_identity_t__flavor(a, f) \
__NDR_convert__float_rep__exc__int((int *)(a), f)
#elif defined(__NDR_convert__float_rep__int__defined)
#define __NDR_convert__float_rep__Reply__exception_raise_state_identity_t__flavor__defined
#define __NDR_convert__float_rep__Reply__exception_raise_state_identity_t__flavor(a, f) \
__NDR_convert__float_rep__int((int *)(a), f)
#elif defined(__NDR_convert__float_rep__exc__int32_t__defined)
#define __NDR_convert__float_rep__Reply__exception_raise_state_identity_t__flavor__defined
#define __NDR_convert__float_rep__Reply__exception_raise_state_identity_t__flavor(a, f) \
__NDR_convert__float_rep__exc__int32_t((int32_t *)(a), f)
#elif defined(__NDR_convert__float_rep__int32_t__defined)
#define __NDR_convert__float_rep__Reply__exception_raise_state_identity_t__flavor__defined
#define __NDR_convert__float_rep__Reply__exception_raise_state_identity_t__flavor(a, f) \
__NDR_convert__float_rep__int32_t((int32_t *)(a), f)
#endif /* defined(__NDR_convert__*__defined) */
#endif /* __NDR_convert__float_rep__Reply__exception_raise_state_identity_t__flavor__defined */
#ifndef __NDR_convert__float_rep__Reply__exception_raise_state_identity_t__new_state__defined
#if defined(__NDR_convert__float_rep__exc__thread_state_t__defined)
#define __NDR_convert__float_rep__Reply__exception_raise_state_identity_t__new_state__defined
#define __NDR_convert__float_rep__Reply__exception_raise_state_identity_t__new_state(a, f, c) \
__NDR_convert__float_rep__exc__thread_state_t((thread_state_t *)(a), f, c)
#elif defined(__NDR_convert__float_rep__thread_state_t__defined)
#define __NDR_convert__float_rep__Reply__exception_raise_state_identity_t__new_state__defined
#define __NDR_convert__float_rep__Reply__exception_raise_state_identity_t__new_state(a, f, c) \
__NDR_convert__float_rep__thread_state_t((thread_state_t *)(a), f, c)
#elif defined(__NDR_convert__float_rep__exc__natural_t__defined)
#define __NDR_convert__float_rep__Reply__exception_raise_state_identity_t__new_state__defined
#define __NDR_convert__float_rep__Reply__exception_raise_state_identity_t__new_state(a, f, c) \
__NDR_convert__ARRAY((natural_t *)(a), f, c, __NDR_convert__float_rep__exc__natural_t)
#elif defined(__NDR_convert__float_rep__natural_t__defined)
#define __NDR_convert__float_rep__Reply__exception_raise_state_identity_t__new_state__defined
#define __NDR_convert__float_rep__Reply__exception_raise_state_identity_t__new_state(a, f, c) \
__NDR_convert__ARRAY((natural_t *)(a), f, c, __NDR_convert__float_rep__natural_t)
#elif defined(__NDR_convert__float_rep__exc__uint32_t__defined)
#define __NDR_convert__float_rep__Reply__exception_raise_state_identity_t__new_state__defined
#define __NDR_convert__float_rep__Reply__exception_raise_state_identity_t__new_state(a, f, c) \
__NDR_convert__ARRAY((uint32_t *)(a), f, c, __NDR_convert__float_rep__exc__uint32_t)
#elif defined(__NDR_convert__float_rep__uint32_t__defined)
#define __NDR_convert__float_rep__Reply__exception_raise_state_identity_t__new_state__defined
#define __NDR_convert__float_rep__Reply__exception_raise_state_identity_t__new_state(a, f, c) \
__NDR_convert__ARRAY((uint32_t *)(a), f, c, __NDR_convert__float_rep__uint32_t)
#endif /* defined(__NDR_convert__*__defined) */
#endif /* __NDR_convert__float_rep__Reply__exception_raise_state_identity_t__new_state__defined */
mig_internal kern_return_t __MIG_check__Reply__exception_raise_state_identity_t(__Reply__exception_raise_state_identity_t *Out0P)
{
typedef __Reply__exception_raise_state_identity_t __Reply;
#if __MigTypeCheck
unsigned int msgh_size;
#endif /* __MigTypeCheck */
if (Out0P->Head.msgh_id != 2503) {
if (Out0P->Head.msgh_id == MACH_NOTIFY_SEND_ONCE)
{ return MIG_SERVER_DIED; }
else
{ return MIG_REPLY_MISMATCH; }
}
#if __MigTypeCheck
msgh_size = Out0P->Head.msgh_size;
if ((Out0P->Head.msgh_bits & MACH_MSGH_BITS_COMPLEX) ||
((msgh_size > (mach_msg_size_t)sizeof(__Reply) || msgh_size < (mach_msg_size_t)(sizeof(__Reply) - 576)) &&
(msgh_size != (mach_msg_size_t)sizeof(mig_reply_error_t) ||
Out0P->RetCode == KERN_SUCCESS)))
{ return MIG_TYPE_ERROR ; }
#endif /* __MigTypeCheck */
if (Out0P->RetCode != KERN_SUCCESS) {
#ifdef __NDR_convert__mig_reply_error_t__defined
__NDR_convert__mig_reply_error_t((mig_reply_error_t *)Out0P);
#endif /* __NDR_convert__mig_reply_error_t__defined */
return ((mig_reply_error_t *)Out0P)->RetCode;
}
#if defined(__NDR_convert__int_rep__Reply__exception_raise_state_identity_t__new_stateCnt__defined)
if (Out0P->NDR.int_rep != NDR_record.int_rep)
__NDR_convert__int_rep__Reply__exception_raise_state_identity_t__new_stateCnt(&Out0P->new_stateCnt, Out0P->NDR.int_rep);
#endif /* __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__new_stateCnt__defined */
#if __MigTypeCheck
if (msgh_size != (mach_msg_size_t)(sizeof(__Reply) - 576) + ((4 * Out0P->new_stateCnt)))
{ return MIG_TYPE_ERROR ; }
#endif /* __MigTypeCheck */
#if defined(__NDR_convert__int_rep__Reply__exception_raise_state_identity_t__RetCode__defined) || \
defined(__NDR_convert__int_rep__Reply__exception_raise_state_identity_t__flavor__defined) || \
defined(__NDR_convert__int_rep__Reply__exception_raise_state_identity_t__new_state__defined) || \
defined(__NDR_convert__int_rep__Reply__exception_raise_state_identity_t__new_stateCnt__defined)
if (Out0P->NDR.int_rep != NDR_record.int_rep) {
#if defined(__NDR_convert__int_rep__Reply__exception_raise_state_identity_t__RetCode__defined)
__NDR_convert__int_rep__Reply__exception_raise_state_identity_t__RetCode(&Out0P->RetCode, Out0P->NDR.int_rep);
#endif /* __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__RetCode__defined */
#if defined(__NDR_convert__int_rep__Reply__exception_raise_state_identity_t__flavor__defined)
__NDR_convert__int_rep__Reply__exception_raise_state_identity_t__flavor(&Out0P->flavor, Out0P->NDR.int_rep);
#endif /* __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__flavor__defined */
#if defined(__NDR_convert__int_rep__Reply__exception_raise_state_identity_t__new_state__defined)
__NDR_convert__int_rep__Reply__exception_raise_state_identity_t__new_state(&Out0P->new_state, Out0P->NDR.int_rep, Out0P->new_stateCnt);
#endif /* __NDR_convert__int_rep__Reply__exception_raise_state_identity_t__new_state__defined */
}
#endif /* defined(__NDR_convert__int_rep...) */
#if 0 || \
defined(__NDR_convert__char_rep__Reply__exception_raise_state_identity_t__flavor__defined) || \
defined(__NDR_convert__char_rep__Reply__exception_raise_state_identity_t__new_state__defined) || \
0
if (Out0P->NDR.char_rep != NDR_record.char_rep) {
#if defined(__NDR_convert__char_rep__Reply__exception_raise_state_identity_t__flavor__defined)
__NDR_convert__char_rep__Reply__exception_raise_state_identity_t__flavor(&Out0P->flavor, Out0P->NDR.char_rep);
#endif /* __NDR_convert__char_rep__Reply__exception_raise_state_identity_t__flavor__defined */
#if defined(__NDR_convert__char_rep__Reply__exception_raise_state_identity_t__new_state__defined)
__NDR_convert__char_rep__Reply__exception_raise_state_identity_t__new_state(&Out0P->new_state, Out0P->NDR.char_rep, Out0P->new_stateCnt);
#endif /* __NDR_convert__char_rep__Reply__exception_raise_state_identity_t__new_state__defined */
}
#endif /* defined(__NDR_convert__char_rep...) */
#if 0 || \
defined(__NDR_convert__float_rep__Reply__exception_raise_state_identity_t__flavor__defined) || \
defined(__NDR_convert__float_rep__Reply__exception_raise_state_identity_t__new_state__defined) || \
0
if (Out0P->NDR.float_rep != NDR_record.float_rep) {
#if defined(__NDR_convert__float_rep__Reply__exception_raise_state_identity_t__flavor__defined)
__NDR_convert__float_rep__Reply__exception_raise_state_identity_t__flavor(&Out0P->flavor, Out0P->NDR.float_rep);
#endif /* __NDR_convert__float_rep__Reply__exception_raise_state_identity_t__flavor__defined */
#if defined(__NDR_convert__float_rep__Reply__exception_raise_state_identity_t__new_state__defined)
__NDR_convert__float_rep__Reply__exception_raise_state_identity_t__new_state(&Out0P->new_state, Out0P->NDR.float_rep, Out0P->new_stateCnt);
#endif /* __NDR_convert__float_rep__Reply__exception_raise_state_identity_t__new_state__defined */
}
#endif /* defined(__NDR_convert__float_rep...) */
return MACH_MSG_SUCCESS;
}
#endif /* !defined(__MIG_check__Reply__exception_raise_state_identity_t__defined) */
#endif /* __MIG_check__Reply__exc_subsystem__ */
#endif /* ( __MigTypeCheck || __NDR_convert__ ) */
/* Routine exception_raise_state_identity */
mig_external kern_return_t exception_raise_state_identity
(
mach_port_t exception_port,
mach_port_t thread,
mach_port_t task,
exception_type_t exception,
exception_data_t code,
mach_msg_type_number_t codeCnt,
int *flavor,
thread_state_t old_state,
mach_msg_type_number_t old_stateCnt,
thread_state_t new_state,
mach_msg_type_number_t *new_stateCnt
)
{
#ifdef __MigPackStructs
#pragma pack(4)
#endif
typedef struct {
mach_msg_header_t Head;
/* start of the kernel processed data */
mach_msg_body_t msgh_body;
mach_msg_port_descriptor_t thread;
mach_msg_port_descriptor_t task;
/* end of the kernel processed data */
NDR_record_t NDR;
exception_type_t exception;
mach_msg_type_number_t codeCnt;
integer_t code[2];
int flavor;
mach_msg_type_number_t old_stateCnt;
natural_t old_state[144];
} Request;
#ifdef __MigPackStructs
#pragma pack()
#endif
#ifdef __MigPackStructs
#pragma pack(4)
#endif
typedef struct {
mach_msg_header_t Head;
NDR_record_t NDR;
kern_return_t RetCode;
int flavor;
mach_msg_type_number_t new_stateCnt;
natural_t new_state[144];
mach_msg_trailer_t trailer;
} Reply;
#ifdef __MigPackStructs
#pragma pack()
#endif
#ifdef __MigPackStructs
#pragma pack(4)
#endif
typedef struct {
mach_msg_header_t Head;
NDR_record_t NDR;
kern_return_t RetCode;
int flavor;
mach_msg_type_number_t new_stateCnt;
natural_t new_state[144];
} __Reply;
#ifdef __MigPackStructs
#pragma pack()
#endif
/*
* typedef struct {
* mach_msg_header_t Head;
* NDR_record_t NDR;
* kern_return_t RetCode;
* } mig_reply_error_t;
*/
union {
Request In;
Reply Out;
} Mess;
Request *InP = &Mess.In;
Reply *Out0P = &Mess.Out;
mach_msg_return_t msg_result;
unsigned int msgh_size;
unsigned int msgh_size_delta;
#ifdef __MIG_check__Reply__exception_raise_state_identity_t__defined
kern_return_t check_result;
#endif /* __MIG_check__Reply__exception_raise_state_identity_t__defined */
__DeclareSendRpc(2403, "exception_raise_state_identity")
#if UseStaticTemplates
const static mach_msg_port_descriptor_t threadTemplate = {
/* name = */ MACH_PORT_NULL,
/* pad1 = */ 0,
/* pad2 = */ 0,
/* disp = */ 19,
/* type = */ MACH_MSG_PORT_DESCRIPTOR,
};
#endif /* UseStaticTemplates */
#if UseStaticTemplates
const static mach_msg_port_descriptor_t taskTemplate = {
/* name = */ MACH_PORT_NULL,
/* pad1 = */ 0,
/* pad2 = */ 0,
/* disp = */ 19,
/* type = */ MACH_MSG_PORT_DESCRIPTOR,
};
#endif /* UseStaticTemplates */
InP->msgh_body.msgh_descriptor_count = 2;
#if UseStaticTemplates
InP->thread = threadTemplate;
InP->thread.name = thread;
#else /* UseStaticTemplates */
InP->thread.name = thread;
InP->thread.disposition = 19;
InP->thread.type = MACH_MSG_PORT_DESCRIPTOR;
#endif /* UseStaticTemplates */
#if UseStaticTemplates
InP->task = taskTemplate;
InP->task.name = task;
#else /* UseStaticTemplates */
InP->task.name = task;
InP->task.disposition = 19;
InP->task.type = MACH_MSG_PORT_DESCRIPTOR;
#endif /* UseStaticTemplates */
InP->NDR = NDR_record;
InP->exception = exception;
if (codeCnt > 2) {
{ return MIG_ARRAY_TOO_LARGE; }
}
(void)memcpy((char *) InP->code, (const char *) code, 4 * codeCnt);
InP->codeCnt = codeCnt;
msgh_size_delta = (4 * codeCnt);
msgh_size = (mach_msg_size_t)(sizeof(Request) - 584) + msgh_size_delta;
InP = (Request *) ((pointer_t) InP + msgh_size_delta - 8);
InP->flavor = *flavor;
if (old_stateCnt > 144) {
{ return MIG_ARRAY_TOO_LARGE; }
}
(void)memcpy((char *) InP->old_state, (const char *) old_state, 4 * old_stateCnt);
InP->old_stateCnt = old_stateCnt;
msgh_size += (4 * old_stateCnt);
InP = &Mess.In;
InP->Head.msgh_bits = MACH_MSGH_BITS_COMPLEX|
MACH_MSGH_BITS(19, MACH_MSG_TYPE_MAKE_SEND_ONCE);
/* msgh_size passed as argument */
InP->Head.msgh_request_port = exception_port;
InP->Head.msgh_reply_port = mig_get_reply_port();
InP->Head.msgh_id = 2403;
__BeforeSendRpc(2403, "exception_raise_state_identity")
msg_result = mach_msg(&InP->Head, MACH_SEND_MSG|MACH_RCV_MSG|MACH_MSG_OPTION_NONE, msgh_size, (mach_msg_size_t)sizeof(Reply), InP->Head.msgh_reply_port, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
__AfterSendRpc(2403, "exception_raise_state_identity")
if (msg_result != MACH_MSG_SUCCESS) {
__MachMsgErrorWithoutTimeout(msg_result);
{ return msg_result; }
}
#if defined(__MIG_check__Reply__exception_raise_state_identity_t__defined)
check_result = __MIG_check__Reply__exception_raise_state_identity_t((__Reply__exception_raise_state_identity_t *)Out0P);
if (check_result != MACH_MSG_SUCCESS)
{ return check_result; }
#endif /* defined(__MIG_check__Reply__exception_raise_state_identity_t__defined) */
*flavor = Out0P->flavor;
if (Out0P->new_stateCnt > 144) {
(void)memcpy((char *) new_state, (const char *) Out0P->new_state, 4 * 144);
*new_stateCnt = Out0P->new_stateCnt;
{ return MIG_ARRAY_TOO_LARGE; }
}
(void)memcpy((char *) new_state, (const char *) Out0P->new_state, 4 * Out0P->new_stateCnt);
*new_stateCnt = Out0P->new_stateCnt;
return KERN_SUCCESS;
}
|
9b941917792759c132601ac5536afb1e187bfe4e
|
b04663400b05fd638e41f3d7f61953c514d835ed
|
/inc/link_log.h
|
7006e170152a7b535e29dab947a8a321318152c1
|
[
"BSD-3-Clause"
] |
permissive
|
LiteOS/LiteOS_Lab
|
0ee3edc08eb9d4c9ea5b52099da307adf1c06bfd
|
187e628b3f151515d920801b402bf38a19eee98c
|
refs/heads/iot-device-sdk-tiny
| 2023-09-04T16:22:21.579294
| 2023-04-25T03:09:46
| 2023-04-25T03:09:46
| 154,946,914
| 141
| 125
|
BSD-3-Clause
| 2022-08-25T09:12:56
| 2018-10-27T09:25:01
|
C
|
UTF-8
|
C
| false
| false
| 5,885
|
h
|
link_log.h
|
/*----------------------------------------------------------------------------
* Copyright (c) <2018>, <Huawei Technologies Co., Ltd>
* All rights reserved.
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior written
* permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*---------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
* Notice of Export Control Law
* ===============================================
* Huawei LiteOS may be subject to applicable export control laws and regulations, which might
* include those applicable to Huawei LiteOS of U.S. and the country in which you are located.
* Import, export and usage of Huawei LiteOS in any manner by you shall be in compliance with such
* applicable export control laws and regulations.
*---------------------------------------------------------------------------*/
#ifndef LITEOS_LAB_IOT_LINK_LINK_LOG_LINK_LOG_H_
#define LITEOS_LAB_IOT_LINK_LINK_LOG_LINK_LOG_H_
#include <stdarg.h>
#include <stdint.h>
#include <stddef.h>
#include <stdio.h>
#include "iot_link_config.h"
/**
* @brief:this defines for the log module, and LINK_LOG_TRACE/LINK_LOG_DEBUG will not participate the compile in the release version
*
*
* */
typedef enum
{
EN_LINK_LOG_LEVEL_TRACE = 0, ///< this is used as the trace function,like the function enter and function out
EN_LINK_LOG_LEVEL_DEBUG, ///< this is used as the debug, you could add any debug as you wish
EN_LINK_LOG_LEVEL_INFO, ///< which means it is import message, and you should known
EN_LINK_LOG_LEVEL_WARN, ///< this is used as the executed result,which means the status is not what we expected,but could accept
EN_LINK_LOG_LEVEL_ERROR, ///< this is used as the executed result,which means the status is not what we expected,could not accepta
EN_LINK_LOG_LEVEL_FATAL, ///< this is used as the parameters input for the api interface, which could not accepted
EN_LINK_LOG_LEVEL_MAX,
}en_link_log_level_t;
/**
* @brief:use this function to get the current output log
*
* @return: the current output mask log, defined by en_link_log_level_t
* */
en_link_log_level_t link_log_level_get(void);
/**
* @brief: use this function to get the debug level name
*
* @parameter[in]:level, the level to get
*
* @return: the mapped level name
* */
const char *link_log_level_name(en_link_log_level_t level);
/**
* @brief:use this function to set the current output log
*
*@parameter[in] level:defined by en_link_log_level_t
*
* @return: 0 success while -1 failed
* */
int link_log_level_set(en_link_log_level_t level);
/*
* @brief: this is a weak function ,and you could rewrite one
*
* @param fmt: same use as the fmt for printf
*
* @param unfixed: same use for printf
*
* @return: don't care about it
*
* @attention: and the components should not call this function directly, you'd better
*
* call LINK_LOG groups
*
* */
//__attribute__((weak)) void link_printf(const char *format, ...);
#ifndef link_printf
#define link_printf(fmt, ...) \
do \
{ \
printf(fmt, ##__VA_ARGS__); \
fflush(stdout); \
}while(0)
#endif
#ifdef CONFIG_LINKLOG_ENABLE
extern unsigned long long osal_sys_time(void);
#define LINK_LOG(level,fmt, ...) \
do \
{ \
link_printf("[%s][%u][%s] " fmt "\r\n", \
link_log_level_name((level)), (unsigned int)osal_sys_time(),__FUNCTION__, ##__VA_ARGS__); \
} while (0)
#define LINK_LOG_TRACE(fmt, ...) \
do \
{ \
if ((EN_LINK_LOG_LEVEL_TRACE) >= link_log_level_get()) \
{ \
LINK_LOG(EN_LINK_LOG_LEVEL_TRACE,fmt,##__VA_ARGS__); \
} \
} while (0)
#define LINK_LOG_DEBUG(fmt, ...) \
do \
{ \
if ((EN_LINK_LOG_LEVEL_DEBUG) >= link_log_level_get()) \
{ \
LINK_LOG(EN_LINK_LOG_LEVEL_DEBUG,fmt,##__VA_ARGS__); \
} \
} while (0)
#else
#define LINK_LOG(level,fmt, ...)
#define LINK_LOG_TRACE(fmt, ...)
#define LINK_LOG_DEBUG(fmt, ...)
#endif
#define LINK_LOG_INFO(fmt, ...) LINK_LOG(EN_LINK_LOG_LEVEL_INFO,fmt,##__VA_ARGS__)
#define LINK_LOG_WARN(fmt, ...) LINK_LOG(EN_LINK_LOG_LEVEL_WARN,fmt,##__VA_ARGS__)
#define LINK_LOG_ERROR(fmt, ...) LINK_LOG(EN_LINK_LOG_LEVEL_ERROR,fmt,##__VA_ARGS__)
#define LINK_LOG_FATAL(fmt, ...) LINK_LOG(EN_LINK_LOG_LEVEL_FATAL,fmt,##__VA_ARGS__)
#endif /* LITEOS_LAB_IOT_LINK_LINK_LOG_LINK_LOG_H_ */
|
734d49c48853b16e9773622db63a126812043b81
|
62bf09400de89c1aa77d8c2570d7f66cec0b5d36
|
/third_party/qca-3.3.5/common_src/api_interface/api_ioctl.c
|
34d5381d56c86cb52106d4a9601c9f57b276211c
|
[
"Apache-2.0"
] |
permissive
|
butok/FNET
|
41b1d2ec4cc683c1b5c188a17ab6a4bb890a6af6
|
ea43715752e6f6823bfcc8bdc94e440443112e7c
|
refs/heads/master
| 2023-08-03T16:32:09.317085
| 2023-07-20T07:01:55
| 2023-07-20T07:01:55
| 50,664,554
| 115
| 40
|
Apache-2.0
| 2023-07-20T07:01:56
| 2016-01-29T13:39:30
|
C
|
WINDOWS-1252
|
C
| false
| false
| 40,498
|
c
|
api_ioctl.c
|
//------------------------------------------------------------------------------
// Copyright (c) Qualcomm Atheros, Inc.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without modification, are permitted (subject to
// the limitations in the disclaimer below) provided that the following conditions are met:
//
// · Redistributions of source code must retain the above copyright notice, this list of conditions and the
// following disclaimer.
// · Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
// · Neither the name of nor the names of its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. 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.
//------------------------------------------------------------------------------
//==============================================================================
// Author(s): ="Atheros"
//==============================================================================
#include <wifi_common.h>
#include <a_types.h>
#include <a_osapi.h>
#include <driver_cxt.h>
#include <custom_wlan_api.h>
#include <hcd_api.h>
#include <common_api.h>
#include <wmi_api.h>
#include <wmi_host.h>
#include <wlan_api.h>
#include <targaddrs.h>
#include <spi_hcd_if.h>
#include "hw20_mbox_host_reg.h"
#include <atheros_wifi_api.h>
#include "hw20_apb_map.h"
#include "hw20_mbox_reg.h"
extern const WMI_SCAN_PARAMS_CMD default_scan_param;
uint8_t countryCode_storge[4];
A_STATUS
Program_CountryCode(void *pCxt)
{
A_DRIVER_CONTEXT *pDCxt;
A_STATUS status = A_ERROR;
uint32_t param;
uint8_t pass_cycle = 0;
A_NETBUF_DECLARE req;
void *pReq = (void *)&req;
uint32_t country_code_word;
uint8_t *ptr_country_code = (uint8_t *)&country_code_word;
uint32_t i;
A_NETBUF_CONFIGURE(pReq, &country_code_word, 0, sizeof(uint32_t), sizeof(uint32_t));
pDCxt = GET_DRIVER_COMMON(pCxt);
do
{
/* bring the chip down */
pDCxt->wmiReady = false;
HW_PowerUpDown(pCxt, false);
/* bring the chip back up */
HW_PowerUpDown(pCxt, true);
pDCxt->htc_creditInit = 0;
/* re-initialize host controller (sub-)driver = HCD */
if ((status = Hcd_ReinitTarget(pCxt)) != A_OK)
{
A_ASSERT(0);
}
if (pass_cycle == 0)
{
A_MDELAY(5);
/* wait for chip to reach point in initialization */
do
{
if (Driver_ReadDataDiag(pCxt, TARG_VTOP(HOST_INTEREST_ITEM_ADDRESS(hi_refclk_hz)), (uint8_t *)¶m,
4) != A_OK)
{
A_ASSERT(0);
}
} while (param != A_CPU2LE32(EXPECTED_REF_CLK_AR4100) && param != A_CPU2LE32(EXPECTED_REF_CLK_AR400X));
/* on 1st pass the mac address is loaded into the
* scratch registers and the parameter is set to
* cause the firmware to read/program the mac address.
*/
ptr_country_code[0] = 0;
// the first byte is used to store the result, the rest three bytes are used to store countrycode
A_MEMCPY(&ptr_country_code[1], &countryCode_storge[1], 3);
QCADRV_PRINTF("ptr_country_code is %c, %c.\n", ptr_country_code[1], ptr_country_code[2]);
// ATH_SET_PIO_EXTERNAL_WRITE_OPERATION(pReq, SCRATCH_ADDRESS, true, sizeof(uint32_t));
ATH_SET_PIO_EXTERNAL_WRITE_OPERATION(pReq, SCRATCH_ADDRESS, true, sizeof(uint32_t));
if (A_OK != (status = Hcd_DoPioExternalAccess(pCxt, pReq)))
{
A_ASSERT(0);
}
#if 0
A_MEMCPY(&ptr_country_code[0], &pDCxt->conn[pDCxt->devId].reqBssid[2], 4);
ATH_SET_PIO_EXTERNAL_WRITE_OPERATION(pReq, SCRATCH_ADDRESS+4, true, sizeof(uint32_t));
if(A_OK != (status = Hcd_DoPioExternalAccess(pCxt, pReq))){
A_ASSERT(0);
}
#endif
A_MDELAY(5);
param = A_CPU2LE32(AR4XXX_PARAM_COUNTRY_CODE_MODE);
if (Driver_WriteDataDiag(pCxt, TARG_VTOP(HOST_INTEREST_ITEM_ADDRESS(hi_flash_is_present)),
(uint8_t *)¶m, 4) != A_OK)
{
A_ASSERT(0);
}
/* wait some sufficient number of attempts before giving up. */
for (i = 0; i < 100; i++)
{
/* poll scratch register for indication of completion */
A_MDELAY(1); // delay 1 ms to make target execute the setting of countrycode
ATH_SET_PIO_EXTERNAL_READ_OPERATION(pReq, SCRATCH_ADDRESS, true, sizeof(uint32_t));
if (A_OK != (status = Hcd_DoPioExternalAccess(pCxt, pReq)))
{
A_ASSERT(0);
}
// result from target is stored in ptr_country_code
if ((ptr_country_code[0] != 0))
{
QCADRV_PRINTF("ptr_country_code break;.\n");
break; /* done - exit loop */
}
}
}
else
{
/* on 2nd pass the chip is brought up normally */
A_MDELAY(5);
Driver_BootComm(pCxt);
pDCxt->chipDown = false;
}
pass_cycle++;
} while (pass_cycle < 2);
if (pass_cycle >= 2)
{
/* store result in reqBssid for use in calling function */
countryCode_storge[0] = ptr_country_code[0];
}
else
{
countryCode_storge[0] = 0;
}
QCADRV_PRINTF("target result is %c,%d.\n", ptr_country_code[0], ptr_country_code[0]);
status = A_OK;
pDCxt->asynchRequest = NULL;
// pDCxt->macProgramming = false;
DRIVER_WAKE_USER(pCxt);
return status;
}
A_STATUS
Api_ProgramCountryCode(void *pCxt, uint8_t *country_code, uint16_t length, uint8_t *pResult)
{
A_STATUS status = A_ERROR;
A_DRIVER_CONTEXT *pDCxt = GET_DRIVER_COMMON(pCxt);
boolean countryCodeProgram = true;
/* init pResult to an error code of 0 */
*pResult = ATH_PROGRAM_COUNTRY_CODE_RESULT_DRIVER_FAILED;
do
{
if (length != sizeof(ATH_PROGRAM_COUNTRY_CODE_PARAM))
{
break;
}
if (Api_DriverAccessCheck(pCxt, 0, ACCESS_REQUEST_IOCTL) != A_OK)
{
break;
}
if (pDCxt->asynchRequest != NULL)
{
break;
}
/* use the reqBssid as storage for the country code. the Program_CountryCode
* function will retrieve this value for use in the operation.
*/
// A_MEMCPY(pDCxt->conn[pDCxt->devId].reqBssid, country_code, 3);
A_MEMCPY(&countryCode_storge[1], country_code, 3);
QCADRV_PRINTF("api_ioctl countryCode_storge is %c,%c.\n", countryCode_storge[1], countryCode_storge[2]);
pDCxt->asynchRequest = Program_CountryCode;
DRIVER_WAKE_DRIVER(pCxt);
DRIVER_WAIT_FOR_CONDITION(pCxt, &countryCodeProgram, false, 5000);
switch (countryCode_storge[0])
{
case 1: /*successful result*/
*pResult = ATH_PROGRAM_COUNTRY_CODE_RESULT_SUCCESS;
break;
case 2: /* device failed in the attempt */
*pResult = ATH_PROGRAM_COUNTRY_CODE_RESULT_DEV_DENIED;
break;
case 4: /* the same country is already programmed */
case 8: /* the device rejected the mac address */
*pResult = ATH_PROGRAM_COUNTRY_CODE_RESULT_DEV_FAILED;
break;
case 0: /* driver failure to communicate with device */
default:
break;
}
Api_InitFinish(pCxt);
Api_WMIInitFinish(pCxt);
status = A_OK;
} while (0);
A_MEMZERO(pDCxt->conn[pDCxt->devId].reqBssid, sizeof(pDCxt->conn[pDCxt->devId].reqBssid));
return status;
}
#if DRIVER_CONFIG_PROGRAM_MAC_ADDR
/*****************************************************************************/
/* program_mac_addr - Used to program a new mac address into the attached
* wifi device. the mac address is in pDCxt->reqBssid. Special firmware
* is loaded to perform the operation. the MAC address is provided to
* the firmware through the MBOX scratch registers.
* void *pCxt - the driver context.
*****************************************************************************/
static A_STATUS program_mac_addr(void *pCxt)
{
A_DRIVER_CONTEXT *pDCxt;
A_STATUS status = A_ERROR;
uint32_t param;
uint8_t pass_cycle = 0;
A_NETBUF_DECLARE req;
void *pReq = (void *)&req;
uint32_t mac_word;
uint8_t *ptr_mac_word = (uint8_t *)&mac_word;
uint32_t i;
A_NETBUF_CONFIGURE(pReq, &mac_word, 0, sizeof(uint32_t), sizeof(uint32_t));
pDCxt = GET_DRIVER_COMMON(pCxt);
do
{
/* bring the chip down */
pDCxt->wmiReady = false;
HW_PowerUpDown(pCxt, false);
/* bring the chip back up */
HW_PowerUpDown(pCxt, true);
pDCxt->htc_creditInit = 0;
/* re-initialize host controller (sub-)driver = HCD */
if ((status = Hcd_ReinitTarget(pCxt)) != A_OK)
{
A_ASSERT(0);
}
if (pass_cycle == 0)
{
A_MDELAY(5);
/* wait for chip to reach point in initialization */
do
{
if (Driver_ReadDataDiag(pCxt, TARG_VTOP(HOST_INTEREST_ITEM_ADDRESS(hi_refclk_hz)), (uint8_t *)¶m,
4) != A_OK)
{
A_ASSERT(0);
}
} while (param != A_CPU2LE32(EXPECTED_REF_CLK_AR4100) && param != A_CPU2LE32(EXPECTED_REF_CLK_AR400X));
/* on 1st pass the mac address is loaded into the
* scratch registers and the parameter is set to
* cause the firmware to read/program the mac address.
*/
ptr_mac_word[0] = 0;
ptr_mac_word[1] = 0;
A_MEMCPY(&ptr_mac_word[2], &pDCxt->conn[pDCxt->devId].reqBssid[0], 2);
ATH_SET_PIO_EXTERNAL_WRITE_OPERATION(pReq, SCRATCH_ADDRESS, true, sizeof(uint32_t));
if (A_OK != (status = Hcd_DoPioExternalAccess(pCxt, pReq)))
{
A_ASSERT(0);
}
A_MEMCPY(&ptr_mac_word[0], &pDCxt->conn[pDCxt->devId].reqBssid[2], 4);
ATH_SET_PIO_EXTERNAL_WRITE_OPERATION(pReq, SCRATCH_ADDRESS + 4, true, sizeof(uint32_t));
if (A_OK != (status = Hcd_DoPioExternalAccess(pCxt, pReq)))
{
A_ASSERT(0);
}
A_MDELAY(5);
param = A_CPU2LE32(AR4XXX_PARAM_MACPROG_MODE);
if (Driver_WriteDataDiag(pCxt, TARG_VTOP(HOST_INTEREST_ITEM_ADDRESS(hi_flash_is_present)),
(uint8_t *)¶m, 4) != A_OK)
{
A_ASSERT(0);
}
/* wait some sufficient number of attempts before giving up. */
for (i = 0; i < 100; i++)
{
/* poll scratch register for indication of completion */
ATH_SET_PIO_EXTERNAL_READ_OPERATION(pReq, SCRATCH_ADDRESS, true, sizeof(uint32_t));
if (A_OK != (status = Hcd_DoPioExternalAccess(pCxt, pReq)))
{
A_ASSERT(0);
}
QCADRV_PRINTF("ptr_mac_word[1] is %c.\n", ptr_mac_word[1]);
if (ptr_mac_word[1] != 0)
{
break; /* done - exit loop */
}
/* delay 1 msec before polling again to give the op time to complete */
A_MDELAY(1);
}
}
else
{
/* on 2nd pass the chip is brought up normally */
A_MDELAY(5);
Driver_BootComm(pCxt);
pDCxt->chipDown = false;
}
pass_cycle++;
} while (pass_cycle < 2);
if (pass_cycle >= 2)
{
/* store result in reqBssid for use in calling function */
pDCxt->conn[pDCxt->devId].reqBssid[0] = ptr_mac_word[1];
}
else
{
pDCxt->conn[pDCxt->devId].reqBssid[0] = 0;
}
status = A_OK;
pDCxt->asynchRequest = NULL;
pDCxt->macProgramming = false;
DRIVER_WAKE_USER(pCxt);
return status;
}
#endif /* DRIVER_CONFIG_PROGRAM_MAC_ADDR */
/*****************************************************************************/
/* Install_static_wep_keys - Used to install WEP keys to the device at the
* appropriate time.
* void *pCxt - the driver context.
*****************************************************************************/
static void Install_static_wep_keys(void *pCxt)
{
uint8_t index;
uint8_t keyUsage;
A_DRIVER_CONTEXT *pDCxt;
WMI_ADD_CIPHER_KEY_CMD add_key_param;
pDCxt = GET_DRIVER_COMMON(pCxt);
for (index = WMI_MIN_KEY_INDEX; index <= WMI_MAX_KEY_INDEX; index++)
{
if (pDCxt->conn[pDCxt->devId].wepKeyList[index].keyLen)
{
keyUsage = GROUP_USAGE;
if (index == pDCxt->conn[pDCxt->devId].wepDefTxKeyIndex)
{
keyUsage |= TX_USAGE;
}
A_MEMZERO(&add_key_param, sizeof(add_key_param));
add_key_param.keyIndex = index;
add_key_param.keyType = WEP_CRYPT;
add_key_param.keyUsage = keyUsage;
add_key_param.keyLength = pDCxt->conn[pDCxt->devId].wepKeyList[index].keyLen;
A_MEMCPY(&add_key_param.key, pDCxt->conn[pDCxt->devId].wepKeyList[index].key, add_key_param.keyLength);
add_key_param.key_op_ctrl = KEY_OP_INIT_VAL;
wmi_cmd_start(pDCxt->pWmiCxt, &add_key_param, WMI_ADD_CIPHER_KEY_CMDID, sizeof(WMI_ADD_CIPHER_KEY_CMD));
}
}
}
/*****************************************************************************/
/* Api_DisconnectWiFi - Called by upper layer to disconnect a network
* connection. Executes wmi_Disconnnect_cmd
* void *pCxt - the driver context.
*****************************************************************************/
A_STATUS
Api_DisconnectWiFi(void *pCxt)
{
A_DRIVER_CONTEXT *pDCxt;
pDCxt = GET_DRIVER_COMMON(pCxt);
if ((pDCxt->conn[pDCxt->devId].isConnected == true) || (pDCxt->conn[pDCxt->devId].isConnectPending == true))
{
wmi_cmd_start(pDCxt->pWmiCxt, NULL, WMI_DISCONNECT_CMDID, 0);
/*
* Disconnect cmd is issued, clear connectPending.
* arConnected will be cleard in disconnect_event notification.
*/
pDCxt->conn[pDCxt->devId].isConnectPending = false;
/*
* clear connect state so that subsequent connect commands start with same
* initial configuration every time.
*/
pDCxt->conn[pDCxt->devId].dot11AuthMode = OPEN_AUTH;
pDCxt->conn[pDCxt->devId].wpaAuthMode = NONE_AUTH;
pDCxt->conn[pDCxt->devId].wpaPairwiseCrypto = pDCxt->conn[pDCxt->devId].wpaGroupCrypto = NONE_CRYPT;
pDCxt->conn[pDCxt->devId].wpaPairwiseCryptoLen = pDCxt->conn[pDCxt->devId].wpaGroupCryptoLen = 0;
A_MEMZERO(pDCxt->conn[pDCxt->devId].reqBssid, sizeof(pDCxt->conn[pDCxt->devId].reqBssid));
pDCxt->conn[pDCxt->devId].channelHint = 0;
pDCxt->conn[pDCxt->devId].connectCtrlFlags = 0;
}
return A_OK;
}
/*****************************************************************************/
/* Api_ConnectWiFi - Called by upper layer to start a network connection
* operation. Executes wmi_connnect_cmd
* void *pCxt - the driver context.
*****************************************************************************/
A_STATUS
Api_ConnectWiFi(void *pCxt)
{
A_DRIVER_CONTEXT *pDCxt;
A_STATUS status = A_OK;
WMI_CONNECT_CMD conn_cmd = {0};
WMI_SCAN_PARAMS_CMD scan_param_cmd;
uint8_t devId;
pDCxt = GET_DRIVER_COMMON(pCxt);
devId = pDCxt->devId;
/* The ssid length check prevents second "essid off" from the user,
to be treated as a connect cmd. The second "essid off" is ignored.
*/
if ((pDCxt->wmiReady == true) && (pDCxt->conn[devId].ssidLen > 0) && pDCxt->conn[devId].networkType != AP_NETWORK)
{
if (/*(ADHOC_NETWORK != ar->arNetworkType) &&*/ // Allow wep key installation in AD-HOC mode
(NONE_AUTH == pDCxt->conn[pDCxt->devId].wpaAuthMode) &&
(WEP_CRYPT == pDCxt->conn[pDCxt->devId].wpaPairwiseCrypto))
{
Install_static_wep_keys(pCxt);
}
/* set scan ctrl flags to default. this will ensure that the firmware will scan for
* an appropriate AP during connect operation. All params that are zero will remain
* unchanged from their pre existing value. If WPS had been previously used it would
* have set the scan ctrl flags in such a way that a subsequent connect might fail.
* This wmi_scanparams_cmd() fixes that issue.
*/
do
{
A_MEMCPY(&scan_param_cmd, &pDCxt->scan_param, sizeof(WMI_SCAN_PARAMS_CMD));
scan_param_cmd.bg_period = pDCxt->scan_param.bg_period = A_CPU2LE16(0xffff);
if (A_OK !=
wmi_cmd_start(pDCxt->pWmiCxt, &scan_param_cmd, WMI_SET_SCAN_PARAMS_CMDID, sizeof(WMI_SCAN_PARAMS_CMD)))
{
break;
}
else
{
WAIT_FOR_WMI_RESPONSE(pCxt);
}
if (pDCxt->conn[devId].ssidLen)
{
A_MEMCPY(conn_cmd.ssid, pDCxt->conn[devId].ssid, pDCxt->conn[devId].ssidLen);
}
conn_cmd.ssidLength = pDCxt->conn[devId].ssidLen;
conn_cmd.networkType = pDCxt->conn[devId].networkType;
conn_cmd.dot11AuthMode = pDCxt->conn[devId].dot11AuthMode;
conn_cmd.authMode = pDCxt->conn[devId].wpaAuthMode;
conn_cmd.pairwiseCryptoType = pDCxt->conn[devId].wpaPairwiseCrypto;
conn_cmd.pairwiseCryptoLen = pDCxt->conn[devId].wpaPairwiseCryptoLen;
conn_cmd.groupCryptoType = pDCxt->conn[devId].wpaGroupCrypto;
conn_cmd.groupCryptoLen = pDCxt->conn[devId].wpaGroupCryptoLen;
conn_cmd.channel = A_CPU2LE16(pDCxt->conn[devId].channelHint);
conn_cmd.ctrl_flags = A_CPU2LE32(pDCxt->conn[devId].connectCtrlFlags);
//NOTE: coverity fix
A_MEMCPY(conn_cmd.bssid, pDCxt->conn[devId].reqBssid, ATH_MAC_LEN);
status = wmi_cmd_start(pDCxt->pWmiCxt, (void *)&conn_cmd, WMI_CONNECT_CMDID, sizeof(WMI_CONNECT_CMD));
if (status != A_OK)
{
break;
}
else
{
WAIT_FOR_WMI_RESPONSE(pCxt);
}
pDCxt->conn[pDCxt->devId].isConnectPending = true;
} while (0);
return status;
}
#if ENABLE_AP_MODE
else if (pDCxt->wmiReady == true && pDCxt->conn[pDCxt->devId].networkType == AP_NETWORK)
{
if ((NONE_AUTH == pDCxt->conn[pDCxt->devId].wpaAuthMode) &&
(WEP_CRYPT == pDCxt->conn[pDCxt->devId].wpaPairwiseCrypto))
{
Install_static_wep_keys(pCxt);
}
A_MEMCPY(conn_cmd.ssid, (uint8_t *)pDCxt->conn[devId].ssid, sizeof(conn_cmd.ssid));
conn_cmd.ssidLength = (int)pDCxt->conn[devId].ssidLen;
conn_cmd.pairwiseCryptoLen = (uint8_t)pDCxt->conn[devId].wpaPairwiseCryptoLen;
conn_cmd.groupCryptoLen = (uint8_t)pDCxt->conn[devId].wpaGroupCryptoLen;
conn_cmd.networkType = pDCxt->conn[devId].networkType;
conn_cmd.dot11AuthMode = pDCxt->conn[devId].dot11AuthMode;
conn_cmd.authMode = pDCxt->conn[devId].wpaAuthMode;
conn_cmd.pairwiseCryptoType = pDCxt->conn[devId].wpaPairwiseCrypto;
conn_cmd.groupCryptoType = pDCxt->conn[devId].wpaGroupCrypto;
conn_cmd.ctrl_flags = (pDCxt->apmodeWPS) ? A_CPU2LE32(pDCxt->conn[devId].connectCtrlFlags | CONNECT_WPS_FLAG) :
A_CPU2LE32(pDCxt->conn[devId].connectCtrlFlags);
conn_cmd.channel = A_CPU2LE16(pDCxt->conn[devId].channelHint);
status = wmi_cmd_start(pDCxt->pWmiCxt, (void *)&conn_cmd, WMI_AP_CONFIG_COMMIT_CMDID, sizeof(WMI_CONNECT_CMD));
return status;
}
#endif /* ENABLE_AP_MODE */
return A_ERROR;
}
static uint8_t wpa_auth_parse(uint8_t *sel)
{
#define WPA_SEL(x) (((x) << 24) | WPA_OUI)
uint32_t w = A_LE_READ_4(sel);
switch (w)
{
case WPA_SEL(WPA_ASE_8021X_UNSPEC):
return WPA_AUTH;
case WPA_SEL(WPA_ASE_8021X_PSK):
return WPA_PSK_AUTH;
case WPA_SEL(WPA_ASE_NONE):
return NONE_AUTH;
}
return 0;
#undef WPA_SEL
}
static uint8_t wpa_cipher_parse(uint8_t *sel, uint8_t *keylen)
{
#define WPA_SEL(x) (((x) << 24) | WPA_OUI)
uint32_t w = A_LE_READ_4(sel);
switch (w)
{
case WPA_SEL(WPA_CSE_NULL):
return NONE_CRYPT;
case WPA_SEL(WPA_CSE_WEP40):
if (keylen)
*keylen = 40 >> 3; // 40/bits_per_byte
return WEP_CRYPT;
case WPA_SEL(WPA_CSE_WEP104):
if (keylen)
*keylen = 104 >> 3; // 104/bits_per_byte
return WEP_CRYPT;
case WPA_SEL(WPA_CSE_TKIP):
return TKIP_CRYPT;
case WPA_SEL(WPA_CSE_CCMP):
return AES_CRYPT;
}
return 0;
#undef WPA_SEL
}
static CRYPTO_TYPE rsn_cipher_parse(uint8_t *sel, uint8_t *keylen)
{
#define RSN_SEL(x) (((x) << 24) | RSN_OUI)
uint32_t w = A_LE_READ_4(sel);
switch (w)
{
case RSN_SEL(RSN_CSE_NULL):
return NONE_CRYPT;
case RSN_SEL(RSN_CSE_WEP40):
if (keylen)
*keylen = 40 >> 3; // 40/bits_per_byte
return WEP_CRYPT;
case RSN_SEL(RSN_CSE_WEP104):
if (keylen)
*keylen = 104 >> 3; // 104/bits_per_byte
return WEP_CRYPT;
case RSN_SEL(RSN_CSE_TKIP):
return TKIP_CRYPT;
case RSN_SEL(RSN_CSE_CCMP):
return AES_CRYPT;
}
return NONE_CRYPT;
#undef RSN_SEL
}
static uint8_t rsn_auth_parse(uint8_t *sel)
{
#define RSN_SEL(x) (((x) << 24) | RSN_OUI)
uint32_t w = A_LE_READ_4(sel);
switch (w)
{
case RSN_SEL(RSN_ASE_8021X_UNSPEC):
return WPA2_AUTH;
case RSN_SEL(RSN_ASE_8021X_PSK):
return WPA2_PSK_AUTH;
case RSN_SEL(RSN_ASE_NONE):
return NONE_AUTH;
}
return 0;
#undef RSN_SEL
}
static void security_ie_parse(uint8_t *pie, uint8_t ie_len, uint8_t *pResult, uint8_t ie_type)
{
uint16_t cnt;
uint16_t i;
uint8_t wepKeyLen;
/* skip mcast cipher */
if (ie_len >= 4)
{
ie_len -= 4;
pie += 4;
}
/* examine ucast cipher(s) */
if (ie_len > 2)
{
cnt = A_LE_READ_2(pie);
ie_len -= 2;
pie += 2;
for (i = 0; ((i < cnt) && (ie_len > 0)); i++)
{
if (ie_type == IEEE80211_ELEMID_RSN)
{
pResult[0] |= rsn_cipher_parse(pie, &wepKeyLen);
}
else
{
pResult[0] |= wpa_cipher_parse(pie, &wepKeyLen);
}
ie_len -= 4;
pie += 4;
}
}
else
{
/* assume default TKIP for wpa */
pResult[0] |= (ie_type == IEEE80211_ELEMID_RSN) ? AES_CRYPT : TKIP_CRYPT;
}
/* parse auth types */
if (ie_len > 2)
{
cnt = A_LE_READ_2(pie);
ie_len -= 2;
pie += 2;
for (i = 0; ((i < cnt) && (ie_len > 0)); i++)
{
if (ie_type == IEEE80211_ELEMID_RSN)
{
pResult[1] |= rsn_auth_parse(pie);
}
else
{
pResult[1] |= wpa_auth_parse(pie);
}
ie_len -= 4;
pie += 4;
}
}
else
{
pResult[1] |= (ie_type == IEEE80211_ELEMID_RSN) ? WPA2_AUTH : WPA_AUTH;
}
}
A_STATUS
Api_ParseInfoElem(void *pCxt, WMI_BSS_INFO_HDR *bih, int32_t len, A_SCAN_SUMMARY *pSummary)
{
uint8_t *buf;
uint8_t *pie, *pieEnd, *pieTemp;
uint8_t ie_result[2];
uint16_t ie_len;
A_MEMZERO(pSummary, sizeof(A_SCAN_SUMMARY));
pSummary->channel = (uint8_t)Util_Freq2ieee(bih->channel);
pSummary->rssi = bih->snr; /* snr is a value from 0 -> 95 where 95 is a strong signal */
A_MEMCPY(pSummary->bssid, bih->bssid, ATH_MAC_LEN);
if ((uint32_t)len < sizeof(WMI_BSS_INFO_HDR) + IE_INDEX)
{
return A_ERROR;
}
buf = (uint8_t *)(bih + 1);
len -= sizeof(WMI_BSS_INFO_HDR);
pSummary->caps = (uint16_t)((uint16_t)buf[CAPS_IE_INDEX] | (uint16_t)(buf[CAPS_IE_INDEX + 1] << 8));
pSummary->beacon_period =
(uint16_t)((uint16_t)buf[BEACON_PERIOD_IE_INDEX] | (uint16_t)(buf[BEACON_PERIOD_IE_INDEX + 1] << 8));
/* loop through IE's to collect additional info */
pie = &buf[IE_INDEX];
len -= IE_INDEX;
pieEnd = &pie[len];
while (pie < pieEnd)
{
switch (*pie)
{
case IEEE80211_ELEMID_SSID:
if (pie[1] <= 32)
{
pSummary->ssid_len = pie[1];
if (pie[1])
{
A_MEMCPY(pSummary->ssid, &pie[2], pie[1]);
}
}
break;
case IEEE80211_ELEMID_RSN:
/*******************/
/* parse RSN IE */
/*******************/
ie_len = pie[1]; /* init ie_len - sizeof wpa_oui */
pieTemp = &pie[2]; /* init pieTemp beyond wpa_oui */
if (A_LE_READ_2(pieTemp) != RSN_VERSION)
{
break;
}
ie_len -= 2;
pieTemp += 2;
ie_result[0] = ie_result[1] = 0;
security_ie_parse(pieTemp, ie_len, &ie_result[0], IEEE80211_ELEMID_RSN);
pSummary->rsn_cipher = ie_result[0];
pSummary->rsn_auth = ie_result[1];
break;
case IEEE80211_ELEMID_VENDOR:
if (pie[1] > 6 && A_LE_READ_4(pie + 2) == ((WPA_OUI_TYPE << 24) | WPA_OUI))
{
/*******************/
/* parse WPA IE */
/*******************/
ie_len = pie[1] - 4; /* init ie_len - sizeof wpa_oui */
pieTemp = &pie[6]; /* init pieTemp beyond wpa_oui */
if (A_LE_READ_2(pieTemp) != WPA_VERSION)
{
break; /* bad version */
}
ie_len -= 2;
pieTemp += 2;
ie_result[0] = ie_result[1] = 0;
security_ie_parse(pieTemp, ie_len, &ie_result[0], IEEE80211_ELEMID_VENDOR);
pSummary->wpa_cipher = ie_result[0];
pSummary->wpa_auth = ie_result[1];
}
break;
}
pie += pie[1] + 2;
}
return A_OK;
}
/*****************************************************************************/
/* Api_DriverAccessCheck - Called by upper layer to confirm that the driver
* is in a State to allow IOCTL's and other requests.
* void *pCxt - the driver context.
* uint8_t block_allowed - caller can tolerate a task block if the
* check is not immediately satisfied.
* uint8_t request_reason - callers reason to request driver access.
*****************************************************************************/
A_STATUS
Api_DriverAccessCheck(void *pCxt, uint8_t block_allowed, uint8_t request_reason)
{
A_DRIVER_CONTEXT *pDCxt = GET_DRIVER_COMMON(pCxt);
A_STATUS status = A_OK;
uint8_t blocked;
UNUSED_ARGUMENT(request_reason);
do
{
blocked = 0;
/* if the chip is powered down when a tx operation is submitted
* then the policy is to wait for the chip to come back */
if (true == pDCxt->chipDown)
{
blocked = 1;
if (block_allowed == 0)
{
/* caller forbids blocking so return A_ERROR */
status = A_ERROR;
break;
}
do
{
DRIVER_WAIT_FOR_CONDITION(pCxt, &(pDCxt->chipDown), false, 5000);
} while (true == pDCxt->chipDown);
}
#if DRIVER_CONFIG_ENABLE_STORE_RECALL
/*Check str-rcl state only if applications requests it*/
if (request_reason != ACCESS_REQUEST_RX)
{
/* if a strrcl command is in process all ioctl's and tx operations
* must be blocked/deferred until it completes.
*/
if (true == pDCxt->strrclBlock)
{
blocked = 1;
if (block_allowed == 0)
{
/* caller forbids blocking so return A_ERROR */
status = A_ERROR;
break;
}
do
{
DRIVER_WAIT_FOR_CONDITION(pCxt, &(pDCxt->strrclBlock), false, 5000);
} while (true == pDCxt->strrclBlock);
}
}
#endif
} while (blocked); /* loop until all conditions are met at one pass */
return status;
}
#if DRIVER_CONFIG_PROGRAM_MAC_ADDR
A_STATUS
Api_ProgramMacAddress(void *pCxt, uint8_t *addr, uint16_t length, uint8_t *pResult)
{
A_STATUS status = A_ERROR;
A_DRIVER_CONTEXT *pDCxt = GET_DRIVER_COMMON(pCxt);
/* init pResult to an error code of 0 */
*pResult = ATH_PROGRAM_MAC_RESULT_DRIVER_FAILED;
do
{
if (length != sizeof(ATH_PROGRAM_MAC_ADDR_PARAM))
{
break;
}
if (Api_DriverAccessCheck(pCxt, 0, ACCESS_REQUEST_IOCTL) != A_OK)
{
break;
}
if (pDCxt->asynchRequest != NULL)
{
break;
}
/* use the reqBssid as storage for the mac address. the program_mac_addr
* function will retrieve this value for use in the operation.
*/
A_MEMCPY(pDCxt->conn[pDCxt->devId].reqBssid, addr, sizeof(pDCxt->conn[pDCxt->devId].reqBssid));
pDCxt->macProgramming = true;
pDCxt->asynchRequest = program_mac_addr;
DRIVER_WAKE_DRIVER(pCxt);
DRIVER_WAIT_FOR_CONDITION(pCxt, &(pDCxt->macProgramming), false, 5000);
if (pDCxt->macProgramming == false)
{
switch (pDCxt->conn[pDCxt->devId].reqBssid[0])
{
case 1: /*successful result*/
*pResult = ATH_PROGRAM_MAC_RESULT_SUCCESS;
break;
case 2: /* device failed in the attempt */
*pResult = ATH_PROGRAM_MAC_RESULT_DEV_FAILED;
break;
case 4: /* the same mac address is already programmed */
case 8: /* the device rejected the mac address */
*pResult = ATH_PROGRAM_MAC_RESULT_DEV_DENIED;
break;
case 0: /* driver failure to communicate with device */
default:
break;
}
Api_InitFinish(pCxt);
Api_WMIInitFinish(pCxt);
status = A_OK;
}
} while (0);
A_MEMZERO(pDCxt->conn[pDCxt->devId].reqBssid, sizeof(pDCxt->conn[pDCxt->devId].reqBssid));
return status;
}
#endif /* DRIVER_CONFIG_PROGRAM_MAC_ADDR */
A_STATUS
Api_SetPowerMode(void *pCxt, POWER_MODE *app_setting)
{
A_DRIVER_CONTEXT *pDCxt = GET_DRIVER_COMMON(pCxt);
if (app_setting->pwr_module < PWR_MAX)
{
(app_setting->pwr_mode == REC_POWER) ? (pDCxt->pwrStateSetting &= ~(1 << app_setting->pwr_module)) :
(pDCxt->pwrStateSetting |= (1 << app_setting->pwr_module));
}
/* Set MAX Perf */
if ((app_setting->pwr_mode == MAX_PERF_POWER) && (pDCxt->userPwrMode == REC_POWER))
{
pDCxt->userPwrMode = MAX_PERF_POWER;
}
/* Set REC Power */
if ((app_setting->pwr_mode == REC_POWER) && (pDCxt->pwrStateSetting == 0x00))
{
pDCxt->userPwrMode = REC_POWER;
}
QCADRV_PRINTF("Power Mode : %x,%d,%d \n", pDCxt->pwrStateSetting, app_setting->pwr_mode, app_setting->pwr_module);
if (A_OK !=
wmi_cmd_start(pDCxt->pWmiCxt, &pDCxt->userPwrMode, WMI_SET_POWER_MODE_CMDID, sizeof(WMI_POWER_MODE_CMD)))
{
return A_ERROR;
}
if ((app_setting->pwr_mode == REC_POWER) && pDCxt->userPwrMode == MAX_PERF_POWER)
{
QCADRV_PRINTF("Device will remain MAX_PERF \n");
}
return A_OK;
}
#if !ENABLE_STACK_OFFLOAD
extern const uint8_t max_performance_power_param;
int32_t power_state_for_module = 0;
/*****************************************************************************/
/* move_to_maxperf - Changes the power mode to max perf in firmware. There are
* some commands which need to run in MAX_PERF mode like store_recall etc
* This function changes the power modeto MAX_PERF and will not
* intimate the application. Later after the command succeeds,
* use restore_power_state to change to original power state
* Note: Application should not directly use this function
* int32_t - module which request the change
* Returns- A_OK on success, A_ERROR otherwise
*****************************************************************************/
A_STATUS move_power_state_to_maxperf(void *pCxt, int32_t module)
{
A_DRIVER_CONTEXT *pDCxt = (A_DRIVER_CONTEXT *)pCxt;
/* Already some HIGH module changes state */
if (power_state_for_module >= module)
{
return A_OK;
}
/* Change the power mode only when the current power mode is REC_POWER */
if (pDCxt->userPwrMode == REC_POWER)
{
if (A_OK != wmi_cmd_start(pDCxt->pWmiCxt, &max_performance_power_param, WMI_SET_POWER_MODE_CMDID,
sizeof(WMI_POWER_MODE_CMD)))
{
return A_ERROR;
}
}
power_state_for_module = module;
return A_OK;
}
#endif
A_STATUS wait_scan_done(void *pCxt, void *pWmi)
{
A_DRIVER_CONTEXT *pDCxt = GET_DRIVER_COMMON(pCxt);
if (pDCxt->scanDone == false)
{
/* block until scan completes */
DRIVER_WAIT_FOR_CONDITION(pCxt, &(pDCxt->scanDone), true, 5000);
if (pDCxt->scanDone == false)
{
wmi_bssfilter_cmd(pWmi, NONE_BSS_FILTER, 0);
}
return A_ERROR;
}
pDCxt->scanDone = false;
return A_OK;
}
A_STATUS scan_setup(void *pCxt, void *pWmi, WMI_START_SCAN_CMD *start_scan)
{
union
{
WMI_START_SCAN_CMD scan_cmd;
WMI_PROBED_SSID_CMD probeParam;
} stackU;
A_STATUS error = A_OK;
uint32_t size;
A_DRIVER_CONTEXT *pDCxt = GET_DRIVER_COMMON(pCxt);
do
{
if (pDCxt->conn[pDCxt->devId].ssidLen > 0)
{
/* apply filter ssid */
stackU.probeParam.entryIndex = 1;
stackU.probeParam.flag = SPECIFIC_SSID_FLAG;
stackU.probeParam.ssidLength = pDCxt->conn[pDCxt->devId].ssidLen;
A_MEMCPY(stackU.probeParam.ssid, pDCxt->conn[pDCxt->devId].ssid, pDCxt->conn[pDCxt->devId].ssidLen);
if (A_OK != wmi_cmd_start(pWmi, &stackU.probeParam, WMI_SET_PROBED_SSID_CMDID, sizeof(WMI_PROBED_SSID_CMD)))
{
error = A_ERROR;
break;
}
if (A_OK != wmi_bssfilter_cmd(pWmi, PROBED_SSID_FILTER, 0))
{
error = A_ERROR;
break;
}
}
else
{
/* clear any pre-existing filter ssid */
stackU.probeParam.entryIndex = 1;
stackU.probeParam.flag = DISABLE_SSID_FLAG;
stackU.probeParam.ssidLength = 0;
if (A_OK != wmi_cmd_start(pWmi, &stackU.probeParam, WMI_SET_PROBED_SSID_CMDID, sizeof(WMI_PROBED_SSID_CMD)))
{
error = A_ERROR;
break;
}
if (A_OK != wmi_bssfilter_cmd(pWmi, ALL_BSS_FILTER, 0))
{
error = A_ERROR;
break;
}
}
GET_DRIVER_COMMON(pCxt)->scanOutSize = ATH_MAX_SCAN_BUFFERS;
GET_DRIVER_COMMON(pCxt)->scanOutCount = 0;
pDCxt->scanDone = false;
/* start the scan */
if (start_scan == NULL)
{
A_MEMZERO(&stackU.scan_cmd, sizeof(WMI_START_SCAN_CMD));
stackU.scan_cmd.scanType = WMI_LONG_SCAN;
stackU.scan_cmd.forceFgScan = false;
stackU.scan_cmd.isLegacy = false;
stackU.scan_cmd.homeDwellTime = 0;
stackU.scan_cmd.forceScanInterval = 1;
stackU.scan_cmd.numChannels = 0;
if (A_OK != wmi_cmd_start(pWmi, (void *)&stackU.scan_cmd, WMI_START_SCAN_CMDID, sizeof(WMI_START_SCAN_CMD)))
{
error = A_ERROR;
}
}
else
{
size = sizeof(WMI_START_SCAN_CMD);
if (start_scan->numChannels > 0)
{
size = size + (start_scan->numChannels - 1) * sizeof(uint16_t);
}
if (A_OK != wmi_cmd_start(pWmi, (void *)start_scan, WMI_START_SCAN_CMDID, size))
{
error = A_ERROR;
}
}
} while (0);
return error;
}
uint8_t Util_Ascii2Hex(char val)
{
if ('0' <= val && '9' >= val)
{
return (uint8_t)(val - '0');
}
else if ('a' <= val && 'f' >= val)
{
return (uint8_t)((val - 'a') + 0x0a);
}
else if ('A' <= val && 'F' >= val)
{
return (uint8_t)((val - 'A') + 0x0a);
}
return 0xff; /* error */
}
A_STATUS
TxRawPacket(void *pCxt, void *pReq, ATH_MAC_TX_PARAMS *pParams)
{
WMI_TX_META_V3 v3_meta;
HTC_ENDPOINT_ID eid;
A_DRIVER_CONTEXT *pDCxt;
A_STATUS status = A_ERROR;
eid = Util_AC2EndpointID(pCxt, WMM_AC_BE);
A_NETBUF_SET_ELEM(pReq, A_REQ_EPID, eid);
pDCxt = GET_DRIVER_COMMON(pCxt);
do
{
/* translate from ATH_MAC_TX_PARAMS to WMI_TX_META_V3 */
/* how convenient the values are all the same */
v3_meta.pktID = pParams->pktID;
A_MEMCPY(&v3_meta.rateSched.rateSeries, &pParams->rateSched.rateSeries,
sizeof(uint8_t) * WMI_TX_MAX_RATE_SERIES);
A_MEMCPY(&v3_meta.rateSched.trySeries, &pParams->rateSched.trySeries, sizeof(uint8_t) * WMI_TX_MAX_RATE_SERIES);
v3_meta.rateSched.flags = pParams->rateSched.flags;
v3_meta.rateSched.accessCategory = pParams->rateSched.accessCategory;
if (wmi_data_hdr_add(pDCxt->pWmiCxt, pReq, DATA_MSGTYPE, false, WMI_DATA_HDR_DATA_TYPE_802_11,
WMI_META_VERSION_3, (void *)&v3_meta) != A_OK)
{
break;
}
A_MDELAY(2);
/* HTC interface is asynchronous, if this fails, cleanup will happen in
* the ar6000_tx_complete callback */
if (A_OK != Driver_SubmitTxRequest((void *)pCxt, pReq))
{
A_NETBUF_FREE(pReq);
break;
}
status = A_OK;
} while (0);
return status;
}
/* EOF */
|
7b048e65c7f491aa99d831ad40e54d45c19d6c5e
|
bf76ef3f082ff89bdb971c08dd7c08437d1ac583
|
/sdk/docs/doxygen/source/doc_adv_dynamic_build.h
|
9917c5c8d9e41600c536ecd35d352ec2b9ff67b0
|
[
"DOC",
"Zlib"
] |
permissive
|
codecat/angelscript-mirror
|
5856379863bf4dfa6e31b5101a4485179a2f4ffa
|
957eac4142448150342afdea46690ef0d45ef434
|
refs/heads/master
| 2023-08-11T20:50:24.542448
| 2023-07-30T14:27:45
| 2023-07-30T14:27:45
| 157,086,380
| 117
| 43
| null | null | null | null |
UTF-8
|
C
| false
| false
| 8,296
|
h
|
doc_adv_dynamic_build.h
|
/**
\page doc_adv_dynamic_build Dynamic compilations
There are various forms of dynamic compilations of scripts. In the following subtopics
I try to explain the theory of them and give some information on how they can be implemented.
\section doc_adv_dynamic_build_ondemand On demand builds
The most common form of dynamic compilations is building new modules on demand, i.e.
as they are needed. When using this the application or game engine is typically designed
to have separate scripts to perform different tasks, e.g. menu handling, different types of AI
controllers, player controller, etc. If these separate scripts have an abstraction layer through
the application to interact with each other it is very easy to build the scripts on demand.
To build a new script on demand, simply get a new module, add the needed script sections
to it and build it just as you would when \ref doc_compile_script "building the first script".
As each module is independent the previously existing module will be unaffected.
Each module can be configured to see a \ref doc_adv_access_mask "different application interface",
so there is no need to create different engine instances.
Though modules are independent, they can still interact with each other if the application
provides the interface for that. To make the communication between modules easier one can
chose to use \ref doc_script_shared "shared script entities". Shared script entities will
be compiled only once by the first module that includes the code. Any subsequent module that
also include the code for the shared entity will reuse what was built by the first module, i.e.
will share the internal type and bytecode.
Another option is to \ref doc_global_import "import global functions" from a previously
compiled module. In this case the application must make sure the function that exports the
functions is compiled first, then after building the module that imports the function the
application must call the \ref asIScriptModule::BindAllImportedFunctions so conclude the imports.
\see \ref doc_samples_game "Game sample"
\section doc_adv_dynamic_build_incr Incremental builds
Besides the ordinary \ref doc_compile_script "compilation of scripts" and subsequent
\ref doc_call_script_func "executions", AngelScript also support dynamically compiling
additional \ref asIScriptModule::CompileFunction "functions" and
\ref asIScriptModule::CompileGlobalVar "global variables" to incrementally add to the
scope of a module. These functions and variables will become part of the scope, just
as if they had been included in the initial script compilation which means that subsequent
executions or incremental compilations can use them.
It is also possible to dynamically remove \ref asIScriptModule::RemoveFunction "functions"
and \ref asIScriptModule::RemoveGlobalVar "variables". Doing so doesn't immediately discard
the functions or variables, so other functions that still refer to them will not fail when
executing them. They will however no longer be visible for new compilations or when searching
for functions or variables in the module.
This kind of dynamic compilations is most useful when dealing with user interaction,
e.g. an ingame console, or perhaps event handlers, e.g. a trigger on a GUI button click.
\see \ref doc_addon_helpers "ExecuteString() add-on", \ref doc_samples_console "Console sample"
\section doc_adv_dynamic_build_hot Hot reloading scripts
Hot reloading is most often used when quick change & test cycles are wanted. It is quite common
for game engines to have a debug mode that continuously monitors the script files to detect any
updates that are made, and when detected automatically reloads the scripts without restarting
the game. This allows the developers, for example, to quickly change the behaviour of the AI and
immediately see the result without having to play through the entire level over and over again.
Hot reloading without preserving the state of existing objects is quite trivial. Simply discard
everything, reload the scripts, and create new objects. On the other hand, hot reloading scripts
while preserving the state of existing objects can be quite tricky, but is also the most rewarding
when implemented successfully.
The first part to reloading while preserving the state is keeping track of the object instances so
the application knows which objects needs to be serialized when a module is hot reloaded. It is
entirely up to the application to build and maintain this mapping.
The second part is knowing which script files that will trigger a reload when changed. When building
the module the application needs to store the list of the files that were added to it. If you use the
standard \ref doc_addon_build "script builder add-on", then it provides methods to enumerate the included
sections or files.
The third part is the hardest, and that is to implement the actual serialization. Serializing object members
of value types is normally quite trivial, simply \ref doc_adv_reflection_vars "enumerate the object properties"
and store a name-value pair for each. Serializing object members of reference types needs some consideration,
as depending on the object that is referred to, either you will be able to store the actual pointer, or you
will need to store some kind of descriptor as the referred to object will also be recreated during the reload.
Once all the objects that will need to be recreated after the reload have been serialized for backup,
the module can be rebuilt using the normal procedure for \ref doc_compile_script "compiling a script".
Afterwards the serialized objects needs to be recreated. Once created you'll enumerate
the members and set their values or references according to the backed up data.
\subsection doc_adv_dynamic_build_hot_1 Things to consider
- Design the engine and script interface with hot reloading in mind from the start. Hot reloading is much
easier to implement the less complex interface you have, e.g. script objects that can only interact with
other script objects indirectly through the application will not be able to hold references to objects
unknown by the application.
- \ref doc_script_shared "Shared script entities" will not be recompiled if some module or existing object
(including those pending destruction in the garbage collector) still refers to the code. It's recommended
that you minimize the use of shared entities to where necessary so as to minimize the need to modify them.
- Before discarding the original objects, consider doing a test compilation of the modified scripts in a
temporary module first, and only go ahead with the hot reloading if the test compilation is successful. That
way you can catch compilation errors that would otherwise cause the recreation of the new objects to fail.
- When recreating object instances you can take advantage of the method
\ref asIScriptEngine::CreateUninitializedScriptObject to create the objects without actually
executing the script class constructor, which may have unwanted side effects during the reload.
- Decide what to do when the script modifications introduces new object properties or removes existing
properties, as you will not be able to restore the exact same object state then. Perhaps the new property
can be filled with some default value to allow the continuation of the execution? Or perhaps the script itself
can have a special event handler to provide the initial value of the new member?
- The \ref doc_addon_serializer "Serializer" add-on has been implemented to aid the implementation of hot reloading
scripts, though it may not suit all types of applications.
- Although it is possible to \ref doc_serialization_contexts "serialize a script context", if any function on the
context's call stack is modified the program position cannot be reliably restored. Therefore it is recommended
that you design your application so that contexts can be aborted when hot reloading and any long running scripts
restarted, or avoid scripts that run over multiple frames all together so that it is guaranteed that no contexts
are active when hot reloading.
\see \ref doc_addon_serializer, \ref doc_serialization
*/
|
6fa4f997e5f706c3d653bd31c5a602b5a539d8a0
|
99bdb3251fecee538e0630f15f6574054dfc1468
|
/bsp/imx6sx/iMX6_Platform_SDK/sdk/common/usb_stack/Device/source/class/usb_hid.h
|
cabb2b3bada2fe0a410913dcf955b865964f3c14
|
[
"Zlib",
"LicenseRef-scancode-proprietary-license",
"MIT",
"BSD-3-Clause",
"X11",
"BSD-4-Clause-UC",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
RT-Thread/rt-thread
|
03a7c52c2aeb1b06a544143b0e803d72f47d1ece
|
3602f891211904a27dcbd51e5ba72fefce7326b2
|
refs/heads/master
| 2023-09-01T04:10:20.295801
| 2023-08-31T16:20:55
| 2023-08-31T16:20:55
| 7,408,108
| 9,599
| 5,805
|
Apache-2.0
| 2023-09-14T13:37:26
| 2013-01-02T14:49:21
|
C
|
UTF-8
|
C
| false
| false
| 5,505
|
h
|
usb_hid.h
|
/******************************************************************************
*
* Freescale Semiconductor Inc.
* (c) Copyright 2004-2009 Freescale Semiconductor, Inc.
* ALL RIGHTS RESERVED.
*
******************************************************************************
*
* THIS SOFTWARE IS PROVIDED BY FREESCALE "AS IS" AND ANY EXPRESSED 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 FREESCALE OR ITS 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.
*
**************************************************************************//*!
*
* @file usb_hid.h
*
* @author
*
* @version
*
* @date May-28-2009
*
* @brief The file contains USB stack HID class layer API header function.
*
*****************************************************************************/
#ifndef _USB_HID_H
#define _USB_HID_H
/******************************************************************************
* Includes
*****************************************************************************/
#include "types.h"
#include "usb_descriptor.h"
#include "usb_class.h"
#ifdef COMPOSITE_DEV
#include "usb_composite.h"
#endif
#include "usb_devapi.h"
/******************************************************************************
* Constants - None
*****************************************************************************/
/******************************************************************************
* Macro's
*****************************************************************************/
#define MAX_QUEUE_ELEMS (4)
/* class specific requests */
#define USB_HID_GET_REPORT_REQUEST (0x01)
#define USB_HID_GET_IDLE_REQUEST (0x02)
#define USB_HID_GET_PROTOCOL_REQUEST (0x03)
#define USB_HID_SET_REPORT_REQUEST (0x09)
#define USB_HID_SET_IDLE_REQUEST (0x0A)
#define USB_HID_SET_PROTOCOL_REQUEST (0x0B)
/* for class specific requests */
#define HIGH_BYTE_SHIFT (8)
#define MSB_MASK (0xFF00)
#define USB_HID_REQUEST_DIR_MASK (0x08)
#define USB_HID_REQUEST_TYPE_MASK (0x01)
#define REPORT_SIZE (4)
#define CLASS_REQ_DATA_SIZE (0x01)
#define HID_ENDPOINT (1)
/******************************************************************************
* Types
*****************************************************************************/
/* structure to hold a request in the endpoint queue */
typedef struct _usb_class_hid_queue
{
uint_8 controller_ID; /* Controller ID*/
uint_8 channel; /* Endpoint number */
uint_8_ptr app_buff; /* Buffer to send */
USB_PACKET_SIZE size; /* Size of the transfer */
}USB_CLASS_HID_QUEUE, *PTR_USB_CLASS_HID_QUEUE;
/* USB class hid endpoint data */
typedef struct _usb_class_hid_endpoint
{
uint_8 endpoint; /* Endpoint number */
uint_8 type; /* Type of endpoint (interrupt,
bulk or isochronous) */
uint_8 bin_consumer; /* Num of queued elements */
uint_8 bin_producer; /* Num of de-queued elements */
uint_8 queue_num; /* HIGH SPEED: Num of queue */
USB_CLASS_HID_QUEUE queue[MAX_QUEUE_ELEMS]; /* Queue data */
}USB_CLASS_HID_ENDPOINT;
/* contains the endpoint data for non control endpoints */
typedef struct _usb_class_hid_endpoint_data
{
/* Num of non control endpoints */
uint_8 count;
/* contains the endpoint info */
#ifndef COMPOSITE_DEV
USB_CLASS_HID_ENDPOINT ep[USB_MAX_SUPPORTED_ENDPOINTS]; //HID_DESC_ENDPOINT_COUNT];
#else
USB_CLASS_HID_ENDPOINT ep[COMPOSITE_DESC_ENDPOINT_COUNT];
#endif
}USB_CLASS_HID_ENDPOINT_DATA, *PTR_USB_CLASS_HID_ENDPOINT_DATA;
/******************************************************************************
* Global Functions
*****************************************************************************/
extern uint_8 USB_Class_HID_Init (
uint_8 controller_ID,
USB_CLASS_CALLBACK hid_class_callback,
USB_REQ_FUNC vendor_req_callback,
USB_CLASS_SPECIFIC_HANDLER_FUNC param_callback
);
extern void USB_Class_Hid_Event (
uint_8 controller_ID, /* [IN] Controller ID */
uint_8 event, /* [IN] Event Type */
void* val /* [IN] Pointer to configuration Value */
);
#ifdef COMPOSITE_DEV
extern uint_8 USB_HID_Other_Requests(uint_8 controller_ID,
USB_SETUP_STRUCT * setup_packet,
uint_8_ptr *data,
USB_PACKET_SIZE *size);
#endif
extern uint_8 USB_Class_HID_DeInit
(
uint_8 controller_ID
);
extern uint_8 USB_Class_HID_Send_Data (
uint_8 controller_ID,
uint_8 ep_num,
uint_8_ptr buff_ptr,
USB_PACKET_SIZE size
);
#define USB_Class_HID_Periodic_Task USB_Class_Periodic_Task
void USB_Service_Hid (PTR_USB_DEV_EVENT_STRUCT event);
#endif
|
b15ff6a1f05dd4c1645f5d3f067a8207ccba1c92
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/drivers/ssb/ssb_private.h
|
4671f17f09aff44e809766e6317273d480ec6444
|
[
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"Linux-syscall-note",
"GPL-2.0-only",
"GPL-1.0-or-later"
] |
permissive
|
OLIMEX/DIY-LAPTOP
|
ae82f4ee79c641d9aee444db9a75f3f6709afa92
|
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
|
refs/heads/rel3
| 2023-08-04T01:54:19.483792
| 2023-04-03T07:18:12
| 2023-04-03T07:18:12
| 80,094,055
| 507
| 92
|
Apache-2.0
| 2023-04-03T07:05:59
| 2017-01-26T07:25:50
|
C
|
UTF-8
|
C
| false
| false
| 8,243
|
h
|
ssb_private.h
|
#ifndef LINUX_SSB_PRIVATE_H_
#define LINUX_SSB_PRIVATE_H_
#include <linux/ssb/ssb.h>
#include <linux/types.h>
#include <linux/bcm47xx_wdt.h>
#define PFX "ssb: "
#ifdef CONFIG_SSB_SILENT
# define ssb_printk(fmt, ...) \
do { if (0) printk(fmt, ##__VA_ARGS__); } while (0)
#else
# define ssb_printk(fmt, ...) \
printk(fmt, ##__VA_ARGS__)
#endif /* CONFIG_SSB_SILENT */
#define ssb_emerg(fmt, ...) ssb_printk(KERN_EMERG PFX fmt, ##__VA_ARGS__)
#define ssb_err(fmt, ...) ssb_printk(KERN_ERR PFX fmt, ##__VA_ARGS__)
#define ssb_warn(fmt, ...) ssb_printk(KERN_WARNING PFX fmt, ##__VA_ARGS__)
#define ssb_notice(fmt, ...) ssb_printk(KERN_NOTICE PFX fmt, ##__VA_ARGS__)
#define ssb_info(fmt, ...) ssb_printk(KERN_INFO PFX fmt, ##__VA_ARGS__)
#define ssb_cont(fmt, ...) ssb_printk(KERN_CONT fmt, ##__VA_ARGS__)
/* dprintk: Debugging printk; vanishes for non-debug compilation */
#ifdef CONFIG_SSB_DEBUG
# define ssb_dbg(fmt, ...) \
ssb_printk(KERN_DEBUG PFX fmt, ##__VA_ARGS__)
#else
# define ssb_dbg(fmt, ...) \
do { if (0) printk(KERN_DEBUG PFX fmt, ##__VA_ARGS__); } while (0)
#endif
#ifdef CONFIG_SSB_DEBUG
# define SSB_WARN_ON(x) WARN_ON(x)
# define SSB_BUG_ON(x) BUG_ON(x)
#else
static inline int __ssb_do_nothing(int x) { return x; }
# define SSB_WARN_ON(x) __ssb_do_nothing(unlikely(!!(x)))
# define SSB_BUG_ON(x) __ssb_do_nothing(unlikely(!!(x)))
#endif
/* pci.c */
#ifdef CONFIG_SSB_PCIHOST
extern int ssb_pci_switch_core(struct ssb_bus *bus,
struct ssb_device *dev);
extern int ssb_pci_switch_coreidx(struct ssb_bus *bus,
u8 coreidx);
extern int ssb_pci_xtal(struct ssb_bus *bus, u32 what,
int turn_on);
extern int ssb_pci_get_invariants(struct ssb_bus *bus,
struct ssb_init_invariants *iv);
extern void ssb_pci_exit(struct ssb_bus *bus);
extern int ssb_pci_init(struct ssb_bus *bus);
extern const struct ssb_bus_ops ssb_pci_ops;
#else /* CONFIG_SSB_PCIHOST */
static inline int ssb_pci_switch_core(struct ssb_bus *bus,
struct ssb_device *dev)
{
return 0;
}
static inline int ssb_pci_switch_coreidx(struct ssb_bus *bus,
u8 coreidx)
{
return 0;
}
static inline int ssb_pci_xtal(struct ssb_bus *bus, u32 what,
int turn_on)
{
return 0;
}
static inline void ssb_pci_exit(struct ssb_bus *bus)
{
}
static inline int ssb_pci_init(struct ssb_bus *bus)
{
return 0;
}
#endif /* CONFIG_SSB_PCIHOST */
/* pcmcia.c */
#ifdef CONFIG_SSB_PCMCIAHOST
extern int ssb_pcmcia_switch_core(struct ssb_bus *bus,
struct ssb_device *dev);
extern int ssb_pcmcia_switch_coreidx(struct ssb_bus *bus,
u8 coreidx);
extern int ssb_pcmcia_switch_segment(struct ssb_bus *bus,
u8 seg);
extern int ssb_pcmcia_get_invariants(struct ssb_bus *bus,
struct ssb_init_invariants *iv);
extern int ssb_pcmcia_hardware_setup(struct ssb_bus *bus);
extern void ssb_pcmcia_exit(struct ssb_bus *bus);
extern int ssb_pcmcia_init(struct ssb_bus *bus);
extern const struct ssb_bus_ops ssb_pcmcia_ops;
#else /* CONFIG_SSB_PCMCIAHOST */
static inline int ssb_pcmcia_switch_core(struct ssb_bus *bus,
struct ssb_device *dev)
{
return 0;
}
static inline int ssb_pcmcia_switch_coreidx(struct ssb_bus *bus,
u8 coreidx)
{
return 0;
}
static inline int ssb_pcmcia_switch_segment(struct ssb_bus *bus,
u8 seg)
{
return 0;
}
static inline int ssb_pcmcia_hardware_setup(struct ssb_bus *bus)
{
return 0;
}
static inline void ssb_pcmcia_exit(struct ssb_bus *bus)
{
}
static inline int ssb_pcmcia_init(struct ssb_bus *bus)
{
return 0;
}
#endif /* CONFIG_SSB_PCMCIAHOST */
/* sdio.c */
#ifdef CONFIG_SSB_SDIOHOST
extern int ssb_sdio_get_invariants(struct ssb_bus *bus,
struct ssb_init_invariants *iv);
extern u32 ssb_sdio_scan_read32(struct ssb_bus *bus, u16 offset);
extern int ssb_sdio_switch_core(struct ssb_bus *bus, struct ssb_device *dev);
extern int ssb_sdio_scan_switch_coreidx(struct ssb_bus *bus, u8 coreidx);
extern int ssb_sdio_hardware_setup(struct ssb_bus *bus);
extern void ssb_sdio_exit(struct ssb_bus *bus);
extern int ssb_sdio_init(struct ssb_bus *bus);
extern const struct ssb_bus_ops ssb_sdio_ops;
#else /* CONFIG_SSB_SDIOHOST */
static inline u32 ssb_sdio_scan_read32(struct ssb_bus *bus, u16 offset)
{
return 0;
}
static inline int ssb_sdio_switch_core(struct ssb_bus *bus,
struct ssb_device *dev)
{
return 0;
}
static inline int ssb_sdio_scan_switch_coreidx(struct ssb_bus *bus, u8 coreidx)
{
return 0;
}
static inline int ssb_sdio_hardware_setup(struct ssb_bus *bus)
{
return 0;
}
static inline void ssb_sdio_exit(struct ssb_bus *bus)
{
}
static inline int ssb_sdio_init(struct ssb_bus *bus)
{
return 0;
}
#endif /* CONFIG_SSB_SDIOHOST */
/* scan.c */
extern const char *ssb_core_name(u16 coreid);
extern int ssb_bus_scan(struct ssb_bus *bus,
unsigned long baseaddr);
extern void ssb_iounmap(struct ssb_bus *ssb);
/* sprom.c */
extern
ssize_t ssb_attr_sprom_show(struct ssb_bus *bus, char *buf,
int (*sprom_read)(struct ssb_bus *bus, u16 *sprom));
extern
ssize_t ssb_attr_sprom_store(struct ssb_bus *bus,
const char *buf, size_t count,
int (*sprom_check_crc)(const u16 *sprom, size_t size),
int (*sprom_write)(struct ssb_bus *bus, const u16 *sprom));
extern int ssb_fill_sprom_with_fallback(struct ssb_bus *bus,
struct ssb_sprom *out);
/* core.c */
extern u32 ssb_calc_clock_rate(u32 plltype, u32 n, u32 m);
extern struct ssb_bus *ssb_pci_dev_to_bus(struct pci_dev *pdev);
int ssb_for_each_bus_call(unsigned long data,
int (*func)(struct ssb_bus *bus, unsigned long data));
extern struct ssb_bus *ssb_pcmcia_dev_to_bus(struct pcmcia_device *pdev);
struct ssb_freeze_context {
/* Pointer to the bus */
struct ssb_bus *bus;
/* Boolean list to indicate whether a device is frozen on this bus. */
bool device_frozen[SSB_MAX_NR_CORES];
};
extern int ssb_devices_freeze(struct ssb_bus *bus, struct ssb_freeze_context *ctx);
extern int ssb_devices_thaw(struct ssb_freeze_context *ctx);
/* b43_pci_bridge.c */
#ifdef CONFIG_SSB_B43_PCI_BRIDGE
extern int __init b43_pci_ssb_bridge_init(void);
extern void __exit b43_pci_ssb_bridge_exit(void);
#else /* CONFIG_SSB_B43_PCI_BRIDGE */
static inline int b43_pci_ssb_bridge_init(void)
{
return 0;
}
static inline void b43_pci_ssb_bridge_exit(void)
{
}
#endif /* CONFIG_SSB_B43_PCI_BRIDGE */
/* driver_chipcommon_pmu.c */
extern u32 ssb_pmu_get_cpu_clock(struct ssb_chipcommon *cc);
extern u32 ssb_pmu_get_controlclock(struct ssb_chipcommon *cc);
extern u32 ssb_pmu_get_alp_clock(struct ssb_chipcommon *cc);
extern u32 ssb_chipco_watchdog_timer_set_wdt(struct bcm47xx_wdt *wdt,
u32 ticks);
extern u32 ssb_chipco_watchdog_timer_set_ms(struct bcm47xx_wdt *wdt, u32 ms);
/* driver_chipcommon_sflash.c */
#ifdef CONFIG_SSB_SFLASH
int ssb_sflash_init(struct ssb_chipcommon *cc);
#else
static inline int ssb_sflash_init(struct ssb_chipcommon *cc)
{
pr_err("Serial flash not supported\n");
return 0;
}
#endif /* CONFIG_SSB_SFLASH */
#ifdef CONFIG_SSB_DRIVER_MIPS
extern struct platform_device ssb_pflash_dev;
#endif
#ifdef CONFIG_SSB_DRIVER_EXTIF
extern u32 ssb_extif_watchdog_timer_set_wdt(struct bcm47xx_wdt *wdt, u32 ticks);
extern u32 ssb_extif_watchdog_timer_set_ms(struct bcm47xx_wdt *wdt, u32 ms);
#else
static inline u32 ssb_extif_watchdog_timer_set_wdt(struct bcm47xx_wdt *wdt,
u32 ticks)
{
return 0;
}
static inline u32 ssb_extif_watchdog_timer_set_ms(struct bcm47xx_wdt *wdt,
u32 ms)
{
return 0;
}
#endif
#ifdef CONFIG_SSB_EMBEDDED
extern int ssb_watchdog_register(struct ssb_bus *bus);
#else /* CONFIG_SSB_EMBEDDED */
static inline int ssb_watchdog_register(struct ssb_bus *bus)
{
return 0;
}
#endif /* CONFIG_SSB_EMBEDDED */
#ifdef CONFIG_SSB_DRIVER_EXTIF
extern void ssb_extif_init(struct ssb_extif *extif);
#else
static inline void ssb_extif_init(struct ssb_extif *extif)
{
}
#endif
#ifdef CONFIG_SSB_DRIVER_GPIO
extern int ssb_gpio_init(struct ssb_bus *bus);
extern int ssb_gpio_unregister(struct ssb_bus *bus);
#else /* CONFIG_SSB_DRIVER_GPIO */
static inline int ssb_gpio_init(struct ssb_bus *bus)
{
return -ENOTSUPP;
}
static inline int ssb_gpio_unregister(struct ssb_bus *bus)
{
return 0;
}
#endif /* CONFIG_SSB_DRIVER_GPIO */
#endif /* LINUX_SSB_PRIVATE_H_ */
|
445752c878bc66387798cdace13d8451552f5c48
|
bdc27c22522a99b5bff2ec4cfa95fadcba65747d
|
/source/adios2/toolkit/sst/dp/ucx_dp.c
|
1b33c5c4c5b10a412ea5e245a394c0521ac8fd63
|
[
"Apache-2.0"
] |
permissive
|
ornladios/ADIOS2
|
a34e257b28adb26e6563b800502266ebb0c9088c
|
c8b7b66ed21b03bfb773bd972d5aeaaf10231e67
|
refs/heads/master
| 2023-08-31T18:11:22.186415
| 2023-08-29T20:45:03
| 2023-08-29T20:45:03
| 75,750,830
| 243
| 140
|
Apache-2.0
| 2023-09-14T11:15:00
| 2016-12-06T16:39:55
|
C++
|
UTF-8
|
C
| false
| false
| 26,260
|
c
|
ucx_dp.c
|
/*----------------------------------------------------------------------------
*
* WRF ADIOS2 I/O
* Author: Sameeh Jubran
* Toga Networks, a Huawei Company
* sameeh.jubran@toganetworks.com
* Author: Michael Laufer
* Toga Networks, a Huawei Company
* michael.laufer@toganetworks.com
* Author: Erick Fredj
* Toga Networks, a Huawei Company
* erick.fredj@toganetworks.com
*
* Date: December 20, 2022
*
*----------------------------------------------------------------------------
*/
#include <assert.h>
#include <errno.h>
#include <inttypes.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "adios2/common/ADIOSConfig.h"
#include <atl.h>
#include <evpath.h>
#include <SSTConfig.h>
#include <ucp/api/ucp.h>
#if defined(__has_feature)
#if __has_feature(thread_sanitizer)
#define NO_SANITIZE_THREAD __attribute__((no_sanitize("thread")))
#endif
#endif
#ifndef NO_SANITIZE_THREAD
#define NO_SANITIZE_THREAD
#endif
#include "sst_data.h"
#include "dp_interface.h"
pthread_mutex_t ucx_wsr_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t ucx_ts_mutex = PTHREAD_MUTEX_INITIALIZER;
struct fabric_state
{
ucp_context_h ucp_context;
ucp_worker_h ucp_worker;
ucp_address_t *local_addr;
size_t local_addr_len;
};
/*
* Some conventions:
* `RS` indicates a reader-side item.
* `WS` indicates a writer-side item.
* `WSR` indicates a writer-side per-reader item.
*
* We keep different "stream" structures for the reader side and for the
* writer side. On the writer side, there's actually a "stream"
* per-connected-reader (a WSR_Stream), with the idea that some (many?)
* RDMA transports will require connections/pairing, so we'd need to track
* resources per reader.
*
* Generally the 'contact information' we exchange at init time includes
* the address of the local 'stream' data structure. This address isn't
* particularly useful to the far side, but it can be returned with
* requests to indicate what resource is targeted. For example, when a
* remote memory read request arrives at the writer from the reader, it
* includes the WSR_Stream value that is the address of the writer-side
* per-reader data structure. Upon message arrival, we just cast that
* value back into a pointer.
*
* By design, neither the data plane nor the control plane reference the
* other's symbols directly. The interface between the control plane and
* the data plane is represented by the types and structures defined in
* dp_interface.h and is a set of function pointers and FFS-style
* descriptions of the data structures to be communicated at init time.
* This allows for the future possibility of loading planes at run-time, etc.
*
* This "Ucx" data plane uses control plane functionality to implement
* the ReadRemoteMemory functionality. That is, it both the request to
* read memory and the response which carries the data are actually
* accomplished using the connections and message delivery facilities of
* the control plane, made available here via CP_Services. A real data
* plane would replace one or both of these with RDMA functionality.
*/
static ucs_status_t init_fabric(struct fabric_state *fabric, struct _SstParams *Params,
CP_Services Svcs, void *CP_Stream)
{
ucp_params_t ucp_params;
ucp_worker_params_t worker_params;
ucp_config_t *config;
ucs_status_t status = UCS_ERR_LAST;
memset(&ucp_params, 0, sizeof(ucp_params));
memset(&worker_params, 0, sizeof(worker_params));
/* UCP initialization */
status = ucp_config_read(NULL, NULL, &config);
if (status != UCS_OK)
{
Svcs->verbose(CP_Stream, DPCriticalVerbose,
"UCX Error during ucp_config_read() with: %s.\n", ucs_status_string(status));
return status;
}
ucp_params.field_mask = UCP_PARAM_FIELD_FEATURES;
ucp_params.features = UCP_FEATURE_RMA;
status = ucp_init(&ucp_params, config, &fabric->ucp_context);
if (status != UCS_OK)
{
Svcs->verbose(CP_Stream, DPCriticalVerbose, "UCX Error during ucp_init() with: %s.\n",
ucs_status_string(status));
return status;
}
ucp_config_release(config);
worker_params.field_mask = UCP_WORKER_PARAM_FIELD_THREAD_MODE;
worker_params.thread_mode = UCS_THREAD_MODE_MULTI;
status = ucp_worker_create(fabric->ucp_context, &worker_params, &fabric->ucp_worker);
if (status != UCS_OK)
{
Svcs->verbose(CP_Stream, DPCriticalVerbose,
"UCX Error during ucp_worker_create() with: %s.\n",
ucs_status_string(status));
return status;
}
status =
ucp_worker_get_address(fabric->ucp_worker, &fabric->local_addr, &fabric->local_addr_len);
if (status != UCS_OK)
{
Svcs->verbose(CP_Stream, DPCriticalVerbose,
"UCX Error during ucp_worker_get_address() with: %s.\n",
ucs_status_string(status));
return status;
}
Svcs->verbose(CP_Stream, DPCriticalVerbose, "UCX init Success\n");
return status;
}
static void fini_fabric(struct fabric_state *fabric)
{
ucp_worker_destroy(fabric->ucp_worker);
ucp_cleanup(fabric->ucp_context);
}
typedef struct fabric_state *FabricState;
typedef struct _UcxCompletionHandle
{
ucs_status_ptr_t req;
void *CPStream;
void *Buffer;
size_t Length;
int Rank;
int Pending;
} *UcxCompletionHandle;
typedef struct _UcxBufferHandle
{
void *Block;
size_t rkey_size;
char *rkey;
} *UcxBufferHandle;
typedef struct _UcxBuffer
{
struct _UcxBufferHandle Handle;
uint64_t BufferLen;
uint64_t Offset;
} *UcxBuffer;
typedef struct _Ucx_RS_Stream
{
CManager cm;
void *CP_Stream;
int Rank;
FabricState Fabric;
struct _SstParams *Params;
/* writer info */
int WriterCohortSize;
CP_PeerCohort PeerCohort;
struct _UcxWriterContactInfo *WriterContactInfo;
ucp_ep_h *WriterEP;
} *Ucx_RS_Stream;
typedef struct _TimestepEntry
{
long Timestep;
struct _SstData *Data;
struct _UcxBufferHandle *DP_TimestepInfo;
struct _TimestepEntry *Next;
ucp_mem_h memh;
void *rkey;
size_t rkey_size;
} *TimestepList;
typedef struct _Ucx_WSR_Stream
{
struct _Ucx_WS_Stream *WS_Stream;
CP_PeerCohort PeerCohort;
int ReaderCohortSize;
struct _UcxWriterContactInfo *WriterContactInfo;
} *Ucx_WSR_Stream;
typedef struct _Ucx_WS_Stream
{
CManager cm;
void *CP_Stream;
int Rank;
FabricState Fabric;
TimestepList Timesteps;
int ReaderCount;
Ucx_WSR_Stream *Readers;
} *Ucx_WS_Stream;
typedef struct _UcxReaderContactInfo
{
void *RS_Stream;
} *UcxReaderContactInfo;
typedef struct _UcxWriterContactInfo
{
void *WS_Stream;
size_t Length;
void *Address;
} *UcxWriterContactInfo;
static DP_RS_Stream UcxInitReader(CP_Services Svcs, void *CP_Stream, void **ReaderContactInfoPtr,
struct _SstParams *Params, attr_list WriterContact,
SstStats Stats)
{
Ucx_RS_Stream Stream = malloc(sizeof(struct _Ucx_RS_Stream));
SMPI_Comm comm = Svcs->getMPIComm(CP_Stream);
ucs_status_t status;
memset(Stream, 0, sizeof(*Stream));
Stream->Fabric = calloc(1, sizeof(*Stream->Fabric));
/*
* save the CP_stream value of later use
*/
Stream->CP_Stream = CP_Stream;
SMPI_Comm_rank(comm, &Stream->Rank);
*ReaderContactInfoPtr = NULL;
if (Params)
{
Stream->Params = malloc(sizeof(*Stream->Params));
memcpy(Stream->Params, Params, sizeof(*Params));
}
status = init_fabric(Stream->Fabric, Stream->Params, Svcs, CP_Stream);
if (status != UCS_OK)
{
Svcs->verbose(CP_Stream, DPCriticalVerbose, "Could not find a valid transport fabric.\n");
if (Stream->Params)
{
free(Stream->Params);
}
free(Stream->Fabric);
return NULL;
}
return Stream;
}
static DP_WS_Stream UcxInitWriter(CP_Services Svcs, void *CP_Stream, struct _SstParams *Params,
attr_list DPAttrs, SstStats Stats)
{
Ucx_WS_Stream Stream = malloc(sizeof(struct _Ucx_WS_Stream));
SMPI_Comm comm = Svcs->getMPIComm(CP_Stream);
ucs_status_t status;
memset(Stream, 0, sizeof(struct _Ucx_WS_Stream));
SMPI_Comm_rank(comm, &Stream->Rank);
Stream->Fabric = calloc(1, sizeof(struct fabric_state));
status = init_fabric(Stream->Fabric, Params, Svcs, CP_Stream);
if (status != UCS_OK)
{
Svcs->verbose(CP_Stream, DPCriticalVerbose, "Could not find a valid transport fabric.\n");
return NULL;
}
Stream->CP_Stream = CP_Stream;
return (void *)Stream;
}
static DP_WSR_Stream UcxInitWriterPerReader(CP_Services Svcs, DP_WS_Stream WS_Stream_v,
int readerCohortSize, CP_PeerCohort PeerCohort,
void **providedReaderInfo_v,
void **WriterContactInfoPtr)
{
Ucx_WS_Stream WS_Stream = (Ucx_WS_Stream)WS_Stream_v;
Ucx_WSR_Stream WSR_Stream = malloc(sizeof(*WSR_Stream));
FabricState Fabric = WS_Stream->Fabric;
UcxWriterContactInfo ContactInfo;
WSR_Stream->WS_Stream = WS_Stream; /* pointer to writer struct */
WSR_Stream->PeerCohort = PeerCohort;
WSR_Stream->ReaderCohortSize = readerCohortSize;
/*
* add this writer-side reader-specific stream to the parent writer stream
* structure
*/
pthread_mutex_lock(&ucx_wsr_mutex);
WS_Stream->Readers =
realloc(WS_Stream->Readers, sizeof(*WSR_Stream) * (WS_Stream->ReaderCount + 1));
WS_Stream->Readers[WS_Stream->ReaderCount] = WSR_Stream;
WS_Stream->ReaderCount++;
pthread_mutex_unlock(&ucx_wsr_mutex);
ContactInfo = calloc(1, sizeof(struct _UcxWriterContactInfo));
ContactInfo->WS_Stream = WSR_Stream;
ContactInfo->Length = Fabric->local_addr_len;
ContactInfo->Address = Fabric->local_addr;
WSR_Stream->WriterContactInfo = ContactInfo;
*WriterContactInfoPtr = ContactInfo;
return WSR_Stream;
}
static void UcxProvideWriterDataToReader(CP_Services Svcs, DP_RS_Stream RS_Stream_v,
int writerCohortSize, CP_PeerCohort PeerCohort,
void **providedWriterInfo_v)
{
Ucx_RS_Stream RS_Stream = (Ucx_RS_Stream)RS_Stream_v;
FabricState Fabric = RS_Stream->Fabric;
UcxWriterContactInfo *providedWriterInfo = (UcxWriterContactInfo *)providedWriterInfo_v;
RS_Stream->PeerCohort = PeerCohort;
RS_Stream->WriterCohortSize = writerCohortSize;
RS_Stream->WriterEP = calloc(writerCohortSize, sizeof(*RS_Stream->WriterEP));
/*
* make a copy of writer contact information (original will not be
* preserved)
*/
RS_Stream->WriterContactInfo = malloc(sizeof(struct _UcxWriterContactInfo) * writerCohortSize);
for (int i = 0; i < writerCohortSize; i++)
{
RS_Stream->WriterContactInfo[i].WS_Stream = providedWriterInfo[i]->WS_Stream;
ucp_ep_params_t ep_params;
ep_params.field_mask = UCP_EP_PARAM_FIELD_REMOTE_ADDRESS;
ep_params.address = providedWriterInfo[i]->Address;
ucs_status_t status =
ucp_ep_create(Fabric->ucp_worker, &ep_params, &RS_Stream->WriterEP[i]);
if (status != UCS_OK)
{
Svcs->verbose(RS_Stream->CP_Stream, DPCriticalVerbose,
"UCX Error during ucp_ep_create() with: %s.\n",
ucs_status_string(status));
return;
}
Svcs->verbose(RS_Stream->CP_Stream, DPTraceVerbose,
"Received contact info for WS_stream %p, WSR Rank %d\n",
RS_Stream->WriterContactInfo[i].WS_Stream, i);
}
}
static void *UcxReadRemoteMemory(CP_Services Svcs, DP_RS_Stream Stream_v, int Rank, long Timestep,
size_t Offset, size_t Length, void *Buffer, void *DP_TimestepInfo)
{
Ucx_RS_Stream RS_Stream = (Ucx_RS_Stream)Stream_v;
UcxBufferHandle Info = (UcxBufferHandle)DP_TimestepInfo;
uint8_t *Addr;
UcxCompletionHandle ret = malloc(sizeof(struct _UcxCompletionHandle));
Svcs->verbose(RS_Stream->CP_Stream, DPTraceVerbose,
"Performing remote read of Writer Rank %d at step %d\n", Rank, Timestep);
if (!ret)
{
Svcs->verbose(RS_Stream->CP_Stream, DPCriticalVerbose,
"Failed to allocate memory for UcxCompletionHandle\n");
return (NULL);
}
if (Info)
{
Svcs->verbose(RS_Stream->CP_Stream, DPTraceVerbose,
"Block address is %p, with a key of %.11s, and access "
"key size %zu.\n",
Info->Block, Info->rkey, Info->rkey_size);
}
else
{
Svcs->verbose(RS_Stream->CP_Stream, DPCriticalVerbose, "Timestep info is null\n");
free(ret);
return NULL;
}
ret->CPStream = RS_Stream;
ret->Buffer = Buffer;
ret->Rank = Rank;
ret->Length = Length;
ret->Pending = 1;
Addr = (uint8_t *)Info->Block + Offset;
Svcs->verbose(RS_Stream->CP_Stream, DPTraceVerbose,
"Remote read target is Rank %d, EP = %p (Offset = %zi, Length = %zi)\n", Rank,
RS_Stream->WriterEP[Rank], Offset, Length);
ucp_rkey_h rkey_p;
ucs_status_t status = ucp_ep_rkey_unpack(RS_Stream->WriterEP[Rank], Info->rkey, &rkey_p);
if (status != UCS_OK)
{
Svcs->verbose(RS_Stream->CP_Stream, DPCriticalVerbose,
"UCX Error during ucp_ep_rkey_unpack() with: %s.\n",
ucs_status_string(status));
free(ret);
return NULL;
}
ucp_request_param_t param;
param.op_attr_mask = 0;
ret->req =
ucp_get_nbx(RS_Stream->WriterEP[Rank], Buffer, Length, (uint64_t)Addr, rkey_p, ¶m);
status = UCS_PTR_STATUS(ret->req);
if (status != UCS_OK && status != UCS_INPROGRESS)
{
Svcs->verbose(RS_Stream->CP_Stream, DPCriticalVerbose,
"UCX Error during ucp_get_nbx() with: %s.\n", ucs_status_string(status));
free(ret);
return NULL;
}
Svcs->verbose(RS_Stream->CP_Stream, DPTraceVerbose,
"Posted RDMA get for Writer Rank %d for handle %p\n", Rank, (void *)ret);
return (ret);
}
static void UcxNotifyConnFailure(CP_Services Svcs, DP_RS_Stream Stream_v, int FailedPeerRank)
{
/* DP_RS_Stream is the return from InitReader */
Ucx_RS_Stream Stream = (Ucx_RS_Stream)Stream_v;
Svcs->verbose(Stream->CP_Stream, DPTraceVerbose,
"received notification that writer peer "
"%d has failed, failing any pending "
"requests\n",
FailedPeerRank);
}
/*
* UcxWaitForCompletion should return 1 if successful, but 0 if the reads
* failed for some reason or were aborted by RdmaNotifyConnFailure()
*/
static int UcxWaitForCompletion(CP_Services Svcs, void *Handle_v)
{
UcxCompletionHandle Handle = (UcxCompletionHandle)Handle_v;
Ucx_RS_Stream Stream = Handle->CPStream;
ucs_status_t status = UCS_ERR_LAST;
if (UCS_PTR_IS_PTR(Handle->req))
{
do
{
ucp_worker_progress(Stream->Fabric->ucp_worker);
status = ucp_request_check_status(Handle->req);
} while (status == UCS_INPROGRESS);
// check if status is Okay here and free the request
if (status == UCS_OK)
ucp_request_free(Handle->req);
}
else if (UCS_PTR_STATUS(Handle->req) != UCS_OK)
{
Svcs->verbose(Stream->CP_Stream, DPTraceVerbose, "RPC failed, not a pointer");
}
else
{ // UCS_OK request completed immediately. Call ucx callback.
status = UCS_OK;
}
if (status == UCS_OK)
{
free(Handle);
return 1;
}
return 0;
}
static void UcxProvideTimestep(CP_Services Svcs, DP_WS_Stream Stream_v, struct _SstData *Data,
struct _SstData *LocalMetadata, long Timestep,
void **TimestepInfoPtr)
{
Ucx_WS_Stream Stream = (Ucx_WS_Stream)Stream_v;
TimestepList Entry = malloc(sizeof(struct _TimestepEntry));
UcxBufferHandle Info = malloc(sizeof(struct _UcxBufferHandle));
FabricState Fabric = Stream->Fabric;
ucs_status_t status;
Entry->Data = malloc(sizeof(*Data));
memcpy(Entry->Data, Data, sizeof(*Data));
Entry->Timestep = Timestep;
Entry->DP_TimestepInfo = Info;
ucp_mem_map_params_t mem_map_params;
mem_map_params.field_mask = UCP_MEM_MAP_PARAM_FIELD_ADDRESS | UCP_MEM_MAP_PARAM_FIELD_LENGTH |
UCP_MEM_MAP_PARAM_FIELD_FLAGS;
mem_map_params.address = Data->block;
mem_map_params.length = Data->DataSize;
mem_map_params.flags = 0;
status = ucp_mem_map(Fabric->ucp_context, &mem_map_params, &Entry->memh);
if (status != UCS_OK)
{
Svcs->verbose(Stream->CP_Stream, DPCriticalVerbose,
"UCX Error during ucp_mem_map() with: %s. while providing timestep "
"data with block %p and access key %d.\n",
ucs_status_string(status), Info->Block, Info->rkey);
return;
}
ucp_mem_attr_t mem_attr;
mem_attr.field_mask = UCP_MEM_ATTR_FIELD_ADDRESS;
status = ucp_mem_query(Entry->memh, &mem_attr);
if (status != UCS_OK)
{
Svcs->verbose(Stream->CP_Stream, DPCriticalVerbose,
"UCX Error during ucp_mem_query() with: %s. while providing "
"timestep data with block %p and access key %d.\n",
ucs_status_string(status), Info->Block, Info->rkey);
return;
}
Data->block = mem_attr.address;
status = ucp_rkey_pack(Fabric->ucp_context, Entry->memh, &Entry->rkey, &Entry->rkey_size);
if (status != UCS_OK)
{
Svcs->verbose(Stream->CP_Stream, DPCriticalVerbose,
"UCX Error during ucp_rkey_pack() with: %s. while providing "
"timestep data with block %p and access key %d.\n",
ucs_status_string(status), Info->Block, Info->rkey);
return;
}
pthread_mutex_lock(&ucx_ts_mutex);
Entry->Next = Stream->Timesteps;
Stream->Timesteps = Entry;
Info->rkey = Entry->rkey;
Info->rkey_size = Entry->rkey_size;
pthread_mutex_unlock(&ucx_ts_mutex);
Info->Block = (uint8_t *)Data->block;
Svcs->verbose(Stream->CP_Stream, DPTraceVerbose,
"Providing timestep data with block %p and access key %d\n", Info->Block,
Info->rkey);
*TimestepInfoPtr = Info;
}
static void UcxReleaseTimestep(CP_Services Svcs, DP_WS_Stream Stream_v, long Timestep)
{
Ucx_WS_Stream Stream = (Ucx_WS_Stream)Stream_v;
FabricState Fabric = Stream->Fabric;
TimestepList *List = &Stream->Timesteps;
TimestepList ReleaseTSL;
Svcs->verbose(Stream->CP_Stream, DPTraceVerbose, "Releasing timestep %ld\n", Timestep);
pthread_mutex_lock(&ucx_ts_mutex);
while ((*List) && (*List)->Timestep != Timestep)
{
List = &((*List)->Next);
}
if ((*List) == NULL)
{
/*
* Shouldn't ever get here because we should never release a
* timestep that we don't have.
*/
Svcs->verbose(Stream->CP_Stream, DPCriticalVerbose,
"Failed to release Timestep %ld, not found\n", Timestep);
assert(0);
}
ReleaseTSL = *List;
*List = ReleaseTSL->Next;
pthread_mutex_unlock(&ucx_ts_mutex);
ucs_status_t status = ucp_mem_unmap(Fabric->ucp_context, ReleaseTSL->memh);
if (status != UCS_OK)
{
Svcs->verbose(Stream->CP_Stream, DPCriticalVerbose, "UCX Error during ucp_mem_unmap: %s.\n",
ucs_status_string(status));
return;
}
// Free Allocated buffer for timestep info
if (ReleaseTSL->DP_TimestepInfo)
{
free(ReleaseTSL->DP_TimestepInfo);
}
}
static void UcxDestroyReader(CP_Services Svcs, DP_RS_Stream RS_Stream_v)
{
Ucx_RS_Stream RS_Stream = (Ucx_RS_Stream)RS_Stream_v;
Svcs->verbose(RS_Stream->CP_Stream, DPTraceVerbose, "Tearing down RDMA state on reader.\n");
if (RS_Stream->Fabric)
{
fini_fabric(RS_Stream->Fabric);
}
free(RS_Stream->WriterContactInfo);
free(RS_Stream);
}
static void UcxDestroyWriterPerReader(CP_Services Svcs, DP_WSR_Stream WSR_Stream_v)
{
Ucx_WSR_Stream WSR_Stream = {0};
memcpy(&WSR_Stream, &WSR_Stream_v, sizeof(Ucx_WSR_Stream));
Ucx_WS_Stream WS_Stream = WSR_Stream->WS_Stream;
pthread_mutex_lock(&ucx_wsr_mutex);
for (int i = 0; i < WS_Stream->ReaderCount; i++)
{
if (WS_Stream->Readers[i] == WSR_Stream)
{
WS_Stream->Readers[i] = WS_Stream->Readers[WS_Stream->ReaderCount - 1];
break;
}
}
WS_Stream->Readers =
realloc(WS_Stream->Readers, sizeof(*WSR_Stream) * (WS_Stream->ReaderCount - 1));
WS_Stream->ReaderCount--;
pthread_mutex_unlock(&ucx_wsr_mutex);
if (WSR_Stream->WriterContactInfo)
{
free(WSR_Stream->WriterContactInfo);
}
free(WSR_Stream);
}
static FMField UcxReaderContactList[] = {
{"reader_ID", "integer", sizeof(void *), FMOffset(UcxReaderContactInfo, RS_Stream)},
{NULL, NULL, 0, 0}};
static FMStructDescRec UcxReaderContactStructs[] = {
{"UcxReaderContactInfo", UcxReaderContactList, sizeof(struct _UcxReaderContactInfo), NULL},
{NULL, NULL, 0, NULL}};
static FMField UcxBufferHandleList[] = {
{"Block", "integer", sizeof(void *), FMOffset(UcxBufferHandle, Block)},
{"rkey_size", "integer", sizeof(size_t), FMOffset(UcxBufferHandle, rkey_size)},
{"rkey", "char[rkey_size]", sizeof(char), FMOffset(UcxBufferHandle, rkey)},
{NULL, NULL, 0, 0}};
static FMStructDescRec UcxBufferHandleStructs[] = {
{"UcxBufferHandle", UcxBufferHandleList, sizeof(struct _UcxBufferHandle), NULL},
{NULL, NULL, 0, NULL}};
static void UcxDestroyWriter(CP_Services Svcs, DP_WS_Stream WS_Stream_v)
{
Ucx_WS_Stream WS_Stream = (Ucx_WS_Stream)WS_Stream_v;
long Timestep;
Svcs->verbose(WS_Stream->CP_Stream, DPTraceVerbose,
"Releasing reader-specific state for remaining readers.\n");
while (WS_Stream->ReaderCount > 0)
{
UcxDestroyWriterPerReader(Svcs, WS_Stream->Readers[0]);
}
Svcs->verbose(WS_Stream->CP_Stream, DPTraceVerbose, "Releasing remaining timesteps.\n");
pthread_mutex_lock(&ucx_ts_mutex);
while (WS_Stream->Timesteps)
{
Timestep = WS_Stream->Timesteps->Timestep;
pthread_mutex_unlock(&ucx_ts_mutex);
UcxReleaseTimestep(Svcs, WS_Stream, Timestep);
pthread_mutex_lock(&ucx_ts_mutex);
}
pthread_mutex_unlock(&ucx_ts_mutex);
Svcs->verbose(WS_Stream->CP_Stream, DPTraceVerbose, "Tearing down RDMA state on writer.\n");
if (WS_Stream->Fabric)
{
fini_fabric(WS_Stream->Fabric);
}
free(WS_Stream->Fabric);
free(WS_Stream);
}
static FMField UcxWriterContactList[] = {
{"writer_ID", "integer", sizeof(void *), FMOffset(UcxWriterContactInfo, WS_Stream)},
{"Length", "integer", sizeof(int), FMOffset(UcxWriterContactInfo, Length)},
{"Address", "integer[Length]", sizeof(char), FMOffset(UcxWriterContactInfo, Address)},
{NULL, NULL, 0, 0}};
static FMStructDescRec UcxWriterContactStructs[] = {
{"UcxWriterContactInfo", UcxWriterContactList, sizeof(struct _UcxWriterContactInfo), NULL},
{NULL, NULL, 0, NULL}};
static struct _CP_DP_Interface UcxDPInterface = {0};
static int UcxGetPriority(CP_Services Svcs, void *CP_Stream, struct _SstParams *Params)
{
/* TODO: Improve priority algorithm */
int ux_dp_priority = 10;
return ux_dp_priority;
}
/* If UcxGetPriority has allocated resources or initialized something
* that needs to be cleaned up, RdmaUnGetPriority should undo that
* operation.
*/
static void UcxUnGetPriority(CP_Services Svcs, void *CP_Stream)
{
Svcs->verbose(CP_Stream, DPPerStepVerbose, "UCX Dataplane unloading\n");
}
static void UcxTimestepArrived(CP_Services Svcs, DP_RS_Stream Stream_v, long Timestep,
SstPreloadModeType PreloadMode)
{
Ucx_RS_Stream Stream = (Ucx_RS_Stream)Stream_v;
Svcs->verbose(Stream->CP_Stream, DPTraceVerbose, "%s with Timestep = %li, PreloadMode = %d\n",
__func__, Timestep, PreloadMode);
}
extern NO_SANITIZE_THREAD CP_DP_Interface LoadUcxDP()
{
UcxDPInterface.DPName = "ucx";
UcxDPInterface.ReaderContactFormats = UcxReaderContactStructs;
UcxDPInterface.WriterContactFormats = UcxWriterContactStructs;
UcxDPInterface.TimestepInfoFormats = UcxBufferHandleStructs;
UcxDPInterface.initReader = UcxInitReader;
UcxDPInterface.initWriter = UcxInitWriter;
UcxDPInterface.initWriterPerReader = UcxInitWriterPerReader;
UcxDPInterface.provideWriterDataToReader = UcxProvideWriterDataToReader;
UcxDPInterface.readRemoteMemory = UcxReadRemoteMemory;
UcxDPInterface.waitForCompletion = UcxWaitForCompletion;
UcxDPInterface.notifyConnFailure = UcxNotifyConnFailure;
UcxDPInterface.provideTimestep = UcxProvideTimestep;
UcxDPInterface.readerRegisterTimestep = NULL;
UcxDPInterface.releaseTimestep = UcxReleaseTimestep;
UcxDPInterface.readerReleaseTimestep = NULL;
UcxDPInterface.WSRreadPatternLocked = NULL;
UcxDPInterface.RSreadPatternLocked = NULL;
UcxDPInterface.RSReleaseTimestep = NULL;
UcxDPInterface.timestepArrived = UcxTimestepArrived;
UcxDPInterface.destroyReader = UcxDestroyReader;
UcxDPInterface.destroyWriter = UcxDestroyWriter;
UcxDPInterface.destroyWriterPerReader = UcxDestroyWriterPerReader;
UcxDPInterface.getPriority = UcxGetPriority;
UcxDPInterface.unGetPriority = UcxUnGetPriority;
return &UcxDPInterface;
}
|
3df5912ee2ee977e2bd9ff9b4c25e24b92e8b927
|
55540f3e86f1d5d86ef6b5d295a63518e274efe3
|
/components/network/ble/blestack/src/services/oad/oad.h
|
a4e93f994ce39e77312d5321d6b59d94084604d7
|
[
"Apache-2.0"
] |
permissive
|
bouffalolab/bl_iot_sdk
|
bc5eaf036b70f8c65dd389439062b169f8d09daa
|
b90664de0bd4c1897a9f1f5d9e360a9631d38b34
|
refs/heads/master
| 2023-08-31T03:38:03.369853
| 2023-08-16T08:50:33
| 2023-08-18T09:13:27
| 307,347,250
| 244
| 101
|
Apache-2.0
| 2023-08-28T06:29:02
| 2020-10-26T11:16:30
|
C
|
UTF-8
|
C
| false
| false
| 2,064
|
h
|
oad.h
|
#ifndef __OAD_H__
#define __OAD_H__
#include "types.h"
#include "hci_host.h"
#include "work_q.h"
#define LOCAL_MANU_CODE 0x2c00
#define LOCAL_FILE_VER 00000001
#define OAD_OPCODE_SIZE 1
//00070000-0745-4650-8d93-df59be2fc10a
#define BT_UUID_OAD BT_UUID_DECLARE_128(BT_UUID_128_ENCODE(0x00070000, 0x0745, 0x4650, 0x8d93, 0xdf59be2fc10a))
//00070001-0745-4650-8d93-df59be2fc10a
#define BT_UUID_OAD_DATA_IN BT_UUID_DECLARE_128(BT_UUID_128_ENCODE(0x00070001, 0x0745, 0x4650, 0x8d93, 0xdf59be2fc10a))
//00070002-0745-4650-8d93-df59be2fc10a
#define BT_UUID_OAD_DATA_OUT BT_UUID_DECLARE_128(BT_UUID_128_ENCODE(0x00070002, 0x0745, 0x4650, 0x8d93, 0xdf59be2fc10a))
enum{
OAD_SUCC = 0x00,
OAD_ABORT,
OAD_INVALID_IMAG,
OAD_REQ_MORE_DATA,
OAD_MALORMED_CMD,
OAD_UPGRD_CMPLT,
OAD_CHECK_HASH256_FAIL,
};
enum{
OAD_CMD_IMAG_IDENTITY = 0x00,
OAD_CMD_IMAG_BLOCK_REQ,
OAD_CMD_IMAG_BLOCK_RESP,
OAD_CMD_IMAG_UPGRD_END,
OAD_CMD_IMAG_INFO,
};
struct oad_file_info{
u16_t manu_code;
u32_t file_ver;
} __packed;
#if defined(CONFIG_BT_SETTINGS)
struct oad_ef_info{
struct oad_file_info file_info;
u32_t file_offset;
u32_t last_wflash_addr;
u32_t upgrd_crc32;
}__packed;
#endif
struct oad_env_tag{
struct oad_file_info file_info;
u32_t cur_file_size;
u32_t upgrd_file_ver;
u32_t upgrd_file_size;
u32_t upgrd_offset;
u32_t upgrd_crc32;
struct k_delayed_work upgrd_work;
u32_t new_img_addr;
u32_t w_img_end_addr;
u32_t hosal_offset;
};
struct oad_image_identity_t{
struct oad_file_info file_info;
u32_t file_size;
u32_t crc32;
} __packed;
struct oad_block_req_t{
struct oad_file_info file_info;
u32_t file_offset;
} __packed;
#define OAD_BLK_RSP_DATA_OFFSET 12
struct oad_block_rsp_t{
uint8_t status;
struct oad_file_info file_info;
u32_t file_offset;
u8_t data_size;
u8_t *pdata;
} __packed;
struct oad_upgrd_end_t{
u8_t status;
struct oad_file_info file_info;
} __packed;
#endif //__OAD_H__
|
e1d2274dac5f498c895bfcdac3e3f72f3bac8491
|
a12b448f44beb4d521cb7e31677281f41df35f0b
|
/3rdParty/isl/isl_id_private.h
|
1d903c8e59e855cce9f8c68dbb44e148169ad53b
|
[
"MIT",
"LGPL-2.0-or-later"
] |
permissive
|
Tiramisu-Compiler/tiramisu
|
d45f65dd9c35f643b3531ec79df1203c7ea3371d
|
f13e480f0ddb142cec371b7d7431a41d8ca885ec
|
refs/heads/master
| 2023-08-25T12:21:26.889736
| 2023-05-09T18:40:52
| 2023-05-09T18:40:52
| 58,378,976
| 906
| 168
|
MIT
| 2023-09-08T11:47:06
| 2016-05-09T13:33:51
|
C++
|
UTF-8
|
C
| false
| false
| 835
|
h
|
isl_id_private.h
|
/*
* Copyright 2008-2009 Katholieke Universiteit Leuven
*
* Use of this software is governed by the MIT license
*
* Written by Sven Verdoolaege, K.U.Leuven, Departement
* Computerwetenschappen, Celestijnenlaan 200A, B-3001 Leuven, Belgium
*/
#ifndef ISL_ID_PRIVATE_H
#define ISL_ID_PRIVATE_H
#include <isl/id.h>
/* Represent a name and/or user pointer.
*
* If "free_user" is set, then it will be called on "user" when
* the last instance of the isl_id is freed.
*/
struct isl_id {
int ref;
isl_ctx *ctx;
const char *name;
void *user;
uint32_t hash;
__isl_give void (*free_user)(void *user);
};
#undef EL
#define EL isl_id
#include <isl_list_templ.h>
uint32_t isl_hash_id(uint32_t hash, __isl_keep isl_id *id);
int isl_id_cmp(__isl_keep isl_id *id1, __isl_keep isl_id *id2);
extern isl_id isl_id_none;
#endif
|
91c59b263d0520d87dc2f89127e2a748c919addf
|
0744dcc5394cebf57ebcba343747af6871b67017
|
/os/wqueue/wqueue.h
|
8938b8376167a6907855273db02701344b68ef01
|
[
"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,415
|
h
|
wqueue.h
|
/****************************************************************************
*
* 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.
*
****************************************************************************/
/****************************************************************************
* wqueue/wqueue.h
*
* Copyright (C) 2014 Gregory Nutt. All rights reserved.
* Author: Gregory Nutt <gnutt@nuttx.org>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name NuttX nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#ifndef __OS_WQUEUE_WQUEUE_H
#define __OS_WQUEUE_WQUEUE_H
#include <tinyara/config.h>
#include <sys/types.h>
#include <stdbool.h>
#include <queue.h>
#include <semaphore.h>
#include <tinyara/wqueue.h>
#ifdef CONFIG_SCHED_WORKQUEUE
/****************************************************************************
* Public Type Definitions
****************************************************************************/
/* This represents one worker */
struct worker_s {
pid_t pid; /* The task ID of the worker thread */
volatile bool busy; /* True: Worker is not available */
};
/* This structure defines the state of work queue */
struct wqueue_s {
struct dq_queue_s q; /* The queue of pending work */
struct worker_s worker[1]; /* Describes a worker thread */
};
/* This structure defines the state of one high-priority work queue. This
* structure must be cast-compatible with kwork_wqueue_s.
*/
#ifdef CONFIG_SCHED_HPWORK
struct hp_wqueue_s {
struct dq_queue_s q; /* The queue of pending work */
struct worker_s worker[1]; /* Describes the single high priority worker */
};
#endif
/* This structure defines the state of one high-priority work queue. This
* structure must be cast compatible with kwork_wqueue_s
*/
#ifdef CONFIG_SCHED_LPWORK
struct lp_wqueue_s {
struct dq_queue_s q; /* The queue of pending work */
/* Describes each thread in the low priority queue's thread pool */
struct worker_s worker[CONFIG_SCHED_LPNTHREADS];
};
#endif
/****************************************************************************
* Public Data
****************************************************************************/
/* The state of the user mode work queue */
struct wqueue_s *get_usrwork(void);
#ifdef CONFIG_SCHED_HPWORK
struct hp_wqueue_s *get_hpwork(void);
#endif
#ifdef CONFIG_SCHED_LPWORK
struct lp_wqueue_s *get_lpwork(void);
#endif
/* This semaphore/mutex supports exclusive access to the user-mode work queue */
#ifdef CONFIG_BUILD_PROTECTED
sem_t *get_usrsem(void);
#else
pthread_mutex_t *get_usrmutex(void);
#endif
/****************************************************************************
* Public Function Prototypes
****************************************************************************/
/****************************************************************************
* Name: work_lock
*
* Description:
* Lock the user-mode work queue.
*
* Input parameters:
* None
*
* Returned Value:
* Zero (OK) on success, a negated errno on failure. This error may be
* reported:
*
* -EINTR - Wait was interrupted by a signal
*
****************************************************************************/
#if defined(CONFIG_SCHED_USRWORK) && !defined(__KERNEL__)
int work_lock(void);
#endif
/****************************************************************************
* Name: work_unlock
*
* Description:
* Unlock the user-mode work queue.
*
* Input parameters:
* None
*
* Returned Value:
* None
*
****************************************************************************/
#if defined(CONFIG_SCHED_USRWORK) && !defined(__KERNEL__)
void work_unlock(void);
#endif
/****************************************************************************
* Name: work_qcancel
*
* Description:
* Cancel previously queued work. This removes work from the work queue.
* After work has been cancelled, it may be re-queue by calling work_queue()
* again.
*
* Input parameters:
* qid - The work queue ID
* work - The previously queue work structure to cancel
*
* Returned Value:
* Zero (OK) on success, a negated errno on failure. This error may be
* reported:
*
* -ENOENT - There is no such work queued.
* -EINVAL - An invalid work queue was specified
*
****************************************************************************/
int work_qcancel(FAR struct wqueue_s *wqueue, FAR struct work_s *work);
/****************************************************************************
* Name: work_qqueue
*
* Description:
* Queue work to be performed at a later time. All queued work will be
* performed on the worker thread of of execution (not the caller's).
*
* The work structure is allocated by caller, but completely managed by
* the work queue logic. The caller should never modify the contents of
* the work queue structure; the caller should not call work_queue()
* again until either (1) the previous work has been performed and removed
* from the queue, or (2) work_cancel() has been called to cancel the work
* and remove it from the work queue.
*
* Input parameters:
* qid - The work queue ID (index)
* work - The work structure to queue
* worker - The worker callback to be invoked. The callback will invoked
* on the worker thread of execution.
* arg - The argument that will be passed to the workder callback when
* int is invoked.
* delay - Delay (in clock ticks) from the time queue until the worker
* is invoked. Zero means to perform the work immediately.
*
* Returned Value:
* Zero (OK) on success, a negated errno on failure.
*
****************************************************************************/
int work_qqueue(FAR struct wqueue_s *wqueue, FAR struct work_s *work, worker_t worker, FAR void *arg, clock_t delay);
/****************************************************************************
* Name: work_process
*
* Description:
* This is the logic that performs actions placed on any work list. This
* logic is the common underlying logic to all work queues. This logic is
* part of the internal implementation of each work queue; it should not
* be called from application level logic.
*
* Input parameters:
* wqueue - Describes the work queue to be processed
*
* Returned Value:
* None
*
****************************************************************************/
void work_process(FAR struct wqueue_s *wqueue, int wdx);
/****************************************************************************
* Name: work_qsignal
*
* Description:
* Signal the worker thread to process the work queue now. This function
* is used internally by the work logic but could also be used by the
* user to force an immediate re-assessment of pending work.
*
* Input parameters:
* pid - The work queue pid
*
* Returned Value:
* Zero on success, a negated errno on failure
*
****************************************************************************/
int work_qsignal(pid_t pid);
#endif /* CONFIG_SCHED_WORKQUEUE */
#endif /* __OS_WQUEUE_WQUEUE_H */
|
19ecdbfbe693db1e6ee08a120e70f485926e489d
|
321d11eaee885ceb3a74db0a062f9bbdf282148c
|
/apps/srp.c
|
a9466f830289b018af5267d0ea2de9b310730cd3
|
[
"Apache-2.0",
"OpenSSL",
"LicenseRef-scancode-proprietary-license"
] |
permissive
|
openssl/openssl
|
75691ebaae957793f2ff0673f77545277dfb3988
|
5318c012885a5382eadbf95aa9c1d35664bca819
|
refs/heads/master
| 2023-09-03T15:22:52.727123
| 2023-09-01T07:10:49
| 2023-09-02T14:30:01
| 7,634,677
| 24,148
| 11,569
|
Apache-2.0
| 2023-09-14T19:48:11
| 2013-01-15T22:34:48
|
C
|
UTF-8
|
C
| false
| false
| 21,131
|
c
|
srp.c
|
/*
* Copyright 2004-2021 The OpenSSL Project Authors. All Rights Reserved.
* Copyright (c) 2004, EdelKey Project. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*
* Originally written by Christophe Renou and Peter Sylvester,
* for the EdelKey project.
*/
/* SRP is deprecated, so we're going to have to use some deprecated APIs */
#define OPENSSL_SUPPRESS_DEPRECATED
#include <openssl/opensslconf.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/conf.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/txt_db.h>
#include <openssl/buffer.h>
#include <openssl/srp.h>
#include "apps.h"
#include "progs.h"
#define BASE_SECTION "srp"
#define CONFIG_FILE "openssl.cnf"
#define ENV_DATABASE "srpvfile"
#define ENV_DEFAULT_SRP "default_srp"
static int get_index(CA_DB *db, char *id, char type)
{
char **pp;
int i;
if (id == NULL)
return -1;
if (type == DB_SRP_INDEX) {
for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
pp = sk_OPENSSL_PSTRING_value(db->db->data, i);
if (pp[DB_srptype][0] == DB_SRP_INDEX
&& strcmp(id, pp[DB_srpid]) == 0)
return i;
}
} else {
for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
pp = sk_OPENSSL_PSTRING_value(db->db->data, i);
if (pp[DB_srptype][0] != DB_SRP_INDEX
&& strcmp(id, pp[DB_srpid]) == 0)
return i;
}
}
return -1;
}
static void print_entry(CA_DB *db, int indx, int verbose, char *s)
{
if (indx >= 0 && verbose) {
int j;
char **pp = sk_OPENSSL_PSTRING_value(db->db->data, indx);
BIO_printf(bio_err, "%s \"%s\"\n", s, pp[DB_srpid]);
for (j = 0; j < DB_NUMBER; j++) {
BIO_printf(bio_err, " %d = \"%s\"\n", j, pp[j]);
}
}
}
static void print_index(CA_DB *db, int indexindex, int verbose)
{
print_entry(db, indexindex, verbose, "g N entry");
}
static void print_user(CA_DB *db, int userindex, int verbose)
{
if (verbose > 0) {
char **pp = sk_OPENSSL_PSTRING_value(db->db->data, userindex);
if (pp[DB_srptype][0] != 'I') {
print_entry(db, userindex, verbose, "User entry");
print_entry(db, get_index(db, pp[DB_srpgN], 'I'), verbose,
"g N entry");
}
}
}
static int update_index(CA_DB *db, char **row)
{
char **irow;
int i;
irow = app_malloc(sizeof(*irow) * (DB_NUMBER + 1), "row pointers");
for (i = 0; i < DB_NUMBER; i++)
irow[i] = row[i];
irow[DB_NUMBER] = NULL;
if (!TXT_DB_insert(db->db, irow)) {
BIO_printf(bio_err, "failed to update srpvfile\n");
BIO_printf(bio_err, "TXT_DB error number %ld\n", db->db->error);
OPENSSL_free(irow);
return 0;
}
return 1;
}
static char *lookup_conf(const CONF *conf, const char *section, const char *tag)
{
char *entry = NCONF_get_string(conf, section, tag);
if (entry == NULL)
BIO_printf(bio_err, "variable lookup failed for %s::%s\n", section, tag);
return entry;
}
static char *srp_verify_user(const char *user, const char *srp_verifier,
char *srp_usersalt, const char *g, const char *N,
const char *passin, int verbose)
{
char password[1025];
PW_CB_DATA cb_tmp;
char *verifier = NULL;
char *gNid = NULL;
int len;
cb_tmp.prompt_info = user;
cb_tmp.password = passin;
len = password_callback(password, sizeof(password)-1, 0, &cb_tmp);
if (len > 0) {
password[len] = 0;
if (verbose)
BIO_printf(bio_err,
"Validating\n user=\"%s\"\n srp_verifier=\"%s\"\n srp_usersalt=\"%s\"\n g=\"%s\"\n N=\"%s\"\n",
user, srp_verifier, srp_usersalt, g, N);
if (verbose > 1)
BIO_printf(bio_err, "Pass %s\n", password);
OPENSSL_assert(srp_usersalt != NULL);
if ((gNid = SRP_create_verifier(user, password, &srp_usersalt,
&verifier, N, g)) == NULL) {
BIO_printf(bio_err, "Internal error validating SRP verifier\n");
} else {
if (strcmp(verifier, srp_verifier))
gNid = NULL;
OPENSSL_free(verifier);
}
OPENSSL_cleanse(password, len);
}
return gNid;
}
static char *srp_create_user(char *user, char **srp_verifier,
char **srp_usersalt, char *g, char *N,
char *passout, int verbose)
{
char password[1025];
PW_CB_DATA cb_tmp;
char *gNid = NULL;
char *salt = NULL;
int len;
cb_tmp.prompt_info = user;
cb_tmp.password = passout;
len = password_callback(password, sizeof(password)-1, 1, &cb_tmp);
if (len > 0) {
password[len] = 0;
if (verbose)
BIO_printf(bio_err, "Creating\n user=\"%s\"\n g=\"%s\"\n N=\"%s\"\n",
user, g, N);
if ((gNid = SRP_create_verifier(user, password, &salt,
srp_verifier, N, g)) == NULL) {
BIO_printf(bio_err, "Internal error creating SRP verifier\n");
} else {
*srp_usersalt = salt;
}
OPENSSL_cleanse(password, len);
if (verbose > 1)
BIO_printf(bio_err, "gNid=%s salt =\"%s\"\n verifier =\"%s\"\n",
gNid, salt, *srp_verifier);
}
return gNid;
}
typedef enum OPTION_choice {
OPT_COMMON,
OPT_VERBOSE, OPT_CONFIG, OPT_NAME, OPT_SRPVFILE, OPT_ADD,
OPT_DELETE, OPT_MODIFY, OPT_LIST, OPT_GN, OPT_USERINFO,
OPT_PASSIN, OPT_PASSOUT, OPT_ENGINE, OPT_R_ENUM, OPT_PROV_ENUM
} OPTION_CHOICE;
const OPTIONS srp_options[] = {
{OPT_HELP_STR, 1, '-', "Usage: %s [options] [user...]\n"},
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
{"verbose", OPT_VERBOSE, '-', "Talk a lot while doing things"},
{"config", OPT_CONFIG, '<', "A config file"},
{"name", OPT_NAME, 's', "The particular srp definition to use"},
#ifndef OPENSSL_NO_ENGINE
{"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
#endif
OPT_SECTION("Action"),
{"add", OPT_ADD, '-', "Add a user and SRP verifier"},
{"modify", OPT_MODIFY, '-', "Modify the SRP verifier of an existing user"},
{"delete", OPT_DELETE, '-', "Delete user from verifier file"},
{"list", OPT_LIST, '-', "List users"},
OPT_SECTION("Configuration"),
{"srpvfile", OPT_SRPVFILE, '<', "The srp verifier file name"},
{"gn", OPT_GN, 's', "Set g and N values to be used for new verifier"},
{"userinfo", OPT_USERINFO, 's', "Additional info to be set for user"},
{"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
{"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
OPT_R_OPTIONS,
OPT_PROV_OPTIONS,
OPT_PARAMETERS(),
{"user", 0, 0, "Username(s) to process (optional)"},
{NULL}
};
int srp_main(int argc, char **argv)
{
ENGINE *e = NULL;
CA_DB *db = NULL;
CONF *conf = NULL;
int gNindex = -1, maxgN = -1, ret = 1, errors = 0, verbose = 0, i;
int doupdatedb = 0, mode = OPT_ERR;
char *user = NULL, *passinarg = NULL, *passoutarg = NULL;
char *passin = NULL, *passout = NULL, *gN = NULL, *userinfo = NULL;
char *section = NULL;
char **gNrow = NULL, *configfile = NULL;
char *srpvfile = NULL, **pp, *prog;
OPTION_CHOICE o;
prog = opt_init(argc, argv, srp_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(srp_options);
ret = 0;
goto end;
case OPT_VERBOSE:
verbose++;
break;
case OPT_CONFIG:
configfile = opt_arg();
break;
case OPT_NAME:
section = opt_arg();
break;
case OPT_SRPVFILE:
srpvfile = opt_arg();
break;
case OPT_ADD:
case OPT_DELETE:
case OPT_MODIFY:
case OPT_LIST:
if (mode != OPT_ERR) {
BIO_printf(bio_err,
"%s: Only one of -add/-delete/-modify/-list\n",
prog);
goto opthelp;
}
mode = o;
break;
case OPT_GN:
gN = opt_arg();
break;
case OPT_USERINFO:
userinfo = opt_arg();
break;
case OPT_PASSIN:
passinarg = opt_arg();
break;
case OPT_PASSOUT:
passoutarg = opt_arg();
break;
case OPT_ENGINE:
e = setup_engine(opt_arg(), 0);
break;
case OPT_R_CASES:
if (!opt_rand(o))
goto end;
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
}
}
/* Optional parameters are usernames. */
argc = opt_num_rest();
argv = opt_rest();
if (!app_RAND_load())
goto end;
if (srpvfile != NULL && configfile != NULL) {
BIO_printf(bio_err,
"-srpvfile and -configfile cannot be specified together.\n");
goto end;
}
if (mode == OPT_ERR) {
BIO_printf(bio_err,
"Exactly one of the options -add, -delete, -modify -list must be specified.\n");
goto opthelp;
}
if (mode == OPT_DELETE || mode == OPT_MODIFY || mode == OPT_ADD) {
if (argc == 0) {
BIO_printf(bio_err, "Need at least one user.\n");
goto opthelp;
}
user = *argv++;
}
if ((passinarg != NULL || passoutarg != NULL) && argc != 1) {
BIO_printf(bio_err,
"-passin, -passout arguments only valid with one user.\n");
goto opthelp;
}
if (!app_passwd(passinarg, passoutarg, &passin, &passout)) {
BIO_printf(bio_err, "Error getting passwords\n");
goto end;
}
if (srpvfile == NULL) {
if (configfile == NULL)
configfile = default_config_file;
conf = app_load_config_verbose(configfile, verbose);
if (conf == NULL)
goto end;
if (configfile != default_config_file && !app_load_modules(conf))
goto end;
/* Lets get the config section we are using */
if (section == NULL) {
if (verbose)
BIO_printf(bio_err,
"trying to read " ENV_DEFAULT_SRP
" in " BASE_SECTION "\n");
section = lookup_conf(conf, BASE_SECTION, ENV_DEFAULT_SRP);
if (section == NULL)
goto end;
}
app_RAND_load_conf(conf, BASE_SECTION);
if (verbose)
BIO_printf(bio_err,
"trying to read " ENV_DATABASE " in section \"%s\"\n",
section);
srpvfile = lookup_conf(conf, section, ENV_DATABASE);
if (srpvfile == NULL)
goto end;
}
if (verbose)
BIO_printf(bio_err, "Trying to read SRP verifier file \"%s\"\n",
srpvfile);
db = load_index(srpvfile, NULL);
if (db == NULL) {
BIO_printf(bio_err, "Problem with index file: %s (could not load/parse file)\n", srpvfile);
goto end;
}
/* Lets check some fields */
for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
pp = sk_OPENSSL_PSTRING_value(db->db->data, i);
if (pp[DB_srptype][0] == DB_SRP_INDEX) {
maxgN = i;
if ((gNindex < 0) && (gN != NULL) && strcmp(gN, pp[DB_srpid]) == 0)
gNindex = i;
print_index(db, i, verbose > 1);
}
}
if (verbose)
BIO_printf(bio_err, "Database initialised\n");
if (gNindex >= 0) {
gNrow = sk_OPENSSL_PSTRING_value(db->db->data, gNindex);
print_entry(db, gNindex, verbose > 1, "Default g and N");
} else if (maxgN > 0 && !SRP_get_default_gN(gN)) {
BIO_printf(bio_err, "No g and N value for index \"%s\"\n", gN);
goto end;
} else {
if (verbose)
BIO_printf(bio_err, "Database has no g N information.\n");
gNrow = NULL;
}
if (verbose > 1)
BIO_printf(bio_err, "Starting user processing\n");
while (mode == OPT_LIST || user != NULL) {
int userindex = -1;
if (user != NULL && verbose > 1)
BIO_printf(bio_err, "Processing user \"%s\"\n", user);
if ((userindex = get_index(db, user, 'U')) >= 0)
print_user(db, userindex, (verbose > 0) || mode == OPT_LIST);
if (mode == OPT_LIST) {
if (user == NULL) {
BIO_printf(bio_err, "List all users\n");
for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++)
print_user(db, i, 1);
} else if (userindex < 0) {
BIO_printf(bio_err,
"user \"%s\" does not exist, ignored. t\n", user);
errors++;
}
} else if (mode == OPT_ADD) {
if (userindex >= 0) {
/* reactivation of a new user */
char **row =
sk_OPENSSL_PSTRING_value(db->db->data, userindex);
BIO_printf(bio_err, "user \"%s\" reactivated.\n", user);
row[DB_srptype][0] = 'V';
doupdatedb = 1;
} else {
char *row[DB_NUMBER];
char *gNid;
row[DB_srpverifier] = NULL;
row[DB_srpsalt] = NULL;
row[DB_srpinfo] = NULL;
if (!
(gNid =
srp_create_user(user, &(row[DB_srpverifier]),
&(row[DB_srpsalt]),
gNrow ? gNrow[DB_srpsalt] : gN,
gNrow ? gNrow[DB_srpverifier] : NULL,
passout, verbose))) {
BIO_printf(bio_err,
"Cannot create srp verifier for user \"%s\", operation abandoned .\n",
user);
errors++;
goto end;
}
row[DB_srpid] = OPENSSL_strdup(user);
row[DB_srptype] = OPENSSL_strdup("v");
row[DB_srpgN] = OPENSSL_strdup(gNid);
if ((row[DB_srpid] == NULL)
|| (row[DB_srpgN] == NULL)
|| (row[DB_srptype] == NULL)
|| (row[DB_srpverifier] == NULL)
|| (row[DB_srpsalt] == NULL)
|| (userinfo
&& ((row[DB_srpinfo] = OPENSSL_strdup(userinfo)) == NULL))
|| !update_index(db, row)) {
OPENSSL_free(row[DB_srpid]);
OPENSSL_free(row[DB_srpgN]);
OPENSSL_free(row[DB_srpinfo]);
OPENSSL_free(row[DB_srptype]);
OPENSSL_free(row[DB_srpverifier]);
OPENSSL_free(row[DB_srpsalt]);
goto end;
}
doupdatedb = 1;
}
} else if (mode == OPT_MODIFY) {
if (userindex < 0) {
BIO_printf(bio_err,
"user \"%s\" does not exist, operation ignored.\n",
user);
errors++;
} else {
char **row =
sk_OPENSSL_PSTRING_value(db->db->data, userindex);
char type = row[DB_srptype][0];
if (type == 'v') {
BIO_printf(bio_err,
"user \"%s\" already updated, operation ignored.\n",
user);
errors++;
} else {
char *gNid;
if (row[DB_srptype][0] == 'V') {
int user_gN;
char **irow = NULL;
if (verbose)
BIO_printf(bio_err,
"Verifying password for user \"%s\"\n",
user);
if ((user_gN =
get_index(db, row[DB_srpgN], DB_SRP_INDEX)) >= 0)
irow =
sk_OPENSSL_PSTRING_value(db->db->data,
userindex);
if (!srp_verify_user
(user, row[DB_srpverifier], row[DB_srpsalt],
irow ? irow[DB_srpsalt] : row[DB_srpgN],
irow ? irow[DB_srpverifier] : NULL, passin,
verbose)) {
BIO_printf(bio_err,
"Invalid password for user \"%s\", operation abandoned.\n",
user);
errors++;
goto end;
}
}
if (verbose)
BIO_printf(bio_err, "Password for user \"%s\" ok.\n",
user);
if (!
(gNid =
srp_create_user(user, &(row[DB_srpverifier]),
&(row[DB_srpsalt]),
gNrow ? gNrow[DB_srpsalt] : NULL,
gNrow ? gNrow[DB_srpverifier] : NULL,
passout, verbose))) {
BIO_printf(bio_err,
"Cannot create srp verifier for user \"%s\", operation abandoned.\n",
user);
errors++;
goto end;
}
row[DB_srptype][0] = 'v';
row[DB_srpgN] = OPENSSL_strdup(gNid);
if (row[DB_srpid] == NULL
|| row[DB_srpgN] == NULL
|| row[DB_srptype] == NULL
|| row[DB_srpverifier] == NULL
|| row[DB_srpsalt] == NULL
|| (userinfo
&& ((row[DB_srpinfo] = OPENSSL_strdup(userinfo))
== NULL)))
goto end;
doupdatedb = 1;
}
}
} else if (mode == OPT_DELETE) {
if (userindex < 0) {
BIO_printf(bio_err,
"user \"%s\" does not exist, operation ignored. t\n",
user);
errors++;
} else {
char **xpp = sk_OPENSSL_PSTRING_value(db->db->data, userindex);
BIO_printf(bio_err, "user \"%s\" revoked. t\n", user);
xpp[DB_srptype][0] = 'R';
doupdatedb = 1;
}
}
user = *argv++;
if (user == NULL) {
/* no more processing in any mode if no users left */
break;
}
}
if (verbose)
BIO_printf(bio_err, "User procession done.\n");
if (doupdatedb) {
/* Lets check some fields */
for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
pp = sk_OPENSSL_PSTRING_value(db->db->data, i);
if (pp[DB_srptype][0] == 'v') {
pp[DB_srptype][0] = 'V';
print_user(db, i, verbose);
}
}
if (verbose)
BIO_printf(bio_err, "Trying to update srpvfile.\n");
if (!save_index(srpvfile, "new", db))
goto end;
if (verbose)
BIO_printf(bio_err, "Temporary srpvfile created.\n");
if (!rotate_index(srpvfile, "new", "old"))
goto end;
if (verbose)
BIO_printf(bio_err, "srpvfile updated.\n");
}
ret = (errors != 0);
end:
if (errors != 0)
if (verbose)
BIO_printf(bio_err, "User errors %d.\n", errors);
if (verbose)
BIO_printf(bio_err, "SRP terminating with code %d.\n", ret);
OPENSSL_free(passin);
OPENSSL_free(passout);
if (ret)
ERR_print_errors(bio_err);
NCONF_free(conf);
free_index(db);
release_engine(e);
return ret;
}
|
623137ddf5993b734a332524ab0f04b1e6fdcb7d
|
24ed6f6bec90986e60641c991afcea9409df40af
|
/src/ft2_sample_ed_features.c
|
be9d2e93d5654d4cd9123c1d6e0332dac01c8a35
|
[
"BSD-3-Clause",
"CC-BY-NC-SA-4.0"
] |
permissive
|
8bitbubsy/ft2-clone
|
24b851b989ee0dd27d24041524c95c06a4648485
|
7c6a629b5407f0acfd1df7235903f475156051de
|
refs/heads/master
| 2023-09-04T12:34:02.982464
| 2023-08-16T10:01:41
| 2023-08-16T10:01:41
| 225,352,979
| 560
| 48
|
BSD-3-Clause
| 2023-05-09T17:26:38
| 2019-12-02T10:59:22
|
C
|
UTF-8
|
C
| false
| false
| 33,822
|
c
|
ft2_sample_ed_features.c
|
/* This file contains the routines for the following sample editor functions:
** - Resampler
** - Echo
** - Mix
** - Volume
**/
// for finding memory leaks in debug mode with Visual Studio
#if defined _DEBUG && defined _MSC_VER
#include <crtdbg.h>
#endif
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <math.h>
#include "ft2_header.h"
#include "ft2_mouse.h"
#include "ft2_audio.h"
#include "ft2_gui.h"
#include "ft2_events.h"
#include "ft2_video.h"
#include "ft2_inst_ed.h"
#include "ft2_sample_ed.h"
#include "ft2_keyboard.h"
#include "ft2_tables.h"
#include "ft2_structs.h"
static volatile bool stopThread;
static int8_t smpEd_RelReSmp, mix_Balance = 50;
static bool echo_AddMemory, exitFlag, outOfMemory;
static int16_t echo_nEcho = 1, echo_VolChange = 30;
static int32_t echo_Distance = 0x100;
static double dVol_StartVol = 100.0, dVol_EndVol = 100.0;
static SDL_Thread *thread;
static void pbExit(void)
{
ui.sysReqShown = false;
exitFlag = true;
}
static void windowOpen(void)
{
ui.sysReqShown = true;
ui.sysReqEnterPressed = false;
unstuckLastUsedGUIElement();
SDL_EventState(SDL_DROPFILE, SDL_DISABLE);
}
static void windowClose(bool rewriteSample)
{
SDL_EventState(SDL_DROPFILE, SDL_ENABLE);
if (exitFlag || rewriteSample)
writeSample(true);
else
updateNewSample();
mouseAnimOff();
}
static void sbSetResampleTones(uint32_t pos)
{
if (smpEd_RelReSmp != (int8_t)(pos - 36))
smpEd_RelReSmp = (int8_t)(pos - 36);
}
static void pbResampleTonesDown(void)
{
if (smpEd_RelReSmp > -36)
smpEd_RelReSmp--;
}
static void pbResampleTonesUp(void)
{
if (smpEd_RelReSmp < 36)
smpEd_RelReSmp++;
}
static int32_t SDLCALL resampleThread(void *ptr)
{
smpPtr_t sp;
if (instr[editor.curInstr] == NULL)
return true;
sample_t *s = &instr[editor.curInstr]->smp[editor.curSmp];
bool sample16Bit = !!(s->flags & SAMPLE_16BIT);
const double dRatio = exp2((int32_t)smpEd_RelReSmp / 12.0);
double dNewLen = s->length * dRatio;
if (dNewLen > (double)MAX_SAMPLE_LEN)
dNewLen = (double)MAX_SAMPLE_LEN;
const uint32_t newLen = (int32_t)floor(dNewLen);
if (!allocateSmpDataPtr(&sp, newLen, sample16Bit))
{
outOfMemory = true;
setMouseBusy(false);
ui.sysReqShown = false;
return true;
}
int8_t *dst = sp.ptr;
int8_t *src = s->dataPtr;
// 32.32 fixed-point logic
const uint64_t delta64 = (const uint64_t)round((UINT32_MAX+1.0) / dRatio);
uint64_t posFrac64 = 0;
pauseAudio();
unfixSample(s);
/* Nearest-neighbor resampling (no interpolation).
**
** Could benefit from windowed-sinc interpolation,
** but it seems like some people prefer no resampling
** interpolation (like FT2).
*/
if (newLen > 0)
{
if (sample16Bit)
{
const int16_t *src16 = (const int16_t *)src;
int16_t *dst16 = (int16_t *)dst;
for (uint32_t i = 0; i < newLen; i++)
{
const uint32_t position = posFrac64 >> 32;
dst16[i] = src16[position];
posFrac64 += delta64;
}
}
else // 8-bit
{
const int8_t *src8 = src;
int8_t *dst8 = dst;
for (uint32_t i = 0; i < newLen; i++)
{
const uint32_t position = posFrac64 >> 32;
dst8[i] = src8[position];
posFrac64 += delta64;
}
}
}
freeSmpData(s);
setSmpDataPtr(s, &sp);
s->relativeNote += smpEd_RelReSmp;
s->length = newLen;
s->loopStart = (int32_t)(s->loopStart * dRatio);
s->loopLength = (int32_t)(s->loopLength * dRatio);
sanitizeSample(s);
fixSample(s);
resumeAudio();
setSongModifiedFlag();
setMouseBusy(false);
ui.sysReqShown = false;
return true;
(void)ptr;
}
static void pbDoResampling(void)
{
mouseAnimOn();
thread = SDL_CreateThread(resampleThread, NULL, NULL);
if (thread == NULL)
{
okBox(0, "System message", "Couldn't create thread!");
return;
}
SDL_DetachThread(thread);
}
static void drawResampleBox(void)
{
char sign;
const int16_t x = 209;
const int16_t y = 230;
const int16_t w = 214;
const int16_t h = 54;
// main fill
fillRect(x + 1, y + 1, w - 2, h - 2, PAL_BUTTONS);
// outer border
vLine(x, y, h - 1, PAL_BUTTON1);
hLine(x + 1, y, w - 2, PAL_BUTTON1);
vLine(x + w - 1, y, h, PAL_BUTTON2);
hLine(x, y + h - 1, w - 1, PAL_BUTTON2);
// inner border
vLine(x + 2, y + 2, h - 5, PAL_BUTTON2);
hLine(x + 3, y + 2, w - 6, PAL_BUTTON2);
vLine(x + w - 3, y + 2, h - 4, PAL_BUTTON1);
hLine(x + 2, y + h - 3, w - 4, PAL_BUTTON1);
sample_t *s = &instr[editor.curInstr]->smp[editor.curSmp];
double dLenMul = exp2(smpEd_RelReSmp * (1.0 / 12.0));
double dNewLen = s->length * dLenMul;
if (dNewLen > (double)MAX_SAMPLE_LEN)
dNewLen = (double)MAX_SAMPLE_LEN;
textOutShadow(215, 236, PAL_FORGRND, PAL_BUTTON2, "Rel. h.tones");
textOutShadow(215, 250, PAL_FORGRND, PAL_BUTTON2, "New sample size");
hexOut(361, 250, PAL_FORGRND, (int32_t)dNewLen, 8);
if (smpEd_RelReSmp == 0) sign = ' ';
else if (smpEd_RelReSmp < 0) sign = '-';
else sign = '+';
uint16_t val = ABS(smpEd_RelReSmp);
if (val > 9)
{
charOut(291, 236, PAL_FORGRND, sign);
charOut(298, 236, PAL_FORGRND, '0' + ((val / 10) % 10));
charOut(305, 236, PAL_FORGRND, '0' + (val % 10));
}
else
{
charOut(298, 236, PAL_FORGRND, sign);
charOut(305, 236, PAL_FORGRND, '0' + (val % 10));
}
}
static void setupResampleBoxWidgets(void)
{
pushButton_t *p;
scrollBar_t *s;
// "Apply" pushbutton
p = &pushButtons[0];
memset(p, 0, sizeof (pushButton_t));
p->caption = "Apply";
p->x = 214;
p->y = 264;
p->w = 73;
p->h = 16;
p->callbackFuncOnUp = pbDoResampling;
p->visible = true;
// "Exit" pushbutton
p = &pushButtons[1];
memset(p, 0, sizeof (pushButton_t));
p->caption = "Exit";
p->x = 345;
p->y = 264;
p->w = 73;
p->h = 16;
p->callbackFuncOnUp = pbExit;
p->visible = true;
// scrollbar buttons
p = &pushButtons[2];
memset(p, 0, sizeof (pushButton_t));
p->caption = ARROW_LEFT_STRING;
p->x = 314;
p->y = 234;
p->w = 23;
p->h = 13;
p->preDelay = 1;
p->delayFrames = 3;
p->callbackFuncOnDown = pbResampleTonesDown;
p->visible = true;
p = &pushButtons[3];
memset(p, 0, sizeof (pushButton_t));
p->caption = ARROW_RIGHT_STRING;
p->x = 395;
p->y = 234;
p->w = 23;
p->h = 13;
p->preDelay = 1;
p->delayFrames = 3;
p->callbackFuncOnDown = pbResampleTonesUp;
p->visible = true;
// echo num scrollbar
s = &scrollBars[0];
memset(s, 0, sizeof (scrollBar_t));
s->x = 337;
s->y = 234;
s->w = 58;
s->h = 13;
s->callbackFunc = sbSetResampleTones;
s->visible = true;
setScrollBarPageLength(0, 1);
setScrollBarEnd(0, 36 * 2);
}
void pbSampleResample(void)
{
uint16_t i;
if (editor.curInstr == 0 ||
instr[editor.curInstr] == NULL ||
instr[editor.curInstr]->smp[editor.curSmp].dataPtr == NULL)
{
return;
}
setupResampleBoxWidgets();
windowOpen();
outOfMemory = false;
exitFlag = false;
while (ui.sysReqShown)
{
readInput();
if (ui.sysReqEnterPressed)
pbDoResampling();
setSyncedReplayerVars();
handleRedrawing();
drawResampleBox();
setScrollBarPos(0, smpEd_RelReSmp + 36, false);
drawCheckBox(0);
for (i = 0; i < 4; i++) drawPushButton(i);
drawScrollBar(0);
flipFrame();
}
for (i = 0; i < 4; i++) hidePushButton(i);
hideScrollBar(0);
windowClose(false);
if (outOfMemory)
okBox(0, "System message", "Not enough memory!");
}
static void cbEchoAddMemory(void)
{
echo_AddMemory ^= 1;
}
static void sbSetEchoNumPos(uint32_t pos)
{
if (echo_nEcho != (int32_t)pos)
echo_nEcho = (int16_t)pos;
}
static void sbSetEchoDistPos(uint32_t pos)
{
if (echo_Distance != (int32_t)pos)
echo_Distance = (int32_t)pos;
}
static void sbSetEchoFadeoutPos(uint32_t pos)
{
if (echo_VolChange != (int32_t)pos)
echo_VolChange = (int16_t)pos;
}
static void pbEchoNumDown(void)
{
if (echo_nEcho > 0)
echo_nEcho--;
}
static void pbEchoNumUp(void)
{
if (echo_nEcho < 64)
echo_nEcho++;
}
static void pbEchoDistDown(void)
{
if (echo_Distance > 0)
echo_Distance--;
}
static void pbEchoDistUp(void)
{
if (echo_Distance < 16384)
echo_Distance++;
}
static void pbEchoFadeoutDown(void)
{
if (echo_VolChange > 0)
echo_VolChange--;
}
static void pbEchoFadeoutUp(void)
{
if (echo_VolChange < 100)
echo_VolChange++;
}
static int32_t SDLCALL createEchoThread(void *ptr)
{
smpPtr_t sp;
if (echo_nEcho < 1)
{
ui.sysReqShown = false;
return true;
}
sample_t *s = &instr[editor.curInstr]->smp[editor.curSmp];
int32_t readLen = s->length;
int8_t *readPtr = s->dataPtr;
bool sample16Bit = !!(s->flags & SAMPLE_16BIT);
int32_t distance = echo_Distance * 16;
double dVolChange = echo_VolChange / 100.0;
// calculate real number of echoes
double dSmp = sample16Bit ? 32768.0 : 128.0;
int32_t k = 0;
while (k++ < echo_nEcho && dSmp >= 1.0)
dSmp *= dVolChange;
int32_t nEchoes = k + 1;
if (nEchoes < 1)
{
ui.sysReqShown = false;
return true;
}
// set write length (either original length or full echo length)
int32_t writeLen = readLen;
if (echo_AddMemory)
{
int64_t tmp64 = (int64_t)distance * (nEchoes - 1);
tmp64 += writeLen;
if (tmp64 > MAX_SAMPLE_LEN)
tmp64 = MAX_SAMPLE_LEN;
writeLen = (uint32_t)tmp64;
}
if (!allocateSmpDataPtr(&sp, writeLen, sample16Bit))
{
outOfMemory = true;
setMouseBusy(false);
ui.sysReqShown = false;
return false;
}
pauseAudio();
unfixSample(s);
int32_t writeIdx = 0;
if (sample16Bit)
{
const int16_t *readPtr16 = (const int16_t *)readPtr;
int16_t *writePtr16 = (int16_t *)sp.ptr;
while (writeIdx < writeLen)
{
double dSmpOut = 0.0;
double dSmpMul = 1.0;
int32_t echoRead = writeIdx;
int32_t echoCycle = nEchoes;
while (!stopThread)
{
if (echoRead < readLen)
dSmpOut += (int32_t)readPtr16[echoRead] * dSmpMul;
dSmpMul *= dVolChange;
echoRead -= distance;
if (echoRead <= 0 || --echoCycle <= 0)
break;
}
DROUND(dSmpOut);
int32_t smp32 = (int32_t)dSmpOut;
CLAMP16(smp32);
writePtr16[writeIdx++] = (int16_t)smp32;
}
}
else // 8-bit
{
int8_t *writePtr8 = sp.ptr;
while (writeIdx < writeLen)
{
double dSmpOut = 0.0;
double dSmpMul = 1.0;
int32_t echoRead = writeIdx;
int32_t echoCycle = nEchoes;
while (!stopThread)
{
if (echoRead < readLen)
dSmpOut += (int32_t)readPtr[echoRead] * dSmpMul;
dSmpMul *= dVolChange;
echoRead -= distance;
if (echoRead <= 0 || --echoCycle <= 0)
break;
}
DROUND(dSmpOut);
int32_t smp32 = (int32_t)dSmpOut;
CLAMP8(smp32);
writePtr8[writeIdx++] = (int8_t)smp32;
}
}
freeSmpData(s);
setSmpDataPtr(s, &sp);
if (stopThread) // we stopped before echo was done, realloc length
{
writeLen = writeIdx;
reallocateSmpData(s, writeLen, sample16Bit);
editor.updateCurSmp = true;
}
s->length = writeLen;
fixSample(s);
resumeAudio();
setSongModifiedFlag();
setMouseBusy(false);
ui.sysReqShown = false;
return true;
(void)ptr;
}
static void pbCreateEcho(void)
{
stopThread = false;
mouseAnimOn();
thread = SDL_CreateThread(createEchoThread, NULL, NULL);
if (thread == NULL)
{
okBox(0, "System message", "Couldn't create thread!");
return;
}
SDL_DetachThread(thread);
}
static void drawEchoBox(void)
{
const int16_t x = 171;
const int16_t y = 220;
const int16_t w = 291;
const int16_t h = 66;
// main fill
fillRect(x + 1, y + 1, w - 2, h - 2, PAL_BUTTONS);
// outer border
vLine(x, y, h - 1, PAL_BUTTON1);
hLine(x + 1, y, w - 2, PAL_BUTTON1);
vLine(x + w - 1, y, h, PAL_BUTTON2);
hLine(x, y + h - 1, w - 1, PAL_BUTTON2);
// inner border
vLine(x + 2, y + 2, h - 5, PAL_BUTTON2);
hLine(x + 3, y + 2, w - 6, PAL_BUTTON2);
vLine(x + w - 3, y + 2, h - 4, PAL_BUTTON1);
hLine(x + 2, y + h - 3, w - 4, PAL_BUTTON1);
textOutShadow(177, 226, PAL_FORGRND, PAL_BUTTON2, "Number of echoes");
textOutShadow(177, 240, PAL_FORGRND, PAL_BUTTON2, "Echo distance");
textOutShadow(177, 254, PAL_FORGRND, PAL_BUTTON2, "Fade out");
textOutShadow(192, 270, PAL_FORGRND, PAL_BUTTON2, "Add memory to sample");
assert(echo_nEcho <= 64);
charOut(315 + (2 * 7), 226, PAL_FORGRND, '0' + (char)(echo_nEcho / 10));
charOut(315 + (3 * 7), 226, PAL_FORGRND, '0' + (echo_nEcho % 10));
assert(echo_Distance <= 0x4000);
hexOut(308, 240, PAL_FORGRND, echo_Distance << 4, 5);
assert(echo_VolChange <= 100);
textOutFixed(312, 254, PAL_FORGRND, PAL_BUTTONS, dec3StrTab[echo_VolChange]);
charOutShadow(313 + (3 * 7), 254, PAL_FORGRND, PAL_BUTTON2, '%');
}
static void setupEchoBoxWidgets(void)
{
checkBox_t *c;
pushButton_t *p;
scrollBar_t *s;
// "Add memory to sample" checkbox
c = &checkBoxes[0];
memset(c, 0, sizeof (checkBox_t));
c->x = 176;
c->y = 268;
c->clickAreaWidth = 146;
c->clickAreaHeight = 12;
c->callbackFunc = cbEchoAddMemory;
c->checked = echo_AddMemory ? CHECKBOX_CHECKED : CHECKBOX_UNCHECKED;
c->visible = true;
// "Apply" pushbutton
p = &pushButtons[0];
memset(p, 0, sizeof (pushButton_t));
p->caption = "Apply";
p->x = 345;
p->y = 266;
p->w = 56;
p->h = 16;
p->callbackFuncOnUp = pbCreateEcho;
p->visible = true;
// "Exit" pushbutton
p = &pushButtons[1];
memset(p, 0, sizeof (pushButton_t));
p->caption = "Exit";
p->x = 402;
p->y = 266;
p->w = 55;
p->h = 16;
p->callbackFuncOnUp = pbExit;
p->visible = true;
// scrollbar buttons
p = &pushButtons[2];
memset(p, 0, sizeof (pushButton_t));
p->caption = ARROW_LEFT_STRING;
p->x = 345;
p->y = 224;
p->w = 23;
p->h = 13;
p->preDelay = 1;
p->delayFrames = 3;
p->callbackFuncOnDown = pbEchoNumDown;
p->visible = true;
p = &pushButtons[3];
memset(p, 0, sizeof (pushButton_t));
p->caption = ARROW_RIGHT_STRING;
p->x = 434;
p->y = 224;
p->w = 23;
p->h = 13;
p->preDelay = 1;
p->delayFrames = 3;
p->callbackFuncOnDown = pbEchoNumUp;
p->visible = true;
p = &pushButtons[4];
memset(p, 0, sizeof (pushButton_t));
p->caption = ARROW_LEFT_STRING;
p->x = 345;
p->y = 238;
p->w = 23;
p->h = 13;
p->preDelay = 1;
p->delayFrames = 3;
p->callbackFuncOnDown = pbEchoDistDown;
p->visible = true;
p = &pushButtons[5];
memset(p, 0, sizeof (pushButton_t));
p->caption = ARROW_RIGHT_STRING;
p->x = 434;
p->y = 238;
p->w = 23;
p->h = 13;
p->preDelay = 1;
p->delayFrames = 3;
p->callbackFuncOnDown = pbEchoDistUp;
p->visible = true;
p = &pushButtons[6];
memset(p, 0, sizeof (pushButton_t));
p->caption = ARROW_LEFT_STRING;
p->x = 345;
p->y = 252;
p->w = 23;
p->h = 13;
p->preDelay = 1;
p->delayFrames = 3;
p->callbackFuncOnDown = pbEchoFadeoutDown;
p->visible = true;
p = &pushButtons[7];
memset(p, 0, sizeof (pushButton_t));
p->caption = ARROW_RIGHT_STRING;
p->x = 434;
p->y = 252;
p->w = 23;
p->h = 13;
p->preDelay = 1;
p->delayFrames = 3;
p->callbackFuncOnDown = pbEchoFadeoutUp;
p->visible = true;
// echo num scrollbar
s = &scrollBars[0];
memset(s, 0, sizeof (scrollBar_t));
s->x = 368;
s->y = 224;
s->w = 66;
s->h = 13;
s->callbackFunc = sbSetEchoNumPos;
s->visible = true;
setScrollBarPageLength(0, 1);
setScrollBarEnd(0, 64);
// echo distance scrollbar
s = &scrollBars[1];
memset(s, 0, sizeof (scrollBar_t));
s->x = 368;
s->y = 238;
s->w = 66;
s->h = 13;
s->callbackFunc = sbSetEchoDistPos;
s->visible = true;
setScrollBarPageLength(1, 1);
setScrollBarEnd(1, 16384);
// echo fadeout scrollbar
s = &scrollBars[2];
memset(s, 0, sizeof (scrollBar_t));
s->x = 368;
s->y = 252;
s->w = 66;
s->h = 13;
s->callbackFunc = sbSetEchoFadeoutPos;
s->visible = true;
setScrollBarPageLength(2, 1);
setScrollBarEnd(2, 100);
}
void handleEchoToolPanic(void)
{
stopThread = true;
}
void pbSampleEcho(void)
{
if (editor.curInstr == 0 ||
instr[editor.curInstr] == NULL ||
instr[editor.curInstr]->smp[editor.curSmp].dataPtr == NULL)
{
return;
}
setupEchoBoxWidgets();
windowOpen();
outOfMemory = false;
exitFlag = false;
while (ui.sysReqShown)
{
readInput();
if (ui.sysReqEnterPressed)
pbCreateEcho();
setSyncedReplayerVars();
handleRedrawing();
drawEchoBox();
setScrollBarPos(0, echo_nEcho, false);
setScrollBarPos(1, echo_Distance, false);
setScrollBarPos(2, echo_VolChange, false);
drawCheckBox(0);
for (uint16_t i = 0; i < 8; i++) drawPushButton(i);
for (uint16_t i = 0; i < 3; i++) drawScrollBar(i);
flipFrame();
}
hideCheckBox(0);
for (uint16_t i = 0; i < 8; i++) hidePushButton(i);
for (uint16_t i = 0; i < 3; i++) hideScrollBar(i);
windowClose(echo_AddMemory ? false : true);
if (outOfMemory)
okBox(0, "System message", "Not enough memory!");
}
static int32_t SDLCALL mixThread(void *ptr)
{
smpPtr_t sp;
int8_t *dstPtr, *mixPtr;
uint8_t mixFlags, dstFlags;
int32_t dstLen, mixLen;
int16_t dstIns = editor.curInstr;
int16_t dstSmp = editor.curSmp;
int16_t mixIns = editor.srcInstr;
int16_t mixSmp = editor.srcSmp;
sample_t *s = &instr[dstIns]->smp[dstSmp];
sample_t *sSrc = &instr[mixIns]->smp[mixSmp];
if (dstIns == mixIns && dstSmp == mixSmp)
{
setMouseBusy(false);
ui.sysReqShown = false;
return true;
}
if (instr[mixIns] == NULL)
{
mixLen = 0;
mixPtr = NULL;
mixFlags = 0;
}
else
{
mixLen = sSrc->length;
mixPtr = sSrc->dataPtr;
mixFlags = sSrc->flags;
if (mixPtr == NULL)
{
mixLen = 0;
mixFlags = 0;
}
}
if (instr[dstIns] == NULL)
{
dstLen = 0;
dstPtr = NULL;
dstFlags = 0;
}
else
{
dstLen = s->length;
dstPtr = s->dataPtr;
dstFlags = s->flags;
if (dstPtr == NULL)
{
dstLen = 0;
dstFlags = 0;
}
}
bool src16Bits = !!(mixFlags & SAMPLE_16BIT);
bool dst16Bits = !!(dstFlags & SAMPLE_16BIT);
int32_t maxLen = (dstLen > mixLen) ? dstLen : mixLen;
if (maxLen == 0)
{
setMouseBusy(false);
ui.sysReqShown = false;
return true;
}
if (!allocateSmpDataPtr(&sp, maxLen, dst16Bits))
{
outOfMemory = true;
setMouseBusy(false);
ui.sysReqShown = false;
return true;
}
memset(sp.ptr, 0, maxLen);
if (instr[dstIns] == NULL && !allocateInstr(dstIns))
{
outOfMemory = true;
setMouseBusy(false);
ui.sysReqShown = false;
return true;
}
pauseAudio();
unfixSample(s);
// unfix source sample
if (instr[mixIns] != NULL)
unfixSample(sSrc);
const double dAmp1 = mix_Balance / 100.0;
const double dAmp2 = 1.0 - dAmp1;
const double dSmp1ScaleMul = src16Bits ? (1.0 / 32768.0) : (1.0 / 128.0);
const double dSmp2ScaleMul = dst16Bits ? (1.0 / 32768.0) : (1.0 / 128.0);
const double dNormalizeMul = dst16Bits ? 32768.0 : 128.0;
for (int32_t i = 0; i < maxLen; i++)
{
double dSmp1 = (i >= mixLen) ? 0.0 : (getSampleValue(mixPtr, i, src16Bits) * dSmp1ScaleMul); // -1.0 .. 0.999inf
double dSmp2 = (i >= dstLen) ? 0.0 : (getSampleValue(dstPtr, i, dst16Bits) * dSmp2ScaleMul); // -1.0 .. 0.999inf
const double dSmp = ((dSmp1 * dAmp1) + (dSmp2 * dAmp2)) * dNormalizeMul;
putSampleValue(sp.ptr, i, dSmp, dst16Bits);
}
freeSmpData(s);
setSmpDataPtr(s, &sp);
s->length = maxLen;
s->flags = dstFlags;
fixSample(s);
// re-fix source sample again
if (instr[mixIns] != NULL)
fixSample(sSrc);
resumeAudio();
setSongModifiedFlag();
setMouseBusy(false);
ui.sysReqShown = false;
return true;
(void)ptr;
}
static void pbMix(void)
{
mouseAnimOn();
thread = SDL_CreateThread(mixThread, NULL, NULL);
if (thread == NULL)
{
okBox(0, "System message", "Couldn't create thread!");
return;
}
SDL_DetachThread(thread);
}
static void sbSetMixBalancePos(uint32_t pos)
{
if (mix_Balance != (int8_t)pos)
mix_Balance = (int8_t)pos;
}
static void pbMixBalanceDown(void)
{
if (mix_Balance > 0)
mix_Balance--;
}
static void pbMixBalanceUp(void)
{
if (mix_Balance < 100)
mix_Balance++;
}
static void drawMixSampleBox(void)
{
const int16_t x = 192;
const int16_t y = 240;
const int16_t w = 248;
const int16_t h = 38;
// main fill
fillRect(x + 1, y + 1, w - 2, h - 2, PAL_BUTTONS);
// outer border
vLine(x, y, h - 1, PAL_BUTTON1);
hLine(x + 1, y, w - 2, PAL_BUTTON1);
vLine(x + w - 1, y, h, PAL_BUTTON2);
hLine(x, y + h - 1, w - 1, PAL_BUTTON2);
// inner border
vLine(x + 2, y + 2, h - 5, PAL_BUTTON2);
hLine(x + 3, y + 2, w - 6, PAL_BUTTON2);
vLine(x + w - 3, y + 2, h - 4, PAL_BUTTON1);
hLine(x + 2, y + h - 3, w - 4, PAL_BUTTON1);
textOutShadow(198, 246, PAL_FORGRND, PAL_BUTTON2, "Mixing balance");
assert((mix_Balance >= 0) && (mix_Balance <= 100));
textOutFixed(299, 246, PAL_FORGRND, PAL_BUTTONS, dec3StrTab[mix_Balance]);
}
static void setupMixBoxWidgets(void)
{
pushButton_t *p;
scrollBar_t *s;
// "Apply" pushbutton
p = &pushButtons[0];
memset(p, 0, sizeof (pushButton_t));
p->caption = "Apply";
p->x = 197;
p->y = 258;
p->w = 73;
p->h = 16;
p->callbackFuncOnUp = pbMix;
p->visible = true;
// "Exit" pushbutton
p = &pushButtons[1];
memset(p, 0, sizeof (pushButton_t));
p->caption = "Exit";
p->x = 361;
p->y = 258;
p->w = 73;
p->h = 16;
p->callbackFuncOnUp = pbExit;
p->visible = true;
// scrollbar buttons
p = &pushButtons[2];
memset(p, 0, sizeof (pushButton_t));
p->caption = ARROW_LEFT_STRING;
p->x = 322;
p->y = 244;
p->w = 23;
p->h = 13;
p->preDelay = 1;
p->delayFrames = 3;
p->callbackFuncOnDown = pbMixBalanceDown;
p->visible = true;
p = &pushButtons[3];
memset(p, 0, sizeof (pushButton_t));
p->caption = ARROW_RIGHT_STRING;
p->x = 411;
p->y = 244;
p->w = 23;
p->h = 13;
p->preDelay = 1;
p->delayFrames = 3;
p->callbackFuncOnDown = pbMixBalanceUp;
p->visible = true;
// mixing balance scrollbar
s = &scrollBars[0];
memset(s, 0, sizeof (scrollBar_t));
s->x = 345;
s->y = 244;
s->w = 66;
s->h = 13;
s->callbackFunc = sbSetMixBalancePos;
s->visible = true;
setScrollBarPageLength(0, 1);
setScrollBarEnd(0, 100);
}
void pbSampleMix(void)
{
uint16_t i;
if (editor.curInstr == 0)
return;
setupMixBoxWidgets();
windowOpen();
outOfMemory = false;
exitFlag = false;
while (ui.sysReqShown)
{
readInput();
if (ui.sysReqEnterPressed)
pbMix();
setSyncedReplayerVars();
handleRedrawing();
drawMixSampleBox();
setScrollBarPos(0, mix_Balance, false);
for (i = 0; i < 4; i++) drawPushButton(i);
drawScrollBar(0);
flipFrame();
}
for (i = 0; i < 4; i++) hidePushButton(i);
hideScrollBar(0);
windowClose(false);
if (outOfMemory)
okBox(0, "System message", "Not enough memory!");
}
static void sbSetStartVolPos(uint32_t pos)
{
int32_t val = (int32_t)(pos - 200);
if (val != (int32_t)dVol_StartVol)
{
if (ABS(val) < 10) val = 0;
else if (ABS(val - 100) < 10) val = 100;
else if (ABS(val + 100) < 10) val = -100;
dVol_StartVol = (double)val;
}
}
static void sbSetEndVolPos(uint32_t pos)
{
int32_t val = (int32_t)(pos - 200);
if (val != (int32_t)dVol_EndVol)
{
if (ABS(val) < 10) val = 0;
else if (ABS(val - 100) < 10) val = 100;
else if (ABS(val + 100) < 10) val = -100;
dVol_EndVol = val;
}
}
static void pbSampStartVolDown(void)
{
if (dVol_StartVol > -200.0)
dVol_StartVol -= 1.0;
dVol_StartVol = floor(dVol_StartVol);
}
static void pbSampStartVolUp(void)
{
if (dVol_StartVol < 200.0)
dVol_StartVol += 1.0;
dVol_StartVol = floor(dVol_StartVol);
}
static void pbSampEndVolDown(void)
{
if (dVol_EndVol > -200.0)
dVol_EndVol -= 1.0;
dVol_EndVol = floor(dVol_EndVol);
}
static void pbSampEndVolUp(void)
{
if (dVol_EndVol < 200.0)
dVol_EndVol += 1.0;
dVol_EndVol = floor(dVol_EndVol);
}
static int32_t SDLCALL applyVolumeThread(void *ptr)
{
int32_t x1, x2;
if (instr[editor.curInstr] == NULL)
goto applyVolumeExit;
sample_t *s = &instr[editor.curInstr]->smp[editor.curSmp];
if (smpEd_Rx1 < smpEd_Rx2)
{
x1 = smpEd_Rx1;
x2 = smpEd_Rx2;
if (x2 > s->length)
x2 = s->length;
if (x1 < 0)
x1 = 0;
if (x2 <= x1)
goto applyVolumeExit;
}
else
{
// no mark, operate on whole sample
x1 = 0;
x2 = s->length;
}
const int32_t len = x2 - x1;
if (len <= 0)
goto applyVolumeExit;
bool mustInterpolate = (dVol_StartVol != dVol_EndVol);
const double dVol = dVol_StartVol / 100.0;
const double dPosMul = ((dVol_EndVol / 100.0) - dVol) / len;
pauseAudio();
unfixSample(s);
if (s->flags & SAMPLE_16BIT)
{
int16_t *ptr16 = (int16_t *)s->dataPtr + x1;
if (mustInterpolate)
{
for (int32_t i = 0; i < len; i++)
{
double dSmp = (int32_t)ptr16[i] * (dVol + (i * dPosMul)); // linear interpolation
DROUND(dSmp);
int32_t smp32 = (int32_t)dSmp;
CLAMP16(smp32);
ptr16[i] = (int16_t)smp32;
}
}
else // no interpolation needed
{
for (int32_t i = 0; i < len; i++)
{
double dSmp = (int32_t)ptr16[i] * dVol;
DROUND(dSmp);
int32_t smp32 = (int32_t)dSmp;
CLAMP16(smp32);
ptr16[i] = (int16_t)smp32;
}
}
}
else // 8-bit sample
{
int8_t *ptr8 = s->dataPtr + x1;
if (mustInterpolate)
{
for (int32_t i = 0; i < len; i++)
{
double dSmp = (int32_t)ptr8[i] * (dVol + (i * dPosMul)); // linear interpolation
DROUND(dSmp);
int32_t smp32 = (int32_t)dSmp;
CLAMP8(smp32);
ptr8[i] = (int8_t)smp32;
}
}
else // no interpolation needed
{
for (int32_t i = 0; i < len; i++)
{
double dSmp = (int32_t)ptr8[i] * dVol;
DROUND(dSmp);
int32_t smp32 = (int32_t)dSmp;
CLAMP8(smp32);
ptr8[i] = (int8_t)smp32;
}
}
}
fixSample(s);
resumeAudio();
setSongModifiedFlag();
applyVolumeExit:
setMouseBusy(false);
ui.sysReqShown = false;
return true;
(void)ptr;
}
static void pbApplyVolume(void)
{
if (dVol_StartVol == 100.0 && dVol_EndVol == 100.0)
{
ui.sysReqShown = false;
return; // no volume change to be done
}
mouseAnimOn();
thread = SDL_CreateThread(applyVolumeThread, NULL, NULL);
if (thread == NULL)
{
okBox(0, "System message", "Couldn't create thread!");
return;
}
SDL_DetachThread(thread);
}
static int32_t SDLCALL getMaxScaleThread(void *ptr)
{
int32_t x1, x2;
if (instr[editor.curInstr] == NULL)
goto getScaleExit;
sample_t *s = &instr[editor.curInstr]->smp[editor.curSmp];
if (smpEd_Rx1 < smpEd_Rx2)
{
x1 = smpEd_Rx1;
x2 = smpEd_Rx2;
if (x2 > s->length)
x2 = s->length;
if (x1 < 0)
x1 = 0;
if (x2 <= x1)
goto getScaleExit;
}
else
{
// no sample marking, operate on the whole sample
x1 = 0;
x2 = s->length;
}
uint32_t len = x2 - x1;
if (len <= 0)
{
dVol_StartVol = dVol_EndVol = 100.0;
goto getScaleExit;
}
double dVolChange = 100.0;
/* If sample is looped and the loopEnd point is inside the marked range,
** we need to unfix the fixed interpolation sample before scanning,
** and fix it again after we're done.
*/
bool hasLoop = GET_LOOPTYPE(s->flags) != LOOP_OFF;
const int32_t loopEnd = s->loopStart + s->loopLength;
bool fixedSampleInRange = hasLoop && (x1 <= loopEnd) && (x2 >= loopEnd);
if (fixedSampleInRange)
unfixSample(s);
int32_t maxAmp = 0;
if (s->flags & SAMPLE_16BIT)
{
const int16_t *ptr16 = (const int16_t *)s->dataPtr + x1;
for (uint32_t i = 0; i < len; i++)
{
const int32_t absSmp = ABS(ptr16[i]);
if (absSmp > maxAmp)
maxAmp = absSmp;
}
if (maxAmp > 0)
dVolChange = (32767.0 / maxAmp) * 100.0;
}
else // 8-bit
{
const int8_t *ptr8 = (const int8_t *)&s->dataPtr[x1];
for (uint32_t i = 0; i < len; i++)
{
const int32_t absSmp = ABS(ptr8[i]);
if (absSmp > maxAmp)
maxAmp = absSmp;
}
if (maxAmp > 0)
dVolChange = (127.0 / maxAmp) * 100.0;
}
if (fixedSampleInRange)
fixSample(s);
if (dVolChange < 100.0) // yes, this can happen...
dVolChange = 100.0;
dVol_StartVol = dVol_EndVol = dVolChange;
getScaleExit:
setMouseBusy(false);
return true;
(void)ptr;
}
static void pbGetMaxScale(void)
{
mouseAnimOn();
thread = SDL_CreateThread(getMaxScaleThread, NULL, NULL);
if (thread == NULL)
{
okBox(0, "System message", "Couldn't create thread!");
return;
}
SDL_DetachThread(thread);
}
static void drawSampleVolumeBox(void)
{
char sign;
const int16_t x = 166;
const int16_t y = 230;
const int16_t w = 301;
const int16_t h = 52;
uint32_t val;
// main fill
fillRect(x + 1, y + 1, w - 2, h - 2, PAL_BUTTONS);
// outer border
vLine(x, y, h - 1, PAL_BUTTON1);
hLine(x + 1, y, w - 2, PAL_BUTTON1);
vLine(x + w - 1, y, h, PAL_BUTTON2);
hLine(x, y + h - 1, w - 1, PAL_BUTTON2);
// inner border
vLine(x + 2, y + 2, h - 5, PAL_BUTTON2);
hLine(x + 3, y + 2, w - 6, PAL_BUTTON2);
vLine(x + w - 3, y + 2, h - 4, PAL_BUTTON1);
hLine(x + 2, y + h - 3, w - 4, PAL_BUTTON1);
textOutShadow(172, 236, PAL_FORGRND, PAL_BUTTON2, "Start volume");
textOutShadow(172, 250, PAL_FORGRND, PAL_BUTTON2, "End volume");
charOutShadow(282, 236, PAL_FORGRND, PAL_BUTTON2, '%');
charOutShadow(282, 250, PAL_FORGRND, PAL_BUTTON2, '%');
const int32_t startVol = (int32_t)dVol_StartVol;
const int32_t endVol = (int32_t)dVol_EndVol;
if (startVol > 200)
{
charOut(253, 236, PAL_FORGRND, '>');
charOut(260, 236, PAL_FORGRND, '2');
charOut(267, 236, PAL_FORGRND, '0');
charOut(274, 236, PAL_FORGRND, '0');
}
else
{
if (startVol == 0) sign = ' ';
else if (startVol < 0) sign = '-';
else sign = '+';
val = ABS(startVol);
if (val > 99)
{
charOut(253, 236, PAL_FORGRND, sign);
charOut(260, 236, PAL_FORGRND, '0' + (char)(val / 100));
charOut(267, 236, PAL_FORGRND, '0' + ((val / 10) % 10));
charOut(274, 236, PAL_FORGRND, '0' + (val % 10));
}
else if (val > 9)
{
charOut(260, 236, PAL_FORGRND, sign);
charOut(267, 236, PAL_FORGRND, '0' + (char)(val / 10));
charOut(274, 236, PAL_FORGRND, '0' + (val % 10));
}
else
{
charOut(267, 236, PAL_FORGRND, sign);
charOut(274, 236, PAL_FORGRND, '0' + (char)val);
}
}
if (endVol > 200)
{
charOut(253, 250, PAL_FORGRND, '>');
charOut(260, 250, PAL_FORGRND, '2');
charOut(267, 250, PAL_FORGRND, '0');
charOut(274, 250, PAL_FORGRND, '0');
}
else
{
if (endVol == 0) sign = ' ';
else if (endVol < 0) sign = '-';
else sign = '+';
val = ABS(endVol);
if (val > 99)
{
charOut(253, 250, PAL_FORGRND, sign);
charOut(260, 250, PAL_FORGRND, '0' + (char)(val / 100));
charOut(267, 250, PAL_FORGRND, '0' + ((val / 10) % 10));
charOut(274, 250, PAL_FORGRND, '0' + (val % 10));
}
else if (val > 9)
{
charOut(260, 250, PAL_FORGRND, sign);
charOut(267, 250, PAL_FORGRND, '0' + (char)(val / 10));
charOut(274, 250, PAL_FORGRND, '0' + (val % 10));
}
else
{
charOut(267, 250, PAL_FORGRND, sign);
charOut(274, 250, PAL_FORGRND, '0' + (char)val);
}
}
}
static void setupVolumeBoxWidgets(void)
{
pushButton_t *p;
scrollBar_t *s;
// "Apply" pushbutton
p = &pushButtons[0];
memset(p, 0, sizeof (pushButton_t));
p->caption = "Apply";
p->x = 171;
p->y = 262;
p->w = 73;
p->h = 16;
p->callbackFuncOnUp = pbApplyVolume;
p->visible = true;
// "Get maximum scale" pushbutton
p = &pushButtons[1];
memset(p, 0, sizeof (pushButton_t));
p->caption = "Get maximum scale";
p->x = 245;
p->y = 262;
p->w = 143;
p->h = 16;
p->callbackFuncOnUp = pbGetMaxScale;
p->visible = true;
// "Exit" pushbutton
p = &pushButtons[2];
memset(p, 0, sizeof (pushButton_t));
p->caption = "Exit";
p->x = 389;
p->y = 262;
p->w = 73;
p->h = 16;
p->callbackFuncOnUp = pbExit;
p->visible = true;
// scrollbar buttons
p = &pushButtons[3];
memset(p, 0, sizeof (pushButton_t));
p->caption = ARROW_LEFT_STRING;
p->x = 292;
p->y = 234;
p->w = 23;
p->h = 13;
p->preDelay = 1;
p->delayFrames = 3;
p->callbackFuncOnDown = pbSampStartVolDown;
p->visible = true;
p = &pushButtons[4];
memset(p, 0, sizeof (pushButton_t));
p->caption = ARROW_RIGHT_STRING;
p->x = 439;
p->y = 234;
p->w = 23;
p->h = 13;
p->preDelay = 1;
p->delayFrames = 3;
p->callbackFuncOnDown = pbSampStartVolUp;
p->visible = true;
p = &pushButtons[5];
memset(p, 0, sizeof (pushButton_t));
p->caption = ARROW_LEFT_STRING;
p->x = 292;
p->y = 248;
p->w = 23;
p->h = 13;
p->preDelay = 1;
p->delayFrames = 3;
p->callbackFuncOnDown = pbSampEndVolDown;
p->visible = true;
p = &pushButtons[6];
memset(p, 0, sizeof (pushButton_t));
p->caption = ARROW_RIGHT_STRING;
p->x = 439;
p->y = 248;
p->w = 23;
p->h = 13;
p->preDelay = 1;
p->delayFrames = 3;
p->callbackFuncOnDown = pbSampEndVolUp;
p->visible = true;
// volume start scrollbar
s = &scrollBars[0];
memset(s, 0, sizeof (scrollBar_t));
s->x = 315;
s->y = 234;
s->w = 124;
s->h = 13;
s->callbackFunc = sbSetStartVolPos;
s->visible = true;
setScrollBarPageLength(0, 1);
setScrollBarEnd(0, 200 * 2);
setScrollBarPos(0, 200, false);
// volume end scrollbar
s = &scrollBars[1];
memset(s, 0, sizeof (scrollBar_t));
s->x = 315;
s->y = 248;
s->w = 124;
s->h = 13;
s->callbackFunc = sbSetEndVolPos;
s->visible = true;
setScrollBarPageLength(1, 1);
setScrollBarEnd(1, 200 * 2);
setScrollBarPos(1, 200, false);
}
void pbSampleVolume(void)
{
uint16_t i;
if (editor.curInstr == 0 ||
instr[editor.curInstr] == NULL ||
instr[editor.curInstr]->smp[editor.curSmp].dataPtr == NULL)
{
return;
}
setupVolumeBoxWidgets();
windowOpen();
exitFlag = false;
while (ui.sysReqShown)
{
readInput();
if (ui.sysReqEnterPressed)
{
pbApplyVolume();
keyb.ignoreCurrKeyUp = true; // don't handle key up event for this key release
}
setSyncedReplayerVars();
handleRedrawing();
// this is needed for the "Get maximum scale" button
if (ui.setMouseIdle) mouseAnimOff();
drawSampleVolumeBox();
const int32_t startVol = (int32_t)dVol_StartVol;
const int32_t endVol = (int32_t)dVol_EndVol;
setScrollBarPos(0, 200 + startVol, false);
setScrollBarPos(1, 200 + endVol, false);
for (i = 0; i < 7; i++) drawPushButton(i);
for (i = 0; i < 2; i++) drawScrollBar(i);
flipFrame();
}
for (i = 0; i < 7; i++) hidePushButton(i);
for (i = 0; i < 2; i++) hideScrollBar(i);
windowClose(true);
}
|
3f669d01ef66fd605a1c7712fc30b93f8776ee48
|
80d97bc5ff8a43da99893a57f03002e68081d780
|
/src/Extension/User32Helper.h
|
debd9dbf196976bc428f70efdad3f92ee73c5183
|
[
"BSD-2-Clause",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
ProgerXP/Notepad2e
|
38798db10e0fe0a5602a463a5681bd653afe3bb6
|
c703f11bc278457286b3ca1565047a3b09ccdf8d
|
refs/heads/master
| 2023-09-05T23:32:07.576076
| 2023-07-27T11:03:30
| 2023-07-27T11:03:49
| 10,840,481
| 376
| 50
|
NOASSERTION
| 2022-08-22T14:06:36
| 2013-06-21T10:28:18
|
C++
|
UTF-8
|
C
| false
| false
| 150
|
h
|
User32Helper.h
|
#pragma once
#include "stdafx.h"
#include <wtypes.h>
BOOL n2e_User32Initialize();
BOOL n2e_ShutdownBlockReasonCreate(HWND hWnd, LPCWSTR pwszReason);
|
0ad95c0d5d9473f5c2b63d894de379a003db6516
|
19a9f2c19bcb81c4a14ba17831d3098de7731fb5
|
/ni/src/lib/hlu/PlotManagerP.h
|
d5bd43766aa1c8d6bde755a745f7e71f34966eb9
|
[
"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
| 5,611
|
h
|
PlotManagerP.h
|
/*
* $Id: PlotManagerP.h,v 1.14 2000-02-16 01:43:31 dbrown Exp $
*/
/************************************************************************
* *
* Copyright (C) 1992 *
* University Corporation for Atmospheric Research *
* All Rights Reserved *
* *
************************************************************************/
/*
* File: PlotManagerP.h
*
* Author: David Brown
* National Center for Atmospheric Research
* PO 3000, Boulder, Colorado
*
* Date: Fri Oct 2 15:01:59 MDT 1992
*
* Description:
*/
#ifndef _NPLOTMANAGERP_h
#define _NPLOTMANAGERP_h
#include <ncarg/hlu/TransformP.h>
#include <ncarg/hlu/PlotManagerI.h>
#define NhlOV_ALLOC_UNIT 8
#define NhlOV_IRR_COUNT 16
#define NhlOV_DEF_TICKMARK_ZONE 2
#define NhlOV_DEF_TITLE_ZONE 4
#define NhlOV_DEF_LABELBAR_ZONE 6
#define NhlOV_DEF_LEGEND_ZONE 7
/* private resources */
#define NhlNpmPlotManagerRecs ".pmPlotManagerRecs"
#define NhlCpmPlotManagerRecs ".PmPlotManagerRecs"
typedef enum { ovTICKMARK, ovTITLE, ovLEGEND, ovLABELBAR, ovEXTERNAL }
ovAnnoType;
typedef struct _NhlAnnoRec {
NhlLayer ovl;
int anno_id;
int plot_id;
NhlBoolean resize_notify;
int zone;
NhlPosition side;
NhlJustification just;
float para_pos;
float ortho_pos;
ovAnnoType type;
int status;
NhlBoolean viewable;
NhlBoolean track_data;
float data_x;
float data_y;
NhlBoolean out_of_range;
float orig_x;
float orig_y;
float orig_height;
float orig_width;
struct _NhlAnnoRec *next;
} NhlAnnoRec;
typedef struct _NhlpmRec {
NhlTransformLayer plot; /* overlay plot (member or base) */
NhlLayer ov_obj; /* plot's PlotManager object */
NhlAnnoRec *anno_list; /* list of annotation records */
int max_zone; /* the max annotation zone */
float ox,oy; /* original vp values */
float owidth,oheight;
} NhlpmRec;
typedef struct _NhlPlotManagerLayerPart {
/* Public resource fields */
NhlGenArray overlay_seq_ids; /* read only */
NhlGenArray pre_draw_order;
NhlGenArray post_draw_order;
NhlGenArray anno_view_ids;
NhlGenArray annomanager_ids;
NhlBoolean fit_to_bb;
float bb_left;
float bb_right;
float bb_top;
float bb_bottom;
NhlAnnotationDisplayMode display_tickmarks;
int tickmark_zone;
NhlAnnotationDisplayMode display_titles;
int title_zone;
NhlAnnotationDisplayMode display_labelbar;
int labelbar_zone;
NhlAnnotationDisplayMode display_legend;
int legend_zone;
#if 0
/* intercepted tickmark resources */
float x_b_data_left;
float x_b_data_right;
float y_l_data_bottom;
float y_l_data_top;
int x_log;
int y_log;
float x_min;
float y_min;
float x_max;
float y_max;
int x_reverse;
int y_reverse;
float x_tension;
float y_tension;
#endif
/* intercepted title resources */
float ti_main_offset_x;
float ti_x_axis_offset_x;
float ti_y_axis_offset_y;
NhlTitlePositions ti_main_position;
NhlTitlePositions ti_x_axis_position;
NhlTitlePositions ti_y_axis_position;
NhlBoolean ti_main_font_height_set;
float ti_main_font_height;
NhlBoolean ti_x_axis_font_height_set;
float ti_x_axis_font_height;
NhlBoolean ti_y_axis_font_height_set;
float ti_y_axis_font_height;
/* labelbar resources */
NhlBoolean lbar_on;
NhlOrientation lbar_orient;
NhlBoolean lbar_width_set;
float lbar_width;
NhlBoolean lbar_height_set;
float lbar_height;
NhlBoolean lbar_keep_aspect;
NhlPosition lbar_side;
float lbar_para_pos;
float lbar_ortho_pos;
NhlJustification lbar_just;
float lbar_x_off;
float lbar_y_off;
NhlPosition lbar_pos;
/* legend resources */
NhlBoolean lgnd_on;
NhlOrientation lgnd_orient;
NhlBoolean lgnd_width_set;
float lgnd_width;
NhlBoolean lgnd_height_set;
float lgnd_height;
NhlBoolean lgnd_keep_aspect;
NhlPosition lgnd_side;
float lgnd_para_pos;
float lgnd_ortho_pos;
NhlJustification lgnd_just;
float lgnd_x_off;
float lgnd_y_off;
NhlPosition lgnd_pos;
/* Private resource fields */
NhlGenArray pm_rec_list;
NhlBoolean update_req;
NhlBoolean update_anno_req;
int trans_change_count;
NhlBoolean trans_changed;
/* Private Fields */
int overlay_alloc;
int overlay_count;
NhlpmRec **pm_recs;
int anno_alloc;
int anno_count;
int anno_ix;
int *view_ids;
int *anno_ids;
NhlLayer tickmarks;
NhlLayer titles;
NhlLayer labelbar;
NhlLayer legend;
float lbar_x;
float lbar_y;
NhlJustification real_lbar_just;
float lgnd_x;
float lgnd_y;
NhlJustification real_lgnd_just;
float ti_x;
float ti_y;
float ti_width;
float ti_height;
float real_main_offset_x;
float real_y_axis_offset_y;
float real_x_axis_offset_x;
NhlTickMarkStyle x_tm_style;
NhlTickMarkStyle y_tm_style;
int x_irr_count;
int y_irr_count;
NhlGenArray x_irr;
NhlGenArray y_irr;
} NhlPlotManagerLayerPart;
typedef struct _NhlPlotManagerLayerRec {
NhlBaseLayerPart base;
NhlViewLayerPart view;
NhlTransformLayerPart trans;
NhlPlotManagerLayerPart plotmanager;
} NhlPlotManagerLayerRec;
typedef struct NhlPlotManagerClassPart{
NhlPointer foo;
} NhlPlotManagerClassPart;
typedef struct _NhlPlotManagerClassRec{
NhlBaseClassPart base_class;
NhlViewClassPart view_class;
NhlTransformClassPart trans_class;
NhlPlotManagerClassPart plotmanager_class;
} NhlPlotManagerClassRec;
typedef struct _NhlPlotManagerClassRec *NhlPlotManagerClass;
typedef struct _NhlPlotManagerLayerRec *NhlPlotManagerLayer;
extern NhlPlotManagerClassRec NhlplotManagerClassRec;
#endif /* _NPLOTMANAGERP_h */
|
4a472d263576c84899228c2039d194d97e094cae
|
50dd46b8ece33f3cdd174284b15d1d51f89669d4
|
/third_party/edk2/QuarkSocPkg/QuarkNorthCluster/Include/Protocol/SmmIchnDispatch2.h
|
e3f72919a7f6515f0791e8294faf5978c2a46d9a
|
[
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"BSD-2-Clause",
"OpenSSL"
] |
permissive
|
google/google-ctf
|
f99da1ee07729bbccb869fff1cbaed6a80e43bcc
|
df02323eaf945d15e124801c74abaadca2749dc7
|
refs/heads/master
| 2023-08-31T14:30:27.548081
| 2023-08-29T13:04:20
| 2023-08-29T13:04:20
| 131,317,137
| 4,136
| 607
|
Apache-2.0
| 2023-08-30T22:17:02
| 2018-04-27T15:56:03
|
Go
|
UTF-8
|
C
| false
| false
| 4,177
|
h
|
SmmIchnDispatch2.h
|
/** @file
Intel-only SMM Child Dispatcher Protocol.
This protocol provides a parent dispatch service for a collection of
chipset-specific SMI source.
Copyright (c) 2013-2015 Intel Corporation.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#ifndef __SMM_ICHN_DISPATCH2_H__
#define __SMM_ICHN_DISPATCH2_H__
//
// Share some common definitions with Framework SMM
//
#include <Protocol/SmmIchnDispatch.h>
#include <PiSmm.h>
//
// Global ID for the ICH SMI Protocol
//
#define EFI_SMM_ICHN_DISPATCH2_PROTOCOL_GUID \
{ \
0xadf3a128, 0x416d, 0x4060, {0x8d, 0xdf, 0x30, 0xa1, 0xd7, 0xaa, 0xb6, 0x99 } \
}
typedef struct _EFI_SMM_ICHN_DISPATCH2_PROTOCOL EFI_SMM_ICHN_DISPATCH2_PROTOCOL;
typedef struct {
EFI_SMM_ICHN_SMI_TYPE Type;
} EFI_SMM_ICHN_REGISTER_CONTEXT;
//
// Member functions
//
/**
Register a child SMI source dispatch function with a parent SMM driver
@param This Protocol instance pointer.
@param DispatchFunction Pointer to dispatch function to be invoked for
this SMI source
@param RegisterContext Pointer to the dispatch function's context.
The caller fills this context in before calling
the register function to indicate to the register
function the ICHN SMI source for which the dispatch
function should be invoked.
@param DispatchHandle Handle generated by the dispatcher to track the
function instance.
@retval EFI_SUCCESS The dispatch function has been successfully
registered and the SMI source has been enabled.
@retval EFI_DEVICE_ERROR The driver was unable to enable the SMI source.
@retval EFI_OUT_OF_RESOURCES Not enough memory (system or SMM) to manage this
child.
@retval EFI_INVALID_PARAMETER RegisterContext is invalid. The ICHN input value
is not within valid range.
**/
typedef
EFI_STATUS
(EFIAPI *EFI_SMM_ICHN_DISPATCH2_REGISTER) (
IN CONST EFI_SMM_ICHN_DISPATCH2_PROTOCOL *This,
IN EFI_SMM_HANDLER_ENTRY_POINT2 DispatchFunction,
IN OUT EFI_SMM_ICHN_REGISTER_CONTEXT *RegisterContext,
OUT EFI_HANDLE *DispatchHandle
);
/**
Unregister a child SMI source dispatch function with a parent SMM driver
@param This Protocol instance pointer.
@param DispatchHandle Handle of dispatch function to deregister.
@retval EFI_SUCCESS The dispatch function has been successfully
unregistered and the SMI source has been disabled
if there are no other registered child dispatch
functions for this SMI source.
@retval EFI_INVALID_PARAMETER Handle is invalid.
@retval other
**/
typedef
EFI_STATUS
(EFIAPI *EFI_SMM_ICHN_DISPATCH2_UNREGISTER) (
IN EFI_SMM_ICHN_DISPATCH2_PROTOCOL *This,
IN EFI_HANDLE DispatchHandle
);
//
// Interface structure for the SMM Ich n specific SMI Dispatch Protocol
//
/**
@par Protocol Description:
Provides a parent dispatch service for ICH SMI sources.
@param Register
Installs a child service to be dispatched by this protocol.
@param UnRegister
Removes a child service dispatched by this protocol.
**/
struct _EFI_SMM_ICHN_DISPATCH2_PROTOCOL {
EFI_SMM_ICHN_DISPATCH2_REGISTER Register;
EFI_SMM_ICHN_DISPATCH2_UNREGISTER UnRegister;
};
extern EFI_GUID gEfiSmmIchnDispatch2ProtocolGuid;
#endif
|
156af6662681aea1354580b38aa60377cdbccebf
|
99bdb3251fecee538e0630f15f6574054dfc1468
|
/bsp/imx6sx/iMX6_Platform_SDK/sdk/drivers/enet/src/enet_drv.c
|
7d8c0b216a5b96861b9b4e6d0a7770bc2be944dc
|
[
"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
| 20,520
|
c
|
enet_drv.c
|
/*
* Copyright (c) 2011-2012, Freescale Semiconductor, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* o 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.
*
* o Neither the name of Freescale Semiconductor, Inc. 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.
*/
/*!
* @file enet_drv.c
* @brief Driver of the i.MX ENET controller.
*
* @ingroup diag_enet
*/
#include "sdk.h"
#include "enet/enet.h"
#include "enet_private.h"
/*!
*Global variable which defines the buffer descriptions for receiving frame
* comment:: it must aligned by 128-bits.
*/
static imx_enet_bd_t imx_enet_rx_bd[ENET_BD_RX_NUM * NUM_OF_ETH_DEVS] __attribute__ ((aligned(32)));
/*!
*Global variable which defines the buffer descriptions for receiving frame
* comment:: it must aligned by 128-bits.
*/
static imx_enet_bd_t imx_enet_tx_bd[ENET_BD_TX_NUM * NUM_OF_ETH_DEVS] __attribute__ ((aligned(32)));
/*!
* Global variable which contains the frame buffers ,
*/
static unsigned char imx_enet_rx_buf[ENET_BD_RX_NUM * NUM_OF_ETH_DEVS][2048]
__attribute__ ((aligned(32)));
/*!
* Global variable which contains the frame buffers ,
*/
static unsigned char imx_enet_tx_buf[ENET_BD_TX_NUM * NUM_OF_ETH_DEVS][2048]
__attribute__ ((aligned(32)));
/*!
* This function gets the value of the PHY registers through the MII interface.
*/
int imx_enet_mii_read(volatile hw_enet_t * enet_reg, unsigned char phy_addr,
unsigned char reg_addr, unsigned short int *value)
{
unsigned long waiting = ENET_MII_TIMEOUT;
if (enet_reg->EIR.U & ENET_EVENT_MII) {
enet_reg->EIR.U = ENET_EVENT_MII;
}
enet_reg->MMFR.U = ENET_MII_READ(phy_addr, reg_addr); /*Write CMD */
while (1) {
if (enet_reg->EIR.U & ENET_EVENT_MII) {
enet_reg->EIR.U = ENET_EVENT_MII;
break;
}
if ((--waiting) == 0)
return -1;
hal_delay_us(ENET_MII_TICK);
}
*value = ENET_MII_GET_DATA(enet_reg->MMFR.U);
return 0;
}
/*!
* This function sets the value of the PHY registers through the MII interface.
*/
int imx_enet_mii_write(volatile hw_enet_t * enet_reg, unsigned char phy_addr,
unsigned char reg_addr, unsigned short int value)
{
unsigned long waiting = ENET_MII_TIMEOUT;
if (enet_reg->EIR.U & ENET_EVENT_MII) {
enet_reg->EIR.U = ENET_EVENT_MII;
}
enet_reg->MMFR.U = ENET_MII_WRITE(phy_addr, reg_addr, value); /* Write CMD */
while (1) {
if (enet_reg->EIR.U & ENET_EVENT_MII) {
enet_reg->EIR.U = ENET_EVENT_MII;
break;
}
if ((--waiting) == 0)
return -1;
hal_delay_us(ENET_MII_TICK);
}
return 0;
}
/*!
* The function initializes the description buffer for receiving or transmitting.
*/
static void imx_enet_bd_init(imx_enet_priv_t * dev, int dev_idx)
{
int i;
imx_enet_bd_t *p;
imx_enet_bd_t *rx_bd_base = imx_enet_rx_bd, *tx_bd_base = imx_enet_tx_bd;
rx_bd_base += (dev_idx * ENET_BD_RX_NUM);
tx_bd_base += (dev_idx * ENET_BD_TX_NUM);
p = dev->rx_bd = (imx_enet_bd_t *) rx_bd_base;
for (i = 0; i < ENET_BD_RX_NUM; i++, p++) {
p->status = BD_RX_ST_EMPTY;
p->length = 0;
p->data = (unsigned char *)imx_enet_rx_buf[i + dev_idx * ENET_BD_RX_NUM];
//printf("rx bd %x, buffer is %x\n", (unsigned int)p, (unsigned int)p->data);
}
dev->rx_bd[i - 1].status |= BD_RX_ST_WRAP;
dev->rx_cur = dev->rx_bd;
p = dev->tx_bd = (imx_enet_bd_t *) tx_bd_base;
for (i = 0; i < ENET_BD_TX_NUM; i++, p++) {
p->status = 0;
p->length = 0;
p->data = (unsigned char *)imx_enet_tx_buf[i + dev_idx * ENET_BD_TX_NUM];
//printf("tx bd %x, buffer is %x\n", (unsigned int)p, (unsigned int)p->data);
}
dev->tx_bd[i - 1].status |= BD_TX_ST_WRAP;
dev->tx_cur = dev->tx_bd;
/*TODO:: add the sync function for items */
}
/*!
* This function initializes the ENET controller.
*/
static void imx_enet_chip_init(imx_enet_priv_t * dev)
{
volatile hw_enet_t *enet_reg = (hw_enet_t *) dev->enet_reg;
unsigned int ipg_clk;
enet_reg->ECR.U = ENET_RESET;
while (enet_reg->ECR.U & ENET_RESET) {
hal_delay_us(ENET_COMMON_TICK);
}
enet_reg->EIMR.U = 0x00000000;
enet_reg->EIR.U = 0xFFFFFFFF;
/*
* setup the MII gasket for RMII mode
*/
enet_reg->RCR.U = (enet_reg->RCR.U & ~(0x0000003F)) | ENET_RCR_RGMII_EN | ENET_RCR_FCE | ENET_RCR_PROM;
enet_reg->TCR.U |= ENET_TCR_FDEN;
enet_reg->MIBC.U |= ENET_MIB_DISABLE;
enet_reg->IAUR.U = 0;
enet_reg->IALR.U = 0;
enet_reg->GAUR.U = 0;
enet_reg->GALR.U = 0;
/*TODO:: Use MII_SPEED(IPG_CLK) to get the value */
ipg_clk = get_main_clock(IPG_CLK);
enet_reg->MSCR.U = (enet_reg->MSCR.U & (~0x7e)) | (((ipg_clk + 499999) / 5000000) << 1);
/*Enable ETHER_EN */
enet_reg->MRBR.U = 2048 - 16;
enet_reg->RDSR.U = (unsigned long)dev->rx_bd;
enet_reg->TDSR.U = (unsigned long)dev->tx_bd;
#if 0//defined(CHIP_MX6DQ) || defined(CHIP_MX6SDL)
/* Enable Swap to support little-endian device */
enet_reg->ECR.U |= (0x1 << 8); //BM_ENET_ECR_DBSWP;
/* set ENET tx at store and forward mode */
enet_reg->TFWR.U |= BM_ENET_TFWR_STRFWD; //(0x1 << 8);
#endif
}
void enet_phy_rework_ar8031(imx_enet_priv_t * dev)
{
unsigned short val = 0;
#if 0
int i;
imx_enet_mii_write(dev->enet_reg, dev->phy_addr, 0x1d, 0x1F); // ?? unknown debug reg
imx_enet_mii_read(dev->enet_reg, dev->phy_addr, 0x1e, &val);
//printf("debug before 0x1F val = 0x%x\n", val);
val |= 0x4;
imx_enet_mii_write(dev->enet_reg, dev->phy_addr, 0x1e, val);
imx_enet_mii_read(dev->enet_reg, dev->phy_addr, 0x1e, &val);
//printf("debug after 0x1F val = 0x%x\n", val);
// Set CLK_25M Clock Select MDIO register
// select_clk25m = 3'b110 = 125 MHz from local PLL source
imx_enet_mii_write(dev->enet_reg, dev->phy_addr, 0xd, 0x7); // MMD Access Control; device addr=7
imx_enet_mii_write(dev->enet_reg, dev->phy_addr, 0xe, 0x8016); // MMD Access Address Data; reg=0x8016 (CLK_25M Clock Select)
imx_enet_mii_write(dev->enet_reg, dev->phy_addr, 0xd, 0x4007); // MMD Access Control; func=data, device addr=7
imx_enet_mii_read(dev->enet_reg, dev->phy_addr, 0xe, &val);
//printf("debug read from 0x8016 val = 0x%x\n", val);
val &= 0xffe3;
val |= 0x18;
imx_enet_mii_write(dev->enet_reg, dev->phy_addr, 0xe, val);
imx_enet_mii_read(dev->enet_reg, dev->phy_addr, 0xe, &val);
//printf("debug after read from 0x8016 val = 0x%x\n", val);
for (i = 0; i < 100000; i++) ;
//debug register 0x5[8]=1'b1 - suggest add 2ns GTX_CLK delay
imx_enet_mii_write(dev->enet_reg, dev->phy_addr, 0x1d, 0x5); // debug reg 0x05 = SerDes Test and System Mode Control
imx_enet_mii_read(dev->enet_reg, dev->phy_addr, 0x1e, &val);
val |= 0x0100; // bit 8 = RGMII_tx_clk_dly
imx_enet_mii_write(dev->enet_reg, dev->phy_addr, 0x1e, val);
// Disable hibernate
imx_enet_mii_write(dev->enet_reg, dev->phy_addr, 0x1d, 0xb); // Hib Control and Auto-negotiation Test
imx_enet_mii_read(dev->enet_reg, dev->phy_addr, 0x1e, &val);
imx_enet_mii_write(dev->enet_reg, dev->phy_addr, 0x1e, 0x3c40); // disable hibernate
// Config to external loopback
imx_enet_mii_write(dev->enet_reg, dev->phy_addr, 0x1d, 0x11); // External Loopback selection
imx_enet_mii_read(dev->enet_reg, dev->phy_addr, 0x1e, &val);
val |= 0x0001; // enable ext loopback
imx_enet_mii_write(dev->enet_reg, dev->phy_addr, 0x1e, val);
// PHY AR8031 Integrated 10/100/1000 Gigabit
// Reset & full duplex
// Use default speed - after Pwer on reset - 1000Mbs
imx_enet_mii_write(dev->enet_reg, dev->phy_addr, 0, 0x8140);
imx_enet_mii_read(dev->enet_reg, dev->phy_addr, 0, &val);
while (val == 0x8140)
imx_enet_mii_read(dev->enet_reg, dev->phy_addr, 0, &val);
#else
/* To enable AR8031 ouput a 125MHz clk from CLK_25M */
imx_enet_mii_write(dev->enet_reg, dev->phy_addr, 0xd, 0x7);
imx_enet_mii_write(dev->enet_reg, dev->phy_addr, 0xe, 0x8016);
imx_enet_mii_write(dev->enet_reg, dev->phy_addr, 0xd, 0x4007);
imx_enet_mii_read(dev->enet_reg, dev->phy_addr, 0xe, &val);
val &= 0xffe3;
val |= 0x18;
imx_enet_mii_write(dev->enet_reg, dev->phy_addr, 0xe, val);
/* introduce tx clock delay */
imx_enet_mii_write(dev->enet_reg, dev->phy_addr, 0x1d, 0x5);
imx_enet_mii_read(dev->enet_reg, dev->phy_addr, 0x1e, &val);
val |= 0x0100;
imx_enet_mii_write(dev->enet_reg, dev->phy_addr, 0x1e, val);
#endif
}
void enet_phy_rework_ksz9021(imx_enet_priv_t * dev)
{
imx_enet_mii_write(dev->enet_reg, dev->phy_addr, 0x9, 0x1c00);
/* min rx data delay */
imx_enet_mii_write(dev->enet_reg, dev->phy_addr, 0x0b, 0x8105);
imx_enet_mii_write(dev->enet_reg, dev->phy_addr, 0x0c, 0x0000);
/* max rx/tx clock delay, min rx/tx control delay */
imx_enet_mii_write(dev->enet_reg, dev->phy_addr, 0x0b, 0x8104);
imx_enet_mii_write(dev->enet_reg, dev->phy_addr, 0x0c, 0xf0f0);
imx_enet_mii_write(dev->enet_reg, dev->phy_addr, 0x0b, 0x104);
}
/*!
* This function initializes the PHY connected to the ENET controller.
*/
void imx_enet_phy_init(imx_enet_priv_t * dev)
{
unsigned short value = 0;
unsigned long id = 0;
// Read PHY ID registers.
imx_enet_mii_read(dev->enet_reg, dev->phy_addr, PHY_IDENTIFY_1, &value);
id = (value & PHY_ID1_MASK) << PHY_ID1_SHIFT;
imx_enet_mii_read(dev->enet_reg, dev->phy_addr, PHY_IDENTIFY_2, &value);
id |= (value & PHY_ID2_MASK) << PHY_ID2_SHIFT;
id &= 0xfffffff0; // mask off lower 4 bits
switch (id)
{
case 0x00540088: // ?? PHY
break;
case PHY_LAN8700_ID:
printf("ENET LAN8700 PHY: ID=%lx\n", id);
break;
case PHY_LAN8720_ID:
printf("ENET LAN8720 PHY: ID=%lx\n", id);
break;
case PHY_AR8031_ID:
printf("ENET AR8031 PHY: ID=%lx\n", id);
enet_phy_rework_ar8031(dev);
break;
case PHY_KSZ9021RN_ID:
printf("ENET KSZ9021RN PHY: ID=%lx\n", id);
enet_phy_rework_ksz9021(dev);
break;
default:
printf("[Warning] ENET not connect right PHY: ID=%lx\n", id);
}
dev->phy_id = id;
// Reset PHY
imx_enet_mii_read(dev->enet_reg, dev->phy_addr, PHY_CTRL_REG, &value);
value |= PHY_CTRL_RESET;
imx_enet_mii_write(dev->enet_reg, dev->phy_addr, PHY_CTRL_REG, value);
// Wait for reset to complete.
do {
imx_enet_mii_read(dev->enet_reg, dev->phy_addr, PHY_CTRL_REG, &value);
} while (value & PHY_CTRL_RESET);
/* restart auto-negotiation */
#if 1
#if 1
imx_enet_mii_read(dev->enet_reg, dev->phy_addr, PHY_CTRL_REG, &value);
value |= 0x1200;
imx_enet_mii_write(dev->enet_reg, dev->phy_addr, PHY_CTRL_REG, value);
#else
value = 0x8100;
imx_enet_mii_write(dev->enet_reg, dev->phy_addr, 0x1f, value);
#endif
#endif
// Read current PHY status.
imx_enet_get_phy_status(dev);
}
uint32_t imx_enet_get_phy_status(imx_enet_priv_t * dev)
{
uint16_t value;
// Reset saved status.
dev->status = 0;
imx_enet_mii_read(dev->enet_reg, dev->phy_addr, PHY_STATUS_REG, &value);
printf("enet phy status %0d: %04x\n", dev->phy_addr, value); // 0x7809 or 0x782d
if (value & PHY_STATUS_LINK_ST)
{
dev->status |= ENET_STATUS_LINK_ON;
}
else
{
dev->status &= ~ENET_STATUS_LINK_ON;
}
if (dev->phy_id == PHY_AR8031_ID)
{
#if 0
imx_enet_mii_read(dev->enet_reg, dev->phy_addr, 0x1b, &value); // Cable Diagnostic Tester (CDT)
if (value & (1 << 2))
dev->status |= ENET_STATUS_FULL_DPLX;
else
dev->status &= ~ENET_STATUS_FULL_DPLX;
if (value & 0x2)
dev->status |= ENET_STATUS_1000M;
else if (value & 0x1)
dev->status |= ENET_STATUS_100M;
else
dev->status |= ENET_STATUS_10M;
#else
imx_enet_mii_read(dev->enet_reg, dev->phy_addr, 0x11, &value); // PHY-Specific status reg
printf("AR8031 reg 0x11 = %04x\n", value);
if(value & (1<<13))
dev->status |= ENET_STATUS_FULL_DPLX;
else
dev->status &= ~ENET_STATUS_FULL_DPLX;
if (((value>>14)&0x3) == 0x2)
dev->status |= ENET_STATUS_1000M;
else if (((value>>14)&0x3) == 0x2)
dev->status |= ENET_STATUS_100M;
else
dev->status |= ENET_STATUS_10M;
#endif
}
else if (dev->phy_id == PHY_KSZ9021RN_ID)
{
imx_enet_mii_read(dev->enet_reg, dev->phy_addr, 0x1f, &value);
printf("KSZ9021 reg 0x1f = %04x\n", value);
if (value & (1 << 3))
dev->status |= ENET_STATUS_FULL_DPLX;
else
dev->status &= ~ENET_STATUS_FULL_DPLX;
if (value & (1 << 6))
dev->status |= ENET_STATUS_1000M;
else if (value & (1 << 5))
dev->status |= ENET_STATUS_100M;
else
dev->status |= ENET_STATUS_10M;
}
else
{
if (value & 0xe000)
dev->status |= ENET_STATUS_100M;
else
dev->status |= ENET_STATUS_10M;
if (value & 0x5000)
dev->status |= ENET_STATUS_FULL_DPLX;
else
dev->status &= ~ENET_STATUS_FULL_DPLX;
}
// printf("ENET %0d: [ %s ] [ %s ] [ %s ]:\n", dev->phy_addr,
// (dev->status & ENET_STATUS_FULL_DPLX) ? "FULL_DUPLEX" : "HALF_DUPLEX",
// (dev->status & ENET_STATUS_LINK_ON) ? "connected" : "disconnected",
// (dev->status & ENET_STATUS_1000M) ? "1000M bps" : (dev->status & ENET_STATUS_100M) ?
// "100M bps" : "10M bps");
return dev->status;
}
void imx_enet_phy_enable_external_loopback(imx_enet_priv_t * dev)
{
uint16_t val;
if (dev->phy_id == PHY_AR8031_ID)
{
// Disable hibernate
imx_enet_mii_write(dev->enet_reg, dev->phy_addr, 0x1d, 0xb); // Hib Control and Auto-negotiation Test
imx_enet_mii_read(dev->enet_reg, dev->phy_addr, 0x1e, &val);
imx_enet_mii_write(dev->enet_reg, dev->phy_addr, 0x1e, 0x3c40); // disable hibernate
// Config to external loopback
imx_enet_mii_write(dev->enet_reg, dev->phy_addr, 0x1d, 0x11); // External Loopback selection
imx_enet_mii_read(dev->enet_reg, dev->phy_addr, 0x1e, &val);
val |= 0x0001; // enable ext loopback
imx_enet_mii_write(dev->enet_reg, dev->phy_addr, 0x1e, val);
}
}
unsigned long imx_enet_poll(imx_enet_priv_t * dev)
{
volatile hw_enet_t *enet_reg = dev->enet_reg;
unsigned int value = 0;
value = enet_reg->EIR.U;
enet_reg->EIR.U = value & (~ENET_EVENT_MII);
if (value & ENET_EVENT_TX_ERR) {
printf("WARNING[POLL]: There are error(%x) for transmit\n", value & ENET_EVENT_TX_ERR);
dev->tx_busy = 0;
} else {
if (value & ENET_EVENT_TX) {
dev->tx_busy = 0;
}
}
if (value & ENET_EVENT_RX) {
//imx_enet_check_rx_bd(sc);
}
if (value & ENET_EVENT_HBERR) {
printf("WARNGING[POLL]: Hearbeat error!\n");
}
if (value & ENET_EVENT_EBERR) {
printf("WARNING[POLL]: Ethernet Bus Error!\n");
}
return value;
}
int imx_enet_send(imx_enet_priv_t * dev, unsigned char *buf, int length, unsigned long key)
{
volatile hw_enet_t *enet_reg = dev->enet_reg;
imx_enet_bd_t *p = dev->tx_cur;
memcpy(p->data, buf, length);
p->length = length;
p->status &= ~(BD_TX_ST_LAST | BD_TX_ST_RDY | BD_TX_ST_TC | BD_TX_ST_ABC);
p->status |= BD_TX_ST_LAST | BD_TX_ST_RDY | BD_TX_ST_TC;
if (p->status & BD_TX_ST_WRAP) {
p = dev->tx_bd;
} else
p++;
dev->tx_cur = p;
dev->tx_busy = 1;
dev->tx_key = key;
enet_reg->TDAR.U = ENET_RX_TX_ACTIVE;
return 0;
}
int imx_enet_recv(imx_enet_priv_t * dev, unsigned char *buf, int *length)
{
imx_enet_bd_t *p = dev->rx_cur;
volatile hw_enet_t *enet_reg = dev->enet_reg;
if (p->status & BD_RX_ST_EMPTY) {
return -1;
}
if (!(p->status & BD_RX_ST_LAST)) {
printf("BUG[RX]: status=%x, length=%x\n", p->status, p->length);
return -1;
}
if ((p->status & BD_RX_ST_ERRS) || (p->length > ENET_FRAME_LEN)) {
printf("BUG1[RX]: status=%x, length=%x\n", p->status, p->length);
} else {
memcpy(buf, p->data, p->length - 4);
*length = p->length - 4;
}
p->status = (p->status & BD_RX_ST_WRAP) | BD_RX_ST_EMPTY;
if (p->status & BD_RX_ST_WRAP) {
p = dev->rx_bd;
} else {
p++;
}
dev->rx_cur = p;
enet_reg->ECR.U |= ENET_ETHER_EN;
enet_reg->RDAR.U |= ENET_RX_TX_ACTIVE;
return 0;
}
int imx_enet_init(imx_enet_priv_t * dev, unsigned long reg_base, int phy_addr)
{
dev->enet_reg = (hw_enet_t *) reg_base;
dev->tx_busy = 0;
dev->status = 0;
dev->phy_addr = phy_addr; /* 0 or 1 */
imx_enet_bd_init(dev, phy_addr);
imx_enet_chip_init(dev);
//imx_enet_phy_init(dev);
return 0;
}
static void imx_enet_set_mac_address(volatile hw_enet_t * enet_reg, unsigned char *enaddr)
{
unsigned long value;
value = enaddr[0];
value = (value << 8) + enaddr[1];
value = (value << 8) + enaddr[2];
value = (value << 8) + enaddr[3];
enet_reg->PALR.U = value;
value = enaddr[4];
value = (value << 8) + enaddr[5];
enet_reg->PAUR.U = (value << 16);
}
void imx_enet_start(imx_enet_priv_t * dev, unsigned char *enaddr)
{
imx_enet_set_mac_address(dev->enet_reg, enaddr);
dev->tx_busy = 0;
dev->enet_reg->ECR.U |= ENET_ETHER_EN | ENET_ETHER_SPEED_1000M | ENET_ETHER_LITTLE_ENDIAN;
dev->enet_reg->RDAR.U |= ENET_RX_TX_ACTIVE;
}
void imx_enet_stop(imx_enet_priv_t * dev)
{
dev->enet_reg->ECR.U &= ~ENET_ETHER_EN;
}
int imx_enet_isolate_phy(imx_enet_priv_t * dev)
{
unsigned short value = 0;
if (!imx_enet_mii_read(dev->enet_reg, dev->phy_addr, PHY_CTRL_REG, &value)) {
value |= (0x01 << 10);
if (!imx_enet_mii_write(dev->enet_reg, dev->phy_addr, PHY_CTRL_REG, value)) {
return 0;
}
}
return -1;
}
int imx_enet_unisolate_phy(imx_enet_priv_t * dev)
{
unsigned short value = 0;
if (!imx_enet_mii_read(dev->enet_reg, dev->phy_addr, PHY_CTRL_REG, &value)) {
value &= ~(0x01 << 10);
if (!imx_enet_mii_write(dev->enet_reg, dev->phy_addr, PHY_CTRL_REG, value)) {
imx_enet_mii_read(dev->enet_reg, dev->phy_addr, PHY_CTRL_REG, &value);
return 0;
}
}
return -1;
}
int imx_enet_mii_type(imx_enet_priv_t * dev, enum imx_mii_type mii_type)
{
volatile hw_enet_t *enet_reg = dev->enet_reg;
switch (mii_type) {
case MII:
/*clear RMII and RGMII */
enet_reg->RCR.U &= ~(ENET_RCR_RMII_MODE | ENET_RCR_RGMII_EN);
enet_reg->RCR.U |= ENET_RCR_MII_MODE;
break;
case RMII:
enet_reg->RCR.U &= ~(ENET_RCR_RGMII_EN);
enet_reg->RCR.U |= (ENET_RCR_MII_MODE | ENET_RCR_RMII_MODE);
break;
case RGMII:
enet_reg->RCR.U &= ~(ENET_RCR_RMII_MODE | ENET_RCR_MII_MODE);
enet_reg->RCR.U |= ENET_RCR_RGMII_EN;
enet_reg->TFWR.U = 0x3f; //for mx6dq
break;
default:
printf("BUG:unknow MII type=%x\n", mii_type);
break;
}
return 0;
}
|
2e9f5365194aed47e8ed18852b088e6a73236a3d
|
346cd95125d2a2666184c2a2957d187790795d5b
|
/sim/vlsim/fpga.h
|
e67c22b723b0a64d669aa4a8ce94f49f645c6088
|
[] |
permissive
|
vortexgpgpu/vortex
|
7aeba2c889d4cf8a11d28a070ef169a8266f7034
|
d69a64c32ceaee5afdc6da3d74a5b6dcbb2fe5b5
|
refs/heads/master
| 2023-08-05T00:34:36.928708
| 2023-05-16T08:59:01
| 2023-05-16T08:59:01
| 273,299,204
| 826
| 170
|
BSD-3-Clause
| 2023-08-03T05:49:59
| 2020-06-18T17:24:17
|
Verilog
|
UTF-8
|
C
| false
| false
| 1,552
|
h
|
fpga.h
|
#ifndef __FPGA_H__
#define __FPGA_H__
#include <stdio.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
FPGA_OK = 0, /**< Operation completed successfully */
FPGA_INVALID_PARAM, /**< Invalid parameter supplied */
FPGA_BUSY, /**< Resource is busy */
FPGA_EXCEPTION, /**< An exception occurred */
FPGA_NOT_FOUND, /**< A required resource was not found */
FPGA_NO_MEMORY, /**< Not enough memory to complete operation */
FPGA_NOT_SUPPORTED, /**< Requested operation is not supported */
FPGA_NO_DRIVER, /**< Driver is not loaded */
FPGA_NO_DAEMON, /**< FPGA Daemon (fpgad) is not running */
FPGA_NO_ACCESS, /**< Insufficient privileges or permissions */
FPGA_RECONF_ERROR /**< Error while reconfiguring FPGA */
} fpga_result;
typedef void *fpga_handle;
typedef void *fpga_token;
fpga_result fpgaOpen(fpga_token token, fpga_handle *handle, int flags);
fpga_result fpgaClose(fpga_handle handle);
fpga_result fpgaPrepareBuffer(fpga_handle handle, uint64_t len, void **buf_addr, uint64_t *wsid, int flags);
fpga_result fpgaReleaseBuffer(fpga_handle handle, uint64_t wsid);
fpga_result fpgaGetIOAddress(fpga_handle handle, uint64_t wsid, uint64_t *ioaddr);
fpga_result fpgaWriteMMIO64(fpga_handle handle, uint32_t mmio_num, uint64_t offset, uint64_t value);
fpga_result fpgaReadMMIO64(fpga_handle handle, uint32_t mmio_num, uint64_t offset, uint64_t *value);
const char *fpgaErrStr(fpga_result e);
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
#endif // __FPGA_H__
|
f05727535b13d0ec299ad80886e390fefd3f9d0b
|
da1500e0d3040497614d5327d2461a22e934b4d8
|
/third_party/llvm-project/compiler-rt/test/builtins/Unit/compiler_rt_logbl_test.c
|
d3e8c4f7f97654966e3d0dc66ca5a8d9683e7c86
|
[
"NCSA",
"MIT",
"LLVM-exception",
"Apache-2.0",
"BSD-3-Clause",
"GPL-1.0-or-later",
"LGPL-2.0-or-later"
] |
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
| 1,990
|
c
|
compiler_rt_logbl_test.c
|
// RUN: %clang_builtins %s %librt -o %t && %run %t
#define QUAD_PRECISION
#include <math.h>
#include <stdio.h>
#include "fp_lib.h"
#include "int_lib.h"
#if defined(CRT_HAS_128BIT) && defined(CRT_LDBL_128BIT)
int test__compiler_rt_logbl(fp_t x) {
#if defined(__ve__)
if (fpclassify(x) == FP_SUBNORMAL)
return 0;
#endif
fp_t crt_value = __compiler_rt_logbl(x);
fp_t libm_value = logbl(x);
// Compare the values, considering all NaNs equivalent, as the spec doesn't
// specify the NaN signedness/payload.
if (crt_value != libm_value &&
!(crt_isnan(crt_value) && crt_isnan(libm_value))) {
// Split expected values into two for printf
twords x_t, crt_value_t, libm_value_t;
x_t.all = toRep(x);
crt_value_t.all = toRep(crt_value);
libm_value_t.all = toRep(libm_value);
printf(
"error: in __compiler_rt_logbl([%llX %llX]) = [%llX %llX] != "
"[%llX %llX]\n",
x_t.s.high, x_t.s.low, crt_value_t.s.high, crt_value_t.s.low,
libm_value_t.s.high, libm_value_t.s.low);
return 1;
}
return 0;
}
double cases[] = {
1.e-6, -1.e-6, NAN, -NAN, INFINITY, -INFINITY, -1,
-0.0, 0.0, 1, -2, 2, -0.5, 0.5,
};
#endif
int main() {
#if defined(CRT_HAS_128BIT) && defined(CRT_LDBL_128BIT)
const unsigned N = sizeof(cases) / sizeof(cases[0]);
unsigned i;
for (i = 0; i < N; ++i) {
if (test__compiler_rt_logbl(cases[i])) return 1;
}
// Test a moving 1 bit, especially to handle denormal values.
// Test the negation as well.
rep_t x = signBit;
while (x) {
if (test__compiler_rt_logbl(fromRep(x))) return 1;
if (test__compiler_rt_logbl(fromRep(signBit ^ x))) return 1;
x >>= 1;
}
// Also try a couple moving ones
x = signBit | (signBit >> 1) | (signBit >> 2);
while (x) {
if (test__compiler_rt_logbl(fromRep(x))) return 1;
if (test__compiler_rt_logbl(fromRep(signBit ^ x))) return 1;
x >>= 1;
}
#else
printf("skipped\n");
#endif
return 0;
}
|
fd4f868399dd8a7456964c4aa3b22b2202da04f3
|
d9ea45dbc964799991b9191ae620d2f150652a3d
|
/Sources/kinc/graphics5/constantlocation.h
|
803317ff0d9e222e804716bd2d846042fe0a4010
|
[
"Zlib"
] |
permissive
|
Kode/Kinc
|
6ebb1cfa11c6e9ed0e153c486f573f1d7dca5664
|
d90b7478b192c8270e0ee32c0c3ee18977becd7a
|
refs/heads/main
| 2023-08-08T16:50:01.534587
| 2023-08-07T20:22:46
| 2023-08-07T20:22:46
| 10,254,751
| 283
| 249
|
Zlib
| 2023-08-26T12:27:36
| 2013-05-23T22:22:58
|
C
|
UTF-8
|
C
| false
| false
| 398
|
h
|
constantlocation.h
|
#pragma once
#include <kinc/global.h>
#include <kinc/backend/graphics5/pipeline.h>
/*! \file constantlocation.h
\brief Provides the constant_location-struct which is used for setting constants/uniforms in a shader.
*/
#ifdef __cplusplus
extern "C" {
#endif
typedef struct kinc_g5_constant_location {
ConstantLocation5Impl impl;
} kinc_g5_constant_location_t;
#ifdef __cplusplus
}
#endif
|
b288f4f613b23d56868fd675f270ceaeaf9a6f6d
|
0337c1df871a431c6a8b03ad871d396826d7e210
|
/src/3rdparty/win32_src/pdcurses/pdccolor.h
|
97212805c30a36441fe1ed074e2c1deed5655ce8
|
[
"LicenseRef-scancode-public-domain",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown"
] |
permissive
|
clangen/musikcube
|
be1ad8c1567c9e3cfbf71e1f595ede9aa0152a97
|
64485978ea2e4483499996a8e2304ce5566573d9
|
refs/heads/master
| 2023-08-28T00:52:06.905519
| 2023-08-02T02:47:41
| 2023-08-02T02:47:41
| 32,483,164
| 4,049
| 370
|
BSD-3-Clause
| 2023-09-08T05:05:44
| 2015-03-18T20:41:57
|
C++
|
UTF-8
|
C
| false
| false
| 540
|
h
|
pdccolor.h
|
#ifndef PDCCOLOR_H
#define PDCCOLOR_H
extern int PDC_blink_state;
typedef uint32_t PACKED_RGB;
#define Get_BValue( rgb) ((int)( (rgb) >> 16))
#define Get_GValue( rgb) ((int)( (rgb) >> 8) & 0xff)
#define Get_RValue( rgb) ((int)((rgb) & 0xff))
int PDC_init_palette( void);
void PDC_get_rgb_values( const chtype srcp,
PACKED_RGB *foreground_rgb, PACKED_RGB *background_rgb);
int PDC_set_palette_entry( const int idx, const PACKED_RGB rgb);
PACKED_RGB PDC_get_palette_entry( const int idx);
void PDC_free_palette( void);
#endif
|
c68f19f9d1649730e357d257da21a3f38f7ecba3
|
1577e1cf4e89584a125cffb855ca50a9654c6d55
|
/libpcap/libpcap/pcap-common.h
|
e97b5878d683be6893b14d84050810172b4ce7f0
|
[
"BSD-3-Clause"
] |
permissive
|
apple-open-source/macos
|
a4188b5c2ef113d90281d03cd1b14e5ee52ebffb
|
2d2b15f13487673de33297e49f00ef94af743a9a
|
refs/heads/master
| 2023-08-01T11:03:26.870408
| 2023-03-27T00:00:00
| 2023-03-27T00:00:00
| 180,595,052
| 124
| 24
| null | 2022-12-27T14:54:09
| 2019-04-10T14:06:23
| null |
UTF-8
|
C
| false
| false
| 2,512
|
h
|
pcap-common.h
|
/*
* Copyright (c) 1993, 1994, 1995, 1996, 1997
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* pcap-common.h - common code for pcap and pcapng files
*/
/*
* We use the "receiver-makes-right" approach to byte order,
* because time is at a premium when we are writing the file.
* In other words, the pcap_file_header and pcap_pkthdr,
* records are written in host byte order.
* Note that the bytes of packet data are written out in the order in
* which they were received, so multi-byte fields in packets are not
* written in host byte order, they're written in whatever order the
* sending machine put them in.
*
* ntoh[ls] aren't sufficient because we might need to swap on a big-endian
* machine (if the file was written in little-end order).
*/
#define SWAPLONG(y) \
(((((u_int)(y))&0xff)<<24) | \
((((u_int)(y))&0xff00)<<8) | \
((((u_int)(y))&0xff0000)>>8) | \
((((u_int)(y))>>24)&0xff))
#define SWAPSHORT(y) \
((u_short)(((((u_int)(y))&0xff)<<8) | \
((((u_int)(y))&0xff00)>>8)))
#ifdef __APPLE__
#define SWAPLONGLONG(y) \
(((unsigned long long)SWAPLONG((unsigned long)(y)) << 32) | (SWAPLONG((unsigned long)((y) >> 32))))
#endif /* __APPLE__ */
extern int dlt_to_linktype(int dlt);
extern int linktype_to_dlt(int linktype);
extern void swap_pseudo_headers(int linktype, struct pcap_pkthdr *hdr,
u_char *data);
extern u_int max_snaplen_for_dlt(int dlt);
|
602e37d0558a0f2861971c000cc3fc4b31dfc68d
|
321d11eaee885ceb3a74db0a062f9bbdf282148c
|
/crypto/context.c
|
ba67b0c618e9c010397eb5fd61989d79ad20fa72
|
[
"Apache-2.0",
"OpenSSL",
"LicenseRef-scancode-proprietary-license"
] |
permissive
|
openssl/openssl
|
75691ebaae957793f2ff0673f77545277dfb3988
|
5318c012885a5382eadbf95aa9c1d35664bca819
|
refs/heads/master
| 2023-09-03T15:22:52.727123
| 2023-09-01T07:10:49
| 2023-09-02T14:30:01
| 7,634,677
| 24,148
| 11,569
|
Apache-2.0
| 2023-09-14T19:48:11
| 2013-01-15T22:34:48
|
C
|
UTF-8
|
C
| false
| false
| 16,691
|
c
|
context.c
|
/*
* Copyright 2019-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "crypto/cryptlib.h"
#include <openssl/conf.h>
#include "internal/thread_once.h"
#include "internal/property.h"
#include "internal/core.h"
#include "internal/bio.h"
#include "internal/provider.h"
#include "crypto/decoder.h"
#include "crypto/context.h"
struct ossl_lib_ctx_st {
CRYPTO_RWLOCK *lock, *rand_crngt_lock;
OSSL_EX_DATA_GLOBAL global;
void *property_string_data;
void *evp_method_store;
void *provider_store;
void *namemap;
void *property_defns;
void *global_properties;
void *drbg;
void *drbg_nonce;
#ifndef FIPS_MODULE
void *provider_conf;
void *bio_core;
void *child_provider;
OSSL_METHOD_STORE *decoder_store;
void *decoder_cache;
OSSL_METHOD_STORE *encoder_store;
OSSL_METHOD_STORE *store_loader_store;
void *self_test_cb;
#endif
#if defined(OPENSSL_THREADS)
void *threads;
#endif
void *rand_crngt;
#ifdef FIPS_MODULE
void *thread_event_handler;
void *fips_prov;
#endif
unsigned int ischild:1;
};
int ossl_lib_ctx_write_lock(OSSL_LIB_CTX *ctx)
{
return CRYPTO_THREAD_write_lock(ossl_lib_ctx_get_concrete(ctx)->lock);
}
int ossl_lib_ctx_read_lock(OSSL_LIB_CTX *ctx)
{
return CRYPTO_THREAD_read_lock(ossl_lib_ctx_get_concrete(ctx)->lock);
}
int ossl_lib_ctx_unlock(OSSL_LIB_CTX *ctx)
{
return CRYPTO_THREAD_unlock(ossl_lib_ctx_get_concrete(ctx)->lock);
}
int ossl_lib_ctx_is_child(OSSL_LIB_CTX *ctx)
{
ctx = ossl_lib_ctx_get_concrete(ctx);
if (ctx == NULL)
return 0;
return ctx->ischild;
}
static void context_deinit_objs(OSSL_LIB_CTX *ctx);
static int context_init(OSSL_LIB_CTX *ctx)
{
int exdata_done = 0;
ctx->lock = CRYPTO_THREAD_lock_new();
if (ctx->lock == NULL)
return 0;
ctx->rand_crngt_lock = CRYPTO_THREAD_lock_new();
if (ctx->rand_crngt_lock == NULL)
goto err;
/* Initialize ex_data. */
if (!ossl_do_ex_data_init(ctx))
goto err;
exdata_done = 1;
/* P2. We want evp_method_store to be cleaned up before the provider store */
ctx->evp_method_store = ossl_method_store_new(ctx);
if (ctx->evp_method_store == NULL)
goto err;
#ifndef FIPS_MODULE
/* P2. Must be freed before the provider store is freed */
ctx->provider_conf = ossl_prov_conf_ctx_new(ctx);
if (ctx->provider_conf == NULL)
goto err;
#endif
/* P2. */
ctx->drbg = ossl_rand_ctx_new(ctx);
if (ctx->drbg == NULL)
goto err;
#ifndef FIPS_MODULE
/*
* P2. We want decoder_store/decoder_cache to be cleaned up before the
* provider store
*/
ctx->decoder_store = ossl_method_store_new(ctx);
if (ctx->decoder_store == NULL)
goto err;
ctx->decoder_cache = ossl_decoder_cache_new(ctx);
if (ctx->decoder_cache == NULL)
goto err;
/* P2. We want encoder_store to be cleaned up before the provider store */
ctx->encoder_store = ossl_method_store_new(ctx);
if (ctx->encoder_store == NULL)
goto err;
/* P2. We want loader_store to be cleaned up before the provider store */
ctx->store_loader_store = ossl_method_store_new(ctx);
if (ctx->store_loader_store == NULL)
goto err;
#endif
/* P1. Needs to be freed before the child provider data is freed */
ctx->provider_store = ossl_provider_store_new(ctx);
if (ctx->provider_store == NULL)
goto err;
/* Default priority. */
ctx->property_string_data = ossl_property_string_data_new(ctx);
if (ctx->property_string_data == NULL)
goto err;
ctx->namemap = ossl_stored_namemap_new(ctx);
if (ctx->namemap == NULL)
goto err;
ctx->property_defns = ossl_property_defns_new(ctx);
if (ctx->property_defns == NULL)
goto err;
ctx->global_properties = ossl_ctx_global_properties_new(ctx);
if (ctx->global_properties == NULL)
goto err;
#ifndef FIPS_MODULE
ctx->bio_core = ossl_bio_core_globals_new(ctx);
if (ctx->bio_core == NULL)
goto err;
#endif
ctx->drbg_nonce = ossl_prov_drbg_nonce_ctx_new(ctx);
if (ctx->drbg_nonce == NULL)
goto err;
#ifndef FIPS_MODULE
ctx->self_test_cb = ossl_self_test_set_callback_new(ctx);
if (ctx->self_test_cb == NULL)
goto err;
#endif
#ifdef FIPS_MODULE
ctx->thread_event_handler = ossl_thread_event_ctx_new(ctx);
if (ctx->thread_event_handler == NULL)
goto err;
ctx->fips_prov = ossl_fips_prov_ossl_ctx_new(ctx);
if (ctx->fips_prov == NULL)
goto err;
#endif
#ifndef OPENSSL_NO_THREAD_POOL
ctx->threads = ossl_threads_ctx_new(ctx);
if (ctx->threads == NULL)
goto err;
#endif
/* Low priority. */
#ifndef FIPS_MODULE
ctx->child_provider = ossl_child_prov_ctx_new(ctx);
if (ctx->child_provider == NULL)
goto err;
#endif
/* Everything depends on properties, so we also pre-initialise that */
if (!ossl_property_parse_init(ctx))
goto err;
return 1;
err:
context_deinit_objs(ctx);
if (exdata_done)
ossl_crypto_cleanup_all_ex_data_int(ctx);
CRYPTO_THREAD_lock_free(ctx->rand_crngt_lock);
CRYPTO_THREAD_lock_free(ctx->lock);
memset(ctx, '\0', sizeof(*ctx));
return 0;
}
static void context_deinit_objs(OSSL_LIB_CTX *ctx)
{
/* P2. We want evp_method_store to be cleaned up before the provider store */
if (ctx->evp_method_store != NULL) {
ossl_method_store_free(ctx->evp_method_store);
ctx->evp_method_store = NULL;
}
/* P2. */
if (ctx->drbg != NULL) {
ossl_rand_ctx_free(ctx->drbg);
ctx->drbg = NULL;
}
#ifndef FIPS_MODULE
/* P2. */
if (ctx->provider_conf != NULL) {
ossl_prov_conf_ctx_free(ctx->provider_conf);
ctx->provider_conf = NULL;
}
/*
* P2. We want decoder_store/decoder_cache to be cleaned up before the
* provider store
*/
if (ctx->decoder_store != NULL) {
ossl_method_store_free(ctx->decoder_store);
ctx->decoder_store = NULL;
}
if (ctx->decoder_cache != NULL) {
ossl_decoder_cache_free(ctx->decoder_cache);
ctx->decoder_cache = NULL;
}
/* P2. We want encoder_store to be cleaned up before the provider store */
if (ctx->encoder_store != NULL) {
ossl_method_store_free(ctx->encoder_store);
ctx->encoder_store = NULL;
}
/* P2. We want loader_store to be cleaned up before the provider store */
if (ctx->store_loader_store != NULL) {
ossl_method_store_free(ctx->store_loader_store);
ctx->store_loader_store = NULL;
}
#endif
/* P1. Needs to be freed before the child provider data is freed */
if (ctx->provider_store != NULL) {
ossl_provider_store_free(ctx->provider_store);
ctx->provider_store = NULL;
}
/* Default priority. */
if (ctx->property_string_data != NULL) {
ossl_property_string_data_free(ctx->property_string_data);
ctx->property_string_data = NULL;
}
if (ctx->namemap != NULL) {
ossl_stored_namemap_free(ctx->namemap);
ctx->namemap = NULL;
}
if (ctx->property_defns != NULL) {
ossl_property_defns_free(ctx->property_defns);
ctx->property_defns = NULL;
}
if (ctx->global_properties != NULL) {
ossl_ctx_global_properties_free(ctx->global_properties);
ctx->global_properties = NULL;
}
#ifndef FIPS_MODULE
if (ctx->bio_core != NULL) {
ossl_bio_core_globals_free(ctx->bio_core);
ctx->bio_core = NULL;
}
#endif
if (ctx->drbg_nonce != NULL) {
ossl_prov_drbg_nonce_ctx_free(ctx->drbg_nonce);
ctx->drbg_nonce = NULL;
}
#ifndef FIPS_MODULE
if (ctx->self_test_cb != NULL) {
ossl_self_test_set_callback_free(ctx->self_test_cb);
ctx->self_test_cb = NULL;
}
#endif
if (ctx->rand_crngt != NULL) {
ossl_rand_crng_ctx_free(ctx->rand_crngt);
ctx->rand_crngt = NULL;
}
#ifdef FIPS_MODULE
if (ctx->thread_event_handler != NULL) {
ossl_thread_event_ctx_free(ctx->thread_event_handler);
ctx->thread_event_handler = NULL;
}
if (ctx->fips_prov != NULL) {
ossl_fips_prov_ossl_ctx_free(ctx->fips_prov);
ctx->fips_prov = NULL;
}
#endif
#ifndef OPENSSL_NO_THREAD_POOL
if (ctx->threads != NULL) {
ossl_threads_ctx_free(ctx->threads);
ctx->threads = NULL;
}
#endif
/* Low priority. */
#ifndef FIPS_MODULE
if (ctx->child_provider != NULL) {
ossl_child_prov_ctx_free(ctx->child_provider);
ctx->child_provider = NULL;
}
#endif
}
static int context_deinit(OSSL_LIB_CTX *ctx)
{
if (ctx == NULL)
return 1;
ossl_ctx_thread_stop(ctx);
context_deinit_objs(ctx);
ossl_crypto_cleanup_all_ex_data_int(ctx);
CRYPTO_THREAD_lock_free(ctx->rand_crngt_lock);
CRYPTO_THREAD_lock_free(ctx->lock);
ctx->rand_crngt_lock = NULL;
ctx->lock = NULL;
return 1;
}
#ifndef FIPS_MODULE
/* The default default context */
static OSSL_LIB_CTX default_context_int;
static CRYPTO_ONCE default_context_init = CRYPTO_ONCE_STATIC_INIT;
static CRYPTO_THREAD_LOCAL default_context_thread_local;
static int default_context_inited = 0;
DEFINE_RUN_ONCE_STATIC(default_context_do_init)
{
if (!CRYPTO_THREAD_init_local(&default_context_thread_local, NULL))
goto err;
if (!context_init(&default_context_int))
goto deinit_thread;
default_context_inited = 1;
return 1;
deinit_thread:
CRYPTO_THREAD_cleanup_local(&default_context_thread_local);
err:
return 0;
}
void ossl_lib_ctx_default_deinit(void)
{
if (!default_context_inited)
return;
context_deinit(&default_context_int);
CRYPTO_THREAD_cleanup_local(&default_context_thread_local);
default_context_inited = 0;
}
static OSSL_LIB_CTX *get_thread_default_context(void)
{
if (!RUN_ONCE(&default_context_init, default_context_do_init))
return NULL;
return CRYPTO_THREAD_get_local(&default_context_thread_local);
}
static OSSL_LIB_CTX *get_default_context(void)
{
OSSL_LIB_CTX *current_defctx = get_thread_default_context();
if (current_defctx == NULL)
current_defctx = &default_context_int;
return current_defctx;
}
static int set_default_context(OSSL_LIB_CTX *defctx)
{
if (defctx == &default_context_int)
defctx = NULL;
return CRYPTO_THREAD_set_local(&default_context_thread_local, defctx);
}
#endif
OSSL_LIB_CTX *OSSL_LIB_CTX_new(void)
{
OSSL_LIB_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));
if (ctx != NULL && !context_init(ctx)) {
OPENSSL_free(ctx);
ctx = NULL;
}
return ctx;
}
#ifndef FIPS_MODULE
OSSL_LIB_CTX *OSSL_LIB_CTX_new_from_dispatch(const OSSL_CORE_HANDLE *handle,
const OSSL_DISPATCH *in)
{
OSSL_LIB_CTX *ctx = OSSL_LIB_CTX_new();
if (ctx == NULL)
return NULL;
if (!ossl_bio_init_core(ctx, in)) {
OSSL_LIB_CTX_free(ctx);
return NULL;
}
return ctx;
}
OSSL_LIB_CTX *OSSL_LIB_CTX_new_child(const OSSL_CORE_HANDLE *handle,
const OSSL_DISPATCH *in)
{
OSSL_LIB_CTX *ctx = OSSL_LIB_CTX_new_from_dispatch(handle, in);
if (ctx == NULL)
return NULL;
if (!ossl_provider_init_as_child(ctx, handle, in)) {
OSSL_LIB_CTX_free(ctx);
return NULL;
}
ctx->ischild = 1;
return ctx;
}
int OSSL_LIB_CTX_load_config(OSSL_LIB_CTX *ctx, const char *config_file)
{
return CONF_modules_load_file_ex(ctx, config_file, NULL, 0) > 0;
}
#endif
void OSSL_LIB_CTX_free(OSSL_LIB_CTX *ctx)
{
if (ossl_lib_ctx_is_default(ctx))
return;
#ifndef FIPS_MODULE
if (ctx->ischild)
ossl_provider_deinit_child(ctx);
#endif
context_deinit(ctx);
OPENSSL_free(ctx);
}
#ifndef FIPS_MODULE
OSSL_LIB_CTX *OSSL_LIB_CTX_get0_global_default(void)
{
if (!RUN_ONCE(&default_context_init, default_context_do_init))
return NULL;
return &default_context_int;
}
OSSL_LIB_CTX *OSSL_LIB_CTX_set0_default(OSSL_LIB_CTX *libctx)
{
OSSL_LIB_CTX *current_defctx;
if ((current_defctx = get_default_context()) != NULL) {
if (libctx != NULL)
set_default_context(libctx);
return current_defctx;
}
return NULL;
}
void ossl_release_default_drbg_ctx(void)
{
/* early release of the DRBG in global default libctx */
if (default_context_int.drbg != NULL) {
ossl_rand_ctx_free(default_context_int.drbg);
default_context_int.drbg = NULL;
}
}
#endif
OSSL_LIB_CTX *ossl_lib_ctx_get_concrete(OSSL_LIB_CTX *ctx)
{
#ifndef FIPS_MODULE
if (ctx == NULL)
return get_default_context();
#endif
return ctx;
}
int ossl_lib_ctx_is_default(OSSL_LIB_CTX *ctx)
{
#ifndef FIPS_MODULE
if (ctx == NULL || ctx == get_default_context())
return 1;
#endif
return 0;
}
int ossl_lib_ctx_is_global_default(OSSL_LIB_CTX *ctx)
{
#ifndef FIPS_MODULE
if (ossl_lib_ctx_get_concrete(ctx) == &default_context_int)
return 1;
#endif
return 0;
}
void *ossl_lib_ctx_get_data(OSSL_LIB_CTX *ctx, int index)
{
void *p;
ctx = ossl_lib_ctx_get_concrete(ctx);
if (ctx == NULL)
return NULL;
switch (index) {
case OSSL_LIB_CTX_PROPERTY_STRING_INDEX:
return ctx->property_string_data;
case OSSL_LIB_CTX_EVP_METHOD_STORE_INDEX:
return ctx->evp_method_store;
case OSSL_LIB_CTX_PROVIDER_STORE_INDEX:
return ctx->provider_store;
case OSSL_LIB_CTX_NAMEMAP_INDEX:
return ctx->namemap;
case OSSL_LIB_CTX_PROPERTY_DEFN_INDEX:
return ctx->property_defns;
case OSSL_LIB_CTX_GLOBAL_PROPERTIES:
return ctx->global_properties;
case OSSL_LIB_CTX_DRBG_INDEX:
return ctx->drbg;
case OSSL_LIB_CTX_DRBG_NONCE_INDEX:
return ctx->drbg_nonce;
#ifndef FIPS_MODULE
case OSSL_LIB_CTX_PROVIDER_CONF_INDEX:
return ctx->provider_conf;
case OSSL_LIB_CTX_BIO_CORE_INDEX:
return ctx->bio_core;
case OSSL_LIB_CTX_CHILD_PROVIDER_INDEX:
return ctx->child_provider;
case OSSL_LIB_CTX_DECODER_STORE_INDEX:
return ctx->decoder_store;
case OSSL_LIB_CTX_DECODER_CACHE_INDEX:
return ctx->decoder_cache;
case OSSL_LIB_CTX_ENCODER_STORE_INDEX:
return ctx->encoder_store;
case OSSL_LIB_CTX_STORE_LOADER_STORE_INDEX:
return ctx->store_loader_store;
case OSSL_LIB_CTX_SELF_TEST_CB_INDEX:
return ctx->self_test_cb;
#endif
#ifndef OPENSSL_NO_THREAD_POOL
case OSSL_LIB_CTX_THREAD_INDEX:
return ctx->threads;
#endif
case OSSL_LIB_CTX_RAND_CRNGT_INDEX: {
/*
* rand_crngt must be lazily initialized because it calls into
* libctx, so must not be called from context_init, else a deadlock
* will occur.
*
* We use a separate lock because code called by the instantiation
* of rand_crngt is liable to try and take the libctx lock.
*/
if (CRYPTO_THREAD_read_lock(ctx->rand_crngt_lock) != 1)
return NULL;
if (ctx->rand_crngt == NULL) {
CRYPTO_THREAD_unlock(ctx->rand_crngt_lock);
if (CRYPTO_THREAD_write_lock(ctx->rand_crngt_lock) != 1)
return NULL;
if (ctx->rand_crngt == NULL)
ctx->rand_crngt = ossl_rand_crng_ctx_new(ctx);
}
p = ctx->rand_crngt;
CRYPTO_THREAD_unlock(ctx->rand_crngt_lock);
return p;
}
#ifdef FIPS_MODULE
case OSSL_LIB_CTX_THREAD_EVENT_HANDLER_INDEX:
return ctx->thread_event_handler;
case OSSL_LIB_CTX_FIPS_PROV_INDEX:
return ctx->fips_prov;
#endif
default:
return NULL;
}
}
OSSL_EX_DATA_GLOBAL *ossl_lib_ctx_get_ex_data_global(OSSL_LIB_CTX *ctx)
{
ctx = ossl_lib_ctx_get_concrete(ctx);
if (ctx == NULL)
return NULL;
return &ctx->global;
}
const char *ossl_lib_ctx_get_descriptor(OSSL_LIB_CTX *libctx)
{
#ifdef FIPS_MODULE
return "FIPS internal library context";
#else
if (ossl_lib_ctx_is_global_default(libctx))
return "Global default library context";
if (ossl_lib_ctx_is_default(libctx))
return "Thread-local default library context";
return "Non-default library context";
#endif
}
|
4fd84dcc642e816b57e7db526e4c76422d45a4c9
|
56df6683865fd9319b389afd6dd4a922299da593
|
/source/reflect/include/reflect/reflect_scope.h
|
7789a8de2947b2f0f0bdf5fbdb6ceaf5a3e28aaa
|
[
"Python-2.0",
"GPL-2.0-or-later",
"MPL-1.1",
"NCSA",
"LicenseRef-scancode-proprietary-license",
"GPL-1.0-or-later",
"BSD-3-Clause",
"MPL-2.0",
"Ruby",
"BSD-2-Clause",
"MIT",
"Apache-2.0"
] |
permissive
|
metacall/core
|
4f36fe0b13924853aab6d0f053285b649398cc1d
|
419ffb573b17501c91662f0f161032bb19ea1ab3
|
refs/heads/develop
| 2023-08-23T10:19:30.898387
| 2023-08-10T18:39:08
| 2023-08-10T18:39:08
| 163,221,062
| 1,391
| 167
|
Apache-2.0
| 2023-09-13T23:49:43
| 2018-12-26T22:02:57
|
C
|
UTF-8
|
C
| false
| false
| 1,923
|
h
|
reflect_scope.h
|
/*
* Reflect Library by Parra Studios
* A library for provide reflection and metadata representation.
*
* Copyright (C) 2016 - 2022 Vicente Eduardo Ferrer Garcia <vic798@gmail.com>
*
* 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 REFLECT_SCOPE_H
#define REFLECT_SCOPE_H 1
#include <reflect/reflect_api.h>
#include <reflect/reflect_function.h>
#include <reflect/reflect_type.h>
#ifdef __cplusplus
extern "C" {
#endif
struct scope_type;
typedef size_t scope_stack_ptr;
typedef struct scope_type *scope;
REFLECT_API scope scope_create(const char *name);
REFLECT_API size_t scope_size(scope sp);
REFLECT_API int scope_define(scope sp, const char *key, value obj);
REFLECT_API value scope_metadata(scope sp);
REFLECT_API value scope_export(scope sp);
REFLECT_API value scope_get(scope sp, const char *key);
REFLECT_API value scope_undef(scope sp, const char *key);
REFLECT_API int scope_append(scope dest, scope src);
REFLECT_API int scope_contains(scope dest, scope src, char **duplicated);
REFLECT_API int scope_remove(scope dest, scope src);
REFLECT_API size_t *scope_stack_return(scope sp);
REFLECT_API scope_stack_ptr scope_stack_push(scope sp, size_t bytes);
REFLECT_API void *scope_stack_get(scope sp, scope_stack_ptr stack_ptr);
REFLECT_API int scope_stack_pop(scope sp);
REFLECT_API void scope_destroy(scope sp);
#ifdef __cplusplus
}
#endif
#endif /* REFLECT_SCOPE_H */
|
b036afefabbd1ef5dbad2420a62d2bc5802bcdcc
|
e552c5408e825acc3a00ae8ab8e0697beddf7a0a
|
/projects/stm8l05x/STM8L15x-16x-05x-AL31-L_StdPeriph_Lib/Libraries/STM8L15x_StdPeriph_Driver/src/stm8l15x_tim5.c
|
64a3af6cee1945831e22bc178ab1add7922f3bba
|
[
"MIT",
"PostgreSQL",
"ISC",
"BSD-3-Clause",
"BSL-1.0",
"BSD-2-Clause"
] |
permissive
|
xhawk18/s_task
|
f81dda8252bbb0631b564eb8775c8008bc4f5583
|
d1e9a348a570433f0f5655f64c8dd3b94a6d1cbe
|
refs/heads/master
| 2023-08-13T08:11:27.712894
| 2023-04-11T12:29:43
| 2023-04-11T12:29:43
| 242,364,894
| 552
| 88
| null | null | null | null |
MacCentralEurope
|
C
| false
| false
| 78,035
|
c
|
stm8l15x_tim5.c
|
/**
******************************************************************************
* @file stm8l15x_tim5.c
* @author MCD Application Team
* @version V1.6.1
* @date 30-September-2014
* @brief This file provides firmware functions to manage the following
* functionalities of the TIM5 peripheral:
* - TimeBase management
* - Output Compare management
* - Input Capture management
* - Interrupts, DMA and flags management
* - Clocks management
* - Synchronization management
* - Specific interface management
*
* @verbatim
*
* ===================================================================
* How to use this driver
* ===================================================================
* This driver provides functions to configure and initialize the TIM5
* peripheral
* These functions are split in 7 groups:
*
* 1. TIM5 TimeBase management: this group includes all needed functions
* to configure the TIM Timebase unit:
* - Set/Get Prescaler
* - Set/Get Autoreload
* - Counter modes configuration
* - Select the One Pulse mode
* - Update Request Configuration
* - Update Disable Configuration
* - Auto-Preload Configuration
* - Enable/Disable the counter
*
* 2. TIM5 Output Compare management: this group includes all needed
* functions to configure the Capture/Compare unit used in Output
* compare mode:
* - Configure each channel, independently, in Output Compare mode
* - Select the output compare modes
* - Select the Polarities of each channel
* - Set/Get the Capture/Compare register values
* - Select the Output Compare Fast mode
* - Select the Output Compare Forced mode
* - Output Compare-Preload Configuration
* - Enable/Disable the Capture/Compare Channels
*
* 3. TIM5 Input Capture management: this group includes all needed
* functions to configure the Capture/Compare unit used in
* Input Capture mode:
* - Configure each channel in input capture mode
* - Configure Channel1/2 in PWM Input mode
* - Set the Input Capture Prescaler
* - Get the Capture/Compare values
*
* 4. TIM5 interrupts, DMA and flags management
* - Enable/Disable interrupt sources
* - Get flags status
* - Clear flags/ Pending bits
* - Enable/Disable DMA requests
* - Select CaptureCompare DMA request
*
* 5. TIM5 clocks management: this group includes all needed functions
* to configure the clock controller unit:
* - Select internal/External clock
* - Select the external clock mode: ETR(Mode1/Mode2) or TIx
*
* 6. TIM5 synchronization management: this group includes all needed
* functions to configure the Synchronization unit:
* - Select Input Trigger
* - Select Output Trigger
* - Select Master Slave Mode
* - ETR Configuration when used as external trigger
*
* 7. TIM5 specific interface management, this group includes all
* needed functions to use the specific TIM5 interface:
* - Encoder Interface Configuration
* - Select Hall Sensor
*
* @endverbatim
*
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT 2014 STMicroelectronics</center></h2>
*
* Licensed under MCD-ST Liberty SW License Agreement V2, (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.st.com/software_license_agreement_liberty_v2
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm8l15x_TIM5.h"
/** @addtogroup STM8L15x_StdPeriph_Driver
* @{
*/
/** @defgroup TIM5
* @brief TIM5 driver modules
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
static void TI1_Config(TIM5_ICPolarity_TypeDef TIM5_ICPolarity,
TIM5_ICSelection_TypeDef TIM5_ICSelection,
uint8_t TIM5_ICFilter);
static void TI2_Config(TIM5_ICPolarity_TypeDef TIM5_ICPolarity,
TIM5_ICSelection_TypeDef TIM5_ICSelection,
uint8_t TIM5_ICFilter);
/** @defgroup TIM5_Private_Functions
* @{
*/
/** @defgroup TIM5_Group1 TimeBase management functions
* @brief TimeBase management functions
*
@verbatim
===============================================================================
TimeBase management functions
===============================================================================
===================================================================
TIM5 Driver: how to use it in Timing(Time base) Mode
===================================================================
To use the Timer in Timing(Time base) mode, the following steps are mandatory:
1. Enable TIM5 clock using CLK_PeripheralClockConfig(CLK_Peripheral_TIM5, ENABLE) function.
2. Call TIM5_TimeBaseInit() to configure the Time Base unit with the
corresponding configuration.
3. Enable global interrupts if you need to generate the update interrupt.
4. Enable the corresponding interrupt using the function TIM5_ITConfig(TIM5_IT_Update)
5. Call the TIM5_Cmd(ENABLE) function to enable the TIM5 counter.
Note1: All other functions can be used separately to modify, if needed,
a specific feature of the Timer.
@endverbatim
* @{
*/
/**
* @brief Deinitialize the TIM5 peripheral registers to their default reset values.
* @param None
* @retval None
*/
void TIM5_DeInit(void)
{
TIM5->CR1 = TIM_CR1_RESET_VALUE;
TIM5->CR2 = TIM_CR2_RESET_VALUE;
TIM5->SMCR = TIM_SMCR_RESET_VALUE;
TIM5->ETR = TIM_ETR_RESET_VALUE;
TIM5->IER = TIM_IER_RESET_VALUE;
TIM5->SR2 = TIM_SR2_RESET_VALUE;
/* Disable channels */
TIM5->CCER1 = TIM_CCER1_RESET_VALUE;
/* Configure channels as inputs: it is necessary if lock level is equal to 2 or 3 */
TIM5->CCMR1 = 0x01;/*TIM5_ICxSource_TIxFPx */
TIM5->CCMR2 = 0x01;/*TIM5_ICxSource_TIxFPx */
/* Then reset channel registers: it also works if lock level is equal to 2 or 3 */
TIM5->CCER1 = TIM_CCER1_RESET_VALUE;
TIM5->CCMR1 = TIM_CCMR1_RESET_VALUE;
TIM5->CCMR2 = TIM_CCMR2_RESET_VALUE;
TIM5->CNTRH = TIM_CNTRH_RESET_VALUE;
TIM5->CNTRL = TIM_CNTRL_RESET_VALUE;
TIM5->PSCR = TIM_PSCR_RESET_VALUE;
TIM5->ARRH = TIM_ARRH_RESET_VALUE;
TIM5->ARRL = TIM_ARRL_RESET_VALUE;
TIM5->CCR1H = TIM_CCR1H_RESET_VALUE;
TIM5->CCR1L = TIM_CCR1L_RESET_VALUE;
TIM5->CCR2H = TIM_CCR2H_RESET_VALUE;
TIM5->CCR2L = TIM_CCR2L_RESET_VALUE;
TIM5->OISR = TIM_OISR_RESET_VALUE;
TIM5->EGR = 0x01;/* TIM_EGR_UG */
TIM5->BKR = TIM_BKR_RESET_VALUE;
TIM5->SR1 = TIM_SR1_RESET_VALUE;
}
/**
* @brief Initializes the TIM5 Time Base Unit according to the specified parameters.
* @param TIM5_Prescaler: Prescaler
* This parameter can be one of the following values:
* @arg TIM5_Prescaler_1: Time base Prescaler = 1 (No effect)
* @arg TIM5_Prescaler_2: Time base Prescaler = 2
* @arg TIM5_Prescaler_4: Time base Prescaler = 4
* @arg TIM5_Prescaler_8: Time base Prescaler = 8
* @arg TIM5_Prescaler_16: Time base Prescaler = 16
* @arg TIM5_Prescaler_32: Time base Prescaler = 32
* @arg TIM5_Prescaler_64: Time base Prescaler = 64
* @arg TIM5_Prescaler_128: Time base Prescaler = 128
* @param TIM5_CounterMode: Counter mode
* This parameter can be one of the following values:
* @arg TIM5_CounterMode_Up: Counter Up Mode
* @arg TIM5_CounterMode_Down: Counter Down Mode
* @arg TIM5_CounterMode_CenterAligned1: Counter Central aligned Mode 1
* @arg TIM5_CounterMode_CenterAligned2: Counter Central aligned Mode 2
* @arg TIM5_CounterMode_CenterAligned3: Counter Central aligned Mode 3
* @param TIM5_Period: This parameter must be a value between 0x0000 and 0xFFFF.
* @retval None
*/
void TIM5_TimeBaseInit(TIM5_Prescaler_TypeDef TIM5_Prescaler,
TIM5_CounterMode_TypeDef TIM5_CounterMode,
uint16_t TIM5_Period)
{
assert_param(IS_TIM5_PRESCALER(TIM5_Prescaler));
assert_param(IS_TIM5_COUNTER_MODE(TIM5_CounterMode));
/* Set the Autoreload value */
TIM5->ARRH = (uint8_t)(TIM5_Period >> 8) ;
TIM5->ARRL = (uint8_t)(TIM5_Period);
/* Set the Prescaler value */
TIM5->PSCR = (uint8_t)(TIM5_Prescaler);
/* Select the Counter Mode */
TIM5->CR1 &= (uint8_t)((uint8_t)(~TIM_CR1_CMS)) & ((uint8_t)(~TIM_CR1_DIR));
TIM5->CR1 |= (uint8_t)(TIM5_CounterMode);
/* Generate an update event to reload the Prescaler value immediately */
TIM5->EGR = TIM5_EventSource_Update;
}
/**
* @brief Configures the TIM5 Prescaler.
* @param Prescaler: Specifies the Prescaler Register value
* This parameter can be one of the following values:
* @arg TIM5_Prescaler_1: Time base Prescaler = 1 (No effect)
* @arg TIM5_Prescaler_2: Time base Prescaler = 2
* @arg TIM5_Prescaler_4: Time base Prescaler = 4
* @arg TIM5_Prescaler_8: Time base Prescaler = 8
* @arg TIM5_Prescaler_16: Time base Prescaler = 16
* @arg TIM5_Prescaler_32: Time base Prescaler = 32
* @arg TIM5_Prescaler_64: Time base Prescaler = 64
* @arg TIM5_Prescaler_128: Time base Prescaler = 128
* @param TIM5_PSCReloadMode: Specifies the TIM5 Prescaler Reload mode.
* This parameter can be one of the following values:
* @arg TIM5_PSCReloadMode_Update: Prescaler value is reloaded at every update
* @arg TIM5_PSCReloadMode_Immediate: Prescaler value is reloaded at every update
* @retval None
*/
void TIM5_PrescalerConfig(TIM5_Prescaler_TypeDef Prescaler,
TIM5_PSCReloadMode_TypeDef TIM5_PSCReloadMode)
{
/* Check the parameters */
assert_param(IS_TIM5_PRESCALER(Prescaler));
assert_param(IS_TIM5_PRESCALER_RELOAD(TIM5_PSCReloadMode));
/* Set the Prescaler value */
TIM5->PSCR = (uint8_t)(Prescaler);
/* Set or reset the UG Bit */
if (TIM5_PSCReloadMode == TIM5_PSCReloadMode_Immediate)
{
TIM5->EGR |= TIM_EGR_UG ;
}
else
{
TIM5->EGR &= (uint8_t)(~TIM_EGR_UG) ;
}
}
/**
* @brief Specifies the TIM5 Counter Mode to be used.
* @param TIM5_CounterMode: Specifies the Counter Mode to be used
* This parameter can be one of the following values:
* @arg TIM5_CounterMode_Up: Counter Up Mode
* @arg TIM5_CounterMode_Down: Counter Down Mode
* @arg TIM5_CounterMode_CenterAligned1: Counter Central aligned Mode 1
* @arg TIM5_CounterMode_CenterAligned2: Counter Central aligned Mode 2
* @arg TIM5_CounterMode_CenterAligned3: Counter Central aligned Mode 3
* @retval None
*/
void TIM5_CounterModeConfig(TIM5_CounterMode_TypeDef TIM5_CounterMode)
{
uint8_t tmpcr1 = 0;
/* Check the parameters */
assert_param(IS_TIM5_COUNTER_MODE(TIM5_CounterMode));
tmpcr1 = TIM5->CR1;
/* Reset the CMS and DIR Bits */
tmpcr1 &= (uint8_t)((uint8_t)(~TIM_CR1_CMS) & (uint8_t)(~TIM_CR1_DIR));
/* Set the Counter Mode */
tmpcr1 |= (uint8_t)TIM5_CounterMode;
TIM5->CR1 = tmpcr1;
}
/**
* @brief Sets the TIM5 Counter Register value.
* @param Counter: Specifies the Counter register new value.
* This parameter is between 0x0000 and 0xFFFF.
* @retval None
*/
void TIM5_SetCounter(uint16_t Counter)
{
/* Set the Counter Register value */
TIM5->CNTRH = (uint8_t)(Counter >> 8);
TIM5->CNTRL = (uint8_t)(Counter);
}
/**
* @brief Sets the TIM5 Autoreload Register value.
* @param Autoreload: Specifies the Autoreload register new value.
* This parameter is between 0x0000 and 0xFFFF.
* @retval None
*/
void TIM5_SetAutoreload(uint16_t Autoreload)
{
/* Set the Autoreload Register value */
TIM5->ARRH = (uint8_t)(Autoreload >> 8);
TIM5->ARRL = (uint8_t)(Autoreload);
}
/**
* @brief Gets the TIM5 Counter value.
* @param None
* @retval Counter Register value.
*/
uint16_t TIM5_GetCounter(void)
{
uint16_t tmpcnt = 0;
uint8_t tmpcntrl, tmpcntrh;
tmpcntrh = TIM5->CNTRH;
tmpcntrl = TIM5->CNTRL;
tmpcnt = (uint16_t)(tmpcntrl);
tmpcnt |= (uint16_t)((uint16_t)tmpcntrh << 8);
/* Get the Counter Register value */
return ((uint16_t)tmpcnt);
}
/**
* @brief Gets the TIM5 Prescaler value.
* @param None
* @retval TIM5 Prescaler, it can be one of the following values:
* - TIM5_Prescaler_1: Time base Prescaler = 1 (No effect)
* - TIM5_Prescaler_2: Time base Prescaler = 2
* - TIM5_Prescaler_4: Time base Prescaler = 4
* - TIM5_Prescaler_8: Time base Prescaler = 8
* - TIM5_Prescaler_16: Time base Prescaler = 16
* - TIM5_Prescaler_32: Time base Prescaler = 32
* - TIM5_Prescaler_64: Time base Prescaler = 64
* - TIM5_Prescaler_128: Time base Prescaler = 128
*/
TIM5_Prescaler_TypeDef TIM5_GetPrescaler(void)
{
/* Get the Prescaler Register value */
return ((TIM5_Prescaler_TypeDef)TIM5->PSCR);
}
/**
* @brief Enables or Disables the TIM5 Update event.
* @param NewState: The new state of the TIM5 peripheral Preload register.
* This parameter can be ENABLE or DISABLE
* @retval None
*/
void TIM5_UpdateDisableConfig(FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_FUNCTIONAL_STATE(NewState));
/* Set or Reset the UDIS Bit */
if (NewState != DISABLE)
{
TIM5->CR1 |= TIM_CR1_UDIS;
}
else
{
TIM5->CR1 &= (uint8_t)(~TIM_CR1_UDIS);
}
}
/**
* @brief Selects the TIM5 Update Request Interrupt source.
* @param TIM5_UpdateSource: Specifies the Update source.
* This parameter can be one of the following values:
* @arg TIM5_UpdateSource_Global: Global Update request source
* @arg TIM5_UpdateSource_Regular: Regular Update request source
* @retval None
*/
void TIM5_UpdateRequestConfig(TIM5_UpdateSource_TypeDef TIM5_UpdateSource)
{
/* Check the parameters */
assert_param(IS_TIM5_UPDATE_SOURCE(TIM5_UpdateSource));
/* Set or Reset the URS Bit */
if (TIM5_UpdateSource == TIM5_UpdateSource_Regular)
{
TIM5->CR1 |= TIM_CR1_URS ;
}
else
{
TIM5->CR1 &= (uint8_t)(~TIM_CR1_URS);
}
}
/**
* @brief Enables or disables TIM5 peripheral Preload register on ARR.
* @param NewState: The new state of the TIM5 peripheral Preload register.
* This parameter can be ENABLE or DISABLE
* @retval None
*/
void TIM5_ARRPreloadConfig(FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_FUNCTIONAL_STATE(NewState));
/* Set or Reset the ARPE Bit */
if (NewState != DISABLE)
{
TIM5->CR1 |= TIM_CR1_ARPE;
}
else
{
TIM5->CR1 &= (uint8_t)(~TIM_CR1_ARPE);
}
}
/**
* @brief Selects the TIMís One Pulse Mode.
* @param TIM5_OPMode: Specifies the OPM Mode to be used.
* This parameter can be one of the following values:
* @arg TIM5_OPMode_Single: Single one Pulse mode (OPM Active)
* @arg TIM5_OPMode_Repetitive: Single one Pulse mode (OPM Active)
* @retval None
*/
void TIM5_SelectOnePulseMode(TIM5_OPMode_TypeDef TIM5_OPMode)
{
/* Check the parameters */
assert_param(IS_TIM5_OPM_MODE(TIM5_OPMode));
/* Set or Reset the OPM Bit */
if (TIM5_OPMode == TIM5_OPMode_Single)
{
TIM5->CR1 |= TIM_CR1_OPM ;
}
else
{
TIM5->CR1 &= (uint8_t)(~TIM_CR1_OPM);
}
}
/**
* @brief Enables or disables the TIM5 peripheral.
* @param NewState: The new state of the TIM5 peripheral.
* This parameter can be ENABLE or DISABLE
* @retval None
*/
void TIM5_Cmd(FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_FUNCTIONAL_STATE(NewState));
/* set or Reset the CEN Bit */
if (NewState != DISABLE)
{
TIM5->CR1 |= TIM_CR1_CEN;
}
else
{
TIM5->CR1 &= (uint8_t)(~TIM_CR1_CEN);
}
}
/**
* @}
*/
/** @defgroup TIM5_Group2 Output Compare management functions
* @brief Output Compare management functions
*
@verbatim
===============================================================================
Output Compare management functions
===============================================================================
===================================================================
TIM5 Driver: how to use it in Output Compare Mode
===================================================================
To use the Timer in Output Compare mode, the following steps are mandatory:
1. Enable TIM5 clock using CLK_PeripheralClockConfig(CLK_Peripheral_TIM5, ENABLE) function.
2. Configure the TIM5 pins in output mode by configuring the corresponding GPIO pins
3. Configure the Time base unit as described in the first part of this driver, if needed,
otherwise the Timer will run with the default configuration:
- Autoreload value = 0xFFFF
- Prescaler value = 0x0000
- Counter mode = Up counting
4. Call TIM5_OCxInit() to configure the channel x with the desired parameters
including:
- TIM5 Output Compare mode: TIM5_OCMode
- TIM5 Output State: TIM5_OutputState
- TIM5 Pulse value: TIM5_Pulse
- TIM5 Output Compare Polarity: TIM5_OCPolarity
- TIM5 Output Idle State: TIM5_OCIdleState
5. Call the TIM5_Cmd(ENABLE) function to enable the TIM5 counter.
Note1: All other functions can be used separately to modify, if needed,
a specific feature of the Timer.
Note2: If the corresponding interrupt or DMA request are needed, the user should:
1. Enable global interrupts (or the DMA) to use the TIM5 interrupts (or DMA requests).
2. Enable the corresponding interrupt (or DMA request) using the function
TIM5_ITConfig(TIM5_IT_CCx) (or TIM5_DMACmd(TIM5_DMASource_CCx))
@endverbatim
* @{
*/
/**
* @brief Initializes the TIM5 Channel1 according to the specified parameters.
* @param TIM5_OCMode: Output Compare Mode
* This parameter can be one of the following values:
* @arg TIM5_OCMode_Timing: Timing (Frozen) Mode
* @arg TIM5_OCMode_Active: Active Mode
* @arg TIM5_OCMode_Inactive: Inactive Mode
* @arg TIM5_OCMode_Toggle: Toggle Mode
* @arg TIM5_OCMode_PWM1: PWM Mode 1
* @arg TIM5_OCMode_PWM2: PWM Mode 2
* @param TIM5_OutputState: Output state
* This parameter can be one of the following values:
* @arg TIM5_OutputState_Disable: Output compare State disabled (channel output disabled)
* @arg TIM5_OutputState_Enable: Output compare State enabled (channel output enabled)
* @param TIM5_Pulse: This parameter must be a value between 0x0000 and 0xFFFF.
* @param TIM5_OCPolarity: Polarity
* This parameter can be one of the following values:
* @arg TIM5_OCPolarity_High: Output compare polarity = High
* @arg TIM5_OCPolarity_Low: Output compare polarity = Low
* @param TIM5_OCIdleState: Output Compare Idle State
* This parameter can be one of the following values:
* @arg TIM5_OCIdleState_Reset: Output Compare Idle state = Reset
* @arg TIM5_OCIdleState_Set: Output Compare Idle state = Set
* @retval None
*/
void TIM5_OC1Init(TIM5_OCMode_TypeDef TIM5_OCMode,
TIM5_OutputState_TypeDef TIM5_OutputState,
uint16_t TIM5_Pulse,
TIM5_OCPolarity_TypeDef TIM5_OCPolarity,
TIM5_OCIdleState_TypeDef TIM5_OCIdleState)
{
uint8_t tmpccmr1 = 0;
/* Check the parameters */
assert_param(IS_TIM5_OC_MODE(TIM5_OCMode));
assert_param(IS_TIM5_OUTPUT_STATE(TIM5_OutputState));
assert_param(IS_TIM5_OC_POLARITY(TIM5_OCPolarity));
assert_param(IS_TIM5_OCIDLE_STATE(TIM5_OCIdleState));
tmpccmr1 = TIM5->CCMR1;
/* Disable the Channel 1: Reset the CCE Bit */
TIM5->CCER1 &= (uint8_t)(~TIM_CCER1_CC1E);
/* Reset the Output Compare Bits */
tmpccmr1 &= (uint8_t)(~TIM_CCMR_OCM);
/* Set the Output Compare Mode */
tmpccmr1 |= (uint8_t)TIM5_OCMode;
TIM5->CCMR1 = tmpccmr1;
/* Set the Output State */
if (TIM5_OutputState == TIM5_OutputState_Enable)
{
TIM5->CCER1 |= TIM_CCER1_CC1E;
}
else
{
TIM5->CCER1 &= (uint8_t)(~TIM_CCER1_CC1E);
}
/* Set the Output Polarity */
if (TIM5_OCPolarity == TIM5_OCPolarity_Low)
{
TIM5->CCER1 |= TIM_CCER1_CC1P;
}
else
{
TIM5->CCER1 &= (uint8_t)(~TIM_CCER1_CC1P);
}
/* Set the Output Idle state */
if (TIM5_OCIdleState == TIM5_OCIdleState_Set)
{
TIM5->OISR |= TIM_OISR_OIS1;
}
else
{
TIM5->OISR &= (uint8_t)(~TIM_OISR_OIS1);
}
/* Set the Pulse value */
TIM5->CCR1H = (uint8_t)(TIM5_Pulse >> 8);
TIM5->CCR1L = (uint8_t)(TIM5_Pulse);
}
/**
* @brief Initializes the TIM5 Channel2 according to the specified parameters.
* @param TIM5_OCMode: Output Compare Mode
* This parameter can be one of the following values:
* @arg TIM5_OCMode_Timing: Timing (Frozen) Mode
* @arg TIM5_OCMode_Active: Active Mode
* @arg TIM5_OCMode_Inactive: Inactive Mode
* @arg TIM5_OCMode_Toggle: Toggle Mode
* @arg TIM5_OCMode_PWM1: PWM Mode 1
* @arg TIM5_OCMode_PWM2: PWM Mode 2
* @param TIM5_OutputState: Output state
* This parameter can be one of the following values:
* @arg TIM5_OutputState_Disable: Output compare State disabled (channel output disabled)
* @arg TIM5_OutputState_Enable: Output compare State enabled (channel output enabled)
* @param TIM5_Pulse: This parameter must be a value between 0x0000 and 0xFFFF.
* @param TIM5_OCPolarity: Polarity
* This parameter can be one of the following values:
* @arg TIM5_OCPolarity_High: Output compare polarity = High
* @arg TIM5_OCPolarity_Low: Output compare polarity = Low
* @param TIM5_OCIdleState: Output Compare Idle State
* This parameter can be one of the following values:
* @arg TIM5_OCIdleState_Reset: Output Compare Idle state = Reset
* @arg TIM5_OCIdleState_Set: Output Compare Idle state = Set
* @retval None
*/
void TIM5_OC2Init(TIM5_OCMode_TypeDef TIM5_OCMode,
TIM5_OutputState_TypeDef TIM5_OutputState,
uint16_t TIM5_Pulse,
TIM5_OCPolarity_TypeDef TIM5_OCPolarity,
TIM5_OCIdleState_TypeDef TIM5_OCIdleState)
{
uint8_t tmpccmr2 = 0;
/* Check the parameters */
assert_param(IS_TIM5_OC_MODE(TIM5_OCMode));
assert_param(IS_TIM5_OUTPUT_STATE(TIM5_OutputState));
assert_param(IS_TIM5_OC_POLARITY(TIM5_OCPolarity));
assert_param(IS_TIM5_OCIDLE_STATE(TIM5_OCIdleState));
tmpccmr2 = TIM5->CCMR2;
/* Disable the Channel 2: Reset the CCE Bit */
TIM5->CCER1 &= (uint8_t)(~TIM_CCER1_CC2E);
/* Reset the Output Compare Bits */
tmpccmr2 &= (uint8_t)(~TIM_CCMR_OCM);
/* Set the Output Compare Mode */
tmpccmr2 |= (uint8_t)TIM5_OCMode;
TIM5->CCMR2 = tmpccmr2;
/* Set the Output State */
if (TIM5_OutputState == TIM5_OutputState_Enable)
{
TIM5->CCER1 |= TIM_CCER1_CC2E;
}
else
{
TIM5->CCER1 &= (uint8_t)(~TIM_CCER1_CC2E);
}
/* Set the Output Polarity */
if (TIM5_OCPolarity == TIM5_OCPolarity_Low)
{
TIM5->CCER1 |= TIM_CCER1_CC2P;
}
else
{
TIM5->CCER1 &= (uint8_t)(~TIM_CCER1_CC2P);
}
/* Set the Output Idle state */
if (TIM5_OCIdleState == TIM5_OCIdleState_Set)
{
TIM5->OISR |= TIM_OISR_OIS2;
}
else
{
TIM5->OISR &= (uint8_t)(~TIM_OISR_OIS2);
}
/* Set the Pulse value */
TIM5->CCR2H = (uint8_t)(TIM5_Pulse >> 8);
TIM5->CCR2L = (uint8_t)(TIM5_Pulse);
}
/**
* @brief Configures the Break feature, dead time, Lock level, the OSSI,
* and the AOE(automatic output enable).
* @param TIM5_OSSIState: Off-State Selection for Idle mode states.
* This parameter can be one of the following values:
* @arg TIM5_OSSIState_Enable: Off-State Selection for Idle mode enabled
* @arg TIM5_OSSIState_Disable: Off-State Selection for Idle mode disabled
* @param TIM5_LockLevel: Lock level.
* This parameter can be one of the following values:
* @arg TIM5_LockLevel_Off: Lock option disabled
* @arg TIM5_LockLevel_1: Select Lock Level 1
* @arg TIM5_LockLevel_2: Select Lock Level 2
* @arg TIM5_LockLevel_3: Select Lock Level 3
* @param TIM5_BreakState: Break Input enable/disable .
* This parameter can be one of the following values:
* @arg TIM5_BreakState_Disable: Break State disabled (break option disabled)
* @arg TIM5_BreakState_Enable: Break State enabled (break option enabled)
* @param TIM5_BreakPolarity: Break Polarity.
* This parameter can be one of the following values:
* @arg TIM5_BreakPolarity_High: if Break, channel polarity = High
* @arg TIM5_BreakPolarity_Low: if Break, channel polarity = Low
* @param TIM5_AutomaticOutput: TIM5 AOE Bit Set/Reset .
* This parameter can be one of the following values:
* @arg TIM5_AutomaticOutput_Enable: Automatic Output option enabled
* @arg TIM5_AutomaticOutput_Disable: Automatic Output option disabled
* @retval None
*/
void TIM5_BKRConfig(TIM5_OSSIState_TypeDef TIM5_OSSIState,
TIM5_LockLevel_TypeDef TIM5_LockLevel,
TIM5_BreakState_TypeDef TIM5_BreakState,
TIM5_BreakPolarity_TypeDef TIM5_BreakPolarity,
TIM5_AutomaticOutput_TypeDef TIM5_AutomaticOutput)
{
/* Check the parameters */
assert_param(IS_TIM5_OSSI_STATE(TIM5_OSSIState));
assert_param(IS_TIM5_LOCK_LEVEL(TIM5_LockLevel));
assert_param(IS_TIM5_BREAK_STATE(TIM5_BreakState));
assert_param(IS_TIM5_BREAK_POLARITY(TIM5_BreakPolarity));
assert_param(IS_TIM5_AUTOMATIC_OUTPUT_STATE(TIM5_AutomaticOutput));
/* Set the Lock level, the Break enable Bit and the Polarity, the OSSI State,
the dead time value and the Automatic Output Enable Bit */
TIM5->BKR = (uint8_t)((uint8_t)((uint8_t)((uint8_t)((uint8_t)TIM5_OSSIState | (uint8_t)TIM5_LockLevel) | \
(uint8_t)((uint8_t)TIM5_BreakState | (uint8_t)TIM5_BreakPolarity)) | \
TIM5_AutomaticOutput));
}
/**
* @brief Enables or disables the TIM5 peripheral Main Outputs.
* @param NewState: The new state of the TIM5 peripheral.
* This parameter can be ENABLE or DISABLE
* @retval None
*/
void TIM5_CtrlPWMOutputs(FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_FUNCTIONAL_STATE(NewState));
/* Set or Reset the MOE Bit */
if (NewState != DISABLE)
{
TIM5->BKR |= TIM_BKR_MOE ;
}
else
{
TIM5->BKR &= (uint8_t)(~TIM_BKR_MOE) ;
}
}
/**
* @brief Selects the TIM5 Output Compare Mode. This function disables the
* selected channel before changing the Output Compare Mode. User has to
* enable this channel using TIM5_CCxCmd and TIM5_CCxNCmd functions.
* @param TIM5_Channel: Specifies the TIM5 Channel.
* This parameter can be one of the following values:
* @arg TIM5_Channel_1: Channel 1
* @arg TIM5_Channel_2: Channel 2
* @param TIM5_OCMode: Specifies the TIM5 Output Compare Mode.
* This parameter can be one of the following values:
* @arg TIM5_OCMode_Timing: Timing (Frozen) Mode
* @arg TIM5_OCMode_Active: Active Mode
* @arg TIM5_OCMode_Inactive: Inactive Mode
* @arg TIM5_OCMode_Toggle: Toggle Mode
* @arg TIM5_OCMode_PWM1: PWM Mode 1
* @arg TIM5_OCMode_PWM2: PWM Mode 2
* @retval None
*/
void TIM5_SelectOCxM(TIM5_Channel_TypeDef TIM5_Channel,
TIM5_OCMode_TypeDef TIM5_OCMode)
{
/* Check the parameters */
assert_param(IS_TIM5_CHANNEL(TIM5_Channel));
assert_param(IS_TIM5_OCM(TIM5_OCMode));
if (TIM5_Channel == TIM5_Channel_1)
{
/* Disable the Channel 1: Reset the CCE Bit */
TIM5->CCER1 &= (uint8_t)(~TIM_CCER1_CC1E);
/* Reset the Output Compare Bits */
TIM5->CCMR1 &= (uint8_t)(~TIM_CCMR_OCM);
/* Set the Output Compare Mode */
TIM5->CCMR1 |= (uint8_t)TIM5_OCMode;
}
else /* if (TIM5_Channel == TIM5_Channel_2) */
{
/* Disable the Channel 2: Reset the CCE Bit */
TIM5->CCER1 &= (uint8_t)(~TIM_CCER1_CC2E);
/* Reset the Output Compare Bits */
TIM5->CCMR2 &= (uint8_t)(~TIM_CCMR_OCM);
/* Set the Output Compare Mode */
TIM5->CCMR2 |= (uint8_t)TIM5_OCMode;
}
}
/**
* @brief Sets the TIM5 Capture Compare1 Register value.
* @param Compare: Specifies the Capture Compare1 register new value.
* This parameter is between 0x0000 and 0xFFFF.
* @retval None
*/
void TIM5_SetCompare1(uint16_t Compare)
{
/* Set the Capture Compare1 Register value */
TIM5->CCR1H = (uint8_t)(Compare >> 8);
TIM5->CCR1L = (uint8_t)(Compare);
}
/**
* @brief Sets the TIM5 Capture Compare2 Register value.
* @param Compare: Specifies the Capture Compare2 register new value.
* This parameter is between 0x0000 and 0xFFFF.
* @retval None
*/
void TIM5_SetCompare2(uint16_t Compare)
{
/* Set the Capture Compare2 Register value */
TIM5->CCR2H = (uint8_t)(Compare >> 8);
TIM5->CCR2L = (uint8_t)(Compare);
}
/**
* @brief Forces the TIM5 Channel1 output waveform to active or inactive level.
* @param TIM5_ForcedAction: Specifies the forced Action to be set to the output waveform.
* This parameter can be one of the following values:
* @arg TIM5_ForcedAction_Active: Output Reference is forced low
* @arg TIM5_ForcedAction_Inactive: Output Reference is forced high
* @retval None
*/
void TIM5_ForcedOC1Config(TIM5_ForcedAction_TypeDef TIM5_ForcedAction)
{
uint8_t tmpccmr1 = 0;
/* Check the parameters */
assert_param(IS_TIM5_FORCED_ACTION(TIM5_ForcedAction));
tmpccmr1 = TIM5->CCMR1;
/* Reset the OCM Bits */
tmpccmr1 &= (uint8_t)(~TIM_CCMR_OCM);
/* Configure The Forced output Mode */
tmpccmr1 |= (uint8_t)TIM5_ForcedAction;
TIM5->CCMR1 = tmpccmr1;
}
/**
* @brief Forces the TIM5 Channel2 output waveform to active or inactive level.
* @param TIM5_ForcedAction: Specifies the forced Action to be set to the output waveform.
* This parameter can be one of the following values:
* @arg TIM5_ForcedAction_Active: Output Reference is forced low
* @arg TIM5_ForcedAction_Inactive: Output Reference is forced high
* @retval None
*/
void TIM5_ForcedOC2Config(TIM5_ForcedAction_TypeDef TIM5_ForcedAction)
{
uint8_t tmpccmr2 = 0;
/* Check the parameters */
assert_param(IS_TIM5_FORCED_ACTION(TIM5_ForcedAction));
tmpccmr2 = TIM5->CCMR2;
/* Reset the OCM Bits */
tmpccmr2 &= (uint8_t)(~TIM_CCMR_OCM);
/* Configure The Forced output Mode */
tmpccmr2 |= (uint8_t)TIM5_ForcedAction;
TIM5->CCMR2 = tmpccmr2;
}
/**
* @brief Enables or disables the TIM5 peripheral Preload Register on CCR1.
* @param NewState: The new state of the Capture Compare Preload register.
* This parameter can be ENABLE or DISABLE
* @retval None
*/
void TIM5_OC1PreloadConfig(FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_FUNCTIONAL_STATE(NewState));
/* Set or Reset the OC1PE Bit */
if (NewState != DISABLE)
{
TIM5->CCMR1 |= TIM_CCMR_OCxPE ;
}
else
{
TIM5->CCMR1 &= (uint8_t)(~TIM_CCMR_OCxPE) ;
}
}
/**
* @brief Enables or disables the TIM5 peripheral Preload Register on CCR2.
* @param NewState: The new state of the Capture Compare Preload register.
* This parameter can be ENABLE or DISABLE
* @retval None
*/
void TIM5_OC2PreloadConfig(FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_FUNCTIONAL_STATE(NewState));
/* Set or Reset the OC2PE Bit */
if (NewState != DISABLE)
{
TIM5->CCMR2 |= TIM_CCMR_OCxPE ;
}
else
{
TIM5->CCMR2 &= (uint8_t)(~TIM_CCMR_OCxPE) ;
}
}
/**
* @brief Configures the TIM5 Capture Compare 1 Fast feature.
* @param NewState: The new state of the Output Compare Fast Enable bit.
* This parameter can be ENABLE or DISABLE
* @retval None
*/
void TIM5_OC1FastConfig(FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_FUNCTIONAL_STATE(NewState));
/* Set or Reset the OC1FE Bit */
if (NewState != DISABLE)
{
TIM5->CCMR1 |= TIM_CCMR_OCxFE ;
}
else
{
TIM5->CCMR1 &= (uint8_t)(~TIM_CCMR_OCxFE) ;
}
}
/**
* @brief Configures the TIM5 Capture Compare 2 Fast feature.
* @param NewState: The new state of the Output Compare Fast Enable bit.
* This parameter can be ENABLE or DISABLE
* @retval None
*/
void TIM5_OC2FastConfig(FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_FUNCTIONAL_STATE(NewState));
/* Set or Reset the OC2FE Bit */
if (NewState != DISABLE)
{
TIM5->CCMR2 |= TIM_CCMR_OCxFE ;
}
else
{
TIM5->CCMR2 &= (uint8_t)(~TIM_CCMR_OCxFE) ;
}
}
/**
* @brief Configures the TIM5 Channel 1 polarity.
* @param TIM5_OCPolarity: Specifies the OC1 Polarity.
* This parameter can be one of the following values:
* @arg TIM5_OCPolarity_High: Output compare polarity = High
* @arg TIM5_OCPolarity_Low: Output compare polarity = Low
* @retval None
*/
void TIM5_OC1PolarityConfig(TIM5_OCPolarity_TypeDef TIM5_OCPolarity)
{
/* Check the parameters */
assert_param(IS_TIM5_OC_POLARITY(TIM5_OCPolarity));
/* Set or Reset the CC1P Bit */
if (TIM5_OCPolarity == TIM5_OCPolarity_Low)
{
TIM5->CCER1 |= TIM_CCER1_CC1P ;
}
else
{
TIM5->CCER1 &= (uint8_t)(~TIM_CCER1_CC1P) ;
}
}
/**
* @brief Configures the TIM5 Channel 2 polarity.
* @param TIM5_OCPolarity: Specifies the OC2 Polarity.
* This parameter can be one of the following values:
* @arg TIM5_OCPolarity_High: Output compare polarity = High
* @arg TIM5_OCPolarity_Low: Output compare polarity = Low
* @retval None
*/
void TIM5_OC2PolarityConfig(TIM5_OCPolarity_TypeDef TIM5_OCPolarity)
{
/* Check the parameters */
assert_param(IS_TIM5_OC_POLARITY(TIM5_OCPolarity));
/* Set or Reset the CC2P Bit */
if (TIM5_OCPolarity == TIM5_OCPolarity_Low)
{
TIM5->CCER1 |= TIM_CCER1_CC2P ;
}
else
{
TIM5->CCER1 &= (uint8_t)(~TIM_CCER1_CC2P) ;
}
}
/**
* @brief Enables or disables the TIM5 Capture Compare Channel x.
* @param TIM5_Channel: Specifies the TIM5 Channel.
* This parameter can be one of the following values:
* @arg TIM5_Channel_1: Channel 1
* @arg TIM5_Channel_2: Channel 2
* @param NewState: Specifies the TIM5 Channel CCxE bit new state.
* This parameter can be ENABLE or DISABLE
* @retval None
*/
void TIM5_CCxCmd(TIM5_Channel_TypeDef TIM5_Channel,
FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_TIM5_CHANNEL(TIM5_Channel));
assert_param(IS_FUNCTIONAL_STATE(NewState));
if (TIM5_Channel == TIM5_Channel_1)
{
/* Set or Reset the CC1E Bit */
if (NewState != DISABLE)
{
TIM5->CCER1 |= TIM_CCER1_CC1E ;
}
else
{
TIM5->CCER1 &= (uint8_t)(~TIM_CCER1_CC1E) ;
}
}
else /* if (TIM5_Channel == TIM5_Channel_2) */
{
/* Set or Reset the CC2E Bit */
if (NewState != DISABLE)
{
TIM5->CCER1 |= TIM_CCER1_CC2E;
}
else
{
TIM5->CCER1 &= (uint8_t)(~TIM_CCER1_CC2E) ;
}
}
}
/** @defgroup TIM5_Group3 Input Capture management functions
* @brief Input Capture management functions
*
@verbatim
===============================================================================
Input Capture management functions
===============================================================================
===================================================================
TIM5 Driver: how to use it in Input Capture Mode
===================================================================
To use the Timer in Input Capture mode, the following steps are mandatory:
1. Enable TIM5 clock using CLK_PeripheralClockConfig(CLK_Peripheral_TIM5, ENABLE) function.
2. Configure the TIM5 pins in input mode by configuring the corresponding GPIO pins
3. Configure the Time base unit as described in the first part of this driver, if needed,
otherwise the Timer will run with the default configuration:
- Autoreload value = 0xFFFF
- Prescaler value = 0x0
- Counter mode = Up counting
4. Call TIM5_ICInit() to configure the desired channel to measure only
frequency or duty cycle of the input signal using the corresponding configuration:
- TIM5 Channel: TIM5_Channel
- TIM5 Input Capture polarity: TIM5_ICPolarity
- TIM5 Input Capture selection: TIM5_ICSelection
- TIM5 Input Capture Prescaler: TIM5_ICPSC
- TIM5 Input Capture filter value
or,
Call TIM5_PWMIConfig() to configure the desired channels with the
corresponding configuration and to measure the frequency and the duty
cycle of the input signal.
5. Enable global interrupts or the DMA to read the measured frequency.
6. Enable the corresponding interrupt (or DMA request) to read the captured value,
using the function TIM5_ITConfig(TIM5_IT_CCx) (or TIM5_DMACmd(TIM5_DMASource_CCx))
7. Call the TIM5_Cmd(ENABLE) function to enable the TIM5 counter.
8. Use TIM5_GetCapturex() to read the captured value corresponding to
channel x.
Note1: All other functions can be used separately to modify, if needed,
a specific feature of the Timer.
@endverbatim
* @{
*/
/**
* @brief Initializes the TIM5 peripheral according to the specified parameters.
* @param TIM5_Channel: TIM5 Channel
* This parameter can be one of the following values:
* @arg TIM5_Channel_1: Channel 1
* @arg TIM5_Channel_2: Channel 2
* @param TIM5_ICPolarity: Input Capture Polarity
* This parameter can be one of the following values:
* @arg TIM5_ICPolarity_Rising: Input Capture on Rising Edge
* @arg TIM5_ICPolarity_Falling: Input Capture on Falling Edge
* @param TIM5_ICSelection: Input Capture Selection
* This parameter can be one of the following values:
* @arg TIM5_ICSelection_DirectTI: Input Capture mapped on the direct input
* @arg TIM5_ICSelection_IndirectTI: Input Capture mapped on the indirect input
* @arg TIM5_ICSelection_TRGI: Input Capture mapped on the Trigger Input
* @param TIM5_ICPrescaler: Input Capture Prescaler
* This parameter can be one of the following values:
* @arg TIM5_ICPSC_DIV1: Input Capture Prescaler = 1 (one capture every 1 event)
* @arg TIM5_ICPSC_DIV2: Input Capture Prescaler = 2 (one capture every 2 events)
* @arg TIM5_ICPSC_DIV4: Input Capture Prescaler = 4 (one capture every 4 events)
* @arg TIM5_ICPSC_DIV8: Input Capture Prescaler = 8 (one capture every 8 events)
* @param TIM5_ICFilter: This parameter must be a value between 0x00 and 0x0F.
* @retval None
*/
void TIM5_ICInit(TIM5_Channel_TypeDef TIM5_Channel,
TIM5_ICPolarity_TypeDef TIM5_ICPolarity,
TIM5_ICSelection_TypeDef TIM5_ICSelection,
TIM5_ICPSC_TypeDef TIM5_ICPrescaler,
uint8_t TIM5_ICFilter)
{
/* Check the parameters */
assert_param(IS_TIM5_CHANNEL(TIM5_Channel));
if (TIM5_Channel == TIM5_Channel_1)
{
/* TI1 Configuration */
TI1_Config(TIM5_ICPolarity, TIM5_ICSelection, TIM5_ICFilter);
/* Set the Input Capture Prescaler value */
TIM5_SetIC1Prescaler(TIM5_ICPrescaler);
}
else /* if (TIM5_Channel == TIM5_Channel_2) */
{
/* TI2 Configuration */
TI2_Config(TIM5_ICPolarity, TIM5_ICSelection, TIM5_ICFilter);
/* Set the Input Capture Prescaler value */
TIM5_SetIC2Prescaler(TIM5_ICPrescaler);
}
}
/**
* @brief Configures the TIM5 peripheral in PWM Input Mode according to the
* specified parameters.
* @param TIM5_Channel: TIM5 Channel
* This parameter can be one of the following values:
* @arg TIM5_Channel_1: Channel 1
* @arg TIM5_Channel_2: Channel 2
* @param TIM5_ICPolarity: Input Capture Polarity
* This parameter can be one of the following values:
* @arg TIM5_ICPolarity_Rising: Input Capture on Rising Edge
* @arg TIM5_ICPolarity_Falling: Input Capture on Falling Edge
* @param TIM5_ICSelection: Input Capture Selection
* This parameter can be one of the following values:
* @arg TIM5_ICSelection_DirectTI: Input Capture mapped on the direct input
* @arg TIM5_ICSelection_IndirectTI: Input Capture mapped on the indirect input
* @arg TIM5_ICSelection_TRGI: Input Capture mapped on the Trigger Input
* @param TIM5_ICPrescaler: Input Capture Prescaler
* This parameter can be one of the following values:
* @arg TIM5_ICPSC_DIV1: Input Capture Prescaler = 1 (one capture every 1 event)
* @arg TIM5_ICPSC_DIV2: Input Capture Prescaler = 2 (one capture every 2 events)
* @arg TIM5_ICPSC_DIV4: Input Capture Prescaler = 4 (one capture every 4 events)
* @arg TIM5_ICPSC_DIV8: Input Capture Prescaler = 8 (one capture every 8 events)
* @retval None
*/
void TIM5_PWMIConfig(TIM5_Channel_TypeDef TIM5_Channel,
TIM5_ICPolarity_TypeDef TIM5_ICPolarity,
TIM5_ICSelection_TypeDef TIM5_ICSelection,
TIM5_ICPSC_TypeDef TIM5_ICPrescaler,
uint8_t TIM5_ICFilter)
{
uint8_t icpolarity = TIM5_ICPolarity_Rising;
uint8_t icselection = TIM5_ICSelection_DirectTI;
/* Check the parameters */
assert_param(IS_TIM5_CHANNEL(TIM5_Channel));
/* Select the Opposite Input Polarity */
if (TIM5_ICPolarity == TIM5_ICPolarity_Rising)
{
icpolarity = TIM5_ICPolarity_Falling;
}
else
{
icpolarity = TIM5_ICPolarity_Rising;
}
/* Select the Opposite Input */
if (TIM5_ICSelection == TIM5_ICSelection_DirectTI)
{
icselection = TIM5_ICSelection_IndirectTI;
}
else
{
icselection = TIM5_ICSelection_DirectTI;
}
if (TIM5_Channel == TIM5_Channel_1)
{
/* TI1 Configuration */
TI1_Config(TIM5_ICPolarity, TIM5_ICSelection,
TIM5_ICFilter);
/* Set the Input Capture Prescaler value */
TIM5_SetIC1Prescaler(TIM5_ICPrescaler);
/* TI2 Configuration */
TI2_Config((TIM5_ICPolarity_TypeDef)icpolarity, (TIM5_ICSelection_TypeDef)icselection, TIM5_ICFilter);
/* Set the Input Capture Prescaler value */
TIM5_SetIC2Prescaler(TIM5_ICPrescaler);
}
else
{
/* TI2 Configuration */
TI2_Config(TIM5_ICPolarity, TIM5_ICSelection,
TIM5_ICFilter);
/* Set the Input Capture Prescaler value */
TIM5_SetIC2Prescaler(TIM5_ICPrescaler);
/* TI1 Configuration */
TI1_Config((TIM5_ICPolarity_TypeDef)icpolarity, (TIM5_ICSelection_TypeDef)icselection, TIM5_ICFilter);
/* Set the Input Capture Prescaler value */
TIM5_SetIC1Prescaler(TIM5_ICPrescaler);
}
}
/**
* @brief Gets the TIM5 Input Capture 1 value.
* @param None
* @retval Capture Compare 1 Register value.
*/
uint16_t TIM5_GetCapture1(void)
{
uint16_t tmpccr1 = 0;
uint8_t tmpccr1l, tmpccr1h;
tmpccr1h = TIM5->CCR1H;
tmpccr1l = TIM5->CCR1L;
tmpccr1 = (uint16_t)(tmpccr1l);
tmpccr1 |= (uint16_t)((uint16_t)tmpccr1h << 8);
/* Get the Capture 1 Register value */
return ((uint16_t)tmpccr1);
}
/**
* @brief Gets the TIM5 Input Capture 2 value.
* @param None
* @retval Capture Compare 2 Register value.
*/
uint16_t TIM5_GetCapture2(void)
{
uint16_t tmpccr2 = 0;
uint8_t tmpccr2l, tmpccr2h;
tmpccr2h = TIM5->CCR2H;
tmpccr2l = TIM5->CCR2L;
tmpccr2 = (uint16_t)(tmpccr2l);
tmpccr2 |= (uint16_t)((uint16_t)tmpccr2h << 8);
/* Get the Capture 2 Register value */
return ((uint16_t)tmpccr2);
}
/**
* @brief Sets the TIM5 Input Capture 1 prescaler.
* @param TIM5_IC1Prescaler: Specifies the Input Capture prescaler new value
* This parameter can be one of the following values:
* @arg TIM5_ICPSC_DIV1: Input Capture Prescaler = 1 (one capture every 1 event)
* @arg TIM5_ICPSC_DIV2: Input Capture Prescaler = 2 (one capture every 2 events)
* @arg TIM5_ICPSC_DIV4: Input Capture Prescaler = 4 (one capture every 4 events)
* @arg TIM5_ICPSC_DIV8: Input Capture Prescaler = 8 (one capture every 8 events)
* @retval None
*/
void TIM5_SetIC1Prescaler(TIM5_ICPSC_TypeDef TIM5_IC1Prescaler)
{
uint8_t tmpccmr1 = 0;
/* Check the parameters */
assert_param(IS_TIM5_IC_PRESCALER(TIM5_IC1Prescaler));
tmpccmr1 = TIM5->CCMR1;
/* Reset the IC1PSC Bits */
tmpccmr1 &= (uint8_t)(~TIM_CCMR_ICxPSC);
/* Set the IC1PSC value */
tmpccmr1 |= (uint8_t)TIM5_IC1Prescaler;
TIM5->CCMR1 = tmpccmr1;
}
/**
* @brief Sets the TIM5 Input Capture 2 prescaler.
* @param TIM5_IC2Prescaler: Specifies the Input Capture prescaler new value
* This parameter can be one of the following values:
* @arg TIM5_ICPSC_DIV1: Input Capture Prescaler = 1 (one capture every 1 event)
* @arg TIM5_ICPSC_DIV2: Input Capture Prescaler = 2 (one capture every 2 events)
* @arg TIM5_ICPSC_DIV4: Input Capture Prescaler = 4 (one capture every 4 events)
* @arg TIM5_ICPSC_DIV8: Input Capture Prescaler = 8 (one capture every 8 events)
* @retval None
*/
void TIM5_SetIC2Prescaler(TIM5_ICPSC_TypeDef TIM5_IC2Prescaler)
{
uint8_t tmpccmr2 = 0;
/* Check the parameters */
assert_param(IS_TIM5_IC_PRESCALER(TIM5_IC2Prescaler));
tmpccmr2 = TIM5->CCMR2;
/* Reset the IC2PSC Bits */
tmpccmr2 &= (uint8_t)(~TIM_CCMR_ICxPSC);
/* Set the IC2PSC value */
tmpccmr2 |= (uint8_t)TIM5_IC2Prescaler;
TIM5->CCMR2 = tmpccmr2;
}
/**
* @}
*/
/** @defgroup TIM5_Group4 Interrupts DMA and flags management functions
* @brief Interrupts, DMA and flags management functions
*
@verbatim
===============================================================================
Interrupts, DMA and flags management functions
===============================================================================
@endverbatim
* @{
*/
/**
* @brief Enables or disables the specified TIM5 interrupts.
* @param TIM5_IT: Specifies the TIM5 interrupts sources to be enabled or disabled.
* This parameter can be any combination of the following values:
* @arg TIM5_IT_Update: Update
* @arg TIM5_IT_CC1: Capture Compare Channel1
* @arg TIM5_IT_CC2: Capture Compare Channel2
* @arg TIM5_IT_Trigger: Trigger
* @arg TIM5_IT_Break: Break
* @param NewState: The new state of the TIM5 peripheral.
* This parameter can be ENABLE or DISABLE
* @retval None
*/
void TIM5_ITConfig(TIM5_IT_TypeDef TIM5_IT, FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_TIM5_IT(TIM5_IT));
assert_param(IS_FUNCTIONAL_STATE(NewState));
if (NewState != DISABLE)
{
/* Enable the Interrupt sources */
TIM5->IER |= (uint8_t)TIM5_IT;
}
else
{
/* Disable the Interrupt sources */
TIM5->IER &= (uint8_t)(~(uint8_t)TIM5_IT);
}
}
/**
* @brief Configures the TIM5 event to be generated by software.
* @param TIM5_EventSource: Specifies the event source.
* This parameter can be any combination of the following values:
* @arg TIM5_EventSource_Update: Update
* @arg TIM5_EventSource_CC1: Capture Compare Channel1
* @arg TIM5_EventSource_CC2: Capture Compare Channel2
* @arg TIM5_EventSource_Trigger: Trigger
* @arg TIM5_EventSource_Break: Break
* @retval None
*/
void TIM5_GenerateEvent(TIM5_EventSource_TypeDef TIM5_EventSource)
{
/* Check the parameters */
assert_param(IS_TIM5_EVENT_SOURCE((uint8_t)TIM5_EventSource));
/* Set the event sources */
TIM5->EGR |= (uint8_t)TIM5_EventSource;
}
/**
* @brief Checks whether the specified TIM5 flag is set or not.
* @param TIM5_FLAG: Specifies the flag to check.
* This parameter can be any combination of the following values:
* @arg TIM5_FLAG_Update: Update
* @arg TIM5_FLAG_CC1: Capture Compare Channel1
* @arg TIM5_FLAG_CC2: Capture Compare Channel2
* @arg TIM5_FLAG_Trigger: Trigger
* @arg TIM5_FLAG_Break: Break
* @arg TIM5_FLAG_CC1OF: Capture compare 1 over capture
* @arg TIM5_FLAG_CC2OF: Capture compare 2 over capture
* @retval FlagStatus: The new state of TIM5_FLAG (SET or RESET)
*/
FlagStatus TIM5_GetFlagStatus(TIM5_FLAG_TypeDef TIM5_FLAG)
{
FlagStatus bitstatus = RESET;
uint8_t tim5_flag_l = 0, tim5_flag_h = 0;
/* Check the parameters */
assert_param(IS_TIM5_GET_FLAG(TIM5_FLAG));
tim5_flag_l = (uint8_t)(TIM5->SR1 & (uint8_t)(TIM5_FLAG));
tim5_flag_h = (uint8_t)(TIM5->SR2 & (uint8_t)((uint16_t)TIM5_FLAG >> 8));
if ((uint8_t)(tim5_flag_l | tim5_flag_h) != 0)
{
bitstatus = SET;
}
else
{
bitstatus = RESET;
}
return ((FlagStatus)bitstatus);
}
/**
* @brief Clears the TIMís pending flags.
* @param TIM5_FLAG: Specifies the flag to clear.
* This parameter can be any combination of the following values:
* @arg TIM5_FLAG_Update: Update
* @arg TIM5_FLAG_CC1: Capture Compare Channel1
* @arg TIM5_FLAG_CC2: Capture Compare Channel2
* @arg TIM5_FLAG_Trigger: Trigger
* @arg TIM5_FLAG_Break: Break
* @retval None
*/
void TIM5_ClearFlag(TIM5_FLAG_TypeDef TIM5_FLAG)
{
/* Check the parameters */
assert_param(IS_TIM5_CLEAR_FLAG((uint16_t)TIM5_FLAG));
/* Clear the flags (rc_w0) clear this bit by writing 0. Writing Ď1í has no effect*/
TIM5->SR1 = (uint8_t)(~(uint8_t)(TIM5_FLAG));
TIM5->SR2 = (uint8_t)(~(uint8_t)((uint16_t)TIM5_FLAG >> 8));
}
/**
* @brief Checks whether the TIM5 interrupt has occurred or not.
* @param TIM5_IT: Specifies the TIM5 interrupt source to check.
* This parameter can be any combination of the following values:
* @arg TIM5_IT_Update: Update
* @arg TIM5_IT_CC1: Capture Compare Channel1
* @arg TIM5_IT_CC2: Capture Compare Channel2
* @arg TIM5_IT_Trigger: Trigger
* @arg TIM5_IT_Break: Break
* @retval ITStatus: The new state of the TIM5_IT (SET or RESET)
*/
ITStatus TIM5_GetITStatus(TIM5_IT_TypeDef TIM5_IT)
{
ITStatus bitstatus = RESET;
uint8_t TIM5_itStatus = 0x0, TIM5_itEnable = 0x0;
/* Check the parameters */
assert_param(IS_TIM5_GET_IT(TIM5_IT));
TIM5_itStatus = (uint8_t)(TIM5->SR1 & (uint8_t)TIM5_IT);
TIM5_itEnable = (uint8_t)(TIM5->IER & (uint8_t)TIM5_IT);
if ((TIM5_itStatus != (uint8_t)RESET ) && (TIM5_itEnable != (uint8_t)RESET))
{
bitstatus = (ITStatus)SET;
}
else
{
bitstatus = (ITStatus)RESET;
}
return ((ITStatus)bitstatus);
}
/**
* @brief Clears the TIM's interrupt pending bits.
* @param TIM5_IT: Specifies the pending bit to clear.
* This parameter can be any combination of the following values:
* @arg TIM5_IT_Update: Update
* @arg TIM5_IT_CC1: Capture Compare Channel1
* @arg TIM5_IT_CC2: Capture Compare Channel2
* @arg TIM5_IT_Trigger: Trigger
* @arg TIM5_IT_Break: Break
* @retval None
*/
void TIM5_ClearITPendingBit(TIM5_IT_TypeDef TIM5_IT)
{
/* Check the parameters */
assert_param(IS_TIM5_IT(TIM5_IT));
/* Clear the IT pending Bit */
TIM5->SR1 = (uint8_t)(~(uint8_t)TIM5_IT);
}
/**
* @brief Enables or disables the TIM5 DMA Requests.
* @param TIM5_DMASource: specifies the DMA Request sources.
* This parameter can be any combination of the following values:
* @arg TIM5_DMASource_Update: TIM5 DMA Update Request
* @arg TIM5_DMASource_CC1: TIM5 DMA CC1 Request
* @arg TIM5_DMASource_CC2: TIM5 DMA CC2 Request
* @param NewState: new state of the DMA Request sources.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void TIM5_DMACmd( TIM5_DMASource_TypeDef TIM5_DMASource, FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_FUNCTIONAL_STATE(NewState));
assert_param(IS_TIM5_DMA_SOURCE(TIM5_DMASource));
if (NewState != DISABLE)
{
/* Enable the DMA sources */
TIM5->DER |= TIM5_DMASource;
}
else
{
/* Disable the DMA sources */
TIM5->DER &= (uint8_t)(~TIM5_DMASource);
}
}
/**
* @brief Selects the TIM5 peripheral Capture Compare DMA source.
* @param NewState: new state of the Capture Compare DMA source.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void TIM5_SelectCCDMA(FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_FUNCTIONAL_STATE(NewState));
if (NewState != DISABLE)
{
/* Set the CCDS Bit */
TIM5->CR2 |= TIM_CR2_CCDS;
}
else
{
/* Reset the CCDS Bit */
TIM5->CR2 &= (uint8_t)(~TIM_CR2_CCDS);
}
}
/**
* @}
*/
/** @defgroup TIM5_Group5 Clocks management functions
* @brief Clocks management functions
*
@verbatim
===============================================================================
Clocks management functions
===============================================================================
@endverbatim
* @{
*/
/**
* @brief Enables the TIM5 internal Clock.
* @par Parameters:
* None
* @retval None
*/
void TIM5_InternalClockConfig(void)
{
/* Disable slave mode to clock the prescaler directly with the internal clock */
TIM5->SMCR &= (uint8_t)(~TIM_SMCR_SMS);
}
/**
* @brief Configures the TIM5 Trigger as External Clock.
* @param TIM5_TIxExternalCLKSource: Specifies Trigger source.
* This parameter can be one of the following values:
* @arg TIM5_TIxExternalCLK1Source_TI1ED: External Clock mode 1 source = TI1ED
* @arg TIM5_TIxExternalCLK1Source_TI1: External Clock mode 1 source = TI1
* @arg TIM5_TIxExternalCLK1Source_TI2: External Clock mode 1 source = TI2
* @param TIM5_ICPolarity: Specifies the TIx Polarity.
* This parameter can be one of the following values:
* @arg TIM5_ICPolarity_Rising: Input Capture on Rising Edge
* @arg TIM5_ICPolarity_Falling: Input Capture on Falling Edge
* @param ICFilter: Specifies the filter value.
* This parameter must be a value between 0x00 and 0x0F
* @retval None
*/
void TIM5_TIxExternalClockConfig(TIM5_TIxExternalCLK1Source_TypeDef TIM5_TIxExternalCLKSource,
TIM5_ICPolarity_TypeDef TIM5_ICPolarity,
uint8_t ICFilter)
{
/* Check the parameters */
assert_param(IS_TIM5_TIXCLK_SOURCE(TIM5_TIxExternalCLKSource));
assert_param(IS_TIM5_IC_POLARITY(TIM5_ICPolarity));
assert_param(IS_TIM5_IC_FILTER(ICFilter));
/* Configure the TIM5 Input Clock Source */
if (TIM5_TIxExternalCLKSource == TIM5_TIxExternalCLK1Source_TI2)
{
TI2_Config(TIM5_ICPolarity, TIM5_ICSelection_DirectTI, ICFilter);
}
else
{
TI1_Config(TIM5_ICPolarity, TIM5_ICSelection_DirectTI, ICFilter);
}
/* Select the Trigger source */
TIM5_SelectInputTrigger((TIM5_TRGSelection_TypeDef)TIM5_TIxExternalCLKSource);
/* Select the External clock mode1 */
TIM5->SMCR |= (uint8_t)(TIM5_SlaveMode_External1);
}
/**
* @brief Configures the TIM5 External clock Mode1.
* @param TIM5_ExtTRGPrescaler: Specifies the external Trigger Prescaler.
* This parameter can be one of the following values:
* @arg TIM5_ExtTRGPSC_OFF: No External Trigger prescaler
* @arg TIM5_ExtTRGPSC_DIV2: External Trigger prescaler = 2 (ETRP frequency divided by 2)
* @arg TIM5_ExtTRGPSC_DIV4: External Trigger prescaler = 4 (ETRP frequency divided by 4)
* @arg TIM5_ExtTRGPSC_DIV8: External Trigger prescaler = 8 (ETRP frequency divided by 8)
* @param TIM5_ExtTRGPolarity: Specifies the external Trigger Polarity.
* This parameter can be one of the following values:
* @arg TIM5_ExtTRGPolarity_Inverted: External Trigger Polarity = inverted
* @arg TIM5_ExtTRGPolarity_NonInverted: External Trigger Polarity = non inverted
* @param ExtTRGFilter: Specifies the External Trigger Filter.
* This parameter must be a value between 0x00 and 0x0F
* @retval None
*/
void TIM5_ETRClockMode1Config(TIM5_ExtTRGPSC_TypeDef TIM5_ExtTRGPrescaler,
TIM5_ExtTRGPolarity_TypeDef TIM5_ExtTRGPolarity,
uint8_t ExtTRGFilter)
{
/* Configure the ETR Clock source */
TIM5_ETRConfig(TIM5_ExtTRGPrescaler, TIM5_ExtTRGPolarity, ExtTRGFilter);
/* Select the External clock mode1 */
TIM5->SMCR &= (uint8_t)(~TIM_SMCR_SMS);
TIM5->SMCR |= (uint8_t)(TIM5_SlaveMode_External1);
/* Select the Trigger selection: ETRF */
TIM5->SMCR &= (uint8_t)(~TIM_SMCR_TS);
TIM5->SMCR |= (uint8_t)((TIM5_TRGSelection_TypeDef)TIM5_TRGSelection_ETRF);
}
/**
* @brief Configures the TIM5 External clock Mode2.
* @param TIM5_ExtTRGPrescaler: Specifies the external Trigger Prescaler.
* This parameter can be one of the following values:
* @arg TIM5_ExtTRGPSC_OFF: No External Trigger prescaler
* @arg TIM5_ExtTRGPSC_DIV2: External Trigger prescaler = 2 (ETRP frequency divided by 2)
* @arg TIM5_ExtTRGPSC_DIV4: External Trigger prescaler = 4 (ETRP frequency divided by 4)
* @arg TIM5_ExtTRGPSC_DIV8: External Trigger prescaler = 8 (ETRP frequency divided by 8)
* @param TIM5_ExtTRGPolarity: Specifies the external Trigger Polarity.
* This parameter can be one of the following values:
* @arg TIM5_ExtTRGPolarity_Inverted: External Trigger Polarity = inverted
* @arg TIM5_ExtTRGPolarity_NonInverted: External Trigger Polarity = non inverted
* @param ExtTRGFilter: Specifies the External Trigger Filter.
* This parameter must be a value between 0x00 and 0x0F
* @retval None
*/
void TIM5_ETRClockMode2Config(TIM5_ExtTRGPSC_TypeDef TIM5_ExtTRGPrescaler,
TIM5_ExtTRGPolarity_TypeDef TIM5_ExtTRGPolarity,
uint8_t ExtTRGFilter)
{
/* Configure the ETR Clock source */
TIM5_ETRConfig(TIM5_ExtTRGPrescaler, TIM5_ExtTRGPolarity, ExtTRGFilter);
/* Enable the External clock mode2 */
TIM5->ETR |= TIM_ETR_ECE ;
}
/**
* @}
*/
/** @defgroup TIM5_Group6 Synchronization management functions
* @brief Synchronization management functions
*
@verbatim
===============================================================================
Synchronization management functions
===============================================================================
===================================================================
TIM5 Driver: how to use it in synchronization Mode
===================================================================
Case of two/several Timers
**************************
1. If TIM5 is used as master to other timers use the following functions:
- TIM5_SelectOutputTrigger()
- TIM5_SelectMasterSlaveMode()
2. If TIM5 is used as slave to other timers use the following functions:
- TIM5_SelectInputTrigger()
- TIM5_SelectSlaveMode()
Case of Timers and external trigger (TRIG pin)
********************************************
1. Configure the External trigger using TIM5_ETRConfig()
2. Configure the Slave Timer using the following functions:
- TIM5_SelectInputTrigger()
- TIM5_SelectSlaveMode()
@endverbatim
* @{
*/
/**
* @brief Selects the TIM5 Input Trigger source.
* @param TIM5_InputTriggerSource: Specifies Input Trigger source.
* This parameter can be one of the following values:
* @arg TIM5_TRGSelection_TIM4: TRIG Input source = TIM TRIG Output
* @arg TIM5_TRGSelection_TIM1: TRIG Input source = TIM TRIG Output
* @arg TIM5_TRGSelection_TIM3: TRIG Input source = TIM TRIG Output
* @arg TIM5_TRGSelection_TIM2: TRIG Input source = TIM TRIG Output
* @arg TIM5_TRGSelection_TI1F_ED: TRIG Input source = TI1F_ED (TI1 Edge Detector)
* @arg TIM5_TRGSelection_TI1FP1: TRIG Input source = TI1FP1 (Filtered Timer Input 1)
* @arg TIM5_TRGSelection_TI2FP2: TRIG Input source = TI2FP2 (Filtered Timer Input 2)
* @arg TIM5_TRGSelection_ETRF: TRIG Input source = ETRF (External Trigger Input )
* @retval None
*/
void TIM5_SelectInputTrigger(TIM5_TRGSelection_TypeDef TIM5_InputTriggerSource)
{
uint8_t tmpsmcr = 0;
/* Check the parameters */
assert_param(IS_TIM5_TRIGGER_SELECTION(TIM5_InputTriggerSource));
tmpsmcr = TIM5->SMCR;
/* Select the Trigger Source */
tmpsmcr &= (uint8_t)(~TIM_SMCR_TS);
tmpsmcr |= (uint8_t)TIM5_InputTriggerSource;
TIM5->SMCR = (uint8_t)tmpsmcr;
}
/**
* @brief Selects the TIM5 Trigger Output Mode.
* @param TIM5_TRGOSource: Specifies the Trigger Output source.
* This parameter can be one of the following values:
* @arg TIM5_TRGOSource_Reset: Trigger Output source = Reset
* @arg TIM5_TRGOSource_Enable: Trigger Output source = TIM5 is enabled
* @arg TIM5_TRGOSource_Update: Trigger Output source = Update event
* @arg TIM5_TRGOSource_OC1: Trigger Output source = output compare channel1
* @arg TIM5_TRGOSource_OC1REF: Trigger Output source = output compare channel 1 reference
* @arg TIM5_TRGOSource_OC2REF: Trigger Output source = output compare channel 2 reference
* @retval None
*/
void TIM5_SelectOutputTrigger(TIM5_TRGOSource_TypeDef TIM5_TRGOSource)
{
uint8_t tmpcr2 = 0;
/* Check the parameters */
assert_param(IS_TIM5_TRGO_SOURCE(TIM5_TRGOSource));
tmpcr2 = TIM5->CR2;
/* Reset the MMS Bits */
tmpcr2 &= (uint8_t)(~TIM_CR2_MMS);
/* Select the TRGO source */
tmpcr2 |= (uint8_t)TIM5_TRGOSource;
TIM5->CR2 = tmpcr2;
}
/**
* @brief Selects the TIM5 Slave Mode.
* @param TIM5_SlaveMode: Specifies the TIM5 Slave Mode.
* This parameter can be one of the following values:
* @arg TIM5_SlaveMode_Reset: Slave Mode Selection = Reset
* @arg TIM5_SlaveMode_Gated: Slave Mode Selection = Gated
* @arg TIM5_SlaveMode_Trigger: Slave Mode Selection = Trigger
* @arg TIM5_SlaveMode_External1: Slave Mode Selection = External 1
* @retval None
*/
void TIM5_SelectSlaveMode(TIM5_SlaveMode_TypeDef TIM5_SlaveMode)
{
uint8_t tmpsmcr = 0;
/* Check the parameters */
assert_param(IS_TIM5_SLAVE_MODE(TIM5_SlaveMode));
tmpsmcr = TIM5->SMCR;
/* Reset the SMS Bits */
tmpsmcr &= (uint8_t)(~TIM_SMCR_SMS);
/* Select the Slave Mode */
tmpsmcr |= (uint8_t)TIM5_SlaveMode;
TIM5->SMCR = tmpsmcr;
}
/**
* @brief Sets or Resets the TIM5 Master/Slave Mode.
* @param NewState: The new state of the synchronization between TIM5 and its slaves (through TRGO).
* This parameter can be ENABLE or DISABLE
* @retval None
*/
void TIM5_SelectMasterSlaveMode(FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_FUNCTIONAL_STATE(NewState));
/* Set or Reset the MSM Bit */
if (NewState != DISABLE)
{
TIM5->SMCR |= TIM_SMCR_MSM;
}
else
{
TIM5->SMCR &= (uint8_t)(~TIM_SMCR_MSM);
}
}
/**
* @brief Configures the TIM5 External Trigger.
* @param TIM5_ExtTRGPrescaler: Specifies the external Trigger Prescaler.
* This parameter can be one of the following values:
* @arg TIM5_ExtTRGPSC_OFF: No External Trigger prescaler
* @arg TIM5_ExtTRGPSC_DIV2: External Trigger prescaler = 2 (ETRP frequency divided by 2)
* @arg TIM5_ExtTRGPSC_DIV4: External Trigger prescaler = 4 (ETRP frequency divided by 4)
* @arg TIM5_ExtTRGPSC_DIV8: External Trigger prescaler = 8 (ETRP frequency divided by 8)
* @param TIM5_ExtTRGPolarity: Specifies the external Trigger Polarity.
* This parameter can be one of the following values:
* @arg TIM5_ExtTRGPolarity_Inverted: External Trigger Polarity = inverted
* @arg TIM5_ExtTRGPolarity_NonInverted: External Trigger Polarity = non inverted
* @param ExtTRGFilter: Specifies the External Trigger Filter.
* This parameter must be a value between 0x00 and 0x0F
* @retval None
*/
void TIM5_ETRConfig(TIM5_ExtTRGPSC_TypeDef TIM5_ExtTRGPrescaler,
TIM5_ExtTRGPolarity_TypeDef TIM5_ExtTRGPolarity,
uint8_t ExtTRGFilter)
{
/* Check the parameters */
assert_param(IS_TIM5_EXT_PRESCALER(TIM5_ExtTRGPrescaler));
assert_param(IS_TIM5_EXT_POLARITY(TIM5_ExtTRGPolarity));
assert_param(IS_TIM5_EXT_FILTER(ExtTRGFilter));
/* Set the Prescaler, the Filter value and the Polarity */
TIM5->ETR |= (uint8_t)((uint8_t)((uint8_t)TIM5_ExtTRGPrescaler | (uint8_t)TIM5_ExtTRGPolarity)
| (uint8_t)ExtTRGFilter);
}
/**
* @}
*/
/** @defgroup TIM5_Group7 Specific interface management functions
* @brief Specific interface management functions
*
@verbatim
===============================================================================
Specific interface management functions
===============================================================================
@endverbatim
* @{
*/
/**
* @brief Configures the TIM5 Encoder Interface.
* @param TIM5_EncoderMode: Specifies the TIM5 Encoder Mode.
* This parameter can be one of the following values:
* @arg TIM5_EncoderMode_TI1: Encoder mode 1
* @arg TIM5_EncoderMode_TI2: Encoder mode 2
* @arg TIM5_EncoderMode_TI12: Encoder mode 3
* @param TIM5_IC1Polarity: Specifies the IC1 Polarity.
* This parameter can be one of the following values:
* @arg TIM5_ICPolarity_Rising: Input Capture on Rising Edge
* @arg TIM5_ICPolarity_Falling: Input Capture on Falling Edge
* @param TIM5_IC2Polarity: Specifies the IC2 Polarity.
* This parameter can be one of the following values:
* @arg TIM5_ICPolarity_Rising: Input Capture on Rising Edge
* @arg TIM5_ICPolarity_Falling: Input Capture on Falling Edge
* @retval None
*/
void TIM5_EncoderInterfaceConfig(TIM5_EncoderMode_TypeDef TIM5_EncoderMode,
TIM5_ICPolarity_TypeDef TIM5_IC1Polarity,
TIM5_ICPolarity_TypeDef TIM5_IC2Polarity)
{
uint8_t tmpsmcr = 0;
uint8_t tmpccmr1 = 0;
uint8_t tmpccmr2 = 0;
/* Check the parameters */
assert_param(IS_TIM5_ENCODER_MODE(TIM5_EncoderMode));
assert_param(IS_TIM5_IC_POLARITY(TIM5_IC1Polarity));
assert_param(IS_TIM5_IC_POLARITY(TIM5_IC2Polarity));
tmpsmcr = TIM5->SMCR;
tmpccmr1 = TIM5->CCMR1;
tmpccmr2 = TIM5->CCMR2;
/* Set the encoder Mode */
tmpsmcr &= (uint8_t)(TIM_SMCR_MSM | TIM_SMCR_TS) ;
tmpsmcr |= (uint8_t)TIM5_EncoderMode;
/* Select the Capture Compare 1 and the Capture Compare 2 as input */
tmpccmr1 &= (uint8_t)(~TIM_CCMR_CCxS);
tmpccmr2 &= (uint8_t)(~TIM_CCMR_CCxS);
tmpccmr1 |= TIM_CCMR_TIxDirect_Set;
tmpccmr2 |= TIM_CCMR_TIxDirect_Set;
/* Set the TI1 and the TI2 Polarities */
if (TIM5_IC1Polarity == TIM5_ICPolarity_Falling)
{
TIM5->CCER1 |= TIM_CCER1_CC1P ;
}
else
{
TIM5->CCER1 &= (uint8_t)(~TIM_CCER1_CC1P) ;
}
if (TIM5_IC2Polarity == TIM5_ICPolarity_Falling)
{
TIM5->CCER1 |= TIM_CCER1_CC2P ;
}
else
{
TIM5->CCER1 &= (uint8_t)(~TIM_CCER1_CC2P) ;
}
TIM5->SMCR = tmpsmcr;
TIM5->CCMR1 = tmpccmr1;
TIM5->CCMR2 = tmpccmr2;
}
/**
* @brief Enables or Disables the TIMís Hall sensor interface.
* @param NewState: The new state of the TIM5 Hall sensor interface.
* This parameter can be ENABLE or DISABLE
* @retval None
*/
void TIM5_SelectHallSensor(FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_FUNCTIONAL_STATE(NewState));
/* Set or Reset the TI1S Bit */
if (NewState != DISABLE)
{
TIM5->CR2 |= TIM_CR2_TI1S;
}
else
{
TIM5->CR2 &= (uint8_t)(~TIM_CR2_TI1S);
}
}
/**
* @}
*/
/**
* @brief Configure the TI1 as Input.
* @param TIM5_ICPolarity: Input Capture Polarity
* This parameter can be one of the following values:
* @arg TIM5_ICPolarity_Rising: Input Capture on Rising Edge
* @arg TIM5_ICPolarity_Falling: Input Capture on Falling Edge
* @param TIM5_ICSelection: Specifies the input to be used.
* This parameter can be one of the following values:
* @arg TIM5_ICSelection_DirectTI: Input Capture mapped on the direct input
* @arg TIM5_ICSelection_IndirectTI: Input Capture mapped on the indirect input
* @arg TIM5_ICSelection_TRGI: Input Capture mapped on the Trigger Input
* @param TIM5_ICFilter: Specifies the Input Capture Filter.
* This parameter must be a value between 0x00 and 0x0F.
* @retval None
*/
static void TI1_Config(TIM5_ICPolarity_TypeDef TIM5_ICPolarity, \
TIM5_ICSelection_TypeDef TIM5_ICSelection, \
uint8_t TIM5_ICFilter)
{
uint8_t tmpccmr1 = 0;
uint8_t tmpicpolarity = TIM5_ICPolarity;
tmpccmr1 = TIM5->CCMR1;
/* Check the parameters */
assert_param(IS_TIM5_IC_POLARITY(TIM5_ICPolarity));
assert_param(IS_TIM5_IC_SELECTION(TIM5_ICSelection));
assert_param(IS_TIM5_IC_FILTER(TIM5_ICFilter));
/* Disable the Channel 1: Reset the CCE Bit */
TIM5->CCER1 &= (uint8_t)(~TIM_CCER1_CC1E);
/* Select the Input and set the filter */
tmpccmr1 &= (uint8_t)(~TIM_CCMR_CCxS) & (uint8_t)(~TIM_CCMR_ICxF);
tmpccmr1 |= (uint8_t)(((uint8_t)(TIM5_ICSelection)) | ((uint8_t)(TIM5_ICFilter << 4)));
TIM5->CCMR1 = tmpccmr1;
/* Select the Polarity */
if (tmpicpolarity == (uint8_t)(TIM5_ICPolarity_Falling))
{
TIM5->CCER1 |= TIM_CCER1_CC1P;
}
else
{
TIM5->CCER1 &= (uint8_t)(~TIM_CCER1_CC1P);
}
/* Set the CCE Bit */
TIM5->CCER1 |= TIM_CCER1_CC1E;
}
/**
* @brief Configure the TI2 as Input.
* @param TIM5_ICPolarity: Input Capture Polarity
* This parameter can be one of the following values:
* @arg TIM5_ICPolarity_Rising: Input Capture on Rising Edge
* @arg TIM5_ICPolarity_Falling: Input Capture on Falling Edge
* @param TIM5_ICSelection: Specifies the input to be used.
* This parameter can be one of the following values:
* @arg TIM5_ICSelection_DirectTI: Input Capture mapped on the direct input
* @arg TIM5_ICSelection_IndirectTI: Input Capture mapped on the indirect input
* @arg TIM5_ICSelection_TRGI: Input Capture mapped on the Trigger Input
* @param TIM5_ICFilter: Specifies the Input Capture Filter.
* This parameter must be a value between 0x00 and 0x0F.
* @retval None
*/
static void TI2_Config(TIM5_ICPolarity_TypeDef TIM5_ICPolarity,
TIM5_ICSelection_TypeDef TIM5_ICSelection,
uint8_t TIM5_ICFilter)
{
uint8_t tmpccmr2 = 0;
uint8_t tmpicpolarity = TIM5_ICPolarity;
/* Check the parameters */
assert_param(IS_TIM5_IC_POLARITY(TIM5_ICPolarity));
assert_param(IS_TIM5_IC_SELECTION(TIM5_ICSelection));
assert_param(IS_TIM5_IC_FILTER(TIM5_ICFilter));
tmpccmr2 = TIM5->CCMR2;
/* Disable the Channel 2: Reset the CCE Bit */
TIM5->CCER1 &= (uint8_t)(~TIM_CCER1_CC2E);
/* Select the Input and set the filter */
tmpccmr2 &= (uint8_t)(~TIM_CCMR_CCxS) & (uint8_t)(~TIM_CCMR_ICxF);
tmpccmr2 |= (uint8_t)(((uint8_t)(TIM5_ICSelection)) | ((uint8_t)(TIM5_ICFilter << 4)));
TIM5->CCMR2 = tmpccmr2;
/* Select the Polarity */
if (tmpicpolarity == TIM5_ICPolarity_Falling)
{
TIM5->CCER1 |= TIM_CCER1_CC2P ;
}
else
{
TIM5->CCER1 &= (uint8_t)(~TIM_CCER1_CC2P) ;
}
/* Set the CCE Bit */
TIM5->CCER1 |= TIM_CCER1_CC2E;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
20671b9d00b52a563f16f4a37acd8684f7aa6b7e
|
50dd46b8ece33f3cdd174284b15d1d51f89669d4
|
/third_party/edk2/Vlv2TbltDevicePkg/Library/EfiRegTableLib/EfiRegTableLib.c
|
fa94cc74e8630c35557232101a20b61380950050
|
[
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"BSD-2-Clause",
"OpenSSL"
] |
permissive
|
google/google-ctf
|
f99da1ee07729bbccb869fff1cbaed6a80e43bcc
|
df02323eaf945d15e124801c74abaadca2749dc7
|
refs/heads/master
| 2023-08-31T14:30:27.548081
| 2023-08-29T13:04:20
| 2023-08-29T13:04:20
| 131,317,137
| 4,136
| 607
|
Apache-2.0
| 2023-08-30T22:17:02
| 2018-04-27T15:56:03
|
Go
|
UTF-8
|
C
| false
| false
| 9,558
|
c
|
EfiRegTableLib.c
|
/*++
Copyright (c) 1999 - 2014, Intel Corporation. All rights reserved
This program and the accompanying materials are licensed and made available under
the terms and conditions of the BSD License that accompanies this distribution.
The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php.
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
EfiRegTableLib.c
Abstract:
Lib function for table driven register initialization.
Revision History
--*/
#include <Library/EfiRegTableLib.h>
#include <Library/S3BootScriptLib.h>
//
// Local Functions
//
/**
Local worker function to process PCI_WRITE table entries. Performs write and
may also call BootScriptSave protocol if indicated in the Entry flags
@param Entry A pointer to the PCI_WRITE entry to process
@param PciRootBridgeIo A pointer to the instance of PciRootBridgeIo that is used
when processing the entry.
@retval Nothing.
**/
STATIC
VOID
PciWrite (
EFI_REG_TABLE_PCI_WRITE *Entry,
EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo
)
{
EFI_STATUS Status;
Status = PciRootBridgeIo->Pci.Write (
PciRootBridgeIo,
(EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH) (OPCODE_EXTRA_DATA (Entry->OpCode)),
(UINT64) Entry->PciAddress,
1,
&Entry->Data
);
ASSERT_EFI_ERROR (Status);
if (OPCODE_FLAGS (Entry->OpCode) & OPCODE_FLAG_S3SAVE) {
Status = S3BootScriptSavePciCfgWrite (
(EFI_BOOT_SCRIPT_WIDTH) (OPCODE_EXTRA_DATA (Entry->OpCode)),
(UINT64) Entry->PciAddress,
1,
&Entry->Data
);
ASSERT_EFI_ERROR (Status);
}
}
/**
Local worker function to process PCI_READ_MODIFY_WRITE table entries.
Performs RMW write and may also call BootScriptSave protocol if indicated in
the Entry flags.
@param Entry A pointer to the PCI_READ_MODIFY_WRITE entry to process.
@param PciRootBridgeIo A pointer to the instance of PciRootBridgeIo that is used
when processing the entry.
@retval Nothing.
**/
STATIC
VOID
PciReadModifyWrite (
EFI_REG_TABLE_PCI_READ_MODIFY_WRITE *Entry,
EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo
)
{
EFI_STATUS Status;
UINT32 TempData;
Status = PciRootBridgeIo->Pci.Read (
PciRootBridgeIo,
(EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH) (OPCODE_EXTRA_DATA (Entry->OpCode)),
(UINT64) Entry->PciAddress,
1,
&TempData
);
ASSERT_EFI_ERROR (Status);
Entry->OrMask &= Entry->AndMask;
TempData &= ~Entry->AndMask;
TempData |= Entry->OrMask;
Status = PciRootBridgeIo->Pci.Write (
PciRootBridgeIo,
(EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH) (OPCODE_EXTRA_DATA (Entry->OpCode)),
(UINT64) Entry->PciAddress,
1,
&TempData
);
ASSERT_EFI_ERROR (Status);
if (OPCODE_FLAGS (Entry->OpCode) & OPCODE_FLAG_S3SAVE) {
Status = S3BootScriptSavePciCfgReadWrite (
(EFI_BOOT_SCRIPT_WIDTH) (OPCODE_EXTRA_DATA (Entry->OpCode)),
(UINT64) Entry->PciAddress,
&Entry->OrMask,
&Entry->AndMask
);
ASSERT_EFI_ERROR (Status);
}
}
/**
Local worker function to process MEM_READ_MODIFY_WRITE table entries.
Performs RMW write and may also call BootScriptSave protocol if indicated in
the Entry flags.
@param Entry A pointer to the MEM_READ_MODIFY_WRITE entry to process.
@param PciRootBridgeIo A pointer to the instance of PciRootBridgeIo that is used
when processing the entry.
@retval Nothing.
**/
STATIC
VOID
MemReadModifyWrite (
EFI_REG_TABLE_MEM_READ_MODIFY_WRITE *Entry,
EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo
)
{
EFI_STATUS Status;
UINT32 TempData;
Status = PciRootBridgeIo->Mem.Read (
PciRootBridgeIo,
(EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH) (OPCODE_EXTRA_DATA (Entry->OpCode)),
(UINT64) Entry->MemAddress,
1,
&TempData
);
ASSERT_EFI_ERROR (Status);
Entry->OrMask &= Entry->AndMask;
TempData &= ~Entry->AndMask;
TempData |= Entry->OrMask;
Status = PciRootBridgeIo->Mem.Write (
PciRootBridgeIo,
(EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH) (OPCODE_EXTRA_DATA (Entry->OpCode)),
(UINT64) Entry->MemAddress,
1,
&TempData
);
ASSERT_EFI_ERROR (Status);
if (OPCODE_FLAGS (Entry->OpCode) & OPCODE_FLAG_S3SAVE) {
Status = S3BootScriptSaveMemReadWrite (
(EFI_BOOT_SCRIPT_WIDTH) (OPCODE_EXTRA_DATA (Entry->OpCode)),
Entry->MemAddress,
&Entry->OrMask,
&Entry->AndMask
);
ASSERT_EFI_ERROR (Status);
}
}
//
// Exported functions
//
/**
Processes register table assuming which may contain PCI, IO, MEM, and STALL
entries.
No parameter checking is done so the caller must be careful about omitting
values for PciRootBridgeIo or CpuIo parameters. If the regtable does
not contain any PCI accesses, it is safe to omit the PciRootBridgeIo (supply
NULL). If the regtable does not contain any IO or Mem entries, it is safe to
omit the CpuIo (supply NULL).
The RegTableEntry parameter is not checked, but is required.
gBS is assumed to have been defined and is used when processing stalls.
The function processes each entry sequentially until an OP_TERMINATE_TABLE
entry is encountered.
@param RegTableEntry A pointer to the register table to process
@param PciRootBridgeIo A pointer to the instance of PciRootBridgeIo that is used
when processing PCI table entries
@param CpuIo A pointer to the instance of CpuIo that is used when processing IO and
MEM table entries
@retval Nothing.
**/
VOID
ProcessRegTablePci (
EFI_REG_TABLE *RegTableEntry,
EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo,
EFI_CPU_IO_PROTOCOL *CpuIo
)
{
while (OPCODE_BASE (RegTableEntry->Generic.OpCode) != OP_TERMINATE_TABLE) {
switch (OPCODE_BASE (RegTableEntry->Generic.OpCode)) {
case OP_PCI_WRITE:
PciWrite ((EFI_REG_TABLE_PCI_WRITE *) RegTableEntry, PciRootBridgeIo);
break;
case OP_PCI_READ_MODIFY_WRITE:
PciReadModifyWrite ((EFI_REG_TABLE_PCI_READ_MODIFY_WRITE *) RegTableEntry, PciRootBridgeIo);
break;
case OP_MEM_READ_MODIFY_WRITE:
MemReadModifyWrite ((EFI_REG_TABLE_MEM_READ_MODIFY_WRITE *) RegTableEntry, PciRootBridgeIo);
break;
default:
DEBUG ((EFI_D_ERROR, "RegTable ERROR: Unknown RegTable OpCode (%x)\n", OPCODE_BASE (RegTableEntry->Generic.OpCode)));
ASSERT (0);
break;
}
RegTableEntry++;
}
}
/**
Processes register table assuming which may contain IO, MEM, and STALL
entries, but must NOT contain any PCI entries. Any PCI entries cause an
ASSERT in a DEBUG build and are skipped in a free build.
No parameter checking is done. Both RegTableEntry and CpuIo parameters are
required.
gBS is assumed to have been defined and is used when processing stalls.
The function processes each entry sequentially until an OP_TERMINATE_TABLE
entry is encountered.
@param RegTableEntry A pointer to the register table to process
@param CpuIo A pointer to the instance of CpuIo that is used when processing IO and
MEM table entries
@retval Nothing.
**/
VOID
ProcessRegTableCpu (
EFI_REG_TABLE *RegTableEntry,
EFI_CPU_IO_PROTOCOL *CpuIo
)
{
while (OPCODE_BASE (RegTableEntry->Generic.OpCode) != OP_TERMINATE_TABLE) {
switch (OPCODE_BASE (RegTableEntry->Generic.OpCode)) {
default:
DEBUG ((EFI_D_ERROR, "RegTable ERROR: Unknown RegTable OpCode (%x)\n", OPCODE_BASE (RegTableEntry->Generic.OpCode)));
ASSERT (0);
break;
}
RegTableEntry++;
}
}
|
903512c758ebb386686f7c977bc29b898d888a52
|
55540f3e86f1d5d86ef6b5d295a63518e274efe3
|
/components/network/wifi_manager/bl60x_wifi_driver/bl_mod_params.c
|
01c47c50c494eae967ec91bc144def8bc4a750cd
|
[
"Apache-2.0"
] |
permissive
|
bouffalolab/bl_iot_sdk
|
bc5eaf036b70f8c65dd389439062b169f8d09daa
|
b90664de0bd4c1897a9f1f5d9e360a9631d38b34
|
refs/heads/master
| 2023-08-31T03:38:03.369853
| 2023-08-16T08:50:33
| 2023-08-18T09:13:27
| 307,347,250
| 244
| 101
|
Apache-2.0
| 2023-08-28T06:29:02
| 2020-10-26T11:16:30
|
C
|
UTF-8
|
C
| false
| false
| 3,505
|
c
|
bl_mod_params.c
|
/*
* Copyright (c) 2016-2022 Bouffalolab.
*
* This file is part of
* *** Bouffalolab Software Dev Kit ***
* (see www.bouffalolab.com).
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of Bouffalo Lab nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "bl_defs.h"
#define COMMON_PARAM(name, default_softmac, default_fullmac) \
.name = default_fullmac,
#define SOFTMAC_PARAM(name, default)
#define FULLMAC_PARAM(name, default) .name = default,
struct bl_mod_params bl_mod_params = {
/* common parameters */
COMMON_PARAM(ht_on, true, true)
COMMON_PARAM(vht_on, false, false)
COMMON_PARAM(mcs_map, IEEE80211_VHT_MCS_SUPPORT_0_7, IEEE80211_VHT_MCS_SUPPORT_0_7)
COMMON_PARAM(phy_cfg, 2, 2)
COMMON_PARAM(uapsd_timeout, 3000, 3000)
COMMON_PARAM(sgi, false, false)
COMMON_PARAM(sgi80, false, false)
COMMON_PARAM(listen_itv, 1, 1)
COMMON_PARAM(listen_bcmc, true, true)
COMMON_PARAM(lp_clk_ppm, 20, 20)
COMMON_PARAM(ps_on, false, false)
COMMON_PARAM(tx_lft, RWNX_TX_LIFETIME_MS, RWNX_TX_LIFETIME_MS)
COMMON_PARAM(amsdu_maxnb, NX_TX_PAYLOAD_MAX, NX_TX_PAYLOAD_MAX)
// By default, only enable UAPSD for Voice queue (see IEEE80211_DEFAULT_UAPSD_QUEUE comment)
COMMON_PARAM(uapsd_queues, 0, 0)
};
int bl_handle_dynparams(struct bl_hw *bl_hw)
{
const int nss = 1;
if (bl_hw->mod_params->phy_cfg < 0 || bl_hw->mod_params->phy_cfg > 5)
bl_hw->mod_params->phy_cfg = 2;
if (bl_hw->mod_params->mcs_map < 0 || bl_hw->mod_params->mcs_map > 2)
bl_hw->mod_params->mcs_map = 0;
/* HT capabilities */
bl_hw->ht_cap.cap |= 1 << IEEE80211_HT_CAP_RX_STBC_SHIFT;
bl_hw->ht_cap.mcs.rx_highest = cpu_to_le16(65 * nss);
//Fixed leo disable MCS5/6/7
bl_hw->ht_cap.mcs.rx_mask[0] = 0xFF;
if (bl_hw->mod_params->sgi) {
bl_hw->ht_cap.cap |= IEEE80211_HT_CAP_SGI_20;
bl_hw->ht_cap.mcs.rx_highest = cpu_to_le16(72 * nss);
}
bl_hw->ht_cap.cap |= IEEE80211_HT_CAP_SM_PS;
if (!bl_hw->mod_params->ht_on)
bl_hw->ht_cap.ht_supported = false;
return 0;
}
|
43e8c0f1b186754e9ca045a8a925316b3d5b5cdd
|
a5a99f646e371b45974a6fb6ccc06b0a674818f2
|
/Calibration/HcalCalibAlgos/macros/CalibMain.C
|
747ed352779b1537e31d08523fe1ad1ab8cf4da7
|
[
"Apache-2.0"
] |
permissive
|
cms-sw/cmssw
|
4ecd2c1105d59c66d385551230542c6615b9ab58
|
19c178740257eb48367778593da55dcad08b7a4f
|
refs/heads/master
| 2023-08-23T21:57:42.491143
| 2023-08-22T20:22:40
| 2023-08-22T20:22:40
| 10,969,551
| 1,006
| 3,696
|
Apache-2.0
| 2023-09-14T19:14:28
| 2013-06-26T14:09:07
|
C++
|
UTF-8
|
C
| false
| false
| 15,812
|
c
|
CalibMain.C
|
////////////////////////////////////////////////////////////////////////////////
//
// This provides a provision of executing CalibMonitor, CalibProperties,
// CalibTree, or CalibSplit in batch operation.
//
// Usage:
// ./calibMain.exe <mode> <other parameters depending on mode>
// mode = 0:CalibMonitor, 1:CalibProperties, 2:CalibTree; 3: CalibSplit
//
// Other parameters for CalibMonitor:
// <InputFile> <HistogramFile> <Flag> <DirectoryName> <Prefix> <PUcorr>
// <Truncate> <Nmax> <datamc> <numb> <usegen> <scale> <usescale> <etalo>
// <etahi> <runlo> <runhi> <phimin> <phimax> <zside> <nvxlo> <nvxhi>
// <exclude> <etamax> <append> <all> <corrfile> <rcorfile> <dupfile>
// <rbxfile> <comfile> <outfile>
//
// Other parameters for CalibProperties:
// <InputFile> <HistogramFile> <Flag> <DirectoryName> <Prefix> <PUcorr>
// <Truncate> <Nmax> <datamc> <usegen> <scale> <usescale> <etalo> <etahi>
// <runlo> <runhi> <phimin> <phimax> <zside> <nvxlo> <nvxhi> <exclude>
// <etamax> <append> <all> <corrfile> <rcorfile> <dupfile> <rbxfile>
//
// Other parameters for CalibTree:
// <InputFile> <OutputFile> <Flag> <DirectoryName> <Prefix> <PUcorr>
// <Truncate> <Nmax> <maxIter> <corrfile> <applyl1> <l1cut> <useiter>
// <useweight> <usemean> <nmin> <inverse> <ratmin> <ratmax> <ietamax>
// <ietatrack> <sysmode> <rcorform> <usegen> <runlo> <runhi> <phimin>
// <phimax> <zside> <nvxlo> <nvxhi> <exclude> <higheta> <fraction>
// <writehisto> <debug> <rcorfile> <dupfile> <rbxfile> <treename>
//
// Other parameters for CalibSplit:
// <InputFile> <HistogramFile> <Flag> <DirectoryName> <Prefix> <PUcorr>
// <Truncate> <Nmax> <pmin> <pmax> <debug>
//
//
////////////////////////////////////////////////////////////////////////////////
#include <TROOT.h>
#include <TChain.h>
#include <TFile.h>
#include <TH1D.h>
#include <TH2F.h>
#include <TProfile.h>
#include <TFitResult.h>
#include <TFitResultPtr.h>
#include <TStyle.h>
#include <TCanvas.h>
#include <TLegend.h>
#include <TPaveStats.h>
#include <TPaveText.h>
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
#include <vector>
#include <string>
void unpackDetId(unsigned int, int&, int&, int&, int&, int&);
#include "CalibMonitor.C"
#include "CalibPlotProperties.C"
#include "CalibTree.C"
int main(Int_t argc, Char_t* argv[]) {
if (argc < 10) {
std::cerr << "Please give N arguments \n"
<< "Mode (0 CalibMonitor; 1 CalibProperties; 2 CalibTree; 3 CalibSplit)\n"
<< "Input File Name\n"
<< "Output File Name(ROOT)\n"
<< "Flag\n"
<< "Directory Name\n"
<< "Prefix\n"
<< "PUcorr\n"
<< "Truncate\n"
<< "Nmax\n"
<< " .... Other parameters depending on mode\n"
<< std::endl;
return -1;
}
int mode = std::atoi(argv[1]);
const char* infile = argv[2];
std::string histfile(argv[3]);
int flag = std::atoi(argv[4]);
const char* dirname = argv[5];
std::string prefix(argv[6]);
int pucorr = std::atoi(argv[7]);
int truncate = std::atoi(argv[8]);
Long64_t nmax = static_cast<Long64_t>(std::atoi(argv[9]));
if (mode == 0) {
// CalibMonitor
bool datamc = (argc > 10) ? (std::atoi(argv[10]) > 0) : true;
int numb = (argc > 11) ? std::atoi(argv[11]) : 50;
bool usegen = (argc > 12) ? (std::atoi(argv[12]) > 0) : false;
double scale = (argc > 13) ? std::atof(argv[13]) : 1.0;
int usescale = (argc > 14) ? std::atoi(argv[14]) : 0;
int etalo = (argc > 15) ? std::atoi(argv[15]) : 0;
int etahi = (argc > 16) ? std::atoi(argv[16]) : 30;
int runlo = (argc > 17) ? std::atoi(argv[17]) : 0;
int runhi = (argc > 18) ? std::atoi(argv[18]) : 99999999;
int phimin = (argc > 19) ? std::atoi(argv[19]) : 1;
int phimax = (argc > 20) ? std::atoi(argv[20]) : 72;
int zside = (argc > 21) ? std::atoi(argv[21]) : 1;
int nvxlo = (argc > 22) ? std::atoi(argv[22]) : 0;
int nvxhi = (argc > 23) ? std::atoi(argv[23]) : 1000;
bool exclude = (argc > 24) ? (std::atoi(argv[24]) > 0) : false;
bool etamax = (argc > 25) ? (std::atoi(argv[25]) > 0) : false;
bool append = (argc > 26) ? (std::atoi(argv[26]) > 0) : true;
bool all = (argc > 27) ? (std::atoi(argv[27]) > 0) : true;
const char* corrfile = (argc > 28) ? argv[28] : "";
const char* rcorfile = (argc > 29) ? argv[29] : "";
const char* dupfile = (argc > 30) ? argv[30] : "";
const char* rbxfile = (argc > 31) ? argv[31] : "";
const char* comfile = (argc > 32) ? argv[32] : "";
const char* outfile = (argc > 33) ? argv[33] : "";
if (strcmp(corrfile, "junk.txt") == 0)
corrfile = "";
if (strcmp(rcorfile, "junk.txt") == 0)
rcorfile = "";
if (strcmp(dupfile, "junk.txt") == 0)
dupfile = "";
if (strcmp(comfile, "junk.txt") == 0)
comfile = "";
if (strcmp(rbxfile, "junk.txt") == 0)
rbxfile = "";
std::cout << "Execute CalibMonitor with infile:" << infile << " dirName: " << dirname << " dupFile: " << dupfile
<< " comFile:" << comfile << " outFile:" << outfile << " prefix: " << prefix << " corrFile: " << corrfile
<< " rcoFile:" << rcorfile << " puCorr:" << pucorr << " Flag:" << flag << " Numb:" << numb
<< " dataMC:" << datamc << " truncate:" << truncate << " useGen:" << usegen << " Scale:" << scale
<< " useScale:" << usescale << " etaRange:" << etalo << ":" << etahi << " runRange:" << runlo << ":"
<< runhi << " phiRange:" << phimin << ":" << phimax << " zside:" << zside << " nvxRange:" << nvxlo << ":"
<< nvxhi << " rbxFile:" << rbxfile << " exclude:" << exclude << " etaMax:" << etamax
<< " histFile:" << histfile << " append:" << append << " all:" << all << " nmax:" << nmax << std::endl;
CalibMonitor c1(infile,
dirname,
dupfile,
comfile,
outfile,
prefix,
corrfile,
rcorfile,
pucorr,
flag,
numb,
datamc,
truncate,
usegen,
scale,
usescale,
etalo,
etahi,
runlo,
runhi,
phimin,
phimax,
zside,
nvxlo,
nvxhi,
rbxfile,
exclude,
etamax);
c1.Loop(nmax);
c1.savePlot(histfile, append, all);
} else if (mode == 1) {
// CalibPlotProperties
bool datamc = (argc > 10) ? (std::atoi(argv[10]) > 0) : true;
bool usegen = (argc > 11) ? (std::atoi(argv[11]) > 0) : false;
double scale = (argc > 12) ? std::atof(argv[12]) : 1.0;
int usescale = (argc > 13) ? std::atoi(argv[13]) : 0;
int etalo = (argc > 14) ? std::atoi(argv[14]) : 0;
int etahi = (argc > 15) ? std::atoi(argv[15]) : 30;
int runlo = (argc > 16) ? std::atoi(argv[16]) : 0;
int runhi = (argc > 17) ? std::atoi(argv[17]) : 99999999;
int phimin = (argc > 18) ? std::atoi(argv[18]) : 1;
int phimax = (argc > 19) ? std::atoi(argv[19]) : 72;
int zside = (argc > 20) ? std::atoi(argv[20]) : 1;
int nvxlo = (argc > 21) ? std::atoi(argv[21]) : 0;
int nvxhi = (argc > 22) ? std::atoi(argv[22]) : 1000;
bool exclude = (argc > 23) ? (std::atoi(argv[23]) > 0) : false;
bool etamax = (argc > 24) ? (std::atoi(argv[24]) > 0) : false;
bool append = (argc > 25) ? (std::atoi(argv[25]) > 0) : true;
bool all = (argc > 26) ? (std::atoi(argv[26]) > 0) : true;
const char* corrfile = (argc > 27) ? argv[27] : "";
const char* rcorfile = (argc > 28) ? argv[28] : "";
const char* dupfile = (argc > 29) ? argv[29] : "";
const char* rbxfile = (argc > 30) ? argv[30] : "";
if (strcmp(corrfile, "junk.txt") == 0)
corrfile = "";
if (strcmp(rcorfile, "junk.txt") == 0)
rcorfile = "";
if (strcmp(dupfile, "junk.txt") == 0)
dupfile = "";
if (strcmp(rbxfile, "junk.txt") == 0)
rbxfile = "";
bool debug(false);
CalibPlotProperties c1(infile,
dirname,
dupfile,
prefix,
corrfile,
rcorfile,
pucorr,
flag,
datamc,
truncate,
usegen,
scale,
usescale,
etalo,
etahi,
runlo,
runhi,
phimin,
phimax,
zside,
nvxlo,
nvxhi,
rbxfile,
exclude,
etamax);
c1.Loop(nmax);
c1.savePlot(histfile, append, all, debug);
} else if (mode == 2) {
// CalibTree
int maxIter = (argc > 10) ? std::atoi(argv[10]) : 30;
const char* corrfile = (argc > 11) ? argv[11] : "";
int applyl1 = (argc > 12) ? std::atoi(argv[12]) : 1;
double l1cut = (argc > 13) ? std::atof(argv[13]) : 0.5;
bool useiter = (argc > 14) ? (std::atoi(argv[14]) > 0) : true;
bool useweight = (argc > 15) ? (std::atoi(argv[15]) > 0) : true;
bool usemean = (argc > 16) ? (std::atoi(argv[16]) > 0) : false;
int nmin = (argc > 17) ? std::atoi(argv[17]) : 0;
bool inverse = (argc > 18) ? (std::atoi(argv[18]) > 0) : true;
double ratmin = (argc > 19) ? std::atof(argv[19]) : 0.25;
double ratmax = (argc > 20) ? std::atof(argv[20]) : 3.0;
int ietamax = (argc > 21) ? std::atoi(argv[21]) : 25;
int ietatrack = (argc > 22) ? std::atoi(argv[22]) : -1;
int sysmode = (argc > 23) ? std::atoi(argv[23]) : -1;
int rcorform = (argc > 24) ? std::atoi(argv[24]) : 0;
bool usegen = (argc > 25) ? (std::atoi(argv[25]) > 0) : false;
int runlo = (argc > 26) ? std::atoi(argv[26]) : 0;
int runhi = (argc > 27) ? std::atoi(argv[27]) : 99999999;
int phimin = (argc > 28) ? std::atoi(argv[28]) : 1;
int phimax = (argc > 29) ? std::atoi(argv[29]) : 72;
int zside = (argc > 30) ? std::atoi(argv[30]) : 0;
int nvxlo = (argc > 31) ? std::atoi(argv[31]) : 0;
int nvxhi = (argc > 32) ? std::atoi(argv[32]) : 1000;
bool exclude = (argc > 33) ? (std::atoi(argv[33]) > 0) : false;
int higheta = (argc > 34) ? std::atoi(argv[34]) : 1;
double fraction = (argc > 35) ? std::atof(argv[35]) : 1.0;
bool writehisto = (argc > 36) ? (std::atoi(argv[36]) > 0) : false;
double pmin = (argc > 37) ? std::atof(argv[37]) : 40.0;
double pmax = (argc > 38) ? std::atof(argv[38]) : 60.0;
bool debug = (argc > 39) ? (std::atoi(argv[39]) > 0) : false;
const char* rcorfile = (argc > 40) ? argv[40] : "";
const char* dupfile = (argc > 41) ? argv[41] : "";
const char* rbxfile = (argc > 42) ? argv[42] : "";
const char* treename = (argc > 43) ? argv[43] : "CalibTree";
if (strcmp(rcorfile, "junk.txt") == 0)
rcorfile = "";
if (strcmp(dupfile, "junk.txt") == 0)
dupfile = "";
if (strcmp(rbxfile, "junk.txt") == 0)
rbxfile = "";
char name[500];
sprintf(name, "%s/%s", dirname, treename);
TChain* chain = new TChain(name);
std::cout << "Create a chain for " << name << " from " << infile << std::endl;
if (!fillChain(chain, infile)) {
std::cout << "*****No valid tree chain can be obtained*****" << std::endl;
} else {
std::cout << "Proceed with a tree chain with " << chain->GetEntries() << " entries" << std::endl;
Long64_t nentryTot = chain->GetEntries();
Long64_t nentries = (fraction > 0.01 && fraction < 0.99) ? (Long64_t)(fraction * nentryTot) : nentryTot;
static const int maxIterMax = 100;
if (maxIter > maxIterMax)
maxIter = maxIterMax;
std::cout << "Tree " << name << " " << chain << " in directory " << dirname << " from file " << infile
<< " with nentries (tracks): " << nentries << std::endl;
unsigned int k(0), kmax(maxIter);
std::cout << "Proceed using CalibTree with dupFile:" << dupfile << " rcorFile:" << rcorfile
<< " trunCate:" << truncate << " useIter:" << useiter << " useMean:" << usemean << " runRange:" << runlo
<< ":" << runhi << " phiRange:" << phimin << ":" << phimax << " zSide:" << zside
<< " nvxRange:" << nvxlo << ":" << nvxhi << " sysMode:" << sysmode << " rbxFile:" << rbxfile
<< " puCorr:" << pucorr << " rcorForm:" << rcorform << " useGen:" << usegen << " exclude:" << exclude
<< " highEta:" << higheta << " pRange:" << pmin << ":" << pmax << std::endl;
CalibTree t(dupfile,
rcorfile,
truncate,
useiter,
usemean,
runlo,
runhi,
phimin,
phimax,
zside,
nvxlo,
nvxhi,
sysmode,
rbxfile,
pucorr,
rcorform,
usegen,
exclude,
higheta,
pmin,
pmax,
chain);
t.h_pbyE = new TH1D("pbyE", "pbyE", 100, -1.0, 9.0);
t.h_Ebyp_bfr = new TProfile("Ebyp_bfr", "Ebyp_bfr", 60, -30, 30, 0, 10);
t.h_Ebyp_aftr = new TProfile("Ebyp_aftr", "Ebyp_aftr", 60, -30, 30, 0, 10);
t.h_cvg = new TH1D("Cvg0", "Convergence", kmax, 0, kmax);
t.h_cvg->SetMarkerStyle(7);
t.h_cvg->SetMarkerSize(5.0);
TFile* fout = new TFile(histfile.c_str(), "RECREATE");
std::cout << "Output file: " << histfile << " opened in recreate mode" << std::endl;
fout->cd();
double cvgs[maxIterMax], itrs[maxIterMax];
t.getDetId(fraction, ietatrack, debug, nmax);
for (; k <= kmax; ++k) {
std::cout << "Calling Loop() " << k << "th time" << std::endl;
double cvg = t.Loop(k,
fout,
useweight,
nmin,
inverse,
ratmin,
ratmax,
ietamax,
ietatrack,
applyl1,
l1cut,
k == kmax,
fraction,
writehisto,
debug,
nmax);
itrs[k] = k;
cvgs[k] = cvg;
if (cvg < 0.00001)
break;
}
t.writeCorrFactor(corrfile, ietamax);
fout->cd();
TGraph* g_cvg;
g_cvg = new TGraph(k, itrs, cvgs);
g_cvg->SetMarkerStyle(7);
g_cvg->SetMarkerSize(5.0);
g_cvg->Draw("AP");
g_cvg->Write("Cvg");
std::cout << "Finish looping after " << k << " iterations" << std::endl;
t.makeplots(ratmin, ratmax, ietamax, useweight, fraction, debug, nmax);
fout->Close();
}
} else {
// CalibSplit
double pmin = (argc > 10) ? std::atof(argv[10]) : 40.0;
double pmax = (argc > 11) ? std::atof(argv[11]) : 60.0;
bool debug = (argc > 12) ? (std::atoi(argv[12]) > 0) : false;
CalibSplit c1(infile, dirname, histfile, pmin, pmax, debug);
c1.Loop(nmax);
}
return 0;
}
|
c7733205ee5ef54811d4e070f675f3b93f275d94
|
4b52bc727e3757a133a02fe5b98dcbdbe80bb2e6
|
/back/gc.h
|
b0fb7336af49b0dfacade0af692f5c5aeac6fd29
|
[
"MIT"
] |
permissive
|
never-lang/never
|
bbad1b6c6de7cd14c1cd956fdb9622f03cd2db9a
|
008b8f3a143513cda312473595dccb9b1212981d
|
refs/heads/master
| 2023-09-04T09:20:41.379437
| 2023-09-02T07:39:04
| 2023-09-02T07:39:04
| 134,974,042
| 432
| 19
|
MIT
| 2023-09-02T07:29:45
| 2018-05-26T15:41:59
|
C
|
UTF-8
|
C
| false
| false
| 6,275
|
h
|
gc.h
|
/**
* Copyright 2018 Slawomir Maludzinski
*
* 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 __GC_H__
#define __GC_H__
#include "object.h"
typedef enum gc_mem_type
{
GC_MEM_UNKNOWN = 0,
GC_MEM_IP = 1,
GC_MEM_ADDR = 2,
GC_MEM_STACK = 3,
} gc_mem_type;
typedef struct gc_mem
{
char mark;
object * object_value;
mem_ptr next;
} gc_mem;
typedef struct gc_stack
{
gc_mem_type type;
union {
ip_ptr ip;
mem_ptr addr;
stack_ptr sp;
};
} gc_stack;
typedef struct gc
{
mem_ptr free;
unsigned int mem_size;
gc_mem * mem;
unsigned int w_index;
unsigned int wb_top[2];
mem_ptr * wb_list[2];
} gc;
gc * gc_new(unsigned int mem_size);
void gc_delete(gc * collector);
void gc_sweep_all(gc * collector);
void gc_mark_vec(gc * collector, mem_ptr addr);
void gc_mark_arr(gc * collector, mem_ptr addr);
void gc_mark(gc * collector, mem_ptr addr);
void gc_mark_access(gc * collector, gc_stack * omfalos, int stack_size);
void gc_run_omfalos(gc * collector, gc_stack * omfalos, int stack_size);
void gc_run(gc * collector, gc_stack * omfalos, int stack_size,
mem_ptr global_vec);
mem_ptr gc_alloc_any(gc * collector, object * value);
mem_ptr gc_alloc_int(gc * collector, int value);
mem_ptr gc_alloc_long(gc * collector, long long value);
mem_ptr gc_alloc_float(gc * collector, float value);
mem_ptr gc_alloc_double(gc * collector, double value);
mem_ptr gc_alloc_char(gc * collector, char value);
mem_ptr gc_alloc_string(gc * collector, char * value);
mem_ptr gc_alloc_string_take(gc * collector, char * value);
mem_ptr gc_alloc_string_ref(gc * collector, mem_ptr str);
mem_ptr gc_alloc_c_ptr(gc * collector, void * value);
mem_ptr gc_alloc_vec(gc * collector, unsigned int size);
mem_ptr gc_alloc_vec_ref(gc * collector, mem_ptr vec);
mem_ptr gc_alloc_arr(gc * collector, unsigned int dims, object_arr_dim * dv);
mem_ptr gc_alloc_arr_ref(gc * collector, mem_ptr array);
mem_ptr gc_alloc_func(gc * collector, mem_ptr vec, ip_ptr addr);
mem_ptr gc_copy_arr(gc * collector, mem_ptr addr);
int gc_get_int(gc * collector, mem_ptr addr);
void gc_set_int(gc * collector, mem_ptr addr, int value);
void gc_inc_int(gc * collector, mem_ptr addr);
void gc_dec_int(gc * collector, mem_ptr addr);
int * gc_get_int_ptr(gc * collector, mem_ptr addr);
long long gc_get_long(gc * collector, mem_ptr addr);
void gc_set_long(gc * collector, mem_ptr addr, long long value);
long long * gc_get_long_ptr(gc * collector, mem_ptr addr);
float gc_get_float(gc * collector, mem_ptr addr);
void gc_set_float(gc * collector, mem_ptr addr, float value);
float * gc_get_float_ptr(gc * collector, mem_ptr addr);
double gc_get_double(gc * collector, mem_ptr addr);
void gc_set_double(gc * collector, mem_ptr addr, double value);
double * gc_get_double_ptr(gc * collector, mem_ptr addr);
char gc_get_char(gc * collector, mem_ptr addr);
void gc_set_char(gc * collector, mem_ptr addr, char value);
char * gc_get_char_ptr(gc * collector, mem_ptr addr);
char * gc_get_string(gc * collector, mem_ptr addr);
void gc_set_string(gc * collector, mem_ptr addr, char * value);
char ** gc_get_string_ptr(gc * collector, mem_ptr addr);
unsigned int gc_get_string_len(gc * collector, mem_ptr addr);
mem_ptr gc_get_string_ref(gc * collector, mem_ptr addr);
void gc_set_string_ref(gc * collector, mem_ptr addr, mem_ptr string_ref);
void * gc_get_c_ptr(gc * collector, mem_ptr addr);
void ** gc_get_c_ptr_ptr(gc * collector, mem_ptr addr);
void gc_set_c_ptr(gc * collector, mem_ptr addr, void * value);
mem_ptr gc_get_vec(gc * collector, mem_ptr addr, unsigned int vec_index);
void gc_set_vec(gc * collector, mem_ptr addr, unsigned int vec_index,
mem_ptr value);
unsigned int gc_get_vec_size(gc * collector, mem_ptr addr);
mem_ptr gc_get_vec_ref(gc * collector, mem_ptr addr);
mem_ptr gc_set_vec_ref(gc * collector, mem_ptr addr, mem_ptr vec_ref);
mem_ptr gc_get_arr(gc * collector, mem_ptr addr);
mem_ptr gc_get_arr_ref(gc * collector, mem_ptr addr);
void gc_set_arr_ref(gc * collector, mem_ptr addr, mem_ptr array);
object_arr * gc_get_arr_obj(gc * collector, mem_ptr addr);
unsigned int gc_get_arr_dim_elems(gc * collector, mem_ptr addr,
unsigned int dim);
unsigned int gc_get_arr_dims(gc * collector, mem_ptr addr);
unsigned int gc_get_arr_elems(gc * collector, mem_ptr addr);
object_arr_dim * gc_get_arr_dv(gc * collector, mem_ptr addr);
mem_ptr gc_get_arr_elem(gc * collector, mem_ptr addr, unsigned int elem_index);
void gc_set_arr_elem(gc * collector, mem_ptr addr, unsigned int elem_index,
mem_ptr value);
void gc_append_arr_elem(gc * collector, mem_ptr addr, mem_ptr value);
ip_ptr gc_get_func_addr(gc * collector, mem_ptr func_addr);
mem_ptr gc_get_func_vec(gc * collector, mem_ptr func_addr);
void gc_set_func_addr(gc * collector, mem_ptr func_addr, ip_ptr addr);
void gc_set_func_vec(gc * collector, mem_ptr func_addr, mem_ptr vec);
object * gc_get_object(gc * collector, mem_ptr addr);
gc_stack * gc_stack_new(int stack_size);
void gc_stack_delete(gc_stack * stack);
void gc_stack_print(gc_stack * stack, int stack_size);
void gc_object_print(gc * collector, mem_ptr addr);
#endif /* __GC_H__ */
|
bf36682284dc2a99d215d4defc5f558497d74b5d
|
3706c9baa2beb9d5b19150d1506dedaf0a036f22
|
/src/DSPUtilities.h
|
676a3cbd0461580806075e97dbbe79fdc96dc74d
|
[
"MIT"
] |
permissive
|
Miserlou/RJModules
|
0e7c0bff3723d64decb13787b6e5031fd7e6740d
|
809ad4f0b11cf227f6fcd6b4fed66110d4348b61
|
refs/heads/master
| 2023-05-12T00:25:07.001406
| 2023-05-04T00:21:51
| 2023-05-04T00:21:51
| 112,019,216
| 105
| 23
|
MIT
| 2023-05-04T00:08:54
| 2017-11-25T16:45:46
|
C++
|
UTF-8
|
C
| false
| false
| 2,509
|
h
|
DSPUtilities.h
|
//
// DSPUtilities.h
//
//
//
#ifndef DSPUtilities_h
#define DSPUtilities_h
//==============================================================================
// Calculates the frequency of a given pitch (MIDI) value.
double pitchToFreq(double pitch);
//==============================================================================
// Calculates the pitch (MIDI) of a given frequency value
double freqToPitch(double freq);
//==============================================================================
/**
Takes a value as input and clips it according to the min and max values.
Returns the input if (minValue <= in <= maxValue).
If (in < minValue), then return minValue.
If (in > maxValue), then return maxValue.
*/
double clipMinMax(double in, double minValue, double maxValue);
//==============================================================================
/**
Takes a value as input and clips it according to the min value.
Returns the input if (minValue <= in).
If (in < minValue), then return minValue.
*/
double clipMin(double in, double minValue);
//==============================================================================
/**
Crossfades linearly between two values (in0, in1). The value returned is
determined by the value of the xFadeCtrl argument.
xFadeCtrl Range: 0->1
- xFadeCtrl = 0 (only in0 comes through)
- xFadeCtrl = 0.5 (equal mix of in0 and in1)
- xfadeCtrl = 1 (only in1 comes through)
*/
double xFadeLin(double xFadeCtrl, double in0, double in1);
//==============================================================================
/**
Parabolic Controller Shaper:
"Bends" the controller curve torwards the X or Y axis.
input range: (-1..0..1) maps to output range: (-1..0..1).
bend range: (-1..0..1)
- bend = -1 (max bend towards X axis)
- bend = 0 (don't bend)
- bend = 1 (max bend towards Y axis)
*/
double parCtrlShaper(double input, double bend);
//==============================================================================
/**
Normalizes a range of values to the range 0->1.
(start/end should probably be the range of a parameter)
- input: the value to be normalized
- start: the start of the input's range
- end: the end of the input's range
Note: (start < end) and (start > end) are both valid.
*/
double normalizeRange(double input, double start, double end);
double resonanceToQ(double resonance);
//==============================================================================
#endif /* DSPUtilities_h */
|
c978102bcc7344fe19c2781a1ea730099a2093b7
|
7744859512f027ef0da8b1bde0f8518e631b98eb
|
/soh/assets/scenes/misc/market_night/market_night_scene.h
|
d35189134abf1ae5cac560db4e48788af52b13ce
|
[] |
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
| 298
|
h
|
market_night_scene.h
|
#pragma once
#include "align_asset_macro.h"
#define dmarket_night_sceneCollisionHeader_0025F8 "__OTR__scenes/nonmq/market_night_scene/market_night_sceneCollisionHeader_0025F8"
static const ALIGN_ASSET(2) char market_night_sceneCollisionHeader_0025F8[] = dmarket_night_sceneCollisionHeader_0025F8;
|
645a37ccfc167c5b5d7fea34a4300c1e5dd7397c
|
78dc9f153549b281be709227bc9897931b06260d
|
/generation/WinSDK/RecompiledIdlHeaders/um/stierr.h
|
84785fce4fa4e78f32c909e477046db6a33ed0aa
|
[
"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
| 4,214
|
h
|
stierr.h
|
/*++
Copyright (c) 1986-1997 Microsoft Corporation
Module Name:
stierr.h
Abstract:
This module contains the user mode still image APIs error and status codes
Author:
Revision History:
--*/
#ifndef _STIERR_
#define _STIERR_
#pragma once
#include <winapifamily.h>
#pragma region Desktop Family
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
//
// Error codes are constructed as compound COM status codes
//
/*
* The operation completed successfully
*/
#define STI_OK S_OK
#define STI_ERROR_NO_ERROR STI_OK
/*
* The device exists but not currently attached to the system
*/
#define STI_NOTCONNECTED S_FALSE
/*
* The requested change in device mode settings had no effect
*/
#define STI_CHANGENOEFFECT S_FALSE
/*
* The application requires newer version
*/
#define STIERR_OLD_VERSION \
MAKE_HRESULT(SEVERITY_ERROR,FACILITY_WIN32,ERROR_OLD_WIN_VERSION)
/*
* The application was written for pre-release version of provider DLL
*/
#define STIERR_BETA_VERSION \
MAKE_HRESULT(SEVERITY_ERROR,FACILITY_WIN32,ERROR_RMODE_APP)
/*
* The requested object could not be created due to incompatible or mismatched driver
*/
#define STIERR_BADDRIVER \
MAKE_HRESULT(SEVERITY_ERROR,FACILITY_WIN32,ERROR_BAD_DRIVER_LEVEL)
/*
* The device is not registered
*/
#define STIERR_DEVICENOTREG REGDB_E_CLASSNOTREG
/*
* The requested container does not exist
*/
#define STIERR_OBJECTNOTFOUND \
MAKE_HRESULT(SEVERITY_ERROR,FACILITY_WIN32,ERROR_FILE_NOT_FOUND)
/*
* An invalid or not state matching parameter was passed to the API
*/
#define STIERR_INVALID_PARAM E_INVALIDARG
/*
* The specified interface is not supported
*/
#define STIERR_NOINTERFACE E_NOINTERFACE
/*
* The undetermined error occured
*/
#define STIERR_GENERIC E_FAIL
/*
* There is not enough memory to perform requested operation
*/
#define STIERR_OUTOFMEMORY E_OUTOFMEMORY
/*
* The application called unsupported (at this time)function
*/
#define STIERR_UNSUPPORTED E_NOTIMPL
/*
* The application requires newer version
*/
#define STIERR_NOT_INITIALIZED \
MAKE_HRESULT(SEVERITY_ERROR,FACILITY_WIN32,ERROR_NOT_READY)
/*
* The application requires newer version
*/
#define STIERR_ALREADY_INITIALIZED \
MAKE_HRESULT(SEVERITY_ERROR,FACILITY_WIN32,ERROR_ALREADY_INITIALIZED)
/*
* The operation can not performed while device is locked
*/
#define STIERR_DEVICE_LOCKED \
MAKE_HRESULT(SEVERITY_ERROR,FACILITY_WIN32,ERROR_LOCK_VIOLATION)
/*
* The specified propery can not be changed for this device
*/
#define STIERR_READONLY E_ACCESSDENIED
/*
* The device already has notification handle associated with it
*/
#define STIERR_NOTINITIALIZED E_ACCESSDENIED
/*
* The device needs to be locked before attempting this operation
*/
#define STIERR_NEEDS_LOCK \
MAKE_HRESULT(SEVERITY_ERROR,FACILITY_WIN32,ERROR_NOT_LOCKED)
/*
* The device is opened by another application in data mode
*/
#define STIERR_SHARING_VIOLATION \
MAKE_HRESULT(SEVERITY_ERROR,FACILITY_WIN32,ERROR_SHARING_VIOLATION)
/*
* Handle already set for this context
*/
#define STIERR_HANDLEEXISTS \
MAKE_HRESULT(SEVERITY_ERROR,FACILITY_WIN32,ERROR_ALREADY_EXISTS)
/*
* Device name is not recognized
*/
#define STIERR_INVALID_DEVICE_NAME \
MAKE_HRESULT(SEVERITY_ERROR,FACILITY_WIN32,ERROR_INVALID_NAME)
/*
* Device hardware type is not valid
*/
#define STIERR_INVALID_HW_TYPE \
MAKE_HRESULT(SEVERITY_ERROR,FACILITY_WIN32,ERROR_INVALID_DATA)
/*
* Device hardware type is not valid
*/
#define STIERR_INVALID_HW_TYPE \
MAKE_HRESULT(SEVERITY_ERROR,FACILITY_WIN32,ERROR_INVALID_DATA)
/*
* No events available
*/
#define STIERR_NOEVENTS \
MAKE_HRESULT(SEVERITY_ERROR,FACILITY_WIN32,ERROR_NO_MORE_ITEMS)
/*
* Device appears as not ready
*/
#define STIERR_DEVICE_NOTREADY \
MAKE_HRESULT(SEVERITY_ERROR,FACILITY_WIN32,ERROR_NOT_READY)
//#define STIERR_
#endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) */
#pragma endregion
#endif // _STIERR_
|
38da06493b264e939cae35f5187687dd1894d97c
|
f367e4b66a1ee42e85830b31df88f63723c36a47
|
/lib/monkey/mk_bin/mk_signals.c
|
b2c9eb6e899a83a3cd99e99b4bc4bea4fe3a6a8b
|
[
"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,919
|
c
|
mk_signals.c
|
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* Monkey HTTP Server
* ==================
* Copyright 2001-2015 Monkey Software LLC <eduardo@monkey.io>
*
* 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 <monkey/monkey.h>
#include <monkey/mk_core.h>
#include "monkey.h"
#include <string.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
static struct mk_server *server_context;
void mk_signal_context(struct mk_server *ctx)
{
server_context = ctx;
}
/* when we catch a signal and want to exit we call this function
to do it gracefully */
static void mk_signal_exit()
{
/* ignore future signals to properly handle the cleanup */
signal(SIGTERM, SIG_IGN);
signal(SIGINT, SIG_IGN);
signal(SIGHUP, SIG_IGN);
mk_user_undo_uidgid(server_context);
mk_utils_remove_pid(server_context->path_conf_pidfile);
mk_exit_all(server_context);
mk_info("Exiting... >:(");
_exit(EXIT_SUCCESS);
}
static void mk_signal_handler(int signo, siginfo_t *si, void *context UNUSED_PARAM)
{
switch (signo) {
case SIGTERM:
case SIGINT:
mk_signal_exit();
break;
case SIGHUP:
/*
* TODO:
* we should implement the httpd config reload here (not in SIGUSR2).
* Daemon processes “overload” this signal with a mechanism to instruct them to
* reload their configuration files. Sending SIGHUP to Apache, for example,
* instructs it to reread httpd.conf.
*/
mk_signal_exit();
break;
case SIGBUS:
case SIGSEGV:
#ifdef DEBUG
mk_utils_stacktrace();
#endif
mk_err("%s (%d), code=%d, addr=%p",
strsignal(signo), signo, si->si_code, si->si_addr);
//close(sched->server_fd);
//pthread_exit(NULL);
abort();
default:
/* let the kernel handle it */
kill(getpid(), signo);
}
}
void mk_signal_init(void *context)
{
struct sigaction act;
memset(&act, 0x0, sizeof(act));
/* allow signals to be handled concurrently */
act.sa_flags = SA_SIGINFO | SA_NODEFER;
act.sa_sigaction = &mk_signal_handler;
sigaction(SIGSEGV, &act, NULL);
sigaction(SIGBUS, &act, NULL);
sigaction(SIGHUP, &act, NULL);
sigaction(SIGINT, &act, NULL);
sigaction(SIGTERM, &act, NULL);
mk_signal_context(context);
}
|
1a84f08904479d45c8fec1660fb20fd03fada149
|
549270020f6c8724e2ef1b12e38d11b025579f8d
|
/recipes/libxpm/all/test_package/test_package.c
|
ed1efad8c383c917933407551791aa4f286b12b5
|
[
"MIT"
] |
permissive
|
conan-io/conan-center-index
|
1bcec065ccd65aa38b1fed93fbd94d9d5fe6bc43
|
3b17e69bb4e5601a850b6e006e44775e690bac33
|
refs/heads/master
| 2023-08-31T11:34:45.403978
| 2023-08-31T11:13:23
| 2023-08-31T11:13:23
| 204,671,232
| 844
| 1,820
|
MIT
| 2023-09-14T21:22:42
| 2019-08-27T09:43:58
|
Python
|
UTF-8
|
C
| false
| false
| 144
|
c
|
test_package.c
|
#include <stddef.h>
#include <X11/xpm.h>
int main(int argc, char const* argv[])
{
(void)argc;
(void)argv;
XpmFree(NULL);
return 0;
}
|
c29644d4ba299c4d9c1390dadbcf8e7812df2ebe
|
f268b50cfc676024734009a0678825d01fa78a57
|
/src/stages/stage6/nonspells/nonspells.h
|
5ff9be8b45823ef464c97068ddc72e26efe32a12
|
[
"LicenseRef-scancode-warranty-disclaimer",
"CC-BY-4.0",
"LicenseRef-scancode-public-domain",
"MIT"
] |
permissive
|
taisei-project/taisei
|
90a1358567c77555eabfdb340bb6adeb913e2ced
|
f1c156cacdb579e66d4bc1776d4d1809e93014d2
|
refs/heads/master
| 2023-09-04T06:25:18.445412
| 2023-09-02T17:31:06
| 2023-09-02T17:31:06
| 977,986
| 785
| 87
|
NOASSERTION
| 2023-04-29T18:16:47
| 2010-10-11T07:31:32
|
C
|
UTF-8
|
C
| false
| false
| 1,061
|
h
|
nonspells.h
|
/*
* This software is licensed under the terms of the MIT License.
* See COPYING for further information.
* ---
* Copyright (c) 2011-2019, Lukas Weber <laochailan@web.de>.
* Copyright (c) 2012-2019, Andrei Alexeyev <akari@taisei-project.org>.
*/
#pragma once
#include "taisei.h"
#include "global.h"
#include "boss.h"
#include "stage.h"
#include "stages/stage6/elly.h"
DECLARE_EXTERN_TASK(stage6_boss_nonspell_scythe_common, { BoxedEllyScythe scythe; });
DECLARE_EXTERN_TASK(stage6_boss_nonspell_baryons_common, { BoxedEllyBaryons baryons; });
DECLARE_EXTERN_TASK_WITH_INTERFACE(stage6_boss_nonspell_1, ScytheAttack);
DECLARE_EXTERN_TASK_WITH_INTERFACE(stage6_boss_nonspell_2, ScytheAttack);
DECLARE_EXTERN_TASK(stage6_boss_paradigm_shift, { BossAttackTaskArgs base; BoxedEllyScythe scythe; BoxedEllyBaryons baryons; });
DECLARE_EXTERN_TASK_WITH_INTERFACE(stage6_boss_nonspell_4, BaryonsAttack);
DECLARE_EXTERN_TASK_WITH_INTERFACE(stage6_boss_nonspell_5, BaryonsAttack);
DECLARE_EXTERN_TASK_WITH_INTERFACE(stage6_boss_baryons_explode, BaryonsAttack);
|
db8b98e6b54be43879cc7aebb67ba6fbd3d143b4
|
e73547787354afd9b717ea57fe8dd0695d161821
|
/include/mapfs/iwa_01_hit.h
|
040d092ae9a05e9eebecf6cf0da70f4d1c79f07b
|
[] |
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
| 2,410
|
h
|
iwa_01_hit.h
|
#define COLLIDER_Root 0x35
#define COLLIDER_g298 0x34
#define COLLIDER_st2 0x33
#define COLLIDER_o1060 0x32
#define COLLIDER_st1 0x31
#define COLLIDER_g283 0x30
#define COLLIDER_o1065 0x2F
#define COLLIDER_o1064 0x2E
#define COLLIDER_o1063 0x2D
#define COLLIDER_o1062 0x2C
#define COLLIDER_tonnel 0x2B
#define COLLIDER_o1082 0x2A
#define COLLIDER_o1079 0x29
#define COLLIDER_o1072 0x28
#define COLLIDER_o1067 0x27
#define COLLIDER_o1047 0x26
#define COLLIDER_o986 0x25
#define COLLIDER_o983 0x24
#define COLLIDER_o982 0x23
#define COLLIDER_o981 0x22
#define COLLIDER_deilit4 0x21
#define COLLIDER_deili4 0x20
#define COLLIDER_t_n 0x1F
#define COLLIDER_o901 0x1E
#define COLLIDER_section4 0x1D
#define COLLIDER_o1081 0x1C
#define COLLIDER_o1078 0x1B
#define COLLIDER_deilit3 0x1A
#define COLLIDER_deili3 0x19
#define COLLIDER_o874 0x18
#define COLLIDER_s4_n 0x17
#define COLLIDER_section3 0x16
#define COLLIDER_noko 0x15
#define COLLIDER_o1077 0x14
#define COLLIDER_o869 0x13
#define COLLIDER_o980 0x12
#define COLLIDER_suberi01 0x11
#define COLLIDER_o870 0x10
#define COLLIDER_section2 0xF
#define COLLIDER_o1075 0xE
#define COLLIDER_o976 0xD
#define COLLIDER_o975 0xC
#define COLLIDER_suberi1 0xB
#define COLLIDER_o865 0xA
#define COLLIDER_section1 0x9
#define COLLIDER_o1076 0x8
#define COLLIDER_deilit2 0x7
#define COLLIDER_deili2 0x6
#define COLLIDER_deilit1 0x5
#define COLLIDER_deili1 0x4
#define COLLIDER_o974 0x3
#define COLLIDER_o972 0x2
#define COLLIDER_s1_n 0x1
#define COLLIDER_o844 0x0
#define ZONE_Root 0x9
#define ZONE_g283 0x8
#define ZONE_section3 0x7
#define ZONE_suberi01 0x6
#define ZONE_section2 0x5
#define ZONE_suberi1 0x4
#define ZONE_section1 0x3
#define ZONE_o973 0x2
#define ZONE_o972 0x1
#define ZONE_default 0x0
|
57f1d70c2bdb23544dc2c7e03749f817eb1f5a2b
|
a12b448f44beb4d521cb7e31677281f41df35f0b
|
/3rdParty/isl/test_inputs/codegen/omega/iter9-0.c
|
baedaa09277178dd95d96b1647ba4ecc0511ba55
|
[
"MIT",
"LGPL-2.0-or-later"
] |
permissive
|
Tiramisu-Compiler/tiramisu
|
d45f65dd9c35f643b3531ec79df1203c7ea3371d
|
f13e480f0ddb142cec371b7d7431a41d8ca885ec
|
refs/heads/master
| 2023-08-25T12:21:26.889736
| 2023-05-09T18:40:52
| 2023-05-09T18:40:52
| 58,378,976
| 906
| 168
|
MIT
| 2023-09-08T11:47:06
| 2016-05-09T13:33:51
|
C++
|
UTF-8
|
C
| false
| false
| 232
|
c
|
iter9-0.c
|
for (int c0 = 1; c0 <= 15; c0 += 1) {
if (((-exprVar1 + 15) % 8) + c0 <= 15) {
s1(c0);
s3(c0);
s2(c0);
s0(c0);
s4(c0);
}
if (((-exprVar1 + 15) % 8) + c0 <= 15 || (exprVar1 - c0 + 1) % 8 == 0)
s5(c0);
}
|
36feaf5980bd1f489342d34b62f7f5edff4eb0a6
|
40eadff029ed08d1c01ee93a735c1b46afca5c19
|
/src/plibraryloader-shl.c
|
8129697c3f120f3423ca2381fcfe6bf46ccb46fd
|
[
"MIT"
] |
permissive
|
saprykin/plibsys
|
59c5be91900e87e2606447c60de9d3ad9b699dbf
|
487bfd45a5b496693e07d6e76840951279a031b1
|
refs/heads/master
| 2023-08-17T00:16:48.121274
| 2023-08-13T17:11:39
| 2023-08-13T17:11:39
| 38,903,208
| 624
| 81
|
MIT
| 2023-07-02T16:27:53
| 2015-07-10T21:38:46
|
C
|
UTF-8
|
C
| false
| false
| 3,635
|
c
|
plibraryloader-shl.c
|
/*
* The MIT License
*
* Copyright (C) 2017 Alexander Saprykin <saprykin.spb@gmail.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.
*/
#include "perror.h"
#include "pfile.h"
#include "plibraryloader.h"
#include "pmem.h"
#include "pstring.h"
#include <dl.h>
#include <errno.h>
#include <string.h>
typedef shl_t plibrary_handle;
struct PLibraryLoader_ {
plibrary_handle handle;
int last_error;
};
static void pp_library_loader_clean_handle (plibrary_handle handle);
static void
pp_library_loader_clean_handle (plibrary_handle handle)
{
if (P_UNLIKELY (shl_unload (handle) != 0))
P_ERROR ("PLibraryLoader::pp_library_loader_clean_handle: shl_unload() failed");
}
P_LIB_API PLibraryLoader *
p_library_loader_new (const pchar *path)
{
PLibraryLoader *loader = NULL;
plibrary_handle handle;
if (!p_file_is_exists (path))
return NULL;
if (P_UNLIKELY ((handle = shl_load (path, BIND_IMMEDIATE | BIND_NONFATAL | DYNAMIC_PATH, 0)) == NULL)) {
P_ERROR ("PLibraryLoader::p_library_loader_new: shl_load() failed");
return NULL;
}
if (P_UNLIKELY ((loader = p_malloc0 (sizeof (PLibraryLoader))) == NULL)) {
P_ERROR ("PLibraryLoader::p_library_loader_new: failed to allocate memory");
pp_library_loader_clean_handle (handle);
return NULL;
}
loader->handle = handle;
loader->last_error = 0;
return loader;
}
P_LIB_API PFuncAddr
p_library_loader_get_symbol (PLibraryLoader *loader, const pchar *sym)
{
PFuncAddr func_addr = NULL;
if (P_UNLIKELY (loader == NULL || sym == NULL || loader->handle == NULL))
return NULL;
if (P_UNLIKELY (shl_findsym (&loader->handle, sym, TYPE_UNDEFINED, (ppointer) &func_addr) != 0)) {
P_ERROR ("PLibraryLoader::p_library_loader_get_symbol: shl_findsym() failed");
loader->last_error = (errno == 0 ? -1 : errno);
return NULL;
}
loader->last_error = 0;
return func_addr;
}
P_LIB_API void
p_library_loader_free (PLibraryLoader *loader)
{
if (P_UNLIKELY (loader == NULL))
return;
pp_library_loader_clean_handle (loader->handle);
p_free (loader);
}
P_LIB_API pchar *
p_library_loader_get_last_error (PLibraryLoader *loader)
{
if (loader == NULL)
return NULL;
if (loader->last_error == 0)
return NULL;
else if (loader->last_error == -1)
return p_strdup ("Failed to find a symbol");
else
return p_strdup (strerror (loader->last_error));
}
P_LIB_API pboolean
p_library_loader_is_ref_counted (void)
{
#if defined (P_OS_HPUX) && defined (P_CPU_HPPA) && (PLIBSYS_SIZEOF_VOID_P == 4)
return FALSE;
#else
return TRUE;
#endif
}
void
p_library_loader_init (void)
{
}
void
p_library_loader_shutdown (void)
{
}
|
d579990b2408496e588185a50ef617746954e9a0
|
25e99a0af5751865bce1702ee85cc5c080b0715c
|
/linux_system/src/linux-server-high-performance/9-1-select-recvdata.c
|
7c5a677eaf2af47cb0cb4a2c20352fb9e3b42f5e
|
[] |
no_license
|
jasonblog/note
|
215837f6a08d07abe3e3d2be2e1f183e14aa4a30
|
4471f95736c60969a718d854cab929f06726280a
|
refs/heads/master
| 2023-05-31T13:02:27.451743
| 2022-04-04T11:28:06
| 2022-04-04T11:28:06
| 35,311,001
| 130
| 67
| null | 2023-02-10T21:26:36
| 2015-05-09T02:04:40
|
C
|
UTF-8
|
C
| false
| false
| 2,649
|
c
|
9-1-select-recvdata.c
|
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <assert.h>
#include <stdio.h>
#include <assert.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int main(int argc, char *argv[])
{
if (argc <= 2)
{
fprintf(stderr, "usage: %s ip_address port_number\n", basename(argv[0]));
return 1;
}
const char *ip = argv[1];
int port = atoi(argv[2]);
int ret = 0;
struct sockaddr_in address;
bzero(&address, sizeof(address));
address.sin_family = AF_INET;
inet_pton(AF_INET, ip, &address.sin_addr);
address.sin_port = htons(port);
int listenfd = socket(PF_INET, SOCK_STREAM, 0);
assert(ret != -1);
ret = bind(listenfd, (struct sockaddr *)&address, sizeof(address));
assert(ret != -1);
ret = listen(listenfd, 5);
assert(ret != -1);
struct sockaddr_in client_address;
socklen_t client_addrlength = sizeof(client_address);
int connfd = accept(listenfd, (struct sockaddr *)&client_address, &client_addrlength);
if (connfd < 0)
{
fprintf(stderr, "accept error, errno:%d, errstr:%s\n", errno, strerror(errno));
}
char buf[1024];
fd_set read_fds;
fd_set exception_fds;
FD_ZERO(&read_fds);
FD_ZERO(&exception_fds);
while(1)
{
memset(buf, '\0', sizeof(buf));
/*每次调用select前都要重新在read_fds和exception_fds中设置文件描述副connfd,因为事件发生后,文件描述符集合将被内核修改*
*/
FD_SET(connfd, &read_fds);
FD_SET(connfd, &exception_fds);
ret = select (connfd + 1, &read_fds, NULL, &exception_fds, NULL);
if (ret < 0)
{
fprintf(stderr, "selcection failure\n");
break;
}
/*对于可读事件,采用普通的recv函数读取数据 */
if (FD_ISSET(connfd, &read_fds))
{
ret = recv(connfd, buf, sizeof(buf) - 1, 0);
if (ret <= 0)
{
break;
}
fprintf(stdout, "get %d bytes of normal data: %s\n", ret, buf);
}
/*对于异常事件,采用带MSG_OOB标志的recv函数读取带外数据 */
else if (FD_ISSET(connfd, &exception_fds))
{
ret = recv(connfd, buf, sizeof(buf) - 1, MSG_OOB);
if (ret <= 0)
{
break;
}
fprintf(stdout, "get %d bytes of oob data: %s\n", ret, buf);
}
}
close(connfd);
close(listenfd);
return 0;
}
|
31603793fbfb54723a522589a093ea51610d1bfb
|
aa3befea459382dc5c01c925653d54f435b3fb0f
|
/boards/arm/stm32/viewtool-stm32f107/src/viewtool_stm32f107.h
|
294dd6cfed9cf2a3ef391dd0f759f1c13e4f8c22
|
[
"MIT-open-group",
"BSD-3-Clause",
"HPND-sell-variant",
"BSD-4-Clause-UC",
"LicenseRef-scancode-warranty-disclaimer",
"MIT-0",
"LicenseRef-scancode-bsd-atmel",
"LicenseRef-scancode-gary-s-brown",
"LicenseRef-scancode-proprietary-license",
"SunPro",
"MIT",
"LicenseRef-scancode-public-domain-disclaimer",
"LicenseRef-scancode-other-permissive",
"HPND",
"ISC",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"GPL-1.0-or-later",
"CC-BY-2.0",
"CC-BY-4.0"
] |
permissive
|
apache/nuttx
|
14519a7bff4a87935d94fb8fb2b19edb501c7cec
|
606b6d9310fb25c7d92c6f95bf61737e3c79fa0f
|
refs/heads/master
| 2023-08-25T06:55:45.822534
| 2023-08-23T16:03:31
| 2023-08-24T21:25:47
| 228,103,273
| 407
| 241
|
Apache-2.0
| 2023-09-14T18:26:05
| 2019-12-14T23:27:55
|
C
|
UTF-8
|
C
| false
| false
| 19,638
|
h
|
viewtool_stm32f107.h
|
/****************************************************************************
* boards/arm/stm32/viewtool-stm32f107/src/viewtool_stm32f107.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.
*
****************************************************************************/
#ifndef __BOARDS_ARM_STM32_VIEWTOOL_STM32F107_SRC_VIEWTOOL_STM32F107_H
#define __BOARDS_ARM_STM32_VIEWTOOL_STM32F107_SRC_VIEWTOOL_STM32F107_H
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <nuttx/compiler.h>
#include <stdint.h>
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/* Configuration ************************************************************/
/* Assume that everything is supported */
#define HAVE_USBDEV 1
#define HAVE_MMCSD 1
#define HAVE_RTC_DRIVER 1
/* Handle chip differences */
#if defined(CONFIG_ARCH_CHIP_STM32F103VC)
# undef CONFIG_STM32_OTGFS
#elif defined(CONFIG_ARCH_CHIP_STM32F107VC)
# undef CONFIG_STM32_USB
# undef CONFIG_STM32_SDIO
#else
# error Unknown chip on Viewtool board
# undef HAVE_USBDEV
# undef HAVE_MMCSD
#endif
/* Check if USB is enabled */
#if !defined(CONFIG_STM32_OTGFS) && !defined(CONFIG_STM32_USB)
# undef HAVE_USBDEV
#elif !defined(CONFIG_USBDEV)
# warning CONFIG_STM32_OTGFS (F107) or CONFIG_STM32_USB (F103) is enabled but CONFIG_USBDEV is not
# undef HAVE_USB
#endif
/* Can't support MMC/SD features if the SDIO peripheral is disabled */
#ifndef CONFIG_STM32_SDIO
# undef HAVE_MMCSD
#endif
/* Can't support MMC/SD features if mountpoints are disabled */
#ifdef CONFIG_DISABLE_MOUNTPOINT
# undef HAVE_MMCSD
#endif
/* Default MMC/SD slot number/device minor number */
#define VIEWTOOL_MMCSD_SLOTNO 0
/* Check if we can support the RTC driver */
#if !defined(CONFIG_RTC) || !defined(CONFIG_RTC_DRIVER)
# undef HAVE_RTC_DRIVER
#endif
/* procfs File System */
#ifdef CONFIG_FS_PROCFS
# ifdef CONFIG_NSH_PROC_MOUNTPOINT
# define STM32_PROCFS_MOUNTPOINT CONFIG_NSH_PROC_MOUNTPOINT
# else
# define STM32_PROCFS_MOUNTPOINT "/proc"
# endif
#endif
/* GPIO Configuration *******************************************************/
/* LEDs
*
* There are four LEDs on the ViewTool STM32F103/F107 board that can be
* controlled by software:
* LED1 through LED4. All pulled high and can be illuminated by driving the
* output to low
*
* LED1 PA6
* LED2 PA7
* LED3 PB12
* LED4 PB13
*/
#define GPIO_LED1 (GPIO_OUTPUT | GPIO_CNF_OUTPP | GPIO_MODE_50MHz|\
GPIO_OUTPUT_SET | GPIO_PORTA | GPIO_PIN6)
#define GPIO_LED2 (GPIO_OUTPUT | GPIO_CNF_OUTPP | GPIO_MODE_50MHz|\
GPIO_OUTPUT_SET | GPIO_PORTA | GPIO_PIN7)
#define GPIO_LED3 (GPIO_OUTPUT | GPIO_CNF_OUTPP | GPIO_MODE_50MHz|\
GPIO_OUTPUT_SET | GPIO_PORTB | GPIO_PIN12)
#define GPIO_LED4 (GPIO_OUTPUT | GPIO_CNF_OUTPP | GPIO_MODE_50MHz|\
GPIO_OUTPUT_SET | GPIO_PORTB | GPIO_PIN13)
/* Buttons ******************************************************************/
/* All pulled high and will be sensed low when depressed.
*
* SW2 PC11 Needs J42 closed
* SW3 PC12 Needs J43 closed
* SW4 PA0 Needs J44 closed
*/
#define MIN_IRQBUTTON BUTTON_SW2
#define MAX_IRQBUTTON BUTTON_SW4
#define NUM_IRQBUTTONS (BUTTON_SW4 - BUTTON_SW2 + 1)
#define GPIO_SW2 (GPIO_INPUT | GPIO_CNF_INFLOAT | GPIO_MODE_INPUT | \
GPIO_EXTI | GPIO_PORTC | GPIO_PIN11)
#define GPIO_SW3 (GPIO_INPUT | GPIO_CNF_INFLOAT | GPIO_MODE_INPUT | \
GPIO_EXTI | GPIO_PORTC | GPIO_PIN12)
#define GPIO_SW4 (GPIO_INPUT | GPIO_CNF_INFLOAT | GPIO_MODE_INPUT | \
GPIO_EXTI | GPIO_PORTA | GPIO_PIN10)
/* microSD Card Interface
*
* microSD Connector
* -----------------
*
* ----------------------------- ------------------------- ---------------
* Connector J17 GPIO CONFIGURATION(s)
* PIN SIGNAL LEGEND (no remapping) DP83848C Board
* --- ------------- ----------- ------------------------- ---------------
* 1 VDD 3.3 N/A N/A 3.3
* 2 GND N/A N/A GND
* 3 PC8 SDIO_D0 GPIO_SDIO_D0 D0
* 4 PD2 SDIO_CMD GPIO_SDIO_CMD CMD
* 5 PC12 SDIO_CLK GPIO_SDIO_CK CLK
* 6 PC11 SDIO_D3 GPIO_SDIO_D3 D3
* 7 PC10 SDIO_D2 GPIO_SDIO_D2 D2
* 8 PC9 SDIO_D1 GPIO_SDIO_D1 D1
* 9 PA8 CD Board-specific GPIO input CD
* --- ------------- ----------- ------------------------- ----------------
*
* NOTES:
* 1. The STM32F107 does not support the SDIO/memory card interface.
* So the SD card cannot be used with the STM32F107 (unless the pin-out
* just happens to match up with an SPI-based card interface???)
*/
#ifdef CONFIG_ARCH_CHIP_STM32F103VC
# define GPIO_SD_CD (GPIO_INPUT | GPIO_CNF_INFLOAT | GPIO_EXTI| \
GPIO_PORTA | GPIO_PIN8)
#endif
/* USB
*
* The Viewtool base board has a USB Mini-B connector.
* Only USB device can be supported with this connector.
*
* ------------------------- ------------------------------------
* USB Connector
* J10 mini-USB GPIO CONFIGURATION(s)
* --- --------- ----------- ------------------------------------
* Pin Signal
* --- --------- ----------- ------------------------------------
* 1 USB_VBUS VDD_USB (No sensing available)
* 2 OTG_DM PA11 GPIO_OTGFS_DM (F107) GPIO_USB_DM (F103)
* 3 OTG_DP PA12 GPIO_OTGFS_DP (F107) GPIO_USB_DP (F103)
* 4 OTG_ID PA10 GPIO_OTGFS_ID (F107)
* 5 Shield N/A N/A
* 6 Shield N/A N/A
* 7 Shield N/A N/A
* 8 Shield N/A N/A
* 9 Shield N/A N/A
* PE11 USB_EN GPIO controlled soft pull-up (if J51 closed)
*
* NOTES:
* 1. GPIO_OTGFS_VBUS (F107) should not be configured. No VBUS sensing
* 2. GPIO_OTGFS_SOF (F107) is not used
* 3. The OTG FS module has is own, internal soft pull-up logic. J51 should
* be open so that PE11 activity does effect USB.
*/
#ifdef CONFIG_ARCH_CHIP_STM32F103VC
# define GPIO_USB_PULLUP (GPIO_OUTPUT | GPIO_CNF_OUTOD | GPIO_MODE_50MHz | \
GPIO_OUTPUT_SET | GPIO_PORTE | GPIO_PIN11)
#endif
/* LCD
*
* An LCD may be connected via J11.
* Only the STM32F103 supports the FSMC signals needed to drive the LCD.
*
* The LCD features an (1) HY32D module with built-in SSD1289 LCD controller,
* and (a) a XPT2046 touch screen controller.
*
* LCD Connector
* -------------
*
* ----------------------------- -------------------- ---------------------
* Connector J11 GPIO CONFIGURATION(s)
* PIN SIGNAL LEGEND (F103 only) LCD Module
* --- ------------- ----------- -------------------- ---------------------
* 1 VDD_5 NC N/A 5V ---
* 2 GND GND N/A GND ---
* 3 PD14 DATA0 GPIO_NPS_D0 D0 HY32D
* 4 PD15 DATA1 GPIO_NPS_D1 D1 HY32D
* 5 PD0 DATA2 GPIO_NPS_D2 D2 HY32D
* 6 PD1 DATA3 GPIO_NPS_D3 D3 HY32D
* 7 PE7 DATA4 GPIO_NPS_D4 D4 HY32D
* 8 PE8 DATA5 GPIO_NPS_D5 D5 HY32D
* 9 PE9 DATA6 GPIO_NPS_D6 D6 HY32D
* 10 PE10 DATA7 GPIO_NPS_D7 D7 HY32D
* 11 PE11 DATA8 GPIO_NPS_D8 D8 HY32D
* 12 PE12 DATA9 GPIO_NPS_D9 D9 HY32D
* 13 PE13 DATA10 GPIO_NPS_D10 D10 HY32D
* 14 PE14 DATA11 GPIO_NPS_D11 D11 HY32D
* 15 PE15 DATA12 GPIO_NPS_D12 D12 HY32D
* 16 PD8 DATA13 GPIO_NPS_D13 D13 HY32D
* 17 PD9 DATA14 GPIO_NPS_D14 D14 HY32D
* 18 PD10 DATA15 GPIO_NPS_D15 D15 HY32D
* 19 (3) LCD_CS GPIO_NPS_NE1 CS HY32D
* 20 PD11 LCD_RS GPIO_NPS_A16 RS HY32D
* 21 PD5 LCD_R/W GPIO_NPS_NWE WR HY32D
* 22 PD4 LCD_RD GPIO_NPS_NOE RD HY32D
* 23 PB1 LCD_RESET (GPIO) RESET HY32D
* 24 N/C NC N/A TE (unused?)
* 25 VDD_3.3 BL_VCC N/A BLVDD CA6219
* (Drives LCD
* backlight)
* 26 GND BL_GND N/A BLGND CA6219
* 27 PB0 BL_PWM GPIO_TIM3_CH3OUT(2) BL_CNT CA6219
* 28 PC5 LCDTP_IRQ (GPIO) TP_IRQ XPT2046
* 29 PC4 LCDTP_CS (GPIO) TP_CS XPT2046
* 30 PB13 LCDTP_CLK GPIO_SPI2_SCK TP_SCK XPT2046
* 31 PB15 LCDTP_DIN GPIO_SPI2_MOSI TP_SI XPT2046
* 32 PB14 LCDTP_DOUT GPIO_SPI2_MISO TP_SO XPT2046
* 33 VDD_3.3 VDD_3.3 N/A 3.3V ---
* 34 GND GND N/A GND ---
* --- ------------- ----------- -------------------- ---------------------
*
* NOTES:
* 1) Only the F103 version of the board supports the FSMC
* 2) No remap
* 3) LCD_CS is controlled by J13 JUMPER4 (under the LCD unfortunately):
*
* 1->2 : PD7 (GPIO_NPS_NE1) enables the multiplexor : 1E\ enable input
* (active LOW)
* 3->4 : PD13 provides 1A0 input (1A1 is grounded). : 1A0 address input
* So will chip enable to either LCD_CS or
* Flash_CS.
* 5->6 : 1Y0 output to LCD_CS : 1Y0 address output
* 7->8 : 1Y1 output to Flash_CE : 1Y1 address output
*
* Truth Table:
* 1E\ 1A0 1A1 1Y0 1Y1
* --- --- --- --- ---
* HI N/A N/A HI HI
* LO LO LO LO HI
* LO HI LO HI LO
*/
#define GPIO_LCD_RESET (GPIO_OUTPUT | GPIO_CNF_OUTPP | GPIO_MODE_50MHz | \
GPIO_OUTPUT_SET | GPIO_PORTB| GPIO_PIN1)
#define GPIO_LCDTP_IRQ (GPIO_INPUT | GPIO_CNF_INFLOAT | GPIO_MODE_INPUT | \
GPIO_EXTI | GPIO_PORTC | GPIO_PIN5)
#define GPIO_LCDTP_CS (GPIO_OUTPUT | GPIO_CNF_OUTPP | GPIO_MODE_50MHz | \
GPIO_OUTPUT_SET | GPIO_PORTC | GPIO_PIN4)
/* Freescale MPL115A barometer (optional add-on)
*
* This board support logic includes support for a Freescale MPL115A
* barometer using SPI3 with chip select on PB6.
*/
#define GPIO_MPL115A_CS (GPIO_OUTPUT | GPIO_CNF_OUTPP | GPIO_MODE_50MHz | \
GPIO_OUTPUT_SET | GPIO_PORTB | GPIO_PIN6)
/* FT80x GUI Discrete I/O (See README.txt for details):
*
* ------ ----------- --------------------
* NAME VIEWTOOL STM32
* ------ ----------- --------------------
* CS# J8 Pin 12 PA4/NSS1 (For SPI1)
* CS# J8 Pin 6 PB12/NSS2 (For SPI2)
* INT# J18 Pin 8 PA1
* PD# J18 Pin 6 PC5
*/
#if defined(CONFIG_VIEWTOOL_FT80X_SPI1)
# define FT80X_SPIBUS 1
# define GPIO_FT80X_CS (GPIO_OUTPUT | GPIO_CNF_OUTPP | GPIO_MODE_50MHz | \
GPIO_OUTPUT_SET | GPIO_PORTA | GPIO_PIN4)
#elif defined(CONFIG_VIEWTOOL_FT80X_SPI2)
# define FT80X_SPIBUS 2
# define GPIO_FT80X_CS (GPIO_OUTPUT | GPIO_CNF_OUTPP | GPIO_MODE_50MHz | \
GPIO_OUTPUT_SET | GPIO_PORTB | GPIO_PIN12)
#endif
#define GPIO_FT80X_INT (GPIO_INPUT | GPIO_CNF_INFLOAT | GPIO_MODE_INPUT | \
GPIO_EXTI | GPIO_PORTA | GPIO_PIN1)
#define GPIO_FT80_PD (GPIO_OUTPUT | GPIO_CNF_OUTPP | GPIO_MODE_50MHz | \
GPIO_OUTPUT_CLEAR | GPIO_PORTC| GPIO_PIN5)
/* MAX3421E USB HOST Discrete I/O (See README.txt for details):
*
* ------ ----------- --------------------
* NAME VIEWTOOL STM32
* ------ ----------- --------------------
* CS# J8 Pin 12 PA4/NSS1 (For SPI1)
* CS# J8 Pin 6 PB12/NSS2 (For SPI2)
* INT# J18 Pin 10 PA0
* RST# J18 Pin 8 PA1
* GPX J18 Pin 6 PC5 (not used)
*/
#if defined(CONFIG_VIEWTOOL_MAX3421E_SPI1)
# define MAX3421E_SPIBUS 1
# define GPIO_MAX3421E_CS (GPIO_OUTPUT | GPIO_CNF_OUTPP | GPIO_MODE_50MHz | \
GPIO_OUTPUT_SET | GPIO_PORTA | GPIO_PIN4)
#elif defined(CONFIG_VIEWTOOL_MAX3421E_SPI2)
# define MAX3421E_SPIBUS 2
# define GPIO_MAX3421E_CS (GPIO_OUTPUT | GPIO_CNF_OUTPP | GPIO_MODE_50MHz | \
GPIO_OUTPUT_SET | GPIO_PORTB | GPIO_PIN12)
#endif
#define GPIO_MAX3421E_INT (GPIO_INPUT | GPIO_CNF_INFLOAT | GPIO_MODE_INPUT | \
GPIO_EXTI | GPIO_PORTA | GPIO_PIN0)
#define GPIO_MAX3421E_RST (GPIO_OUTPUT | GPIO_CNF_OUTPP | GPIO_MODE_50MHz | \
GPIO_OUTPUT_CLEAR | GPIO_PORTA | GPIO_PIN1)
#define GPIO_MAX3421E_GPX (GPIO_INPUT | GPIO_CNF_INFLOAT | GPIO_MODE_INPUT | \
GPIO_PORTC | GPIO_PIN5)
/****************************************************************************
* Public Functions Definitions
****************************************************************************/
#ifndef __ASSEMBLY__
/****************************************************************************
* Name: stm32_bringup
*
* Description:
* Perform architecture-specific initialization
*
* CONFIG_BOARD_LATE_INITIALIZE=y :
* Called from board_late_initialize().
*
* CONFIG_BOARD_LATE_INITIALIZE=n && CONFIG_BOARDCTL=y :
* Called from the NSH library
*
****************************************************************************/
int stm32_bringup(void);
/****************************************************************************
* Name: stm32_spidev_initialize
*
* Description:
* Called to configure SPI chip select GPIO pins for the M3 Wildfire board.
*
****************************************************************************/
void weak_function stm32_spidev_initialize(void);
/****************************************************************************
* Name: stm32_led_initialize
*
* Description:
* Configure LEDs. LEDs are left in the OFF state.
*
****************************************************************************/
void stm32_led_initialize(void);
/****************************************************************************
* Name: stm32_usbdev_initialize
*
* Description:
* Called from stm32_usbdev_initialize very early in initialization to
* setup USB-related GPIO pins for the Viewtool STM32F107 board.
*
****************************************************************************/
#if defined(CONFIG_STM32_OTGFS) && defined(CONFIG_USBDEV)
void weak_function stm32_usbdev_initialize(void);
#endif
/****************************************************************************
* Name: stm32_tsc_setup
*
* Description:
* This function is called by board-bringup logic to configure the
* touchscreen device. This function will register the driver as
* /dev/inputN where N is the minor device number.
*
* Input Parameters:
* minor - The input device minor number
*
* Returned Value:
* Zero is returned on success. Otherwise, a negated errno value is
* returned to indicate the nature of the failure.
*
****************************************************************************/
#ifdef CONFIG_INPUT_ADS7843E
int stm32_tsc_setup(int minor);
#endif
/****************************************************************************
* Name: stm32_sdinitialize
*
* Description:
* Initialize the SPI-based SD card. Requires CONFIG_DISABLE_MOUNTPOINT=n
* and CONFIG_STM32_SPI1=y
*
****************************************************************************/
int stm32_sdinitialize(int minor);
/****************************************************************************
* Name: stm32_can_setup
*
* Description:
* Initialize CAN and register the CAN device
*
****************************************************************************/
#ifdef CONFIG_STM32_CAN_CHARDRIVER
int stm32_can_setup(void);
#endif
/****************************************************************************
* Name: stm32_mpl115ainitialize
*
* Description:
* Initialize and register the MPL115A Pressure Sensor driver.
*
* Input Parameters:
* devpath - The full path to the driver to register. E.g., "/dev/press0"
*
* Returned Value:
* Zero (OK) on success; a negated errno value on failure.
*
****************************************************************************/
#if defined(CONFIG_SPI) && defined(CONFIG_SENSORS_MPL115A) && defined(CONFIG_STM32_SPI3)
int stm32_mpl115ainitialize(const char *devpath);
#endif
/****************************************************************************
* Name: stm32_ft80x_setup
*
* Description:
* This function is called by board-bringup logic to configure the
* FT80x GUI device.
*
* Input Parameters:
* None
*
* Returned Value:
* Zero is returned on success. Otherwise, a negated errno value is
* returned to indicate the nature of the failure.
*
****************************************************************************/
#if defined(CONFIG_VIEWTOOL_FT80X_SPI1) || defined(CONFIG_VIEWTOOL_FT80X_SPI2)
int stm32_ft80x_setup(void);
#endif
/****************************************************************************
* Name: stm32_max3421e_setup
*
* Description:
* This function is called by board-bringup logic to configure the
* MAX3421E USB host.
*
* Input Parameters:
* None
*
* Returned Value:
* Zero is returned on success. Otherwise, a negated errno value is
* returned to indicate the nature of the failure.
*
****************************************************************************/
#if defined(CONFIG_VIEWTOOL_MAX3421E_SPI1) || defined(CONFIG_VIEWTOOL_MAX3421E_SPI2)
int stm32_max3421e_setup(void);
#endif
#endif /* __ASSEMBLY__ */
#endif /* __BOARDS_ARM_STM32_VIEWTOOL_STM32F107_SRC_VIEWTOOL_STM32F107_H */
|
30c7fdfa94ded47f2c9dbd243b841867b5cf4d62
|
fd016aacb50a65dbda2f0e2b35cec38a63baf68d
|
/targets/AzureRTOS/SiliconLabs/SL_STK3701A/config/sl_usbd_class_winusb_config.h
|
4da7f4409b54188ce35d4043f40334e0c293072b
|
[
"MIT"
] |
permissive
|
nanoframework/nf-interpreter
|
4795563afe8b1d8e4819a4b4ebd700c9e36a4d80
|
2ebb0aeef2d9482a6233e4c78f562878ba726cf6
|
refs/heads/main
| 2023-08-29T11:30:31.384324
| 2023-08-29T10:55:46
| 2023-08-29T10:55:46
| 74,834,622
| 283
| 266
|
MIT
| 2023-09-14T00:22:43
| 2016-11-26T15:45:06
|
C
|
UTF-8
|
C
| false
| false
| 1,709
|
h
|
sl_usbd_class_winusb_config.h
|
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright 2021 Silicon Laboratories Inc. All rights reserved.
// See LICENSE file in the project root for full license information.
//
#ifndef SL_USBD_VENDOR_WINUSB_CONFIG_H
#define SL_USBD_VENDOR_WINUSB_CONFIG_H
// <<< Use Configuration Wizard in Context Menu >>>
// <h> Class Configuration
// <s SL_USBD_VENDOR_WINUSB_CONFIGURATIONS> Configuration(s) to add this class instance to
// <i> Default: all
// <i> Comma separated list of configuration instances (like inst0, inst1)
// <i> that this vendor class instance will be attached to. You can
// <i> use "all" to attach the class to all configs, or use an empty
// <i> string if you do not want to attach the interface to any configuration.
#define SL_USBD_VENDOR_WINUSB_CONFIGURATIONS "all"
// </h>
// <h> Protocol Details
// <q SL_USBD_VENDOR_WINUSB_INTERRUPT_ENDPOINTS> Add interrupt endpoints
// <i> Default: 0
// <i> Specifies whether we should add IN and OUT endpoints to this
// <i> vendor class interface.
#define SL_USBD_VENDOR_WINUSB_INTERRUPT_ENDPOINTS 0
// <o SL_USBD_VENDOR_WINUSB_INTERVAL> Endpoint interval
// <1=> 1ms
// <2=> 2ms
// <4=> 4ms
// <8=> 8ms
// <16=> 16ms
// <32=> 32ms
// <64=> 64ms
// <128=> 128ms
// <256=> 256ms
// <512=> 512ms
// <1024=> 1024ms
// <2048=> 2048ms
// <4096=> 4096ms
// <8192=> 8192ms
// <16384=> 16384ms
// <32768=> 32768ms
// <i> Default: 2
// <i> Polling interval for input/output transfers, in milliseconds.
// <i> It must be a power of 2.
#define SL_USBD_VENDOR_WINUSB_INTERVAL 2
// </h>
// <<< end of configuration section >>>
#endif // SL_USBD_VENDOR_WINUSB_CONFIG_H
|
36ed3f93d893594761efd576415f66059dccbe09
|
010279e2ba272d09e9d2c4e903722e5faba2cf7a
|
/contrib/tools/python3/src/Include/errcode.h
|
54ae929bf258703845c0c832585ffa9595ee7da0
|
[
"LicenseRef-scancode-python-cwi",
"LicenseRef-scancode-other-copyleft",
"Python-2.0",
"BSD-3-Clause",
"0BSD",
"GPL-1.0-or-later",
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] |
permissive
|
catboost/catboost
|
854c1a1f439a96f1ae6b48e16644be20aa04dba2
|
f5042e35b945aded77b23470ead62d7eacefde92
|
refs/heads/master
| 2023-09-01T12:14:14.174108
| 2023-09-01T10:01:01
| 2023-09-01T10:22:12
| 97,556,265
| 8,012
| 1,425
|
Apache-2.0
| 2023-09-11T03:32:32
| 2017-07-18T05:29:04
|
Python
|
UTF-8
|
C
| false
| false
| 1,700
|
h
|
errcode.h
|
#ifndef Py_ERRCODE_H
#define Py_ERRCODE_H
#ifdef __cplusplus
extern "C" {
#endif
/* Error codes passed around between file input, tokenizer, parser and
interpreter. This is necessary so we can turn them into Python
exceptions at a higher level. Note that some errors have a
slightly different meaning when passed from the tokenizer to the
parser than when passed from the parser to the interpreter; e.g.
the parser only returns E_EOF when it hits EOF immediately, and it
never returns E_OK. */
#define E_OK 10 /* No error */
#define E_EOF 11 /* End Of File */
#define E_INTR 12 /* Interrupted */
#define E_TOKEN 13 /* Bad token */
#define E_SYNTAX 14 /* Syntax error */
#define E_NOMEM 15 /* Ran out of memory */
#define E_DONE 16 /* Parsing complete */
#define E_ERROR 17 /* Execution error */
#define E_TABSPACE 18 /* Inconsistent mixing of tabs and spaces */
#define E_OVERFLOW 19 /* Node had too many children */
#define E_TOODEEP 20 /* Too many indentation levels */
#define E_DEDENT 21 /* No matching outer block for dedent */
#define E_DECODE 22 /* Error in decoding into Unicode */
#define E_EOFS 23 /* EOF in triple-quoted string */
#define E_EOLS 24 /* EOL in single-quoted string */
#define E_LINECONT 25 /* Unexpected characters after a line continuation */
#define E_BADSINGLE 27 /* Ill-formed single statement input */
#define E_INTERACT_STOP 28 /* Interactive mode stopped tokenization */
#ifdef __cplusplus
}
#endif
#endif /* !Py_ERRCODE_H */
|
820b0539a3bf0bd1315507db6c754ddb9b303874
|
fdbb74a95924e2677466614f6ab6e2bb13b2a95a
|
/test/libc/sock/nonblock_test.c
|
76535d7b890ffb8784307501c059c9f3dcfeda25
|
[
"ISC"
] |
permissive
|
jart/cosmopolitan
|
fb11b5658939023977060a7c6c71a74093d9cb44
|
0d748ad58e1063dd1f8560f18a0c75293b9415b7
|
refs/heads/master
| 2023-09-06T09:17:29.303607
| 2023-09-02T03:49:13
| 2023-09-02T03:50:18
| 272,457,606
| 11,887
| 435
|
ISC
| 2023-09-14T17:47:58
| 2020-06-15T14:16:13
|
C
|
UTF-8
|
C
| false
| false
| 5,584
|
c
|
nonblock_test.c
|
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
│vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│
╞══════════════════════════════════════════════════════════════════════════════╡
│ Copyright 2023 Justine Alexandra Roberts Tunney │
│ │
│ Permission to use, copy, modify, and/or distribute this software for │
│ any purpose with or without fee is hereby granted, provided that the │
│ above copyright notice and this permission notice appear in all copies. │
│ │
│ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │
│ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │
│ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │
│ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │
│ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │
│ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/calls/calls.h"
#include "libc/errno.h"
#include "libc/intrin/strace.internal.h"
#include "libc/runtime/runtime.h"
#include "libc/runtime/syslib.internal.h"
#include "libc/sock/sock.h"
#include "libc/sock/struct/sockaddr.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/consts/f.h"
#include "libc/sysv/consts/ipproto.h"
#include "libc/sysv/consts/limits.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/sock.h"
#include "libc/testlib/subprocess.h"
#include "libc/testlib/testlib.h"
#include "libc/thread/thread.h"
TEST(O_NONBLOCK, canBeSetBySocket_toMakeListenNonBlocking) {
char buf[16] = {0};
uint32_t addrsize = sizeof(struct sockaddr_in);
struct sockaddr_in addr = {
.sin_family = AF_INET,
.sin_addr.s_addr = htonl(0x7f000001),
};
pthread_spinlock_t *phaser = _mapshared(4096);
EXPECT_EQ(0, pthread_spin_lock(phaser + 0));
EXPECT_EQ(0, pthread_spin_lock(phaser + 1));
ASSERT_SYS(0, 3, socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP));
ASSERT_SYS(0, 0, bind(3, (struct sockaddr *)&addr, sizeof(addr)));
ASSERT_SYS(0, 0, getsockname(3, (struct sockaddr *)&addr, &addrsize));
ASSERT_SYS(0, 0, listen(3, SOMAXCONN));
SPAWN(fork);
ASSERT_SYS(EAGAIN, -1, accept(3, (struct sockaddr *)&addr, &addrsize));
EXPECT_EQ(0, pthread_spin_unlock(phaser + 0));
for (;;) {
int e = errno;
int fd = accept(3, (struct sockaddr *)&addr, &addrsize);
if (fd == -1 && errno == EAGAIN) {
errno = e;
usleep(1000);
continue;
}
ASSERT_SYS(0, 4, fd);
break;
}
ASSERT_SYS(0, 5, send(4, "hello", 5, 0));
EXPECT_EQ(0, pthread_spin_unlock(phaser + 1));
EXPECT_SYS(0, 0, close(4));
EXPECT_SYS(0, 0, close(3));
PARENT();
EXPECT_SYS(0, 0, close(3));
ASSERT_SYS(0, 3, socket(AF_INET, SOCK_STREAM, IPPROTO_TCP));
EXPECT_EQ(0, pthread_spin_lock(phaser + 0));
ASSERT_SYS(0, 0, connect(3, (struct sockaddr *)&addr, sizeof(addr)));
EXPECT_EQ(0, pthread_spin_lock(phaser + 1));
EXPECT_SYS(0, 5, read(3, buf, 16));
EXPECT_STREQ("hello", buf);
EXPECT_SYS(0, 0, close(3));
WAIT(exit, 0);
munmap(phaser, 4096);
}
TEST(O_NONBLOCK, canBeTunedWithFcntl_toMakeReadNonBlocking) {
char buf[16] = {0};
uint32_t addrsize = sizeof(struct sockaddr_in);
struct sockaddr_in addr = {
.sin_family = AF_INET,
.sin_addr.s_addr = htonl(0x7f000001),
};
pthread_spinlock_t *phaser = _mapshared(4096);
EXPECT_EQ(0, pthread_spin_lock(phaser + 0));
EXPECT_EQ(0, pthread_spin_lock(phaser + 1));
ASSERT_SYS(0, 3, socket(AF_INET, SOCK_STREAM, IPPROTO_TCP));
ASSERT_SYS(0, 0, bind(3, (struct sockaddr *)&addr, sizeof(addr)));
ASSERT_SYS(0, 0, getsockname(3, (struct sockaddr *)&addr, &addrsize));
ASSERT_SYS(0, 0, listen(3, SOMAXCONN));
SPAWN(fork);
ASSERT_SYS(0, 4, accept(3, (struct sockaddr *)&addr, &addrsize));
EXPECT_EQ(0, pthread_spin_lock(phaser + 0));
ASSERT_SYS(0, 5, send(4, "hello", 5, 0));
EXPECT_EQ(0, pthread_spin_lock(phaser + 1));
EXPECT_SYS(0, 0, close(4));
EXPECT_SYS(0, 0, close(3));
PARENT();
EXPECT_SYS(0, 0, close(3));
ASSERT_SYS(0, 3, socket(AF_INET, SOCK_STREAM, IPPROTO_TCP));
ASSERT_SYS(0, O_RDWR, fcntl(3, F_GETFL));
ASSERT_SYS(0, 0, connect(3, (struct sockaddr *)&addr, sizeof(addr)));
ASSERT_SYS(0, 0, fcntl(3, F_SETFL, O_RDWR | O_NONBLOCK));
ASSERT_SYS(EAGAIN, -1, read(3, buf, 16));
EXPECT_EQ(0, pthread_spin_unlock(phaser + 0));
TryAgain:
int e = errno;
ssize_t rc = read(3, buf, 16);
if (rc == -1 && errno == EAGAIN) {
errno = e;
usleep(1000);
goto TryAgain;
}
EXPECT_SYS(0, 5, rc);
EXPECT_STREQ("hello", buf);
EXPECT_EQ(0, pthread_spin_unlock(phaser + 1));
EXPECT_SYS(0, 0, close(3));
WAIT(exit, 0);
munmap(phaser, 4096);
}
|
5ce1327f4d7ca1d20dfd093a08524306cb22dc6b
|
9de0cec678bc4a3bec2b4adabef9f39ff5b4afac
|
/PWGCF/FEMTOSCOPY/macros/Train/PWG2Train2/ConfigFemtoAnalysis.C
|
c5d8e7b4e25f73605a5843e90a999b7144443192
|
[] |
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
| 21,624
|
c
|
ConfigFemtoAnalysis.C
|
/*********************************************************************
* *
* ConfigFemtoAnalysis.C - configuration macro for the femtoscopic *
* analysis, to be run in the analysis train. *
* Assumed input data: large (>10M) sample of MC pp events *
* Inluded analysis: *
* - positive pion HBT, 3 kt bins, 1D+3D functions *
* - negative pion HBT, 3 kt bins, 1D+3D functions *
* - positive kaon HBT, 1 kt bin, 1D+3D functions *
* *
* Author: Adam Kisiel (Adam.Kisiel@cern.ch) *
* *
*********************************************************************/
#if !defined(__CINT__) || defined(__MAKECINT_)
#include "AliFemtoManager.h"
#include "AliFemtoEventReaderESDChain.h"
#include "AliFemtoEventReaderESDChainKine.h"
#include "AliFemtoSimpleAnalysis.h"
#include "AliFemtoBasicEventCut.h"
#include "AliFemtoESDTrackCut.h"
#include "AliFemtoCorrFctn.h"
#include "AliFemtoCutMonitorParticleYPt.h"
#include "AliFemtoCutMonitorParticleVertPos.h"
#include "AliFemtoCutMonitorParticleMomRes.h"
#include "AliFemtoCutMonitorEventMult.h"
#include "AliFemtoCutMonitorEventVertex.h"
#include "AliFemtoShareQualityTPCEntranceSepPairCut.h"
#include "AliFemtoQinvCorrFctn.h"
#include "AliFemtoShareQualityCorrFctn.h"
#include "AliFemtoTPCInnerCorrFctn.h"
#include "AliFemtoVertexMultAnalysis.h"
#include "AliFemtoCorrFctn3DSpherical.h"
#include "AliFemtoChi2CorrFctn.h"
#include "AliFemtoCorrFctnTPCNcls.h"
#include "AliFemtoModelBPLCMSCorrFctn.h"
#include "AliFemtoModelCorrFctn3DSpherical.h"
#include "AliFemtoModelGausLCMSFreezeOutGenerator.h"
#include "AliFemtoModelGausRinvFreezeOutGenerator.h"
#include "AliFemtoModelManager.h"
#include "AliFemtoModelWeightGeneratorBasic.h"
#include "AliFemtoModelWeightGeneratorLednicky.h"
#include "AliFemtoCorrFctnDirectYlm.h"
#include "AliFemtoModelCorrFctnDirectYlm.h"
#include "AliFemtoModelCorrFctnSource.h"
#include "AliFemtoCutMonitorParticlePtPDG.h"
#include "AliFemtoKTPairCut.h"
#endif
//________________________________________________________________________
AliFemtoManager* ConfigFemtoAnalysis() {
double PionMass = 0.13956995;
double KaonMass = 0.493677;
AliFemtoEventReaderESDChainKine* Reader=new AliFemtoEventReaderESDChainKine();
Reader->SetConstrained(true);
Reader->SetUseTPCOnly(false);
AliFemtoManager* Manager=new AliFemtoManager();
Manager->SetEventReader(Reader);
// *** Begin pion-pion (positive) analysis ***
AliFemtoVertexMultAnalysis *anpip = new AliFemtoVertexMultAnalysis(3, -15.6, 15.6, 5, 2, 200000);
anpip->SetNumEventsToMix(10);
anpip->SetMinSizePartCollection(2);
AliFemtoBasicEventCut* mecpip = new AliFemtoBasicEventCut();
mecpip->SetEventMult(2,100000);
mecpip->SetVertZPos(-1000,1000);
AliFemtoESDTrackCut* dtcpip = new AliFemtoESDTrackCut();
dtcpip->SetPidProbPion(0.2,1.001);
dtcpip->SetPidProbMuon(0.0,1.0);
dtcpip->SetPidProbKaon(0.0,1.0);
dtcpip->SetPidProbProton(0.0,1.0);
dtcpip->SetCharge(1.0);
dtcpip->SetPt(0.15,0.5);
dtcpip->SetMass(PionMass);
// Track quality cuts
dtcpip->SetStatus(AliESDtrack::kTPCrefit|AliESDtrack::kITSrefit);
// dtcpip->SetStatus(AliESDtrack::kTPCrefit);
dtcpip->SetminTPCncls(50);
dtcpip->SetRemoveKinks(kTRUE);
dtcpip->SetLabel(kFALSE);
dtcpip->SetMaxITSChiNdof(2.5);
dtcpip->SetMaxTPCChiNdof(3.0);
dtcpip->SetMaxImpactXY(3.0);
dtcpip->SetMaxImpactZ(3.0);
AliFemtoCutMonitorParticleYPt *cutPassYPtpip = new AliFemtoCutMonitorParticleYPt("cutPasspip", 0.13957);
AliFemtoCutMonitorParticleYPt *cutFailYPtpip = new AliFemtoCutMonitorParticleYPt("cutFailpip", 0.13957);
dtcpip->AddCutMonitor(cutPassYPtpip, cutFailYPtpip);
AliFemtoCutMonitorEventMult *cutPassEvMpip = new AliFemtoCutMonitorEventMult("cutPasspip");
AliFemtoCutMonitorEventMult *cutFailEvMpip = new AliFemtoCutMonitorEventMult("cutFailpip");
mecpip->AddCutMonitor(cutPassEvMpip, cutFailEvMpip);
AliFemtoCutMonitorEventVertex *cutPassEvVpip = new AliFemtoCutMonitorEventVertex("cutPasspip");
AliFemtoCutMonitorEventVertex *cutFailEvVpip = new AliFemtoCutMonitorEventVertex("cutFailpip");
mecpip->AddCutMonitor(cutPassEvVpip, cutFailEvVpip);
AliFemtoShareQualityTPCEntranceSepPairCut *sqpcpip = new AliFemtoShareQualityTPCEntranceSepPairCut();
sqpcpip->SetShareQualityMax(0.0);
sqpcpip->SetShareFractionMax(0.02);
sqpcpip->SetRemoveSameLabel(kFALSE);
sqpcpip->SetTPCEntranceSepMinimum(2.0);
anpip->SetEventCut(mecpip);
anpip->SetFirstParticleCut(dtcpip);
anpip->SetSecondParticleCut(dtcpip);
anpip->SetPairCut(sqpcpip);
AliFemtoCorrFctn3DSpherical *cqsphpip = new AliFemtoCorrFctn3DSpherical("cqsphpip",60,0.0,0.3, 12, 12);
AliFemtoShareQualityCorrFctn *csqqinvpip= new AliFemtoShareQualityCorrFctn("sqqinvcfpip",40,0.0,0.4);
// Intrdouce kT binning
AliFemtoKTPairCut *ktpairkT1pip = new AliFemtoKTPairCut(0.1,0.27);
AliFemtoKTPairCut *ktpairkT2pip = new AliFemtoKTPairCut(0.27,0.37);
AliFemtoKTPairCut *ktpairkT3pip = new AliFemtoKTPairCut(0.37,0.52);
AliFemtoCorrFctnDirectYlm *cylmkT1pip = new AliFemtoCorrFctnDirectYlm("cylmkT1pip",3,60,0.0,0.3,1);
cylmkT1pip->SetPairSelectionCut(ktpairkT1pip);
anpip->AddCorrFctn(cylmkT1pip);
AliFemtoCorrFctnDirectYlm *cylmkT2pip = new AliFemtoCorrFctnDirectYlm("cylmkT2pip",3,60,0.0,0.3,1);
cylmkT2pip->SetPairSelectionCut(ktpairkT2pip);
anpip->AddCorrFctn(cylmkT2pip);
AliFemtoCorrFctnDirectYlm *cylmkT3pip = new AliFemtoCorrFctnDirectYlm("cylmkT3pip",3,60,0.0,0.3,1);
cylmkT3pip->SetPairSelectionCut(ktpairkT3pip);
anpip->AddCorrFctn(cylmkT3pip);
AliFemtoQinvCorrFctn *cqinvkt1pip = new AliFemtoQinvCorrFctn("qinvcfkt1pip", 100,0.0,1.0);
cqinvkt1pip->SetPairSelectionCut(ktpairkT1pip);
anpip->AddCorrFctn(cqinvkt1pip);
AliFemtoQinvCorrFctn *cqinvkt2pip = new AliFemtoQinvCorrFctn("qinvcfkt2pip", 100,0.0,1.0);
cqinvkt2pip->SetPairSelectionCut(ktpairkT2pip);
anpip->AddCorrFctn(cqinvkt2pip);
AliFemtoQinvCorrFctn *cqinvkt3pip = new AliFemtoQinvCorrFctn("qinvcfkt3pip", 100,0.0,1.0);
cqinvkt3pip->SetPairSelectionCut(ktpairkT3pip);
anpip->AddCorrFctn(cqinvkt3pip);
AliFemtoChi2CorrFctn *cchiqinvpip= new AliFemtoChi2CorrFctn("chicfpip",40,0.0,0.4);
AliFemtoCorrFctnTPCNcls *cqtpcnclspip = new AliFemtoCorrFctnTPCNcls("cqtpcnclspip",40,0.0,0.4);
AliFemtoModelBPLCMSCorrFctn *c3dsmallkt1pip;
AliFemtoModelBPLCMSCorrFctn *c3dsmallkt2pip;
AliFemtoModelBPLCMSCorrFctn *c3dsmallkt3pip;
AliFemtoModelCorrFctn *c1dpipip;
AliFemtoModelCorrFctn3DSpherical *c3dmsphpip;
// Setting up the model calculation
// First create the freeze-out generator
AliFemtoModelGausLCMSFreezeOutGenerator *tFreezepip = new AliFemtoModelGausLCMSFreezeOutGenerator();
tFreezepip->SetSizeOut(1.8*TMath::Sqrt(2.0));
tFreezepip->SetSizeSide(1.3*TMath::Sqrt(2.0));
tFreezepip->SetSizeLong(1.6*TMath::Sqrt(2.0));
// And the weight generator
AliFemtoModelWeightGeneratorBasic *tWeightpip = new AliFemtoModelWeightGeneratorBasic();
tWeightpip->SetPairType(AliFemtoModelWeightGenerator::PionPlusPionPlus());
// Create a manager that will connect it
AliFemtoModelManager *tModelManagerpip = new AliFemtoModelManager();
tModelManagerpip->AcceptFreezeOutGenerator(tFreezepip);
tModelManagerpip->AcceptWeightGenerator(tWeightpip);
tModelManagerpip->CreateCopyHiddenInfo(kFALSE);
c3dsmallkt1pip = new AliFemtoModelBPLCMSCorrFctn("c3dsmallkt2pip",30, 0.0, 0.3);
c3dsmallkt1pip->SetSpecificPairCut(ktpairkT2pip);
c3dsmallkt1pip->ConnectToManager(tModelManagerpip);
c3dsmallkt2pip = new AliFemtoModelBPLCMSCorrFctn("c3dsmallkt1pip",30, 0.0, 0.3);
c3dsmallkt2pip->SetSpecificPairCut(ktpairkT1pip);
c3dsmallkt2pip->ConnectToManager(tModelManagerpip);
c3dsmallkt3pip = new AliFemtoModelBPLCMSCorrFctn("c3dsmallkt3pip",30, 0.0, 0.3);
c3dsmallkt3pip->SetSpecificPairCut(ktpairkT3pip);
c3dsmallkt3pip->ConnectToManager(tModelManagerpip);
c1dpipip = new AliFemtoModelCorrFctn("c1dpipip",100,0.0,1.0);
c1dpipip->ConnectToManager(tModelManagerpip);
c3dmsphpip = new AliFemtoModelCorrFctn3DSpherical("c3dmsphpip",60, 0.0, 0.3, 12,12);
c3dmsphpip->ConnectToManager(tModelManagerpip);
AliFemtoModelCorrFctnDirectYlm *cmylmkt1pip = new AliFemtoModelCorrFctnDirectYlm("mcylmkt1pip",3,60,0.0,0.3,1);
cmylmkt1pip->SetPairSelectionCut(ktpairkT1pip);
cmylmkt1pip->ConnectToManager(tModelManagerpip);
anpip->AddCorrFctn(cmylmkt1pip);
AliFemtoModelCorrFctnDirectYlm *cmylmkt2pip = new AliFemtoModelCorrFctnDirectYlm("mcylmkt2pip",3,60,0.0,0.3,1);
cmylmkt2pip->SetPairSelectionCut(ktpairkT2pip);
cmylmkt2pip->ConnectToManager(tModelManagerpip);
anpip->AddCorrFctn(cmylmkt2pip);
AliFemtoModelCorrFctnDirectYlm *cmylmkt3pip = new AliFemtoModelCorrFctnDirectYlm("mcylmkt3pip",3,60,0.0,0.3,1);
cmylmkt3pip->SetPairSelectionCut(ktpairkT3pip);
cmylmkt3pip->ConnectToManager(tModelManagerpip);
anpip->AddCorrFctn(cmylmkt3pip);
//###
anpip->AddCorrFctn(cqsphpip);
anpip->AddCorrFctn(csqqinvpip);
anpip->AddCorrFctn(cchiqinvpip);
anpip->AddCorrFctn(cqtpcnclspip);
anpip->AddCorrFctn(c3dsmallkt1pip);
anpip->AddCorrFctn(c3dsmallkt2pip);
anpip->AddCorrFctn(c3dsmallkt3pip);
anpip->AddCorrFctn(c1dpipip);
anpip->AddCorrFctn(c3dmsphpip);
Manager->AddAnalysis(anpip);
// *** End pion-pion (positive) analysis
// *** Begin pion-pion (negative) analysis ***
AliFemtoVertexMultAnalysis *anpim = new AliFemtoVertexMultAnalysis(3, -15.6, 15.6, 5, 2, 200000);
anpim->SetNumEventsToMix(10);
anpim->SetMinSizePartCollection(2);
AliFemtoBasicEventCut* mecpim = new AliFemtoBasicEventCut();
mecpim->SetEventMult(2,100000);
mecpim->SetVertZPos(-1000,1000);
AliFemtoESDTrackCut* dtcpim = new AliFemtoESDTrackCut();
dtcpim->SetPidProbPion(0.2,1.001);
dtcpim->SetPidProbMuon(0.0,1.0);
dtcpim->SetPidProbKaon(0.0,1.0);
dtcpim->SetPidProbProton(0.0,1.0);
dtcpim->SetCharge(-1.0);
dtcpim->SetPt(0.15,0.5);
dtcpim->SetMass(PionMass);
// Track quality cuts
dtcpim->SetStatus(AliESDtrack::kTPCrefit|AliESDtrack::kITSrefit);
// dtcpim->SetStatus(AliESDtrack::kTPCrefit);
dtcpim->SetminTPCncls(50);
dtcpim->SetRemoveKinks(kTRUE);
dtcpim->SetLabel(kFALSE);
dtcpim->SetMaxITSChiNdof(2.5);
dtcpim->SetMaxTPCChiNdof(3.0);
dtcpim->SetMaxImpactXY(3.0);
dtcpim->SetMaxImpactZ(3.0);
AliFemtoCutMonitorParticleYPt *cutPassYPtpim = new AliFemtoCutMonitorParticleYPt("cutPasspim", 0.13957);
AliFemtoCutMonitorParticleYPt *cutFailYPtpim = new AliFemtoCutMonitorParticleYPt("cutFailpim", 0.13957);
dtcpim->AddCutMonitor(cutPassYPtpim, cutFailYPtpim);
AliFemtoCutMonitorEventMult *cutPassEvMpim = new AliFemtoCutMonitorEventMult("cutPasspim");
AliFemtoCutMonitorEventMult *cutFailEvMpim = new AliFemtoCutMonitorEventMult("cutFailpim");
mecpim->AddCutMonitor(cutPassEvMpim, cutFailEvMpim);
AliFemtoCutMonitorEventVertex *cutPassEvVpim = new AliFemtoCutMonitorEventVertex("cutPasspim");
AliFemtoCutMonitorEventVertex *cutFailEvVpim = new AliFemtoCutMonitorEventVertex("cutFailpim");
mecpim->AddCutMonitor(cutPassEvVpim, cutFailEvVpim);
AliFemtoShareQualityTPCEntranceSepPairCut *sqpcpim = new AliFemtoShareQualityTPCEntranceSepPairCut();
sqpcpim->SetShareQualityMax(0.0);
sqpcpim->SetShareFractionMax(0.02);
sqpcpim->SetRemoveSameLabel(kFALSE);
sqpcpim->SetTPCEntranceSepMinimum(2.0);
anpim->SetEventCut(mecpim);
anpim->SetFirstParticleCut(dtcpim);
anpim->SetSecondParticleCut(dtcpim);
anpim->SetPairCut(sqpcpim);
AliFemtoCorrFctn3DSpherical *cqsphpim = new AliFemtoCorrFctn3DSpherical("cqsphpim",60,0.0,0.3, 12, 12);
AliFemtoShareQualityCorrFctn *csqqinvpim= new AliFemtoShareQualityCorrFctn("sqqinvcfpim",40,0.0,0.4);
// Intrdouce kT binning
AliFemtoKTPairCut *ktpairkT1pim = new AliFemtoKTPairCut(0.1,0.27);
AliFemtoKTPairCut *ktpairkT2pim = new AliFemtoKTPairCut(0.27,0.37);
AliFemtoKTPairCut *ktpairkT3pim = new AliFemtoKTPairCut(0.37,0.52);
AliFemtoCorrFctnDirectYlm *cylmkT1pim = new AliFemtoCorrFctnDirectYlm("cylmkT1pim",3,60,0.0,0.3,1);
cylmkT1pim->SetPairSelectionCut(ktpairkT1pim);
anpim->AddCorrFctn(cylmkT1pim);
AliFemtoCorrFctnDirectYlm *cylmkT2pim = new AliFemtoCorrFctnDirectYlm("cylmkT2pim",3,60,0.0,0.3,1);
cylmkT2pim->SetPairSelectionCut(ktpairkT2pim);
anpim->AddCorrFctn(cylmkT2pim);
AliFemtoCorrFctnDirectYlm *cylmkT3pim = new AliFemtoCorrFctnDirectYlm("cylmkT3pim",3,60,0.0,0.3,1);
cylmkT3pim->SetPairSelectionCut(ktpairkT3pim);
anpim->AddCorrFctn(cylmkT3pim);
AliFemtoQinvCorrFctn *cqinvkt1pim = new AliFemtoQinvCorrFctn("qinvcfkt1pim", 100,0.0,1.0);
cqinvkt1pim->SetPairSelectionCut(ktpairkT1pim);
anpim->AddCorrFctn(cqinvkt1pim);
AliFemtoQinvCorrFctn *cqinvkt2pim = new AliFemtoQinvCorrFctn("qinvcfkt2pim", 100,0.0,1.0);
cqinvkt2pim->SetPairSelectionCut(ktpairkT2pim);
anpim->AddCorrFctn(cqinvkt2pim);
AliFemtoQinvCorrFctn *cqinvkt3pim = new AliFemtoQinvCorrFctn("qinvcfkt3pim", 100,0.0,1.0);
cqinvkt3pim->SetPairSelectionCut(ktpairkT3pim);
anpim->AddCorrFctn(cqinvkt3pim);
AliFemtoChi2CorrFctn *cchiqinvpim= new AliFemtoChi2CorrFctn("chicfpim",40,0.0,0.4);
AliFemtoCorrFctnTPCNcls *cqtpcnclspim = new AliFemtoCorrFctnTPCNcls("cqtpcnclspim",40,0.0,0.4);
AliFemtoModelBPLCMSCorrFctn *c3dsmallkt1pim;
AliFemtoModelBPLCMSCorrFctn *c3dsmallkt2pim;
AliFemtoModelBPLCMSCorrFctn *c3dsmallkt3pim;
AliFemtoModelCorrFctn *c1dpimip;
AliFemtoModelCorrFctn3DSpherical *c3dmsphpim;
// Setting up the model calculation
// First create the freeze-out generator
AliFemtoModelGausLCMSFreezeOutGenerator *tFreezepim = new AliFemtoModelGausLCMSFreezeOutGenerator();
tFreezepim->SetSizeOut(1.8*TMath::Sqrt(2.0));
tFreezepim->SetSizeSide(1.3*TMath::Sqrt(2.0));
tFreezepim->SetSizeLong(1.6*TMath::Sqrt(2.0));
// And the weight generator
AliFemtoModelWeightGeneratorBasic *tWeightpim = new AliFemtoModelWeightGeneratorBasic();
tWeightpim->SetPairType(AliFemtoModelWeightGenerator::PionPlusPionPlus());
// Create a manager that will connect it
AliFemtoModelManager *tModelManagerpim = new AliFemtoModelManager();
tModelManagerpim->AcceptFreezeOutGenerator(tFreezepim);
tModelManagerpim->AcceptWeightGenerator(tWeightpim);
tModelManagerpim->CreateCopyHiddenInfo(kFALSE);
c3dsmallkt1pim = new AliFemtoModelBPLCMSCorrFctn("c3dsmallkt2pim",30, 0.0, 0.3);
c3dsmallkt1pim->SetSpecificPairCut(ktpairkT2pim);
c3dsmallkt1pim->ConnectToManager(tModelManagerpim);
c3dsmallkt2pim = new AliFemtoModelBPLCMSCorrFctn("c3dsmallkt1pim",30, 0.0, 0.3);
c3dsmallkt2pim->SetSpecificPairCut(ktpairkT1pim);
c3dsmallkt2pim->ConnectToManager(tModelManagerpim);
c3dsmallkt3pim = new AliFemtoModelBPLCMSCorrFctn("c3dsmallkt3pim",30, 0.0, 0.3);
c3dsmallkt3pim->SetSpecificPairCut(ktpairkT3pim);
c3dsmallkt3pim->ConnectToManager(tModelManagerpim);
c1dpimip = new AliFemtoModelCorrFctn("c1dpimip",100,0.0,1.0);
c1dpimip->ConnectToManager(tModelManagerpim);
c3dmsphpim = new AliFemtoModelCorrFctn3DSpherical("c3dmsphpim",60, 0.0, 0.3, 12,12);
c3dmsphpim->ConnectToManager(tModelManagerpim);
AliFemtoModelCorrFctnDirectYlm *cmylmkt1pim = new AliFemtoModelCorrFctnDirectYlm("mcylmkt1pim",3,60,0.0,0.3,1);
cmylmkt1pim->SetPairSelectionCut(ktpairkT1pim);
cmylmkt1pim->ConnectToManager(tModelManagerpim);
anpim->AddCorrFctn(cmylmkt1pim);
AliFemtoModelCorrFctnDirectYlm *cmylmkt2pim = new AliFemtoModelCorrFctnDirectYlm("mcylmkt2pim",3,60,0.0,0.3,1);
cmylmkt2pim->SetPairSelectionCut(ktpairkT2pim);
cmylmkt2pim->ConnectToManager(tModelManagerpim);
anpim->AddCorrFctn(cmylmkt2pim);
AliFemtoModelCorrFctnDirectYlm *cmylmkt3pim = new AliFemtoModelCorrFctnDirectYlm("mcylmkt3pim",3,60,0.0,0.3,1);
cmylmkt3pim->SetPairSelectionCut(ktpairkT3pim);
cmylmkt3pim->ConnectToManager(tModelManagerpim);
anpim->AddCorrFctn(cmylmkt3pim);
//###
anpim->AddCorrFctn(cqsphpim);
anpim->AddCorrFctn(csqqinvpim);
anpim->AddCorrFctn(cchiqinvpim);
anpim->AddCorrFctn(cqtpcnclspim);
anpim->AddCorrFctn(c3dsmallkt1pim);
anpim->AddCorrFctn(c3dsmallkt2pim);
anpim->AddCorrFctn(c3dsmallkt3pim);
anpim->AddCorrFctn(c1dpimip);
anpim->AddCorrFctn(c3dmsphpim);
Manager->AddAnalysis(anpim);
// *** End pion-pion (negative) analysis
// *** Begin Kaon-Kaon (positive) analysis
AliFemtoVertexMultAnalysis *ankp = new AliFemtoVertexMultAnalysis(18, -15.6, 15.6, 1, 2, 20000);
ankp->SetNumEventsToMix(5);
ankp->SetMinSizePartCollection(2);
AliFemtoBasicEventCut* meckp = new AliFemtoBasicEventCut();
meckp->SetEventMult(1,100000);
meckp->SetVertZPos(-1000,1000);
AliFemtoESDTrackCut* dtckp = new AliFemtoESDTrackCut();
dtckp->SetPidProbKaon(0.7,1.001);
dtckp->SetPidProbMuon(0.0,0.5);
dtckp->SetPidProbPion(0.0,0.5);
dtckp->SetPidProbProton(0.0,0.5);
dtckp->SetCharge(1.0);
dtckp->SetMostProbableKaon();
dtckp->SetPt(0.15,2.0);
dtckp->SetMass(KaonMass);
// Track quality cuts
dtckp->SetStatus(AliESDtrack::kTPCrefit|AliESDtrack::kITSrefit);
//dtckp->SetStatus(AliESDtrack::kTPCrefit);
// dtckp->SetminTPCclsF(95);
dtckp->SetminTPCncls(50);
dtckp->SetRemoveKinks(kTRUE);
dtckp->SetLabel(kFALSE);
dtckp->SetMaxITSChiNdof(2.5);
dtckp->SetMaxTPCChiNdof(3.0);
// dtckp->SetMaxSigmaToVertex(3.0);
dtckp->SetMaxImpactXY(3.0);
dtckp->SetMaxImpactZ(3.0);
AliFemtoCutMonitorParticleYPt *cutPassYPtkp = new AliFemtoCutMonitorParticleYPt("cutPasskp", 0.493677);
AliFemtoCutMonitorParticleYPt *cutFailYPtkp = new AliFemtoCutMonitorParticleYPt("cutFailkp", 0.493677);
dtckp->AddCutMonitor(cutPassYPtkp, cutFailYPtkp);
AliFemtoCutMonitorParticlePtPDG *cutPassPidkp = new AliFemtoCutMonitorParticlePtPDG("cutPasskp", 0.493677);
AliFemtoCutMonitorParticlePtPDG *cutFailPidkp = new AliFemtoCutMonitorParticlePtPDG("cutFailkp", 0.493677);
dtckp->AddCutMonitor(cutPassPidkp, cutFailPidkp);
AliFemtoCutMonitorParticleMomRes *cutPassMRkp = new AliFemtoCutMonitorParticleMomRes("cutPasskp");
AliFemtoCutMonitorParticleMomRes *cutFailMRkp = new AliFemtoCutMonitorParticleMomRes("cutFailkp");
dtckp->AddCutMonitor(cutPassMRkp, cutFailMRkp);
AliFemtoCutMonitorParticleVertPos *cutPassVPkp = new AliFemtoCutMonitorParticleVertPos("cutPasskp");
AliFemtoCutMonitorParticleVertPos *cutFailVPkp = new AliFemtoCutMonitorParticleVertPos("cutFailkp");
dtckp->AddCutMonitor(cutPassVPkp, cutFailVPkp);
AliFemtoCutMonitorEventMult *cutPassEvMkp = new AliFemtoCutMonitorEventMult("cutPasskp");
AliFemtoCutMonitorEventMult *cutFailEvMkp = new AliFemtoCutMonitorEventMult("cutFailkp");
meckp->AddCutMonitor(cutPassEvMkp, cutFailEvMkp);
AliFemtoCutMonitorEventVertex *cutPassEvVkp = new AliFemtoCutMonitorEventVertex("cutPasskp");
AliFemtoCutMonitorEventVertex *cutFailEvVkp = new AliFemtoCutMonitorEventVertex("cutFailkp");
meckp->AddCutMonitor(cutPassEvVkp, cutFailEvVkp);
AliFemtoShareQualityTPCEntranceSepPairCut *sqpckp = new AliFemtoShareQualityTPCEntranceSepPairCut();
sqpckp->SetShareQualityMax(0.0);
sqpckp->SetShareFractionMax(0.02);
sqpckp->SetRemoveSameLabel(kFALSE);
sqpckp->SetTPCEntranceSepMinimum(3.0);
ankp->SetEventCut(meckp);
ankp->SetFirstParticleCut(dtckp);
ankp->SetSecondParticleCut(dtckp);
ankp->SetPairCut(sqpckp);
AliFemtoQinvCorrFctn *cqinvkp= new AliFemtoQinvCorrFctn("qinvcf",100,0.0,1.0);
AliFemtoModelBPLCMSCorrFctn *c3dsmallkp;
AliFemtoModelCorrFctn *c1dpikp;
// Setting up the model calculation
// First create the freeze-out generator
AliFemtoModelGausRinvFreezeOutGenerator *tFreezekp = new AliFemtoModelGausRinvFreezeOutGenerator();
tFreezekp->SetSizeInv(1.8*TMath::Sqrt(2.0));
tFreezekp->SetSelectPrimaryFromHidden(false);
// And the weight generator
AliFemtoModelWeightGeneratorBasic *tWeightkp = new AliFemtoModelWeightGeneratorBasic();
tWeightkp->SetPairType(AliFemtoModelWeightGenerator::KaonPlusKaonPlus());
// Create a manager that will connect it
AliFemtoModelManager *tModelManagerkp = new AliFemtoModelManager();
tModelManagerkp->AcceptFreezeOutGenerator(tFreezekp);
tModelManagerkp->AcceptWeightGenerator(tWeightkp);
tModelManagerkp->CreateCopyHiddenInfo(kFALSE);
c3dsmallkp = new AliFemtoModelBPLCMSCorrFctn("c3dsmallkp",30, 0.0, 0.6);
c3dsmallkp->ConnectToManager(tModelManagerkp);
c1dpikp = new AliFemtoModelCorrFctn("c1dpikp",100,0.0,1.0);
c1dpikp->ConnectToManager(tModelManagerkp);
//###
ankp->AddCorrFctn(cqinvkp);
ankp->AddCorrFctn(c3dsmallkp);
ankp->AddCorrFctn(c1dpikp);
Manager->AddAnalysis(ankp);
// *** End Kaon-Kaon (positive) analysis
return Manager;
}
|
b91f1dcf1e35db36006a1ed6fb656bc369ca0628
|
94b153fe49c2e7bd901c4f26d3cc4134920b4ccf
|
/docs/examples/c/session_buffer_test/session_buffer_test.c
|
19c4244ba544f0f4668e3225257596855d55f49a
|
[
"LicenseRef-scancode-proprietary-license",
"Apache-2.0"
] |
permissive
|
cossacklabs/themis
|
d6d39836fcebe88d228d25a670a35c556b6a117d
|
86096502c48a80edb11f567c92e26eb463eae36c
|
refs/heads/master
| 2023-08-17T03:48:03.760843
| 2023-07-10T19:57:46
| 2023-07-10T19:57:46
| 35,159,920
| 1,831
| 168
|
Apache-2.0
| 2023-09-14T04:05:12
| 2015-05-06T13:25:25
|
C
|
UTF-8
|
C
| false
| false
| 3,421
|
c
|
session_buffer_test.c
|
#include "session_buffer_test.h"
typedef struct callback_key_type {
uint8_t *key;
size_t key_length;
} callback_key_t;
static int
on_get_pub_key(const void *id, size_t id_length, void *key_buffer, size_t key_buffer_length, void *user_data) {
callback_key_t *cb = (callback_key_t *) user_data;
memcpy(key_buffer, cb->key, cb->key_length);
return THEMIS_SUCCESS;
}
callback_key_t client_callback_data = {server_pub, sizeof(server_pub)};
callback_key_t server_callback_data = {client_pub, sizeof(client_pub)};
int main(int argc, char *argv[]) {
secure_session_user_callbacks_t client_callback = {NULL, NULL, NULL, on_get_pub_key, &client_callback_data};
secure_session_user_callbacks_t server_callback = {NULL, NULL, NULL, on_get_pub_key, &server_callback_data};
secure_session_t *server_session = secure_session_create(SERVER_ID, strlen(SERVER_ID), server_priv,
sizeof(server_priv), &server_callback);
secure_session_t *client_session = secure_session_create(CLIENT_ID, strlen(CLIENT_ID), client_priv,
sizeof(client_priv), &client_callback);
uint8_t client_buf[2048];
size_t client_buf_length = sizeof(client_buf);
uint8_t server_buf[2048];
size_t server_buf_length = sizeof(server_buf);
if (secure_session_generate_connect_request(client_session, client_buf, &client_buf_length) != THEMIS_SUCCESS) {
fprintf(stdout, "connection request error\n");
return 1;
};
themis_status_t status;
while (!secure_session_is_established(client_session) && !secure_session_is_established(server_session)) {
if (!secure_session_is_established(server_session)) {
status = secure_session_unwrap(server_session, client_buf, client_buf_length, server_buf, &server_buf_length);
if (!(status == THEMIS_SSESSION_SEND_OUTPUT_TO_PEER || status == THEMIS_SUCCESS)) {
fprintf(stdout, "server unwrap error\n");
return 1;
}
}
if (!secure_session_is_established(client_session)) {
status = secure_session_unwrap(client_session, server_buf, server_buf_length, client_buf,
&client_buf_length);
if (!(status == THEMIS_SSESSION_SEND_OUTPUT_TO_PEER || status == THEMIS_SUCCESS)) {
fprintf(stdout, "client unwrap error\n");
return 1;
}
}
}
fprintf(stdout, "session established\n");
char message[10];
size_t message_size;
for (int i = 0; i < 10; i++) {
client_buf_length = sizeof(client_buf);
server_buf_length = sizeof(server_buf);
message_size = (size_t)sprintf((char*)message, "%d", i);
if(secure_session_wrap(client_session, message, message_size, client_buf, &client_buf_length) != THEMIS_SUCCESS){
fprintf(stdout, "client wrap error\n");
return 1;
};
if(secure_session_unwrap(server_session, client_buf, client_buf_length, server_buf, &server_buf_length) != THEMIS_SUCCESS){
fprintf(stdout, "client wrap error\n");
return 1;
};
if(memcmp(server_buf, message, message_size) != 0){
fprintf(stdout, "incorrect decrypted message\n");
};
}
fprintf(stdout, "finished\n");
}
|
1c712134a79003e466e46c073797fc5735426d53
|
10a8580aa44d33b7458429023c00de8c01ceda98
|
/axiom/tests/test_configstrings.c
|
3958748adc56b751eb6a7bd195509c405264c16d
|
[
"BSD-4-Clause-UC",
"Apache-2.0"
] |
permissive
|
newrelic/newrelic-php-agent
|
87ad20e0a5abf0d2855e7d27a25c36454ae4389a
|
dfb359f0dbb53e4cbc5106b52c8f3807c7fc8d42
|
refs/heads/main
| 2023-08-15T10:28:24.372352
| 2023-08-14T17:29:31
| 2023-08-14T17:29:31
| 302,112,572
| 116
| 67
|
Apache-2.0
| 2023-09-13T18:33:47
| 2020-10-07T17:35:01
|
C
|
UTF-8
|
C
| false
| false
| 3,360
|
c
|
test_configstrings.c
|
/*
* Copyright 2020 New Relic Corporation. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#include "nr_axiom.h"
#include "nr_configstrings.h"
#include "tlib_main.h"
static void test_nr_parse_time(void) {
int i;
nrtime_t t;
struct {
const char* testname;
const char* input;
nrtime_t expect;
} testcases[] = {
{"null string", NULL, 0},
{"empty string", "", 0},
{"bogus time string", "a", 0},
{"h string", "h", 0},
{"1msec", "1", 1000},
{"2msec", "2", 2000},
{"space 1msec", " 1", 1000},
{"space 1msec", " 1 ", 1000},
{"space 1msec", " 1\t", 1000},
{"space 1msec", "\t\t1", 1000},
{"1msec with ms suffix", "1ms", 1000},
/* Numbers with franctional components aren't allowed, and return 0. */
{"1msec with fraction", "1000.999", 0},
{"0", "0", 0},
{"0d", "0d", 0},
/*
* Now test the various suffixes, both cases.
*/
{"1w", "1w", 1ULL * 7ULL * 86400 * 1000 * 1000},
{"1d", "1d", 1ULL * 86400 * 1000 * 1000},
{"1h", "1h", 1ULL * 3600 * 1000 * 1000},
{"1m", "1m", 1ULL * 60 * 1000 * 1000},
{"1s", "1s", 1ULL * 1000 * 1000},
{"1ms", "1ms", 1ULL * 1000},
{"1us", "1us", 1ULL * 1},
{"1W", "1W", 1ULL * 7ULL * 86400 * 1000 * 1000},
{"1D", "1D", 1ULL * 86400 * 1000 * 1000},
{"1H", "1H", 1ULL * 3600 * 1000 * 1000},
{"1M", "1M", 1ULL * 60 * 1000 * 1000},
{"1S", "1S", 1ULL * 1000 * 1000},
{"1MS", "1MS", 1ULL * 1000},
{"1US", "1US", 1ULL * 1},
};
int num_testcases = sizeof(testcases) / sizeof(testcases[0]);
t = nr_parse_time("-1000"); /* dangerous! */
tlib_pass_if_true("1msec", 1000 * -1000LL == (int64_t)t, "t=" NR_TIME_FMT, t);
for (i = 0; i < num_testcases; i++) {
t = nr_parse_time(testcases[i].input);
tlib_pass_if_true(testcases[i].testname, t == testcases[i].expect,
"t=" NR_TIME_FMT " expect=" NR_TIME_FMT " input=%s", t,
testcases[i].expect, NRSAFESTR(testcases[i].input));
}
}
static void test_nr_bool_from_str(void) {
int x;
int i;
struct {
const char* input;
int expect;
} testcases[] = {
{NULL, 0},
{"", 0},
{"0", 0},
{"false", 0},
{"f", 0},
{"FalSe", 0},
{"n", 0},
{"no", 0},
{"No", 0},
{"Off", 0},
{"DisABLE", 0},
{"Disabled", 0},
{"true", 1},
{"1", 1},
{"t", 1},
{"TruE", 1},
{"y", 1},
{"yes", 1},
{"Yes", 1},
{"On", 1},
{"Enabled", 1},
{"ENABLE", 1},
/* Error cases. */
{"7", -1},
{" On", -1}, /* alas, we don't ignore spaces */
{"On ", -1}, /* alas, we don't ignore spaces */
{"Off7", -1},
{"On7", -1},
};
int num_testcases = sizeof(testcases) / sizeof(testcases[0]);
for (i = 0; i < num_testcases; i++) {
x = nr_bool_from_str(testcases[i].input);
tlib_pass_if_true(testcases[i].input ? testcases[i].input : "NULL",
x == testcases[i].expect, "x=%d expect=%d input=%s", x,
testcases[i].expect, NRSAFESTR(testcases[i].input));
}
}
tlib_parallel_info_t parallel_info = {.suggested_nthreads = 2, .state_size = 0};
void test_main(void* p NRUNUSED) {
test_nr_parse_time();
test_nr_bool_from_str();
}
|
c353cba2227988aefc70d5c94d5af6e7401a3a0d
|
39568e19301a7a112398be542154950af25591de
|
/sw/device/lib/crypto/drivers/entropy.c
|
862b2cfe99c4cd708e7dd0eb9c7f942b4604695c
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
lowRISC/opentitan
|
493995bc7cf7cb3aee486a5203af3fd62bba3bfc
|
51f6017b8425b14d5a4aa9abace8fe5a25ef08c8
|
refs/heads/master
| 2023-08-31T22:05:09.425796
| 2023-08-14T14:52:15
| 2023-08-31T20:31:13
| 204,516,692
| 2,077
| 634
|
Apache-2.0
| 2023-09-14T21:16:21
| 2019-08-26T16:30:16
|
SystemVerilog
|
UTF-8
|
C
| false
| false
| 32,932
|
c
|
entropy.c
|
// Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
#include "sw/device/lib/crypto/drivers/entropy.h"
#include "sw/device/lib/base/abs_mmio.h"
#include "sw/device/lib/base/bitfield.h"
#include "sw/device/lib/base/memory.h"
#include "sw/device/lib/base/multibits.h"
#include "sw/device/lib/crypto/impl/status.h"
#include "csrng_regs.h" // Generated
#include "edn_regs.h" // Generated
#include "entropy_src_regs.h" // Generated
#include "hw/top_earlgrey/sw/autogen/top_earlgrey.h"
// Module ID for status codes.
#define MODULE_ID MAKE_MODULE_ID('d', 'e', 'n')
enum {
kBaseCsrng = TOP_EARLGREY_CSRNG_BASE_ADDR,
kBaseEntropySrc = TOP_EARLGREY_ENTROPY_SRC_BASE_ADDR,
kBaseEdn0 = TOP_EARLGREY_EDN0_BASE_ADDR,
kBaseEdn1 = TOP_EARLGREY_EDN1_BASE_ADDR,
/**
* CSRNG genbits buffer size in uint32_t words.
*/
kEntropyCsrngBitsBufferNumWords = 4,
};
/**
* Supported CSRNG application commands.
* See https://docs.opentitan.org/hw/ip/csrng/doc/#command-header for
* details.
*/
// TODO(#14542): Harden csrng/edn command fields.
typedef enum entropy_csrng_op {
kEntropyDrbgOpInstantiate = 1,
kEntropyDrbgOpReseed = 2,
kEntropyDrbgOpGenerate = 3,
kEntropyDrbgOpUpdate = 4,
kEntropyDrbgOpUninstantiate = 5,
} entropy_csrng_op_t;
/**
* CSRNG application interface command header parameters.
*/
typedef struct entropy_csrng_cmd {
/**
* Application command ID.
*/
entropy_csrng_op_t id;
/**
* Entropy source enable.
*
* Mapped to flag0 in the hardware command interface.
*/
hardened_bool_t disable_trng_input;
const entropy_seed_material_t *seed_material;
/**
* Generate length. Specified as number of 128bit blocks.
*/
uint32_t generate_len;
} entropy_csrng_cmd_t;
/**
* Entropy complex configuration modes.
*
* Each enum value is used a confiugration index in `kEntropyComplexConfigs`.
*/
typedef enum entropy_complex_config_id {
/**
* Entropy complex in continuous mode. This is the default runtime
* configuration.
*/
kEntropyComplexConfigIdContinuous,
kEntropyComplexConfigIdNumEntries,
} entropy_complex_config_id_t;
/**
* EDN configuration settings.
*/
typedef struct edn_config {
/**
* Base address of the EDN block.
*/
uint32_t base_address;
/**
* Number of generate calls between reseed commands.
*/
uint32_t reseed_interval;
/**
* Downstream CSRNG instantiate command configuration.
*/
entropy_csrng_cmd_t instantiate;
/**
* Downstream CSRNG generate command configuration.
*/
entropy_csrng_cmd_t generate;
/**
* Downstream CSRNG reseed command configuration.
*/
entropy_csrng_cmd_t reseed;
} edn_config_t;
/**
* Entropy source configuration settings.
*/
typedef struct entropy_src_config {
/**
* If set, FIPS compliant entropy will be generated by this module after being
* processed by an SP 800-90B compliant conditioning function.
*/
multi_bit_bool_t fips_enable;
/**
* If set, entropy will be routed to a firmware-visible register instead of
* being distributed to other hardware IPs.
*/
multi_bit_bool_t route_to_firmware;
/**
* If set, raw entropy will be sent to CSRNG, bypassing the conditioner block
* and disabling the FIPS hardware generated flag.
*/
multi_bit_bool_t bypass_conditioner;
/**
* Enables single bit entropy mode.
*/
multi_bit_bool_t single_bit_mode;
/**
* The size of the window used for health tests.
*/
uint16_t fips_test_window_size;
/**
* The number of health test failures that must occur before an alert is
* triggered. When set to 0, alerts are disabled.
*/
uint16_t alert_threshold;
/**
* Repetition count test threshold.
*/
uint16_t repcnt_threshold;
/**
* Repetition count symbol test threshold.
*/
uint16_t repcnts_threshold;
/**
* Adaptive proportion test high threshold.
*/
uint16_t adaptp_hi_threshold;
/**
* Adaptive proportion test low threshold.
*/
uint16_t adaptp_lo_threshold;
/**
* Bucket test threshold.
*/
uint16_t bucket_threshold;
/**
* Markov test high threshold.
*/
uint16_t markov_hi_threshold;
/**
* Markov test low threshold.
*/
uint16_t markov_lo_threshold;
/**
* External health test high threshold.
*/
uint16_t extht_hi_threshold;
/**
* External health test low threshold.
*/
uint16_t extht_lo_threshold;
} entropy_src_config_t;
/**
* Entropy complex configuration settings.
*
* Contains configuration paramenters for entropy_src, csrng, edn0 and edn1.
*/
typedef struct entropy_complex_config {
/**
* Configuration identifier.
*/
entropy_complex_config_id_t id;
/**
* ENTROPY_SRC configuration.
*/
entropy_src_config_t entropy_src;
/**
* EDN0 configuration.
*/
edn_config_t edn0;
/**
* EDN1 configuration.
*/
edn_config_t edn1;
} entropy_complex_config_t;
// Entropy complex configuration table. This is expected to be fixed at build
// time. For this reason, it is not recommended to use this table in a ROM
// target unless the values are known to work. In other words, only use in
// mutable code partitions.
static const entropy_complex_config_t
kEntropyComplexConfigs[kEntropyComplexConfigIdNumEntries] = {
[kEntropyComplexConfigIdContinuous] =
{
.entropy_src =
{
.fips_enable = kMultiBitBool4True,
.route_to_firmware = kMultiBitBool4False,
.bypass_conditioner = kMultiBitBool4False,
.single_bit_mode = kMultiBitBool4False,
.fips_test_window_size = 0x200,
.alert_threshold = 2,
// TODO(#19392): Figure out appropriate thresholds.
.repcnt_threshold = 0xffff,
.repcnts_threshold = 0xffff,
.adaptp_hi_threshold = 0xffff,
.adaptp_lo_threshold = 0x0,
.bucket_threshold = 0xffff,
.markov_hi_threshold = 0xffff,
.markov_lo_threshold = 0x0,
.extht_hi_threshold = 0xffff,
.extht_lo_threshold = 0x0,
},
.edn0 =
{
.base_address = kBaseEdn0,
.reseed_interval = 32,
.instantiate =
{
.id = kEntropyDrbgOpInstantiate,
.disable_trng_input = kHardenedBoolFalse,
.seed_material = NULL,
.generate_len = 0,
},
.generate =
{
.id = kEntropyDrbgOpGenerate,
.disable_trng_input = kHardenedBoolFalse,
.seed_material = NULL,
.generate_len = 8,
},
.reseed =
{
.id = kEntropyDrbgOpReseed,
.disable_trng_input = kHardenedBoolFalse,
.seed_material = NULL,
.generate_len = 0,
},
},
.edn1 =
{
.base_address = kBaseEdn1,
.reseed_interval = 4,
.instantiate =
{
.id = kEntropyDrbgOpInstantiate,
.disable_trng_input = kHardenedBoolFalse,
.seed_material = NULL,
.generate_len = 0,
},
.generate =
{
.id = kEntropyDrbgOpGenerate,
.seed_material = NULL,
.generate_len = 1,
},
.reseed =
{
.id = kEntropyDrbgOpReseed,
.disable_trng_input = kHardenedBoolFalse,
.seed_material = NULL,
.generate_len = 0,
},
},
},
};
// Write a CSRNG command to a register. That register can be the SW interface
// of CSRNG, in which case the `check_completion` argument should be `true`.
// That register can alternatively be one of EDN's that holds commands that EDN
// passes to CSRNG, in which case the `check_completion` argument must be
// `false`.
OT_WARN_UNUSED_RESULT
static status_t csrng_send_app_cmd(uint32_t reg_address,
entropy_csrng_cmd_t cmd,
bool check_completion) {
enum {
// This is to maintain full compliance with NIST SP 800-90A, which requires
// the max generate output to be constrained to gen < 2 ^ 12 bits or 0x800
// 128-bit blocks.
kMaxGenerateSizeIn128BitBlocks = 0x800,
};
if (cmd.generate_len > kMaxGenerateSizeIn128BitBlocks) {
return OUT_OF_RANGE();
}
uint32_t reg;
bool cmd_ready;
do {
reg = abs_mmio_read32(kBaseCsrng + CSRNG_SW_CMD_STS_REG_OFFSET);
cmd_ready = bitfield_bit32_read(reg, CSRNG_SW_CMD_STS_CMD_RDY_BIT);
} while (!cmd_ready);
#define ENTROPY_CMD(m, i) ((bitfield_field32_t){.mask = m, .index = i})
// The application command header is not specified as a register in the
// hardware specification, so the fields are mapped here by hand. The
// command register also accepts arbitrary 32bit data.
static const bitfield_field32_t kAppCmdFieldFlag0 = ENTROPY_CMD(0xf, 8);
static const bitfield_field32_t kAppCmdFieldCmdId = ENTROPY_CMD(0xf, 0);
static const bitfield_field32_t kAppCmdFieldCmdLen = ENTROPY_CMD(0xf, 4);
static const bitfield_field32_t kAppCmdFieldGlen = ENTROPY_CMD(0x7ffff, 12);
#undef ENTROPY_CMD
uint32_t cmd_len = cmd.seed_material == NULL ? 0 : cmd.seed_material->len;
if (cmd_len & ~kAppCmdFieldCmdLen.mask) {
return OTCRYPTO_RECOV_ERR;
}
// TODO: Consider removing this since the driver will be constructing these
// commands internally.
// Ensure the `seed_material` array is word-aligned, so it can be loaded to a
// CPU register with natively aligned loads.
if (cmd.seed_material != NULL &&
misalignment32_of((uintptr_t)cmd.seed_material->data) != 0) {
return OTCRYPTO_RECOV_ERR;
}
if (check_completion) {
// Clear the `cs_cmd_req_done` bit, which is asserted whenever a command
// request is completed, because that bit will be used below to determine if
// this command request is completed.
reg = bitfield_bit32_write(0, CSRNG_INTR_STATE_CS_CMD_REQ_DONE_BIT, true);
abs_mmio_write32(kBaseCsrng + CSRNG_INTR_STATE_REG_OFFSET, reg);
}
// Build and write application command header.
reg = bitfield_field32_write(0, kAppCmdFieldCmdId, cmd.id);
reg = bitfield_field32_write(reg, kAppCmdFieldCmdLen, cmd_len);
reg = bitfield_field32_write(reg, kAppCmdFieldGlen, cmd.generate_len);
if (launder32(cmd.disable_trng_input) == kHardenedBoolTrue) {
reg = bitfield_field32_write(reg, kAppCmdFieldFlag0, kMultiBitBool4True);
}
abs_mmio_write32(reg_address, reg);
for (size_t i = 0; i < cmd_len; ++i) {
abs_mmio_write32(reg_address, cmd.seed_material->data[i]);
}
if (check_completion) {
if (cmd.id == kEntropyDrbgOpGenerate) {
// The Generate command is complete only after all entropy bits have been
// consumed. Thus poll the register that indicates if entropy bits are
// available.
do {
reg = abs_mmio_read32(kBaseCsrng + CSRNG_GENBITS_VLD_REG_OFFSET);
} while (!bitfield_bit32_read(reg, CSRNG_GENBITS_VLD_GENBITS_VLD_BIT));
} else {
// The non-Generate commands complete earlier, so poll the "command
// request done" interrupt bit. Once it is set, the "status" bit is
// updated.
do {
reg = abs_mmio_read32(kBaseCsrng + CSRNG_INTR_STATE_REG_OFFSET);
} while (!bitfield_bit32_read(reg, CSRNG_INTR_STATE_CS_CMD_REQ_DONE_BIT));
// Check the "status" bit, which will be 1 only if there was an error.
reg = abs_mmio_read32(kBaseCsrng + CSRNG_SW_CMD_STS_REG_OFFSET);
if (bitfield_bit32_read(reg, CSRNG_SW_CMD_STS_CMD_STS_BIT)) {
return OTCRYPTO_RECOV_ERR;
}
}
}
return OTCRYPTO_OK;
}
/**
* Enables the CSRNG block with the SW application and internal state registers
* enabled.
*/
static void csrng_configure(void) {
uint32_t reg =
bitfield_field32_write(0, CSRNG_CTRL_ENABLE_FIELD, kMultiBitBool4True);
reg = bitfield_field32_write(reg, CSRNG_CTRL_SW_APP_ENABLE_FIELD,
kMultiBitBool4True);
reg = bitfield_field32_write(reg, CSRNG_CTRL_READ_INT_STATE_FIELD,
kMultiBitBool4True);
abs_mmio_write32(kBaseCsrng + CSRNG_CTRL_REG_OFFSET, reg);
}
/**
* Stops a given EDN instance.
*
* It also resets the EDN CSRNG command buffer to avoid synchronization issues
* with the upstream CSRNG instance.
*
* @param edn_address The based address of the target EDN block.
*/
static void edn_stop(uint32_t edn_address) {
// FIFO clear is only honored if edn is enabled. This is needed to avoid
// synchronization issues with the upstream CSRNG instance.
uint32_t reg = abs_mmio_read32(edn_address + EDN_CTRL_REG_OFFSET);
abs_mmio_write32(edn_address + EDN_CTRL_REG_OFFSET,
bitfield_field32_write(reg, EDN_CTRL_CMD_FIFO_RST_FIELD,
kMultiBitBool4True));
// Disable EDN and restore the FIFO clear at the same time so that no rogue
// command can get in after the clear above.
abs_mmio_write32(edn_address + EDN_CTRL_REG_OFFSET, EDN_CTRL_REG_RESVAL);
}
/**
* Blocks until EDN instance is ready to execute a new CSNRG command.
*
* @param edn_address EDN base address.
* @returns an error if the EDN error status bit is set.
*/
OT_WARN_UNUSED_RESULT
static status_t edn_ready_block(uint32_t edn_address) {
uint32_t reg;
do {
reg = abs_mmio_read32(edn_address + EDN_SW_CMD_STS_REG_OFFSET);
} while (!bitfield_bit32_read(reg, EDN_SW_CMD_STS_CMD_RDY_BIT));
if (bitfield_bit32_read(reg, EDN_SW_CMD_STS_CMD_STS_BIT)) {
return OTCRYPTO_RECOV_ERR;
}
return OTCRYPTO_OK;
}
/**
* Configures EDN instance based on `config` options.
*
* @param config EDN configuration options.
* @returns error on failure.
*/
OT_WARN_UNUSED_RESULT
static status_t edn_configure(const edn_config_t *config) {
HARDENED_TRY(csrng_send_app_cmd(
config->base_address + EDN_RESEED_CMD_REG_OFFSET, config->reseed, false));
HARDENED_TRY(
csrng_send_app_cmd(config->base_address + EDN_GENERATE_CMD_REG_OFFSET,
config->generate, false));
abs_mmio_write32(
config->base_address + EDN_MAX_NUM_REQS_BETWEEN_RESEEDS_REG_OFFSET,
config->reseed_interval);
uint32_t reg =
bitfield_field32_write(0, EDN_CTRL_EDN_ENABLE_FIELD, kMultiBitBool4True);
reg = bitfield_field32_write(reg, EDN_CTRL_AUTO_REQ_MODE_FIELD,
kMultiBitBool4True);
abs_mmio_write32(config->base_address + EDN_CTRL_REG_OFFSET, reg);
HARDENED_TRY(edn_ready_block(config->base_address));
HARDENED_TRY(
csrng_send_app_cmd(config->base_address + EDN_SW_CMD_REQ_REG_OFFSET,
config->instantiate, false));
return edn_ready_block(config->base_address);
}
/**
* Stops the current mode of operation and disables the entropy_src module.
*
* All configuration registers are set to their reset values to avoid
* synchronization issues with internal FIFOs.
*/
static void entropy_src_stop(void) {
abs_mmio_write32(kBaseEntropySrc + ENTROPY_SRC_MODULE_ENABLE_REG_OFFSET,
ENTROPY_SRC_MODULE_ENABLE_REG_RESVAL);
// Set default values for other critical registers to avoid synchronization
// issues.
abs_mmio_write32(kBaseEntropySrc + ENTROPY_SRC_ENTROPY_CONTROL_REG_OFFSET,
ENTROPY_SRC_ENTROPY_CONTROL_REG_RESVAL);
abs_mmio_write32(kBaseEntropySrc + ENTROPY_SRC_CONF_REG_OFFSET,
ENTROPY_SRC_CONF_REG_RESVAL);
abs_mmio_write32(kBaseEntropySrc + ENTROPY_SRC_HEALTH_TEST_WINDOWS_REG_OFFSET,
ENTROPY_SRC_HEALTH_TEST_WINDOWS_REG_RESVAL);
abs_mmio_write32(kBaseEntropySrc + ENTROPY_SRC_ALERT_THRESHOLD_REG_OFFSET,
ENTROPY_SRC_ALERT_THRESHOLD_REG_RESVAL);
}
/**
* Disables the entropy complex.
*
* The order of operations is important to avoid synchronization issues across
* blocks. For Example, EDN has FIFOs used to send commands to the downstream
* CSRNG instances. Such FIFOs are not cleared when EDN is reconfigured, and an
* explicit clear FIFO command needs to be set by software (see #14506). There
* may be additional race conditions for downstream blocks that are
* processing requests from an upstream endpoint (e.g. entropy_src processing a
* request from CSRNG, or CSRNG processing a request from EDN). To avoid these
* issues, it is recommended to first disable EDN, then CSRNG and entropy_src
* last.
*
* See hw/ip/csrng/doc/_index.md#module-enable-and-disable for more details.
*/
static void entropy_complex_stop_all(void) {
edn_stop(kBaseEdn0);
edn_stop(kBaseEdn1);
abs_mmio_write32(kBaseCsrng + CSRNG_CTRL_REG_OFFSET, CSRNG_CTRL_REG_RESVAL);
entropy_src_stop();
}
/**
* Set the value of an entropy_src threshold register.
*
* Only sets the FIPS threshold value, not the bypass threshold field; for the
* bypass threshold we use the reset value, which is ignored if looser than the
* thresholds already set.
*
* @param name Name of register (e.g. REPCNT, BUCKET).
* @param value Value to set for the FIPS_THRESH field.
*/
#define SET_FIPS_THRESH(name, value) \
abs_mmio_write32( \
kBaseEntropySrc + ENTROPY_SRC_##name##_THRESHOLDS_REG_OFFSET, \
bitfield_field32_write( \
ENTROPY_SRC_##name##_THRESHOLDS_REG_RESVAL, \
ENTROPY_SRC_##name##_THRESHOLDS_FIPS_THRESH_FIELD, value));
/**
* Configures the entropy_src with based on `config` options.
*
* @param config Entropy Source configuration options.
* @return error on failure.
*/
OT_WARN_UNUSED_RESULT
static status_t entropy_src_configure(const entropy_src_config_t *config) {
if (config->bypass_conditioner != kMultiBitBool4False) {
// Bypassing the conditioner is not supported.
return OTCRYPTO_BAD_ARGS;
}
// Control register configuration.
uint32_t reg = bitfield_field32_write(
0, ENTROPY_SRC_ENTROPY_CONTROL_ES_ROUTE_FIELD, config->route_to_firmware);
reg = bitfield_field32_write(reg, ENTROPY_SRC_ENTROPY_CONTROL_ES_TYPE_FIELD,
config->bypass_conditioner);
abs_mmio_write32(kBaseEntropySrc + ENTROPY_SRC_ENTROPY_CONTROL_REG_OFFSET,
reg);
// Config register configuration
reg = bitfield_field32_write(0, ENTROPY_SRC_CONF_FIPS_ENABLE_FIELD,
config->fips_enable);
reg = bitfield_field32_write(reg,
ENTROPY_SRC_CONF_ENTROPY_DATA_REG_ENABLE_FIELD,
config->route_to_firmware);
reg = bitfield_field32_write(reg, ENTROPY_SRC_CONF_THRESHOLD_SCOPE_FIELD,
kMultiBitBool4False);
reg = bitfield_field32_write(reg, ENTROPY_SRC_CONF_RNG_BIT_ENABLE_FIELD,
config->single_bit_mode);
reg = bitfield_field32_write(reg, ENTROPY_SRC_CONF_RNG_BIT_SEL_FIELD, 0);
abs_mmio_write32(kBaseEntropySrc + ENTROPY_SRC_CONF_REG_OFFSET, reg);
// Configure health test window. Conditioning bypass is not supported.
abs_mmio_write32(
kBaseEntropySrc + ENTROPY_SRC_HEALTH_TEST_WINDOWS_REG_OFFSET,
bitfield_field32_write(ENTROPY_SRC_HEALTH_TEST_WINDOWS_REG_RESVAL,
ENTROPY_SRC_HEALTH_TEST_WINDOWS_FIPS_WINDOW_FIELD,
config->fips_test_window_size));
// Configure alert threshold
reg = bitfield_field32_write(
0, ENTROPY_SRC_ALERT_THRESHOLD_ALERT_THRESHOLD_FIELD,
config->alert_threshold);
reg = bitfield_field32_write(
reg, ENTROPY_SRC_ALERT_THRESHOLD_ALERT_THRESHOLD_INV_FIELD,
~config->alert_threshold);
abs_mmio_write32(kBaseEntropySrc + ENTROPY_SRC_ALERT_THRESHOLD_REG_OFFSET,
reg);
// Configure health test thresholds. Conditioning bypass is not supported.
SET_FIPS_THRESH(REPCNT, config->repcnt_threshold);
SET_FIPS_THRESH(REPCNTS, config->repcnts_threshold);
SET_FIPS_THRESH(ADAPTP_HI, config->adaptp_hi_threshold);
SET_FIPS_THRESH(ADAPTP_LO, config->adaptp_lo_threshold);
SET_FIPS_THRESH(BUCKET, config->bucket_threshold);
SET_FIPS_THRESH(MARKOV_HI, config->markov_hi_threshold);
SET_FIPS_THRESH(MARKOV_LO, config->markov_lo_threshold);
SET_FIPS_THRESH(EXTHT_HI, config->extht_hi_threshold);
SET_FIPS_THRESH(EXTHT_LO, config->extht_lo_threshold);
// Enable entropy_src.
abs_mmio_write32(kBaseEntropySrc + ENTROPY_SRC_MODULE_ENABLE_REG_OFFSET,
kMultiBitBool4True);
// TODO: Add FI checks.
return OTCRYPTO_OK;
}
/**
* Verify the value of an entropy_src threshold register.
*
* Only checks the FIPS threshold value, not the bypass threshold field.
*
* @param name Name of register (e.g. REPCNT, BUCKET).
* @param exp Expected value of the FIPS_THRESH field.
*/
#define VERIFY_FIPS_THRESH(name, exp) \
do { \
uint32_t reg = abs_mmio_read32( \
kBaseEntropySrc + ENTROPY_SRC_##name##_THRESHOLDS_REG_OFFSET); \
uint32_t act = bitfield_field32_read( \
reg, ENTROPY_SRC_##name##_THRESHOLDS_FIPS_THRESH_FIELD); \
if (act != exp) { \
return OTCRYPTO_RECOV_ERR; \
} \
} while (false);
/**
* Check the entropy_src configuration.
*
* Verifies that the entropy_src block is enabled and running in a
* FIPS-compatible mode that forwards results to hardware. Checks the threshold
* register values against the configuration provided.
*
* @param config Entropy Source configuration options.
* @return error on failure.
*/
OT_WARN_UNUSED_RESULT
static status_t entropy_src_check(const entropy_src_config_t *config) {
if (config->fips_enable != kMultiBitBool4True ||
config->bypass_conditioner != kMultiBitBool4False ||
config->route_to_firmware != kMultiBitBool4False) {
// This check only supports FIPS-compatible configurations which do not
// bypass the conditioner or route to firmware.
return OTCRYPTO_BAD_ARGS;
}
// Check that entropy_src is enabled.
uint32_t reg =
abs_mmio_read32(kBaseEntropySrc + ENTROPY_SRC_MODULE_ENABLE_REG_OFFSET);
if (reg != kMultiBitBool4True) {
return OTCRYPTO_RECOV_ERR;
}
// Check that entropy_src is running in a FIPS-enabled mode without bypassing
// the conditioner (es_type) and while making results available to hardware
// (es_route):
// 1. CONF.FIPS_ENABLE = true
// 2. CONF.RNG_BIT_ENABLE = false
// 3. CONTROL.ES_TYPE = false
// 3. CONTROL.ES_ROUTE = false
reg = abs_mmio_read32(kBaseEntropySrc + ENTROPY_SRC_CONF_REG_OFFSET);
uint32_t conf_fips_enable =
bitfield_field32_read(reg, ENTROPY_SRC_CONF_FIPS_ENABLE_FIELD);
uint32_t conf_rng_bit_enable =
bitfield_field32_read(reg, ENTROPY_SRC_CONF_RNG_BIT_ENABLE_FIELD);
if (conf_fips_enable != kMultiBitBool4True ||
conf_rng_bit_enable != kMultiBitBool4False) {
return OTCRYPTO_RECOV_ERR;
}
reg =
abs_mmio_read32(kBaseEntropySrc + ENTROPY_SRC_ENTROPY_CONTROL_REG_OFFSET);
uint32_t control_es_type =
bitfield_field32_read(reg, ENTROPY_SRC_ENTROPY_CONTROL_ES_TYPE_FIELD);
uint32_t control_es_route =
bitfield_field32_read(reg, ENTROPY_SRC_ENTROPY_CONTROL_ES_ROUTE_FIELD);
if (control_es_type != kMultiBitBool4False ||
control_es_route != kMultiBitBool4False) {
return OTCRYPTO_RECOV_ERR;
}
// Check health test window register.
reg = abs_mmio_read32(kBaseEntropySrc +
ENTROPY_SRC_HEALTH_TEST_WINDOWS_REG_OFFSET);
if (bitfield_field32_read(
reg, ENTROPY_SRC_HEALTH_TEST_WINDOWS_FIPS_WINDOW_FIELD) !=
config->fips_test_window_size) {
return OTCRYPTO_RECOV_ERR;
}
// Check alert threshold.
uint32_t exp_reg = bitfield_field32_write(
0, ENTROPY_SRC_ALERT_THRESHOLD_ALERT_THRESHOLD_FIELD,
config->alert_threshold);
exp_reg = bitfield_field32_write(
exp_reg, ENTROPY_SRC_ALERT_THRESHOLD_ALERT_THRESHOLD_INV_FIELD,
~config->alert_threshold);
if (exp_reg != abs_mmio_read32(kBaseEntropySrc +
ENTROPY_SRC_ALERT_THRESHOLD_REG_OFFSET)) {
return OTCRYPTO_RECOV_ERR;
}
// Check health test thresholds.
VERIFY_FIPS_THRESH(REPCNT, config->repcnt_threshold);
VERIFY_FIPS_THRESH(REPCNTS, config->repcnts_threshold);
VERIFY_FIPS_THRESH(ADAPTP_HI, config->adaptp_hi_threshold);
VERIFY_FIPS_THRESH(ADAPTP_LO, config->adaptp_lo_threshold);
VERIFY_FIPS_THRESH(BUCKET, config->bucket_threshold);
VERIFY_FIPS_THRESH(MARKOV_HI, config->markov_hi_threshold);
VERIFY_FIPS_THRESH(MARKOV_LO, config->markov_lo_threshold);
VERIFY_FIPS_THRESH(EXTHT_HI, config->extht_hi_threshold);
VERIFY_FIPS_THRESH(EXTHT_LO, config->extht_lo_threshold);
// TODO: more FI checks on comparisons here.
return OTCRYPTO_OK;
}
/**
* Check the CSRNG configuration.
*
* This check simply ensures that the CSRNG is enabled.
*
* @param config EDN configuration.
* @return error on failure.
*/
OT_WARN_UNUSED_RESULT
static status_t csrng_check(void) {
uint32_t reg = abs_mmio_read32(kBaseCsrng + CSRNG_CTRL_REG_OFFSET);
uint32_t enable = bitfield_field32_read(reg, CSRNG_CTRL_ENABLE_FIELD);
if (enable == kMultiBitBool4True) {
return OTCRYPTO_OK;
}
return OTCRYPTO_RECOV_ERR;
}
/**
* Check the EDN configuration.
*
* This check simply ensures that the EDN is enabled and running in auto_req
* mode.
*
* @param config EDN configuration.
* @return error on failure.
*/
OT_WARN_UNUSED_RESULT
static status_t edn_check(const edn_config_t *config) {
uint32_t reg = abs_mmio_read32(config->base_address + EDN_CTRL_REG_OFFSET);
uint32_t edn_enable = bitfield_field32_read(reg, EDN_CTRL_EDN_ENABLE_FIELD);
uint32_t auto_req_mode =
bitfield_field32_read(reg, EDN_CTRL_AUTO_REQ_MODE_FIELD);
if (edn_enable == kMultiBitBool4True && auto_req_mode == kMultiBitBool4True) {
return OTCRYPTO_OK;
}
return OTCRYPTO_RECOV_ERR;
}
status_t entropy_complex_init(void) {
entropy_complex_stop_all();
const entropy_complex_config_t *config =
&kEntropyComplexConfigs[kEntropyComplexConfigIdContinuous];
if (launder32(config->id) != kEntropyComplexConfigIdContinuous) {
return OTCRYPTO_RECOV_ERR;
}
HARDENED_TRY(entropy_src_configure(&config->entropy_src));
csrng_configure();
HARDENED_TRY(edn_configure(&config->edn0));
return edn_configure(&config->edn1);
}
status_t entropy_complex_check(void) {
const entropy_complex_config_t *config =
&kEntropyComplexConfigs[kEntropyComplexConfigIdContinuous];
if (launder32(config->id) != kEntropyComplexConfigIdContinuous) {
return OTCRYPTO_RECOV_ERR;
}
HARDENED_TRY(entropy_src_check(&config->entropy_src));
HARDENED_TRY(csrng_check());
HARDENED_TRY(edn_check(&config->edn0));
return edn_check(&config->edn1);
}
status_t entropy_csrng_instantiate(
hardened_bool_t disable_trng_input,
const entropy_seed_material_t *seed_material) {
return csrng_send_app_cmd(kBaseCsrng + CSRNG_CMD_REQ_REG_OFFSET,
(entropy_csrng_cmd_t){
.id = kEntropyDrbgOpInstantiate,
.disable_trng_input = disable_trng_input,
.seed_material = seed_material,
.generate_len = 0,
},
true);
}
status_t entropy_csrng_reseed(hardened_bool_t disable_trng_input,
const entropy_seed_material_t *seed_material) {
return csrng_send_app_cmd(kBaseCsrng + CSRNG_CMD_REQ_REG_OFFSET,
(entropy_csrng_cmd_t){
.id = kEntropyDrbgOpReseed,
.disable_trng_input = disable_trng_input,
.seed_material = seed_material,
.generate_len = 0,
},
true);
}
status_t entropy_csrng_update(const entropy_seed_material_t *seed_material) {
return csrng_send_app_cmd(kBaseCsrng + CSRNG_CMD_REQ_REG_OFFSET,
(entropy_csrng_cmd_t){
.id = kEntropyDrbgOpUpdate,
.seed_material = seed_material,
.generate_len = 0,
},
true);
}
status_t entropy_csrng_generate_start(
const entropy_seed_material_t *seed_material, size_t len) {
// Round up the number of 128bit blocks. Aligning with respect to uint32_t.
// TODO(#6112): Consider using a canonical reference for alignment operations.
const uint32_t num_128bit_blocks = (len + 3) / 4;
return csrng_send_app_cmd(kBaseCsrng + CSRNG_CMD_REQ_REG_OFFSET,
(entropy_csrng_cmd_t){
.id = kEntropyDrbgOpGenerate,
.seed_material = seed_material,
.generate_len = num_128bit_blocks,
},
true);
}
status_t entropy_csrng_generate_data_get(uint32_t *buf, size_t len,
hardened_bool_t fips_check) {
static_assert(kEntropyCsrngBitsBufferNumWords == 4,
"kEntropyCsrngBitsBufferNumWords must be 4.");
size_t nblocks = (len + 3) / 4;
status_t res = OTCRYPTO_OK;
for (size_t block_idx = 0; block_idx < nblocks; ++block_idx) {
// Block until there is more data available in the genbits buffer. CSRNG
// generates data in 128bit chunks (i.e. 4 words).
uint32_t reg;
do {
reg = abs_mmio_read32(kBaseCsrng + CSRNG_GENBITS_VLD_REG_OFFSET);
} while (!bitfield_bit32_read(reg, CSRNG_GENBITS_VLD_GENBITS_VLD_BIT));
if (fips_check != kHardenedBoolFalse &&
!bitfield_bit32_read(reg, CSRNG_GENBITS_VLD_GENBITS_FIPS_BIT)) {
// Entropy isn't FIPS-compatible, so we should return an error when
// done. However, we still need to read the result to clear CSRNG's FIFO.
res = OTCRYPTO_RECOV_ERR;
}
// Read the full 128-bit block, in reverse word order to match known-answer
// tests. To clear the FIFO, we need to read all blocks generated by the
// request even if we don't use them.
for (size_t offset = 0; offset < kEntropyCsrngBitsBufferNumWords;
++offset) {
uint32_t word = abs_mmio_read32(kBaseCsrng + CSRNG_GENBITS_REG_OFFSET);
size_t word_idx = (block_idx * kEntropyCsrngBitsBufferNumWords) +
kEntropyCsrngBitsBufferNumWords - 1 - offset;
if (word_idx < len) {
buf[word_idx] = word;
}
}
}
return res;
}
status_t entropy_csrng_generate(const entropy_seed_material_t *seed_material,
uint32_t *buf, size_t len,
hardened_bool_t fips_check) {
HARDENED_TRY(entropy_csrng_generate_start(seed_material, len));
return entropy_csrng_generate_data_get(buf, len, fips_check);
}
status_t entropy_csrng_uninstantiate(void) {
return csrng_send_app_cmd(kBaseCsrng + CSRNG_CMD_REQ_REG_OFFSET,
(entropy_csrng_cmd_t){
.id = kEntropyDrbgOpUninstantiate,
.seed_material = NULL,
.generate_len = 0,
},
true);
}
|
69155ca324f2105b56d0db53d0da7a3394c5a5d3
|
152033c36c5b8f0c12843db6036bff9e0e848e98
|
/src/utils/api-utils.h
|
1df95e86cab741cdccc9b4b0348a2f939db84963
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
haiwen/seafile-client
|
4f8348c184ec749757e44cea8cc44ae0713492ae
|
5c832cb119af540e6c2517f225cca67b172e6a63
|
refs/heads/master
| 2023-09-01T20:47:19.188179
| 2023-08-28T07:53:26
| 2023-08-28T07:53:26
| 11,894,308
| 441
| 332
|
Apache-2.0
| 2023-09-08T02:22:13
| 2013-08-05T09:08:07
|
C++
|
UTF-8
|
C
| false
| false
| 254
|
h
|
api-utils.h
|
#ifndef SEAFILE_CLIENT_API_UTILS_H_
#define SEAFILE_CLIENT_API_UTILS_H_
QHash<QString, QString>
getSeafileLoginParams(const QString& computer_name=QString(),
const QString& prefix=QString());
#endif // SEAFILE_CLIENT_API_UTILS_H_
|
287ff11838bde457440eedd2b04cd9b8cce11bd6
|
99bdb3251fecee538e0630f15f6574054dfc1468
|
/bsp/phytium/libraries/standalone/drivers/mio/fmio/fmio.h
|
20645951973d5b290ebf74c1a06a78cb390db2d3
|
[
"Apache-2.0",
"Zlib",
"LicenseRef-scancode-proprietary-license",
"MIT",
"BSD-3-Clause",
"X11",
"BSD-4-Clause-UC",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] |
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
| 2,681
|
h
|
fmio.h
|
/*
* Copyright : (C) 2022 Phytium Information Technology, Inc.
* All Rights Reserved.
*
* This program is OPEN SOURCE software: you can redistribute it and/or modify it
* under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd,
* either version 1.0 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the Phytium Public License for more details.
*
*
* FilePath: fmio.h
* Date: 2022-06-21 15:40:06
* LastEditTime: 2022-06-21 15:40:06
* Description: This file is for user external interface definition
*
* Modify History:
* Ver Who Date Changes
* ----- ------ -------- --------------------------------------
* 1.0 liushengming 2022/06/21 first commit
*/
#ifndef FMIO_H
#define FMIO_H
#ifdef __cplusplus
extern "C"
{
#endif
/***************************** Include Files *********************************/
#include "ftypes.h"
#include "ferror_code.h"
#include "fassert.h"
/************************** Constant Definitions *****************************/
#define FMIO_SUCCESS FT_SUCCESS
#define FMIO_ERR_INVAL_PARM FT_MAKE_ERRCODE(ErrModBsp, ErrBspMio, 1)
#define FMIO_ERR_NOT_READY FT_MAKE_ERRCODE(ErrModBsp, ErrBspMio, 2)
#define FMIO_ERR_TIMEOUT FT_MAKE_ERRCODE(ErrModBsp, ErrBspMio, 3)
#define FMIO_ERR_NOT_SUPPORT FT_MAKE_ERRCODE(ErrModBsp, ErrBspMio, 4)
#define FMIO_ERR_INVAL_STATE FT_MAKE_ERRCODE(ErrModBsp, ErrBspMio, 5)
/**************************** Type Definitions *******************************/
typedef struct
{
u32 instance_id; /*mio id*/
uintptr func_base_addr; /*I2C or UART function address*/
u32 irq_num; /* Device intrrupt id */
uintptr mio_base_addr; /*MIO control address*/
} FMioConfig; /*mio configs*/
typedef struct
{
FMioConfig config; /* mio config */
u32 is_ready; /* mio initialize the complete flag */
} FMioCtrl;
/************************** Function Prototypes ******************************/
/*获取MIO的配置信息*/
const FMioConfig *FMioLookupConfig(u32 instance_id);
/*初始化MIO的功能*/
FError FMioFuncInit(FMioCtrl *instance_p, u32 mio_type);
/*去初始化*/
FError FMioFuncDeinit(FMioCtrl *instance_p);
/*获取功能配置的基地址*/
uintptr FMioFuncGetAddress(FMioCtrl *instance_p, u32 mio_type);
/*获取功能的中断号*/
u32 FMioFuncGetIrqNum(FMioCtrl *instance_p, u32 mio_type);
#ifdef __cplusplus
}
#endif
#endif
|
36e66563fa4309f8a1ea779d3b038b0b72860bb2
|
34cfb15a219a735d58fcaadfb71ef1606a9114dc
|
/ext/deps/libcat/src/cat_api.c
|
9961ba4815082c46840b4e39cf77581410102918
|
[
"Apache-2.0",
"ISC",
"BSL-1.0",
"MIT",
"BSD-2-Clause"
] |
permissive
|
swow/swow
|
e32007f3cf1c8daf4accd7d64f9b2b728f5ab103
|
231f580dd1ee84d0364f314387073c5bda9854d2
|
refs/heads/develop
| 2023-08-19T13:51:39.840737
| 2023-08-05T01:51:04
| 2023-08-05T03:13:03
| 295,651,066
| 1,085
| 117
|
Apache-2.0
| 2023-06-15T09:18:12
| 2020-09-15T07:37:43
|
C
|
UTF-8
|
C
| false
| false
| 3,959
|
c
|
cat_api.c
|
/*
+--------------------------------------------------------------------------+
| libcat |
+--------------------------------------------------------------------------+
| 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. See accompanying LICENSE file. |
+--------------------------------------------------------------------------+
| Author: Twosee <twosee@php.net> |
+--------------------------------------------------------------------------+
*/
#include "cat_api.h"
CAT_API cat_bool_t cat_init_all(void)
{
return cat_module_init_all() &&
cat_runtime_init_all();
}
CAT_API cat_bool_t cat_shutdown_all(void)
{
cat_bool_t ret = cat_true;
ret = cat_runtime_shutdown_all();
ret = cat_runtime_close_all() && ret;
ret = cat_module_shutdown_all() && ret;
return ret;
}
CAT_API cat_bool_t cat_module_init_all(void)
{
return cat_module_init() &&
cat_coroutine_module_init() &&
cat_event_module_init() &&
cat_buffer_module_init() &&
#ifdef CAT_SSL
cat_ssl_module_init() &&
#endif
cat_socket_module_init() &&
#ifdef CAT_OS_WAIT
cat_os_wait_module_init() &&
#endif
cat_watchdog_module_init() &&
cat_true;
}
CAT_API cat_bool_t cat_module_shutdown_all(void)
{
cat_bool_t ret = cat_true;
ret = cat_watchdog_module_shutdown() && ret;
#ifdef CAT_OS_WAIT
ret = cat_os_wait_module_shutdown() && ret;
#endif
ret = cat_socket_module_shutdown() && ret;
ret = cat_event_module_shutdown() && ret;
ret = cat_coroutine_module_shutdown() && ret;
ret = cat_module_shutdown() && ret;
return ret;
}
CAT_API cat_bool_t cat_runtime_init_all(void)
{
return cat_runtime_init() &&
cat_coroutine_runtime_init() &&
cat_event_runtime_init() &&
cat_socket_runtime_init() &&
#ifdef CAT_OS_WAIT
cat_os_wait_runtime_init() &&
#endif
cat_watchdog_runtime_init() &&
cat_true;
}
CAT_API cat_bool_t cat_runtime_shutdown_all(void)
{
cat_bool_t ret = cat_true;
ret = cat_watchdog_runtime_shutdown() && ret;
#ifdef CAT_OS_WAIT
ret = cat_os_wait_runtime_shutdown() && ret;
#endif
ret = cat_event_runtime_shutdown() && ret;
ret = cat_coroutine_runtime_shutdown() && ret;
ret = cat_runtime_shutdown() && ret;
return ret;
}
CAT_API cat_bool_t cat_runtime_close_all(void)
{
cat_bool_t ret = cat_true;
ret = cat_event_runtime_close() &&
cat_runtime_close() &&
ret;
return ret;
}
CAT_API cat_bool_t cat_run(cat_run_mode_t run_mode)
{
switch (run_mode) {
case CAT_RUN_EASY: {
return cat_event_scheduler_run(NULL) != NULL;
}
}
CAT_NEVER_HERE("Unknown run mode");
}
CAT_API cat_bool_t cat_stop(void)
{
return cat_event_scheduler_close() != NULL;
}
#ifdef CAT_DEBUG
CAT_API void cat_enable_debug_mode(void)
{
CAT_LOG_G(types) = CAT_LOG_TYPES_ALL;
if (CAT_LOG_G(debug_level) == 0) {
CAT_LOG_G(debug_level) = (unsigned int) -1;
}
}
#endif
CAT_API FILE *cat_get_error_log(void)
{
return CAT_LOG_G(error_output);
}
CAT_API void cat_set_error_log(FILE *file)
{
CAT_LOG_G(error_output) = file;
}
|
1087f3ec38c4f5bd9f07ccdee5626f4bc8f7ded9
|
f79dec3c4033ca3cbb55d8a51a748cc7b8b6fbab
|
/emulators/gxemul/patches/patch-src_include_components_M88K__CPUComponent.h
|
299d96b08ece10e55f370e6366e666d9ab234ca1
|
[] |
no_license
|
jsonn/pkgsrc
|
fb34c4a6a2d350e8e415f3c4955d4989fcd86881
|
c1514b5f4a3726d90e30aa16b0c209adbc276d17
|
refs/heads/trunk
| 2021-01-24T09:10:01.038867
| 2017-07-07T15:49:43
| 2017-07-07T15:49:43
| 2,095,004
| 106
| 47
| null | 2016-09-19T09:26:01
| 2011-07-23T23:49:04
|
Makefile
|
UTF-8
|
C
| false
| false
| 655
|
h
|
patch-src_include_components_M88K__CPUComponent.h
|
$NetBSD: patch-src_include_components_M88K__CPUComponent.h,v 1.1 2012/11/23 12:33:22 joerg Exp $
--- src/include/components/M88K_CPUComponent.h.orig 2012-11-19 20:10:14.000000000 +0000
+++ src/include/components/M88K_CPUComponent.h
@@ -377,7 +377,7 @@ protected:
virtual bool FunctionTraceReturnImpl(int64_t& retval) { retval = m_r[M88K_RETURN_VALUE_REG]; return true; }
virtual int GetDyntransICshift() const;
- virtual void (*GetDyntransToBeTranslated())(CPUDyntransComponent*, DyntransIC*) const;
+ virtual DyntransIC_t GetDyntransToBeTranslated() const ;
virtual void ShowRegisters(GXemul* gxemul, const vector<string>& arguments) const;
|
45a6cb70071c7815a75b9844f208e7c414e83c03
|
9ceacf33fd96913cac7ef15492c126d96cae6911
|
/sys/dev/pci/drm/amd/amdgpu/amdgpu_sdma.c
|
d318016f41b40564441890ad6ef0485fb7ef46f4
|
[] |
no_license
|
openbsd/src
|
ab97ef834fd2d5a7f6729814665e9782b586c130
|
9e79f3a0ebd11a25b4bff61e900cb6de9e7795e9
|
refs/heads/master
| 2023-09-02T18:54:56.624627
| 2023-09-02T15:16:12
| 2023-09-02T15:16:12
| 66,966,208
| 3,394
| 1,235
| null | 2023-08-08T02:42:25
| 2016-08-30T18:18:25
|
C
|
UTF-8
|
C
| false
| false
| 8,310
|
c
|
amdgpu_sdma.c
|
/*
* Copyright 2018 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include <linux/firmware.h>
#include "amdgpu.h"
#include "amdgpu_sdma.h"
#include "amdgpu_ras.h"
#define AMDGPU_CSA_SDMA_SIZE 64
/* SDMA CSA reside in the 3rd page of CSA */
#define AMDGPU_CSA_SDMA_OFFSET (4096 * 2)
/*
* GPU SDMA IP block helpers function.
*/
struct amdgpu_sdma_instance *amdgpu_sdma_get_instance_from_ring(struct amdgpu_ring *ring)
{
struct amdgpu_device *adev = ring->adev;
int i;
for (i = 0; i < adev->sdma.num_instances; i++)
if (ring == &adev->sdma.instance[i].ring ||
ring == &adev->sdma.instance[i].page)
return &adev->sdma.instance[i];
return NULL;
}
int amdgpu_sdma_get_index_from_ring(struct amdgpu_ring *ring, uint32_t *index)
{
struct amdgpu_device *adev = ring->adev;
int i;
for (i = 0; i < adev->sdma.num_instances; i++) {
if (ring == &adev->sdma.instance[i].ring ||
ring == &adev->sdma.instance[i].page) {
*index = i;
return 0;
}
}
return -EINVAL;
}
uint64_t amdgpu_sdma_get_csa_mc_addr(struct amdgpu_ring *ring,
unsigned vmid)
{
struct amdgpu_device *adev = ring->adev;
uint64_t csa_mc_addr;
uint32_t index = 0;
int r;
/* don't enable OS preemption on SDMA under SRIOV */
if (amdgpu_sriov_vf(adev) || vmid == 0 || !amdgpu_mcbp)
return 0;
if (ring->is_mes_queue) {
uint32_t offset = 0;
offset = offsetof(struct amdgpu_mes_ctx_meta_data,
sdma[ring->idx].sdma_meta_data);
csa_mc_addr = amdgpu_mes_ctx_get_offs_gpu_addr(ring, offset);
} else {
r = amdgpu_sdma_get_index_from_ring(ring, &index);
if (r || index > 31)
csa_mc_addr = 0;
else
csa_mc_addr = amdgpu_csa_vaddr(adev) +
AMDGPU_CSA_SDMA_OFFSET +
index * AMDGPU_CSA_SDMA_SIZE;
}
return csa_mc_addr;
}
int amdgpu_sdma_ras_late_init(struct amdgpu_device *adev,
struct ras_common_if *ras_block)
{
int r, i;
r = amdgpu_ras_block_late_init(adev, ras_block);
if (r)
return r;
if (amdgpu_ras_is_supported(adev, ras_block->block)) {
for (i = 0; i < adev->sdma.num_instances; i++) {
r = amdgpu_irq_get(adev, &adev->sdma.ecc_irq,
AMDGPU_SDMA_IRQ_INSTANCE0 + i);
if (r)
goto late_fini;
}
}
return 0;
late_fini:
amdgpu_ras_block_late_fini(adev, ras_block);
return r;
}
int amdgpu_sdma_process_ras_data_cb(struct amdgpu_device *adev,
void *err_data,
struct amdgpu_iv_entry *entry)
{
kgd2kfd_set_sram_ecc_flag(adev->kfd.dev);
if (amdgpu_sriov_vf(adev))
return AMDGPU_RAS_SUCCESS;
amdgpu_ras_reset_gpu(adev);
return AMDGPU_RAS_SUCCESS;
}
int amdgpu_sdma_process_ecc_irq(struct amdgpu_device *adev,
struct amdgpu_irq_src *source,
struct amdgpu_iv_entry *entry)
{
struct ras_common_if *ras_if = adev->sdma.ras_if;
struct ras_dispatch_if ih_data = {
.entry = entry,
};
if (!ras_if)
return 0;
ih_data.head = *ras_if;
amdgpu_ras_interrupt_dispatch(adev, &ih_data);
return 0;
}
static int amdgpu_sdma_init_inst_ctx(struct amdgpu_sdma_instance *sdma_inst)
{
int err = 0;
uint16_t version_major;
const struct common_firmware_header *header = NULL;
const struct sdma_firmware_header_v1_0 *hdr;
const struct sdma_firmware_header_v2_0 *hdr_v2;
err = amdgpu_ucode_validate(sdma_inst->fw);
if (err)
return err;
header = (const struct common_firmware_header *)
sdma_inst->fw->data;
version_major = le16_to_cpu(header->header_version_major);
switch (version_major) {
case 1:
hdr = (const struct sdma_firmware_header_v1_0 *)sdma_inst->fw->data;
sdma_inst->fw_version = le32_to_cpu(hdr->header.ucode_version);
sdma_inst->feature_version = le32_to_cpu(hdr->ucode_feature_version);
break;
case 2:
hdr_v2 = (const struct sdma_firmware_header_v2_0 *)sdma_inst->fw->data;
sdma_inst->fw_version = le32_to_cpu(hdr_v2->header.ucode_version);
sdma_inst->feature_version = le32_to_cpu(hdr_v2->ucode_feature_version);
break;
default:
return -EINVAL;
}
if (sdma_inst->feature_version >= 20)
sdma_inst->burst_nop = true;
return 0;
}
void amdgpu_sdma_destroy_inst_ctx(struct amdgpu_device *adev,
bool duplicate)
{
int i;
for (i = 0; i < adev->sdma.num_instances; i++) {
release_firmware(adev->sdma.instance[i].fw);
if (duplicate)
break;
}
memset((void *)adev->sdma.instance, 0,
sizeof(struct amdgpu_sdma_instance) * AMDGPU_MAX_SDMA_INSTANCES);
}
int amdgpu_sdma_init_microcode(struct amdgpu_device *adev,
char *fw_name, u32 instance,
bool duplicate)
{
struct amdgpu_firmware_info *info = NULL;
const struct common_firmware_header *header = NULL;
int err = 0, i;
const struct sdma_firmware_header_v2_0 *sdma_hdr;
uint16_t version_major;
err = request_firmware(&adev->sdma.instance[instance].fw, fw_name, adev->dev);
if (err)
goto out;
header = (const struct common_firmware_header *)
adev->sdma.instance[instance].fw->data;
version_major = le16_to_cpu(header->header_version_major);
if ((duplicate && instance) || (!duplicate && version_major > 1)) {
err = -EINVAL;
goto out;
}
err = amdgpu_sdma_init_inst_ctx(&adev->sdma.instance[instance]);
if (err)
goto out;
if (duplicate) {
for (i = 1; i < adev->sdma.num_instances; i++)
memcpy((void *)&adev->sdma.instance[i],
(void *)&adev->sdma.instance[0],
sizeof(struct amdgpu_sdma_instance));
}
if (amdgpu_sriov_vf(adev))
return 0;
DRM_DEBUG("psp_load == '%s'\n",
adev->firmware.load_type == AMDGPU_FW_LOAD_PSP ? "true" : "false");
if (adev->firmware.load_type == AMDGPU_FW_LOAD_PSP) {
switch (version_major) {
case 1:
for (i = 0; i < adev->sdma.num_instances; i++) {
if (!duplicate && (instance != i))
continue;
else {
info = &adev->firmware.ucode[AMDGPU_UCODE_ID_SDMA0 + i];
info->ucode_id = AMDGPU_UCODE_ID_SDMA0 + i;
info->fw = adev->sdma.instance[i].fw;
adev->firmware.fw_size +=
roundup2(le32_to_cpu(header->ucode_size_bytes), PAGE_SIZE);
}
}
break;
case 2:
sdma_hdr = (const struct sdma_firmware_header_v2_0 *)
adev->sdma.instance[0].fw->data;
info = &adev->firmware.ucode[AMDGPU_UCODE_ID_SDMA_UCODE_TH0];
info->ucode_id = AMDGPU_UCODE_ID_SDMA_UCODE_TH0;
info->fw = adev->sdma.instance[0].fw;
adev->firmware.fw_size +=
roundup2(le32_to_cpu(sdma_hdr->ctx_ucode_size_bytes), PAGE_SIZE);
info = &adev->firmware.ucode[AMDGPU_UCODE_ID_SDMA_UCODE_TH1];
info->ucode_id = AMDGPU_UCODE_ID_SDMA_UCODE_TH1;
info->fw = adev->sdma.instance[0].fw;
adev->firmware.fw_size +=
roundup2(le32_to_cpu(sdma_hdr->ctl_ucode_size_bytes), PAGE_SIZE);
break;
default:
err = -EINVAL;
}
}
out:
if (err) {
DRM_ERROR("SDMA: Failed to init firmware \"%s\"\n", fw_name);
amdgpu_sdma_destroy_inst_ctx(adev, duplicate);
}
return err;
}
void amdgpu_sdma_unset_buffer_funcs_helper(struct amdgpu_device *adev)
{
struct amdgpu_ring *sdma;
int i;
for (i = 0; i < adev->sdma.num_instances; i++) {
if (adev->sdma.has_page_queue) {
sdma = &adev->sdma.instance[i].page;
if (adev->mman.buffer_funcs_ring == sdma) {
amdgpu_ttm_set_buffer_funcs_status(adev, false);
break;
}
}
sdma = &adev->sdma.instance[i].ring;
if (adev->mman.buffer_funcs_ring == sdma) {
amdgpu_ttm_set_buffer_funcs_status(adev, false);
break;
}
}
}
|
9c2139d2ec762e84cd53bae525439f84099c737d
|
99bdb3251fecee538e0630f15f6574054dfc1468
|
/bsp/samd21/sam_d2x_asflib/sam0/drivers/tsens/tsens_callback.c
|
ef7fd46ca697fe243c64f021a2b4f5d6bc55dc46
|
[
"Apache-2.0",
"Zlib",
"LicenseRef-scancode-proprietary-license",
"MIT",
"BSD-3-Clause",
"X11",
"BSD-4-Clause-UC",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
RT-Thread/rt-thread
|
03a7c52c2aeb1b06a544143b0e803d72f47d1ece
|
3602f891211904a27dcbd51e5ba72fefce7326b2
|
refs/heads/master
| 2023-09-01T04:10:20.295801
| 2023-08-31T16:20:55
| 2023-08-31T16:20:55
| 7,408,108
| 9,599
| 5,805
|
Apache-2.0
| 2023-09-14T13:37:26
| 2013-01-02T14:49:21
|
C
|
UTF-8
|
C
| false
| false
| 4,511
|
c
|
tsens_callback.c
|
/**
* \file
*
* \brief SAM Temperature Sensor Driver
*
* 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 "tsens_callback.h"
struct tsens_module *_tsens_instances;
/** Interrupt handler for the TSENS module. */
void TSENS_Handler(void)
{
struct tsens_module *module = _tsens_instances;
Assert(module);
/* get interrupt flags and mask out enabled callbacks */
uint32_t flags = TSENS->INTFLAG.reg;
/* store TSENS result in job buffer */
uint32_t temp = TSENS->VALUE.reg;
if(temp & 0x00800000) {
temp |= ~TSENS_VALUE_MASK;
}
#if (ERRATA_14476)
*(module->value) = temp * (-1);
#endif
for(uint8_t i = 0; i < TSENS_CALLBACK_NUM; i++)
{
if (flags & ((uint32_t)0x01 << i)) {
/* Clear the INTFLAG anyway */
TSENS->INTFLAG.reg = (uint32_t)0x01 << i;
if(module->callback[i] != NULL) {
module->callback[i]((enum tsens_callback)i);
}
}
}
}
/**
* \brief Registers a callback.
*
* Registers a callback function which is implemented by the user.
*
* \note The callback must be enabled by for the interrupt handler to call it
* when the condition for the callback is met.
*
* \param[in] module Pointer to TSENS software instance struct
* \param[in] callback_func Pointer to callback function
* \param[in] callback_type Callback type given by an enum
*
*/
enum status_code tsens_register_callback(
struct tsens_module *const module,
tsens_callback_t callback_func,
enum tsens_callback callback_type)
{
/* Sanity check arguments */
Assert(module);
Assert(callback_func);
if(callback_type > TSENS_CALLBACK_NUM) {
return STATUS_ERR_INVALID_ARG;
}
/* Register callback function */
module->callback[callback_type] = callback_func;
_tsens_instances = module;
return STATUS_OK;
}
/**
* \brief Unregisters a callback.
*
* Unregisters a callback function which is implemented by the user.
*
* \param[in] module Pointer to TSENS software instance struct
* \param[in] callback_type Callback type given by an enum
*
*/
enum status_code tsens_unregister_callback(
struct tsens_module *const module,
enum tsens_callback callback_type)
{
/* Sanity check arguments */
Assert(module);
if(callback_type > TSENS_CALLBACK_NUM) {
return STATUS_ERR_INVALID_ARG;
}
/* Register callback function */
module->callback[callback_type] = NULL;
return STATUS_OK;
}
/**
* \brief Read result from TSENS.
*
* \param[in] module_inst Pointer to the TSENS software instance struct
* \param[out] result Pointer to store the TSENS result
*
*/
void tsens_read_job(
struct tsens_module *const module_inst,
int32_t *result)
{
Assert(module_inst);
Assert(result);
module_inst->value = result;
if(!(TSENS->CTRLC.reg & TSENS_CTRLC_FREERUN)) {
tsens_start_conversion();
}
}
|
88f8510e8dc1853228b3eb3fb159ebeddbb5a535
|
88ae8695987ada722184307301e221e1ba3cc2fa
|
/third_party/sqlite/src/ext/misc/base85.c
|
5ec136dbc68007df75b3a887ecc126eee2621bb0
|
[
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"blessing",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
] |
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
| 12,900
|
c
|
base85.c
|
/*
** 2022-11-16
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
**
** This is a utility for converting binary to base85 or vice-versa.
** It can be built as a standalone program or an SQLite3 extension.
**
** Much like base64 representations, base85 can be sent through a
** sane USASCII channel unmolested. It also plays nicely in CSV or
** written as TCL brace-enclosed literals or SQL string literals.
** It is not suited for unmodified use in XML-like documents.
**
** The encoding used resembles Ascii85, but was devised by the author
** (Larry Brasfield) before Mozilla, Adobe, ZMODEM or other Ascii85
** variant sources existed, in the 1984 timeframe on a VAX mainframe.
** Further, this is an independent implementation of a base85 system.
** Hence, the author has rightfully put this into the public domain.
**
** Base85 numerals are taken from the set of 7-bit USASCII codes,
** excluding control characters and Space ! " ' ( ) { | } ~ Del
** in code order representing digit values 0 to 84 (base 10.)
**
** Groups of 4 bytes, interpreted as big-endian 32-bit values,
** are represented as 5-digit base85 numbers with MS to LS digit
** order. Groups of 1-3 bytes are represented with 2-4 digits,
** still big-endian but 8-24 bit values. (Using big-endian yields
** the simplest transition to byte groups smaller than 4 bytes.
** These byte groups can also be considered base-256 numbers.)
** Groups of 0 bytes are represented with 0 digits and vice-versa.
** No pad characters are used; Encoded base85 numeral sequence
** (aka "group") length maps 1-to-1 to the decoded binary length.
**
** Any character not in the base85 numeral set delimits groups.
** When base85 is streamed or stored in containers of indefinite
** size, newline is used to separate it into sub-sequences of no
** more than 80 digits so that fgets() can be used to read it.
**
** Length limitations are not imposed except that the runtime
** SQLite string or blob length limits are respected. Otherwise,
** any length binary sequence can be represented and recovered.
** Base85 sequences can be concatenated by separating them with
** a non-base85 character; the conversion to binary will then
** be the concatenation of the represented binary sequences.
** The standalone program either converts base85 on stdin to create
** a binary file or converts a binary file to base85 on stdout.
** Read or make it blurt its help for invocation details.
**
** The SQLite3 extension creates a function, base85(x), which will
** either convert text base85 to a blob or a blob to text base85
** and return the result (or throw an error for other types.)
** Unless built with OMIT_BASE85_CHECKER defined, it also creates a
** function, is_base85(t), which returns 1 iff the text t contains
** nothing other than base85 numerals and whitespace, or 0 otherwise.
**
** To build the extension:
** Set shell variable SQDIR=<your favorite SQLite checkout directory>
** and variable OPTS to -DOMIT_BASE85_CHECKER if is_base85() unwanted.
** *Nix: gcc -O2 -shared -I$SQDIR $OPTS -fPIC -o base85.so base85.c
** OSX: gcc -O2 -dynamiclib -fPIC -I$SQDIR $OPTS -o base85.dylib base85.c
** Win32: gcc -O2 -shared -I%SQDIR% %OPTS% -o base85.dll base85.c
** Win32: cl /Os -I%SQDIR% %OPTS% base85.c -link -dll -out:base85.dll
**
** To build the standalone program, define PP symbol BASE85_STANDALONE. Eg.
** *Nix or OSX: gcc -O2 -DBASE85_STANDALONE base85.c -o base85
** Win32: gcc -O2 -DBASE85_STANDALONE -o base85.exe base85.c
** Win32: cl /Os /MD -DBASE85_STANDALONE base85.c
*/
#include <stdio.h>
#include <memory.h>
#include <string.h>
#include <assert.h>
#ifndef OMIT_BASE85_CHECKER
# include <ctype.h>
#endif
#ifndef BASE85_STANDALONE
# include "sqlite3ext.h"
SQLITE_EXTENSION_INIT1;
#else
# ifdef _WIN32
# include <io.h>
# include <fcntl.h>
# else
# define setmode(fd,m)
# endif
static char *zHelp =
"Usage: base85 <dirFlag> <binFile>\n"
" <dirFlag> is either -r to read or -w to write <binFile>,\n"
" content to be converted to/from base85 on stdout/stdin.\n"
" <binFile> names a binary file to be rendered or created.\n"
" Or, the name '-' refers to the stdin or stdout stream.\n"
;
static void sayHelp(){
printf("%s", zHelp);
}
#endif
#ifndef U8_TYPEDEF
typedef unsigned char u8;
#define U8_TYPEDEF
#endif
/* Classify c according to interval within USASCII set w.r.t. base85
* Values of 1 and 3 are base85 numerals. Values of 0, 2, or 4 are not.
*/
#define B85_CLASS( c ) (((c)>='#')+((c)>'&')+((c)>='*')+((c)>'z'))
/* Provide digitValue to b85Numeral offset as a function of above class. */
static u8 b85_cOffset[] = { 0, '#', 0, '*'-4, 0 };
#define B85_DNOS( c ) b85_cOffset[B85_CLASS(c)]
/* Say whether c is a base85 numeral. */
#define IS_B85( c ) (B85_CLASS(c) & 1)
#if 0 /* Not used, */
static u8 base85DigitValue( char c ){
u8 dv = (u8)(c - '#');
if( dv>87 ) return 0xff;
return (dv > 3)? dv-3 : dv;
}
#endif
/* Width of base64 lines. Should be an integer multiple of 5. */
#define B85_DARK_MAX 80
static char * skipNonB85( char *s ){
char c;
while( (c = *s) && !IS_B85(c) ) ++s;
return s;
}
/* Convert small integer, known to be in 0..84 inclusive, to base85 numeral.
* Do not use the macro form with argument expression having a side-effect.*/
#if 0
static char base85Numeral( u8 b ){
return (b < 4)? (char)(b + '#') : (char)(b - 4 + '*');
}
#else
# define base85Numeral( dn )\
((char)(((dn) < 4)? (char)((dn) + '#') : (char)((dn) - 4 + '*')))
#endif
static char *putcs(char *pc, char *s){
char c;
while( (c = *s++)!=0 ) *pc++ = c;
return pc;
}
/* Encode a byte buffer into base85 text. If pSep!=0, it's a C string
** to be appended to encoded groups to limit their length to B85_DARK_MAX
** or to terminate the last group (to aid concatenation.)
*/
static char* toBase85( u8 *pIn, int nbIn, char *pOut, char *pSep ){
int nCol = 0;
while( nbIn >= 4 ){
int nco = 5;
unsigned long qbv = (((unsigned long)pIn[0])<<24) |
(pIn[1]<<16) | (pIn[2]<<8) | pIn[3];
while( nco > 0 ){
unsigned nqv = (unsigned)(qbv/85UL);
unsigned char dv = qbv - 85UL*nqv;
qbv = nqv;
pOut[--nco] = base85Numeral(dv);
}
nbIn -= 4;
pIn += 4;
pOut += 5;
if( pSep && (nCol += 5)>=B85_DARK_MAX ){
pOut = putcs(pOut, pSep);
nCol = 0;
}
}
if( nbIn > 0 ){
int nco = nbIn + 1;
unsigned long qv = *pIn++;
int nbe = 1;
while( nbe++ < nbIn ){
qv = (qv<<8) | *pIn++;
}
nCol += nco;
while( nco > 0 ){
u8 dv = (u8)(qv % 85);
qv /= 85;
pOut[--nco] = base85Numeral(dv);
}
pOut += (nbIn+1);
}
if( pSep && nCol>0 ) pOut = putcs(pOut, pSep);
*pOut = 0;
return pOut;
}
/* Decode base85 text into a byte buffer. */
static u8* fromBase85( char *pIn, int ncIn, u8 *pOut ){
if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn;
while( ncIn>0 ){
static signed char nboi[] = { 0, 0, 1, 2, 3, 4 };
char *pUse = skipNonB85(pIn);
unsigned long qv = 0L;
int nti, nbo;
ncIn -= (pUse - pIn);
pIn = pUse;
nti = (ncIn>5)? 5 : ncIn;
nbo = nboi[nti];
if( nbo==0 ) break;
while( nti>0 ){
char c = *pIn++;
u8 cdo = B85_DNOS(c);
--ncIn;
if( cdo==0 ) break;
qv = 85 * qv + (c - cdo);
--nti;
}
nbo -= nti; /* Adjust for early (non-digit) end of group. */
switch( nbo ){
case 4:
*pOut++ = (qv >> 24)&0xff;
case 3:
*pOut++ = (qv >> 16)&0xff;
case 2:
*pOut++ = (qv >> 8)&0xff;
case 1:
*pOut++ = qv&0xff;
case 0:
break;
}
}
return pOut;
}
#ifndef OMIT_BASE85_CHECKER
/* Say whether input char sequence is all (base85 and/or whitespace).*/
static int allBase85( char *p, int len ){
char c;
while( len-- > 0 && (c = *p++) != 0 ){
if( !IS_B85(c) && !isspace(c) ) return 0;
}
return 1;
}
#endif
#ifndef BASE85_STANDALONE
# ifndef OMIT_BASE85_CHECKER
/* This function does the work for the SQLite is_base85(t) UDF. */
static void is_base85(sqlite3_context *context, int na, sqlite3_value *av[]){
assert(na==1);
switch( sqlite3_value_type(av[0]) ){
case SQLITE_TEXT:
{
int rv = allBase85( (char *)sqlite3_value_text(av[0]),
sqlite3_value_bytes(av[0]) );
sqlite3_result_int(context, rv);
}
break;
case SQLITE_NULL:
sqlite3_result_null(context);
break;
default:
sqlite3_result_error(context, "is_base85 accepts only text or NULL", -1);
return;
}
}
# endif
/* This function does the work for the SQLite base85(x) UDF. */
static void base85(sqlite3_context *context, int na, sqlite3_value *av[]){
int nb, nc, nv = sqlite3_value_bytes(av[0]);
int nvMax = sqlite3_limit(sqlite3_context_db_handle(context),
SQLITE_LIMIT_LENGTH, -1);
char *cBuf;
u8 *bBuf;
assert(na==1);
switch( sqlite3_value_type(av[0]) ){
case SQLITE_BLOB:
nb = nv;
/* ulongs tail newlines tailenc+nul*/
nc = 5*(nv/4) + nv%4 + nv/64+1 + 2;
if( nvMax < nc ){
sqlite3_result_error(context, "blob expanded to base85 too big", -1);
return;
}
cBuf = sqlite3_malloc(nc);
if( !cBuf ) goto memFail;
bBuf = (u8*)sqlite3_value_blob(av[0]);
nc = (int)(toBase85(bBuf, nb, cBuf, "\n") - cBuf);
sqlite3_result_text(context, cBuf, nc, sqlite3_free);
break;
case SQLITE_TEXT:
nc = nv;
nb = 4*(nv/5) + nv%5; /* may overestimate */
if( nvMax < nb ){
sqlite3_result_error(context, "blob from base85 may be too big", -1);
return;
}else if( nb<1 ){
nb = 1;
}
bBuf = sqlite3_malloc(nb);
if( !bBuf ) goto memFail;
cBuf = (char *)sqlite3_value_text(av[0]);
nb = (int)(fromBase85(cBuf, nc, bBuf) - bBuf);
sqlite3_result_blob(context, bBuf, nb, sqlite3_free);
break;
default:
sqlite3_result_error(context, "base85 accepts only blob or text.", -1);
return;
}
return;
memFail:
sqlite3_result_error(context, "base85 OOM", -1);
}
/*
** Establish linkage to running SQLite library.
*/
#ifndef SQLITE_SHELL_EXTFUNCS
#ifdef _WIN32
__declspec(dllexport)
#endif
int sqlite3_base_init
#else
static int sqlite3_base85_init
#endif
(sqlite3 *db, char **pzErr, const sqlite3_api_routines *pApi){
SQLITE_EXTENSION_INIT2(pApi);
(void)pzErr;
# ifndef OMIT_BASE85_CHECKER
{
int rc = sqlite3_create_function
(db, "is_base85", 1,
SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_UTF8,
0, is_base85, 0, 0);
if( rc!=SQLITE_OK ) return rc;
}
# endif
return sqlite3_create_function
(db, "base85", 1,
SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_DIRECTONLY|SQLITE_UTF8,
0, base85, 0, 0);
}
/*
** Define some macros to allow this extension to be built into the shell
** conveniently, in conjunction with use of SQLITE_SHELL_EXTFUNCS. This
** allows shell.c, as distributed, to have this extension built in.
*/
# define BASE85_INIT(db) sqlite3_base85_init(db, 0, 0)
# define BASE85_EXPOSE(db, pzErr) /* Not needed, ..._init() does this. */
#else /* standalone program */
int main(int na, char *av[]){
int cin;
int rc = 0;
u8 bBuf[4*(B85_DARK_MAX/5)];
char cBuf[5*(sizeof(bBuf)/4)+2];
size_t nio;
# ifndef OMIT_BASE85_CHECKER
int b85Clean = 1;
# endif
char rw;
FILE *fb = 0, *foc = 0;
char fmode[3] = "xb";
if( na < 3 || av[1][0]!='-' || (rw = av[1][1])==0 || (rw!='r' && rw!='w') ){
sayHelp();
return 0;
}
fmode[0] = rw;
if( av[2][0]=='-' && av[2][1]==0 ){
switch( rw ){
case 'r':
fb = stdin;
setmode(fileno(stdin), O_BINARY);
break;
case 'w':
fb = stdout;
setmode(fileno(stdout), O_BINARY);
break;
}
}else{
fb = fopen(av[2], fmode);
foc = fb;
}
if( !fb ){
fprintf(stderr, "Cannot open %s for %c\n", av[2], rw);
rc = 1;
}else{
switch( rw ){
case 'r':
while( (nio = fread( bBuf, 1, sizeof(bBuf), fb))>0 ){
toBase85( bBuf, (int)nio, cBuf, 0 );
fprintf(stdout, "%s\n", cBuf);
}
break;
case 'w':
while( 0 != fgets(cBuf, sizeof(cBuf), stdin) ){
int nc = strlen(cBuf);
size_t nbo = fromBase85( cBuf, nc, bBuf ) - bBuf;
if( 1 != fwrite(bBuf, nbo, 1, fb) ) rc = 1;
# ifndef OMIT_BASE85_CHECKER
b85Clean &= allBase85( cBuf, nc );
# endif
}
break;
default:
sayHelp();
rc = 1;
}
if( foc ) fclose(foc);
}
# ifndef OMIT_BASE85_CHECKER
if( !b85Clean ){
fprintf(stderr, "Base85 input had non-base85 dark or control content.\n");
}
# endif
return rc;
}
#endif
|
b45ca69f93719df9a1a29f0d78d71d5e4a31782d
|
aa3befea459382dc5c01c925653d54f435b3fb0f
|
/libs/libc/aio/aio_error.c
|
f0d3268399e1b3b3e8cf0385a9e7f9c1b850c78e
|
[
"MIT-open-group",
"BSD-3-Clause",
"HPND-sell-variant",
"BSD-4-Clause-UC",
"LicenseRef-scancode-warranty-disclaimer",
"MIT-0",
"LicenseRef-scancode-bsd-atmel",
"LicenseRef-scancode-gary-s-brown",
"LicenseRef-scancode-proprietary-license",
"SunPro",
"MIT",
"LicenseRef-scancode-public-domain-disclaimer",
"LicenseRef-scancode-other-permissive",
"HPND",
"ISC",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"GPL-1.0-or-later",
"CC-BY-2.0",
"CC-BY-4.0"
] |
permissive
|
apache/nuttx
|
14519a7bff4a87935d94fb8fb2b19edb501c7cec
|
606b6d9310fb25c7d92c6f95bf61737e3c79fa0f
|
refs/heads/master
| 2023-08-25T06:55:45.822534
| 2023-08-23T16:03:31
| 2023-08-24T21:25:47
| 228,103,273
| 407
| 241
|
Apache-2.0
| 2023-09-14T18:26:05
| 2019-12-14T23:27:55
|
C
|
UTF-8
|
C
| false
| false
| 3,993
|
c
|
aio_error.c
|
/****************************************************************************
* libs/libc/aio/aio_error.c
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <aio.h>
#include <assert.h>
#include <errno.h>
#ifdef CONFIG_FS_AIO
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/* Configuration ************************************************************/
/****************************************************************************
* Private Types
****************************************************************************/
/****************************************************************************
* Private Data
****************************************************************************/
/****************************************************************************
* Public Data
****************************************************************************/
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: aio_error
*
* Description:
* The aio_error() function returns the error status associated with the
* aiocb structure referenced by the aiocbp argument. The error status fo
* an asynchronous I/O operation is the errno value that would be set by
* the corresponding read(), write(), fdatasync(), or fsync() operation. If
* the operation has not yet completed, then the error status will be equal
* to EINPROGRESS.
*
* Input Parameters:
* aiocbp - A pointer to an instance of struct aiocb
*
* Returned Value:
* If the asynchronous I/O operation has completed successfully, then 0
* will be returned. If the asynchronous operation has completed
* unsuccessfully, then the error status, as described for read(),
* write(), fdatasync(), and fsync(), will be returned. If the
* asynchronous I/O operation has not yet completed, then EINPROGRESS will
* be returned.
*
* The aio_error() function may fail if:
*
* EINVAL - The aiocbp argument does not refer to an asynchronous
* operation whose return status has not yet been retrieved.
*
****************************************************************************/
int aio_error(FAR const struct aiocb *aiocbp)
{
DEBUGASSERT(aiocbp);
/* the aio_reqprio field must be large or equal than 0 */
if (aiocbp->aio_reqprio < 0)
{
return EINVAL;
}
if (aiocbp->aio_result < 0)
{
return -aiocbp->aio_result;
}
return OK;
}
#endif /* CONFIG_FS_AIO */
|
599d6286b20987daf37461056cfa40a2e8d7cf10
|
83e7dc1281874779c46dfadcc15b2bb66d8e599c
|
/examples/widgets/obj/lv_example_obj_1.c
|
9c5ff7a05690920d863db936166fe7dfeafb6d07
|
[
"MIT"
] |
permissive
|
lvgl/lvgl
|
7d51d6774d6ac71df7101fc7ded56fea4b70be01
|
5c984b4a5364b6455966eb3a860153806c51626f
|
refs/heads/master
| 2023-08-30T22:39:20.283922
| 2023-08-30T19:55:29
| 2023-08-30T19:55:29
| 60,667,730
| 9,296
| 2,218
|
MIT
| 2023-09-14T17:59:34
| 2016-06-08T04:14:34
|
C
|
UTF-8
|
C
| false
| false
| 649
|
c
|
lv_example_obj_1.c
|
#include "../../lv_examples.h"
#if LV_BUILD_EXAMPLES
void lv_example_obj_1(void)
{
lv_obj_t * obj1;
obj1 = lv_obj_create(lv_scr_act());
lv_obj_set_size(obj1, 100, 50);
lv_obj_align(obj1, LV_ALIGN_CENTER, -60, -30);
static lv_style_t style_shadow;
lv_style_init(&style_shadow);
lv_style_set_shadow_width(&style_shadow, 10);
lv_style_set_shadow_spread(&style_shadow, 5);
lv_style_set_shadow_color(&style_shadow, lv_palette_main(LV_PALETTE_BLUE));
lv_obj_t * obj2;
obj2 = lv_obj_create(lv_scr_act());
lv_obj_add_style(obj2, &style_shadow, 0);
lv_obj_align(obj2, LV_ALIGN_CENTER, 60, 30);
}
#endif
|
bb3f4a2cf70bce116c0335b80e57f79f39e78a28
|
0744dcc5394cebf57ebcba343747af6871b67017
|
/os/board/rtl8730e/src/component/utils/ipc/ipc-2.0/rtl8730e/include/ipc.h
|
56d8d0c56073ae198314dc5cc2ea445b64b472a1
|
[
"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
| 2,822
|
h
|
ipc.h
|
/*
* Copyright (c) 2022 Realtek, LLC.
* All rights reserved.
*
* Licensed under the Realtek License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License from Realtek
*
* 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 IPC_MESSAGE_H
#define IPC_MESSAGE_H
#include <stdint.h>
#include "ameba_ipc.h"
//#define DEBUG_ENABLE
#define TAG "[IPC_MSG]"
#define TAG_ERR "[IPC_MSG][ERR]"
#ifdef DEBUG_ENABLE
#define IPC_LOGV(fmt, ...) printf(TAG fmt, ##__VA_ARGS__)
#else
#define IPC_LOGV(fmt, ...) do { } while(0)
#endif
#define IPC_LOGI(fmt, ...) printf(TAG fmt, ##__VA_ARGS__)
#define IPC_LOGE(fmt, ...) printf(TAG_ERR fmt, ##__VA_ARGS__)
#define NELEM(tab) (sizeof(tab) / sizeof((tab)[0]))
#define WAIT_FOREVER -1
#define IPC_RRAM RRAM
// LP IPC NOT USED, JUST DEFINE
#define IPC_L2N_IMQ_TRX_TRAN 0xFF
#define IPC_N2L_IMQ_TRX_TRAN 0xFF
#define IPC_L2A_IMQ_TRX_TRAN 0xFF
#define IPC_A2L_IMQ_TRX_TRAN 0xFF
#if defined(ARM_CORE_CM4)
#define IPC_RX_TRAN_0 IPC_A2N_IMQ_TRX_TRAN
#define IPC_RX_TRAN_1 IPC_L2N_IMQ_TRX_TRAN
#define IPC_TX_TRAN_0 IPC_N2A_IMQ_TRX_TRAN
#define IPC_TX_TRAN_1 IPC_N2L_IMQ_TRX_TRAN
#define IPC_DIR_MSG_RX_0 IPC_AP_TO_NP
#define IPC_DIR_MSG_RX_1 IPC_LP_TO_NP
#elif defined(ARM_CORE_CA32)
#define IPC_RX_TRAN_0 IPC_N2A_IMQ_TRX_TRAN
#define IPC_RX_TRAN_1 IPC_L2A_IMQ_TRX_TRAN
#define IPC_TX_TRAN_0 IPC_A2N_IMQ_TRX_TRAN
#define IPC_TX_TRAN_1 IPC_A2L_IMQ_TRX_TRAN
#define IPC_DIR_MSG_RX_0 IPC_NP_TO_AP
#define IPC_DIR_MSG_RX_1 IPC_LP_TO_AP
#else //ARM_CORE_CM0
#define IPC_RX_TRAN_0 IPC_A2L_IMQ_TRX_TRAN
#define IPC_RX_TRAN_1 IPC_N2L_IMQ_TRX_TRAN
#define IPC_TX_TRAN_0 IPC_L2A_IMQ_TRX_TRAN
#define IPC_TX_TRAN_1 IPC_L2N_IMQ_TRX_TRAN
#define IPC_DIR_MSG_RX_0 IPC_AP_TO_LP
#define IPC_DIR_MSG_RX_1 IPC_NP_TO_LP
#endif
typedef enum {
IPC_ID_NP_TO_AP = 0,
IPC_ID_AP_TO_NP = 1,
/*14-19 used for RPC*/
IPC_ID_NUM = 20
} IPC_ID;
typedef enum {
IPC_SUCCESS = 0,
IPC_ERROR = -1,
IPC_INVALID_CH = -2,
IPC_INVALID_SIZE = -3,
IPC_NO_MEMORY = -4,
IPC_NOT_INIT = -5,
IPC_TX_TIMEOUT = -6,
IPC_RX_TIMEOUT = -7,
IPC_TX_ERROR = -8,
IPC_RX_ERROR = -9,
} ipc_error_t;
typedef struct {
uint32_t id;
uint8_t dir;
} IMQ2_INIT_TABLE;
int32_t IPC2_Message_Queue_Init(void);
int32_t IPC2_Message_Queue_Send(uint32_t id, uint8_t *buf, uint32_t size, int32_t timeout);
int32_t IPC2_Message_Queue_Recv(uint32_t id, uint8_t *buf, uint32_t *size);
#endif //IPC_MESSAGE_H
|
9541be2e70021552d39a8681928772de71933525
|
cc5ec0714e290895bc04c6c6292ae29b3236c658
|
/materials.h
|
a6b4b6a7d02b9efb6f73b7f42d1db8b259b38311
|
[
"MIT"
] |
permissive
|
hankmorgan/UnderworldExporter
|
bde6f99e4a5fca1a3deedef4b2f8ac3d31c66316
|
3907ffe900709fe7abf5cea6373a4d6661dea3aa
|
refs/heads/master
| 2023-07-20T12:32:01.499701
| 2023-07-15T11:47:17
| 2023-07-15T11:47:17
| 15,637,144
| 321
| 23
|
MIT
| 2020-05-22T20:10:59
| 2014-01-04T18:24:07
|
C#
|
UTF-8
|
C
| false
| false
| 374
|
h
|
materials.h
|
#ifndef materials_h
#define materials_h
void BuildXDataFile(int game);
void BuildSndShaderFiles();
void BuildSHOCKMtrFiles(int MtrType);
void BuildGuiFiles();
void ExportModelFormat();
void BuildWORDSXData(int game);
void BuildUWXData(int game, int TargetBlock);
void BuildUWMtrFiles(int game, int mtrType);
void BuildParticles(int game);
#endif /*materials_h*/
|
425bfa9a0bd79575b2bccf037fb71d9f424a96d7
|
ff477a586b946c575441b6189123ab86c175e5ae
|
/samtools/bam_import.c
|
14ff0b0de7f81d10f79de0c987c5968aef2c3961
|
[
"MIT",
"LicenseRef-scancode-proprietary-license"
] |
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
| 15,912
|
c
|
bam_import.c
|
/* bam_import -- Import of FASTQ files.
*
* samtools import -1 a_1.fq -2 a_2.fq --i1 a_i1.fq --i2 a_i2.fq
* samtools import a_1.fq a_2.fq
* samtools import a_interleaved.fq
*
* Copyright (C) 2020-2021 Genome Research Ltd.
*
* Author: James Bonfield <jkb@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 notices 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.
*/
// TODO: Store other non-aux comments; in new sam tag?
#include <config.h>
#include <ctype.h>
#include "htslib/sam.h"
#include "htslib/thread_pool.h"
#include "samtools.h"
#include "sam_opts.h"
static int usage(FILE *fp, int exit_status) {
fprintf(fp, "Usage: samtools import [options] [file.fastq ...]\n");
fprintf(fp, "\n");
fprintf(fp, "Options:\n");
fprintf(fp, " -s FILE Read paired-ended data from single FILE\n");
fprintf(fp, " -0 FILE Read single-ended data from FILE\n");
fprintf(fp, " -1 FILE Read-1 from FILE\n");
fprintf(fp, " -2 FILE Read-2 from FILE\n");
fprintf(fp, " --i1 FILE Index-1 from FILE\n");
fprintf(fp, " --i2 FILE Index-2 from FILE\n");
fprintf(fp, " -i Parse CASAVA identifier\n");
fprintf(fp, " --barcode-tag TAG\n");
fprintf(fp, " Tag to use with barcode sequences [BC]\n");
fprintf(fp, " --quality-tag TAG\n");
fprintf(fp, " Tag to use with barcode qualities [QT]\n");
fprintf(fp, " -N, --name2 Use 2nd field as read name (SRA format)\n");
fprintf(fp, " -r STRING Build up a complete @RG line\n");
fprintf(fp, " -R STRING Add a simple RG line of \"@RG\\tID:STRING\"\n");
fprintf(fp, " -T TAGLIST Parse tags in SAM format; list of '*' for all\n");
fprintf(fp, " -o FILE Output to FILE instead of stdout\n");
fprintf(fp, " -u Uncompressed output\n");
fprintf(fp, " --order TAG Store Nth record count in TAG\n");
fprintf(fp, "\n");
sam_global_opt_help(fp, "-.O.-@--");
fprintf(fp, "\nA single fastq file will be interpreted as -s, -0 or -1 depending on\n");
fprintf(fp, "file contents, and a pair of fastq files as \"-1 FILE1 -2 FILE2\".\n");
return exit_status;
}
// Order matters here as we want to read index elements before main
// sequences so on reading the seqs we can emit a fully annotated record.
enum fileno {
FQ_I1, FQ_I2, // index seqs for R1 and R2
FQ_R0, // single file and unpaired data (singled-ended tech).
FQ_R1, FQ_R2, // separate read1 and read2 files
FQ_SINGLE, // single file, but with read1 and/or read2 present.
FQ_END
};
typedef struct {
sam_global_args ga;
int no_pg;
char *fn[FQ_END], *fn_out;
int idx_both; // add index to READ2 too, not just READ1
int casava;
char *barcode_seq;
char *barcode_qual;
char *aux;
char *rg;
char *rg_line;
char *order;
int compress_level;
htsThreadPool p;
int name2;
} opts_t;
// Append a sequence and quality string from a BAM record to a BC:Z and
// QT:Z style aux tag string.
static int append_index(kstring_t *s, kstring_t *q, bam1_t *b) {
char *sp, *qp;
if (ks_resize(s, s->l + b->core.l_qseq+1 +1) < 0)
return -1;
if (ks_resize(q, q->l + b->core.l_qseq+1 +1) < 0)
return -1;
sp = s->s + s->l - (s->l > 0);
qp = q->s + q->l - (q->l > 0);
if (s->l)
*sp++ = '-';
if (q->l)
*qp++ = ' ';
int i;
uint8_t *seq = bam_get_seq(b);
uint8_t *qual = bam_get_qual(b);
for (i = 0; i < b->core.l_qseq; i++) {
*sp++ = seq_nt16_str[bam_seqi(seq, i)];
*qp++ = qual[i] + '!';
}
*sp++ = 0;
*qp++ = 0;
s->l = sp - s->s;
q->l = qp - q->s;
return 0;
}
static int import_fastq(int argc, char **argv, opts_t *opts) {
int i, n, ret = 0;
samFile *fp_in[FQ_END] = {NULL};
bam1_t *b = bam_init1();
int ids[FQ_END];
samFile *fp_out = NULL;
sam_hdr_t *hdr_out = NULL;
kstring_t index_str = {0,0};
kstring_t read_str = {0,0};
char *rg = opts->rg;
kstring_t rg_line = {0,0};
uint64_t read_num = 0;
kstring_t idx_seq = {0};
kstring_t idx_qual = {0};
// Any additional arguments are assumed to be r1 r2, as a
// short cut. We support reading index tags out of those too (eg
// Illumina CASAVA format), but if we do that we lack the barcode
// quality string.
//
// We also consider a read name ending in /1 or /2 to be a single
// file containing interleaved fastq records for both ends.
// These will be labeled as fn[FQ_R1] but adjusted during reading.
if (argc == 1)
opts->fn[FQ_SINGLE] = argv[0];
else
for (i = 0; i < 4; i++)
if (argc > i)
opts->fn[FQ_R1+i] = argv[i];
// Open all files
for (i = n = 0; i < FQ_END; i++) {
if (!opts->fn[i])
continue;
fp_in[i] = sam_open_format(opts->fn[i], "r", &opts->ga.in);
if (!fp_in[i]) {
perror(opts->fn[i]);
ret = -1;
goto err;
}
if (opts->p.pool)
hts_set_thread_pool(fp_in[i], &opts->p);
ids[n++] = i;
if (opts->name2)
hts_set_opt(fp_in[i], FASTQ_OPT_NAME2, 1);
if (opts->casava)
hts_set_opt(fp_in[i], FASTQ_OPT_CASAVA, 1);
if (opts->barcode_seq) // for auto-CASAVA parsing
hts_set_opt(fp_in[i], FASTQ_OPT_BARCODE, opts->barcode_seq);
if (opts->aux)
hts_set_opt(fp_in[i], FASTQ_OPT_AUX,
*opts->aux == '*' || *opts->aux == '\0'
? NULL : opts->aux);
switch (i) {
case FQ_I1:
kputs("--i1 I1.fastq ", &read_str);
kputs("i*", &index_str);
break;
case FQ_I2:
kputs("--i2 I2.fastq ", &read_str);
kputs("i*", &index_str);
break;
case FQ_R0:
kputs("-0 unpaired.fastq ", &read_str);
break;
case FQ_R1:
kputs("-1 R1.fastq ", &read_str);
break;
case FQ_R2:
kputs("-2 R2.fastq ", &read_str);
break;
case FQ_SINGLE:
kputs("-N -o paired.fastq ", &read_str);
break;
default:
ks_clear(&read_str); // not reversible
kputs("", &read_str);
}
}
if (n == 0) {
bam_destroy1(b);
return usage(stdout, EXIT_SUCCESS);
}
char out_mode[10] = {'w', 0, 0};
if (opts->compress_level != -1)
out_mode[1] = '0' + opts->compress_level;
sam_open_mode(out_mode+strlen(out_mode), opts->fn_out, NULL);
fp_out = sam_open_format(opts->fn_out, out_mode, &opts->ga.out);
if (!fp_out) {
perror(opts->fn_out);
goto err;
}
autoflush_if_stdout(fp_out, opts->fn_out);
if (opts->p.pool)
hts_set_thread_pool(fp_out, &opts->p);
// Create header
if (ks_len(&read_str)) {
char CO[2100];
if (ks_len(&index_str))
snprintf(CO, sizeof(CO), "@CO\tReverse with: samtools fastq %s "
"--index-format=\"%s\"\n",
ks_str(&read_str), ks_str(&index_str));
else
snprintf(CO, sizeof(CO), "@CO\tReverse with: samtools fastq %s\n",
ks_str(&read_str));
hdr_out = sam_hdr_parse(strlen(CO), CO);
} else {
hdr_out = sam_hdr_init();
}
// Add a version line with the sort order to the output header
if (sam_hdr_add_line(hdr_out, "HD", "VN", SAM_FORMAT_VERSION, "SO", "unsorted", "GO", "query", NULL) < 0) {
fprintf(stderr, "Could not set SO and GO in the header.\n");
goto err;
}
// Read group
if (opts->rg_line) {
if (*opts->rg_line != '@')
ksprintf(&rg_line, "@RG\t%s", opts->rg_line);
else
kputs(opts->rg_line, &rg_line);
} else if (opts->rg) {
ksprintf(&rg_line, "@RG\tID:%s", opts->rg);
}
if (ks_len(&rg_line)) {
if (sam_hdr_add_lines(hdr_out, ks_str(&rg_line), 0) < 0)
goto err;
rg = strstr(ks_str(&rg_line), "\tID:");
if (!rg) {
fprintf(stderr, "\"-r RG-LINE\" option contained no ID field\n");
goto err;
}
rg += 4;
i = 0;
while (rg[i] != '\t' && rg[i] != '\0')
i++;
rg[i] = 0;
}
if ((ret = sam_hdr_write(fp_out, hdr_out)) < 0)
goto err;
// Interleave / combine from n files (ids[0..n-1]).
int res;
int eof = 0;
do {
idx_seq.l = idx_qual.l = 0;
for (i = 0; i < n; i++) {
if ((res = sam_read1(fp_in[ids[i]], NULL, b)) < 0) {
if (res == -1) {
eof++;
continue;
} else
break;
}
// index
if (ids[i] == FQ_I1 || ids[i] == FQ_I2) {
if (append_index(&idx_seq, &idx_qual, b) < 0) {
res = -1;
break;
}
continue;
}
// full read
if (idx_seq.l) {
if (opts->idx_both || ids[i] == FQ_SINGLE ||
ids[i] == FQ_R0 || ids[i] == FQ_R1) {
if (bam_aux_append(b, opts->barcode_seq, 'Z', idx_seq.l,
(uint8_t *)idx_seq.s) ||
bam_aux_append(b, opts->barcode_qual, 'Z', idx_qual.l,
(uint8_t *)idx_qual.s)) {
res = -1;
break;
}
}
}
switch(ids[i]) {
case FQ_R0:
// unpaired; no flags to declare
break;
case FQ_SINGLE:
// paired (but don't know if R1 or R2) or unpaired.
// We rely on the /1 and /2 read suffix parsing in htslib
// to distinguish the two cases, or CASAVA tags if
// explicitly enabled.
break;
case FQ_R1:
if ((b->core.flag & (BAM_FREAD1 | BAM_FREAD2)) == 0)
b->core.flag |= BAM_FREAD1;
b->core.flag |= BAM_FPAIRED;
if (i+1 < n && ids[i+1] == FQ_R2)
b->core.flag |= BAM_FMUNMAP;
break;
case FQ_R2:
b->core.flag |= BAM_FPAIRED | BAM_FREAD2;
if (i > 0 && ids[i-1] == FQ_R1)
b->core.flag |= BAM_FMUNMAP;
break;
}
if (rg) {
if (bam_aux_append(b, "RG", 'Z', strlen(rg)+1,
(uint8_t *)rg) < 0) {
ret = -1;
goto err;
}
}
if (opts->order) {
if (bam_aux_update_int(b, opts->order, read_num++) < 0) {
ret = -1;
goto err;
}
}
res = sam_write1(fp_out, hdr_out, b);
}
} while (res >= 0);
if (res != -1) {
print_error("import", "truncated file. Aborting");
ret = res;
goto err;
}
if (eof != n) {
print_error("import", "input files with differing number of records");
ret = -1;
goto err;
}
// Close and return
ret = 0;
err:
bam_destroy1(b);
sam_hdr_destroy(hdr_out);
ks_free(&rg_line);
ks_free(&index_str);
ks_free(&read_str);
if (fp_out) {
release_autoflush(fp_out);
if (sam_close(fp_out) < 0) {
perror(opts->fn_out);
ret |= -1;
}
}
for (i = 0; i < FQ_END; i++) {
if (fp_in[i] && sam_close(fp_in[i]) < 0) {
perror(opts->fn[i]);
ret |= -1;
}
}
ks_free(&idx_seq);
ks_free(&idx_qual);
return ret;
}
int main_import(int argc, char *argv[]) {
int c;
opts_t opts = {
.no_pg = 0,
.ga = SAM_GLOBAL_ARGS_INIT,
.fn = {NULL},
.fn_out = "-",
.casava = 0,
.barcode_seq = "BC",
.barcode_qual = "QT",
.aux = NULL,
.rg = NULL,
.rg_line = NULL,
.order = NULL,
.compress_level = -1,
.name2 = 0,
};
kstring_t rg = {0};
static const struct option lopts[] = {
SAM_OPT_GLOBAL_OPTIONS('-', 0, 'O', 0, '-', '@'),
{"no-PG", no_argument, NULL, 9},
{"i1", required_argument, NULL, 1},
{"i2", required_argument, NULL, 2},
{"r1", required_argument, NULL, '1'},
{"r2", required_argument, NULL, '2'},
{"rg", required_argument, NULL, 'R'},
{"rg-line", required_argument, NULL, 'r'},
{"order", required_argument, NULL, 3},
{"barcode-tag", required_argument, NULL, 4},
{"quality-tag", required_argument, NULL, 5},
{"name2", no_argument, NULL, 'N'},
{ NULL, 0, NULL, 0 }
};
while ((c = getopt_long(argc, argv, "1:2:s:0:bhiT:r:R:o:O:u@:N", lopts, NULL)) >= 0) {
switch (c) {
case 'b': opts.idx_both = 1; break;
case '0': opts.fn[FQ_R0] = optarg; break;
case '1': opts.fn[FQ_R1] = optarg; break;
case '2': opts.fn[FQ_R2] = optarg; break;
case 1: opts.fn[FQ_I1] = optarg; break;
case 2: opts.fn[FQ_I2] = optarg; break;
case 's': opts.fn[FQ_SINGLE] = optarg; break;
case 'o': opts.fn_out = optarg; break;
case 'i': opts.casava = 1; break;
case 4: opts.barcode_seq = optarg; break;
case 5: opts.barcode_qual = optarg; break;
case 'T': opts.aux = optarg; break;
case 'u': opts.compress_level = 0; break;
case 'R': opts.rg = optarg; break;
case 'r':
if (*optarg != '@' && ks_len(&rg) == 0)
kputs("@RG", &rg);
if (ks_len(&rg))
kputc_('\t', &rg);
kputs(optarg, &rg);
opts.rg_line = rg.s;
break;
case 'N': opts.name2 = 1; break;
case 9: opts.no_pg = 1; break;
case 3: opts.order = optarg; break;
case 'h': return usage(stdout, EXIT_SUCCESS);
case '?': return usage(stderr, EXIT_FAILURE);
default:
if (parse_sam_global_opt(c, optarg, lopts, &opts.ga) != 0)
return usage(stderr, EXIT_FAILURE);
break;
}
}
if (opts.ga.nthreads > 0) {
if (!(opts.p.pool = hts_tpool_init(opts.ga.nthreads))) {
fprintf(stderr, "Failed to create thread pool\n");
if (rg.s)
free(rg.s);
return -1;;
}
}
int ret = import_fastq(argc-optind, argv+optind, &opts) ? 1 : 0;
if (rg.s)
free(rg.s);
if (opts.p.pool)
hts_tpool_destroy(opts.p.pool);
return ret;
}
|
59b6b08579325719a22450d2ee109e2c229714fa
|
257934c726f465f2074f501e2cd58c36d7de84c9
|
/deps/subhook/tests/test.c
|
d8b39fda6965583a98252470d05a744e507d8a54
|
[
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] |
permissive
|
Zeex/samp-plugin-crashdetect
|
8bc71097c52a5522e801aa183f088e2d8554f262
|
a2b61f0f10c37c1762467a6979e7ddc6db27dc9d
|
refs/heads/master
| 2023-08-29T14:07:51.608644
| 2023-08-18T08:04:32
| 2023-08-18T08:04:32
| 3,925,501
| 106
| 35
|
BSD-2-Clause
| 2023-08-26T17:41:41
| 2012-04-04T04:36:38
|
C
|
UTF-8
|
C
| false
| false
| 1,747
|
c
|
test.c
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <subhook.h>
typedef void (*foo_func_t)(void);
#ifdef SUBHOOK_X86
#if defined SUBHOOK_WINDOWS
#define FOO_CALL __cdecl
#elif defined SUBHOOK_UNIX
#define FOO_CALL __attribute__((cdecl))
#endif
#endif
#ifndef FOO_CALL
#define FOO_CALL
#endif
extern void FOO_CALL foo(void);
foo_func_t foo_tr = NULL;
void foo_hooked(void) {
puts("foo_hooked() called");
}
void foo_hooked_tr(void) {
puts("foo_hooked_tr() called");
foo_tr();
}
int main() {
puts("Testing initial install");
subhook_t foo_hook = subhook_new((void *)foo,
(void *)foo_hooked,
SUBHOOK_64BIT_OFFSET);
if (foo_hook == NULL || subhook_install(foo_hook) < 0) {
puts("Install failed");
return EXIT_FAILURE;
}
foo();
if (subhook_remove(foo_hook) < 0) {
puts("Remove failed");
return EXIT_FAILURE;
}
foo();
puts("Testing re-install");
if (subhook_install(foo_hook) < 0) {
puts("Install failed");
return EXIT_FAILURE;
}
foo();
if (subhook_remove(foo_hook) < 0) {
puts("Remove failed");
return EXIT_FAILURE;
}
foo();
subhook_free(foo_hook);
puts("Testing trampoline");
subhook_t foo_hook_tr = subhook_new((void *)foo,
(void *)foo_hooked_tr,
SUBHOOK_64BIT_OFFSET);
if (subhook_install(foo_hook_tr) < 0) {
puts("Install failed");
return EXIT_FAILURE;
}
foo_tr = (foo_func_t)subhook_get_trampoline(foo_hook_tr);
if (foo_tr == NULL) {
puts("Failed to build trampoline");
return EXIT_FAILURE;
}
foo();
subhook_free(foo_hook_tr);
return EXIT_SUCCESS;
}
|
e42e70acd310fd67c6e2a98da99ddab53fc964a9
|
9ceacf33fd96913cac7ef15492c126d96cae6911
|
/lib/libc/thread/rthread_libc.c
|
2a117c14f6ed24f7f0810771342f0bf66d60697b
|
[] |
no_license
|
openbsd/src
|
ab97ef834fd2d5a7f6729814665e9782b586c130
|
9e79f3a0ebd11a25b4bff61e900cb6de9e7795e9
|
refs/heads/master
| 2023-09-02T18:54:56.624627
| 2023-09-02T15:16:12
| 2023-09-02T15:16:12
| 66,966,208
| 3,394
| 1,235
| null | 2023-08-08T02:42:25
| 2016-08-30T18:18:25
|
C
|
UTF-8
|
C
| false
| false
| 6,750
|
c
|
rthread_libc.c
|
/* $OpenBSD: rthread_libc.c,v 1.4 2021/01/06 19:54:17 otto Exp $ */
/* PUBLIC DOMAIN: No Rights Reserved. Marco S Hyman <marc@snafu.org> */
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include "rthread.h"
#include "rthread_cb.h"
/*
* A thread tag is a pointer to a structure of this type. An opaque
* tag is used to decouple libc from the thread library.
*/
struct _thread_tag {
pthread_mutex_t m; /* the tag's mutex */
pthread_key_t k; /* a key for private data */
};
/*
* local mutex to protect against tag creation races.
*/
static pthread_mutex_t _thread_tag_mutex = PTHREAD_MUTEX_INITIALIZER;
/*
* Initialize a thread tag structure once. This function is called
* if the tag is null. Allocation and initialization are controlled
* by a mutex. If the tag is not null when the mutex is obtained
* the caller lost a race -- some other thread initialized the tag.
* This function will never return NULL.
*/
static void
_thread_tag_init(void **tag, void (*dt)(void *))
{
struct _thread_tag *tt;
int result;
result = pthread_mutex_lock(&_thread_tag_mutex);
if (result == 0) {
if (*tag == NULL) {
tt = malloc(sizeof *tt);
if (tt != NULL) {
result = pthread_mutex_init(&tt->m, NULL);
result |= pthread_key_create(&tt->k, dt ? dt :
free);
*tag = tt;
}
}
result |= pthread_mutex_unlock(&_thread_tag_mutex);
}
if (result != 0)
_rthread_debug(1, "tag init failure");
}
/*
* lock the mutex associated with the given tag
*/
void
_thread_tag_lock(void **tag)
{
struct _thread_tag *tt;
if (__isthreaded) {
if (*tag == NULL)
_thread_tag_init(tag, NULL);
tt = *tag;
if (pthread_mutex_lock(&tt->m) != 0)
_rthread_debug(1, "tag mutex lock failure");
}
}
/*
* unlock the mutex associated with the given tag
*/
void
_thread_tag_unlock(void **tag)
{
struct _thread_tag *tt;
if (__isthreaded) {
if (*tag == NULL)
_thread_tag_init(tag, NULL);
tt = *tag;
if (pthread_mutex_unlock(&tt->m) != 0)
_rthread_debug(1, "tag mutex unlock failure");
}
}
/*
* return the thread specific data for the given tag. If there
* is no data for this thread allocate and initialize it from 'storage'
* or clear it for non-main threads.
* On any error return 'err'.
*/
void *
_thread_tag_storage(void **tag, void *storage, size_t sz, void (*dt)(void *),
void *err)
{
struct _thread_tag *tt;
void *ret;
if (*tag == NULL)
_thread_tag_init(tag, dt);
tt = *tag;
ret = pthread_getspecific(tt->k);
if (ret == NULL) {
ret = calloc(1, sz);
if (ret == NULL)
ret = err;
else {
if (pthread_setspecific(tt->k, ret) == 0) {
if (pthread_self() == &_initial_thread)
memcpy(ret, storage, sz);
} else {
free(ret);
ret = err;
}
}
}
return ret;
}
void
_thread_mutex_lock(void **mutex)
{
pthread_mutex_t *pmutex = (pthread_mutex_t *)mutex;
if (pthread_mutex_lock(pmutex) != 0)
_rthread_debug(1, "mutex lock failure");
}
void
_thread_mutex_unlock(void **mutex)
{
pthread_mutex_t *pmutex = (pthread_mutex_t *)mutex;
if (pthread_mutex_unlock(pmutex) != 0)
_rthread_debug(1, "mutex unlock failure");
}
void
_thread_mutex_destroy(void **mutex)
{
pthread_mutex_t *pmutex = (pthread_mutex_t *)mutex;
if (pthread_mutex_destroy(pmutex) != 0)
_rthread_debug(1, "mutex destroy failure");
}
/*
* the malloc lock
*/
#ifndef FUTEX
#define MALLOC_LOCK_INITIALIZER(n) { \
_SPINLOCK_UNLOCKED, \
TAILQ_HEAD_INITIALIZER(malloc_lock[n].lockers), \
PTHREAD_MUTEX_DEFAULT, \
NULL, \
0, \
-1 }
#else
#define MALLOC_LOCK_INITIALIZER(n) { \
_SPINLOCK_UNLOCKED, \
PTHREAD_MUTEX_DEFAULT, \
NULL, \
0, \
-1 }
#endif
static struct pthread_mutex malloc_lock[_MALLOC_MUTEXES] = {
MALLOC_LOCK_INITIALIZER(0),
MALLOC_LOCK_INITIALIZER(1),
MALLOC_LOCK_INITIALIZER(2),
MALLOC_LOCK_INITIALIZER(3),
MALLOC_LOCK_INITIALIZER(4),
MALLOC_LOCK_INITIALIZER(5),
MALLOC_LOCK_INITIALIZER(6),
MALLOC_LOCK_INITIALIZER(7),
MALLOC_LOCK_INITIALIZER(8),
MALLOC_LOCK_INITIALIZER(9),
MALLOC_LOCK_INITIALIZER(10),
MALLOC_LOCK_INITIALIZER(11),
MALLOC_LOCK_INITIALIZER(12),
MALLOC_LOCK_INITIALIZER(13),
MALLOC_LOCK_INITIALIZER(14),
MALLOC_LOCK_INITIALIZER(15),
MALLOC_LOCK_INITIALIZER(16),
MALLOC_LOCK_INITIALIZER(17),
MALLOC_LOCK_INITIALIZER(18),
MALLOC_LOCK_INITIALIZER(19),
MALLOC_LOCK_INITIALIZER(20),
MALLOC_LOCK_INITIALIZER(21),
MALLOC_LOCK_INITIALIZER(22),
MALLOC_LOCK_INITIALIZER(23),
MALLOC_LOCK_INITIALIZER(24),
MALLOC_LOCK_INITIALIZER(25),
MALLOC_LOCK_INITIALIZER(26),
MALLOC_LOCK_INITIALIZER(27),
MALLOC_LOCK_INITIALIZER(28),
MALLOC_LOCK_INITIALIZER(29),
MALLOC_LOCK_INITIALIZER(30),
MALLOC_LOCK_INITIALIZER(31)
};
static pthread_mutex_t malloc_mutex[_MALLOC_MUTEXES] = {
&malloc_lock[0],
&malloc_lock[1],
&malloc_lock[2],
&malloc_lock[3],
&malloc_lock[4],
&malloc_lock[5],
&malloc_lock[6],
&malloc_lock[7],
&malloc_lock[8],
&malloc_lock[9],
&malloc_lock[10],
&malloc_lock[11],
&malloc_lock[12],
&malloc_lock[13],
&malloc_lock[14],
&malloc_lock[15],
&malloc_lock[16],
&malloc_lock[17],
&malloc_lock[18],
&malloc_lock[19],
&malloc_lock[20],
&malloc_lock[21],
&malloc_lock[22],
&malloc_lock[23],
&malloc_lock[24],
&malloc_lock[25],
&malloc_lock[26],
&malloc_lock[27],
&malloc_lock[28],
&malloc_lock[29],
&malloc_lock[30],
&malloc_lock[31]
};
void
_thread_malloc_lock(int i)
{
pthread_mutex_lock(&malloc_mutex[i]);
}
void
_thread_malloc_unlock(int i)
{
pthread_mutex_unlock(&malloc_mutex[i]);
}
static void
_thread_malloc_reinit(void)
{
int i;
for (i = 0; i < _MALLOC_MUTEXES; i++) {
malloc_lock[i].lock = _SPINLOCK_UNLOCKED;
#ifndef FUTEX
TAILQ_INIT(&malloc_lock[i].lockers);
#endif
malloc_lock[i].owner = NULL;
malloc_lock[i].count = 0;
}
}
/*
* atexit lock
*/
static _atomic_lock_t atexit_lock = _SPINLOCK_UNLOCKED;
void
_thread_atexit_lock(void)
{
_spinlock(&atexit_lock);
}
void
_thread_atexit_unlock(void)
{
_spinunlock(&atexit_lock);
}
/*
* atfork lock
*/
static _atomic_lock_t atfork_lock = _SPINLOCK_UNLOCKED;
void
_thread_atfork_lock(void)
{
_spinlock(&atfork_lock);
}
void
_thread_atfork_unlock(void)
{
_spinunlock(&atfork_lock);
}
/*
* arc4random lock
*/
static _atomic_lock_t arc4_lock = _SPINLOCK_UNLOCKED;
void
_thread_arc4_lock(void)
{
_spinlock(&arc4_lock);
}
void
_thread_arc4_unlock(void)
{
_spinunlock(&arc4_lock);
}
pid_t
_thread_dofork(pid_t (*sys_fork)(void))
{
int i;
pid_t newid;
_thread_atexit_lock();
for (i = 0; i < _MALLOC_MUTEXES; i++)
_thread_malloc_lock(i);
_thread_arc4_lock();
newid = sys_fork();
_thread_arc4_unlock();
if (newid == 0)
_thread_malloc_reinit();
else
for (i = 0; i < _MALLOC_MUTEXES; i++)
_thread_malloc_unlock(i);
_thread_atexit_unlock();
return newid;
}
|
889f90841f4685b9f0e6030407b9d4060a51dc0d
|
8838eb997879add5759b6dfb23f9a646464e53ca
|
/src/drivers/video/lynxfb/ddk750_chip.c
|
a2e65e606e082c9a16969cdea20652c546b951bf
|
[
"BSD-2-Clause"
] |
permissive
|
embox/embox
|
d6aacec876978522f01cdc4b8de37a668c6f4c80
|
98e3c06e33f3fdac10a29c069c20775568e0a6d1
|
refs/heads/master
| 2023-09-04T03:02:20.165042
| 2023-09-02T14:55:31
| 2023-09-02T14:55:31
| 33,078,138
| 1,087
| 325
|
BSD-2-Clause
| 2023-09-14T16:58:34
| 2015-03-29T15:27:48
|
C
|
UTF-8
|
C
| false
| false
| 11,037
|
c
|
ddk750_chip.c
|
/**
* @file
*
* @date Apr 2, 2018
* @author Anton Bondarev
*/
#include <util/log.h>
#include <stdint.h>
#include <stdlib.h>
#include <drivers/video/fb.h>
#include "ddk750_reg.h"
#include "ddk750_chip.h"
#include "ddk750_power.h"
#include "lynxfb_hw750.h"
#define SZ_1M 0x00100000
#define SZ_2M 0x00200000
#define SZ_4M 0x00400000
#define SZ_8M 0x00800000
#define SZ_16M 0x01000000
#define SZ_32M 0x02000000
#define SZ_64M 0x04000000
/*
* Divide positive or negative dividend by positive or negative divisor
* and round to closest integer. Result is undefined for negative
* divisors if he dividend variable type is unsigned and for negative
* dividends if the divisor variable type is unsigned.
*/
#define DIV_ROUND_CLOSEST(x, divisor)( \
{ \
typeof(x) __x = x; \
typeof(divisor) __d = divisor; \
(((typeof(x))-1) > 0 || \
((typeof(divisor))-1) > 0 || \
(((__x) > 0) == ((__d) > 0))) ? \
(((__x) + ((__d) / 2)) / (__d)) : \
(((__x) - ((__d) / 2)) / (__d)); \
} \
)
#define MHz(x) ((x) * 1000000)
static logical_chip_type_t chip;
logical_chip_type_t sm750_get_chip_type(void)
{
return chip;
}
void sm750_set_chip_type(unsigned short devId, uint8_t revId)
{
if (devId == 0x718) {
chip = SM718;
} else if (devId == 0x750) {
chip = SM750;
/* SM750 and SM750LE are different in their revision ID only. */
if (revId == SM750LE_REVISION_ID) {
chip = SM750LE;
log_info("found sm750le");
}
} else {
chip = SM_UNKNOWN;
}
}
static unsigned int get_mxclk_freq(void)
{
unsigned int pll_reg;
unsigned int M, N, OD, POD;
if (sm750_get_chip_type() == SM750LE)
return MHz(130);
pll_reg = peek32(MXCLK_PLL_CTRL);
M = (pll_reg & PLL_CTRL_M_MASK) >> PLL_CTRL_M_SHIFT;
N = (pll_reg & PLL_CTRL_N_MASK) >> PLL_CTRL_N_SHIFT;
OD = (pll_reg & PLL_CTRL_OD_MASK) >> PLL_CTRL_OD_SHIFT;
POD = (pll_reg & PLL_CTRL_POD_MASK) >> PLL_CTRL_POD_SHIFT;
return DEFAULT_INPUT_CLOCK * M / N / (1 << OD) / (1 << POD);
}
/*
* This function set up the main chip clock.
*
* Input: Frequency to be set.
*/
static void set_chip_clock(unsigned int frequency)
{
struct pll_value pll;
unsigned int ulActualMxClk;
/* Cheok_0509: For SM750LE, the chip clock is fixed. Nothing to set. */
if (sm750_get_chip_type() == SM750LE)
return;
if (frequency) {
/*
* Set up PLL structure to hold the value to be set in clocks.
*/
pll.inputFreq = DEFAULT_INPUT_CLOCK; /* Defined in CLOCK.H */
pll.clockType = MXCLK_PLL;
/*
* Call sm750_calc_pll_value() to fill the other fields
* of the PLL structure. Sometimes, the chip cannot set
* up the exact clock required by the User.
* Return value of sm750_calc_pll_value gives the actual
* possible clock.
*/
ulActualMxClk = sm750_calc_pll_value(frequency, &pll);
/* Master Clock Control: MXCLK_PLL */
poke32(MXCLK_PLL_CTRL, sm750_format_pll_reg(&pll));
}
}
static void set_memory_clock(unsigned int frequency)
{
unsigned int reg, divisor;
/*
* Cheok_0509: For SM750LE, the memory clock is fixed.
* Nothing to set.
*/
if (sm750_get_chip_type() == SM750LE)
return;
if (frequency) {
/*
* Set the frequency to the maximum frequency
* that the DDR Memory can take which is 336MHz.
*/
if (frequency > MHz(336))
frequency = MHz(336);
/* Calculate the divisor */
divisor = DIV_ROUND_CLOSEST(get_mxclk_freq(), frequency);
/* Set the corresponding divisor in the register. */
reg = peek32(CURRENT_GATE) & ~CURRENT_GATE_M2XCLK_MASK;
switch (divisor) {
default:
case 1:
reg |= CURRENT_GATE_M2XCLK_DIV_1;
break;
case 2:
reg |= CURRENT_GATE_M2XCLK_DIV_2;
break;
case 3:
reg |= CURRENT_GATE_M2XCLK_DIV_3;
break;
case 4:
reg |= CURRENT_GATE_M2XCLK_DIV_4;
break;
}
sm750_set_current_gate(reg);
}
}
/*
* This function set up the master clock (MCLK).
*
* Input: Frequency to be set.
*
* NOTE:
* The maximum frequency the engine can run is 168MHz.
*/
static void set_master_clock(unsigned int frequency)
{
unsigned int reg, divisor;
/*
* Cheok_0509: For SM750LE, the memory clock is fixed.
* Nothing to set.
*/
if (sm750_get_chip_type() == SM750LE)
return;
if (frequency) {
/*
* Set the frequency to the maximum frequency
* that the SM750 engine can run, which is about 190 MHz.
*/
if (frequency > MHz(190))
frequency = MHz(190);
/* Calculate the divisor */
divisor = DIV_ROUND_CLOSEST(get_mxclk_freq(), frequency);
/* Set the corresponding divisor in the register. */
reg = peek32(CURRENT_GATE) & ~CURRENT_GATE_MCLK_MASK;
switch (divisor) {
default:
case 3:
reg |= CURRENT_GATE_MCLK_DIV_3;
break;
case 4:
reg |= CURRENT_GATE_MCLK_DIV_4;
break;
case 6:
reg |= CURRENT_GATE_MCLK_DIV_6;
break;
case 8:
reg |= CURRENT_GATE_MCLK_DIV_8;
break;
}
sm750_set_current_gate(reg);
}
}
unsigned int ddk750_get_vm_size(void)
{
unsigned int reg;
unsigned int data;
/* sm750le only use 64 mb memory*/
if (sm750_get_chip_type() == SM750LE)
return SZ_64M;
/* for 750,always use power mode0*/
reg = peek32(MODE0_GATE);
reg |= MODE0_GATE_GPIO;
poke32(MODE0_GATE, reg);
/* get frame buffer size from GPIO */
reg = peek32(MISC_CTRL) & MISC_CTRL_LOCALMEM_SIZE_MASK;
switch (reg) {
case MISC_CTRL_LOCALMEM_SIZE_8M:
data = SZ_8M; break; /* 8 Mega byte */
case MISC_CTRL_LOCALMEM_SIZE_16M:
data = SZ_16M; break; /* 16 Mega byte */
case MISC_CTRL_LOCALMEM_SIZE_32M:
data = SZ_32M; break; /* 32 Mega byte */
case MISC_CTRL_LOCALMEM_SIZE_64M:
data = SZ_64M; break; /* 64 Mega byte */
default:
data = 0;
break;
}
return data;
}
//int ddk750_init_hw(struct initchip_param *pInitParam)
int ddk750_init_hw(struct sm750_init_status *pInitParam)
{
unsigned int reg;
if (pInitParam->powerMode != 0)
pInitParam->powerMode = 0;
sm750_set_power_mode(pInitParam->powerMode);
/* Enable display power gate & LOCALMEM power gate*/
reg = peek32(CURRENT_GATE);
reg |= (CURRENT_GATE_DISPLAY | CURRENT_GATE_LOCALMEM);
sm750_set_current_gate(reg);
if (sm750_get_chip_type() != SM750LE) {
/* set panel pll and graphic mode via mmio_88 */
reg = peek32(VGA_CONFIGURATION);
reg |= (VGA_CONFIGURATION_PLL | VGA_CONFIGURATION_MODE);
poke32(VGA_CONFIGURATION, reg);
log_debug("set panel pll and graphic mode via mmio_88");
} else {
#if 0
#if defined(__i386__) || defined(__x86_64__)
/* set graphic mode via IO method */
outb_p(0x88, 0x3d4);
outb_p(0x06, 0x3d5);
#endif
#endif
}
/* Set the Main Chip Clock */
//set_chip_clock(MHz((unsigned int)pInitParam->chipClock));
set_chip_clock(MHz((unsigned int)pInitParam->chip_clk));
/* Set up memory clock. */
//set_memory_clock(MHz(pInitParam->memClock));
set_memory_clock(MHz(pInitParam->mem_clk));
/* Set up master clock */
//set_master_clock(MHz(pInitParam->masterClock));
set_master_clock(MHz(pInitParam->master_clk));
/*
* Reset the memory controller.
* If the memory controller is not reset in SM750,
* the system might hang when sw accesses the memory.
* The memory should be resetted after changing the MXCLK.
*/
if (pInitParam->resetMemory == 1) {
reg = peek32(MISC_CTRL);
reg &= ~MISC_CTRL_LOCALMEM_RESET;
poke32(MISC_CTRL, reg);
reg |= MISC_CTRL_LOCALMEM_RESET;
poke32(MISC_CTRL, reg);
}
if (pInitParam->setAllEngOff == 1) {
sm750_enable_2d_engine(0);
/* Disable Overlay, if a former application left it on */
reg = peek32(VIDEO_DISPLAY_CTRL);
reg &= ~DISPLAY_CTRL_PLANE;
poke32(VIDEO_DISPLAY_CTRL, reg);
/* Disable video alpha, if a former application left it on */
reg = peek32(VIDEO_ALPHA_DISPLAY_CTRL);
reg &= ~DISPLAY_CTRL_PLANE;
poke32(VIDEO_ALPHA_DISPLAY_CTRL, reg);
/* Disable alpha plane, if a former application left it on */
reg = peek32(ALPHA_DISPLAY_CTRL);
reg &= ~DISPLAY_CTRL_PLANE;
poke32(ALPHA_DISPLAY_CTRL, reg);
/* Disable DMA Channel, if a former application left it on */
reg = peek32(DMA_ABORT_INTERRUPT);
reg |= DMA_ABORT_INTERRUPT_ABORT_1;
poke32(DMA_ABORT_INTERRUPT, reg);
/* Disable DMA Power, if a former application left it on */
sm750_enable_dma(0);
}
/* We can add more initialization as needed. */
return 0;
}
/*
* monk liu @ 4/6/2011:
* re-write the calculatePLL function of ddk750.
* the original version function does not use
* some mathematics tricks and shortcut
* when it doing the calculation of the best N,M,D combination
* I think this version gives a little upgrade in speed
*
* 750 pll clock formular:
* Request Clock = (Input Clock * M )/(N * X)
*
* Input Clock = 14318181 hz
* X = 2 power D
* D ={0,1,2,3,4,5,6}
* M = {1,...,255}
* N = {2,...,15}
*/
unsigned int sm750_calc_pll_value(unsigned int request_orig,
struct pll_value *pll)
{
/*
* as sm750 register definition,
* N located in 2,15 and M located in 1,255
*/
int N, M, X, d;
int mini_diff;
unsigned int RN, quo, rem, fl_quo;
unsigned int input, request;
unsigned int tmpClock, ret;
const int max_OD = 3;
int max_d = 6;
if (sm750_get_chip_type() == SM750LE) {
/*
* SM750LE don't have
* programmable PLL and M/N values to work on.
* Just return the requested clock.
*/
return request_orig;
}
ret = 0;
mini_diff = ~0;
request = request_orig / 1000;
input = pll->inputFreq / 1000;
/*
* for MXCLK register,
* no POD provided, so need be treated differently
*/
if (pll->clockType == MXCLK_PLL)
max_d = 3;
for (N = 15; N > 1; N--) {
/*
* RN will not exceed maximum long
* if @request <= 285 MHZ (for 32bit cpu)
*/
RN = N * request;
quo = RN / input;
rem = RN % input;/* rem always small than 14318181 */
fl_quo = rem * 10000 / input;
for (d = max_d; d >= 0; d--) {
X = BIT(d);
M = quo * X;
M += fl_quo * X / 10000;
/* round step */
M += (fl_quo * X % 10000) > 5000 ? 1 : 0;
if (M < 256 && M > 0) {
unsigned int diff;
tmpClock = pll->inputFreq * M / N / X;
diff = abs(tmpClock - request_orig);
if (diff < mini_diff) {
pll->M = M;
pll->N = N;
pll->POD = 0;
if (d > max_OD)
pll->POD = d - max_OD;
pll->OD = d - pll->POD;
mini_diff = diff;
ret = tmpClock;
}
}
}
}
return ret;
}
unsigned int sm750_format_pll_reg(struct pll_value *pPLL)
{
#ifndef VALIDATION_CHIP
unsigned int POD = pPLL->POD;
#endif
unsigned int OD = pPLL->OD;
unsigned int M = pPLL->M;
unsigned int N = pPLL->N;
unsigned int reg = 0;
/*
* Note that all PLL's have the same format. Here, we just use
* Panel PLL parameter to work out the bit fields in the
* register. On returning a 32 bit number, the value can be
* applied to any PLL in the calling function.
*/
reg = PLL_CTRL_POWER |
#ifndef VALIDATION_CHIP
((POD << PLL_CTRL_POD_SHIFT) & PLL_CTRL_POD_MASK) |
#endif
((OD << PLL_CTRL_OD_SHIFT) & PLL_CTRL_OD_MASK) |
((N << PLL_CTRL_N_SHIFT) & PLL_CTRL_N_MASK) |
((M << PLL_CTRL_M_SHIFT) & PLL_CTRL_M_MASK);
return reg;
}
|
d58dc99df9096e070ff6a303225f882e96201395
|
1577e1cf4e89584a125cffb855ca50a9654c6d55
|
/Security/header_symlinks/iOS/Security/SecOTRSessionPriv.h
|
916397164f31eee0db52d4e20d3c4bb0bece3450
|
[] |
no_license
|
apple-open-source/macos
|
a4188b5c2ef113d90281d03cd1b14e5ee52ebffb
|
2d2b15f13487673de33297e49f00ef94af743a9a
|
refs/heads/master
| 2023-08-01T11:03:26.870408
| 2023-03-27T00:00:00
| 2023-03-27T00:00:00
| 180,595,052
| 124
| 24
| null | 2022-12-27T14:54:09
| 2019-04-10T14:06:23
| null |
UTF-8
|
C
| false
| false
| 45
|
h
|
SecOTRSessionPriv.h
|
../../../OSX/sec/Security/SecOTRSessionPriv.h
|
b78b3aeae11cdabb824fd33878a26966445b8ca2
|
431a5c28b8dfcc7d6ca6f4f97bf370cd770547a7
|
/src/tmx/Asn_J2735/include/asn_j2735_r63/ObjectType.h
|
52837430b2cb11a14c4e8fa3692b0d91c213c7bc
|
[
"Apache-2.0"
] |
permissive
|
usdot-fhwa-OPS/V2X-Hub
|
134061cfb55d8c83e871f7fd4bbfa5d8d3092eb0
|
aae33e6a16b8a30e1faee31a7ee863d191be06b8
|
refs/heads/develop
| 2023-08-26T10:10:59.989176
| 2023-08-24T14:58:21
| 2023-08-24T14:58:21
| 168,020,929
| 106
| 63
| null | 2023-09-11T20:24:45
| 2019-01-28T19:16:45
|
C
|
UTF-8
|
C
| false
| false
| 1,327
|
h
|
ObjectType.h
|
/*
* Generated by asn1c-0.9.29 (http://lionet.info/asn1c)
* From ASN.1 module "SDSM"
* found in "J2735_201603_2023-06-22.asn"
* `asn1c -fcompound-names `
*/
#ifndef _ObjectType_H_
#define _ObjectType_H_
#include <asn_application.h>
/* Including external dependencies */
#include <NativeEnumerated.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Dependencies */
typedef enum ObjectType {
ObjectType_unknown = 0,
ObjectType_vehicle = 1,
ObjectType_vru = 2,
ObjectType_animal = 3
/*
* Enumeration is extensible
*/
} e_ObjectType;
/* ObjectType */
typedef long ObjectType_t;
/* Implementation */
extern asn_per_constraints_t asn_PER_type_ObjectType_constr_1;
extern asn_TYPE_descriptor_t asn_DEF_ObjectType;
extern const asn_INTEGER_specifics_t asn_SPC_ObjectType_specs_1;
asn_struct_free_f ObjectType_free;
asn_struct_print_f ObjectType_print;
asn_constr_check_f ObjectType_constraint;
ber_type_decoder_f ObjectType_decode_ber;
der_type_encoder_f ObjectType_encode_der;
xer_type_decoder_f ObjectType_decode_xer;
xer_type_encoder_f ObjectType_encode_xer;
oer_type_decoder_f ObjectType_decode_oer;
oer_type_encoder_f ObjectType_encode_oer;
per_type_decoder_f ObjectType_decode_uper;
per_type_encoder_f ObjectType_encode_uper;
#ifdef __cplusplus
}
#endif
#endif /* _ObjectType_H_ */
#include <asn_internal.h>
|
e1c0c8d5ad0128574e396f3c32172ffda6e62741
|
407c96d904cf46a5f95217e44071f999783698a3
|
/trezor-crypto/crypto/cardano.c
|
6b07f776c15ea04f87dd50354a78d3190a809877
|
[
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-protobuf",
"LGPL-2.1-only",
"Swift-exception",
"BSL-1.0",
"Apache-2.0"
] |
permissive
|
trustwallet/wallet-core
|
dfeb276ddf1e3faf46c82f0a0cda2551e9c873f6
|
0c8e2e58aa8eb1360e4a6b03df91fb2de97e3caa
|
refs/heads/master
| 2023-08-21T11:58:43.983035
| 2023-08-18T10:51:13
| 2023-08-18T10:51:13
| 170,738,310
| 2,311
| 1,283
|
Apache-2.0
| 2023-09-08T11:26:39
| 2019-02-14T18:25:54
|
C++
|
UTF-8
|
C
| false
| false
| 10,227
|
c
|
cardano.c
|
/**
* Copyright (c) 2013-2021 SatoshiLabs
*
* 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 <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <TrezorCrypto/options.h>
#include <TrezorCrypto/bignum.h>
#include <TrezorCrypto/bip32.h>
#include <TrezorCrypto/cardano.h>
#include <TrezorCrypto/curves.h>
#include <TrezorCrypto/hasher.h>
#include <TrezorCrypto/hmac.h>
#include <TrezorCrypto/memzero.h>
#include <TrezorCrypto/pbkdf2.h>
#include <TrezorCrypto/sha2.h>
#if USE_CARDANO
#define CARDANO_MAX_NODE_DEPTH 1048576
const curve_info ed25519_cardano_info = {
.bip32_name = ED25519_CARDANO_NAME,
.params = NULL,
.hasher_base58 = HASHER_SHA2D,
.hasher_sign = HASHER_SHA2D,
.hasher_pubkey = HASHER_SHA2_RIPEMD,
.hasher_script = HASHER_SHA2,
};
static void scalar_multiply8(const uint8_t *src, int bytes, uint8_t *dst) {
uint8_t prev_acc = 0;
for (int i = 0; i < bytes; i++) {
dst[i] = (src[i] << 3) + (prev_acc & 0x7);
prev_acc = src[i] >> 5;
}
dst[bytes] = src[bytes - 1] >> 5;
}
static void scalar_add_256bits(const uint8_t *src1, const uint8_t *src2,
uint8_t *dst) {
uint16_t r = 0;
for (int i = 0; i < 32; i++) {
r = r + (uint16_t)src1[i] + (uint16_t)src2[i];
dst[i] = r & 0xff;
r >>= 8;
}
}
static void cardano_ed25519_tweak_bits(uint8_t private_key[32]) {
private_key[0] &= 0xf8;
private_key[31] &= 0x1f;
private_key[31] |= 0x40;
}
int hdnode_private_ckd_cardano(HDNode *inout, uint32_t index) {
if (inout->curve != &ed25519_cardano_info) {
return 0;
}
if (inout->depth >= CARDANO_MAX_NODE_DEPTH) {
return 0;
}
// checks for hardened/non-hardened derivation, keysize 32 means we are
// dealing with public key and thus non-h, keysize 64 is for private key
int keysize = 32;
if (index & 0x80000000) {
keysize = 64;
}
CONFIDENTIAL uint8_t data[1 + 64 + 4];
CONFIDENTIAL uint8_t z[32 + 32];
CONFIDENTIAL uint8_t priv_key[64];
CONFIDENTIAL uint8_t res_key[64];
write_le(data + keysize + 1, index);
memcpy(priv_key, inout->private_key, 32);
memcpy(priv_key + 32, inout->private_key_extension, 32);
if (keysize == 64) { // private derivation
data[0] = 0;
memcpy(data + 1, inout->private_key, 32);
memcpy(data + 1 + 32, inout->private_key_extension, 32);
} else { // public derivation
if (hdnode_fill_public_key(inout) != 0) {
return 0;
}
data[0] = 2;
memcpy(data + 1, inout->public_key + 1, 32);
}
CONFIDENTIAL HMAC_SHA512_CTX ctx;
hmac_sha512_Init(&ctx, inout->chain_code, 32);
hmac_sha512_Update(&ctx, data, 1 + keysize + 4);
hmac_sha512_Final(&ctx, z);
CONFIDENTIAL uint8_t zl8[32];
memzero(zl8, 32);
/* get 8 * Zl */
scalar_multiply8(z, 28, zl8);
/* Kl = 8*Zl + parent(K)l */
scalar_add_256bits(zl8, priv_key, res_key);
/* Kr = Zr + parent(K)r */
scalar_add_256bits(z + 32, priv_key + 32, res_key + 32);
memcpy(inout->private_key, res_key, 32);
memcpy(inout->private_key_extension, res_key + 32, 32);
if (keysize == 64) {
data[0] = 1;
} else {
data[0] = 3;
}
hmac_sha512_Init(&ctx, inout->chain_code, 32);
hmac_sha512_Update(&ctx, data, 1 + keysize + 4);
hmac_sha512_Final(&ctx, z);
memcpy(inout->chain_code, z + 32, 32);
inout->depth++;
inout->child_num = index;
memzero(inout->public_key, sizeof(inout->public_key));
// making sure to wipe our memory
memzero(z, sizeof(z));
memzero(data, sizeof(data));
memzero(priv_key, sizeof(priv_key));
memzero(res_key, sizeof(res_key));
return 1;
}
int hdnode_from_secret_cardano(const uint8_t secret[CARDANO_SECRET_LENGTH],
HDNode *out) {
memzero(out, sizeof(HDNode));
out->depth = 0;
out->child_num = 0;
out->curve = &ed25519_cardano_info;
memcpy(out->private_key, secret, 32);
memcpy(out->private_key_extension, secret + 32, 32);
memcpy(out->chain_code, secret + 64, 32);
cardano_ed25519_tweak_bits(out->private_key);
out->public_key[0] = 0;
if (hdnode_fill_public_key(out) != 0) {
return 0;
}
return 1;
}
// Derives the root Cardano secret from a master secret, aka seed, as defined in
// SLIP-0023.
int secret_from_seed_cardano_slip23(const uint8_t *seed, int seed_len,
uint8_t secret_out[CARDANO_SECRET_LENGTH]) {
CONFIDENTIAL uint8_t I[SHA512_DIGEST_LENGTH];
CONFIDENTIAL HMAC_SHA512_CTX ctx;
hmac_sha512_Init(&ctx, (const uint8_t *)ED25519_CARDANO_NAME,
strlen(ED25519_CARDANO_NAME));
hmac_sha512_Update(&ctx, seed, seed_len);
hmac_sha512_Final(&ctx, I);
sha512_Raw(I, 32, secret_out);
memcpy(secret_out + SHA512_DIGEST_LENGTH, I + 32, 32);
cardano_ed25519_tweak_bits(secret_out);
memzero(I, sizeof(I));
memzero(&ctx, sizeof(ctx));
return 1;
}
// Derives the root Cardano secret from a BIP-32 master secret via the Ledger
// derivation:
// https://github.com/cardano-foundation/CIPs/blob/09d7d8ee1bd64f7e6b20b5a6cae088039dce00cb/CIP-0003/Ledger.md
int secret_from_seed_cardano_ledger(const uint8_t *seed, int seed_len,
uint8_t secret_out[CARDANO_SECRET_LENGTH]) {
CONFIDENTIAL uint8_t chain_code[SHA256_DIGEST_LENGTH];
CONFIDENTIAL uint8_t root_key[SHA512_DIGEST_LENGTH];
CONFIDENTIAL HMAC_SHA256_CTX ctx;
CONFIDENTIAL HMAC_SHA512_CTX sctx;
const uint8_t *intermediate_result = seed;
int intermediate_result_len = seed_len;
do {
// STEP 1: derive a master secret like in BIP-32/SLIP-10
hmac_sha512_Init(&sctx, (const uint8_t *)ED25519_SEED_NAME,
strlen(ED25519_SEED_NAME));
hmac_sha512_Update(&sctx, intermediate_result, intermediate_result_len);
hmac_sha512_Final(&sctx, root_key);
// STEP 2: check that the resulting key does not have a particular bit set,
// otherwise iterate like in SLIP-10
intermediate_result = root_key;
intermediate_result_len = sizeof(root_key);
} while (root_key[31] & 0x20);
// STEP 3: calculate the chain code as a HMAC-SHA256 of "\x01" + seed,
// key is "ed25519 seed"
hmac_sha256_Init(&ctx, (const unsigned char *)ED25519_SEED_NAME,
strlen(ED25519_SEED_NAME));
hmac_sha256_Update(&ctx, (const unsigned char *)"\x01", 1);
hmac_sha256_Update(&ctx, seed, seed_len);
hmac_sha256_Final(&ctx, chain_code);
// STEP 4: extract information into output
_Static_assert(
SHA512_DIGEST_LENGTH + SHA256_DIGEST_LENGTH == CARDANO_SECRET_LENGTH,
"Invalid configuration of Cardano secret size");
memcpy(secret_out, root_key, SHA512_DIGEST_LENGTH);
memcpy(secret_out + SHA512_DIGEST_LENGTH, chain_code, SHA256_DIGEST_LENGTH);
// STEP 5: tweak bits of the private key
cardano_ed25519_tweak_bits(secret_out);
memzero(&ctx, sizeof(ctx));
memzero(&sctx, sizeof(sctx));
memzero(root_key, sizeof(root_key));
memzero(chain_code, sizeof(chain_code));
return 1;
}
#define CARDANO_ICARUS_STEPS 32
_Static_assert(
CARDANO_ICARUS_PBKDF2_ROUNDS % CARDANO_ICARUS_STEPS == 0,
"CARDANO_ICARUS_STEPS does not divide CARDANO_ICARUS_PBKDF2_ROUNDS");
#define CARDANO_ICARUS_ROUNDS_PER_STEP \
(CARDANO_ICARUS_PBKDF2_ROUNDS / CARDANO_ICARUS_STEPS)
// Derives the root Cardano HDNode from a passphrase and the entropy encoded in
// a BIP-0039 mnemonic using the Icarus derivation scheme, aka V2 derivation
// scheme:
// https://github.com/cardano-foundation/CIPs/blob/09d7d8ee1bd64f7e6b20b5a6cae088039dce00cb/CIP-0003/Icarus.md
int secret_from_entropy_cardano_icarus(
const uint8_t *pass, int pass_len, const uint8_t *entropy, int entropy_len,
uint8_t secret_out[CARDANO_SECRET_LENGTH],
void (*progress_callback)(uint32_t, uint32_t)) {
CONFIDENTIAL PBKDF2_HMAC_SHA512_CTX pctx;
CONFIDENTIAL uint8_t digest[SHA512_DIGEST_LENGTH];
uint32_t progress = 0;
// PASS 1: first 64 bytes
pbkdf2_hmac_sha512_Init(&pctx, pass, pass_len, entropy, entropy_len, 1);
if (progress_callback) {
progress_callback(progress, CARDANO_ICARUS_PBKDF2_ROUNDS * 2);
}
for (int i = 0; i < CARDANO_ICARUS_STEPS; i++) {
pbkdf2_hmac_sha512_Update(&pctx, CARDANO_ICARUS_ROUNDS_PER_STEP);
if (progress_callback) {
progress += CARDANO_ICARUS_ROUNDS_PER_STEP;
progress_callback(progress, CARDANO_ICARUS_PBKDF2_ROUNDS * 2);
}
}
pbkdf2_hmac_sha512_Final(&pctx, digest);
memcpy(secret_out, digest, SHA512_DIGEST_LENGTH);
// PASS 2: remaining 32 bytes
pbkdf2_hmac_sha512_Init(&pctx, pass, pass_len, entropy, entropy_len, 2);
if (progress_callback) {
progress_callback(progress, CARDANO_ICARUS_PBKDF2_ROUNDS * 2);
}
for (int i = 0; i < CARDANO_ICARUS_STEPS; i++) {
pbkdf2_hmac_sha512_Update(&pctx, CARDANO_ICARUS_ROUNDS_PER_STEP);
if (progress_callback) {
progress += CARDANO_ICARUS_ROUNDS_PER_STEP;
progress_callback(progress, CARDANO_ICARUS_PBKDF2_ROUNDS * 2);
}
}
pbkdf2_hmac_sha512_Final(&pctx, digest);
memcpy(secret_out + SHA512_DIGEST_LENGTH, digest,
CARDANO_SECRET_LENGTH - SHA512_DIGEST_LENGTH);
cardano_ed25519_tweak_bits(secret_out);
memzero(&pctx, sizeof(pctx));
memzero(digest, sizeof(digest));
return 1;
}
#endif // USE_CARDANO
|
2dd2711d2ca191859f091668c65c6d923d1e16ba
|
0744dcc5394cebf57ebcba343747af6871b67017
|
/os/net/bluetooth/bt_smp.h
|
dc42f30ca28163bbbb2e38b399cc7acd9cda81ee
|
[
"Apache-2.0",
"GPL-1.0-or-later",
"BSD-3-Clause",
"ISC",
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-other-permissive"
] |
permissive
|
Samsung/TizenRT
|
96abf62f1853f61fcf91ff14671a5e0c6ca48fdb
|
1a5c2e00a4b1bbf4c505bbf5cc6a8259e926f686
|
refs/heads/master
| 2023-08-31T08:59:33.327998
| 2023-08-08T06:09:20
| 2023-08-31T04:38:20
| 82,517,252
| 590
| 719
|
Apache-2.0
| 2023-09-14T06:54:49
| 2017-02-20T04:38:30
|
C
|
UTF-8
|
C
| false
| false
| 6,187
|
h
|
bt_smp.h
|
/****************************************************************************
* net/bluetooth/bt_smp.h
* Security Manager Protocol implementation.
*
* Copyright (C) 2018 Gregory Nutt. All rights reserved.
* Author: Gregory Nutt <gnutt@nuttx.org>
*
* Ported from the Intel/Zephyr arduino101_firmware_source-v1.tar package
* where the code was released with a compatible 3-clause BSD license:
*
* Copyright (c) 2016, Intel Corporation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
#ifndef __NET_BLUETOOTH_BT_SMP_H
#define __NET_BLUETOOTH_BT_SMP_H 1
/****************************************************************************
* Included Files
****************************************************************************/
#include <tinyara/config.h>
#include "bt_conn.h"
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
#define BT_SMP_ERR_PASSKEY_ENTRY_FAILED 0x01
#define BT_SMP_ERR_OOB_NOT_AVAIL 0x02
#define BT_SMP_ERR_AUTH_REQUIREMENTS 0x03
#define BT_SMP_ERR_CONFIRM_FAILED 0x04
#define BT_SMP_ERR_PAIRING_NOTSUPP 0x05
#define BT_SMP_ERR_ENC_KEY_SIZE 0x06
#define BT_SMP_ERR_CMD_NOTSUPP 0x07
#define BT_SMP_ERR_UNSPECIFIED 0x08
#define BT_SMP_ERR_REPEATED_ATTEMPTS 0x09
#define BT_SMP_ERR_INVALID_PARAMS 0x0a
#define BT_SMP_ERR_DHKEY_CHECK_FAILED 0x0b
#define BT_SMP_ERR_NUMERIC_COMP_FAILED 0x0c
#define BT_SMP_ERR_BREDR_PAIRING_IN_PROGRESS 0x0d
#define BT_SMP_ERR_CROSS_TRANSP_NOT_ALLOWED 0x0e
#define BT_SMP_IO_DISPLAY_ONLY 0x00
#define BT_SMP_IO_DISPLAY_YESNO 0x01
#define BT_SMP_IO_KEYBOARD_ONLY 0x02
#define BT_SMP_IO_NO_INPUT_OUTPUT 0x03
#define BT_SMP_IO_KEYBOARD_DISPLAY 0x04
#define BT_SMP_OOB_NOT_PRESENT 0x00
#define BT_SMP_OOB_PRESENT 0x01
#define BT_SMP_MIN_ENC_KEY_SIZE 16
#define BT_SMP_MAX_ENC_KEY_SIZE 16
#define BT_SMP_DIST_ENC_KEY 0x01
#define BT_SMP_DIST_ID_KEY 0x02
#define BT_SMP_DIST_SIGN 0x04
#define BT_SMP_DIST_LINK_KEY 0x08
#define BT_SMP_DIST_MASK 0x0f
#define BT_SMP_AUTH_NONE 0x00
#define BT_SMP_AUTH_BONDING 0x01
#define BT_SMP_AUTH_MITM 0x04
#define BT_SMP_AUTH_SC 0x08
#define BT_SMP_AUTH_KEYPRESS 0x10
#define BT_SMP_AUTH_MASK 0x1f
#define BT_SMP_CMD_PAIRING_REQ 0x01
#define BT_SMP_CMD_PAIRING_RSP 0x02
#define BT_SMP_CMD_PAIRING_CONFIRM 0x03
#define BT_SMP_CMD_PAIRING_RANDOM 0x04
#define BT_SMP_CMD_PAIRING_FAIL 0x05
#define BT_SMP_CMD_ENCRYPT_INFO 0x06
#define BT_SMP_CMD_MASTER_IDENT 0x07
#define BT_SMP_CMD_IDENT_INFO 0x08
#define BT_SMP_CMD_IDENT_ADDR_INFO 0x09
#define BT_SMP_CMD_SECURITY_REQUEST 0x0b
/****************************************************************************
* Public Types
****************************************************************************/
struct bt_smp_hdr_s {
uint8_t code;
} packed_struct;
struct bt_smp_pairing_s {
uint8_t io_capability;
uint8_t oob_flag;
uint8_t auth_req;
uint8_t max_key_size;
uint8_t init_key_dist;
uint8_t resp_key_dist;
} packed_struct;
struct bt_smp_pairing_confirm_s {
uint8_t val[16];
} packed_struct;
struct bt_smp_pairing_random_s {
uint8_t val[16];
} packed_struct;
struct bt_smp_pairing_fail_s {
uint8_t reason;
} packed_struct;
struct bt_smp_encrypt_info_s {
uint8_t ltk[16];
} packed_struct;
struct bt_smp_master_ident_s {
uint16_t ediv;
uint64_t rand;
} packed_struct;
struct bt_smp_ident_info_s {
uint8_t irk[16];
} packed_struct;
struct bt_smp_ident_addr_info_s {
bt_addr_le_t addr;
} packed_struct;
struct bt_smp_security_request_s {
uint8_t auth_req;
} packed_struct;
/****************************************************************************
* Public Function Prototypes
****************************************************************************/
bool bt_smp_irk_matches(FAR const uint8_t irk[16], FAR const bt_addr_t *addr);
int bt_smp_send_pairing_req(FAR struct bt_conn_s *conn);
int bt_smp_send_security_req(FAR struct bt_conn_s *conn);
int bt_smp_initialize(void);
#endif /* __NET_BLUETOOTH_BT_SMP_H */
|
0897022745d3a4ec795afa02583b1e2cb535c2f7
|
178c7fa06ccc0c306dc2b63d6113406e55297648
|
/drishti/connecttfeditor.h
|
e41c73a072bfd9cdaaf8f3385c46a198142dc9d7
|
[
"MIT"
] |
permissive
|
nci/drishti
|
3314726701c77e4f5f0b2dfdb1e7782489ebce34
|
da80a8e1f5e39c3010e9752d2053ed4aac5407aa
|
refs/heads/master
| 2023-08-03T08:58:29.843136
| 2023-08-01T03:53:58
| 2023-08-01T03:53:58
| 14,131,626
| 145
| 29
|
MIT
| 2021-02-04T09:33:22
| 2013-11-05T04:00:01
|
C++
|
UTF-8
|
C
| false
| false
| 627
|
h
|
connecttfeditor.h
|
#ifndef CONNECTTFEDITOR_H
#define CONNECTTFEDITOR_H
connect(m_tfEditor, SIGNAL(updateComposite()),
this, SLOT(updateComposite()));
connect(m_tfEditor, SIGNAL(giveHistogram(int)),
this, SLOT(changeHistogram(int)));
connect(m_tfEditor, SIGNAL(applyUndo(bool)),
this, SLOT(applyTFUndo(bool)));
connect(m_tfEditor, SIGNAL(transferFunctionUpdated()),
this, SLOT(transferFunctionUpdated()));
connect(this, SIGNAL(histogramUpdated(QImage, QImage)),
m_tfEditor, SLOT(setHistogramImage(QImage, QImage)));
connect(this, SIGNAL(histogramUpdated(int*)),
m_tfEditor, SLOT(setHistogram2D(int*)));
#endif
|
5526333818f58a823c630546a62a0f37a13cd3bb
|
50dd46b8ece33f3cdd174284b15d1d51f89669d4
|
/third_party/edk2/MdePkg/Include/Protocol/HiiPackageList.h
|
4122f11dddb26c0b06069930d37d0872c161d6a9
|
[
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"BSD-2-Clause",
"OpenSSL"
] |
permissive
|
google/google-ctf
|
f99da1ee07729bbccb869fff1cbaed6a80e43bcc
|
df02323eaf945d15e124801c74abaadca2749dc7
|
refs/heads/master
| 2023-08-31T14:30:27.548081
| 2023-08-29T13:04:20
| 2023-08-29T13:04:20
| 131,317,137
| 4,136
| 607
|
Apache-2.0
| 2023-08-30T22:17:02
| 2018-04-27T15:56:03
|
Go
|
UTF-8
|
C
| false
| false
| 1,183
|
h
|
HiiPackageList.h
|
/** @file
EFI_HII_PACKAGE_LIST_PROTOCOL as defined in UEFI 2.1.
Boot service LoadImage() installs EFI_HII_PACKAGE_LIST_PROTOCOL on the handle
if the image contains a custom PE/COFF resource with the type 'HII'.
The protocol's interface pointer points to the HII package list, which is
contained in the resource's data.
Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#ifndef __HII_PACKAGE_LIST_H__
#define __HII_PACKAGE_LIST_H__
#define EFI_HII_PACKAGE_LIST_PROTOCOL_GUID \
{ 0x6a1ee763, 0xd47a, 0x43b4, {0xaa, 0xbe, 0xef, 0x1d, 0xe2, 0xab, 0x56, 0xfc}}
typedef EFI_HII_PACKAGE_LIST_HEADER * EFI_HII_PACKAGE_LIST_PROTOCOL;
extern EFI_GUID gEfiHiiPackageListProtocolGuid;
#endif
|
85ed8aeaf82e4c6da9c97e29c2629cdafa81ff96
|
010279e2ba272d09e9d2c4e903722e5faba2cf7a
|
/util/system/maxlen.h
|
e1ff7f500869274cade6dd81fe384f603b865e62
|
[
"Apache-2.0"
] |
permissive
|
catboost/catboost
|
854c1a1f439a96f1ae6b48e16644be20aa04dba2
|
f5042e35b945aded77b23470ead62d7eacefde92
|
refs/heads/master
| 2023-09-01T12:14:14.174108
| 2023-09-01T10:01:01
| 2023-09-01T10:22:12
| 97,556,265
| 8,012
| 1,425
|
Apache-2.0
| 2023-09-11T03:32:32
| 2017-07-18T05:29:04
|
Python
|
UTF-8
|
C
| false
| false
| 499
|
h
|
maxlen.h
|
#pragma once
#include <cstdlib>
// http://support.microsoft.com/kb/208427
#ifndef URL_MAXLEN
#define URL_MAXLEN 2083
#endif
#define HOST_MAX 260
#ifndef URL_MAX
#define URL_MAX 1024
#endif
#define FULLURL_MAX (URL_MAX + HOST_MAX)
#define LINKTEXT_MAX 1024
#ifdef WIN32
#ifndef PATH_MAX
#define PATH_MAX _MAX_PATH
#endif
#else
#ifndef MAX_PATH
#define MAX_PATH PATH_MAX
#endif
#ifndef _MAX_PATH
#define _MAX_PATH PATH_MAX
#endif
#endif
|
306ad639083352e29c3004c00c2ba1aa16eaa333
|
9ca19ee62e2c985be413bd12e5eb63b44833750d
|
/src/cforth/config.h
|
9b7ba0ed9e6200dec178b7159f83be95fcb6f240
|
[
"MIT"
] |
permissive
|
MitchBradley/cforth
|
4cb523847c552b2e32e5e50a328b8e263a074d85
|
bae39263f2615e1d260426e3eca0ab32816f54ef
|
refs/heads/master
| 2023-08-31T17:23:00.037535
| 2023-08-17T09:01:57
| 2023-08-17T09:01:57
| 12,050,604
| 142
| 43
|
NOASSERTION
| 2023-08-21T16:36:56
| 2013-08-12T07:50:31
|
C
|
UTF-8
|
C
| false
| false
| 4,351
|
h
|
config.h
|
/* config.h 1.7 93/11/03 */
/*
* This file contains definitions which configure C Forth 83 for specific
* processors, operating systems, compilers, and memory models.
*
* IMPORTANT NOTE: The preferred place to set the basic configuration
* parameters (the OS name and the number of bits) is in the Makefile
* for the particular machine. However, some C development systems
* don't have "make", and some C compilers don't allow defines (-D)
* on the command line. Consequently, it may be necessary to edit this
* file to enable the appropriate #defines.
*/
#include <stdint.h>
#ifdef WIN32
#define inline __inline
#endif
/*
* If ALLOCDICT is defined, the space for the Forth dictionary will
* be dynamically allocated at startup time. Otherwise, the dictionary
* will be a static array in the BSS section of the program.
* On a system where the BSS does not take up space in the program
* file (e.g. Unix), it is often better to leave ALLOCDICT undefined.
* On a system where the BSS occupies file space (e.g. DOS), it is
* often better to define ALLOCDICT.
*/
/* #define ALLOCDICT */
#ifdef UNIX
/* Define SIGNALS to catch Unix signals (keyboard interrupts, errors, etc) */
/* If left undefined, signals will cause the Forth process to terminate */
#define SIGNALS
/*
* Note: It is okay to define neither BSD nor SYSV. The only result will
* be that the word "key?" will always return false. This is not a serious
* problem; all of the utilities supplied with C Forth will still work.
* The down side is that you won't be able to stop "words" by typing a key.
*/
/* Define BSD to make key? work right on 4.2BSD systems. */
/* #define BSD */
/* Define SYSV to make key? work right on System V systems */
/* #define SYSV */
#endif
#ifndef VMS
#define EXITSTATUS 0
#else
#define EXITSTATUS
/* Mods reported by Norman Smith */
#define system vms_system
#define chdir vms_chdir
#endif
#define INIT_FILENAME "init.x"
/*
* DEFAULT_EXE is the name of the default dictionary file.
* This file is created by the build procedure after the extensions are
* loaded. New dictionary files are produced by the SAVE-FORTH command.
*
* You can add a path specification to this if you wish,
* so that forth can be started from any working directory.
*/
#define DEFAULT_EXE "forth.dic"
typedef uint8_t u_char;
/*
* Both token_t and cell should be big enough to hold an absolute
* address on your machine. You will probably not need to change this,
* assuming that you have set BITS32 appropriately.
*/
#if defined(BITS64) || defined(BITS32)
typedef intptr_t cell;
typedef uintptr_t u_cell;
#ifdef T16
typedef uint16_t token_t;
typedef int16_t branch_t;
typedef uint16_t unum_t;
#else
typedef uintptr_t token_t;
typedef intptr_t branch_t;
typedef uintptr_t unum_t;
#endif
#else
// 16-bit case, now largely uninteresting
typedef unsigned int token_t;
typedef int cell;
typedef unsigned int unum_t;
typedef int branch_t;
#endif
#if defined(BITS64)
#define CELLBITS (64)
typedef __int128_t double_cell_t;
typedef __uint128_t u_double_cell_t;
#endif
#if defined(BITS32)
#define CELLBITS (32)
typedef long long double_cell_t;
typedef unsigned long long u_double_cell_t;
#endif
#if defined(BITS16)
#define CELLBITS (16)
typedef __int32_t double_cell_t;
typedef __uint32_t u_double_cell_t;
#endif
#ifndef CELLBITS
# error "BITS16, BITS32 or BITS64 not defined"
#endif
typedef token_t *xt_t;
#define ALIGN_BOUNDARY (sizeof(token_t))
/*
* SNEWLINE is the end-of-line sequence for the operating system's files.
* CNEWLINE is the LAST character in the end-of-line sequence
*/
#ifdef UNIX
#define SNEWLINE "\n" /* Unix */
#define CNEWLINE '\n'
#endif
#ifdef MAC
#define SNEWLINE "\r" /* MAC, OS-9, UNIFLEX, ... */
#define CNEWLINE '\r'
#endif
#ifndef SNEWLINE
#define SNEWLINE "\r\n" /* MS-DOS, RT-11, VMS? */
#define CNEWLINE '\n'
#endif
#define TIBSIZE 132
#define PSSIZE 100
#define RSSIZE 100
#define CBUFSIZE 64
#define MAXVARS 0x300
#define MAXUSER (MAXVARS * sizeof(cell))
#if !defined(MAXDICT) && defined(T16)
#define MAXDICT (0x1fffcL) /* The extent of token-space reach */
#endif
#ifndef MAXDICT
#ifdef BITS64
#define MAXDICT (0x80000L)
#else
#ifdef BITS32
#define MAXDICT (0x60000L)
#else
#define MAXDICT (45000)
#endif
#endif
#endif
|
96747633e6e671ed61fb0e9bc6ec80e0f063ca66
|
5eff7a36d9a9917dce9111f0c3074375fe6f7656
|
/lib/libxkbfile/src/xkbout.c
|
57f5adf17955f1fc1c6572d3630e0bd0fdb22955
|
[
"MIT-open-group",
"HPND"
] |
permissive
|
openbsd/xenocara
|
cb392d02ebba06f6ff7d826fd8a89aa3b8401779
|
a012b5de33ea0b977095d77316a521195b26cc6b
|
refs/heads/master
| 2023-08-25T12:16:58.862008
| 2023-08-12T16:16:25
| 2023-08-12T16:16:25
| 66,967,384
| 177
| 66
| null | 2023-07-22T18:12:37
| 2016-08-30T18:36:01
|
C
|
UTF-8
|
C
| false
| false
| 40,052
|
c
|
xkbout.c
|
/************************************************************
Copyright (c) 1994 by Silicon Graphics Computer Systems, Inc.
Permission to use, copy, modify, and distribute this
software and its documentation for any purpose and without
fee is hereby granted, provided that the above copyright
notice appear in all copies and that both that copyright
notice and this permission notice appear in supporting
documentation, and that the name of Silicon Graphics not be
used in advertising or publicity pertaining to distribution
of the software without specific prior written permission.
Silicon Graphics makes no representation about the suitability
of this software for any purpose. It is provided "as is"
without any express or implied warranty.
SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
GRAPHICS 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.
********************************************************/
#ifdef HAVE_DIX_CONFIG_H
#include <dix-config.h>
#elif defined(HAVE_CONFIG_H)
#include <config.h>
#endif
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <X11/Xfuncs.h>
#include <X11/Xlib.h>
#include <X11/XKBlib.h>
#include <X11/extensions/XKBgeom.h>
#include "XKMformat.h"
#include "XKBfileInt.h"
#define VMOD_HIDE_VALUE 0
#define VMOD_SHOW_VALUE 1
#define VMOD_COMMENT_VALUE 2
static Bool
WriteXKBVModDecl(FILE *file, Display *dpy, XkbDescPtr xkb, int showValue)
{
register int i, nMods;
Atom *vmodNames;
if (xkb == NULL)
return False;
if (xkb->names != NULL)
vmodNames = xkb->names->vmods;
else
vmodNames = NULL;
for (i = nMods = 0; i < XkbNumVirtualMods; i++) {
if ((vmodNames != NULL) && (vmodNames[i] != None)) {
if (nMods == 0)
fprintf(file, " virtual_modifiers ");
else
fprintf(file, ",");
fprintf(file, "%s", XkbAtomText(dpy, vmodNames[i], XkbXKBFile));
if ((showValue != VMOD_HIDE_VALUE) &&
(xkb->server) && (xkb->server->vmods[i] != XkbNoModifierMask)) {
if (showValue == VMOD_COMMENT_VALUE) {
fprintf(file, "/* = %s */",
XkbModMaskText(xkb->server->vmods[i], XkbXKBFile));
}
else {
fprintf(file, "= %s",
XkbModMaskText(xkb->server->vmods[i], XkbXKBFile));
}
}
nMods++;
}
}
if (nMods > 0)
fprintf(file, ";\n\n");
return True;
}
/***====================================================================***/
static Bool
WriteXKBAction(FILE *file, XkbFileInfo *result, XkbAnyAction *action)
{
XkbDescPtr xkb;
Display *dpy;
xkb = result->xkb;
dpy = xkb->dpy;
fprintf(file, "%s",
XkbActionText(dpy, xkb, (XkbAction *) action, XkbXKBFile));
return True;
}
/***====================================================================***/
Bool
XkbWriteXKBKeycodes(FILE * file,
XkbFileInfo * result,
Bool topLevel,
Bool showImplicit,
XkbFileAddOnFunc addOn,
void * priv)
{
Atom kcName;
register unsigned i;
XkbDescPtr xkb;
Display *dpy;
const char *alternate;
xkb = result->xkb;
if ((!xkb) || (!xkb->names) || (!xkb->names->keys)) {
_XkbLibError(_XkbErrMissingNames, "XkbWriteXKBKeycodes", 0);
return False;
}
dpy = xkb->dpy;
kcName = xkb->names->keycodes;
if (kcName != None)
fprintf(file, "xkb_keycodes \"%s\" {\n",
XkbAtomText(dpy, kcName, XkbXKBFile));
else
fprintf(file, "xkb_keycodes {\n");
fprintf(file, " minimum = %d;\n", xkb->min_key_code);
fprintf(file, " maximum = %d;\n", xkb->max_key_code);
for (i = xkb->min_key_code; i <= xkb->max_key_code; i++) {
if (xkb->names->keys[i].name[0] != '\0') {
if (XkbFindKeycodeByName(xkb, xkb->names->keys[i].name, True) != i)
alternate = "alternate ";
else
alternate = "";
fprintf(file, " %s%6s = %d;\n", alternate,
XkbKeyNameText(xkb->names->keys[i].name, XkbXKBFile), i);
}
}
if (xkb->indicators != NULL) {
for (i = 0; i < XkbNumIndicators; i++) {
const char *type;
if (xkb->indicators->phys_indicators & (1 << i))
type = " ";
else
type = " virtual ";
if (xkb->names->indicators[i] != None) {
fprintf(file, "%sindicator %d = \"%s\";\n", type, i + 1,
XkbAtomText(dpy, xkb->names->indicators[i],
XkbXKBFile));
}
}
}
if (xkb->names->key_aliases != NULL) {
XkbKeyAliasPtr pAl;
pAl = xkb->names->key_aliases;
for (i = 0; i < xkb->names->num_key_aliases; i++, pAl++) {
fprintf(file, " alias %6s = %6s;\n",
XkbKeyNameText(pAl->alias, XkbXKBFile),
XkbKeyNameText(pAl->real, XkbXKBFile));
}
}
if (addOn)
(*addOn) (file, result, topLevel, showImplicit, XkmKeyNamesIndex, priv);
fprintf(file, "};\n\n");
return True;
}
Bool
XkbWriteXKBKeyTypes(FILE * file,
XkbFileInfo * result,
Bool topLevel,
Bool showImplicit,
XkbFileAddOnFunc addOn,
void * priv)
{
Display *dpy;
register unsigned i, n;
XkbKeyTypePtr type;
XkbKTMapEntryPtr entry;
XkbDescPtr xkb;
xkb = result->xkb;
if ((!xkb) || (!xkb->map) || (!xkb->map->types)) {
_XkbLibError(_XkbErrMissingTypes, "XkbWriteXKBKeyTypes", 0);
return False;
}
dpy = xkb->dpy;
if (xkb->map->num_types < XkbNumRequiredTypes) {
_XkbLibError(_XkbErrMissingReqTypes, "XkbWriteXKBKeyTypes", 0);
return 0;
}
if ((xkb->names == NULL) || (xkb->names->types == None))
fprintf(file, "xkb_types {\n\n");
else
fprintf(file, "xkb_types \"%s\" {\n\n",
XkbAtomText(dpy, xkb->names->types, XkbXKBFile));
WriteXKBVModDecl(file, dpy, xkb,
(showImplicit ? VMOD_COMMENT_VALUE : VMOD_HIDE_VALUE));
type = xkb->map->types;
for (i = 0; i < xkb->map->num_types; i++, type++) {
fprintf(file, " type \"%s\" {\n",
XkbAtomText(dpy, type->name, XkbXKBFile));
fprintf(file, " modifiers= %s;\n",
XkbVModMaskText(dpy, xkb, type->mods.real_mods,
type->mods.vmods, XkbXKBFile));
entry = type->map;
for (n = 0; n < type->map_count; n++, entry++) {
char *str;
str =
XkbVModMaskText(dpy, xkb, entry->mods.real_mods,
entry->mods.vmods, XkbXKBFile);
fprintf(file, " map[%s]= Level%d;\n", str, entry->level + 1);
if ((type->preserve) && ((type->preserve[n].real_mods) ||
(type->preserve[n].vmods))) {
fprintf(file, " preserve[%s]= ", str);
fprintf(file, "%s;\n", XkbVModMaskText(dpy, xkb,
type->preserve[n].
real_mods,
type->preserve[n].vmods,
XkbXKBFile));
}
}
if (type->level_names != NULL) {
Atom *name = type->level_names;
for (n = 0; n < type->num_levels; n++, name++) {
if ((*name) == None)
continue;
fprintf(file, " level_name[Level%d]= \"%s\";\n", n + 1,
XkbAtomText(dpy, *name, XkbXKBFile));
}
}
fprintf(file, " };\n");
}
if (addOn)
(*addOn) (file, result, topLevel, showImplicit, XkmTypesIndex, priv);
fprintf(file, "};\n\n");
return True;
}
static Bool
WriteXKBIndicatorMap(FILE * file,
XkbFileInfo * result,
Atom name,
XkbIndicatorMapPtr led,
XkbFileAddOnFunc addOn,
void * priv)
{
XkbDescPtr xkb;
char *tmp;
xkb = result->xkb;
tmp = XkbAtomGetString(xkb->dpy, name);
fprintf(file, " indicator \"%s\" {\n", tmp);
_XkbFree(tmp);
if (led->flags & XkbIM_NoExplicit)
fprintf(file, " !allowExplicit;\n");
if (led->flags & XkbIM_LEDDrivesKB)
fprintf(file, " indicatorDrivesKeyboard;\n");
if (led->which_groups != 0) {
if (led->which_groups != XkbIM_UseEffective) {
fprintf(file, " whichGroupState= %s;\n",
XkbIMWhichStateMaskText(led->which_groups, XkbXKBFile));
}
fprintf(file, " groups= 0x%02x;\n", led->groups);
}
if (led->which_mods != 0) {
if (led->which_mods != XkbIM_UseEffective) {
fprintf(file, " whichModState= %s;\n",
XkbIMWhichStateMaskText(led->which_mods, XkbXKBFile));
}
fprintf(file, " modifiers= %s;\n",
XkbVModMaskText(xkb->dpy, xkb,
led->mods.real_mods, led->mods.vmods,
XkbXKBFile));
}
if (led->ctrls != 0) {
fprintf(file, " controls= %s;\n",
XkbControlsMaskText(led->ctrls, XkbXKBFile));
}
if (addOn)
(*addOn) (file, result, False, True, XkmIndicatorsIndex, priv);
fprintf(file, " };\n");
return True;
}
Bool
XkbWriteXKBCompatMap(FILE * file,
XkbFileInfo * result,
Bool topLevel,
Bool showImplicit,
XkbFileAddOnFunc addOn,
void * priv)
{
Display * dpy;
register unsigned i;
XkbSymInterpretPtr interp;
XkbDescPtr xkb;
xkb = result->xkb;
if ((!xkb) || (!xkb->compat) || (!xkb->compat->sym_interpret)) {
_XkbLibError(_XkbErrMissingCompatMap, "XkbWriteXKBCompatMap", 0);
return False;
}
dpy = xkb->dpy;
if ((xkb->names == NULL) || (xkb->names->compat == None))
fprintf(file, "xkb_compatibility {\n\n");
else
fprintf(file, "xkb_compatibility \"%s\" {\n\n",
XkbAtomText(dpy, xkb->names->compat, XkbXKBFile));
WriteXKBVModDecl(file, dpy, xkb,
(showImplicit ? VMOD_COMMENT_VALUE : VMOD_HIDE_VALUE));
fprintf(file, " interpret.useModMapMods= AnyLevel;\n");
fprintf(file, " interpret.repeat= False;\n");
fprintf(file, " interpret.locking= False;\n");
interp = xkb->compat->sym_interpret;
for (i = 0; i < xkb->compat->num_si; i++, interp++) {
fprintf(file, " interpret %s+%s(%s) {\n",
((interp->sym == NoSymbol) ? "Any" :
XkbKeysymText(interp->sym, XkbXKBFile)),
XkbSIMatchText(interp->match, XkbXKBFile),
XkbModMaskText(interp->mods, XkbXKBFile));
if (interp->virtual_mod != XkbNoModifier) {
fprintf(file, " virtualModifier= %s;\n",
XkbVModIndexText(dpy, xkb, interp->virtual_mod,
XkbXKBFile));
}
if (interp->match & XkbSI_LevelOneOnly)
fprintf(file, " useModMapMods=level1;\n");
if (interp->flags & XkbSI_LockingKey)
fprintf(file, " locking= True;\n");
if (interp->flags & XkbSI_AutoRepeat)
fprintf(file, " repeat= True;\n");
fprintf(file, " action= ");
WriteXKBAction(file, result, &interp->act);
fprintf(file, ";\n");
fprintf(file, " };\n");
}
for (i = 0; i < XkbNumKbdGroups; i++) {
XkbModsPtr gc;
gc = &xkb->compat->groups[i];
if ((gc->real_mods == 0) && (gc->vmods == 0))
continue;
fprintf(file, " group %d = %s;\n", i + 1,
XkbVModMaskText(xkb->dpy, xkb, gc->real_mods, gc->vmods,
XkbXKBFile));
}
if (xkb->indicators) {
for (i = 0; i < XkbNumIndicators; i++) {
XkbIndicatorMapPtr map = &xkb->indicators->maps[i];
if ((map->flags != 0) || (map->which_groups != 0) ||
(map->groups != 0) || (map->which_mods != 0) ||
(map->mods.real_mods != 0) || (map->mods.vmods != 0) ||
(map->ctrls != 0)) {
WriteXKBIndicatorMap(file, result, xkb->names->indicators[i],
map, addOn, priv);
}
}
}
if (addOn)
(*addOn) (file, result, topLevel, showImplicit, XkmCompatMapIndex,
priv);
fprintf(file, "};\n\n");
return True;
}
Bool
XkbWriteXKBSymbols(FILE * file,
XkbFileInfo * result,
Bool topLevel,
Bool showImplicit,
XkbFileAddOnFunc addOn,
void * priv)
{
Display *dpy;
register unsigned i, tmp;
XkbDescPtr xkb;
XkbClientMapPtr map;
XkbServerMapPtr srv;
Bool showActions;
xkb = result->xkb;
if ((!xkb) || (!xkb->map) || (!xkb->map->syms) || (!xkb->map->key_sym_map)) {
_XkbLibError(_XkbErrMissingSymbols, "XkbWriteXKBSymbols", 0);
return False;
}
if ((!xkb->names) || (!xkb->names->keys)) {
_XkbLibError(_XkbErrMissingNames, "XkbWriteXKBSymbols", 0);
return False;
}
map = xkb->map;
srv = xkb->server;
dpy = xkb->dpy;
if ((xkb->names == NULL) || (xkb->names->symbols == None))
fprintf(file, "xkb_symbols {\n\n");
else
fprintf(file, "xkb_symbols \"%s\" {\n\n",
XkbAtomText(dpy, xkb->names->symbols, XkbXKBFile));
for (tmp = i = 0; i < XkbNumKbdGroups; i++) {
if (xkb->names->groups[i] != None) {
fprintf(file, " name[group%d]=\"%s\";\n", i + 1,
XkbAtomText(dpy, xkb->names->groups[i], XkbXKBFile));
tmp++;
}
}
if (tmp > 0)
fprintf(file, "\n");
for (i = xkb->min_key_code; i <= xkb->max_key_code; i++) {
Bool simple;
if ((int) XkbKeyNumSyms(xkb, i) < 1)
continue;
if (XkbFindKeycodeByName(xkb, xkb->names->keys[i].name, True) != i)
continue;
simple = True;
fprintf(file, " key %6s {",
XkbKeyNameText(xkb->names->keys[i].name, XkbXKBFile));
if (srv->explicit) {
if (((srv->explicit[i] & XkbExplicitKeyTypesMask) != 0) ||
(showImplicit)) {
int typeNdx, g;
Bool multi;
const char *comment = " ";
if ((srv->explicit[i] & XkbExplicitKeyTypesMask) == 0)
comment = "//";
multi = False;
typeNdx = XkbKeyKeyTypeIndex(xkb, i, 0);
for (g = 1; (g < XkbKeyNumGroups(xkb, i)) && (!multi); g++) {
if (XkbKeyKeyTypeIndex(xkb, i, g) != typeNdx)
multi = True;
}
if (multi) {
for (g = 0; g < XkbKeyNumGroups(xkb, i); g++) {
typeNdx = XkbKeyKeyTypeIndex(xkb, i, g);
if (srv->explicit[i] & (1 << g)) {
fprintf(file, "\n%s type[group%d]= \"%s\",",
comment, g + 1,
XkbAtomText(dpy, map->types[typeNdx].name,
XkbXKBFile));
}
else if (showImplicit) {
fprintf(file, "\n// type[group%d]= \"%s\",",
g + 1,
XkbAtomText(dpy, map->types[typeNdx].name,
XkbXKBFile));
}
}
}
else {
fprintf(file, "\n%s type= \"%s\",", comment,
XkbAtomText(dpy, map->types[typeNdx].name,
XkbXKBFile));
}
simple = False;
}
if (((srv->explicit[i] & XkbExplicitAutoRepeatMask) != 0) &&
(xkb->ctrls != NULL)) {
if (xkb->ctrls->per_key_repeat[i / 8] & (1 << (i % 8)))
fprintf(file, "\n repeat= Yes,");
else
fprintf(file, "\n repeat= No,");
simple = False;
}
if ((xkb->server != NULL) && (xkb->server->vmodmap != NULL) &&
(xkb->server->vmodmap[i] != 0)) {
if ((srv->explicit[i] & XkbExplicitVModMapMask) != 0) {
fprintf(file, "\n virtualMods= %s,",
XkbVModMaskText(dpy, xkb, 0,
xkb->server->vmodmap[i],
XkbXKBFile));
}
else if (showImplicit) {
fprintf(file, "\n// virtualMods= %s,",
XkbVModMaskText(dpy, xkb, 0,
xkb->server->vmodmap[i],
XkbXKBFile));
}
}
}
switch (XkbOutOfRangeGroupAction(XkbKeyGroupInfo(xkb, i))) {
case XkbClampIntoRange:
fprintf(file, "\n groupsClamp,");
break;
case XkbRedirectIntoRange:
fprintf(file, "\n groupsRedirect= Group%d,",
XkbOutOfRangeGroupNumber(XkbKeyGroupInfo(xkb, i)) + 1);
break;
}
if (srv->behaviors != NULL) {
unsigned type;
type = srv->behaviors[i].type & XkbKB_OpMask;
if (type != XkbKB_Default) {
simple = False;
fprintf(file, "\n %s,",
XkbBehaviorText(xkb, &srv->behaviors[i], XkbXKBFile));
}
}
if ((srv->explicit == NULL) || showImplicit ||
((srv->explicit[i] & XkbExplicitInterpretMask) != 0))
showActions = XkbKeyHasActions(xkb, i);
else
showActions = False;
if (((unsigned) XkbKeyNumGroups(xkb, i) > 1) || showActions)
simple = False;
if (simple) {
KeySym *syms;
unsigned s;
syms = XkbKeySymsPtr(xkb, i);
fprintf(file, " [ ");
for (s = 0; s < XkbKeyGroupWidth(xkb, i, XkbGroup1Index); s++) {
if (s != 0)
fprintf(file, ", ");
fprintf(file, "%15s", XkbKeysymText(*syms++, XkbXKBFile));
}
fprintf(file, " ] };\n");
}
else {
unsigned g, s;
KeySym *syms;
XkbAction *acts;
syms = XkbKeySymsPtr(xkb, i);
acts = XkbKeyActionsPtr(xkb, i);
for (g = 0; g < XkbKeyNumGroups(xkb, i); g++) {
if (g != 0)
fprintf(file, ",");
fprintf(file, "\n symbols[Group%d]= [ ", g + 1);
for (s = 0; s < XkbKeyGroupWidth(xkb, i, g); s++) {
if (s != 0)
fprintf(file, ", ");
fprintf(file, "%15s", XkbKeysymText(syms[s], XkbXKBFile));
}
fprintf(file, " ]");
syms += XkbKeyGroupsWidth(xkb, i);
if (showActions) {
fprintf(file, ",\n actions[Group%d]= [ ", g + 1);
for (s = 0; s < XkbKeyGroupWidth(xkb, i, g); s++) {
if (s != 0)
fprintf(file, ", ");
WriteXKBAction(file, result,
(XkbAnyAction *) & acts[s]);
}
fprintf(file, " ]");
acts += XkbKeyGroupsWidth(xkb, i);
}
}
fprintf(file, "\n };\n");
}
}
if (map && map->modmap) {
for (i = xkb->min_key_code; i <= xkb->max_key_code; i++) {
if (map->modmap[i] != 0) {
register int n, bit;
for (bit = 1, n = 0; n < XkbNumModifiers; n++, bit <<= 1) {
if (map->modmap[i] & bit) {
char buf[5];
memcpy(buf, xkb->names->keys[i].name, 4);
buf[4] = '\0';
fprintf(file, " modifier_map %s { <%s> };\n",
XkbModIndexText(n, XkbXKBFile), buf);
}
}
}
}
}
if (addOn)
(*addOn) (file, result, topLevel, showImplicit, XkmSymbolsIndex, priv);
fprintf(file, "};\n\n");
return True;
}
static Bool
WriteXKBOutline(FILE * file,
XkbShapePtr shape,
XkbOutlinePtr outline,
int lastRadius,
int first,
int indent)
{
register int i;
XkbPointPtr pt;
char *iStr;
fprintf(file, "%s", iStr = XkbIndentText(first));
if (first != indent)
iStr = XkbIndentText(indent);
if (outline->corner_radius != lastRadius) {
fprintf(file, "corner= %s,",
XkbGeomFPText(outline->corner_radius, XkbMessage));
if (shape != NULL) {
fprintf(file, "\n%s", iStr);
}
}
if (shape) {
if (outline == shape->approx)
fprintf(file, "approx= ");
else if (outline == shape->primary)
fprintf(file, "primary= ");
}
fprintf(file, "{");
for (pt = outline->points, i = 0; i < outline->num_points; i++, pt++) {
if (i == 0)
fprintf(file, " ");
else if ((i % 4) == 0)
fprintf(file, ",\n%s ", iStr);
else
fprintf(file, ", ");
fprintf(file, "[ %3s, %3s ]", XkbGeomFPText(pt->x, XkbXKBFile),
XkbGeomFPText(pt->y, XkbXKBFile));
}
fprintf(file, " }");
return True;
}
static Bool
WriteXKBDoodad(FILE * file,
Display * dpy,
unsigned indent,
XkbGeometryPtr geom,
XkbDoodadPtr doodad)
{
register char *i_str;
XkbShapePtr shape;
XkbColorPtr color;
i_str = XkbIndentText(indent);
fprintf(file, "%s%s \"%s\" {\n", i_str,
XkbDoodadTypeText(doodad->any.type, XkbMessage),
XkbAtomText(dpy, doodad->any.name, XkbMessage));
fprintf(file, "%s top= %s;\n", i_str,
XkbGeomFPText(doodad->any.top, XkbXKBFile));
fprintf(file, "%s left= %s;\n", i_str,
XkbGeomFPText(doodad->any.left, XkbXKBFile));
fprintf(file, "%s priority= %d;\n", i_str, doodad->any.priority);
switch (doodad->any.type) {
case XkbOutlineDoodad:
case XkbSolidDoodad:
if (doodad->shape.angle != 0) {
fprintf(file, "%s angle= %s;\n", i_str,
XkbGeomFPText(doodad->shape.angle, XkbXKBFile));
}
if (doodad->shape.color_ndx != 0) {
fprintf(file, "%s color= \"%s\";\n", i_str,
XkbShapeDoodadColor(geom, &doodad->shape)->spec);
}
shape = XkbShapeDoodadShape(geom, &doodad->shape);
fprintf(file, "%s shape= \"%s\";\n", i_str,
XkbAtomText(dpy, shape->name, XkbXKBFile));
break;
case XkbTextDoodad:
if (doodad->text.angle != 0) {
fprintf(file, "%s angle= %s;\n", i_str,
XkbGeomFPText(doodad->text.angle, XkbXKBFile));
}
if (doodad->text.width != 0) {
fprintf(file, "%s width= %s;\n", i_str,
XkbGeomFPText(doodad->text.width, XkbXKBFile));
}
if (doodad->text.height != 0) {
fprintf(file, "%s height= %s;\n", i_str,
XkbGeomFPText(doodad->text.height, XkbXKBFile));
}
if (doodad->text.color_ndx != 0) {
color = XkbTextDoodadColor(geom, &doodad->text);
fprintf(file, "%s color= \"%s\";\n", i_str,
XkbStringText(color->spec, XkbXKBFile));
}
fprintf(file, "%s XFont= \"%s\";\n", i_str,
XkbStringText(doodad->text.font, XkbXKBFile));
fprintf(file, "%s text= \"%s\";\n", i_str,
XkbStringText(doodad->text.text, XkbXKBFile));
break;
case XkbIndicatorDoodad:
shape = XkbIndicatorDoodadShape(geom, &doodad->indicator);
color = XkbIndicatorDoodadOnColor(geom, &doodad->indicator);
fprintf(file, "%s onColor= \"%s\";\n", i_str,
XkbStringText(color->spec, XkbXKBFile));
color = XkbIndicatorDoodadOffColor(geom, &doodad->indicator);
fprintf(file, "%s offColor= \"%s\";\n", i_str,
XkbStringText(color->spec, XkbXKBFile));
fprintf(file, "%s shape= \"%s\";\n", i_str,
XkbAtomText(dpy, shape->name, XkbXKBFile));
break;
case XkbLogoDoodad:
fprintf(file, "%s logoName= \"%s\";\n", i_str,
XkbStringText(doodad->logo.logo_name, XkbXKBFile));
if (doodad->shape.angle != 0) {
fprintf(file, "%s angle= %s;\n", i_str,
XkbGeomFPText(doodad->logo.angle, XkbXKBFile));
}
if (doodad->shape.color_ndx != 0) {
fprintf(file, "%s color= \"%s\";\n", i_str,
XkbLogoDoodadColor(geom, &doodad->logo)->spec);
}
shape = XkbLogoDoodadShape(geom, &doodad->logo);
fprintf(file, "%s shape= \"%s\";\n", i_str,
XkbAtomText(dpy, shape->name, XkbXKBFile));
break;
}
fprintf(file, "%s};\n", i_str);
return True;
}
/*ARGSUSED*/
static Bool
WriteXKBOverlay(FILE * file,
Display * dpy,
unsigned indent,
XkbGeometryPtr geom,
XkbOverlayPtr ol)
{
register char *i_str;
int r, k, nOut;
XkbOverlayRowPtr row;
XkbOverlayKeyPtr key;
i_str = XkbIndentText(indent);
if (ol->name != None) {
fprintf(file, "%soverlay \"%s\" {\n", i_str,
XkbAtomText(dpy, ol->name, XkbMessage));
}
else
fprintf(file, "%soverlay {\n", i_str);
for (nOut = r = 0, row = ol->rows; r < ol->num_rows; r++, row++) {
for (k = 0, key = row->keys; k < row->num_keys; k++, key++) {
char *over, *under;
over = XkbKeyNameText(key->over.name, XkbXKBFile);
under = XkbKeyNameText(key->under.name, XkbXKBFile);
if (nOut == 0)
fprintf(file, "%s %6s=%6s", i_str, under, over);
else if ((nOut % 4) == 0)
fprintf(file, ",\n%s %6s=%6s", i_str, under, over);
else
fprintf(file, ", %6s=%6s", under, over);
nOut++;
}
}
fprintf(file, "\n%s};\n", i_str);
return True;
}
static Bool
WriteXKBSection(FILE * file,
Display * dpy,
XkbSectionPtr s,
XkbGeometryPtr geom)
{
register int i;
XkbRowPtr row;
int dfltKeyColor = 0;
fprintf(file, " section \"%s\" {\n",
XkbAtomText(dpy, s->name, XkbXKBFile));
if (s->rows && (s->rows->num_keys > 0)) {
dfltKeyColor = s->rows->keys[0].color_ndx;
fprintf(file, " key.color= \"%s\";\n",
XkbStringText(geom->colors[dfltKeyColor].spec, XkbXKBFile));
}
fprintf(file, " priority= %d;\n", s->priority);
fprintf(file, " top= %s;\n",
XkbGeomFPText(s->top, XkbXKBFile));
fprintf(file, " left= %s;\n",
XkbGeomFPText(s->left, XkbXKBFile));
fprintf(file, " width= %s;\n",
XkbGeomFPText(s->width, XkbXKBFile));
fprintf(file, " height= %s;\n",
XkbGeomFPText(s->height, XkbXKBFile));
if (s->angle != 0) {
fprintf(file, " angle= %s;\n",
XkbGeomFPText(s->angle, XkbXKBFile));
}
for (i = 0, row = s->rows; row && i < s->num_rows; i++, row++) {
fprintf(file, " row {\n");
fprintf(file, " top= %s;\n",
XkbGeomFPText(row->top, XkbXKBFile));
fprintf(file, " left= %s;\n",
XkbGeomFPText(row->left, XkbXKBFile));
if (row->vertical)
fprintf(file, " vertical;\n");
if (row->num_keys > 0) {
register int k;
register XkbKeyPtr key;
int forceNL = 0;
int nThisLine = 0;
fprintf(file, " keys {\n");
for (k = 0, key = row->keys; k < row->num_keys; k++, key++) {
XkbShapePtr shape;
if (key->color_ndx != dfltKeyColor)
forceNL = 1;
if (k == 0) {
fprintf(file, " ");
nThisLine = 0;
}
else if (((nThisLine % 2) == 1) || (forceNL)) {
fprintf(file, ",\n ");
forceNL = nThisLine = 0;
}
else {
fprintf(file, ", ");
nThisLine++;
}
shape = XkbKeyShape(geom, key);
fprintf(file, "{ %6s, \"%s\", %3s",
XkbKeyNameText(key->name.name, XkbXKBFile),
XkbAtomText(dpy, shape->name, XkbXKBFile),
XkbGeomFPText(key->gap, XkbXKBFile));
if (key->color_ndx != dfltKeyColor) {
fprintf(file, ", color=\"%s\"",
XkbKeyColor(geom, key)->spec);
forceNL = 1;
}
fprintf(file, " }");
}
fprintf(file, "\n };\n");
}
fprintf(file, " };\n");
}
if (s->doodads != NULL) {
XkbDoodadPtr doodad;
for (i = 0, doodad = s->doodads; i < s->num_doodads; i++, doodad++) {
WriteXKBDoodad(file, dpy, 8, geom, doodad);
}
}
if (s->overlays != NULL) {
XkbOverlayPtr ol;
for (i = 0, ol = s->overlays; i < s->num_overlays; i++, ol++) {
WriteXKBOverlay(file, dpy, 8, geom, ol);
}
}
fprintf(file, " }; // End of \"%s\" section\n\n",
XkbAtomText(dpy, s->name, XkbXKBFile));
return True;
}
Bool
XkbWriteXKBGeometry(FILE * file,
XkbFileInfo * result,
Bool topLevel,
Bool showImplicit,
XkbFileAddOnFunc addOn,
void * priv)
{
Display *dpy;
register unsigned i, n;
XkbDescPtr xkb;
XkbGeometryPtr geom;
xkb = result->xkb;
if ((!xkb) || (!xkb->geom)) {
_XkbLibError(_XkbErrMissingGeometry, "XkbWriteXKBGeometry", 0);
return False;
}
dpy = xkb->dpy;
geom = xkb->geom;
if (geom->name == None)
fprintf(file, "xkb_geometry {\n\n");
else
fprintf(file, "xkb_geometry \"%s\" {\n\n",
XkbAtomText(dpy, geom->name, XkbXKBFile));
fprintf(file, " width= %s;\n",
XkbGeomFPText(geom->width_mm, XkbXKBFile));
fprintf(file, " height= %s;\n\n",
XkbGeomFPText(geom->height_mm, XkbXKBFile));
if (geom->key_aliases != NULL) {
XkbKeyAliasPtr pAl;
pAl = geom->key_aliases;
for (i = 0; i < geom->num_key_aliases; i++, pAl++) {
fprintf(file, " alias %6s = %6s;\n",
XkbKeyNameText(pAl->alias, XkbXKBFile),
XkbKeyNameText(pAl->real, XkbXKBFile));
}
fprintf(file, "\n");
}
if (geom->base_color != NULL)
fprintf(file, " baseColor= \"%s\";\n",
XkbStringText(geom->base_color->spec, XkbXKBFile));
if (geom->label_color != NULL)
fprintf(file, " labelColor= \"%s\";\n",
XkbStringText(geom->label_color->spec, XkbXKBFile));
if (geom->label_font != NULL)
fprintf(file, " xfont= \"%s\";\n",
XkbStringText(geom->label_font, XkbXKBFile));
if ((geom->num_colors > 0) && (showImplicit)) {
XkbColorPtr color;
for (color = geom->colors, i = 0; i < geom->num_colors; i++, color++) {
fprintf(file, "// color[%d]= \"%s\"\n", i,
XkbStringText(color->spec, XkbXKBFile));
}
fprintf(file, "\n");
}
if (geom->num_properties > 0) {
XkbPropertyPtr prop;
for (prop = geom->properties, i = 0; i < geom->num_properties;
i++, prop++) {
fprintf(file, " %s= \"%s\";\n", prop->name,
XkbStringText(prop->value, XkbXKBFile));
}
fprintf(file, "\n");
}
if (geom->num_shapes > 0) {
XkbShapePtr shape;
XkbOutlinePtr outline;
int lastR;
for (shape = geom->shapes, i = 0; i < geom->num_shapes; i++, shape++) {
lastR = 0;
fprintf(file, " shape \"%s\" {",
XkbAtomText(dpy, shape->name, XkbXKBFile));
outline = shape->outlines;
if (shape->num_outlines > 1) {
for (n = 0; n < shape->num_outlines; n++, outline++) {
if (n == 0)
fprintf(file, "\n");
else
fprintf(file, ",\n");
WriteXKBOutline(file, shape, outline, lastR, 8, 8);
lastR = outline->corner_radius;
}
fprintf(file, "\n };\n");
}
else {
WriteXKBOutline(file, NULL, outline, lastR, 1, 8);
fprintf(file, " };\n");
}
}
}
if (geom->num_sections > 0) {
XkbSectionPtr section;
for (section = geom->sections, i = 0; i < geom->num_sections;
i++, section++) {
WriteXKBSection(file, dpy, section, geom);
}
}
if (geom->num_doodads > 0) {
XkbDoodadPtr doodad;
for (i = 0, doodad = geom->doodads; i < geom->num_doodads;
i++, doodad++) {
WriteXKBDoodad(file, dpy, 4, geom, doodad);
}
}
if (addOn)
(*addOn) (file, result, topLevel, showImplicit, XkmGeometryIndex, priv);
fprintf(file, "};\n\n");
return True;
}
/*ARGSUSED*/
Bool
XkbWriteXKBSemantics(FILE * file,
XkbFileInfo * result,
Bool topLevel,
Bool showImplicit,
XkbFileAddOnFunc addOn,
void * priv)
{
Bool ok;
fprintf(file, "xkb_semantics {\n");
ok = XkbWriteXKBKeyTypes(file, result, False, False, addOn, priv);
ok = ok && XkbWriteXKBCompatMap(file, result, False, False, addOn, priv);
fprintf(file, "};\n");
return ok;
}
/*ARGSUSED*/
Bool
XkbWriteXKBLayout(FILE * file,
XkbFileInfo * result,
Bool topLevel,
Bool showImplicit,
XkbFileAddOnFunc addOn,
void * priv)
{
Bool ok;
XkbDescPtr xkb;
xkb = result->xkb;
fprintf(file, "xkb_layout {\n");
ok = XkbWriteXKBKeycodes(file, result, False, showImplicit, addOn, priv);
ok = ok &&
XkbWriteXKBKeyTypes(file, result, False, showImplicit, addOn, priv);
ok = ok &&
XkbWriteXKBSymbols(file, result, False, showImplicit, addOn, priv);
if (xkb->geom)
ok = ok &&
XkbWriteXKBGeometry(file, result, False, showImplicit, addOn, priv);
fprintf(file, "};\n");
return ok;
}
/*ARGSUSED*/
Bool
XkbWriteXKBKeymap(FILE * file,
XkbFileInfo * result,
Bool topLevel,
Bool showImplicit,
XkbFileAddOnFunc addOn,
void * priv)
{
Bool ok;
XkbDescPtr xkb;
xkb = result->xkb;
fprintf(file, "xkb_keymap {\n");
ok = XkbWriteXKBKeycodes(file, result, False, showImplicit, addOn, priv);
ok = ok &&
XkbWriteXKBKeyTypes(file, result, False, showImplicit, addOn, priv);
ok = ok &&
XkbWriteXKBCompatMap(file, result, False, showImplicit, addOn, priv);
ok = ok &&
XkbWriteXKBSymbols(file, result, False, showImplicit, addOn, priv);
if (xkb->geom)
ok = ok &&
XkbWriteXKBGeometry(file, result, False, showImplicit, addOn, priv);
fprintf(file, "};\n");
return ok;
}
Bool
XkbWriteXKBFile(FILE * out,
XkbFileInfo * result,
Bool showImplicit,
XkbFileAddOnFunc addOn,
void * priv)
{
Bool ok = False;
Bool (*func) (FILE * /* file */ ,
XkbFileInfo * /* result */ ,
Bool /* topLevel */ ,
Bool /* showImplicit */ ,
XkbFileAddOnFunc /* addOn */ ,
void * /* priv */
) = NULL;
switch (result->type) {
case XkmSemanticsFile:
func = XkbWriteXKBSemantics;
break;
case XkmLayoutFile:
func = XkbWriteXKBLayout;
break;
case XkmKeymapFile:
func = XkbWriteXKBKeymap;
break;
case XkmTypesIndex:
func = XkbWriteXKBKeyTypes;
break;
case XkmCompatMapIndex:
func = XkbWriteXKBCompatMap;
break;
case XkmSymbolsIndex:
func = XkbWriteXKBSymbols;
break;
case XkmKeyNamesIndex:
func = XkbWriteXKBKeycodes;
break;
case XkmGeometryFile:
case XkmGeometryIndex:
func = XkbWriteXKBGeometry;
break;
case XkmVirtualModsIndex:
case XkmIndicatorsIndex:
_XkbLibError(_XkbErrBadImplementation,
XkbConfigText(result->type, XkbMessage), 0);
return False;
}
if (out == NULL) {
_XkbLibError(_XkbErrFileCannotOpen, "XkbWriteXkbFile", 0);
ok = False;
}
else if (func) {
ok = (*func) (out, result, True, showImplicit, addOn, priv);
}
return ok;
}
|
220ee1f68dc78e0169cf5bd391079193d359f927
|
665da87f9fefd8678b0635e31df3f3ff28a1d48c
|
/third-party/libtommath-1.2.0/bn_mp_init_ull.c
|
84110c002d285f8324de4aba55020543acaa76dc
|
[
"LicenseRef-scancode-free-unknown",
"Unlicense",
"MIT"
] |
permissive
|
justinethier/cyclone
|
eeb782c20a38f916138ac9a988dc53817eb56e79
|
cc24c6be6d2b7cc16d5e0ee91f0823d7a90a3273
|
refs/heads/master
| 2023-08-30T15:30:09.209833
| 2023-08-22T02:11:59
| 2023-08-22T02:11:59
| 31,150,535
| 862
| 64
|
MIT
| 2023-03-04T15:15:37
| 2015-02-22T03:08:21
|
Scheme
|
UTF-8
|
C
| false
| false
| 228
|
c
|
bn_mp_init_ull.c
|
#include "tommath_private.h"
#ifdef BN_MP_INIT_ULL_C
/* LibTomMath, multiple-precision integer library -- Tom St Denis */
/* SPDX-License-Identifier: Unlicense */
MP_INIT_INT(mp_init_ull, mp_set_ull, unsigned long long)
#endif
|
ea08584c42ddd15455db0b098b13689315d824d9
|
667be8b1a5d7cce70b6424aa22e8c8e56e358fb3
|
/modules/matrix/float/dspm_mult_f32_ansi.c
|
371aa25326bfcc5a95e83e3bfd1d31b9f178c2cd
|
[
"Apache-2.0"
] |
permissive
|
espressif/esp-dsp
|
d9636e15afa879ff28824194cf2408a6637025be
|
2091d66e84e8024dbb182428494073e2151f8e88
|
refs/heads/master
| 2023-07-23T11:22:06.700408
| 2023-07-13T20:24:07
| 2023-07-13T20:24:07
| 165,801,253
| 347
| 81
|
Apache-2.0
| 2023-06-12T08:16:50
| 2019-01-15T06:58:03
|
C
|
UTF-8
|
C
| false
| false
| 1,166
|
c
|
dspm_mult_f32_ansi.c
|
// Copyright 2018-2019 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "dsps_dotprod.h"
#include "dspm_mult.h"
// Matrinx A(m,n), m - amount or rows, n - amount of columns
// C(m,k) = A(m,n)*B(n,k)
// c(i,j) = sum(a(i,s)*b(s,j)) , s=1..n
esp_err_t dspm_mult_f32_ansi(const float *A, const float *B, float *C, int m, int n, int k)
{
for (int i = 0 ; i < m ; i++) {
for (int j = 0 ; j < k ; j++) {
C[i * k + j] = A[i * n] * B[j];
for (int s = 1; s < n ; s++) {
C[i * k + j] += A[i * n + s] * B[s * k + j];
}
}
}
return ESP_OK;
}
|
a3e73bcf277c4ea004f565b8208a979b496829cb
|
b452bbb87214f174122f425f6f98f4c3890c3cca
|
/internal/ccall/cgraph/edge.c
|
5256cd16da2ebc0946f27da0b02d664fdd68ca9c
|
[
"MIT"
] |
permissive
|
goccy/go-graphviz
|
bea9bc86b42734aff7ffae283aeae71702ca588a
|
865af036ddbb745c4424bbd2fdaa9a75668cf0d4
|
refs/heads/master
| 2023-07-20T08:05:39.868377
| 2023-03-21T23:49:44
| 2023-03-21T23:49:44
| 236,740,615
| 511
| 66
|
MIT
| 2023-07-07T13:53:28
| 2020-01-28T13:24:09
|
Go
|
UTF-8
|
C
| false
| false
| 11,900
|
c
|
edge.c
|
/* $Id$ $Revision$ */
/* vim:set shiftwidth=4 ts=8: */
/*************************************************************************
* Copyright (c) 2011 AT&T Intellectual Property
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: See CVS logs. Details at http://www.graphviz.org/
*************************************************************************/
#include <cghdr.h>
#define IN_SET FALSE
#define OUT_SET TRUE
#define ID_ORDER TRUE
#define SEQ_ORDER FALSE
static Agtag_t Tag; /* to silence warnings about initialization */
/* return first outedge of <n> */
Agedge_t *agfstout(Agraph_t * g, Agnode_t * n)
{
Agsubnode_t *sn;
Agedge_t *e = NILedge;
sn = agsubrep(g, n);
if (sn) {
dtrestore(g->e_seq, sn->out_seq);
e = (Agedge_t *) dtfirst(g->e_seq);
sn->out_seq = dtextract(g->e_seq);
}
return e;
}
/* return outedge that follows <e> of <n> */
Agedge_t *agnxtout(Agraph_t * g, Agedge_t * e)
{
Agnode_t *n;
Agsubnode_t *sn;
Agedge_t *f = NILedge;
n = AGTAIL(e);
sn = agsubrep(g, n);
if (sn) {
dtrestore(g->e_seq, sn->out_seq);
f = (Agedge_t *) dtnext(g->e_seq, e);
sn->out_seq = dtextract(g->e_seq);
}
return f;
}
Agedge_t *agfstin(Agraph_t * g, Agnode_t * n)
{
Agsubnode_t *sn;
Agedge_t *e = NILedge;
sn = agsubrep(g, n);
if (sn) {
dtrestore(g->e_seq, sn->in_seq);
e = (Agedge_t *) dtfirst(g->e_seq);
sn->in_seq = dtextract(g->e_seq);
}
return e;
}
Agedge_t *agnxtin(Agraph_t * g, Agedge_t * e)
{
Agnode_t *n;
Agsubnode_t *sn;
Agedge_t *f = NILedge;
n = AGHEAD(e);
sn = agsubrep(g, n);
if (sn) {
dtrestore(g->e_seq, sn->in_seq);
f = (Agedge_t *) dtnext(g->e_seq, e);
sn->in_seq = dtextract(g->e_seq);
}
return f;
}
Agedge_t *agfstedge(Agraph_t * g, Agnode_t * n)
{
Agedge_t *rv;
rv = agfstout(g, n);
if (rv == NILedge)
rv = agfstin(g, n);
return rv;
}
Agedge_t *agnxtedge(Agraph_t * g, Agedge_t * e, Agnode_t * n)
{
Agedge_t *rv;
if (AGTYPE(e) == AGOUTEDGE) {
rv = agnxtout(g, e);
if (rv == NILedge) {
do {
rv = !rv ? agfstin(g, n) : agnxtin(g,rv);
} while (rv && (rv->node == n));
}
} else {
do {
rv = agnxtin(g, e); /* so that we only see each edge once, */
e = rv;
} while (rv && (rv->node == n)); /* ignore loops as in-edges */
}
return rv;
}
/* internal edge set lookup */
static Agedge_t *agfindedge_by_key(Agraph_t * g, Agnode_t * t, Agnode_t * h,
Agtag_t key)
{
Agedge_t *e, template;
Agsubnode_t *sn;
if ((t == NILnode) || (h == NILnode))
return NILedge;
template.base.tag = key;
template.node = t; /* guess that fan-in < fan-out */
sn = agsubrep(g, h);
if (!sn) e = 0;
else {
#if 0
if (t != h) {
#endif
dtrestore(g->e_id, sn->in_id);
e = (Agedge_t *) dtsearch(g->e_id, &template);
sn->in_id = dtextract(g->e_id);
#if 0
} else { /* self edge */
dtrestore(g->e_id, sn->out_id);
e = (Agedge_t *) dtsearch(g->e_id, &template);
sn->out_id = dtextract(g->e_id);
}
#endif
}
return e;
}
static Agedge_t *agfindedge_by_id(Agraph_t * g, Agnode_t * t, Agnode_t * h,
IDTYPE id)
{
Agtag_t tag;
tag = Tag;
tag.objtype = AGEDGE;
tag.id = id;
return agfindedge_by_key(g, t, h, tag);
}
Agsubnode_t *agsubrep(Agraph_t * g, Agnode_t * n)
{
Agsubnode_t *sn, template;
if (g == n->root) sn = &(n->mainsub);
else {
template.node = n;
sn = dtsearch(g->n_id, &template);
}
return sn;
}
static void ins(Dict_t * d, Dtlink_t ** set, Agedge_t * e)
{
dtrestore(d, *set);
dtinsert(d, e);
*set = dtextract(d);
}
static void del(Dict_t * d, Dtlink_t ** set, Agedge_t * e)
{
void *x;
dtrestore(d, *set);
x = dtdelete(d, e);
assert(x);
*set = dtextract(d);
}
static void installedge(Agraph_t * g, Agedge_t * e)
{
Agnode_t *t, *h;
Agedge_t *out, *in;
Agsubnode_t *sn;
out = AGMKOUT(e);
in = AGMKIN(e);
t = agtail(e);
h = aghead(e);
while (g) {
if (agfindedge_by_key(g, t, h, AGTAG(e))) break;
sn = agsubrep(g, t);
ins(g->e_seq, &sn->out_seq, out);
ins(g->e_id, &sn->out_id, out);
sn = agsubrep(g, h);
ins(g->e_seq, &sn->in_seq, in);
ins(g->e_id, &sn->in_id, in);
g = agparent(g);
}
}
static void subedge(Agraph_t * g, Agedge_t * e)
{
installedge(g, e);
/* might an init method call be needed here? */
}
static Agedge_t *newedge(Agraph_t * g, Agnode_t * t, Agnode_t * h,
IDTYPE id)
{
Agedgepair_t *e2;
Agedge_t *in, *out;
int seq;
(void)agsubnode(g,t,TRUE);
(void)agsubnode(g,h,TRUE);
e2 = (Agedgepair_t *) agalloc(g, sizeof(Agedgepair_t));
in = &(e2->in);
out = &(e2->out);
seq = agnextseq(g, AGEDGE);
AGTYPE(in) = AGINEDGE;
AGTYPE(out) = AGOUTEDGE;
AGID(in) = AGID(out) = id;
AGSEQ(in) = AGSEQ(out) = seq;
in->node = t;
out->node = h;
installedge(g, out);
if (g->desc.has_attrs) {
(void) agbindrec(out, AgDataRecName, sizeof(Agattr_t), FALSE);
agedgeattr_init(g, out);
}
agmethod_init(g, out);
return out;
}
/* edge creation predicate */
static int ok_to_make_edge(Agraph_t * g, Agnode_t * t, Agnode_t * h)
{
Agtag_t key;
/* protect against self, multi-edges in strict graphs */
if (agisstrict(g)) {
key = Tag;
key.objtype = 0; /* wild card */
if (agfindedge_by_key(g, t, h, key))
return FALSE;
}
if (g->desc.no_loop && (t == h)) /* simple graphs */
return FALSE;
return TRUE;
}
Agedge_t *agidedge(Agraph_t * g, Agnode_t * t, Agnode_t * h,
IDTYPE id, int cflag)
{
Agraph_t *root;
Agedge_t *e;
e = agfindedge_by_id(g, t, h, id);
if ((e == NILedge) && agisundirected(g))
e = agfindedge_by_id(g, h, t, id);
if ((e == NILedge) && cflag && ok_to_make_edge(g, t, h)) {
root = agroot(g);
if ((g != root) && ((e = agfindedge_by_id(root, t, h, id)))) {
subedge(g, e); /* old */
} else {
if (agallocid(g, AGEDGE, id)) {
e = newedge(g, t, h, id); /* new */
}
}
}
return e;
}
Agedge_t *agedge(Agraph_t * g, Agnode_t * t, Agnode_t * h, char *name,
int cflag)
{
Agedge_t *e;
IDTYPE my_id;
int have_id;
have_id = agmapnametoid(g, AGEDGE, name, &my_id, FALSE);
if (have_id || ((name == NILstr) && (NOT(cflag) || agisstrict(g)))) {
/* probe for pre-existing edge */
Agtag_t key;
key = Tag;
if (have_id) {
key.id = my_id;
key.objtype = AGEDGE;
} else {
key.id = key.objtype = 0;
}
/* might already exist locally */
e = agfindedge_by_key(g, t, h, key);
if ((e == NILedge) && agisundirected(g))
e = agfindedge_by_key(g, h, t, key);
if (e)
return e;
if (cflag) {
e = agfindedge_by_key(agroot(g), t, h, key);
if ((e == NILedge) && agisundirected(g))
e = agfindedge_by_key(agroot(g), h, t, key);
if (e) {
subedge(g,e);
return e;
}
}
}
if (cflag && ok_to_make_edge(g, t, h)
&& agmapnametoid(g, AGEDGE, name, &my_id, TRUE)) { /* reserve id */
e = newedge(g, t, h, my_id);
agregister(g, AGEDGE, e); /* register new object in external namespace */
}
else
e = NILedge;
return e;
}
void agdeledgeimage(Agraph_t * g, Agedge_t * e, void *ignored)
{
Agedge_t *in, *out;
Agnode_t *t, *h;
Agsubnode_t *sn;
NOTUSED(ignored);
if (AGTYPE(e) == AGINEDGE) {
in = e;
out = AGIN2OUT(e);
} else {
out = e;
in = AGOUT2IN(e);
}
t = in->node;
h = out->node;
sn = agsubrep(g, t);
del(g->e_seq, &sn->out_seq, out);
del(g->e_id, &sn->out_id, out);
sn = agsubrep(g, h);
del(g->e_seq, &sn->in_seq, in);
del(g->e_id, &sn->in_id, in);
#ifdef DEBUG
for (e = agfstin(g,h); e; e = agnxtin(g,e))
assert(e != in);
for (e = agfstout(g,t); e; e = agnxtout(g,e))
assert(e != out);
#endif
}
int agdeledge(Agraph_t * g, Agedge_t * e)
{
e = AGMKOUT(e);
if (agfindedge_by_key(g, agtail(e), aghead(e), AGTAG(e)) == NILedge)
return FAILURE;
if (g == agroot(g)) {
if (g->desc.has_attrs)
agedgeattr_delete(e);
agmethod_delete(g, e);
agrecclose((Agobj_t *) e);
agfreeid(g, AGEDGE, AGID(e));
}
if (agapply (g, (Agobj_t *) e, (agobjfn_t) agdeledgeimage, NILedge, FALSE) == SUCCESS) {
if (g == agroot(g))
agfree(g, e);
return SUCCESS;
} else
return FAILURE;
}
Agedge_t *agsubedge(Agraph_t * g, Agedge_t * e, int cflag)
{
Agnode_t *t, *h;
Agedge_t *rv;
rv = NILedge;
t = agsubnode(g, AGTAIL(e), cflag);
h = agsubnode(g, AGHEAD(e), cflag);
if (t && h) {
rv = agfindedge_by_key(g, t, h, AGTAG(e));
if (cflag && (rv == NILedge)) {
#ifdef OLD_OBSOLETE
rv = agfindedge_by_id(g, t, h, AGID(e));
if (!rv)
rv = newedge(g, t, h, AGID(e));
#else
installedge(g, e);
rv = e;
#endif
}
if (rv && (AGTYPE(rv) != AGTYPE(e)))
rv = AGOPP(rv);
}
return rv;
}
/* edge comparison. AGTYPE(e) == 0 means ID is a wildcard. */
int agedgeidcmpf(Dict_t * d, void *arg_e0, void *arg_e1, Dtdisc_t * disc)
{
Agedge_t *e0, *e1;
NOTUSED(d);
e0 = arg_e0;
e1 = arg_e1;
NOTUSED(disc);
if (AGID(e0->node) < AGID(e1->node)) return -1;
if (AGID(e0->node) > AGID(e1->node)) return 1;
/* same node */
if ((AGTYPE(e0) != 0) && (AGTYPE(e1) != 0)) {
if (AGID(e0) < AGID(e1)) return -1;
if (AGID(e0) > AGID(e1)) return 1;
}
return 0;
}
/* edge comparison. for ordered traversal. */
int agedgeseqcmpf(Dict_t * d, void *arg_e0, void *arg_e1, Dtdisc_t * disc)
{
Agedge_t *e0, *e1;
NOTUSED(d);
e0 = arg_e0;
e1 = arg_e1;
NOTUSED(disc);
assert(arg_e0 && arg_e1);
if (e0->node != e1->node) {
if (AGSEQ(e0->node) < AGSEQ(e1->node)) return -1;
if (AGSEQ(e0->node) > AGSEQ(e1->node)) return 1;
}
else {
if (AGSEQ(e0) < AGSEQ(e1)) return -1;
if (AGSEQ(e0) > AGSEQ(e1)) return 1;
}
return 0;
}
/* indexing for ordered traversal */
Dtdisc_t Ag_mainedge_seq_disc = {
0, /* pass object ptr */
0, /* size (ignored) */
offsetof(Agedge_t,seq_link),/* use internal links */
NIL(Dtmake_f),
NIL(Dtfree_f),
agedgeseqcmpf,
NIL(Dthash_f),
agdictobjmem,
NIL(Dtevent_f)
};
Dtdisc_t Ag_subedge_seq_disc = {
0, /* pass object ptr */
0, /* size (ignored) */
-1, /* use external holder objects */
NIL(Dtmake_f),
NIL(Dtfree_f),
agedgeseqcmpf,
NIL(Dthash_f),
agdictobjmem,
NIL(Dtevent_f)
};
/* indexing for random search */
Dtdisc_t Ag_mainedge_id_disc = {
0, /* pass object ptr */
0, /* size (ignored) */
offsetof(Agedge_t,id_link), /* use internal links */
NIL(Dtmake_f),
NIL(Dtfree_f),
agedgeidcmpf,
NIL(Dthash_f),
agdictobjmem,
NIL(Dtevent_f)
};
Dtdisc_t Ag_subedge_id_disc = {
0, /* pass object ptr */
0, /* size (ignored) */
-1, /* use external holder objects */
NIL(Dtmake_f),
NIL(Dtfree_f),
agedgeidcmpf,
NIL(Dthash_f),
agdictobjmem,
NIL(Dtevent_f)
};
/* debug functions */
#ifdef agtail
#undef agtail
#endif
Agnode_t *agtail(Agedge_t * e)
{
return AGTAIL(e);
}
#ifdef aghead
#undef aghead
#endif
Agnode_t *aghead(Agedge_t * e)
{
return AGHEAD(e);
}
#ifdef agopp
#undef agopp
#endif
Agedge_t *agopp(Agedge_t * e)
{
return AGOPP(e);
}
#ifdef NOTDEF
/* could be useful if we write relabel_edge */
static Agedge_t *agfindedge_by_name(Agraph_t * g, Agnode_t * t,
Agnode_t * h, char *name)
{
uint64_t id;
if (agmapnametoid(agraphof(t), AGEDGE, name, &id, FALSE))
return agfindedge_by_id(g, t, h, id);
else
return NILedge;
}
#endif
|
5e5eccf480d632b88ddd39cb265dfc21ab031bae
|
4cd1537b92864ee108def7886aafc0f924f97c0f
|
/src/dogstatsd/client.c
|
25d69274a789e9035e4ed910756b699733592a18
|
[
"Apache-2.0",
"BSD-3-Clause"
] |
permissive
|
DataDog/dd-trace-php
|
68f08674208ef9ec1c874e3eabd7b88f1d6dd5dd
|
014989e42bfa5919f451cee3ae2b57cc35bdee9b
|
refs/heads/master
| 2023-09-01T15:36:22.838634
| 2023-09-01T13:17:02
| 2023-09-01T13:17:02
| 119,990,860
| 363
| 166
|
NOASSERTION
| 2023-09-13T16:09:22
| 2018-02-02T14:21:54
|
PHP
|
UTF-8
|
C
| false
| false
| 5,483
|
c
|
client.c
|
#include "dogstatsd_client/client.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
/* These functions are inline, but need to go in a translation unit somewhere
* to avoid certain linker errors. The extern inline handles this.
*/
extern inline dogstatsd_client dogstatsd_client_default_ctor();
extern inline bool dogstatsd_client_is_default_client(dogstatsd_client client);
extern inline const char *dogstatsd_metric_type_to_str(dogstatsd_metric_t type);
extern inline const char *dogstatsd_client_status_to_str(
dogstatsd_client_status status);
extern inline dogstatsd_client_status dogstatsd_client_count(
dogstatsd_client *client, const char *metric, const char *value,
const char *tags);
extern inline dogstatsd_client_status dogstatsd_client_gauge(
dogstatsd_client *client, const char *metric, const char *value,
const char *tags);
extern inline dogstatsd_client_status dogstatsd_client_histogram(
dogstatsd_client *client, const char *metric, const char *value,
const char *tags);
int dogstatsd_client_getaddrinfo(struct addrinfo **result, const char *host,
const char *port) {
struct addrinfo hints;
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_protocol = IPPROTO_UDP;
hints.ai_flags = AI_NUMERICSERV;
/* resolve the domain name into a list of addresses */
return getaddrinfo(host, port, &hints, result);
}
dogstatsd_client dogstatsd_client_ctor(struct addrinfo *addrs, int buffer_len,
const char *const_tags) {
dogstatsd_client client = dogstatsd_client_default_ctor();
if (!addrs) {
return client;
}
client.addresslist = addrs;
struct addrinfo *addr = NULL;
if (buffer_len < 0) {
return client;
}
/* loop over all returned results and do inverse lookup */
for (addr = client.addresslist; addr != NULL; addr = addr->ai_next) {
if ((client.socket = socket(addr->ai_family, addr->ai_socktype,
addr->ai_protocol)) != -1) {
break;
}
}
if (addr->ai_family == PF_UNIX) {
if (!connect(client.socket, addr->ai_addr, addr->ai_addrlen)) {
free(addr->ai_addr);
free(client.addresslist);
client.addresslist = NULL;
close(client.socket);
client.socket = -1;
return client;
}
}
if (!const_tags) {
const_tags = "";
}
client.const_tags = const_tags;
client.const_tags_len = strlen(const_tags);
client.address = addr;
client.msg_buffer = malloc(buffer_len);
client.msg_buffer_len = buffer_len;
return client;
}
void dogstatsd_client_dtor(dogstatsd_client *client) {
if (!client) {
return;
}
if (client->msg_buffer) {
free(client->msg_buffer);
}
if (client->socket != -1) {
close(client->socket);
client->socket = -1;
}
if (client->addresslist) {
if (client->address->ai_family == PF_UNIX) {
free(client->address->ai_addr);
free(client->addresslist);
} else {
freeaddrinfo(client->addresslist);
}
client->addresslist = NULL;
}
}
/* allowed metric types: c, g, ms, h, and s.
* sample_rate must be between 0.0 and 1.0 (inclusive); if you are unsure then
* specify 1.0.
*/
dogstatsd_client_status dogstatsd_client_metric_send(
dogstatsd_client *client, const char *name, const char *value,
dogstatsd_metric_t type, double sample_rate, const char *tags) {
if (dogstatsd_client_is_default_client(*client)) {
return DOGSTATSD_CLIENT_E_NO_CLIENT;
}
const char *typestr = dogstatsd_metric_type_to_str(type);
if (!name || !value || !typestr || sample_rate < 0.0 || sample_rate > 1.0) {
return DOGSTATSD_CLIENT_E_VALUE;
}
/* We need to concatenate all the strings together (without spaces, they
* are there just to show how the format maps):
* metric : value | type |@ sample_rate |# tags , const_tags
* %s : %s | %s |@ %f %s %s %s %s
*/
if (!tags) {
tags = "";
}
size_t tags_len = strlen(tags);
size_t const_tags_len = client->const_tags_len;
const char *tags_prefix = (tags_len + const_tags_len > 0) ? "|#" : "";
const char *tags_separator = (tags_len > 0 && const_tags_len > 0) ? "," : "";
const char *format;
int size;
/* Omit the sample rate iff it is 1.0; a sample rate of 1.000000 causes issues
* for the agent, for some reason
*/
if (sample_rate != 1.0) {
format = "%s:%s|%s|@%.6f%s%s%s%s";
size = snprintf(client->msg_buffer, client->msg_buffer_len, format, name,
value, typestr, sample_rate, tags_prefix, tags,
tags_separator, client->const_tags);
} else {
format = "%s:%s|%s%s%s%s%s";
size = snprintf(client->msg_buffer, client->msg_buffer_len, format, name,
value, typestr, tags_prefix, tags, tags_separator,
client->const_tags);
}
if (size < 0) {
return DOGSTATSD_CLIENT_E_FORMATTING;
}
/* snprintf does not report the null byte in the length, so if it is size or
* more then it is an error
*/
if (size >= client->msg_buffer_len) {
return DOGSTATSD_CLIENT_E_TOO_LONG;
}
ssize_t send_status =
sendto(client->socket, client->msg_buffer, size, MSG_DONTWAIT,
client->address->ai_addr, client->address->ai_addrlen);
if (send_status > -1) {
return DOGSTATSD_CLIENT_OK;
}
return DOGSTATSD_CLIENT_EWRITE;
}
|
de93fcc41bf48ffed25dddbf74d233795d0a8e6b
|
84f1ce4838c39cec710818d69005f8919ec39994
|
/src/arch/armv8/armv8-a/inc/arch/page_table.h
|
bcfd2e4d61f7efa7dd422887877981149b52ac81
|
[
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] |
permissive
|
bao-project/bao-hypervisor
|
adb2689fdd690d10ea11fa693375c4043a9f9309
|
291cac3df9d5e0b4704006376196cd2231105704
|
refs/heads/main
| 2023-08-31T05:50:21.845457
| 2023-07-25T19:46:28
| 2023-08-22T12:09:57
| 233,099,706
| 231
| 78
|
Apache-2.0
| 2023-09-14T13:58:26
| 2020-01-10T17:42:11
|
C
|
UTF-8
|
C
| false
| false
| 5,145
|
h
|
page_table.h
|
/**
* SPDX-License-Identifier: Apache-2.0
* Copyright (c) Bao Project and Contributors. All rights reserved.
*/
#ifndef __ARCH_PAGE_TABLE_H__
#define __ARCH_PAGE_TABLE_H__
#include <bao.h>
#include <bit.h>
#ifdef __ASSEMBLER__
#define PT_SIZE PAGE_SIZE
#define PTE_INDEX_SHIFT(LEVEL) ((9 * (3 - LEVEL)) + 12)
#define PTE_INDEX(LEVEL, ADDR) ((ADDR >> PTE_INDEX_SHIFT(LEVEL)) & (0x1FF))
.macro PTE_INDEX_ASM index, addr, level
lsr \index, \addr, #PTE_INDEX_SHIFT(\level)
and \index, \index, #0x1ff
lsl \index, \index, #3
.endm
#endif
#ifdef AARCH32
#define PT_SHARED_LVL (1)
#else
#define PT_SHARED_LVL (0)
#endif
#define HYP_ROOT_PT_SIZE PAGE_SIZE
#define ADDR_MSK(MSB, LSB) (((1ULL << (MSB + 1)) - 1) & ~((1ULL << (LSB)) - 1))
#define PTE_ADDR_MSK ADDR_MSK(47, 12)
#define PTE_FLAGS_MSK (~PTE_ADDR_MSK)
#define PTE_MASK(OFF, LEN) BIT64_MASK(OFF, LEN)
#define PTE_TYPE_MSK (0x3)
#define PTE_VALID (0x1)
#define PTE_SUPERPAGE (0x1)
#define PTE_TABLE (0x3)
#define PTE_PAGE (0x3)
#define PTE_NSTable (1LL << 63)
#define PTE_APTable_OFF (61)
#define PTE_APTable_MSK (0x3LL << PTE_APTable_OFF)
#define PTE_APTable_ALL (0x0LL << PTE_APTable_OFF)
#define PTE_APTable_NOEL0 (0x1LL << PTE_APTable_OFF)
#define PTE_APTable_RO (0x2LL << PTE_APTable_OFF)
#define PTE_APTable_RO_NOEL0 (0x3LL << PTE_APTable_OFF)
#define PTE_XNTable (1LL << 60)
#define PTE_PXNTable (1LL << 59)
#define PTE_PBHA_OFF (59)
#define PTE_PBHA_MSK (0xf << PTE_PBHA_OFF)
#define PTE_PBHA(VAL) ((VAL << PTE_PBHA_OFF) & PTE_PBHA_MSK)
#define PTE_XN (1LL << 54)
#define PTE_PXN (1LL << 53)
#define PTE_Con (1LL << 52)
#define PTE_DBM (1LL << 51)
#define PTE_nG (1LL << 11)
#define PTE_AF (1LL << 10)
#define PTE_SH_OFF (8)
#define PTE_SH_MSK (0x3LL << PTE_SH_OFF)
#define PTE_SH_NS (0x0LL << PTE_SH_OFF)
#define PTE_SH_OS (0x2LL << PTE_SH_OFF)
#define PTE_SH_IS (0x3LL << PTE_SH_OFF)
#define PTE_AP_OFF (6)
#define PTE_AP_MSK (0x3LL << PTE_AP_OFF)
#define PTE_AP_RW_PRIV (0x0LL << PTE_AP_OFF)
#define PTE_AP_RO_PRIV (0x2LL << PTE_AP_OFF)
#define PTE_AP_RW (0x1LL << PTE_AP_OFF)
#define PTE_AP_RO (0x3LL << PTE_AP_OFF)
#define PTE_NS (1 << 5)
#define PTE_ATTR_OFF (2)
#define PTE_ATTR_MSK (0x7LL << PTE_ATTR_OFF)
#define PTE_ATTR(N) ((N << PTE_ATTR_OFF) & PTE_ATTR_MSK)
/* Stage 2 fields */
#define PTE_MEMATTR_OFF (2)
#define PTE_MEMATTR_DEV_nGnRnE ((0x00 << 0) << PTE_MEMATTR_OFF)
#define PTE_MEMATTR_DEV_nGnRE ((0x01 << 0) << PTE_MEMATTR_OFF)
#define PTE_MEMATTR_DEV_nGRE ((0x02 << 0) << PTE_MEMATTR_OFF)
#define PTE_MEMATTR_DEV_GRE ((0x03 << 0) << PTE_MEMATTR_OFF)
#define PTE_MEMATTR_NRML_ONC ((0x01 << 2) << PTE_MEMATTR_OFF)
#define PTE_MEMATTR_NRML_OWTC ((0x02 << 2) << PTE_MEMATTR_OFF)
#define PTE_MEMATTR_NRML_OWBC ((0x03 << 2) << PTE_MEMATTR_OFF)
#define PTE_MEMATTR_NRML_INC ((0x01 << 0) << PTE_MEMATTR_OFF)
#define PTE_MEMATTR_NRML_IWTC ((0x02 << 0) << PTE_MEMATTR_OFF)
#define PTE_MEMATTR_NRML_IWBC ((0x03 << 0) << PTE_MEMATTR_OFF)
#define PTE_S2AP_RO (0x1 << PTE_AP_OFF)
#define PTE_S2AP_WO (0x2 << PTE_AP_OFF)
#define PTE_S2AP_RW (0x3 << PTE_AP_OFF)
#define PTE_RSW_OFF (55)
#define PTE_RSW_WDT (4)
#define PTE_RSW_MSK \
(((1ULL << (PTE_RSW_OFF + PTE_RSW_WDT)) - 1) - ((1ULL << (PTE_RSW_OFF)) - 1))
/* ------------------------------------------------------------- */
#define PTE_RSW_EMPT (0x0LL << PTE_RSW_OFF)
#define PTE_RSW_OPEN (0x1LL << PTE_RSW_OFF)
#define PTE_RSW_FULL (0x2LL << PTE_RSW_OFF)
#define PTE_RSW_RSRV (0x3LL << PTE_RSW_OFF)
#define PT_ROOT_FLAGS_REC_IND_OFF (0)
#define PT_ROOT_FLAGS_REC_IND_LEN (13)
#define PT_ROOT_FLAGS_REC_IND_MSK \
BIT64_MASK(PT_ROOT_FLAGS_REC_IND_OFF, PT_ROOT_FLAGS_REC_IND_LEN)
#define PT_CPU_REC_IND (pt_nentries(&cpu()->as.pt, 0) - 1)
#define PT_VM_REC_IND (pt_nentries(&cpu()->as.pt, 0) - 2)
#define PTE_INVALID (0)
#define PTE_HYP_FLAGS (PTE_ATTR(1) | PTE_AP_RW | PTE_SH_IS | PTE_AF)
#define PTE_HYP_DEV_FLAGS \
(PTE_ATTR(2) | PTE_AP_RW | PTE_SH_IS | PTE_AF | PTE_XN)
#define PTE_VM_FLAGS \
(PTE_MEMATTR_NRML_OWBC | PTE_MEMATTR_NRML_IWBC | PTE_SH_NS | PTE_S2AP_RW | \
PTE_AF)
#define PTE_VM_DEV_FLAGS \
(PTE_MEMATTR_DEV_GRE | PTE_SH_NS | PTE_S2AP_RW | PTE_AF)
#ifndef __ASSEMBLER__
typedef uint64_t pte_t;
typedef pte_t pte_type_t;
typedef pte_t pte_flags_t;
extern size_t parange;
extern size_t parange_table[];
struct page_table;
struct page_table_arch {
pte_t rec_mask;
size_t rec_ind;
};
void pt_set_recursive(struct page_table* pt, size_t index);
static inline void pte_set(pte_t* pte, paddr_t addr, pte_type_t type, pte_flags_t flags)
{
*pte = (addr & PTE_ADDR_MSK) | ((type | flags) & PTE_FLAGS_MSK);
}
static inline bool pte_valid(pte_t* pte)
{
return (*pte & PTE_VALID);
}
static inline void pte_set_rsw(pte_t* pte, pte_flags_t flag)
{
*pte = (*pte & ~PTE_RSW_MSK) | (flag & PTE_RSW_MSK);
}
static inline bool pte_check_rsw(pte_t* pte, pte_flags_t flag)
{
return (*pte & PTE_RSW_MSK) == (flag & PTE_RSW_MSK);
}
static inline paddr_t pte_addr(pte_t* pte)
{
return (paddr_t)(*pte & PTE_ADDR_MSK);
}
#endif /* |__ASSEMBLER__ */
#endif /* __ARCH_PAGE_TABLE_H__ */
|
7cf60451e5b0fb6fd6955e3d78bf3777d6f91d29
|
0cc343d927d5db6693006018986715c43acab961
|
/examples/termination/concurrent/semas.c
|
9d6d58bf3cce0fde7e42d1c66ef8f8d37525250d
|
[
"MIT"
] |
permissive
|
verifast/verifast
|
ec0101fc4a69bd33c5f66be4444169c4e060ead8
|
d152da790c7ebf72ce616533a6c83082629adbdb
|
refs/heads/master
| 2023-08-25T00:13:51.464802
| 2023-08-13T10:00:00
| 2023-08-13T10:00:00
| 14,519,163
| 325
| 64
|
NOASSERTION
| 2023-08-10T21:16:08
| 2013-11-19T08:57:02
|
OCaml
|
UTF-8
|
C
| false
| false
| 30,766
|
c
|
semas.c
|
#include <stdlib.h>
#include "semas.h"
//@ #include "listex.gh"
//@ #include "splittable_counting.gh"
/*
Deadlock-preventing specification approach based on [K.R.M. Leino, P. Mueller, J. Smans. Deadlock-free channels and locks. ESOP 2010].
*/
struct sema {
semaphore semaphore;
//@ int space;
//@ int termScope;
//@ real spaceFrac;
//@ level level;
//@ int creditObject;
//@ predicate() inv_;
//@ int countingId;
};
/*@
lemma void mem_remove_eq_append<t>(t x, list<t> xs)
requires mem(x, xs) == true;
ensures exists(pair(?xs1, ?xs2)) &*& xs == append(xs1, cons(x, xs2)) &*& remove(x, xs) == append(xs1, xs2);
{
switch (xs) {
case nil:
case cons(x0, xs0):
if (x0 == x) {
close exists(pair(nil, xs0));
} else {
mem_remove_eq_append(x, xs0);
open exists(pair(?xs1, ?xs2));
close exists(pair(cons(x0, xs1), xs2));
}
}
}
lemma_auto void n_times_nonnegative()
requires n_times(?n, ?p);
ensures n_times(n, p) &*& 0 <= n;
{
open n_times(_, _);
if (n != 0)
n_times_nonnegative();
close n_times(n, p);
}
predicate_ctor sema_inv(sema sema, semaphore semaphore, int space, int termScope, real spaceFrac, level level, int creditObject, predicate() inv)() =
[spaceFrac]term_perm(termScope, false) &*&
semaphore(semaphore, ?items, ?blockees) &*&
credit_object_handle(creditObject, items, blockees) &*&
n_times(items, inv) &*&
n_times(items, sema_release_token_(sema, space, termScope, level, creditObject, inv));
predicate sema(sema sema; int space, int termScope, real spaceFrac, level level, int creditObject, predicate() inv, int countingId) =
sema->semaphore |-> ?semaphore &*&
sema->space |-> space &*&
sema->termScope |-> termScope &*&
sema->spaceFrac |-> spaceFrac &*&
sema->level |-> level &*&
sema->creditObject |-> creditObject &*&
sema->inv_ |-> inv &*&
sema->countingId |-> countingId &*&
obspace(spaceFrac, space, termScope) &*&
malloc_block_sema(sema) &*&
[_]ghost_cell<pair<int, real> >(space, pair(?scope, ?olevel)) &*&
atomic_space(olevel + 2, sema_inv(sema, semaphore, space, termScope, spaceFrac, level, creditObject, inv));
predicate obspace(real f, int space, int termScope;) = [f]obligation_space0(space, termScope);
predicate_ctor sema_(sema sema)(;) = [1/2]sema(sema, _, _, _, _, _, _, _);
predicate sema_handle(sema sema, real frac, int space, int termScope, real spaceFrac, level level, int creditObject, predicate() inv, int releaseTokens) =
[frac/2]sema(sema, space, termScope, spaceFrac, level, creditObject, inv, ?countingId) &*& 0 < frac &*&
[_]obspace_credit_object_info(creditObject, space, level) &*&
counting_handle(countingId, sema_(sema), frac, releaseTokens);
predicate_ctor sema_release_token_(sema sema, int space, int termScope, level level, int creditObject, predicate() inv)() =
sema_release_token(sema, space, termScope, level, creditObject, inv);
predicate sema_release_token(sema sema, int space, int termScope, level level, int creditObject, predicate() inv) =
[?f]sema(sema, space, termScope, ?fs, level, creditObject, inv, ?countingId) &*& 0 < f &*&
[_]obspace_credit_object_info(creditObject, space, level) &*&
counting_ticket(countingId, 2*f);
lemma void real_mul_pos(real x, real y);
requires 0 < x &*& 0 < y;
ensures 0 < x * y;
lemma void sema_create_release_token(sema sema)
nonghost_callers_only
requires sema_handle(sema, ?f, ?space, ?termScope, ?fs, ?level, ?creditObject, ?inv, ?releaseTokens);
ensures sema_handle(sema, f, space, termScope, fs, level, creditObject, inv, releaseTokens + 1) &*& sema_release_token(sema, space, termScope, level, creditObject, inv);
{
open sema_handle(sema, f, space, termScope, fs, level, creditObject, inv, releaseTokens);
assert counting_handle(?countingId, _, _, _);
create_counting_ticket(countingId);
open [?frac]sema_(sema)();
close sema_handle(sema, f, space, termScope, fs, level, creditObject, inv, releaseTokens + 1);
close sema_release_token(sema, space, termScope, level, creditObject, inv);
}
lemma void sema_handle_split(sema sema, real f1, int releaseTokens1)
nonghost_callers_only
requires sema_handle(sema, ?f, ?space, ?termScope, ?fs, ?level, ?creditObject, ?inv, ?releaseTokens) &*& 0 < f1 &*& f1 < f;
ensures sema_handle(sema, f1, space, termScope, fs, level, creditObject, inv, releaseTokens1) &*& sema_handle(sema, f - f1, space, termScope, fs, level, creditObject, inv, releaseTokens - releaseTokens1);
{
open sema_handle(sema, f, space, termScope, fs, level, creditObject, inv, releaseTokens);
assert counting_handle(?countingId, _, _, _);
split_counting_handle(countingId, f1, releaseTokens1);
close sema_handle(sema, f1, space, termScope, fs, level, creditObject, inv, releaseTokens1);
close sema_handle(sema, f - f1, space, termScope, fs, level, creditObject, inv, releaseTokens - releaseTokens1);
}
lemma void sema_handle_merge(sema sema)
nonghost_callers_only
requires sema_handle(sema, ?f1, ?space1, ?termScope1, ?fs1, ?level1, ?creditObject1, ?inv1, ?releaseTokens1) &*& sema_handle(sema, ?f2, ?space2, ?termScope2, ?fs2, ?level2, ?creditObject2, ?inv2, ?releaseTokens2);
ensures sema_handle(sema, f1 + f2, space1, termScope1, fs1, level1, creditObject1, inv1, releaseTokens1 + releaseTokens2) &*&
space2 == space1 &*& termScope2 == termScope1 &*& fs2 == fs1 &*& level2 == level1 &*& creditObject2 == creditObject1 &*& inv2 == inv1;
{
open sema_handle(sema, f1, space1, termScope1, fs1, level1, creditObject1, inv1, releaseTokens1);
open sema_handle(sema, f2, space2, termScope2, fs2, level2, creditObject2, inv2, releaseTokens2);
assert counting_handle(?countingId, _, _, _);
merge_counting_handle(countingId);
close sema_handle(sema, f1 + f2, space1, termScope1, fs1, level1, creditObject1, inv1, releaseTokens1 + releaseTokens2);
}
@*/
sema create_sema()
//@ requires exists<real>(?fs) &*& [fs]obligation_space(?space, ?termScope) &*& obspace_credit_object(?creditObject, space, ?level, 0, 0) &*& exists<predicate()>(?inv);
//@ ensures sema_handle(result, 1, space, termScope, fs, level, creditObject, inv, 0);
//@ terminates;
{
//@ obspace_credit_object_get_info();
//@ open exists<predicate()>(inv);
sema sema = malloc(sizeof(struct sema));
if (sema == 0) abort();
sema->semaphore = create_semaphore(0);
//@ semaphore semaphore = sema->semaphore;
//@ sema->space = space;
//@ sema->termScope = termScope;
//@ sema->spaceFrac = fs;
//@ sema->level = level;
//@ sema->creditObject = creditObject;
//@ sema->inv_ = inv;
//@ int countingId = create_counting_handle_id_reservation();
//@ sema->countingId = countingId;
//@ open [fs]obligation_space(space, termScope);
//@ assert [_]ghost_cell<pair<int, real> >(space, pair(?scope, ?olevel));
//@ close n_times(0, inv);
//@ close n_times(0, sema_release_token_(sema, space, termScope, level, creditObject, inv));
//@ open obspace_credit_object(creditObject, space, level, 0, 0);
//@ close sema_inv(sema, sema->semaphore, space, termScope, fs, level, creditObject, inv)();
//@ create_atomic_space(olevel + 2, sema_inv(sema, sema->semaphore, space, termScope, fs, level, creditObject, inv));
return sema;
//@ close [fs]obligation_space0(space, termScope);
//@ close sema(sema, space, termScope, fs, level, creditObject, inv, countingId);
//@ close sema_(sema)();
//@ create_counting_handle(sema_(sema));
//@ close sema_handle(sema, 1, space, termScope, fs, level, creditObject, inv, 0);
}
void sema_acquire(sema sema)
/*@
requires
sema_handle(sema, ?f, ?space, ?termScope, ?fs, ?level, ?creditObject, ?inv, ?releaseTokens) &*&
obspace_obligation_set(space, ?obs) &*& level_all_above(obs, level) == true &*&
credit(creditObject);
@*/
/*@
ensures
sema_handle(sema, f, space, termScope, fs, level, creditObject, inv, releaseTokens - 1) &*&
obspace_obligation_set(space, obs) &*&
inv();
@*/
//@ terminates;
{
//@ open sema_handle(sema, f, space, termScope, fs, level, creditObject, inv, releaseTokens);
//@ open [f/2]sema(sema, space, termScope, fs, level, creditObject, inv, ?countingId);
//@ open obspace(fs, space, termScope);
//@ open [?fs_]obligation_space0(space, termScope);
//@ open [_]obspace_credit_object_info(creditObject, space, level);
//@ open obspace_obligation_set(space, obs);
//@ semaphore s = sema->semaphore;
//@ assert [_]ghost_cell<pair<int, real> >(space, pair(?scope, ?olevel));
{
/*@
predicate sep() =
[fs_]atomic_space(olevel, obligation_space_inv(scope, termScope)) &*&
[_]atomic_space(olevel + 1, credit_object_(creditObject, scope, level)) &*&
true;
predicate unsep(int items, int blockees) =
[fs_]atomic_space(olevel, obligation_space_inv(scope, termScope)) &*&
[_]atomic_space(olevel + 1, credit_object_(creditObject, scope, level)) &*&
[fs]term_perm(termScope, false) &*&
credit_object_handle(creditObject, items, blockees) &*&
n_times(items, inv) &*&
n_times(items, sema_release_token_(sema, space, termScope, level, creditObject, inv));
predicate P() = obligation_set(scope, obs) &*& credit(creditObject);
predicate blocked() = obligation_set_calling(scope, obs, 1, level);
predicate Q() = obligation_set(scope, obs) &*& inv() &*& sema_release_token(sema, space, termScope, level, creditObject, inv);
lemma void sep()
requires sema_inv(sema, s, space, termScope, fs, level, creditObject, inv)() &*& sep();
ensures semaphore(s, ?items, ?blockees) &*& unsep(items, blockees);
{
open sema_inv(sema, s, space, termScope, fs, level, creditObject, inv)();
open sep();
assert semaphore(s, ?items, ?blockees);
close unsep(items, blockees);
}
lemma void unsep()
requires semaphore(s, ?items, ?blockees) &*& unsep(items, blockees);
ensures sema_inv(sema, s, space, termScope, fs, level, creditObject, inv)() &*& sep();
{
open unsep(_, _);
close sep();
close sema_inv(sema, s, space, termScope, fs, level, creditObject, inv)();
}
lemma void block()
requires atomic_space_level(olevel + 2) &*& unsep(0, ?blockees) &*& P();
ensures atomic_space_level(olevel + 2) &*& unsep(0, blockees + 1) &*& blocked() &*& stop_perm(termScope);
{
open unsep(_, _);
open P();
{
predicate P1() =
[fs_]atomic_space(olevel, obligation_space_inv(scope, termScope)) &*&
obligation_set(scope, obs) &*&
credit_object_handle(creditObject, 0, blockees) &*&
credit(creditObject);
predicate Q1() =
[fs_]atomic_space(olevel, obligation_space_inv(scope, termScope)) &*&
credit_object_handle(creditObject, 0, blockees + 1) &*&
obligation_set_calling(scope, obs, 1, level) &*&
stop_perm(termScope);
lemma void body()
requires atomic_space_level(olevel + 1) &*& credit_object_(creditObject, scope, level)() &*& P1();
ensures atomic_space_level(olevel + 1) &*& credit_object_(creditObject, scope, level)() &*& Q1();
{
open credit_object_(creditObject, scope, level)();
open P1();
credit_object_block();
{
predicate P2() =
obligation_set(scope, obs) &*& obligation(scope, level);
predicate Q2() =
obligation_set_calling(scope, obs, 1, level) &*& stop_perm(termScope);
lemma void body2()
requires atomic_space_level(olevel) &*& obligation_space_inv(scope, termScope)() &*& P2();
ensures atomic_space_level(olevel) &*& obligation_space_inv(scope, termScope)() &*& Q2();
{
open obligation_space_inv(scope, termScope)();
open P2();
call_obligation();
close Q2();
close obligation_space_inv(scope, termScope)();
}
produce_lemma_function_pointer_chunk(body2) : atomic_noop_body(olevel, obligation_space_inv(scope, termScope), P2, Q2)() { call(); } {
close P2();
atomic_noop_nested();
open Q2();
}
}
close Q1();
close credit_object_(creditObject, scope, level)();
}
produce_lemma_function_pointer_chunk(body) : atomic_noop_body(olevel + 1, credit_object_(creditObject, scope, level), P1, Q1)() { call(); } {
close P1();
atomic_noop_nested();
open Q1();
}
}
close unsep(0, blockees + 1);
close blocked();
}
lemma void unblock()
requires atomic_space_level(olevel + 2) &*& unsep(0, ?blockees) &*& 0 < blockees &*& blocked() &*& stop_perm(termScope);
ensures atomic_space_level(olevel + 2) &*& unsep(0, blockees - 1) &*& P();
{
open unsep(_, _);
open blocked();
{
predicate P1() =
[fs_]atomic_space(olevel, obligation_space_inv(scope, termScope)) &*&
obligation_set_calling(scope, obs, 1, level) &*&
credit_object_handle(creditObject, 0, blockees) &*&
stop_perm(termScope);
predicate Q1() =
[fs_]atomic_space(olevel, obligation_space_inv(scope, termScope)) &*&
credit_object_handle(creditObject, 0, blockees - 1) &*&
obligation_set(scope, obs) &*&
credit(creditObject);
lemma void body()
requires atomic_space_level(olevel + 1) &*& credit_object_(creditObject, scope, level)() &*& P1();
ensures atomic_space_level(olevel + 1) &*& credit_object_(creditObject, scope, level)() &*& Q1();
{
open credit_object_(creditObject, scope, level)();
open P1();
{
predicate P2() =
obligation_set_calling(scope, obs, 1, level) &*& stop_perm(termScope);
predicate Q2() =
obligation_set(scope, obs) &*& obligation(scope, level);
lemma void body2()
requires atomic_space_level(olevel) &*& obligation_space_inv(scope, termScope)() &*& P2();
ensures atomic_space_level(olevel) &*& obligation_space_inv(scope, termScope)() &*& Q2();
{
open obligation_space_inv(scope, termScope)();
open P2();
return_obligation();
close Q2();
close obligation_space_inv(scope, termScope)();
}
produce_lemma_function_pointer_chunk(body2) : atomic_noop_body(olevel, obligation_space_inv(scope, termScope), P2, Q2)() { call(); } {
close P2();
atomic_noop_nested();
open Q2();
}
}
credit_object_unblock();
close Q1();
close credit_object_(creditObject, scope, level)();
}
produce_lemma_function_pointer_chunk(body) : atomic_noop_body(olevel + 1, credit_object_(creditObject, scope, level), P1, Q1)() { call(); } {
close P1();
atomic_noop_nested();
open Q1();
}
}
close unsep(0, blockees - 1);
close P();
}
lemma void acquire()
requires atomic_space_level(olevel + 2) &*& unsep(?items, 0) &*& 0 < items &*& P();
ensures atomic_space_level(olevel + 2) &*& unsep(items - 1, 0) &*& Q();
{
open unsep(_, _);
open P();
{
predicate P1() =
credit_object_handle(creditObject, items, 0) &*&
credit(creditObject);
predicate Q1() =
credit_object_handle(creditObject, items - 1, 0);
lemma void body()
requires atomic_space_level(olevel + 1) &*& credit_object_(creditObject, scope, level)() &*& P1();
ensures atomic_space_level(olevel + 1) &*& credit_object_(creditObject, scope, level)() &*& Q1();
{
open credit_object_(creditObject, scope, level)();
open P1();
credit_object_acquire();
close Q1();
close credit_object_(creditObject, scope, level)();
}
produce_lemma_function_pointer_chunk(body) : atomic_noop_body(olevel + 1, credit_object_(creditObject, scope, level), P1, Q1)() { call(); } {
close P1();
atomic_noop_nested();
open Q1();
}
}
open n_times(items, inv);
open n_times(items, sema_release_token_(sema, space, termScope, level, creditObject, inv));
open sema_release_token_(sema, space, termScope, level, creditObject, inv)();
close Q();
close unsep(items - 1, 0);
}
lemma void dummy_lemma()
requires true;
ensures true;
{}
@*/
/*@
produce_lemma_function_pointer_chunk(dummy_lemma) : inv_has_term_perm(termScope, sema_inv(sema, s, space, termScope, fs, level, creditObject, inv))() {
call();
open sema_inv(sema, s, space, termScope, fs, level, creditObject, inv)();
};
@*/
//@ leak is_inv_has_term_perm(_, _, _);
//@ produce_lemma_function_pointer_chunk(sep) : semaphore_sep(olevel + 2, sema_inv(sema, s, space, termScope, fs, level, creditObject, inv), s, sep, unsep)() { call(); };
//@ produce_lemma_function_pointer_chunk(unsep) : semaphore_unsep(olevel + 2, sema_inv(sema, s, space, termScope, fs, level, creditObject, inv), s, sep, unsep)() { call(); };
//@ produce_lemma_function_pointer_chunk(block) : semaphore_acquire_block(termScope, olevel + 2, unsep, P, blocked)() { call(); };
//@ produce_lemma_function_pointer_chunk(unblock) : semaphore_acquire_unblock(termScope, olevel + 2, unsep, blocked, P)() { call(); };
//@ produce_lemma_function_pointer_chunk(acquire) : semaphore_acquire_success(olevel + 2, unsep, P, Q)() { call(); };
//@ close sep();
//@ close P();
//@ close exists(olevel + 2);
semaphore_acquire(sema->semaphore);
//@ open sep();
//@ open Q();
}
//@ close [fs_]obligation_space0(space, termScope);
//@ close [f/2]obspace(fs, space, termScope);
//@ close [f/2]sema(sema, space, termScope, fs, level, creditObject, inv, countingId);
//@ open sema_release_token(sema, space, termScope, level, creditObject, inv);
//@ assert counting_ticket(countingId, ?frac);
//@ close [frac]sema_(sema)();
//@ destroy_counting_ticket(countingId);
//@ close sema_handle(sema, f, space, termScope, fs, level, creditObject, inv, releaseTokens - 1);
//@ close obspace_obligation_set(space, obs);
}
void sema_release(sema sema)
/*@
requires
sema_release_token(sema, ?space, ?termScope, ?level, ?creditObject, ?inv) &*& inv() &*&
exists<bool>(?final) &*&
final ?
obspace_obligation_set(space, {level}) &*& debit(creditObject) &*& obspace_joinee(space) &*&
ensures stop_perm(termScope)
:
ensures credit(creditObject);
@*/
//@ ensures true;
//@ terminates;
{
//@ open sema_release_token(sema, space, termScope, level, creditObject, inv);
//@ assert counting_ticket(?countingId, ?f);
//@ open [f/2]sema(sema, space, termScope, ?fs, level, creditObject, inv, countingId);
//@ open [?fs_]obligation_space0(space, termScope);
//@ open [_]obspace_credit_object_info(creditObject, space, _);
semaphore s = sema->semaphore;
//@ assert [_]ghost_cell<pair<int, real> >(space, pair(?scope, ?olevel));
{
/*@
predicate sep() = true;
predicate unsep(int items, int blockees) =
[fs]term_perm(termScope, false) &*&
credit_object_handle(creditObject, items, blockees) &*&
n_times(items, inv) &*&
n_times(items, sema_release_token_(sema, space, termScope, level, creditObject, inv));
predicate P() =
[fs_]atomic_space(olevel, obligation_space_inv(scope, termScope)) &*&
[_]atomic_space(olevel + 1, credit_object_(creditObject, scope, level)) &*&
[f/2]sema->semaphore |-> s &*&
[f/2]sema->space |-> space &*&
[f/2]sema->termScope |-> termScope &*&
[f/2]sema->spaceFrac |-> fs &*&
[f/2]sema->level |-> level &*&
[f/2]sema->creditObject |-> creditObject &*&
[f/2]sema->inv_ |-> inv &*&
[f/2]sema->countingId |-> countingId &*&
[f/2]malloc_block_sema(sema) &*&
[_]ghost_cell<pair<int, real> >(space, pair(scope, olevel)) &*&
[_]obspace_credit_object_info(creditObject, space, level) &*&
counting_ticket(countingId, f) &*&
inv() &*&
final ?
obspace_obligation_set(space, {level}) &*& debit(creditObject) &*& obspace_joinee(space)
:
true;
predicate Q() =
final ?
stop_perm(termScope)
:
credit(creditObject);
lemma void sep()
requires sema_inv(sema, s, space, termScope, fs, level, creditObject, inv)() &*& sep();
ensures semaphore(s, ?items, ?blockees) &*& unsep(items, blockees);
{
open sema_inv(sema, s, space, termScope, fs, level, creditObject, inv)();
open sep();
assert semaphore(s, ?items, ?blockees);
close unsep(items, blockees);
}
lemma void unsep()
requires semaphore(s, ?items, ?blockees) &*& unsep(items, blockees);
ensures sema_inv(sema, s, space, termScope, fs, level, creditObject, inv)() &*& sep();
{
open unsep(_, _);
close sep();
close sema_inv(sema, s, space, termScope, fs, level, creditObject, inv)();
}
lemma void release()
requires atomic_space_level(olevel + 2) &*& semaphore(s, ?items, 0) &*& unsep(items - 1, 0) &*& P() &*& [f/2]atomic_space(olevel + 2, sema_inv(sema, s, space, termScope, fs, level, creditObject, inv));
ensures atomic_space_level(olevel + 2) &*& sema_inv(sema, s, space, termScope, fs, level, creditObject, inv)() &*& Q();
{
open unsep(_, _);
open P();
if (final) {
open obspace_obligation_set(space, {level});
open obspace_joinee(space);
}
{
predicate P1() =
[fs_]atomic_space(olevel, obligation_space_inv(scope, termScope)) &*&
credit_object_handle(creditObject, items - 1, 0) &*&
final ?
obligation_set(scope, {level}) &*& debit(creditObject) &*& obligation_scope_joinee(scope)
:
true;
predicate Q1() =
[fs_]atomic_space(olevel, obligation_space_inv(scope, termScope)) &*&
credit_object_handle(creditObject, items, 0) &*&
final ?
stop_perm(termScope)
:
credit(creditObject);
lemma void body()
requires atomic_space_level(olevel + 1) &*& credit_object_(creditObject, scope, level)() &*& P1();
ensures atomic_space_level(olevel + 1) &*& credit_object_(creditObject, scope, level)() &*& Q1();
{
open credit_object_(creditObject, scope, level)();
open P1();
credit_object_release();
if (final) {
debit_dispose();
{
predicate P2() =
obligation_set(scope, {level}) &*& obligation(scope, level) &*& obligation_scope_joinee(scope);
predicate Q2() =
stop_perm(termScope);
lemma void body2()
requires atomic_space_level(olevel) &*& obligation_space_inv(scope, termScope)() &*& P2();
ensures atomic_space_level(olevel) &*& obligation_space_inv(scope, termScope)() &*& Q2();
{
open obligation_space_inv(scope, termScope)();
open P2();
destroy_obligation();
leave_obligation_scope(scope);
close Q2();
close obligation_space_inv(scope, termScope)();
}
produce_lemma_function_pointer_chunk(body2) : atomic_noop_body(olevel, obligation_space_inv(scope, termScope), P2, Q2)() { call(); } {
close P2();
atomic_noop_nested();
open Q2();
}
}
}
close Q1();
close credit_object_(creditObject, scope, level)();
}
produce_lemma_function_pointer_chunk(body) : atomic_noop_body(olevel + 1, credit_object_(creditObject, scope, level), P1, Q1)() { call(); } {
close P1();
atomic_noop_nested();
open Q1();
}
}
close n_times(items, inv);
close [(f/2)*fs]obligation_space0(space, termScope);
close [f/2]obspace(fs, space, termScope);
close [f/2]sema(sema, space, termScope, fs, level, creditObject, inv, countingId);
close sema_release_token(sema, space, termScope, level, creditObject, inv);
close sema_release_token_(sema, space, termScope, level, creditObject, inv)();
close n_times(items, sema_release_token_(sema, space, termScope, level, creditObject, inv));
close Q();
close sema_inv(sema, s, space, termScope, fs, level, creditObject, inv)();
}
lemma void dummy_lemma()
requires true;
ensures true;
{}
@*/
/*@
produce_lemma_function_pointer_chunk(dummy_lemma) : inv_has_term_perm(termScope, sema_inv(sema, s, space, termScope, fs, level, creditObject, inv))() {
call();
open sema_inv(sema, s, space, termScope, fs, level, creditObject, inv)();
};
@*/
//@ leak is_inv_has_term_perm(_, _, _);
//@ produce_lemma_function_pointer_chunk(sep) : semaphore_sep(olevel + 2, sema_inv(sema, s, space, termScope, fs, level, creditObject, inv), s, sep, unsep)() { call(); };
//@ produce_lemma_function_pointer_chunk(unsep) : semaphore_unsep(olevel + 2, sema_inv(sema, s, space, termScope, fs, level, creditObject, inv), s, sep, unsep)() { call(); };
//@ produce_lemma_function_pointer_chunk(release) : semaphore_release(olevel + 2, sema_inv(sema, s, space, termScope, fs, level, creditObject, inv), s, unsep, f/2, P, Q)() { call(); };
//@ close sep();
//@ close P();
semaphore_release(s);
//@ open Q();
}
}
void sema_dispose(sema sema)
//@ requires sema_handle(sema, 1, ?space, ?termScope, ?fs, ?level, ?creditObject, ?inv, 0);
//@ ensures [fs]obligation_space(space, termScope) &*& obspace_credit_object(creditObject, space, level, 0, 0);
//@ terminates;
{
//@ open sema_handle(sema, 1, space, termScope, fs, level, creditObject, inv, 0);
//@ open obspace_credit_object_info(creditObject, space, level);
//@ assert counting_handle(?countingId, _, 1, 0);
//@ destroy_counting_handle(countingId);
//@ open sema_(sema)();
//@ open sema(sema, space, termScope, fs, level, creditObject, inv, countingId);
//@ semaphore semaphore = sema->semaphore;
//@ open [fs]obligation_space0(space, termScope);
//@ assert [_]ghost_cell<pair<int, real> >(space, pair(?scope, ?olevel));
//@ atomic_space_destroy(olevel + 2, sema_inv(sema, sema->semaphore, space, termScope, fs, level, creditObject, inv));
//@ open sema_inv(sema, sema->semaphore, space, termScope, fs, level, creditObject, inv)();
//@ close [fs]obligation_space(space, termScope);
//@ assert semaphore(semaphore, ?items, ?blockees);
//@ close obspace_credit_object(creditObject, space, level, items, blockees);
semaphore_dispose(sema->semaphore);
//@ open n_times(items, sema_release_token_(sema, space, termScope, level, creditObject, inv));
//@ open n_times(items, inv);
/*@
if (items != 0) {
open sema_release_token_(sema, space, termScope, level, creditObject, inv)();
open sema_release_token(sema, space, termScope, level, creditObject, inv);
open sema(sema, space, termScope, _, level, creditObject, inv, _);
assert false;
}
@*/
free(sema);
}
|
6fb6764256adc46c471c8314809d12d3d428c328
|
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
|
/stage0/stdlib/Init/System/ST.c
|
327a0e3597916b54f67ba097687e02dc1074087f
|
[
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"
] |
permissive
|
leanprover/lean4
|
4bdf9790294964627eb9be79f5e8f6157780b4cc
|
f1f9dc0f2f531af3312398999d8b8303fa5f096b
|
refs/heads/master
| 2023-08-30T01:57:45.786981
| 2023-08-29T23:14:28
| 2023-08-29T23:14:28
| 129,571,436
| 2,827
| 311
|
Apache-2.0
| 2023-09-14T18:29:16
| 2018-04-15T02:49:20
|
Lean
|
UTF-8
|
C
| false
| false
| 23,226
|
c
|
ST.c
|
// Lean compiler output
// Module: Init.System.ST
// Imports: Init.Classical Init.Control.EState Init.Control.Reader
#include <lean/lean.h>
#if defined(__clang__)
#pragma clang diagnostic ignored "-Wunused-parameter"
#pragma clang diagnostic ignored "-Wunused-label"
#elif defined(__GNUC__) && !defined(__CLANG__)
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wunused-label"
#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
#endif
#ifdef __cplusplus
extern "C" {
#endif
LEAN_EXPORT lean_object* l_ST_Ref_take___rarg(lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_ST_Ref_set___rarg(lean_object*, lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_instSTWorldEST(lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_ST_Ref_modifyGet___rarg(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_instInhabitedEST___rarg(lean_object*);
LEAN_EXPORT lean_object* l_ST_Ref_toMonadStateOf___elambda__1(lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_ST_Ref_modify___rarg(lean_object*, lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_ST_Prim_Ref_modifyUnsafe___rarg___boxed(lean_object*, lean_object*, lean_object*);
lean_object* lean_st_ref_ptr_eq(lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_ST_Prim_Ref_set___boxed(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_ST_Ref_toMonadStateOf___elambda__1___rarg(lean_object*, lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_ST_Prim_Ref_get___boxed(lean_object*, lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_instMonadST(lean_object*);
LEAN_EXPORT lean_object* l_ST_Ref_toMonadStateOf___rarg(lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_ST_Ref_modify(lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_ST_Prim_Ref_take___boxed(lean_object*, lean_object*, lean_object*, lean_object*);
lean_object* l_EStateM_instMonadEStateM(lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_ST_Ref_get___rarg(lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_ST_Ref_set(lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_ST_Ref_toMonadStateOf___elambda__2(lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_ST_Ref_ptrEq(lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_ST_Ref_get(lean_object*, lean_object*);
lean_object* lean_st_ref_swap(lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_runST___rarg(lean_object*);
LEAN_EXPORT lean_object* l_ST_Ref_modifyGet(lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_instMonadLiftSTEST___rarg(lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_ST_mkRef___rarg(lean_object*, lean_object*, lean_object*);
lean_object* lean_st_ref_take(lean_object*, lean_object*);
lean_object* l_EStateM_instInhabitedEStateM___rarg(lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_instMonadExceptOfEST(lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_ST_RefPointed;
LEAN_EXPORT lean_object* l_instMonadEST(lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_ST_Prim_Ref_modifyUnsafe___rarg(lean_object*, lean_object*, lean_object*);
static lean_object* l_instMonadEST___closed__1;
LEAN_EXPORT lean_object* l_instInhabitedEST(lean_object*, lean_object*, lean_object*);
lean_object* lean_st_ref_get(lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_instSTWorld(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
lean_object* lean_st_mk_ref(lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_ST_Prim_mkRef___boxed(lean_object*, lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_runST(lean_object*);
LEAN_EXPORT lean_object* l_ST_Prim_Ref_modifyGetUnsafe___rarg___boxed(lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_ST_Ref_take(lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_runEST___rarg(lean_object*);
lean_object* l_EStateM_instMonadExceptOfEStateM___rarg(lean_object*);
LEAN_EXPORT lean_object* l_ST_Ref_ptrEq___rarg(lean_object*, lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_instSTWorld___boxed(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_ST_Prim_Ref_modifyGetUnsafe___rarg(lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_instMonadLiftSTEST(lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_ST_Prim_Ref_modifyGetUnsafe(lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_ST_mkRef(lean_object*, lean_object*);
static lean_object* l_instMonadExceptOfEST___closed__2;
LEAN_EXPORT lean_object* l_ST_Ref_swap(lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_ST_Ref_swap___rarg(lean_object*, lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_ST_Prim_Ref_modifyUnsafe(lean_object*, lean_object*);
static lean_object* l_instMonadExceptOfEST___closed__1;
lean_object* lean_st_ref_set(lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_ST_Prim_Ref_swap___boxed(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_ST_Ref_toMonadStateOf(lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_ST_Prim_Ref_ptrEq___boxed(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_ST_Ref_toMonadStateOf___elambda__2___rarg(lean_object*, lean_object*, lean_object*, lean_object*);
lean_object* l_EStateM_nonBacktrackable(lean_object*);
LEAN_EXPORT lean_object* l_runEST(lean_object*, lean_object*);
static lean_object* _init_l_instMonadEST___closed__1() {
_start:
{
lean_object* x_1;
x_1 = l_EStateM_instMonadEStateM(lean_box(0), lean_box(0));
return x_1;
}
}
LEAN_EXPORT lean_object* l_instMonadEST(lean_object* x_1, lean_object* x_2) {
_start:
{
lean_object* x_3;
x_3 = l_instMonadEST___closed__1;
return x_3;
}
}
static lean_object* _init_l_instMonadExceptOfEST___closed__1() {
_start:
{
lean_object* x_1;
x_1 = l_EStateM_nonBacktrackable(lean_box(0));
return x_1;
}
}
static lean_object* _init_l_instMonadExceptOfEST___closed__2() {
_start:
{
lean_object* x_1; lean_object* x_2;
x_1 = l_instMonadExceptOfEST___closed__1;
x_2 = l_EStateM_instMonadExceptOfEStateM___rarg(x_1);
return x_2;
}
}
LEAN_EXPORT lean_object* l_instMonadExceptOfEST(lean_object* x_1, lean_object* x_2) {
_start:
{
lean_object* x_3;
x_3 = l_instMonadExceptOfEST___closed__2;
return x_3;
}
}
LEAN_EXPORT lean_object* l_instInhabitedEST___rarg(lean_object* x_1) {
_start:
{
lean_object* x_2;
x_2 = lean_alloc_closure((void*)(l_EStateM_instInhabitedEStateM___rarg), 2, 1);
lean_closure_set(x_2, 0, x_1);
return x_2;
}
}
LEAN_EXPORT lean_object* l_instInhabitedEST(lean_object* x_1, lean_object* x_2, lean_object* x_3) {
_start:
{
lean_object* x_4;
x_4 = lean_alloc_closure((void*)(l_instInhabitedEST___rarg), 1, 0);
return x_4;
}
}
LEAN_EXPORT lean_object* l_instMonadST(lean_object* x_1) {
_start:
{
lean_object* x_2;
x_2 = l_instMonadEST___closed__1;
return x_2;
}
}
LEAN_EXPORT lean_object* l_instSTWorld(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5) {
_start:
{
lean_object* x_6;
x_6 = lean_box(0);
return x_6;
}
}
LEAN_EXPORT lean_object* l_instSTWorld___boxed(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5) {
_start:
{
lean_object* x_6;
x_6 = l_instSTWorld(x_1, x_2, x_3, x_4, x_5);
lean_dec(x_5);
lean_dec(x_4);
return x_6;
}
}
LEAN_EXPORT lean_object* l_instSTWorldEST(lean_object* x_1, lean_object* x_2) {
_start:
{
lean_object* x_3;
x_3 = lean_box(0);
return x_3;
}
}
LEAN_EXPORT lean_object* l_runEST___rarg(lean_object* x_1) {
_start:
{
lean_object* x_2; lean_object* x_3;
x_2 = lean_box(0);
x_3 = lean_apply_2(x_1, lean_box(0), x_2);
if (lean_obj_tag(x_3) == 0)
{
lean_object* x_4; lean_object* x_5;
x_4 = lean_ctor_get(x_3, 0);
lean_inc(x_4);
lean_dec(x_3);
x_5 = lean_alloc_ctor(1, 1, 0);
lean_ctor_set(x_5, 0, x_4);
return x_5;
}
else
{
lean_object* x_6; lean_object* x_7;
x_6 = lean_ctor_get(x_3, 0);
lean_inc(x_6);
lean_dec(x_3);
x_7 = lean_alloc_ctor(0, 1, 0);
lean_ctor_set(x_7, 0, x_6);
return x_7;
}
}
}
LEAN_EXPORT lean_object* l_runEST(lean_object* x_1, lean_object* x_2) {
_start:
{
lean_object* x_3;
x_3 = lean_alloc_closure((void*)(l_runEST___rarg), 1, 0);
return x_3;
}
}
LEAN_EXPORT lean_object* l_runST___rarg(lean_object* x_1) {
_start:
{
lean_object* x_2; lean_object* x_3; lean_object* x_4;
x_2 = lean_box(0);
x_3 = lean_apply_2(x_1, lean_box(0), x_2);
x_4 = lean_ctor_get(x_3, 0);
lean_inc(x_4);
lean_dec(x_3);
return x_4;
}
}
LEAN_EXPORT lean_object* l_runST(lean_object* x_1) {
_start:
{
lean_object* x_2;
x_2 = lean_alloc_closure((void*)(l_runST___rarg), 1, 0);
return x_2;
}
}
LEAN_EXPORT lean_object* l_instMonadLiftSTEST___rarg(lean_object* x_1, lean_object* x_2) {
_start:
{
lean_object* x_3; uint8_t x_4;
x_3 = lean_apply_1(x_1, x_2);
x_4 = !lean_is_exclusive(x_3);
if (x_4 == 0)
{
return x_3;
}
else
{
lean_object* x_5; lean_object* x_6; lean_object* x_7;
x_5 = lean_ctor_get(x_3, 0);
x_6 = lean_ctor_get(x_3, 1);
lean_inc(x_6);
lean_inc(x_5);
lean_dec(x_3);
x_7 = lean_alloc_ctor(0, 2, 0);
lean_ctor_set(x_7, 0, x_5);
lean_ctor_set(x_7, 1, x_6);
return x_7;
}
}
}
LEAN_EXPORT lean_object* l_instMonadLiftSTEST(lean_object* x_1, lean_object* x_2, lean_object* x_3) {
_start:
{
lean_object* x_4;
x_4 = lean_alloc_closure((void*)(l_instMonadLiftSTEST___rarg), 2, 0);
return x_4;
}
}
static lean_object* _init_l_ST_RefPointed() {
_start:
{
return lean_box(0);
}
}
LEAN_EXPORT lean_object* l_ST_Prim_mkRef___boxed(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4) {
_start:
{
lean_object* x_5;
x_5 = lean_st_mk_ref(x_3, x_4);
return x_5;
}
}
LEAN_EXPORT lean_object* l_ST_Prim_Ref_get___boxed(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4) {
_start:
{
lean_object* x_5;
x_5 = lean_st_ref_get(x_3, x_4);
lean_dec(x_3);
return x_5;
}
}
LEAN_EXPORT lean_object* l_ST_Prim_Ref_set___boxed(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5) {
_start:
{
lean_object* x_6;
x_6 = lean_st_ref_set(x_3, x_4, x_5);
lean_dec(x_3);
return x_6;
}
}
LEAN_EXPORT lean_object* l_ST_Prim_Ref_swap___boxed(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5) {
_start:
{
lean_object* x_6;
x_6 = lean_st_ref_swap(x_3, x_4, x_5);
lean_dec(x_3);
return x_6;
}
}
LEAN_EXPORT lean_object* l_ST_Prim_Ref_take___boxed(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4) {
_start:
{
lean_object* x_5;
x_5 = lean_st_ref_take(x_3, x_4);
lean_dec(x_3);
return x_5;
}
}
LEAN_EXPORT lean_object* l_ST_Prim_Ref_ptrEq___boxed(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5) {
_start:
{
lean_object* x_6;
x_6 = lean_st_ref_ptr_eq(x_3, x_4, x_5);
lean_dec(x_4);
lean_dec(x_3);
return x_6;
}
}
LEAN_EXPORT lean_object* l_ST_Prim_Ref_modifyUnsafe___rarg(lean_object* x_1, lean_object* x_2, lean_object* x_3) {
_start:
{
lean_object* x_4;
x_4 = lean_st_ref_take(x_1, x_3);
if (lean_obj_tag(x_4) == 0)
{
lean_object* x_5; lean_object* x_6; lean_object* x_7; lean_object* x_8;
x_5 = lean_ctor_get(x_4, 0);
lean_inc(x_5);
x_6 = lean_ctor_get(x_4, 1);
lean_inc(x_6);
lean_dec(x_4);
x_7 = lean_apply_1(x_2, x_5);
x_8 = lean_st_ref_set(x_1, x_7, x_6);
return x_8;
}
else
{
uint8_t x_9;
lean_dec(x_2);
x_9 = !lean_is_exclusive(x_4);
if (x_9 == 0)
{
return x_4;
}
else
{
lean_object* x_10; lean_object* x_11; lean_object* x_12;
x_10 = lean_ctor_get(x_4, 0);
x_11 = lean_ctor_get(x_4, 1);
lean_inc(x_11);
lean_inc(x_10);
lean_dec(x_4);
x_12 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_12, 0, x_10);
lean_ctor_set(x_12, 1, x_11);
return x_12;
}
}
}
}
LEAN_EXPORT lean_object* l_ST_Prim_Ref_modifyUnsafe(lean_object* x_1, lean_object* x_2) {
_start:
{
lean_object* x_3;
x_3 = lean_alloc_closure((void*)(l_ST_Prim_Ref_modifyUnsafe___rarg___boxed), 3, 0);
return x_3;
}
}
LEAN_EXPORT lean_object* l_ST_Prim_Ref_modifyUnsafe___rarg___boxed(lean_object* x_1, lean_object* x_2, lean_object* x_3) {
_start:
{
lean_object* x_4;
x_4 = l_ST_Prim_Ref_modifyUnsafe___rarg(x_1, x_2, x_3);
lean_dec(x_1);
return x_4;
}
}
LEAN_EXPORT lean_object* l_ST_Prim_Ref_modifyGetUnsafe___rarg(lean_object* x_1, lean_object* x_2, lean_object* x_3) {
_start:
{
lean_object* x_4;
x_4 = lean_st_ref_take(x_1, x_3);
if (lean_obj_tag(x_4) == 0)
{
lean_object* x_5; lean_object* x_6; lean_object* x_7; lean_object* x_8; lean_object* x_9; lean_object* x_10;
x_5 = lean_ctor_get(x_4, 0);
lean_inc(x_5);
x_6 = lean_ctor_get(x_4, 1);
lean_inc(x_6);
lean_dec(x_4);
x_7 = lean_apply_1(x_2, x_5);
x_8 = lean_ctor_get(x_7, 0);
lean_inc(x_8);
x_9 = lean_ctor_get(x_7, 1);
lean_inc(x_9);
lean_dec(x_7);
x_10 = lean_st_ref_set(x_1, x_9, x_6);
if (lean_obj_tag(x_10) == 0)
{
uint8_t x_11;
x_11 = !lean_is_exclusive(x_10);
if (x_11 == 0)
{
lean_object* x_12;
x_12 = lean_ctor_get(x_10, 0);
lean_dec(x_12);
lean_ctor_set(x_10, 0, x_8);
return x_10;
}
else
{
lean_object* x_13; lean_object* x_14;
x_13 = lean_ctor_get(x_10, 1);
lean_inc(x_13);
lean_dec(x_10);
x_14 = lean_alloc_ctor(0, 2, 0);
lean_ctor_set(x_14, 0, x_8);
lean_ctor_set(x_14, 1, x_13);
return x_14;
}
}
else
{
uint8_t x_15;
lean_dec(x_8);
x_15 = !lean_is_exclusive(x_10);
if (x_15 == 0)
{
return x_10;
}
else
{
lean_object* x_16; lean_object* x_17; lean_object* x_18;
x_16 = lean_ctor_get(x_10, 0);
x_17 = lean_ctor_get(x_10, 1);
lean_inc(x_17);
lean_inc(x_16);
lean_dec(x_10);
x_18 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_18, 0, x_16);
lean_ctor_set(x_18, 1, x_17);
return x_18;
}
}
}
else
{
uint8_t x_19;
lean_dec(x_2);
x_19 = !lean_is_exclusive(x_4);
if (x_19 == 0)
{
return x_4;
}
else
{
lean_object* x_20; lean_object* x_21; lean_object* x_22;
x_20 = lean_ctor_get(x_4, 0);
x_21 = lean_ctor_get(x_4, 1);
lean_inc(x_21);
lean_inc(x_20);
lean_dec(x_4);
x_22 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_22, 0, x_20);
lean_ctor_set(x_22, 1, x_21);
return x_22;
}
}
}
}
LEAN_EXPORT lean_object* l_ST_Prim_Ref_modifyGetUnsafe(lean_object* x_1, lean_object* x_2, lean_object* x_3) {
_start:
{
lean_object* x_4;
x_4 = lean_alloc_closure((void*)(l_ST_Prim_Ref_modifyGetUnsafe___rarg___boxed), 3, 0);
return x_4;
}
}
LEAN_EXPORT lean_object* l_ST_Prim_Ref_modifyGetUnsafe___rarg___boxed(lean_object* x_1, lean_object* x_2, lean_object* x_3) {
_start:
{
lean_object* x_4;
x_4 = l_ST_Prim_Ref_modifyGetUnsafe___rarg(x_1, x_2, x_3);
lean_dec(x_1);
return x_4;
}
}
LEAN_EXPORT lean_object* l_ST_mkRef___rarg(lean_object* x_1, lean_object* x_2, lean_object* x_3) {
_start:
{
lean_object* x_4; lean_object* x_5;
x_4 = lean_alloc_closure((void*)(l_ST_Prim_mkRef___boxed), 4, 3);
lean_closure_set(x_4, 0, lean_box(0));
lean_closure_set(x_4, 1, lean_box(0));
lean_closure_set(x_4, 2, x_3);
x_5 = lean_apply_2(x_1, lean_box(0), x_4);
return x_5;
}
}
LEAN_EXPORT lean_object* l_ST_mkRef(lean_object* x_1, lean_object* x_2) {
_start:
{
lean_object* x_3;
x_3 = lean_alloc_closure((void*)(l_ST_mkRef___rarg), 3, 0);
return x_3;
}
}
LEAN_EXPORT lean_object* l_ST_Ref_get___rarg(lean_object* x_1, lean_object* x_2, lean_object* x_3) {
_start:
{
lean_object* x_4; lean_object* x_5;
x_4 = lean_alloc_closure((void*)(l_ST_Prim_Ref_get___boxed), 4, 3);
lean_closure_set(x_4, 0, lean_box(0));
lean_closure_set(x_4, 1, lean_box(0));
lean_closure_set(x_4, 2, x_3);
x_5 = lean_apply_2(x_1, lean_box(0), x_4);
return x_5;
}
}
LEAN_EXPORT lean_object* l_ST_Ref_get(lean_object* x_1, lean_object* x_2) {
_start:
{
lean_object* x_3;
x_3 = lean_alloc_closure((void*)(l_ST_Ref_get___rarg), 3, 0);
return x_3;
}
}
LEAN_EXPORT lean_object* l_ST_Ref_set___rarg(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4) {
_start:
{
lean_object* x_5; lean_object* x_6;
x_5 = lean_alloc_closure((void*)(l_ST_Prim_Ref_set___boxed), 5, 4);
lean_closure_set(x_5, 0, lean_box(0));
lean_closure_set(x_5, 1, lean_box(0));
lean_closure_set(x_5, 2, x_3);
lean_closure_set(x_5, 3, x_4);
x_6 = lean_apply_2(x_1, lean_box(0), x_5);
return x_6;
}
}
LEAN_EXPORT lean_object* l_ST_Ref_set(lean_object* x_1, lean_object* x_2) {
_start:
{
lean_object* x_3;
x_3 = lean_alloc_closure((void*)(l_ST_Ref_set___rarg), 4, 0);
return x_3;
}
}
LEAN_EXPORT lean_object* l_ST_Ref_swap___rarg(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4) {
_start:
{
lean_object* x_5; lean_object* x_6;
x_5 = lean_alloc_closure((void*)(l_ST_Prim_Ref_swap___boxed), 5, 4);
lean_closure_set(x_5, 0, lean_box(0));
lean_closure_set(x_5, 1, lean_box(0));
lean_closure_set(x_5, 2, x_3);
lean_closure_set(x_5, 3, x_4);
x_6 = lean_apply_2(x_1, lean_box(0), x_5);
return x_6;
}
}
LEAN_EXPORT lean_object* l_ST_Ref_swap(lean_object* x_1, lean_object* x_2) {
_start:
{
lean_object* x_3;
x_3 = lean_alloc_closure((void*)(l_ST_Ref_swap___rarg), 4, 0);
return x_3;
}
}
LEAN_EXPORT lean_object* l_ST_Ref_take___rarg(lean_object* x_1, lean_object* x_2, lean_object* x_3) {
_start:
{
lean_object* x_4; lean_object* x_5;
x_4 = lean_alloc_closure((void*)(l_ST_Prim_Ref_take___boxed), 4, 3);
lean_closure_set(x_4, 0, lean_box(0));
lean_closure_set(x_4, 1, lean_box(0));
lean_closure_set(x_4, 2, x_3);
x_5 = lean_apply_2(x_1, lean_box(0), x_4);
return x_5;
}
}
LEAN_EXPORT lean_object* l_ST_Ref_take(lean_object* x_1, lean_object* x_2) {
_start:
{
lean_object* x_3;
x_3 = lean_alloc_closure((void*)(l_ST_Ref_take___rarg), 3, 0);
return x_3;
}
}
LEAN_EXPORT lean_object* l_ST_Ref_ptrEq___rarg(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4) {
_start:
{
lean_object* x_5; lean_object* x_6;
x_5 = lean_alloc_closure((void*)(l_ST_Prim_Ref_ptrEq___boxed), 5, 4);
lean_closure_set(x_5, 0, lean_box(0));
lean_closure_set(x_5, 1, lean_box(0));
lean_closure_set(x_5, 2, x_3);
lean_closure_set(x_5, 3, x_4);
x_6 = lean_apply_2(x_1, lean_box(0), x_5);
return x_6;
}
}
LEAN_EXPORT lean_object* l_ST_Ref_ptrEq(lean_object* x_1, lean_object* x_2) {
_start:
{
lean_object* x_3;
x_3 = lean_alloc_closure((void*)(l_ST_Ref_ptrEq___rarg), 4, 0);
return x_3;
}
}
LEAN_EXPORT lean_object* l_ST_Ref_modify___rarg(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4) {
_start:
{
lean_object* x_5; lean_object* x_6;
x_5 = lean_alloc_closure((void*)(l_ST_Prim_Ref_modifyUnsafe___rarg___boxed), 3, 2);
lean_closure_set(x_5, 0, x_3);
lean_closure_set(x_5, 1, x_4);
x_6 = lean_apply_2(x_1, lean_box(0), x_5);
return x_6;
}
}
LEAN_EXPORT lean_object* l_ST_Ref_modify(lean_object* x_1, lean_object* x_2) {
_start:
{
lean_object* x_3;
x_3 = lean_alloc_closure((void*)(l_ST_Ref_modify___rarg), 4, 0);
return x_3;
}
}
LEAN_EXPORT lean_object* l_ST_Ref_modifyGet___rarg(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5) {
_start:
{
lean_object* x_6; lean_object* x_7;
x_6 = lean_alloc_closure((void*)(l_ST_Prim_Ref_modifyGetUnsafe___rarg___boxed), 3, 2);
lean_closure_set(x_6, 0, x_4);
lean_closure_set(x_6, 1, x_5);
x_7 = lean_apply_2(x_1, lean_box(0), x_6);
return x_7;
}
}
LEAN_EXPORT lean_object* l_ST_Ref_modifyGet(lean_object* x_1, lean_object* x_2) {
_start:
{
lean_object* x_3;
x_3 = lean_alloc_closure((void*)(l_ST_Ref_modifyGet___rarg), 5, 0);
return x_3;
}
}
LEAN_EXPORT lean_object* l_ST_Ref_toMonadStateOf___elambda__1___rarg(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4) {
_start:
{
lean_object* x_5; lean_object* x_6;
x_5 = lean_alloc_closure((void*)(l_ST_Prim_Ref_modifyGetUnsafe___rarg___boxed), 3, 2);
lean_closure_set(x_5, 0, x_1);
lean_closure_set(x_5, 1, x_4);
x_6 = lean_apply_2(x_2, lean_box(0), x_5);
return x_6;
}
}
LEAN_EXPORT lean_object* l_ST_Ref_toMonadStateOf___elambda__1(lean_object* x_1, lean_object* x_2, lean_object* x_3) {
_start:
{
lean_object* x_4;
x_4 = lean_alloc_closure((void*)(l_ST_Ref_toMonadStateOf___elambda__1___rarg), 4, 0);
return x_4;
}
}
LEAN_EXPORT lean_object* l_ST_Ref_toMonadStateOf___elambda__2___rarg(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4) {
_start:
{
lean_object* x_5; lean_object* x_6;
x_5 = lean_alloc_closure((void*)(l_ST_Prim_Ref_set___boxed), 5, 4);
lean_closure_set(x_5, 0, lean_box(0));
lean_closure_set(x_5, 1, lean_box(0));
lean_closure_set(x_5, 2, x_3);
lean_closure_set(x_5, 3, x_4);
x_6 = lean_apply_2(x_1, lean_box(0), x_5);
return x_6;
}
}
LEAN_EXPORT lean_object* l_ST_Ref_toMonadStateOf___elambda__2(lean_object* x_1, lean_object* x_2) {
_start:
{
lean_object* x_3;
x_3 = lean_alloc_closure((void*)(l_ST_Ref_toMonadStateOf___elambda__2___rarg), 4, 0);
return x_3;
}
}
LEAN_EXPORT lean_object* l_ST_Ref_toMonadStateOf___rarg(lean_object* x_1, lean_object* x_2, lean_object* x_3) {
_start:
{
lean_object* x_4; lean_object* x_5; lean_object* x_6; lean_object* x_7; lean_object* x_8;
lean_inc(x_3);
x_4 = lean_alloc_closure((void*)(l_ST_Prim_Ref_get___boxed), 4, 3);
lean_closure_set(x_4, 0, lean_box(0));
lean_closure_set(x_4, 1, lean_box(0));
lean_closure_set(x_4, 2, x_3);
lean_inc(x_1);
x_5 = lean_apply_2(x_1, lean_box(0), x_4);
lean_inc(x_3);
lean_inc(x_1);
x_6 = lean_alloc_closure((void*)(l_ST_Ref_toMonadStateOf___elambda__2___rarg), 4, 3);
lean_closure_set(x_6, 0, x_1);
lean_closure_set(x_6, 1, lean_box(0));
lean_closure_set(x_6, 2, x_3);
x_7 = lean_alloc_closure((void*)(l_ST_Ref_toMonadStateOf___elambda__1___rarg), 4, 2);
lean_closure_set(x_7, 0, x_3);
lean_closure_set(x_7, 1, x_1);
x_8 = lean_alloc_ctor(0, 3, 0);
lean_ctor_set(x_8, 0, x_5);
lean_ctor_set(x_8, 1, x_6);
lean_ctor_set(x_8, 2, x_7);
return x_8;
}
}
LEAN_EXPORT lean_object* l_ST_Ref_toMonadStateOf(lean_object* x_1, lean_object* x_2) {
_start:
{
lean_object* x_3;
x_3 = lean_alloc_closure((void*)(l_ST_Ref_toMonadStateOf___rarg), 3, 0);
return x_3;
}
}
lean_object* initialize_Init_Classical(uint8_t builtin, lean_object*);
lean_object* initialize_Init_Control_EState(uint8_t builtin, lean_object*);
lean_object* initialize_Init_Control_Reader(uint8_t builtin, lean_object*);
static bool _G_initialized = false;
LEAN_EXPORT lean_object* initialize_Init_System_ST(uint8_t builtin, lean_object* w) {
lean_object * res;
if (_G_initialized) return lean_io_result_mk_ok(lean_box(0));
_G_initialized = true;
res = initialize_Init_Classical(builtin, lean_io_mk_world());
if (lean_io_result_is_error(res)) return res;
lean_dec_ref(res);
res = initialize_Init_Control_EState(builtin, lean_io_mk_world());
if (lean_io_result_is_error(res)) return res;
lean_dec_ref(res);
res = initialize_Init_Control_Reader(builtin, lean_io_mk_world());
if (lean_io_result_is_error(res)) return res;
lean_dec_ref(res);
l_instMonadEST___closed__1 = _init_l_instMonadEST___closed__1();
lean_mark_persistent(l_instMonadEST___closed__1);
l_instMonadExceptOfEST___closed__1 = _init_l_instMonadExceptOfEST___closed__1();
lean_mark_persistent(l_instMonadExceptOfEST___closed__1);
l_instMonadExceptOfEST___closed__2 = _init_l_instMonadExceptOfEST___closed__2();
lean_mark_persistent(l_instMonadExceptOfEST___closed__2);
l_ST_RefPointed = _init_l_ST_RefPointed();
return lean_io_result_mk_ok(lean_box(0));
}
#ifdef __cplusplus
}
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.